code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
---|---|
public class class_name {
public static String quote(String s, boolean flag) {
if (s == null)
return "null";
//PM21395 starts
if (flag){
s = s.replaceAll(""", "\"");
}
//PM21395 ends
return '"' + escape(s) + '"';
} } | public class class_name {
public static String quote(String s, boolean flag) {
if (s == null)
return "null";
//PM21395 starts
if (flag){
s = s.replaceAll(""", "\""); // depends on control dependency: [if], data = [none]
}
//PM21395 ends
return '"' + escape(s) + '"';
} } |
public class class_name {
private Geometry makePolygonValid(Polygon polygon) {
//This first step analyze linear components and create degenerate geometries
//of dimension 0 or 1 if they do not form valid LinearRings
//If degenerate geometries are found, it may produce a GeometryCollection with
//heterogeneous dimension
Geometry geom = makePolygonComponentsValid(polygon);
List<Geometry> list = new ArrayList<>();
for (int i = 0; i < geom.getNumGeometries(); i++) {
Geometry component = geom.getGeometryN(i);
if (component instanceof Polygon) {
Geometry nodedPolygon = nodePolygon((Polygon) component);
for (int j = 0; j < nodedPolygon.getNumGeometries(); j++) {
list.add(nodedPolygon.getGeometryN(j));
}
} else {
list.add(component);
}
}
return polygon.getFactory().buildGeometry(list);
} } | public class class_name {
private Geometry makePolygonValid(Polygon polygon) {
//This first step analyze linear components and create degenerate geometries
//of dimension 0 or 1 if they do not form valid LinearRings
//If degenerate geometries are found, it may produce a GeometryCollection with
//heterogeneous dimension
Geometry geom = makePolygonComponentsValid(polygon);
List<Geometry> list = new ArrayList<>();
for (int i = 0; i < geom.getNumGeometries(); i++) {
Geometry component = geom.getGeometryN(i);
if (component instanceof Polygon) {
Geometry nodedPolygon = nodePolygon((Polygon) component);
for (int j = 0; j < nodedPolygon.getNumGeometries(); j++) {
list.add(nodedPolygon.getGeometryN(j)); // depends on control dependency: [for], data = [j]
}
} else {
list.add(component); // depends on control dependency: [if], data = [none]
}
}
return polygon.getFactory().buildGeometry(list);
} } |
public class class_name {
public static List<String> getUiExtensionsRunningIssues(AddOn.AddOnRunRequirements requirements, AddOnSearcher addOnSearcher) {
if (!requirements.hasExtensionsWithRunningIssues()) {
return new ArrayList<>(0);
}
List<String> issues = new ArrayList<>(10);
for (AddOn.ExtensionRunRequirements extReqs : requirements.getExtensionRequirements()) {
issues.addAll(getUiRunningIssues(extReqs, addOnSearcher));
}
return issues;
} } | public class class_name {
public static List<String> getUiExtensionsRunningIssues(AddOn.AddOnRunRequirements requirements, AddOnSearcher addOnSearcher) {
if (!requirements.hasExtensionsWithRunningIssues()) {
return new ArrayList<>(0); // depends on control dependency: [if], data = [none]
}
List<String> issues = new ArrayList<>(10);
for (AddOn.ExtensionRunRequirements extReqs : requirements.getExtensionRequirements()) {
issues.addAll(getUiRunningIssues(extReqs, addOnSearcher)); // depends on control dependency: [for], data = [extReqs]
}
return issues;
} } |
public class class_name {
@Override
public void destroy() {
try {
ContextClassLoaderUtils.doWithClassLoader(jasperClassLoader,
new Callable<Void>() {
@Override
public Void call() throws Exception {
jasperServlet.destroy();
return null;
}
});
//CHECKSTYLE:OFF
} catch (Exception ignore) {
// ignored as it should never happen
LOG.error("Ignored exception", ignore);
}
//CHECKSTYLE:ON
} } | public class class_name {
@Override
public void destroy() {
try {
ContextClassLoaderUtils.doWithClassLoader(jasperClassLoader,
new Callable<Void>() {
@Override
public Void call() throws Exception {
jasperServlet.destroy();
return null;
}
});
// depends on control dependency: [try], data = [none]
//CHECKSTYLE:OFF
} catch (Exception ignore) {
// ignored as it should never happen
LOG.error("Ignored exception", ignore);
}
// depends on control dependency: [catch], data = [none]
//CHECKSTYLE:ON
} } |
public class class_name {
public RouteMethod attributes(Map<String, Object> attributes) {
if (attributes != null) {
if (this.attributes == null) {
this.attributes = new LinkedHashMap<>();
}
this.attributes.putAll(attributes);
}
return this;
} } | public class class_name {
public RouteMethod attributes(Map<String, Object> attributes) {
if (attributes != null) {
if (this.attributes == null) {
this.attributes = new LinkedHashMap<>(); // depends on control dependency: [if], data = [none]
}
this.attributes.putAll(attributes); // depends on control dependency: [if], data = [(attributes]
}
return this;
} } |
public class class_name {
private String buildHandlingMethodName(final EnumEventType annotationType) {
final StringBuilder methodName = new StringBuilder();
if (Arrays.asList(getAnnotationValue()).contains(annotationType)) {
// Lower case the first letter of the annotation name
methodName.append(this.annotation.annotationType().getSimpleName().substring(0, 1).toLowerCase());
// Don't change the case for all other letters
methodName.append(this.annotation.annotationType().getSimpleName().substring(1));
// Append if necessary the sub type if not equals to any
methodName.append(Key.Any.name().equals(annotationType.toString()) || Action.Action.name().equals(annotationType.toString()) ? "" : annotationType.name());
// Add suffix if handling method is named
final String uniqueName = getAnnotationName();
if (uniqueName.length() > 0) {
methodName.append(uniqueName);
}
}
return methodName.toString();
} } | public class class_name {
private String buildHandlingMethodName(final EnumEventType annotationType) {
final StringBuilder methodName = new StringBuilder();
if (Arrays.asList(getAnnotationValue()).contains(annotationType)) {
// Lower case the first letter of the annotation name
methodName.append(this.annotation.annotationType().getSimpleName().substring(0, 1).toLowerCase()); // depends on control dependency: [if], data = [none]
// Don't change the case for all other letters
methodName.append(this.annotation.annotationType().getSimpleName().substring(1)); // depends on control dependency: [if], data = [none]
// Append if necessary the sub type if not equals to any
methodName.append(Key.Any.name().equals(annotationType.toString()) || Action.Action.name().equals(annotationType.toString()) ? "" : annotationType.name()); // depends on control dependency: [if], data = [none]
// Add suffix if handling method is named
final String uniqueName = getAnnotationName();
if (uniqueName.length() > 0) {
methodName.append(uniqueName); // depends on control dependency: [if], data = [none]
}
}
return methodName.toString();
} } |
public class class_name {
static void escapePressed() {
final Component focusOwner = getPermanentFocusOwner();
final Window focusedWindow = SwingUtilities.getWindowAncestor(focusOwner);
if (focusedWindow instanceof Dialog && ((Dialog) focusedWindow).isModal()) {
// try {
// final Robot robot = new Robot();
// robot.keyPress(KeyEvent.VK_ALT);
// robot.keyPress(KeyEvent.VK_F4);
// robot.keyRelease(KeyEvent.VK_F4);
// robot.keyRelease(KeyEvent.VK_ALT);
// } catch (final AWTException e) {
// throw new IllegalStateException(e);
// }
focusedWindow.dispose();
}
} } | public class class_name {
static void escapePressed() {
final Component focusOwner = getPermanentFocusOwner();
final Window focusedWindow = SwingUtilities.getWindowAncestor(focusOwner);
if (focusedWindow instanceof Dialog && ((Dialog) focusedWindow).isModal()) {
// try {
// final Robot robot = new Robot();
// robot.keyPress(KeyEvent.VK_ALT);
// robot.keyPress(KeyEvent.VK_F4);
// robot.keyRelease(KeyEvent.VK_F4);
// robot.keyRelease(KeyEvent.VK_ALT);
// } catch (final AWTException e) {
// throw new IllegalStateException(e);
// }
focusedWindow.dispose();
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static boolean resetPrefixLength(JcsegTaskConfig config, ADictionary dic, int mixLength)
{
if ( mixLength <= config.MAX_LENGTH
&& mixLength > dic.mixPrefixLength ) {
dic.mixPrefixLength = mixLength;
return true;
}
return false;
} } | public class class_name {
public static boolean resetPrefixLength(JcsegTaskConfig config, ADictionary dic, int mixLength)
{
if ( mixLength <= config.MAX_LENGTH
&& mixLength > dic.mixPrefixLength ) {
dic.mixPrefixLength = mixLength; // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public void marshall(InstanceIdentity instanceIdentity, ProtocolMarshaller protocolMarshaller) {
if (instanceIdentity == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(instanceIdentity.getDocument(), DOCUMENT_BINDING);
protocolMarshaller.marshall(instanceIdentity.getSignature(), SIGNATURE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(InstanceIdentity instanceIdentity, ProtocolMarshaller protocolMarshaller) {
if (instanceIdentity == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(instanceIdentity.getDocument(), DOCUMENT_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(instanceIdentity.getSignature(), SIGNATURE_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 {
@Override
public void init() {
loadConfig();
if (!isEnabled()) {
return;
}
try {
String actorStr = format(ACTOR_FORMAT, actorName, actorEmail);
// Setup GET params...
List<BasicNameValuePair> getParams = new ArrayList<>();
getParams.add(new BasicNameValuePair(PARAM_ACTIVITY_ID, activityId));
getParams.add(new BasicNameValuePair(PARAM_AGENT, actorStr));
getParams.add(new BasicNameValuePair(PARAM_STATE_ID, stateId));
Object body = null;
if (formEncodeActivityData) {
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
String json = format(STATE_FORMAT, STATE_KEY_STATUS, STATE_VALUE_STARTED);
map.add(activitiesFormParamName, json);
body = map;
} else {
// just post a simple: {"status": "started"} record to the states API to verify
// the service is up.
Map<String, String> data = new HashMap<String, String>();
data.put(STATE_KEY_STATUS, STATE_VALUE_STARTED);
body = data;
}
ResponseEntity<Object> response =
sendRequest(
STATES_REST_ENDPOINT, HttpMethod.POST, getParams, body, Object.class);
if (response.getStatusCode().series() != Series.SUCCESSFUL) {
logger.error(
"LRS provider for URL "
+ LRSUrl
+ " it not configured properly, or is offline. Disabling provider.");
}
// todo: Need to think through a strategy for handling errors submitting
// to the LRS.
} catch (HttpClientErrorException e) {
// log some additional info in this case...
logger.error(
"LRS provider for URL "
+ LRSUrl
+ " failed to contact LRS for initialization. Disabling provider.",
e);
logger.error(
" Status: {}, Response: {}", e.getStatusCode(), e.getResponseBodyAsString());
enabled = false;
} catch (Exception e) {
logger.error(
"LRS provider for URL "
+ LRSUrl
+ " failed to contact LRS for initialization. Disabling provider",
e);
enabled = false;
}
} } | public class class_name {
@Override
public void init() {
loadConfig();
if (!isEnabled()) {
return; // depends on control dependency: [if], data = [none]
}
try {
String actorStr = format(ACTOR_FORMAT, actorName, actorEmail);
// Setup GET params...
List<BasicNameValuePair> getParams = new ArrayList<>();
getParams.add(new BasicNameValuePair(PARAM_ACTIVITY_ID, activityId)); // depends on control dependency: [try], data = [none]
getParams.add(new BasicNameValuePair(PARAM_AGENT, actorStr)); // depends on control dependency: [try], data = [none]
getParams.add(new BasicNameValuePair(PARAM_STATE_ID, stateId)); // depends on control dependency: [try], data = [none]
Object body = null;
if (formEncodeActivityData) {
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
String json = format(STATE_FORMAT, STATE_KEY_STATUS, STATE_VALUE_STARTED);
map.add(activitiesFormParamName, json); // depends on control dependency: [if], data = [none]
body = map; // depends on control dependency: [if], data = [none]
} else {
// just post a simple: {"status": "started"} record to the states API to verify
// the service is up.
Map<String, String> data = new HashMap<String, String>();
data.put(STATE_KEY_STATUS, STATE_VALUE_STARTED); // depends on control dependency: [if], data = [none]
body = data; // depends on control dependency: [if], data = [none]
}
ResponseEntity<Object> response =
sendRequest(
STATES_REST_ENDPOINT, HttpMethod.POST, getParams, body, Object.class);
if (response.getStatusCode().series() != Series.SUCCESSFUL) {
logger.error(
"LRS provider for URL "
+ LRSUrl
+ " it not configured properly, or is offline. Disabling provider."); // depends on control dependency: [if], data = [none]
}
// todo: Need to think through a strategy for handling errors submitting
// to the LRS.
} catch (HttpClientErrorException e) {
// log some additional info in this case...
logger.error(
"LRS provider for URL "
+ LRSUrl
+ " failed to contact LRS for initialization. Disabling provider.",
e);
logger.error(
" Status: {}, Response: {}", e.getStatusCode(), e.getResponseBodyAsString());
enabled = false;
} catch (Exception e) { // depends on control dependency: [catch], data = [none]
logger.error(
"LRS provider for URL "
+ LRSUrl
+ " failed to contact LRS for initialization. Disabling provider",
e);
enabled = false;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
static public Date getStandardOrISO(String text) {
Date result = getStandardDate(text);
if (result == null) {
DateFormatter formatter = new DateFormatter();
result = formatter.getISODate(text);
}
return result;
} } | public class class_name {
static public Date getStandardOrISO(String text) {
Date result = getStandardDate(text);
if (result == null) {
DateFormatter formatter = new DateFormatter();
result = formatter.getISODate(text);
// depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
private Vector get_hierarchy() {
synchronized (this) {
final Vector h = new Vector();
final Iterator it = elements.iterator();
while (it.hasNext()) {
final GroupElement e = (GroupElement) it.next();
if (e instanceof GroupDeviceElement) {
h.add(e);
} else {
h.add(((Group) e).get_hierarchy());
}
}
return h;
}
} } | public class class_name {
private Vector get_hierarchy() {
synchronized (this) {
final Vector h = new Vector();
final Iterator it = elements.iterator();
while (it.hasNext()) {
final GroupElement e = (GroupElement) it.next();
if (e instanceof GroupDeviceElement) {
h.add(e); // depends on control dependency: [if], data = [none]
} else {
h.add(((Group) e).get_hierarchy()); // depends on control dependency: [if], data = [none]
}
}
return h;
}
} } |
public class class_name {
public static ODatabaseDocument castToODatabaseDocument(ODatabase<?> db)
{
while(db!=null && !(db instanceof ODatabaseDocument))
{
if(db instanceof ODatabaseInternal<?>)
{
db = ((ODatabaseInternal<?>)db).getUnderlying();
}
}
return (ODatabaseDocument)db;
} } | public class class_name {
public static ODatabaseDocument castToODatabaseDocument(ODatabase<?> db)
{
while(db!=null && !(db instanceof ODatabaseDocument))
{
if(db instanceof ODatabaseInternal<?>)
{
db = ((ODatabaseInternal<?>)db).getUnderlying(); // depends on control dependency: [if], data = [)]
}
}
return (ODatabaseDocument)db;
} } |
public class class_name {
public static void removeThreadIdentityService(ThreadIdentityService tis) {
if (tis != null) {
threadIdentityServices.remove(tis);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "A ThreadIdentityService implementation was removed.", tis.getClass().getName());
}
}
} } | public class class_name {
public static void removeThreadIdentityService(ThreadIdentityService tis) {
if (tis != null) {
threadIdentityServices.remove(tis); // depends on control dependency: [if], data = [(tis]
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "A ThreadIdentityService implementation was removed.", tis.getClass().getName()); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public EClass getIDESize() {
if (ideSizeEClass == null) {
ideSizeEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(389);
}
return ideSizeEClass;
} } | public class class_name {
public EClass getIDESize() {
if (ideSizeEClass == null) {
ideSizeEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(389); // depends on control dependency: [if], data = [none]
}
return ideSizeEClass;
} } |
public class class_name {
@Override
public void writeCookieValue(CookieValue cookieValue) {
HttpServletRequest request = cookieValue.getRequest();
HttpServletResponse response = cookieValue.getResponse();
StringBuilder sb = new StringBuilder();
sb.append(this.cookieName).append('=');
String value = getValue(cookieValue);
if (value != null && value.length() > 0) {
validateValue(value);
sb.append(value);
}
int maxAge = getMaxAge(cookieValue);
if (maxAge > -1) {
sb.append("; Max-Age=").append(cookieValue.getCookieMaxAge());
OffsetDateTime expires = (maxAge != 0)
? OffsetDateTime.now().plusSeconds(maxAge)
: Instant.EPOCH.atOffset(ZoneOffset.UTC);
sb.append("; Expires=")
.append(expires.format(DateTimeFormatter.RFC_1123_DATE_TIME));
}
String domain = getDomainName(request);
if (domain != null && domain.length() > 0) {
validateDomain(domain);
sb.append("; Domain=").append(domain);
}
String path = getCookiePath(request);
if (path != null && path.length() > 0) {
validatePath(path);
sb.append("; Path=").append(path);
}
if (isSecureCookie(request)) {
sb.append("; Secure");
}
if (this.useHttpOnlyCookie) {
sb.append("; HttpOnly");
}
if (this.sameSite != null) {
sb.append("; SameSite=").append(this.sameSite);
}
response.addHeader("Set-Cookie", sb.toString());
} } | public class class_name {
@Override
public void writeCookieValue(CookieValue cookieValue) {
HttpServletRequest request = cookieValue.getRequest();
HttpServletResponse response = cookieValue.getResponse();
StringBuilder sb = new StringBuilder();
sb.append(this.cookieName).append('=');
String value = getValue(cookieValue);
if (value != null && value.length() > 0) {
validateValue(value); // depends on control dependency: [if], data = [(value]
sb.append(value); // depends on control dependency: [if], data = [(value]
}
int maxAge = getMaxAge(cookieValue);
if (maxAge > -1) {
sb.append("; Max-Age=").append(cookieValue.getCookieMaxAge()); // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
OffsetDateTime expires = (maxAge != 0)
? OffsetDateTime.now().plusSeconds(maxAge)
: Instant.EPOCH.atOffset(ZoneOffset.UTC);
sb.append("; Expires=")
.append(expires.format(DateTimeFormatter.RFC_1123_DATE_TIME)); // depends on control dependency: [if], data = [none]
}
String domain = getDomainName(request);
if (domain != null && domain.length() > 0) {
validateDomain(domain); // depends on control dependency: [if], data = [(domain]
sb.append("; Domain=").append(domain); // depends on control dependency: [if], data = [(domain]
}
String path = getCookiePath(request);
if (path != null && path.length() > 0) {
validatePath(path); // depends on control dependency: [if], data = [(path]
sb.append("; Path=").append(path); // depends on control dependency: [if], data = [(path]
}
if (isSecureCookie(request)) {
sb.append("; Secure"); // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
}
if (this.useHttpOnlyCookie) {
sb.append("; HttpOnly"); // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
}
if (this.sameSite != null) {
sb.append("; SameSite=").append(this.sameSite); // depends on control dependency: [if], data = [(this.sameSite]
}
response.addHeader("Set-Cookie", sb.toString());
} } |
public class class_name {
protected List<SparseItemset> frequentItemsetsSparse(List<SparseItemset> candidates, Relation<BitVector> relation, int needed, DBIDs ids, ArrayModifiableDBIDs survivors, int length) {
// Current search interval:
int begin = 0, end = candidates.size();
int[] scratchi = new int[length], iters = new int[length];
SparseItemset scratch = new SparseItemset(scratchi);
for(DBIDIter iditer = ids.iter(); iditer.valid(); iditer.advance()) {
BitVector bv = relation.get(iditer);
if(!initializeSearchItemset(bv, scratchi, iters)) {
continue;
}
int lives = 0;
while(begin < end) {
begin = binarySearch(candidates, scratch, begin, end);
if(begin > 0) {
candidates.get(begin).increaseSupport();
++lives;
}
else {
begin = (-begin) - 1;
}
if(begin >= end || !nextSearchItemset(bv, scratchi, iters)) {
break;
}
}
for(Itemset candidate : candidates) {
if(candidate.containedIn(bv)) {
candidate.increaseSupport();
++lives;
}
}
if(lives > length) {
survivors.add(iditer);
}
}
// Retain only those with minimum support:
List<SparseItemset> frequent = new ArrayList<>(candidates.size());
for(Iterator<SparseItemset> iter = candidates.iterator(); iter.hasNext();) {
final SparseItemset candidate = iter.next();
if(candidate.getSupport() >= needed) {
frequent.add(candidate);
}
}
return frequent;
} } | public class class_name {
protected List<SparseItemset> frequentItemsetsSparse(List<SparseItemset> candidates, Relation<BitVector> relation, int needed, DBIDs ids, ArrayModifiableDBIDs survivors, int length) {
// Current search interval:
int begin = 0, end = candidates.size();
int[] scratchi = new int[length], iters = new int[length];
SparseItemset scratch = new SparseItemset(scratchi);
for(DBIDIter iditer = ids.iter(); iditer.valid(); iditer.advance()) {
BitVector bv = relation.get(iditer);
if(!initializeSearchItemset(bv, scratchi, iters)) {
continue;
}
int lives = 0;
while(begin < end) {
begin = binarySearch(candidates, scratch, begin, end); // depends on control dependency: [while], data = [end)]
if(begin > 0) {
candidates.get(begin).increaseSupport(); // depends on control dependency: [if], data = [(begin]
++lives; // depends on control dependency: [if], data = [none]
}
else {
begin = (-begin) - 1; // depends on control dependency: [if], data = [none]
}
if(begin >= end || !nextSearchItemset(bv, scratchi, iters)) {
break;
}
}
for(Itemset candidate : candidates) {
if(candidate.containedIn(bv)) {
candidate.increaseSupport(); // depends on control dependency: [if], data = [none]
++lives; // depends on control dependency: [if], data = [none]
}
}
if(lives > length) {
survivors.add(iditer); // depends on control dependency: [if], data = [none]
}
}
// Retain only those with minimum support:
List<SparseItemset> frequent = new ArrayList<>(candidates.size());
for(Iterator<SparseItemset> iter = candidates.iterator(); iter.hasNext();) {
final SparseItemset candidate = iter.next();
if(candidate.getSupport() >= needed) {
frequent.add(candidate); // depends on control dependency: [if], data = [none]
}
}
return frequent;
} } |
public class class_name {
DeleteResult deleteOne(final MongoNamespace namespace, final Bson filter) {
this.waitUntilInitialized();
try {
ongoingOperationsGroup.enter();
final ChangeEvent<BsonDocument> event;
final DeleteResult result;
final NamespaceSynchronizationConfig nsConfig =
this.syncConfig.getNamespaceConfig(namespace);
nsConfig.getLock().writeLock().lock();
try {
final MongoCollection<BsonDocument> localCollection = getLocalCollection(namespace);
final BsonDocument docToDelete = localCollection
.find(filter)
.first();
if (docToDelete == null) {
return DeleteResult.acknowledged(0);
}
final BsonValue documentId = BsonUtils.getDocumentId(docToDelete);
final CoreDocumentSynchronizationConfig config =
syncConfig.getSynchronizedDocument(namespace, documentId);
if (config == null) {
return DeleteResult.acknowledged(0);
}
final MongoCollection<BsonDocument> undoCollection = getUndoCollection(namespace);
undoCollection.insertOne(docToDelete);
result = localCollection.deleteOne(filter);
event = ChangeEvents.changeEventForLocalDelete(namespace, documentId, true);
// this block is to trigger coalescence for a delete after insert
if (config.getLastUncommittedChangeEvent() != null
&& config.getLastUncommittedChangeEvent().getOperationType()
== OperationType.INSERT) {
final LocalSyncWriteModelContainer localSyncWriteModelContainer =
desyncDocumentsFromRemote(nsConfig, config.getDocumentId());
localSyncWriteModelContainer.commitAndClear();
// delete the namespace listener if necessary
checkAndDeleteNamespaceListener(namespace);
undoCollection.deleteOne(getDocumentIdFilter(config.getDocumentId()));
return result;
}
config.setSomePendingWritesAndSave(logicalT, event);
undoCollection.deleteOne(getDocumentIdFilter(config.getDocumentId()));
} finally {
nsConfig.getLock().writeLock().unlock();
}
eventDispatcher.emitEvent(nsConfig, event);
return result;
} finally {
ongoingOperationsGroup.exit();
}
} } | public class class_name {
DeleteResult deleteOne(final MongoNamespace namespace, final Bson filter) {
this.waitUntilInitialized();
try {
ongoingOperationsGroup.enter(); // depends on control dependency: [try], data = [none]
final ChangeEvent<BsonDocument> event;
final DeleteResult result;
final NamespaceSynchronizationConfig nsConfig =
this.syncConfig.getNamespaceConfig(namespace);
nsConfig.getLock().writeLock().lock(); // depends on control dependency: [try], data = [none]
try {
final MongoCollection<BsonDocument> localCollection = getLocalCollection(namespace);
final BsonDocument docToDelete = localCollection
.find(filter)
.first();
if (docToDelete == null) {
return DeleteResult.acknowledged(0); // depends on control dependency: [if], data = [none]
}
final BsonValue documentId = BsonUtils.getDocumentId(docToDelete);
final CoreDocumentSynchronizationConfig config =
syncConfig.getSynchronizedDocument(namespace, documentId);
if (config == null) {
return DeleteResult.acknowledged(0); // depends on control dependency: [if], data = [none]
}
final MongoCollection<BsonDocument> undoCollection = getUndoCollection(namespace);
undoCollection.insertOne(docToDelete); // depends on control dependency: [try], data = [none]
result = localCollection.deleteOne(filter); // depends on control dependency: [try], data = [none]
event = ChangeEvents.changeEventForLocalDelete(namespace, documentId, true); // depends on control dependency: [try], data = [none]
// this block is to trigger coalescence for a delete after insert
if (config.getLastUncommittedChangeEvent() != null
&& config.getLastUncommittedChangeEvent().getOperationType()
== OperationType.INSERT) {
final LocalSyncWriteModelContainer localSyncWriteModelContainer =
desyncDocumentsFromRemote(nsConfig, config.getDocumentId());
localSyncWriteModelContainer.commitAndClear(); // depends on control dependency: [if], data = [none]
// delete the namespace listener if necessary
checkAndDeleteNamespaceListener(namespace); // depends on control dependency: [if], data = [none]
undoCollection.deleteOne(getDocumentIdFilter(config.getDocumentId())); // depends on control dependency: [if], data = [none]
return result; // depends on control dependency: [if], data = [none]
}
config.setSomePendingWritesAndSave(logicalT, event); // depends on control dependency: [try], data = [none]
undoCollection.deleteOne(getDocumentIdFilter(config.getDocumentId())); // depends on control dependency: [try], data = [none]
} finally {
nsConfig.getLock().writeLock().unlock();
}
eventDispatcher.emitEvent(nsConfig, event); // depends on control dependency: [try], data = [none]
return result; // depends on control dependency: [try], data = [none]
} finally {
ongoingOperationsGroup.exit();
}
} } |
public class class_name {
@CommandHandler
public void handle(StartTransactionCommand command, MetaData metaData) {
if (command.getStartTransactionInfo().getEvseId().getNumberedId() > numberOfEvses) {
apply(new EvseNotFoundEvent(id, command.getStartTransactionInfo().getEvseId(), command.getIdentityContext()), metaData);
return;
}
apply(new TransactionStartedEvent(command.getChargingStationId(), command.getTransactionId(), command.getStartTransactionInfo(), command.getIdentityContext()), metaData);
} } | public class class_name {
@CommandHandler
public void handle(StartTransactionCommand command, MetaData metaData) {
if (command.getStartTransactionInfo().getEvseId().getNumberedId() > numberOfEvses) {
apply(new EvseNotFoundEvent(id, command.getStartTransactionInfo().getEvseId(), command.getIdentityContext()), metaData); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
apply(new TransactionStartedEvent(command.getChargingStationId(), command.getTransactionId(), command.getStartTransactionInfo(), command.getIdentityContext()), metaData);
} } |
public class class_name {
public FireableEventType getEventId(EventLookupFacility eventLookupFacility,
Request request, boolean inDialogActivity) {
final String requestMethod = request.getMethod();
// Cancel is always the same.
if (requestMethod.equals(Request.CANCEL))
inDialogActivity = false;
FireableEventType eventID = null;
if (inDialogActivity) {
eventID = getEventId(eventLookupFacility,
new StringBuilder(INDIALOG_REQUEST_EVENT_PREFIX).append(requestMethod).toString());
if (eventID == null) {
eventID = getEventId(eventLookupFacility,
new StringBuilder(INDIALOG_REQUEST_EVENT_PREFIX).append(SIP_EXTENSION_REQUEST_EVENT_NAME_SUFIX).toString());
}
} else {
eventID = getEventId(eventLookupFacility,
new StringBuilder(OUT_OF_DIALOG_REQUEST_EVENT_PREFIX).append(requestMethod).toString());
if (eventID == null) {
eventID = getEventId(eventLookupFacility,
new StringBuilder(OUT_OF_DIALOG_REQUEST_EVENT_PREFIX).append(SIP_EXTENSION_REQUEST_EVENT_NAME_SUFIX).toString());
}
}
return eventID;
} } | public class class_name {
public FireableEventType getEventId(EventLookupFacility eventLookupFacility,
Request request, boolean inDialogActivity) {
final String requestMethod = request.getMethod();
// Cancel is always the same.
if (requestMethod.equals(Request.CANCEL))
inDialogActivity = false;
FireableEventType eventID = null;
if (inDialogActivity) {
eventID = getEventId(eventLookupFacility,
new StringBuilder(INDIALOG_REQUEST_EVENT_PREFIX).append(requestMethod).toString()); // depends on control dependency: [if], data = [none]
if (eventID == null) {
eventID = getEventId(eventLookupFacility,
new StringBuilder(INDIALOG_REQUEST_EVENT_PREFIX).append(SIP_EXTENSION_REQUEST_EVENT_NAME_SUFIX).toString()); // depends on control dependency: [if], data = [none]
}
} else {
eventID = getEventId(eventLookupFacility,
new StringBuilder(OUT_OF_DIALOG_REQUEST_EVENT_PREFIX).append(requestMethod).toString()); // depends on control dependency: [if], data = [none]
if (eventID == null) {
eventID = getEventId(eventLookupFacility,
new StringBuilder(OUT_OF_DIALOG_REQUEST_EVENT_PREFIX).append(SIP_EXTENSION_REQUEST_EVENT_NAME_SUFIX).toString()); // depends on control dependency: [if], data = [none]
}
}
return eventID;
} } |
public class class_name {
@SuppressWarnings("unchecked")
public <T extends Tag> Set<T> getOfType(final Class<T> type) {
read.lock();
try {
final Set<T> tagsOfType = (Set<T>) tags.get(type);
return tagsOfType != null ? Collections.unmodifiableSet(tagsOfType) : Collections.emptySet();
} finally {
read.unlock();
}
} } | public class class_name {
@SuppressWarnings("unchecked")
public <T extends Tag> Set<T> getOfType(final Class<T> type) {
read.lock();
try {
final Set<T> tagsOfType = (Set<T>) tags.get(type);
return tagsOfType != null ? Collections.unmodifiableSet(tagsOfType) : Collections.emptySet(); // depends on control dependency: [try], data = [none]
} finally {
read.unlock();
}
} } |
public class class_name {
@Override
public void setBean(final Object bean) {
BeanAndProviderBoundComponentModel model = getOrCreateComponentModel();
model.setBean(bean);
if (getBeanProperty() == null) {
setBeanProperty(".");
}
// Remove values in scratch map
removeBeanFromScratchMap();
} } | public class class_name {
@Override
public void setBean(final Object bean) {
BeanAndProviderBoundComponentModel model = getOrCreateComponentModel();
model.setBean(bean);
if (getBeanProperty() == null) {
setBeanProperty("."); // depends on control dependency: [if], data = [none]
}
// Remove values in scratch map
removeBeanFromScratchMap();
} } |
public class class_name {
private static void statFile(String fname) {
try {
Path path = Paths.get(new URI(fname));
long size = Files.size(path);
System.out.println(fname + ": " + size + " bytes.");
} catch (Exception ex) {
System.out.println(fname + ": " + ex.toString());
}
} } | public class class_name {
private static void statFile(String fname) {
try {
Path path = Paths.get(new URI(fname));
long size = Files.size(path);
System.out.println(fname + ": " + size + " bytes."); // depends on control dependency: [try], data = [none]
} catch (Exception ex) {
System.out.println(fname + ": " + ex.toString());
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Transactional
public static ServiceManagementRecord updateServiceManagementRecord(EntityManager em, ServiceManagementRecord record) {
SystemAssert.requireArgument(em != null, "Entity manager can not be null.");
SystemAssert.requireArgument(record != null, "ServiceManagementRecord cannot be null.");
TypedQuery<ServiceManagementRecord> query = em.createNamedQuery("ServiceManagementRecord.findByService", ServiceManagementRecord.class);
query.setParameter("service", record.getService());
try {
ServiceManagementRecord oldRecord = query.getSingleResult();
oldRecord.setEnabled(record.isEnabled());
return em.merge(oldRecord);
} catch (NoResultException ex) {
return em.merge(record);
}
} } | public class class_name {
@Transactional
public static ServiceManagementRecord updateServiceManagementRecord(EntityManager em, ServiceManagementRecord record) {
SystemAssert.requireArgument(em != null, "Entity manager can not be null.");
SystemAssert.requireArgument(record != null, "ServiceManagementRecord cannot be null.");
TypedQuery<ServiceManagementRecord> query = em.createNamedQuery("ServiceManagementRecord.findByService", ServiceManagementRecord.class);
query.setParameter("service", record.getService());
try {
ServiceManagementRecord oldRecord = query.getSingleResult();
oldRecord.setEnabled(record.isEnabled()); // depends on control dependency: [try], data = [none]
return em.merge(oldRecord); // depends on control dependency: [try], data = [none]
} catch (NoResultException ex) {
return em.merge(record);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public <ATTRIBUTE> OptionalThing<ATTRIBUTE> getAttribute(String key, Class<ATTRIBUTE> attributeType) {
assertArgumentNotNull("key", key);
assertArgumentNotNull("attributeType", attributeType);
final Object original = findSuccessAttribute(key);
final ATTRIBUTE attribute;
if (original != null) {
try {
attribute = attributeType.cast(original);
} catch (ClassCastException e) {
final ExceptionMessageBuilder br = new ExceptionMessageBuilder();
br.addNotice("Cannot cast the validation success attribute");
br.addItem("Attribute Key");
br.addElement(key);
br.addItem("Specified Type");
br.addElement(attributeType);
br.addItem("Existing Attribute");
br.addElement(original.getClass());
br.addElement(original);
br.addItem("Attribute Map");
br.addElement(getSuccessAttributeMap());
final String msg = br.buildExceptionMessage();
throw new ValidationSuccessAttributeCannotCastException(msg);
}
} else {
attribute = null;
}
return OptionalThing.ofNullable(attribute, () -> {
final Set<String> keySet = getSuccessAttributeMap().keySet();
final String msg = "Not found the validation success attribute by the string key: " + key + " existing=" + keySet;
throw new ValidationSuccessAttributeNotFoundException(msg);
});
} } | public class class_name {
public <ATTRIBUTE> OptionalThing<ATTRIBUTE> getAttribute(String key, Class<ATTRIBUTE> attributeType) {
assertArgumentNotNull("key", key);
assertArgumentNotNull("attributeType", attributeType);
final Object original = findSuccessAttribute(key);
final ATTRIBUTE attribute;
if (original != null) {
try {
attribute = attributeType.cast(original); // depends on control dependency: [try], data = [none]
} catch (ClassCastException e) {
final ExceptionMessageBuilder br = new ExceptionMessageBuilder();
br.addNotice("Cannot cast the validation success attribute");
br.addItem("Attribute Key");
br.addElement(key);
br.addItem("Specified Type");
br.addElement(attributeType);
br.addItem("Existing Attribute");
br.addElement(original.getClass());
br.addElement(original);
br.addItem("Attribute Map");
br.addElement(getSuccessAttributeMap());
final String msg = br.buildExceptionMessage();
throw new ValidationSuccessAttributeCannotCastException(msg);
} // depends on control dependency: [catch], data = [none]
} else {
attribute = null; // depends on control dependency: [if], data = [none]
}
return OptionalThing.ofNullable(attribute, () -> {
final Set<String> keySet = getSuccessAttributeMap().keySet();
final String msg = "Not found the validation success attribute by the string key: " + key + " existing=" + keySet;
throw new ValidationSuccessAttributeNotFoundException(msg);
});
} } |
public class class_name {
long expireAfterCreate(@Nullable K key, @Nullable V value, Expiry<K, V> expiry, long now) {
if (expiresVariable() && (key != null) && (value != null)) {
long duration = expiry.expireAfterCreate(key, value, now);
return isAsync ? (now + duration) : (now + Math.min(duration, MAXIMUM_EXPIRY));
}
return 0L;
} } | public class class_name {
long expireAfterCreate(@Nullable K key, @Nullable V value, Expiry<K, V> expiry, long now) {
if (expiresVariable() && (key != null) && (value != null)) {
long duration = expiry.expireAfterCreate(key, value, now);
return isAsync ? (now + duration) : (now + Math.min(duration, MAXIMUM_EXPIRY)); // depends on control dependency: [if], data = [none]
}
return 0L;
} } |
public class class_name {
@Override
public void removeByUuid(String uuid) {
for (CommerceOrder commerceOrder : findByUuid(uuid, QueryUtil.ALL_POS,
QueryUtil.ALL_POS, null)) {
remove(commerceOrder);
}
} } | public class class_name {
@Override
public void removeByUuid(String uuid) {
for (CommerceOrder commerceOrder : findByUuid(uuid, QueryUtil.ALL_POS,
QueryUtil.ALL_POS, null)) {
remove(commerceOrder); // depends on control dependency: [for], data = [commerceOrder]
}
} } |
public class class_name {
private static String processMsgPartsHelper(
ImmutableList<SoyMsgPart> parts, Function<String, String> escaper) {
StringBuilder rawMsgTextSb = new StringBuilder();
for (SoyMsgPart part : parts) {
if (part instanceof SoyMsgRawTextPart) {
rawMsgTextSb.append(escaper.apply(((SoyMsgRawTextPart) part).getRawText()));
}
if (part instanceof SoyMsgPlaceholderPart) {
String phName = ((SoyMsgPlaceholderPart) part).getPlaceholderName();
rawMsgTextSb.append("{" + phName + "}");
}
}
return rawMsgTextSb.toString();
} } | public class class_name {
private static String processMsgPartsHelper(
ImmutableList<SoyMsgPart> parts, Function<String, String> escaper) {
StringBuilder rawMsgTextSb = new StringBuilder();
for (SoyMsgPart part : parts) {
if (part instanceof SoyMsgRawTextPart) {
rawMsgTextSb.append(escaper.apply(((SoyMsgRawTextPart) part).getRawText())); // depends on control dependency: [if], data = [none]
}
if (part instanceof SoyMsgPlaceholderPart) {
String phName = ((SoyMsgPlaceholderPart) part).getPlaceholderName();
rawMsgTextSb.append("{" + phName + "}"); // depends on control dependency: [if], data = [none]
}
}
return rawMsgTextSb.toString();
} } |
public class class_name {
private int getHuffmanValue(final int table[], final int temp[], final int index[]) throws IOException {
int code, input;
final int mask = 0xFFFF;
if (index[0] < 8) {
temp[0] <<= 8;
input = this.input.readUnsignedByte();
if (input == 0xFF) {
marker = this.input.readUnsignedByte();
if (marker != 0) {
markerIndex = 9;
}
}
temp[0] |= input;
}
else {
index[0] -= 8;
}
code = table[temp[0] >> index[0]];
if ((code & MSB) != 0) {
if (markerIndex != 0) {
markerIndex = 0;
return 0xFF00 | marker;
}
temp[0] &= (mask >> (16 - index[0]));
temp[0] <<= 8;
input = this.input.readUnsignedByte();
if (input == 0xFF) {
marker = this.input.readUnsignedByte();
if (marker != 0) {
markerIndex = 9;
}
}
temp[0] |= input;
code = table[((code & 0xFF) * 256) + (temp[0] >> index[0])];
index[0] += 8;
}
index[0] += 8 - (code >> 8);
if (index[0] < 0) {
throw new IIOException("index=" + index[0] + " temp=" + temp[0] + " code=" + code + " in HuffmanValue()");
}
if (index[0] < markerIndex) {
markerIndex = 0;
return 0xFF00 | marker;
}
temp[0] &= (mask >> (16 - index[0]));
return code & 0xFF;
} } | public class class_name {
private int getHuffmanValue(final int table[], final int temp[], final int index[]) throws IOException {
int code, input;
final int mask = 0xFFFF;
if (index[0] < 8) {
temp[0] <<= 8;
input = this.input.readUnsignedByte();
if (input == 0xFF) {
marker = this.input.readUnsignedByte();
if (marker != 0) {
markerIndex = 9; // depends on control dependency: [if], data = [none]
}
}
temp[0] |= input;
}
else {
index[0] -= 8;
}
code = table[temp[0] >> index[0]];
if ((code & MSB) != 0) {
if (markerIndex != 0) {
markerIndex = 0;
return 0xFF00 | marker;
}
temp[0] &= (mask >> (16 - index[0]));
temp[0] <<= 8;
input = this.input.readUnsignedByte();
if (input == 0xFF) {
marker = this.input.readUnsignedByte();
if (marker != 0) {
markerIndex = 9;
}
}
temp[0] |= input;
code = table[((code & 0xFF) * 256) + (temp[0] >> index[0])];
index[0] += 8;
}
index[0] += 8 - (code >> 8);
if (index[0] < 0) {
throw new IIOException("index=" + index[0] + " temp=" + temp[0] + " code=" + code + " in HuffmanValue()");
}
if (index[0] < markerIndex) {
markerIndex = 0;
return 0xFF00 | marker;
}
temp[0] &= (mask >> (16 - index[0]));
return code & 0xFF;
} } |
public class class_name {
public static String separatorsToSystem(String path) {
if (path == null) {
return null;
}
if (EnvUtil.isWindows()) {
return separatorsToWindows(path);
} else {
return separatorsToUnix(path);
}
} } | public class class_name {
public static String separatorsToSystem(String path) {
if (path == null) {
return null; // depends on control dependency: [if], data = [none]
}
if (EnvUtil.isWindows()) {
return separatorsToWindows(path); // depends on control dependency: [if], data = [none]
} else {
return separatorsToUnix(path); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public View onViewCreated(View view, Context context, AttributeSet attrs) {
if (view == null) {
return null;
}
view = onViewCreatedInternal(view, context, attrs);
for (OnViewCreatedListener listener : otherListeners) {
if (listener != null) {
view = listener.onViewCreated(view, context, attrs);
}
}
return view;
} } | public class class_name {
public View onViewCreated(View view, Context context, AttributeSet attrs) {
if (view == null) {
return null; // depends on control dependency: [if], data = [none]
}
view = onViewCreatedInternal(view, context, attrs);
for (OnViewCreatedListener listener : otherListeners) {
if (listener != null) {
view = listener.onViewCreated(view, context, attrs); // depends on control dependency: [if], data = [none]
}
}
return view;
} } |
public class class_name {
public static void removeLegacyNonScopesFromMapping(Map<ScopeImpl, PvmExecutionImpl> mapping) {
Map<PvmExecutionImpl, List<ScopeImpl>> scopesForExecutions = new HashMap<PvmExecutionImpl, List<ScopeImpl>>();
for (Map.Entry<ScopeImpl, PvmExecutionImpl> mappingEntry : mapping.entrySet()) {
List<ScopeImpl> scopesForExecution = scopesForExecutions.get(mappingEntry.getValue());
if (scopesForExecution == null) {
scopesForExecution = new ArrayList<ScopeImpl>();
scopesForExecutions.put(mappingEntry.getValue(), scopesForExecution);
}
scopesForExecution.add(mappingEntry.getKey());
}
for (Map.Entry<PvmExecutionImpl, List<ScopeImpl>> scopesForExecution : scopesForExecutions.entrySet()) {
List<ScopeImpl> scopes = scopesForExecution.getValue();
if (scopes.size() > 1) {
ScopeImpl topMostScope = getTopMostScope(scopes);
for (ScopeImpl scope : scopes) {
if (scope != scope.getProcessDefinition() && scope != topMostScope) {
mapping.remove(scope);
}
}
}
}
} } | public class class_name {
public static void removeLegacyNonScopesFromMapping(Map<ScopeImpl, PvmExecutionImpl> mapping) {
Map<PvmExecutionImpl, List<ScopeImpl>> scopesForExecutions = new HashMap<PvmExecutionImpl, List<ScopeImpl>>();
for (Map.Entry<ScopeImpl, PvmExecutionImpl> mappingEntry : mapping.entrySet()) {
List<ScopeImpl> scopesForExecution = scopesForExecutions.get(mappingEntry.getValue());
if (scopesForExecution == null) {
scopesForExecution = new ArrayList<ScopeImpl>(); // depends on control dependency: [if], data = [none]
scopesForExecutions.put(mappingEntry.getValue(), scopesForExecution); // depends on control dependency: [if], data = [none]
}
scopesForExecution.add(mappingEntry.getKey()); // depends on control dependency: [for], data = [mappingEntry]
}
for (Map.Entry<PvmExecutionImpl, List<ScopeImpl>> scopesForExecution : scopesForExecutions.entrySet()) {
List<ScopeImpl> scopes = scopesForExecution.getValue();
if (scopes.size() > 1) {
ScopeImpl topMostScope = getTopMostScope(scopes);
for (ScopeImpl scope : scopes) {
if (scope != scope.getProcessDefinition() && scope != topMostScope) {
mapping.remove(scope); // depends on control dependency: [if], data = [(scope]
}
}
}
}
} } |
public class class_name {
@Override
public void handle(CommandContext ctx, String commandLine) {
// TODO Validate command
if (commandLine.contains("--help")) {
this.printHelp(commandLine, ctx);
return;
}
String[] commands = commandLine.split(" ");
if (commands.length == 1) {
ctx.connectController(null, -1);
} else if (commands.length == 2) {
if (commandLine.contains("--help")) {
this.printHelp("help/connect.txt", ctx);
return;
}
} else if (commands.length == 3) {
String host = commands[1];
try {
int port = Integer.parseInt(commands[2]);
ctx.connectController(host, port);
} catch (NumberFormatException ne) {
ctx.printLine("Port must be from 1 to 65535");
}
} else {
ctx.printLine("Invalid command.");
}
} } | public class class_name {
@Override
public void handle(CommandContext ctx, String commandLine) {
// TODO Validate command
if (commandLine.contains("--help")) {
this.printHelp(commandLine, ctx); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
String[] commands = commandLine.split(" ");
if (commands.length == 1) {
ctx.connectController(null, -1); // depends on control dependency: [if], data = [1)]
} else if (commands.length == 2) {
if (commandLine.contains("--help")) {
this.printHelp("help/connect.txt", ctx); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
} else if (commands.length == 3) {
String host = commands[1];
try {
int port = Integer.parseInt(commands[2]);
ctx.connectController(host, port); // depends on control dependency: [try], data = [none]
} catch (NumberFormatException ne) {
ctx.printLine("Port must be from 1 to 65535");
} // depends on control dependency: [catch], data = [none]
} else {
ctx.printLine("Invalid command."); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Implementation
protected boolean getPosTan(float distance, float pos[], float tan[]) {
if ((pos != null && pos.length < 2) || (tan != null && tan.length < 2)) {
throw new ArrayIndexOutOfBoundsException();
}
// This is not mathematically correct, but the simulation keeps the support library happy.
if (getLength() > 0) {
pos[0] = round(distance / getLength(), 4);
pos[1] = round(distance / getLength(), 4);
}
return true;
} } | public class class_name {
@Implementation
protected boolean getPosTan(float distance, float pos[], float tan[]) {
if ((pos != null && pos.length < 2) || (tan != null && tan.length < 2)) {
throw new ArrayIndexOutOfBoundsException();
}
// This is not mathematically correct, but the simulation keeps the support library happy.
if (getLength() > 0) {
pos[0] = round(distance / getLength(), 4); // depends on control dependency: [if], data = [none]
pos[1] = round(distance / getLength(), 4); // depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
public TranslationMap doImport() {
try {
for (String locale : LOCALES) {
TranslationHashMap trMap = new TranslationHashMap(getLocale(locale));
trMap.doImport(TranslationMap.class.getResourceAsStream(locale + ".txt"));
add(trMap);
}
postImportHook();
return this;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
} } | public class class_name {
public TranslationMap doImport() {
try {
for (String locale : LOCALES) {
TranslationHashMap trMap = new TranslationHashMap(getLocale(locale));
trMap.doImport(TranslationMap.class.getResourceAsStream(locale + ".txt")); // depends on control dependency: [for], data = [locale]
add(trMap); // depends on control dependency: [for], data = [none]
}
postImportHook(); // depends on control dependency: [try], data = [none]
return this; // depends on control dependency: [try], data = [none]
} catch (Exception ex) {
throw new RuntimeException(ex);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static boolean includes(final Language language1, final Language language2) {
if(language1==null || language2==null) {
return false;
}
if(language1.isWildcard()) {
return true;
}
if(language2.isWildcard()) {
return false;
}
return
language1.primaryTag().equals(language2.primaryTag()) &&
(language1.subTag().isEmpty() || language1.subTag().equals(language2.subTag()));
} } | public class class_name {
public static boolean includes(final Language language1, final Language language2) {
if(language1==null || language2==null) {
return false; // depends on control dependency: [if], data = [none]
}
if(language1.isWildcard()) {
return true; // depends on control dependency: [if], data = [none]
}
if(language2.isWildcard()) {
return false; // depends on control dependency: [if], data = [none]
}
return
language1.primaryTag().equals(language2.primaryTag()) &&
(language1.subTag().isEmpty() || language1.subTag().equals(language2.subTag()));
} } |
public class class_name {
protected CertPathValidatorResult validate(CertPath certPath) throws CertPathValidatorException {
List<? extends Certificate> certificates = certPath.getCertificates();
if (certificates.size() == 0) {
return null;
}
X509Certificate cert;
TBSCertificateStructure tbsCert;
GSIConstants.CertificateType certType;
X509Certificate issuerCert;
TBSCertificateStructure issuerTbsCert;
GSIConstants.CertificateType issuerCertType;
int proxyDepth = 0;
cert = (X509Certificate) certificates.get(0);
try {
tbsCert = getTBSCertificateStructure(cert);
certType = getCertificateType(tbsCert);
// validate the first certificate in chain
checkCertificate(cert, certType);
boolean isProxy = ProxyCertificateUtil.isProxy(certType);
if (isProxy) {
proxyDepth++;
}
} catch (CertPathValidatorException e) {
throw new CertPathValidatorException("Path validation failed for " + cert.getSubjectDN() + ": " + e.getMessage(),
e, certPath, 0);
}
for (int i = 1; i < certificates.size(); i++) {
boolean certIsProxy = ProxyCertificateUtil.isProxy(certType);
issuerCert = (X509Certificate) certificates.get(i);
issuerTbsCert = getTBSCertificateStructure(issuerCert);
issuerCertType = getCertificateType(issuerTbsCert);
proxyDepth = validateCert(cert, certType, issuerCert, issuerTbsCert, issuerCertType, proxyDepth, i,
certIsProxy);
if (certIsProxy) {
try {
checkProxyConstraints(certPath, cert, tbsCert, certType, issuerTbsCert, i);
} catch (CertPathValidatorException e) {
throw new CertPathValidatorException("Path validation failed for " + cert.getSubjectDN() + ": " + e.getMessage(),
e, certPath, i - 1);
}
} else {
try {
checkKeyUsage(issuerTbsCert);
} catch (IOException e) {
throw new CertPathValidatorException("Key usage check failed on " + issuerCert.getSubjectDN() + ": " + e.getMessage(),
e, certPath, i);
} catch (CertPathValidatorException e) {
throw new CertPathValidatorException("Path validation failed for " + issuerCert.getSubjectDN() + ": " + e.getMessage(),
e, certPath, i);
}
}
try {
checkCertificate(issuerCert, issuerCertType);
} catch (CertPathValidatorException e) {
throw new CertPathValidatorException("Path validation failed for " + issuerCert.getSubjectDN() + ": " + e.getMessage(),
e, certPath, i);
}
cert = issuerCert;
certType = issuerCertType;
tbsCert = issuerTbsCert;
}
return new X509ProxyCertPathValidatorResult(this.identityCert,
this.limited);
} } | public class class_name {
protected CertPathValidatorResult validate(CertPath certPath) throws CertPathValidatorException {
List<? extends Certificate> certificates = certPath.getCertificates();
if (certificates.size() == 0) {
return null;
}
X509Certificate cert;
TBSCertificateStructure tbsCert;
GSIConstants.CertificateType certType;
X509Certificate issuerCert;
TBSCertificateStructure issuerTbsCert;
GSIConstants.CertificateType issuerCertType;
int proxyDepth = 0;
cert = (X509Certificate) certificates.get(0);
try {
tbsCert = getTBSCertificateStructure(cert);
certType = getCertificateType(tbsCert);
// validate the first certificate in chain
checkCertificate(cert, certType);
boolean isProxy = ProxyCertificateUtil.isProxy(certType);
if (isProxy) {
proxyDepth++; // depends on control dependency: [if], data = [none]
}
} catch (CertPathValidatorException e) {
throw new CertPathValidatorException("Path validation failed for " + cert.getSubjectDN() + ": " + e.getMessage(),
e, certPath, 0);
}
for (int i = 1; i < certificates.size(); i++) {
boolean certIsProxy = ProxyCertificateUtil.isProxy(certType);
issuerCert = (X509Certificate) certificates.get(i);
issuerTbsCert = getTBSCertificateStructure(issuerCert);
issuerCertType = getCertificateType(issuerTbsCert);
proxyDepth = validateCert(cert, certType, issuerCert, issuerTbsCert, issuerCertType, proxyDepth, i,
certIsProxy);
if (certIsProxy) {
try {
checkProxyConstraints(certPath, cert, tbsCert, certType, issuerTbsCert, i); // depends on control dependency: [try], data = [none]
} catch (CertPathValidatorException e) {
throw new CertPathValidatorException("Path validation failed for " + cert.getSubjectDN() + ": " + e.getMessage(),
e, certPath, i - 1);
} // depends on control dependency: [catch], data = [none]
} else {
try {
checkKeyUsage(issuerTbsCert); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new CertPathValidatorException("Key usage check failed on " + issuerCert.getSubjectDN() + ": " + e.getMessage(),
e, certPath, i);
} catch (CertPathValidatorException e) { // depends on control dependency: [catch], data = [none]
throw new CertPathValidatorException("Path validation failed for " + issuerCert.getSubjectDN() + ": " + e.getMessage(),
e, certPath, i);
} // depends on control dependency: [catch], data = [none]
}
try {
checkCertificate(issuerCert, issuerCertType);
} catch (CertPathValidatorException e) {
throw new CertPathValidatorException("Path validation failed for " + issuerCert.getSubjectDN() + ": " + e.getMessage(),
e, certPath, i);
}
cert = issuerCert;
certType = issuerCertType;
tbsCert = issuerTbsCert;
}
return new X509ProxyCertPathValidatorResult(this.identityCert,
this.limited);
} } |
public class class_name {
public static List<ConnectionParams> manyFromConfig(ConfigParams config, boolean configAsDefault) {
List<ConnectionParams> result = new ArrayList<ConnectionParams>();
// Try to get multiple connections first
ConfigParams connections = config.getSection("connections");
if (connections.size() > 0) {
List<String> connectionSections = connections.getSectionNames();
for (String section : connectionSections) {
ConfigParams connection = connections.getSection(section);
result.add(new ConnectionParams(connection));
}
}
// Then try to get a single connection
else {
ConfigParams connection = config.getSection("connection");
if (connection.size() > 0)
result.add(new ConnectionParams(connection));
// Apply default if possible
else if (configAsDefault)
result.add(new ConnectionParams(config));
}
return result;
} } | public class class_name {
public static List<ConnectionParams> manyFromConfig(ConfigParams config, boolean configAsDefault) {
List<ConnectionParams> result = new ArrayList<ConnectionParams>();
// Try to get multiple connections first
ConfigParams connections = config.getSection("connections");
if (connections.size() > 0) {
List<String> connectionSections = connections.getSectionNames();
for (String section : connectionSections) {
ConfigParams connection = connections.getSection(section);
result.add(new ConnectionParams(connection)); // depends on control dependency: [for], data = [none]
}
}
// Then try to get a single connection
else {
ConfigParams connection = config.getSection("connection");
if (connection.size() > 0)
result.add(new ConnectionParams(connection));
// Apply default if possible
else if (configAsDefault)
result.add(new ConnectionParams(config));
}
return result;
} } |
public class class_name {
protected void exportSchema(final String persistenceUnit, List<TableInfo> tables)
{
// Get persistence unit metadata
this.puMetadata = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(persistenceUnit);
String paramString = externalProperties != null ? (String) externalProperties
.get(PersistenceProperties.KUNDERA_CLIENT_FACTORY) : null;
if (clientFactory != null
&& ((clientFactory.equalsIgnoreCase(puMetadata.getProperties().getProperty(
PersistenceProperties.KUNDERA_CLIENT_FACTORY))) || (paramString != null && clientFactory
.equalsIgnoreCase(paramString))))
{
readConfigProperties(puMetadata);
// invoke handle operation.
if (operation != null && initiateClient())
{
tableInfos = tables;
handleOperations(tables);
}
}
} } | public class class_name {
protected void exportSchema(final String persistenceUnit, List<TableInfo> tables)
{
// Get persistence unit metadata
this.puMetadata = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(persistenceUnit);
String paramString = externalProperties != null ? (String) externalProperties
.get(PersistenceProperties.KUNDERA_CLIENT_FACTORY) : null;
if (clientFactory != null
&& ((clientFactory.equalsIgnoreCase(puMetadata.getProperties().getProperty(
PersistenceProperties.KUNDERA_CLIENT_FACTORY))) || (paramString != null && clientFactory
.equalsIgnoreCase(paramString))))
{
readConfigProperties(puMetadata); // depends on control dependency: [if], data = [none]
// invoke handle operation.
if (operation != null && initiateClient())
{
tableInfos = tables; // depends on control dependency: [if], data = [none]
handleOperations(tables); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public EClass getIfcBuildingElementPart() {
if (ifcBuildingElementPartEClass == null) {
ifcBuildingElementPartEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(57);
}
return ifcBuildingElementPartEClass;
} } | public class class_name {
public EClass getIfcBuildingElementPart() {
if (ifcBuildingElementPartEClass == null) {
ifcBuildingElementPartEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(57);
// depends on control dependency: [if], data = [none]
}
return ifcBuildingElementPartEClass;
} } |
public class class_name {
public ServiceCall<LogCollection> listLogs(ListLogsOptions listLogsOptions) {
Validator.notNull(listLogsOptions, "listLogsOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "logs" };
String[] pathParameters = { listLogsOptions.workspaceId() };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query("version", versionDate);
Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("conversation", "v1", "listLogs");
for (Entry<String, String> header : sdkHeaders.entrySet()) {
builder.header(header.getKey(), header.getValue());
}
builder.header("Accept", "application/json");
if (listLogsOptions.sort() != null) {
builder.query("sort", listLogsOptions.sort());
}
if (listLogsOptions.filter() != null) {
builder.query("filter", listLogsOptions.filter());
}
if (listLogsOptions.pageLimit() != null) {
builder.query("page_limit", String.valueOf(listLogsOptions.pageLimit()));
}
if (listLogsOptions.cursor() != null) {
builder.query("cursor", listLogsOptions.cursor());
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(LogCollection.class));
} } | public class class_name {
public ServiceCall<LogCollection> listLogs(ListLogsOptions listLogsOptions) {
Validator.notNull(listLogsOptions, "listLogsOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "logs" };
String[] pathParameters = { listLogsOptions.workspaceId() };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query("version", versionDate);
Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("conversation", "v1", "listLogs");
for (Entry<String, String> header : sdkHeaders.entrySet()) {
builder.header(header.getKey(), header.getValue()); // depends on control dependency: [for], data = [header]
}
builder.header("Accept", "application/json");
if (listLogsOptions.sort() != null) {
builder.query("sort", listLogsOptions.sort()); // depends on control dependency: [if], data = [none]
}
if (listLogsOptions.filter() != null) {
builder.query("filter", listLogsOptions.filter()); // depends on control dependency: [if], data = [none]
}
if (listLogsOptions.pageLimit() != null) {
builder.query("page_limit", String.valueOf(listLogsOptions.pageLimit())); // depends on control dependency: [if], data = [(listLogsOptions.pageLimit()]
}
if (listLogsOptions.cursor() != null) {
builder.query("cursor", listLogsOptions.cursor()); // depends on control dependency: [if], data = [none]
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(LogCollection.class));
} } |
public class class_name {
@Override
public String marshall(Object value) {
if( value == null ) {
return "null";
}
return KieExtendedDMNFunctions.getFunction(CodeFunction.class).invoke(value).cata(justNull(), Function.identity());
} } | public class class_name {
@Override
public String marshall(Object value) {
if( value == null ) {
return "null"; // depends on control dependency: [if], data = [none]
}
return KieExtendedDMNFunctions.getFunction(CodeFunction.class).invoke(value).cata(justNull(), Function.identity());
} } |
public class class_name {
protected TaskInstance createTaskInstance() throws ActivityException {
try {
String taskTemplate = getAttributeValue(ATTRIBUTE_TASK_TEMPLATE);
if (taskTemplate == null)
throw new ActivityException("Missing attribute: " + ATTRIBUTE_TASK_TEMPLATE);
String templateVersion = getAttributeValue(ATTRIBUTE_TASK_TEMPLATE_VERSION);
AssetVersionSpec spec = new AssetVersionSpec(taskTemplate, templateVersion == null ? "0" : templateVersion);
TaskTemplate template = TaskTemplateCache.getTaskTemplate(spec);
if (template == null)
throw new ActivityException("Task template not found: " + spec);
String taskName = template.getTaskName();
String title = null;
if (ActivityRuntimeContext.isExpression(taskName)) {
title = getRuntimeContext().evaluateToString(taskName);
}
String comments = null;
Exception exception = (Exception) getVariableValue("exception");
if (exception != null) {
comments = exception.toString();
if (exception instanceof ActivityException) {
ActivityRuntimeContext rc = ((ActivityException)exception).getRuntimeContext();
if (rc != null && rc.getProcess() != null) {
comments = rc.getProcess().getFullLabel() + "\n" + comments;
}
}
}
return createTaskInstance(spec, getMasterRequestId(), getProcessInstanceId(),
getActivityInstanceId(), getWorkTransitionInstanceId(), title, comments);
}
catch (Exception ex) {
throw new ActivityException(ex.getMessage(), ex);
}
} } | public class class_name {
protected TaskInstance createTaskInstance() throws ActivityException {
try {
String taskTemplate = getAttributeValue(ATTRIBUTE_TASK_TEMPLATE);
if (taskTemplate == null)
throw new ActivityException("Missing attribute: " + ATTRIBUTE_TASK_TEMPLATE);
String templateVersion = getAttributeValue(ATTRIBUTE_TASK_TEMPLATE_VERSION);
AssetVersionSpec spec = new AssetVersionSpec(taskTemplate, templateVersion == null ? "0" : templateVersion);
TaskTemplate template = TaskTemplateCache.getTaskTemplate(spec);
if (template == null)
throw new ActivityException("Task template not found: " + spec);
String taskName = template.getTaskName();
String title = null;
if (ActivityRuntimeContext.isExpression(taskName)) {
title = getRuntimeContext().evaluateToString(taskName);
}
String comments = null;
Exception exception = (Exception) getVariableValue("exception");
if (exception != null) {
comments = exception.toString();
if (exception instanceof ActivityException) {
ActivityRuntimeContext rc = ((ActivityException)exception).getRuntimeContext();
if (rc != null && rc.getProcess() != null) {
comments = rc.getProcess().getFullLabel() + "\n" + comments; // depends on control dependency: [if], data = [none]
}
}
}
return createTaskInstance(spec, getMasterRequestId(), getProcessInstanceId(),
getActivityInstanceId(), getWorkTransitionInstanceId(), title, comments);
}
catch (Exception ex) {
throw new ActivityException(ex.getMessage(), ex);
}
} } |
public class class_name {
public static Instance findInstanceByPath( AbstractApplication application, String instancePath ) {
Collection<Instance> currentList = new ArrayList<> ();
if( application != null )
currentList.addAll( application.getRootInstances());
List<String> instanceNames = new ArrayList<> ();
if( instancePath != null )
instanceNames.addAll( Arrays.asList( instancePath.split( "/" )));
if( instanceNames.size() > 0
&& Utils.isEmptyOrWhitespaces( instanceNames.get( 0 )))
instanceNames.remove( 0 );
// Every path segment points to an instance
Instance result = null;
for( String instanceName : instanceNames ) {
result = null;
for( Instance instance : currentList ) {
if( instanceName.equals( instance.getName())) {
result = instance;
break;
}
}
// The segment does not match any instance
if( result == null )
break;
// Otherwise, prepare the next iteration
currentList = result.getChildren();
}
return result;
} } | public class class_name {
public static Instance findInstanceByPath( AbstractApplication application, String instancePath ) {
Collection<Instance> currentList = new ArrayList<> ();
if( application != null )
currentList.addAll( application.getRootInstances());
List<String> instanceNames = new ArrayList<> ();
if( instancePath != null )
instanceNames.addAll( Arrays.asList( instancePath.split( "/" )));
if( instanceNames.size() > 0
&& Utils.isEmptyOrWhitespaces( instanceNames.get( 0 )))
instanceNames.remove( 0 );
// Every path segment points to an instance
Instance result = null;
for( String instanceName : instanceNames ) {
result = null; // depends on control dependency: [for], data = [none]
for( Instance instance : currentList ) {
if( instanceName.equals( instance.getName())) {
result = instance; // depends on control dependency: [if], data = [none]
break;
}
}
// The segment does not match any instance
if( result == null )
break;
// Otherwise, prepare the next iteration
currentList = result.getChildren(); // depends on control dependency: [for], data = [none]
}
return result;
} } |
public class class_name {
DatanodeCommand[] handleHeartbeat(DatanodeRegistration nodeReg,
long capacity, long dfsUsed, long remaining, long namespaceUsed,
int xceiverCount, int xmitsInProgress)
throws IOException {
DatanodeCommand cmd = null;
synchronized (heartbeats) {
synchronized (datanodeMap) {
DatanodeDescriptor nodeinfo = null;
try {
nodeinfo = getDatanode(nodeReg);
} catch (UnregisteredDatanodeException e) {
return new DatanodeCommand[]{DatanodeCommand.REGISTER};
}
// Check if this datanode should actually be shutdown instead.
if (nodeinfo != null && nodeinfo.isDisallowed()) {
setDatanodeDead(nodeinfo);
throw new DisallowedDatanodeException(nodeinfo);
}
if (nodeinfo == null || !nodeinfo.isAlive) {
return new DatanodeCommand[]{DatanodeCommand.REGISTER};
}
updateStats(nodeinfo, false);
nodeinfo.updateHeartbeat(capacity, dfsUsed, remaining, namespaceUsed, xceiverCount);
updateStats(nodeinfo, true);
//check lease recovery
cmd = nodeinfo.getLeaseRecoveryCommand(Integer.MAX_VALUE);
if (cmd != null) {
return new DatanodeCommand[]{cmd};
}
ArrayList<DatanodeCommand> cmds = new ArrayList<DatanodeCommand>(2);
//check pending replication
cmd = nodeinfo.getReplicationCommand(maxReplicationStreams -
xmitsInProgress);
if (cmd != null) {
cmds.add(cmd);
}
//check block invalidation
cmd = nodeinfo.getInvalidateBlocks(ReplicationConfigKeys.blockInvalidateLimit);
if (cmd != null) {
cmds.add(cmd);
}
// check raid tasks
cmd = nodeinfo.getRaidCommand(ReplicationConfigKeys.raidEncodingTaskLimit,
ReplicationConfigKeys.raidDecodingTaskLimit);
if (cmd != null) {
cmds.add(cmd);
}
if (!cmds.isEmpty()) {
return cmds.toArray(new DatanodeCommand[cmds.size()]);
}
}
}
//check distributed upgrade
cmd = getDistributedUpgradeCommand();
if (cmd != null) {
return new DatanodeCommand[]{cmd};
}
return null;
} } | public class class_name {
DatanodeCommand[] handleHeartbeat(DatanodeRegistration nodeReg,
long capacity, long dfsUsed, long remaining, long namespaceUsed,
int xceiverCount, int xmitsInProgress)
throws IOException {
DatanodeCommand cmd = null;
synchronized (heartbeats) {
synchronized (datanodeMap) {
DatanodeDescriptor nodeinfo = null;
try {
nodeinfo = getDatanode(nodeReg); // depends on control dependency: [try], data = [none]
} catch (UnregisteredDatanodeException e) {
return new DatanodeCommand[]{DatanodeCommand.REGISTER};
} // depends on control dependency: [catch], data = [none]
// Check if this datanode should actually be shutdown instead.
if (nodeinfo != null && nodeinfo.isDisallowed()) {
setDatanodeDead(nodeinfo); // depends on control dependency: [if], data = [(nodeinfo]
throw new DisallowedDatanodeException(nodeinfo);
}
if (nodeinfo == null || !nodeinfo.isAlive) {
return new DatanodeCommand[]{DatanodeCommand.REGISTER}; // depends on control dependency: [if], data = [none]
}
updateStats(nodeinfo, false);
nodeinfo.updateHeartbeat(capacity, dfsUsed, remaining, namespaceUsed, xceiverCount);
updateStats(nodeinfo, true);
//check lease recovery
cmd = nodeinfo.getLeaseRecoveryCommand(Integer.MAX_VALUE);
if (cmd != null) {
return new DatanodeCommand[]{cmd}; // depends on control dependency: [if], data = [none]
}
ArrayList<DatanodeCommand> cmds = new ArrayList<DatanodeCommand>(2);
//check pending replication
cmd = nodeinfo.getReplicationCommand(maxReplicationStreams -
xmitsInProgress);
if (cmd != null) {
cmds.add(cmd); // depends on control dependency: [if], data = [(cmd]
}
//check block invalidation
cmd = nodeinfo.getInvalidateBlocks(ReplicationConfigKeys.blockInvalidateLimit);
if (cmd != null) {
cmds.add(cmd); // depends on control dependency: [if], data = [(cmd]
}
// check raid tasks
cmd = nodeinfo.getRaidCommand(ReplicationConfigKeys.raidEncodingTaskLimit,
ReplicationConfigKeys.raidDecodingTaskLimit);
if (cmd != null) {
cmds.add(cmd); // depends on control dependency: [if], data = [(cmd]
}
if (!cmds.isEmpty()) {
return cmds.toArray(new DatanodeCommand[cmds.size()]); // depends on control dependency: [if], data = [none]
}
}
}
//check distributed upgrade
cmd = getDistributedUpgradeCommand();
if (cmd != null) {
return new DatanodeCommand[]{cmd};
}
return null;
} } |
public class class_name {
public static EventType map(Event event) {
EventType eventType = new EventType();
eventType.setTimestamp(Converter.convertDate(event.getTimestamp()));
eventType.setEventType(convertEventType(event.getEventType()));
OriginatorType origType = mapOriginator(event.getOriginator());
eventType.setOriginator(origType);
MessageInfoType miType = mapMessageInfo(event.getMessageInfo());
eventType.setMessageInfo(miType);
eventType.setCustomInfo(convertCustomInfo(event.getCustomInfo()));
eventType.setContentCut(event.isContentCut());
if (event.getContent() != null) {
DataHandler datHandler = getDataHandlerForString(event);
eventType.setContent(datHandler);
}
return eventType;
} } | public class class_name {
public static EventType map(Event event) {
EventType eventType = new EventType();
eventType.setTimestamp(Converter.convertDate(event.getTimestamp()));
eventType.setEventType(convertEventType(event.getEventType()));
OriginatorType origType = mapOriginator(event.getOriginator());
eventType.setOriginator(origType);
MessageInfoType miType = mapMessageInfo(event.getMessageInfo());
eventType.setMessageInfo(miType);
eventType.setCustomInfo(convertCustomInfo(event.getCustomInfo()));
eventType.setContentCut(event.isContentCut());
if (event.getContent() != null) {
DataHandler datHandler = getDataHandlerForString(event);
eventType.setContent(datHandler); // depends on control dependency: [if], data = [none]
}
return eventType;
} } |
public class class_name {
@Override
public Fix replace(ExpressionTemplateMatch match) {
Inliner inliner = match.createInliner();
Context context = inliner.getContext();
if (annotations().containsKey(UseImportPolicy.class)) {
ImportPolicy.bind(context, annotations().getInstance(UseImportPolicy.class).value());
} else {
ImportPolicy.bind(context, ImportPolicy.IMPORT_TOP_LEVEL);
}
int prec = getPrecedence(match.getLocation(), context);
SuggestedFix.Builder fix = SuggestedFix.builder();
try {
StringWriter writer = new StringWriter();
pretty(inliner.getContext(), writer).printExpr(expression().inline(inliner), prec);
fix.replace(match.getLocation(), writer.toString());
} catch (CouldNotResolveImportException e) {
logger.log(SEVERE, "Failure to resolve in replacement", e);
} catch (IOException e) {
throw new RuntimeException(e);
}
return addImports(inliner, fix);
} } | public class class_name {
@Override
public Fix replace(ExpressionTemplateMatch match) {
Inliner inliner = match.createInliner();
Context context = inliner.getContext();
if (annotations().containsKey(UseImportPolicy.class)) {
ImportPolicy.bind(context, annotations().getInstance(UseImportPolicy.class).value()); // depends on control dependency: [if], data = [none]
} else {
ImportPolicy.bind(context, ImportPolicy.IMPORT_TOP_LEVEL); // depends on control dependency: [if], data = [none]
}
int prec = getPrecedence(match.getLocation(), context);
SuggestedFix.Builder fix = SuggestedFix.builder();
try {
StringWriter writer = new StringWriter();
pretty(inliner.getContext(), writer).printExpr(expression().inline(inliner), prec); // depends on control dependency: [try], data = [none]
fix.replace(match.getLocation(), writer.toString()); // depends on control dependency: [try], data = [none]
} catch (CouldNotResolveImportException e) {
logger.log(SEVERE, "Failure to resolve in replacement", e);
} catch (IOException e) { // depends on control dependency: [catch], data = [none]
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
return addImports(inliner, fix);
} } |
public class class_name {
public synchronized void initialize() {
if (!isInitialized()) {
fillMethodIndex();
try {
addProperties();
} catch (Throwable e) {
if (!AndroidSupport.isRunningAndroid()) {
ExceptionUtils.sneakyThrow(e);
}
// Introspection failure...
// May happen in Android
}
initialized = true;
}
} } | public class class_name {
public synchronized void initialize() {
if (!isInitialized()) {
fillMethodIndex(); // depends on control dependency: [if], data = [none]
try {
addProperties(); // depends on control dependency: [try], data = [none]
} catch (Throwable e) {
if (!AndroidSupport.isRunningAndroid()) {
ExceptionUtils.sneakyThrow(e); // depends on control dependency: [if], data = [none]
}
// Introspection failure...
// May happen in Android
} // depends on control dependency: [catch], data = [none]
initialized = true; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static ClassLoader getParaClassLoader() {
if (paraClassLoader == null) {
try {
ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
List<URL> jars = new ArrayList<>();
File lib = new File(Config.getConfigParam("plugin_folder", "lib/"));
if (lib.exists() && lib.isDirectory()) {
for (File file : FileUtils.listFiles(lib, new String[]{"jar"}, false)) {
jars.add(file.toURI().toURL());
}
}
paraClassLoader = new URLClassLoader(jars.toArray(new URL[0]), currentClassLoader);
// Thread.currentThread().setContextClassLoader(paraClassLoader);
} catch (Exception e) {
logger.error(null, e);
}
}
return paraClassLoader;
} } | public class class_name {
public static ClassLoader getParaClassLoader() {
if (paraClassLoader == null) {
try {
ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
List<URL> jars = new ArrayList<>();
File lib = new File(Config.getConfigParam("plugin_folder", "lib/"));
if (lib.exists() && lib.isDirectory()) {
for (File file : FileUtils.listFiles(lib, new String[]{"jar"}, false)) {
jars.add(file.toURI().toURL()); // depends on control dependency: [for], data = [file]
}
}
paraClassLoader = new URLClassLoader(jars.toArray(new URL[0]), currentClassLoader); // depends on control dependency: [try], data = [none]
// Thread.currentThread().setContextClassLoader(paraClassLoader);
} catch (Exception e) {
logger.error(null, e);
} // depends on control dependency: [catch], data = [none]
}
return paraClassLoader;
} } |
public class class_name {
public static PoolInfoStrings createPoolInfoStrings(PoolInfo poolInfo) {
if (poolInfo == null) {
return null;
}
return new PoolInfoStrings(poolInfo.getPoolGroupName(),
poolInfo.getPoolName());
} } | public class class_name {
public static PoolInfoStrings createPoolInfoStrings(PoolInfo poolInfo) {
if (poolInfo == null) {
return null; // depends on control dependency: [if], data = [none]
}
return new PoolInfoStrings(poolInfo.getPoolGroupName(),
poolInfo.getPoolName());
} } |
public class class_name {
@Override
public EClass getIfcStructuralSurfaceAction() {
if (ifcStructuralSurfaceActionEClass == null) {
ifcStructuralSurfaceActionEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(660);
}
return ifcStructuralSurfaceActionEClass;
} } | public class class_name {
@Override
public EClass getIfcStructuralSurfaceAction() {
if (ifcStructuralSurfaceActionEClass == null) {
ifcStructuralSurfaceActionEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(660);
// depends on control dependency: [if], data = [none]
}
return ifcStructuralSurfaceActionEClass;
} } |
public class class_name {
public static String loadResourceFile(FacesContext ctx, String file)
{
ByteArrayOutputStream content = new ByteArrayOutputStream(10240);
InputStream in = null;
try
{
in = ctx.getExternalContext().getResourceAsStream(file);
if (in == null)
{
return null;
}
byte[] fileBuffer = new byte[10240];
int read;
while ((read = in.read(fileBuffer)) > -1)
{
content.write(fileBuffer, 0, read);
}
}
catch (FileNotFoundException e)
{
if (log.isLoggable(Level.WARNING))
{
log.log(Level.WARNING, "no such file " + file, e);
}
content = null;
}
catch (IOException e)
{
if (log.isLoggable(Level.WARNING))
{
log.log(Level.WARNING, "problems during processing resource "
+ file, e);
}
content = null;
}
finally
{
try
{
if (content != null)
{
content.close();
}
}
catch (IOException e)
{
log.log(Level.WARNING, e.getLocalizedMessage(), e);
}
if (in != null)
{
try
{
in.close();
}
catch (IOException e)
{
log.log(Level.WARNING, e.getLocalizedMessage(), e);
}
}
}
return content != null ? content.toString() : null;
} } | public class class_name {
public static String loadResourceFile(FacesContext ctx, String file)
{
ByteArrayOutputStream content = new ByteArrayOutputStream(10240);
InputStream in = null;
try
{
in = ctx.getExternalContext().getResourceAsStream(file); // depends on control dependency: [try], data = [none]
if (in == null)
{
return null; // depends on control dependency: [if], data = [none]
}
byte[] fileBuffer = new byte[10240];
int read;
while ((read = in.read(fileBuffer)) > -1)
{
content.write(fileBuffer, 0, read); // depends on control dependency: [while], data = [none]
}
}
catch (FileNotFoundException e)
{
if (log.isLoggable(Level.WARNING))
{
log.log(Level.WARNING, "no such file " + file, e); // depends on control dependency: [if], data = [none]
}
content = null;
} // depends on control dependency: [catch], data = [none]
catch (IOException e)
{
if (log.isLoggable(Level.WARNING))
{
log.log(Level.WARNING, "problems during processing resource "
+ file, e); // depends on control dependency: [if], data = [none]
}
content = null;
} // depends on control dependency: [catch], data = [none]
finally
{
try
{
if (content != null)
{
content.close(); // depends on control dependency: [if], data = [none]
}
}
catch (IOException e)
{
log.log(Level.WARNING, e.getLocalizedMessage(), e);
} // depends on control dependency: [catch], data = [none]
if (in != null)
{
try
{
in.close(); // depends on control dependency: [try], data = [none]
}
catch (IOException e)
{
log.log(Level.WARNING, e.getLocalizedMessage(), e);
} // depends on control dependency: [catch], data = [none]
}
}
return content != null ? content.toString() : null;
} } |
public class class_name {
private static byte[] readInputStream(byte[] buf, InputStream s) throws IOException {
try {
buf = ensureCapacity(buf, s.available());
int r = s.read(buf);
int bp = 0;
while (r != -1) {
bp += r;
buf = ensureCapacity(buf, bp);
r = s.read(buf, bp, buf.length - bp);
}
return buf;
} finally {
try {
s.close();
} catch (IOException e) {
/* Ignore any errors, as this stream may have already
* thrown a related exception which is the one that
* should be reported.
*/
}
}
} } | public class class_name {
private static byte[] readInputStream(byte[] buf, InputStream s) throws IOException {
try {
buf = ensureCapacity(buf, s.available());
int r = s.read(buf);
int bp = 0;
while (r != -1) {
bp += r;
buf = ensureCapacity(buf, bp);
r = s.read(buf, bp, buf.length - bp);
}
return buf;
} finally {
try {
s.close(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
/* Ignore any errors, as this stream may have already
* thrown a related exception which is the one that
* should be reported.
*/
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
@Override protected void handleEvents(final String EVENT_TYPE) {
super.handleEvents(EVENT_TYPE);
if ("VISIBILITY".equals(EVENT_TYPE)) {
Helper.enableNode(titleText, !tile.getTitle().isEmpty());
Helper.enableNode(text, tile.isTextVisible());
Helper.enableNode(description, !tile.getDescription().isEmpty());
} else if ("RECALC".equals(EVENT_TYPE)) {
if (null != tile.getLeftGraphics()) { leftGraphicsPane.getChildren().setAll(tile.getLeftGraphics()); }
if (null != tile.getMiddleGraphics()) { middleGraphicsPane.getChildren().setAll(tile.getMiddleGraphics()); }
if (null != tile.getRightGraphics()) { rightGraphicsPane.getChildren().setAll(tile.getRightGraphics()); }
resize();
}
} } | public class class_name {
@Override protected void handleEvents(final String EVENT_TYPE) {
super.handleEvents(EVENT_TYPE);
if ("VISIBILITY".equals(EVENT_TYPE)) {
Helper.enableNode(titleText, !tile.getTitle().isEmpty()); // depends on control dependency: [if], data = [none]
Helper.enableNode(text, tile.isTextVisible()); // depends on control dependency: [if], data = [none]
Helper.enableNode(description, !tile.getDescription().isEmpty()); // depends on control dependency: [if], data = [none]
} else if ("RECALC".equals(EVENT_TYPE)) {
if (null != tile.getLeftGraphics()) { leftGraphicsPane.getChildren().setAll(tile.getLeftGraphics()); } // depends on control dependency: [if], data = [tile.getLeftGraphics())]
if (null != tile.getMiddleGraphics()) { middleGraphicsPane.getChildren().setAll(tile.getMiddleGraphics()); } // depends on control dependency: [if], data = [tile.getMiddleGraphics())]
if (null != tile.getRightGraphics()) { rightGraphicsPane.getChildren().setAll(tile.getRightGraphics()); } // depends on control dependency: [if], data = [tile.getRightGraphics())]
resize(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public int encode ( byte[] dst, int dstIndex ) {
int start = dstIndex;
SMBUtil.writeInt4(this.capabilities, dst, dstIndex);
dstIndex += 4;
System.arraycopy(this.clientGuid, 0, dst, dstIndex, 16);
dstIndex += 16;
SMBUtil.writeInt2(this.securityMode, dst, dstIndex);
dstIndex += 2;
SMBUtil.writeInt2(this.dialects.length, dst, dstIndex);
dstIndex += 2;
for ( int dialect : this.dialects ) {
SMBUtil.writeInt2(dialect, dst, dstIndex);
dstIndex += 2;
}
return dstIndex - start;
} } | public class class_name {
@Override
public int encode ( byte[] dst, int dstIndex ) {
int start = dstIndex;
SMBUtil.writeInt4(this.capabilities, dst, dstIndex);
dstIndex += 4;
System.arraycopy(this.clientGuid, 0, dst, dstIndex, 16);
dstIndex += 16;
SMBUtil.writeInt2(this.securityMode, dst, dstIndex);
dstIndex += 2;
SMBUtil.writeInt2(this.dialects.length, dst, dstIndex);
dstIndex += 2;
for ( int dialect : this.dialects ) {
SMBUtil.writeInt2(dialect, dst, dstIndex); // depends on control dependency: [for], data = [dialect]
dstIndex += 2; // depends on control dependency: [for], data = [none]
}
return dstIndex - start;
} } |
public class class_name {
public void processRequest(RequestContext context, RequestSecurityProcessorChain processorChain) throws Exception {
if (isLogoutRequest(context.getRequest())) {
logger.debug("Processing logout request");
Authentication auth = SecurityUtils.getAuthentication(context.getRequest());
if (auth != null) {
authenticationManager.invalidateAuthentication(auth);
}
onLogoutSuccess(context, auth);
} else {
processorChain.processRequest(context);
}
} } | public class class_name {
public void processRequest(RequestContext context, RequestSecurityProcessorChain processorChain) throws Exception {
if (isLogoutRequest(context.getRequest())) {
logger.debug("Processing logout request");
Authentication auth = SecurityUtils.getAuthentication(context.getRequest());
if (auth != null) {
authenticationManager.invalidateAuthentication(auth); // depends on control dependency: [if], data = [(auth]
}
onLogoutSuccess(context, auth);
} else {
processorChain.processRequest(context);
}
} } |
public class class_name {
public TypeMirror unaryNumericPromotion(TypeMirror type) {
TypeKind t = type.getKind();
if (t == TypeKind.DECLARED) {
type = javacTypes.unboxedType(type);
t = type.getKind();
}
if (t == TypeKind.BYTE || t == TypeKind.SHORT || t == TypeKind.CHAR) {
return getInt();
} else {
return type;
}
} } | public class class_name {
public TypeMirror unaryNumericPromotion(TypeMirror type) {
TypeKind t = type.getKind();
if (t == TypeKind.DECLARED) {
type = javacTypes.unboxedType(type); // depends on control dependency: [if], data = [(t]
t = type.getKind(); // depends on control dependency: [if], data = [none]
}
if (t == TypeKind.BYTE || t == TypeKind.SHORT || t == TypeKind.CHAR) {
return getInt(); // depends on control dependency: [if], data = [none]
} else {
return type; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void onCloseConnection()
{
try {
finishRequest();
} catch (Exception e) {
log.log(Level.FINE, e.toString(), e);
}
HttpBufferStore httpBuffer = _largeHttpBuffer;
_largeHttpBuffer = null;
if (httpBuffer != null) {
http().freeHttpBuffer(httpBuffer);
}
} } | public class class_name {
public void onCloseConnection()
{
try {
finishRequest(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
log.log(Level.FINE, e.toString(), e);
} // depends on control dependency: [catch], data = [none]
HttpBufferStore httpBuffer = _largeHttpBuffer;
_largeHttpBuffer = null;
if (httpBuffer != null) {
http().freeHttpBuffer(httpBuffer); // depends on control dependency: [if], data = [(httpBuffer]
}
} } |
public class class_name {
<E extends BaseClient> Observable<E> initialise(@NonNull final Application application, @NonNull final E instance, @NonNull final CallbackAdapter adapter) {
if (state.compareAndSet(GlobalState.NOT_INITIALISED, GlobalState.INITIALISING)) {
return init(application, adapter)
.concatMap(new Func1<Boolean, Observable<SessionData>>() {
@Override
public Observable<SessionData> call(Boolean state) {
return loadSession(state);
}
})
.doOnNext(session -> log.d(session != null ? "Comapi initialised with session profile id : " + session.getProfileId() : "Comapi initialisation with no session."))
.doOnError(e -> {
if (log != null) {
log.f("Error initialising ComapiImpl SDK. " + e.getMessage(), new ComapiException("Error initialising ComapiImpl SDK.", e));
}
})
.flatMap(session -> {
if (state.get() == GlobalState.SESSION_ACTIVE && config.isFcmEnabled()) {
return instance.service.updatePushToken()
.doOnNext(sessionComapiResultPair -> log.d("Push token updated"))
.doOnError(throwable -> log.f("Error updating push token", throwable))
.map((Func1<Pair<SessionData, ComapiResult<Void>>, Object>) resultPair -> resultPair.first)
.onErrorReturn(new Func1<Throwable, SessionData>() {
@Override
public SessionData call(Throwable throwable) {
return session;
}
});
}
return Observable.fromCallable(() -> session);
})
.map(result -> instance);
} else if (state.get() >= GlobalState.INITIALISED) {
return Observable.fromCallable(() -> instance);
} else {
return Observable.error(new ComapiException("Initialise in progress. Shouldn't be called twice. Ignoring."));
}
} } | public class class_name {
<E extends BaseClient> Observable<E> initialise(@NonNull final Application application, @NonNull final E instance, @NonNull final CallbackAdapter adapter) {
if (state.compareAndSet(GlobalState.NOT_INITIALISED, GlobalState.INITIALISING)) {
return init(application, adapter)
.concatMap(new Func1<Boolean, Observable<SessionData>>() {
@Override
public Observable<SessionData> call(Boolean state) {
return loadSession(state);
}
})
.doOnNext(session -> log.d(session != null ? "Comapi initialised with session profile id : " + session.getProfileId() : "Comapi initialisation with no session."))
.doOnError(e -> {
if (log != null) {
log.f("Error initialising ComapiImpl SDK. " + e.getMessage(), new ComapiException("Error initialising ComapiImpl SDK.", e)); // depends on control dependency: [if], data = [none]
}
})
.flatMap(session -> {
if (state.get() == GlobalState.SESSION_ACTIVE && config.isFcmEnabled()) {
return instance.service.updatePushToken()
.doOnNext(sessionComapiResultPair -> log.d("Push token updated"))
.doOnError(throwable -> log.f("Error updating push token", throwable))
.map((Func1<Pair<SessionData, ComapiResult<Void>>, Object>) resultPair -> resultPair.first)
.onErrorReturn(new Func1<Throwable, SessionData>() {
@Override
public SessionData call(Throwable throwable) {
return session;
}
});
}
return Observable.fromCallable(() -> session);
})
.map(result -> instance);
} else if (state.get() >= GlobalState.INITIALISED) {
return Observable.fromCallable(() -> instance);
} else {
return Observable.error(new ComapiException("Initialise in progress. Shouldn't be called twice. Ignoring."));
}
} } |
public class class_name {
private void insertAction(final Element subTree, final QName attName, final Action action) {
if (subTree == null || action == null) {
return;
}
final LinkedList<Element> queue = new LinkedList<>();
// Skip the sub-tree root because it has been added already.
NodeList children = subTree.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
queue.offer((Element)children.item(i));
}
}
while (!queue.isEmpty()) {
final Element node = queue.poll();
children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
queue.offer((Element)children.item(i));
}
}
if (SUBJECTSCHEME_SUBJECTDEF.matches(node)) {
final String key = node.getAttribute(ATTRIBUTE_NAME_KEYS);
if (key != null && !key.trim().isEmpty()) {
final FilterKey k = new FilterKey(attName, key);
if (!filterMap.containsKey(k)) {
filterMap.put(k, action);
}
}
}
}
} } | public class class_name {
private void insertAction(final Element subTree, final QName attName, final Action action) {
if (subTree == null || action == null) {
return; // depends on control dependency: [if], data = [none]
}
final LinkedList<Element> queue = new LinkedList<>();
// Skip the sub-tree root because it has been added already.
NodeList children = subTree.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
queue.offer((Element)children.item(i)); // depends on control dependency: [if], data = [none]
}
}
while (!queue.isEmpty()) {
final Element node = queue.poll();
children = node.getChildNodes(); // depends on control dependency: [while], data = [none]
for (int i = 0; i < children.getLength(); i++) {
if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
queue.offer((Element)children.item(i)); // depends on control dependency: [if], data = [none]
}
}
if (SUBJECTSCHEME_SUBJECTDEF.matches(node)) {
final String key = node.getAttribute(ATTRIBUTE_NAME_KEYS);
if (key != null && !key.trim().isEmpty()) {
final FilterKey k = new FilterKey(attName, key);
if (!filterMap.containsKey(k)) {
filterMap.put(k, action); // depends on control dependency: [if], data = [none]
}
}
}
}
} } |
public class class_name {
public void transformPacket(RawPacket pkt) {
boolean encrypt = false;
// Encrypt the packet using Counter Mode encryption
if (policy.getEncType() == SRTPPolicy.AESCM_ENCRYPTION || policy.getEncType() == SRTPPolicy.TWOFISH_ENCRYPTION) {
processPacketAESCM(pkt, sentIndex);
encrypt = true;
}
// Encrypt the packet using F8 Mode encryption
else if (policy.getEncType() == SRTPPolicy.AESF8_ENCRYPTION || policy.getEncType() == SRTPPolicy.TWOFISHF8_ENCRYPTION) {
processPacketAESF8(pkt, sentIndex);
encrypt = true;
}
int index = 0;
if (encrypt) {
index = sentIndex | 0x80000000;
}
// Grow packet storage in one step
pkt.grow(4 + policy.getAuthTagLength());
// Authenticate the packet
// The authenticate method gets the index via parameter and stores
// it in network order in rbStore variable.
if (policy.getAuthType() != SRTPPolicy.NULL_AUTHENTICATION) {
authenticatePacket(pkt, index);
pkt.append(rbStore, 4);
pkt.append(tagStore, policy.getAuthTagLength());
}
sentIndex++;
sentIndex &= ~0x80000000; // clear possible overflow
} } | public class class_name {
public void transformPacket(RawPacket pkt) {
boolean encrypt = false;
// Encrypt the packet using Counter Mode encryption
if (policy.getEncType() == SRTPPolicy.AESCM_ENCRYPTION || policy.getEncType() == SRTPPolicy.TWOFISH_ENCRYPTION) {
processPacketAESCM(pkt, sentIndex);
// depends on control dependency: [if], data = [none]
encrypt = true;
// depends on control dependency: [if], data = [none]
}
// Encrypt the packet using F8 Mode encryption
else if (policy.getEncType() == SRTPPolicy.AESF8_ENCRYPTION || policy.getEncType() == SRTPPolicy.TWOFISHF8_ENCRYPTION) {
processPacketAESF8(pkt, sentIndex);
// depends on control dependency: [if], data = [none]
encrypt = true;
// depends on control dependency: [if], data = [none]
}
int index = 0;
if (encrypt) {
index = sentIndex | 0x80000000;
// depends on control dependency: [if], data = [none]
}
// Grow packet storage in one step
pkt.grow(4 + policy.getAuthTagLength());
// Authenticate the packet
// The authenticate method gets the index via parameter and stores
// it in network order in rbStore variable.
if (policy.getAuthType() != SRTPPolicy.NULL_AUTHENTICATION) {
authenticatePacket(pkt, index);
// depends on control dependency: [if], data = [none]
pkt.append(rbStore, 4);
// depends on control dependency: [if], data = [none]
pkt.append(tagStore, policy.getAuthTagLength());
// depends on control dependency: [if], data = [none]
}
sentIndex++;
sentIndex &= ~0x80000000; // clear possible overflow
} } |
public class class_name {
public static CmsDriverManager newInstance(
CmsConfigurationManager configurationManager,
CmsSecurityManager securityManager,
I_CmsDbContextFactory runtimeInfoFactory,
CmsPublishEngine publishEngine)
throws CmsInitException {
// read the opencms.properties from the configuration
CmsParameterConfiguration config = configurationManager.getConfiguration();
CmsDriverManager driverManager = null;
try {
// create a driver manager instance
driverManager = new CmsDriverManager();
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DRIVER_MANAGER_START_PHASE1_0));
}
if (runtimeInfoFactory == null) {
throw new CmsInitException(
org.opencms.main.Messages.get().container(org.opencms.main.Messages.ERR_CRITICAL_NO_DB_CONTEXT_0));
}
} catch (Exception exc) {
CmsMessageContainer message = Messages.get().container(Messages.LOG_ERR_DRIVER_MANAGER_START_0);
if (LOG.isFatalEnabled()) {
LOG.fatal(message.key(), exc);
}
throw new CmsInitException(message, exc);
}
// store the configuration
driverManager.m_propertyConfiguration = config;
// set the security manager
driverManager.m_securityManager = securityManager;
// set the lock manager
driverManager.m_lockManager = new CmsLockManager(driverManager);
// create and set the sql manager
driverManager.m_sqlManager = new CmsSqlManager(driverManager);
// set the publish engine
driverManager.m_publishEngine = publishEngine;
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DRIVER_MANAGER_START_PHASE2_0));
}
// read the pool names to initialize
List<String> driverPoolNames = config.getList(CmsDriverManager.CONFIGURATION_DB + ".pools");
if (CmsLog.INIT.isInfoEnabled()) {
String names = "";
for (String name : driverPoolNames) {
names += name + " ";
}
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DRIVER_MANAGER_START_POOLS_1, names));
}
// initialize each pool
for (String name : driverPoolNames) {
driverManager.newPoolInstance(config, name);
}
// initialize the runtime info factory with the generated driver manager
runtimeInfoFactory.initialize(driverManager);
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DRIVER_MANAGER_START_PHASE3_0));
}
// store the access objects
CmsDbContext dbc = runtimeInfoFactory.getDbContext();
driverManager.m_vfsDriver = (I_CmsVfsDriver)driverManager.createDriver(
dbc,
configurationManager,
config,
CONFIGURATION_VFS,
".vfs.driver");
dbc.clear();
dbc = runtimeInfoFactory.getDbContext();
driverManager.m_userDriver = (I_CmsUserDriver)driverManager.createDriver(
dbc,
configurationManager,
config,
CONFIGURATION_USER,
".user.driver");
dbc.clear();
dbc = runtimeInfoFactory.getDbContext();
driverManager.m_projectDriver = (I_CmsProjectDriver)driverManager.createDriver(
dbc,
configurationManager,
config,
CONFIGURATION_PROJECT,
".project.driver");
dbc.clear();
dbc = runtimeInfoFactory.getDbContext();
driverManager.m_historyDriver = (I_CmsHistoryDriver)driverManager.createDriver(
dbc,
configurationManager,
config,
CONFIGURATION_HISTORY,
".history.driver");
dbc.clear();
dbc = runtimeInfoFactory.getDbContext();
try {
// we wrap this in a try-catch because otherwise it would fail during the update
// process, since the subscription driver configuration does not exist at that point.
driverManager.m_subscriptionDriver = (I_CmsSubscriptionDriver)driverManager.createDriver(
dbc,
configurationManager,
config,
CONFIGURATION_SUBSCRIPTION,
".subscription.driver");
} catch (IndexOutOfBoundsException npe) {
LOG.warn("Could not instantiate subscription driver!");
LOG.warn(npe.getLocalizedMessage(), npe);
}
dbc.clear();
// register the driver manager for required events
org.opencms.main.OpenCms.addCmsEventListener(
driverManager,
new int[] {
I_CmsEventListener.EVENT_UPDATE_EXPORTS,
I_CmsEventListener.EVENT_CLEAR_CACHES,
I_CmsEventListener.EVENT_CLEAR_PRINCIPAL_CACHES,
I_CmsEventListener.EVENT_USER_MODIFIED,
I_CmsEventListener.EVENT_PUBLISH_PROJECT});
// return the configured driver manager
return driverManager;
} } | public class class_name {
public static CmsDriverManager newInstance(
CmsConfigurationManager configurationManager,
CmsSecurityManager securityManager,
I_CmsDbContextFactory runtimeInfoFactory,
CmsPublishEngine publishEngine)
throws CmsInitException {
// read the opencms.properties from the configuration
CmsParameterConfiguration config = configurationManager.getConfiguration();
CmsDriverManager driverManager = null;
try {
// create a driver manager instance
driverManager = new CmsDriverManager();
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DRIVER_MANAGER_START_PHASE1_0)); // depends on control dependency: [if], data = [none]
}
if (runtimeInfoFactory == null) {
throw new CmsInitException(
org.opencms.main.Messages.get().container(org.opencms.main.Messages.ERR_CRITICAL_NO_DB_CONTEXT_0));
}
} catch (Exception exc) {
CmsMessageContainer message = Messages.get().container(Messages.LOG_ERR_DRIVER_MANAGER_START_0);
if (LOG.isFatalEnabled()) {
LOG.fatal(message.key(), exc); // depends on control dependency: [if], data = [none]
}
throw new CmsInitException(message, exc);
}
// store the configuration
driverManager.m_propertyConfiguration = config;
// set the security manager
driverManager.m_securityManager = securityManager;
// set the lock manager
driverManager.m_lockManager = new CmsLockManager(driverManager);
// create and set the sql manager
driverManager.m_sqlManager = new CmsSqlManager(driverManager);
// set the publish engine
driverManager.m_publishEngine = publishEngine;
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DRIVER_MANAGER_START_PHASE2_0));
}
// read the pool names to initialize
List<String> driverPoolNames = config.getList(CmsDriverManager.CONFIGURATION_DB + ".pools");
if (CmsLog.INIT.isInfoEnabled()) {
String names = "";
for (String name : driverPoolNames) {
names += name + " ";
}
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DRIVER_MANAGER_START_POOLS_1, names));
}
// initialize each pool
for (String name : driverPoolNames) {
driverManager.newPoolInstance(config, name);
}
// initialize the runtime info factory with the generated driver manager
runtimeInfoFactory.initialize(driverManager);
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DRIVER_MANAGER_START_PHASE3_0));
}
// store the access objects
CmsDbContext dbc = runtimeInfoFactory.getDbContext();
driverManager.m_vfsDriver = (I_CmsVfsDriver)driverManager.createDriver(
dbc,
configurationManager,
config,
CONFIGURATION_VFS,
".vfs.driver");
dbc.clear();
dbc = runtimeInfoFactory.getDbContext();
driverManager.m_userDriver = (I_CmsUserDriver)driverManager.createDriver(
dbc,
configurationManager,
config,
CONFIGURATION_USER,
".user.driver");
dbc.clear();
dbc = runtimeInfoFactory.getDbContext();
driverManager.m_projectDriver = (I_CmsProjectDriver)driverManager.createDriver(
dbc,
configurationManager,
config,
CONFIGURATION_PROJECT,
".project.driver");
dbc.clear();
dbc = runtimeInfoFactory.getDbContext();
driverManager.m_historyDriver = (I_CmsHistoryDriver)driverManager.createDriver(
dbc,
configurationManager,
config,
CONFIGURATION_HISTORY,
".history.driver");
dbc.clear();
dbc = runtimeInfoFactory.getDbContext();
try {
// we wrap this in a try-catch because otherwise it would fail during the update
// process, since the subscription driver configuration does not exist at that point.
driverManager.m_subscriptionDriver = (I_CmsSubscriptionDriver)driverManager.createDriver(
dbc,
configurationManager,
config,
CONFIGURATION_SUBSCRIPTION,
".subscription.driver");
} catch (IndexOutOfBoundsException npe) {
LOG.warn("Could not instantiate subscription driver!");
LOG.warn(npe.getLocalizedMessage(), npe);
}
dbc.clear();
// register the driver manager for required events
org.opencms.main.OpenCms.addCmsEventListener(
driverManager,
new int[] {
I_CmsEventListener.EVENT_UPDATE_EXPORTS,
I_CmsEventListener.EVENT_CLEAR_CACHES,
I_CmsEventListener.EVENT_CLEAR_PRINCIPAL_CACHES,
I_CmsEventListener.EVENT_USER_MODIFIED,
I_CmsEventListener.EVENT_PUBLISH_PROJECT});
// return the configured driver manager
return driverManager;
} } |
public class class_name {
private OutputStream initializeSource()
{
try
{
PipedOutputStream pipeOut = new PipedOutputStream();
PipedInputStream pipeIn = new PipedInputStream( pipeOut);
filterInput_ = pipeIn;
return new FilterSourceStream( pipeOut);
}
catch( Exception e)
{
throw new RuntimeException( "Can't initialize source stream", e);
}
} } | public class class_name {
private OutputStream initializeSource()
{
try
{
PipedOutputStream pipeOut = new PipedOutputStream();
PipedInputStream pipeIn = new PipedInputStream( pipeOut);
filterInput_ = pipeIn; // depends on control dependency: [try], data = [none]
return new FilterSourceStream( pipeOut); // depends on control dependency: [try], data = [none]
}
catch( Exception e)
{
throw new RuntimeException( "Can't initialize source stream", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void setSortDirection(final SortDirection _sortdirection)
{
this.sortDirection = _sortdirection;
try {
Context.getThreadContext().setUserAttribute(getCacheKey(UserCacheKey.SORTDIRECTION),
_sortdirection.getValue());
} catch (final EFapsException e) {
// we don't throw an error because this are only Usersettings
AbstractUIHeaderObject.LOG.error("error during the retrieve of UserAttributes", e);
}
} } | public class class_name {
public void setSortDirection(final SortDirection _sortdirection)
{
this.sortDirection = _sortdirection;
try {
Context.getThreadContext().setUserAttribute(getCacheKey(UserCacheKey.SORTDIRECTION),
_sortdirection.getValue()); // depends on control dependency: [try], data = [none]
} catch (final EFapsException e) {
// we don't throw an error because this are only Usersettings
AbstractUIHeaderObject.LOG.error("error during the retrieve of UserAttributes", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public Set<Class<?>> scan() {
for (URL url : ResourceUtil.getResourceIter(this.packagePath)) {
switch (url.getProtocol()) {
case "file":
scanFile(new File(URLUtil.decode(url.getFile(), this.charset.name())), null);
break;
case "jar":
scanJar(URLUtil.getJarFile(url));
break;
}
}
if(CollUtil.isEmpty(this.classes)) {
scanJavaClassPaths();
}
return Collections.unmodifiableSet(this.classes);
} } | public class class_name {
public Set<Class<?>> scan() {
for (URL url : ResourceUtil.getResourceIter(this.packagePath)) {
switch (url.getProtocol()) {
case "file":
scanFile(new File(URLUtil.decode(url.getFile(), this.charset.name())), null);
break;
case "jar":
scanJar(URLUtil.getJarFile(url));
break;
}
}
if(CollUtil.isEmpty(this.classes)) {
scanJavaClassPaths();
// depends on control dependency: [if], data = [none]
}
return Collections.unmodifiableSet(this.classes);
} } |
public class class_name {
private Deferred<byte[]> hbaseGet(final byte[] key, final byte[] family) {
final GetRequest get = new GetRequest(table, key);
get.family(family).qualifier(kind);
class GetCB implements Callback<byte[], ArrayList<KeyValue>> {
public byte[] call(final ArrayList<KeyValue> row) {
if (row == null || row.isEmpty()) {
return null;
}
return row.get(0).value();
}
}
return client.get(get).addCallback(new GetCB());
} } | public class class_name {
private Deferred<byte[]> hbaseGet(final byte[] key, final byte[] family) {
final GetRequest get = new GetRequest(table, key);
get.family(family).qualifier(kind);
class GetCB implements Callback<byte[], ArrayList<KeyValue>> {
public byte[] call(final ArrayList<KeyValue> row) {
if (row == null || row.isEmpty()) {
return null; // depends on control dependency: [if], data = [none]
}
return row.get(0).value();
}
}
return client.get(get).addCallback(new GetCB());
} } |
public class class_name {
public int getWidth(Attribute attr) {
State state;
state = lookup(attr);
if (state == null) {
return 1;
} else {
return state.maxOcc;
}
} } | public class class_name {
public int getWidth(Attribute attr) {
State state;
state = lookup(attr);
if (state == null) {
return 1; // depends on control dependency: [if], data = [none]
} else {
return state.maxOcc; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public EClass getIfcWarpingMomentMeasure() {
if (ifcWarpingMomentMeasureEClass == null) {
ifcWarpingMomentMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(894);
}
return ifcWarpingMomentMeasureEClass;
} } | public class class_name {
@Override
public EClass getIfcWarpingMomentMeasure() {
if (ifcWarpingMomentMeasureEClass == null) {
ifcWarpingMomentMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(894);
// depends on control dependency: [if], data = [none]
}
return ifcWarpingMomentMeasureEClass;
} } |
public class class_name {
private static List<String> getElementsId(List<Element> elementList) {
List<String> result = new ArrayList<String>();
for (Element element : elementList) {
result.add(element.getAttribute("id"));
}
return result;
} } | public class class_name {
private static List<String> getElementsId(List<Element> elementList) {
List<String> result = new ArrayList<String>();
for (Element element : elementList) {
result.add(element.getAttribute("id"));
// depends on control dependency: [for], data = [element]
}
return result;
} } |
public class class_name {
public ToStringBuilder appendToString(final String toString) {
if (toString != null) {
style.appendToString(buffer, toString);
}
return this;
} } | public class class_name {
public ToStringBuilder appendToString(final String toString) {
if (toString != null) {
style.appendToString(buffer, toString); // depends on control dependency: [if], data = [none]
}
return this;
} } |
public class class_name {
public byte getByte(String key, byte defaultValue) {
addToDefaults(key, Byte.toString(defaultValue));
String value = get(key);
if (value == null) {
return defaultValue;
} else {
return Byte.valueOf(value);
}
} } | public class class_name {
public byte getByte(String key, byte defaultValue) {
addToDefaults(key, Byte.toString(defaultValue));
String value = get(key);
if (value == null) {
return defaultValue; // depends on control dependency: [if], data = [none]
} else {
return Byte.valueOf(value); // depends on control dependency: [if], data = [(value]
}
} } |
public class class_name {
public static void closeQuietly(final ResultSet rs, final Statement stmt, final Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
logger.error("Failed to close ResultSet", e);
}
}
if (stmt != null) {
if (stmt instanceof PreparedStatement) {
try {
((PreparedStatement) stmt).clearParameters();
} catch (Exception e) {
logger.error("Failed to clear parameters", e);
}
}
try {
stmt.close();
} catch (Exception e) {
logger.error("Failed to close Statement", e);
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
logger.error("Failed to close Connection", e);
}
}
} } | public class class_name {
public static void closeQuietly(final ResultSet rs, final Statement stmt, final Connection conn) {
if (rs != null) {
try {
rs.close();
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
logger.error("Failed to close ResultSet", e);
}
// depends on control dependency: [catch], data = [none]
}
if (stmt != null) {
if (stmt instanceof PreparedStatement) {
try {
((PreparedStatement) stmt).clearParameters();
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
logger.error("Failed to clear parameters", e);
}
// depends on control dependency: [catch], data = [none]
}
try {
stmt.close();
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
logger.error("Failed to close Statement", e);
}
// depends on control dependency: [catch], data = [none]
}
if (conn != null) {
try {
conn.close();
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
logger.error("Failed to close Connection", e);
}
// depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
private void buildOperationTitle(MarkupDocBuilder markupDocBuilder, String title, String anchor) {
if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
markupDocBuilder.sectionTitleWithAnchorLevel2(title, anchor);
} else {
markupDocBuilder.sectionTitleWithAnchorLevel3(title, anchor);
}
} } | public class class_name {
private void buildOperationTitle(MarkupDocBuilder markupDocBuilder, String title, String anchor) {
if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
markupDocBuilder.sectionTitleWithAnchorLevel2(title, anchor); // depends on control dependency: [if], data = [none]
} else {
markupDocBuilder.sectionTitleWithAnchorLevel3(title, anchor); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public T getSingleValue() {
List<T> values = getSelectedValue();
if (!values.isEmpty()) {
return values.get(0);
}
return null;
} } | public class class_name {
public T getSingleValue() {
List<T> values = getSelectedValue();
if (!values.isEmpty()) {
return values.get(0); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public void marshall(BatchSuspendUserRequest batchSuspendUserRequest, ProtocolMarshaller protocolMarshaller) {
if (batchSuspendUserRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(batchSuspendUserRequest.getAccountId(), ACCOUNTID_BINDING);
protocolMarshaller.marshall(batchSuspendUserRequest.getUserIdList(), USERIDLIST_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(BatchSuspendUserRequest batchSuspendUserRequest, ProtocolMarshaller protocolMarshaller) {
if (batchSuspendUserRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(batchSuspendUserRequest.getAccountId(), ACCOUNTID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(batchSuspendUserRequest.getUserIdList(), USERIDLIST_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 initialize() {
rows = cols = (int)Math.sqrt(matrix.length);
map = new int[levels];
for (int i = 0; i < levels; i++) {
int v = 255 * i / (levels-1);
map[i] = v;
}
div = new int[256];
mod = new int[256];
int rc = (rows*cols+1);
for (int i = 0; i < 256; i++) {
div[i] = (levels-1)*i / 256;
mod[i] = i*rc/256;
}
} } | public class class_name {
protected void initialize() {
rows = cols = (int)Math.sqrt(matrix.length);
map = new int[levels];
for (int i = 0; i < levels; i++) {
int v = 255 * i / (levels-1);
map[i] = v; // depends on control dependency: [for], data = [i]
}
div = new int[256];
mod = new int[256];
int rc = (rows*cols+1);
for (int i = 0; i < 256; i++) {
div[i] = (levels-1)*i / 256; // depends on control dependency: [for], data = [i]
mod[i] = i*rc/256; // depends on control dependency: [for], data = [i]
}
} } |
public class class_name {
public String toJson() {
build();
try {
return JsonSerializer.toString(this);
} catch (IOException e) {
throw new IndexException(e, "Unformateable JSON search: {}", e.getMessage());
}
} } | public class class_name {
public String toJson() {
build();
try {
return JsonSerializer.toString(this); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new IndexException(e, "Unformateable JSON search: {}", e.getMessage());
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void scheduleReconnect() {
logger.debug("{} scheduleReconnect()", logPrefix());
if (!isEventLoopGroupActive()) {
logger.debug("isEventLoopGroupActive() == false");
return;
}
if (!isListenOnChannelInactive()) {
logger.debug("Skip reconnect scheduling, listener disabled");
return;
}
if ((channel == null || !channel.isActive()) && reconnectSchedulerSync.compareAndSet(false, true)) {
attempts++;
final int attempt = attempts;
int timeout = (int) reconnectDelay.createDelay(attempt).toMillis();
logger.debug("{} Reconnect attempt {}, delay {}ms", logPrefix(), attempt, timeout);
this.reconnectScheduleTimeout = timer.newTimeout(it -> {
reconnectScheduleTimeout = null;
if (!isEventLoopGroupActive()) {
logger.warn("Cannot execute scheduled reconnect timer, reconnect workers are terminated");
return;
}
reconnectWorkers.submit(() -> {
ConnectionWatchdog.this.run(attempt);
return null;
});
}, timeout, TimeUnit.MILLISECONDS);
// Set back to null when ConnectionWatchdog#run runs earlier than reconnectScheduleTimeout's assignment.
if (!reconnectSchedulerSync.get()) {
reconnectScheduleTimeout = null;
}
} else {
logger.debug("{} Skipping scheduleReconnect() because I have an active channel", logPrefix());
}
} } | public class class_name {
public void scheduleReconnect() {
logger.debug("{} scheduleReconnect()", logPrefix());
if (!isEventLoopGroupActive()) {
logger.debug("isEventLoopGroupActive() == false"); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
if (!isListenOnChannelInactive()) {
logger.debug("Skip reconnect scheduling, listener disabled"); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
if ((channel == null || !channel.isActive()) && reconnectSchedulerSync.compareAndSet(false, true)) {
attempts++; // depends on control dependency: [if], data = [none]
final int attempt = attempts;
int timeout = (int) reconnectDelay.createDelay(attempt).toMillis();
logger.debug("{} Reconnect attempt {}, delay {}ms", logPrefix(), attempt, timeout); // depends on control dependency: [if], data = [none]
this.reconnectScheduleTimeout = timer.newTimeout(it -> {
reconnectScheduleTimeout = null; // depends on control dependency: [if], data = [none]
if (!isEventLoopGroupActive()) {
logger.warn("Cannot execute scheduled reconnect timer, reconnect workers are terminated"); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
reconnectWorkers.submit(() -> {
ConnectionWatchdog.this.run(attempt); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
});
}, timeout, TimeUnit.MILLISECONDS);
// Set back to null when ConnectionWatchdog#run runs earlier than reconnectScheduleTimeout's assignment.
if (!reconnectSchedulerSync.get()) {
reconnectScheduleTimeout = null;
}
} else {
logger.debug("{} Skipping scheduleReconnect() because I have an active channel", logPrefix());
}
} } |
public class class_name {
@Override
public <V> V until(Function<? super T, V> isTrue) {
Instant end = clock.instant().plus(timeout);
Throwable lastException;
while (true) {
try {
V value = isTrue.apply(input);
if (value != null && (Boolean.class != value.getClass() || Boolean.TRUE.equals(value))) {
return value;
}
// Clear the last exception; if another retry or timeout exception would
// be caused by a false or null value, the last exception is not the
// cause of the timeout.
lastException = null;
} catch (Throwable e) {
lastException = propagateIfNotIgnored(e);
}
// Check the timeout after evaluating the function to ensure conditions
// with a zero timeout can succeed.
if (end.isBefore(clock.instant())) {
String message = messageSupplier != null ?
messageSupplier.get() : null;
String timeoutMessage = String.format(
"Expected condition failed: %s (tried for %d second(s) with %d milliseconds interval)",
message == null ? "waiting for " + isTrue : message,
timeout.getSeconds(), interval.toMillis());
throw timeoutException(timeoutMessage, lastException);
}
try {
sleeper.sleep(interval);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new WebDriverException(e);
}
}
} } | public class class_name {
@Override
public <V> V until(Function<? super T, V> isTrue) {
Instant end = clock.instant().plus(timeout);
Throwable lastException;
while (true) {
try {
V value = isTrue.apply(input);
if (value != null && (Boolean.class != value.getClass() || Boolean.TRUE.equals(value))) {
return value; // depends on control dependency: [if], data = [none]
}
// Clear the last exception; if another retry or timeout exception would
// be caused by a false or null value, the last exception is not the
// cause of the timeout.
lastException = null; // depends on control dependency: [try], data = [none]
} catch (Throwable e) {
lastException = propagateIfNotIgnored(e);
} // depends on control dependency: [catch], data = [none]
// Check the timeout after evaluating the function to ensure conditions
// with a zero timeout can succeed.
if (end.isBefore(clock.instant())) {
String message = messageSupplier != null ?
messageSupplier.get() : null;
String timeoutMessage = String.format(
"Expected condition failed: %s (tried for %d second(s) with %d milliseconds interval)",
message == null ? "waiting for " + isTrue : message,
timeout.getSeconds(), interval.toMillis());
throw timeoutException(timeoutMessage, lastException);
}
try {
sleeper.sleep(interval); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new WebDriverException(e);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
private static boolean compareAnnotatedParameters(List<? extends AnnotatedParameter<?>> p1, List<? extends AnnotatedParameter<?>> p2) {
if (p1.size() != p2.size()) {
return false;
}
for (int i = 0; i < p1.size(); ++i) {
if (!compareAnnotated(p1.get(i), p2.get(i))) {
return false;
}
}
return true;
} } | public class class_name {
private static boolean compareAnnotatedParameters(List<? extends AnnotatedParameter<?>> p1, List<? extends AnnotatedParameter<?>> p2) {
if (p1.size() != p2.size()) {
return false;
}
for (int i = 0; i < p1.size(); ++i) {
if (!compareAnnotated(p1.get(i), p2.get(i))) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
protected void append(String v, int start, int end) {
try {
writer.write(v, start, end - start);
} catch (Exception e) {
throw MwsUtl.wrap(e);
}
} } | public class class_name {
protected void append(String v, int start, int end) {
try {
writer.write(v, start, end - start); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw MwsUtl.wrap(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void decodeEndRule() {
useDaylight = (startDay != 0) && (endDay != 0);
if (useDaylight && dst == 0) {
dst = Grego.MILLIS_PER_DAY;
}
if (endDay != 0) {
if (endMonth < Calendar.JANUARY || endMonth > Calendar.DECEMBER) {
throw new IllegalArgumentException();
}
if (endTime < 0 || endTime > Grego.MILLIS_PER_DAY ||
endTimeMode < WALL_TIME || endTimeMode > UTC_TIME) {
throw new IllegalArgumentException();
}
if (endDayOfWeek == 0) {
endMode = DOM_MODE;
} else {
if (endDayOfWeek > 0) {
endMode = DOW_IN_MONTH_MODE;
} else {
endDayOfWeek = -endDayOfWeek;
if (endDay > 0) {
endMode = DOW_GE_DOM_MODE;
} else {
endDay = -endDay;
endMode = DOW_LE_DOM_MODE;
}
}
if (endDayOfWeek > Calendar.SATURDAY) {
throw new IllegalArgumentException();
}
}
if (endMode == DOW_IN_MONTH_MODE) {
if (endDay < -5 || endDay > 5) {
throw new IllegalArgumentException();
}
} else if (endDay<1 || endDay > staticMonthLength[endMonth]) {
throw new IllegalArgumentException();
}
}
} } | public class class_name {
private void decodeEndRule() {
useDaylight = (startDay != 0) && (endDay != 0);
if (useDaylight && dst == 0) {
dst = Grego.MILLIS_PER_DAY; // depends on control dependency: [if], data = [none]
}
if (endDay != 0) {
if (endMonth < Calendar.JANUARY || endMonth > Calendar.DECEMBER) {
throw new IllegalArgumentException();
}
if (endTime < 0 || endTime > Grego.MILLIS_PER_DAY ||
endTimeMode < WALL_TIME || endTimeMode > UTC_TIME) {
throw new IllegalArgumentException();
}
if (endDayOfWeek == 0) {
endMode = DOM_MODE; // depends on control dependency: [if], data = [none]
} else {
if (endDayOfWeek > 0) {
endMode = DOW_IN_MONTH_MODE; // depends on control dependency: [if], data = [none]
} else {
endDayOfWeek = -endDayOfWeek; // depends on control dependency: [if], data = [none]
if (endDay > 0) {
endMode = DOW_GE_DOM_MODE; // depends on control dependency: [if], data = [none]
} else {
endDay = -endDay; // depends on control dependency: [if], data = [none]
endMode = DOW_LE_DOM_MODE; // depends on control dependency: [if], data = [none]
}
}
if (endDayOfWeek > Calendar.SATURDAY) {
throw new IllegalArgumentException();
}
}
if (endMode == DOW_IN_MONTH_MODE) {
if (endDay < -5 || endDay > 5) {
throw new IllegalArgumentException();
}
} else if (endDay<1 || endDay > staticMonthLength[endMonth]) {
throw new IllegalArgumentException();
}
}
} } |
public class class_name {
private static void setValue(Postcard postcard, Integer typeDef, String key, String value) {
if (TextUtils.isEmpty(key) || TextUtils.isEmpty(value)) {
return;
}
try {
if (null != typeDef) {
if (typeDef == TypeKind.BOOLEAN.ordinal()) {
postcard.withBoolean(key, Boolean.parseBoolean(value));
} else if (typeDef == TypeKind.BYTE.ordinal()) {
postcard.withByte(key, Byte.valueOf(value));
} else if (typeDef == TypeKind.SHORT.ordinal()) {
postcard.withShort(key, Short.valueOf(value));
} else if (typeDef == TypeKind.INT.ordinal()) {
postcard.withInt(key, Integer.valueOf(value));
} else if (typeDef == TypeKind.LONG.ordinal()) {
postcard.withLong(key, Long.valueOf(value));
} else if (typeDef == TypeKind.FLOAT.ordinal()) {
postcard.withFloat(key, Float.valueOf(value));
} else if (typeDef == TypeKind.DOUBLE.ordinal()) {
postcard.withDouble(key, Double.valueOf(value));
} else if (typeDef == TypeKind.STRING.ordinal()) {
postcard.withString(key, value);
} else if (typeDef == TypeKind.PARCELABLE.ordinal()) {
// TODO : How to description parcelable value with string?
} else if (typeDef == TypeKind.OBJECT.ordinal()) {
postcard.withString(key, value);
} else { // Compatible compiler sdk 1.0.3, in that version, the string type = 18
postcard.withString(key, value);
}
} else {
postcard.withString(key, value);
}
} catch (Throwable ex) {
logger.warning(Consts.TAG, "LogisticsCenter setValue failed! " + ex.getMessage());
}
} } | public class class_name {
private static void setValue(Postcard postcard, Integer typeDef, String key, String value) {
if (TextUtils.isEmpty(key) || TextUtils.isEmpty(value)) {
return; // depends on control dependency: [if], data = [none]
}
try {
if (null != typeDef) {
if (typeDef == TypeKind.BOOLEAN.ordinal()) {
postcard.withBoolean(key, Boolean.parseBoolean(value)); // depends on control dependency: [if], data = [none]
} else if (typeDef == TypeKind.BYTE.ordinal()) {
postcard.withByte(key, Byte.valueOf(value)); // depends on control dependency: [if], data = [none]
} else if (typeDef == TypeKind.SHORT.ordinal()) {
postcard.withShort(key, Short.valueOf(value)); // depends on control dependency: [if], data = [none]
} else if (typeDef == TypeKind.INT.ordinal()) {
postcard.withInt(key, Integer.valueOf(value)); // depends on control dependency: [if], data = [none]
} else if (typeDef == TypeKind.LONG.ordinal()) {
postcard.withLong(key, Long.valueOf(value)); // depends on control dependency: [if], data = [none]
} else if (typeDef == TypeKind.FLOAT.ordinal()) {
postcard.withFloat(key, Float.valueOf(value)); // depends on control dependency: [if], data = [none]
} else if (typeDef == TypeKind.DOUBLE.ordinal()) {
postcard.withDouble(key, Double.valueOf(value)); // depends on control dependency: [if], data = [none]
} else if (typeDef == TypeKind.STRING.ordinal()) {
postcard.withString(key, value); // depends on control dependency: [if], data = [none]
} else if (typeDef == TypeKind.PARCELABLE.ordinal()) {
// TODO : How to description parcelable value with string?
} else if (typeDef == TypeKind.OBJECT.ordinal()) {
postcard.withString(key, value); // depends on control dependency: [if], data = [none]
} else { // Compatible compiler sdk 1.0.3, in that version, the string type = 18
postcard.withString(key, value); // depends on control dependency: [if], data = [none]
}
} else {
postcard.withString(key, value); // depends on control dependency: [if], data = [none]
}
} catch (Throwable ex) {
logger.warning(Consts.TAG, "LogisticsCenter setValue failed! " + ex.getMessage());
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public ByteBuf encode(GatewayMessage message) throws MessageCodecException {
ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
try (JsonGenerator generator =
jsonFactory.createGenerator(
(OutputStream) new ByteBufOutputStream(byteBuf), JsonEncoding.UTF8)) {
generator.writeStartObject();
// headers
for (Entry<String, String> header : message.headers().entrySet()) {
String fieldName = header.getKey();
String value = header.getValue();
switch (fieldName) {
case STREAM_ID_FIELD:
case SIGNAL_FIELD:
case INACTIVITY_FIELD:
case RATE_LIMIT_FIELD:
generator.writeNumberField(fieldName, Long.parseLong(value));
break;
default:
generator.writeStringField(fieldName, value);
}
}
// data
Object data = message.data();
if (data != null) {
if (data instanceof ByteBuf) {
ByteBuf dataBin = (ByteBuf) data;
if (dataBin.isReadable()) {
try {
generator.writeFieldName(DATA_FIELD);
generator.writeRaw(":");
generator.flush();
byteBuf.writeBytes(dataBin);
} finally {
if (releaseDataOnEncode) {
ReferenceCountUtil.safestRelease(dataBin);
}
}
}
} else {
generator.writeObjectField(DATA_FIELD, data);
}
}
generator.writeEndObject();
} catch (Throwable ex) {
ReferenceCountUtil.safestRelease(byteBuf);
Optional.ofNullable(message.data()).ifPresent(ReferenceCountUtil::safestRelease);
LOGGER.error("Failed to encode message: {}", message, ex);
throw new MessageCodecException("Failed to encode message", ex);
}
return byteBuf;
} } | public class class_name {
public ByteBuf encode(GatewayMessage message) throws MessageCodecException {
ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
try (JsonGenerator generator =
jsonFactory.createGenerator(
(OutputStream) new ByteBufOutputStream(byteBuf), JsonEncoding.UTF8)) {
generator.writeStartObject();
// headers
for (Entry<String, String> header : message.headers().entrySet()) {
String fieldName = header.getKey();
String value = header.getValue();
switch (fieldName) {
case STREAM_ID_FIELD:
case SIGNAL_FIELD:
case INACTIVITY_FIELD:
case RATE_LIMIT_FIELD:
generator.writeNumberField(fieldName, Long.parseLong(value));
break;
default:
generator.writeStringField(fieldName, value);
}
}
// data
Object data = message.data();
if (data != null) {
if (data instanceof ByteBuf) {
ByteBuf dataBin = (ByteBuf) data;
if (dataBin.isReadable()) {
try {
generator.writeFieldName(DATA_FIELD); // depends on control dependency: [try], data = [none]
generator.writeRaw(":"); // depends on control dependency: [try], data = [none]
generator.flush(); // depends on control dependency: [try], data = [none]
byteBuf.writeBytes(dataBin); // depends on control dependency: [try], data = [none]
} finally {
if (releaseDataOnEncode) {
ReferenceCountUtil.safestRelease(dataBin); // depends on control dependency: [if], data = [none]
}
}
}
} else {
generator.writeObjectField(DATA_FIELD, data); // depends on control dependency: [if], data = [none]
}
}
generator.writeEndObject();
} catch (Throwable ex) {
ReferenceCountUtil.safestRelease(byteBuf);
Optional.ofNullable(message.data()).ifPresent(ReferenceCountUtil::safestRelease);
LOGGER.error("Failed to encode message: {}", message, ex);
throw new MessageCodecException("Failed to encode message", ex);
}
return byteBuf;
} } |
public class class_name {
public static <T> boolean removeIf(Iterable<T> iterable, Predicate<? super T> predicate)
{
if (iterable instanceof MutableCollection)
{
return ((MutableCollection<T>) iterable).removeIf(predicate);
}
if (iterable instanceof ArrayList)
{
return ArrayListIterate.removeIf((ArrayList<T>) iterable, predicate);
}
if (iterable instanceof List)
{
return ListIterate.removeIf((List<T>) iterable, predicate);
}
if (iterable != null)
{
return IterableIterate.removeIf(iterable, predicate);
}
throw new IllegalArgumentException("Cannot perform a remove on null");
} } | public class class_name {
public static <T> boolean removeIf(Iterable<T> iterable, Predicate<? super T> predicate)
{
if (iterable instanceof MutableCollection)
{
return ((MutableCollection<T>) iterable).removeIf(predicate); // depends on control dependency: [if], data = [none]
}
if (iterable instanceof ArrayList)
{
return ArrayListIterate.removeIf((ArrayList<T>) iterable, predicate); // depends on control dependency: [if], data = [none]
}
if (iterable instanceof List)
{
return ListIterate.removeIf((List<T>) iterable, predicate); // depends on control dependency: [if], data = [none]
}
if (iterable != null)
{
return IterableIterate.removeIf(iterable, predicate); // depends on control dependency: [if], data = [(iterable]
}
throw new IllegalArgumentException("Cannot perform a remove on null");
} } |
public class class_name {
@Override
public EtlResult etl(String task, List<String> params) {
EtlResult etlResult = new EtlResult();
MappingConfig config = rdbMapping.get(task);
RdbEtlService rdbEtlService = new RdbEtlService(dataSource, config);
if (config != null) {
return rdbEtlService.importData(params);
} else {
StringBuilder resultMsg = new StringBuilder();
boolean resSucc = true;
for (MappingConfig configTmp : rdbMapping.values()) {
// 取所有的destination为task的配置
if (configTmp.getDestination().equals(task)) {
EtlResult etlRes = rdbEtlService.importData(params);
if (!etlRes.getSucceeded()) {
resSucc = false;
resultMsg.append(etlRes.getErrorMessage()).append("\n");
} else {
resultMsg.append(etlRes.getResultMessage()).append("\n");
}
}
}
if (resultMsg.length() > 0) {
etlResult.setSucceeded(resSucc);
if (resSucc) {
etlResult.setResultMessage(resultMsg.toString());
} else {
etlResult.setErrorMessage(resultMsg.toString());
}
return etlResult;
}
}
etlResult.setSucceeded(false);
etlResult.setErrorMessage("Task not found");
return etlResult;
} } | public class class_name {
@Override
public EtlResult etl(String task, List<String> params) {
EtlResult etlResult = new EtlResult();
MappingConfig config = rdbMapping.get(task);
RdbEtlService rdbEtlService = new RdbEtlService(dataSource, config);
if (config != null) {
return rdbEtlService.importData(params); // depends on control dependency: [if], data = [none]
} else {
StringBuilder resultMsg = new StringBuilder();
boolean resSucc = true;
for (MappingConfig configTmp : rdbMapping.values()) {
// 取所有的destination为task的配置
if (configTmp.getDestination().equals(task)) {
EtlResult etlRes = rdbEtlService.importData(params);
if (!etlRes.getSucceeded()) {
resSucc = false; // depends on control dependency: [if], data = [none]
resultMsg.append(etlRes.getErrorMessage()).append("\n"); // depends on control dependency: [if], data = [none]
} else {
resultMsg.append(etlRes.getResultMessage()).append("\n"); // depends on control dependency: [if], data = [none]
}
}
}
if (resultMsg.length() > 0) {
etlResult.setSucceeded(resSucc); // depends on control dependency: [if], data = [none]
if (resSucc) {
etlResult.setResultMessage(resultMsg.toString()); // depends on control dependency: [if], data = [none]
} else {
etlResult.setErrorMessage(resultMsg.toString()); // depends on control dependency: [if], data = [none]
}
return etlResult; // depends on control dependency: [if], data = [none]
}
}
etlResult.setSucceeded(false);
etlResult.setErrorMessage("Task not found");
return etlResult;
} } |
public class class_name {
private Statement createStatement(Connection con, boolean scrollable, int explicitFetchSizeHint)
throws java.sql.SQLException
{
Statement result;
try
{
// if necessary use JDBC1.0 methods
if (!FORCEJDBC1_0)
{
result =
con.createStatement(
scrollable
? ResultSet.TYPE_SCROLL_INSENSITIVE
: ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
afterJdbc2CapableStatementCreate(result, explicitFetchSizeHint);
}
else
{
result = con.createStatement();
}
}
catch (AbstractMethodError err)
{
// if a JDBC1.0 driver is used, the signature
// createStatement(int, int) is not defined.
// we then call the JDBC1.0 variant createStatement()
log.warn("Used driver seems not JDBC 2.0 compatible, use the JDBC 1.0 mode", err);
result = con.createStatement();
FORCEJDBC1_0 = true;
}
catch (SQLException eSql)
{
// there are JDBC Driver that nominally implement JDBC 2.0, but
// throw DriverNotCapableExceptions. If we catch one of these
// we force usage of JDBC 1.0
if (eSql.getClass().getName()
.equals("interbase.interclient.DriverNotCapableException"))
{
log.warn("JDBC 2.0 problems with this interbase driver, we use the JDBC 1.0 mode");
FORCEJDBC1_0 = true;
result = con.createStatement();
}
else
{
throw eSql;
}
}
try
{
platform.afterStatementCreate(result);
}
catch (PlatformException e)
{
log.error("Platform dependend failure", e);
}
return result;
} } | public class class_name {
private Statement createStatement(Connection con, boolean scrollable, int explicitFetchSizeHint)
throws java.sql.SQLException
{
Statement result;
try
{
// if necessary use JDBC1.0 methods
if (!FORCEJDBC1_0)
{
result =
con.createStatement(
scrollable
? ResultSet.TYPE_SCROLL_INSENSITIVE
: ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
// depends on control dependency: [if], data = [none]
afterJdbc2CapableStatementCreate(result, explicitFetchSizeHint);
// depends on control dependency: [if], data = [none]
}
else
{
result = con.createStatement();
// depends on control dependency: [if], data = [none]
}
}
catch (AbstractMethodError err)
{
// if a JDBC1.0 driver is used, the signature
// createStatement(int, int) is not defined.
// we then call the JDBC1.0 variant createStatement()
log.warn("Used driver seems not JDBC 2.0 compatible, use the JDBC 1.0 mode", err);
result = con.createStatement();
FORCEJDBC1_0 = true;
}
catch (SQLException eSql)
{
// there are JDBC Driver that nominally implement JDBC 2.0, but
// throw DriverNotCapableExceptions. If we catch one of these
// we force usage of JDBC 1.0
if (eSql.getClass().getName()
.equals("interbase.interclient.DriverNotCapableException"))
{
log.warn("JDBC 2.0 problems with this interbase driver, we use the JDBC 1.0 mode");
FORCEJDBC1_0 = true;
result = con.createStatement();
}
else
{
throw eSql;
}
}
try
{
platform.afterStatementCreate(result);
}
catch (PlatformException e)
{
log.error("Platform dependend failure", e);
}
return result;
} } |
public class class_name {
@Override
public void onMessageReceived(MessageReceivedEvent event)
{
//These are provided with every event in JDA
JDA jda = event.getJDA(); //JDA, the core of the api.
long responseNumber = event.getResponseNumber();//The amount of discord events that JDA has received since the last reconnect.
//Event specific information
User author = event.getAuthor(); //The user that sent the message
Message message = event.getMessage(); //The message that was received.
MessageChannel channel = event.getChannel(); //This is the MessageChannel that the message was sent to.
// This could be a TextChannel, PrivateChannel, or Group!
String msg = message.getContentDisplay(); //This returns a human readable version of the Message. Similar to
// what you would see in the client.
boolean bot = author.isBot(); //This boolean is useful to determine if the User that
// sent the Message is a BOT or not!
if (event.isFromType(ChannelType.TEXT)) //If this message was sent to a Guild TextChannel
{
//Because we now know that this message was sent in a Guild, we can do guild specific things
// Note, if you don't check the ChannelType before using these methods, they might return null due
// the message possibly not being from a Guild!
Guild guild = event.getGuild(); //The Guild that this message was sent in. (note, in the API, Guilds are Servers)
TextChannel textChannel = event.getTextChannel(); //The TextChannel that this message was sent to.
Member member = event.getMember(); //This Member that sent the message. Contains Guild specific information about the User!
String name;
if (message.isWebhookMessage())
{
name = author.getName(); //If this is a Webhook message, then there is no Member associated
} // with the User, thus we default to the author for name.
else
{
name = member.getEffectiveName(); //This will either use the Member's nickname if they have one,
} // otherwise it will default to their username. (User#getName())
System.out.printf("(%s)[%s]<%s>: %s\n", guild.getName(), textChannel.getName(), name, msg);
}
else if (event.isFromType(ChannelType.PRIVATE)) //If this message was sent to a PrivateChannel
{
//The message was sent in a PrivateChannel.
//In this example we don't directly use the privateChannel, however, be sure, there are uses for it!
PrivateChannel privateChannel = event.getPrivateChannel();
System.out.printf("[PRIV]<%s>: %s\n", author.getName(), msg);
}
else if (event.isFromType(ChannelType.GROUP)) //If this message was sent to a Group. This is CLIENT only!
{
//The message was sent in a Group. It should be noted that Groups are CLIENT only.
Group group = event.getGroup();
String groupName = group.getName() != null ? group.getName() : ""; //A group name can be null due to it being unnamed.
System.out.printf("[GRP: %s]<%s>: %s\n", groupName, author.getName(), msg);
}
//Now that you have a grasp on the things that you might see in an event, specifically MessageReceivedEvent,
// we will look at sending / responding to messages!
//This will be an extremely simplified example of command processing.
//Remember, in all of these .equals checks it is actually comparing
// message.getContentDisplay().equals, which is comparing a string to a string.
// If you did message.equals() it will fail because you would be comparing a Message to a String!
if (msg.equals("!ping"))
{
//This will send a message, "pong!", by constructing a RestAction and "queueing" the action with the Requester.
// By calling queue(), we send the Request to the Requester which will send it to discord. Using queue() or any
// of its different forms will handle ratelimiting for you automatically!
channel.sendMessage("pong!").queue();
}
else if (msg.equals("!roll"))
{
//In this case, we have an example showing how to use the Success consumer for a RestAction. The Success consumer
// will provide you with the object that results after you execute your RestAction. As a note, not all RestActions
// have object returns and will instead have Void returns. You can still use the success consumer to determine when
// the action has been completed!
Random rand = new Random();
int roll = rand.nextInt(6) + 1; //This results in 1 - 6 (instead of 0 - 5)
channel.sendMessage("Your roll: " + roll).queue(sentMessage -> //This is called a lambda statement. If you don't know
{ // what they are or how they work, try google!
if (roll < 3)
{
channel.sendMessage("The roll for messageId: " + sentMessage.getId() + " wasn't very good... Must be bad luck!\n").queue();
}
});
}
else if (msg.startsWith("!kick")) //Note, I used "startsWith, not equals.
{
//This is an admin command. That means that it requires specific permissions to use it, in this case
// it needs Permission.KICK_MEMBERS. We will have a check before we attempt to kick members to see
// if the logged in account actually has the permission, but considering something could change after our
// check we should also take into account the possibility that we don't have permission anymore, thus Discord
// response with a permission failure!
//We will use the error consumer, the second parameter in queue!
//We only want to deal with message sent in a Guild.
if (message.isFromType(ChannelType.TEXT))
{
//If no users are provided, we can't kick anyone!
if (message.getMentionedUsers().isEmpty())
{
channel.sendMessage("You must mention 1 or more Users to be kicked!").queue();
}
else
{
Guild guild = event.getGuild();
Member selfMember = guild.getSelfMember(); //This is the currently logged in account's Member object.
// Very similar to JDA#getSelfUser()!
//Now, we the the logged in account doesn't have permission to kick members.. well.. we can't kick!
if (!selfMember.hasPermission(Permission.KICK_MEMBERS))
{
channel.sendMessage("Sorry! I don't have permission to kick members in this Guild!").queue();
return; //We jump out of the method instead of using cascading if/else
}
//Loop over all mentioned users, kicking them one at a time. Mwauahahah!
List<User> mentionedUsers = message.getMentionedUsers();
for (User user : mentionedUsers)
{
Member member = guild.getMember(user); //We get the member object for each mentioned user to kick them!
//We need to make sure that we can interact with them. Interacting with a Member means you are higher
// in the Role hierarchy than they are. Remember, NO ONE is above the Guild's Owner. (Guild#getOwner())
if (!selfMember.canInteract(member))
{
// use the MessageAction to construct the content in StringBuilder syntax using append calls
channel.sendMessage("Cannot kick member: ")
.append(member.getEffectiveName())
.append(", they are higher in the hierarchy than I am!")
.queue();
continue; //Continue to the next mentioned user to be kicked.
}
//Remember, due to the fact that we're using queue we will never have to deal with RateLimits.
// JDA will do it all for you so long as you are using queue!
guild.getController().kick(member).queue(
success -> channel.sendMessage("Kicked ").append(member.getEffectiveName()).append("! Cya!").queue(),
error ->
{
//The failure consumer provides a throwable. In this case we want to check for a PermissionException.
if (error instanceof PermissionException)
{
PermissionException pe = (PermissionException) error;
Permission missingPermission = pe.getPermission(); //If you want to know exactly what permission is missing, this is how.
//Note: some PermissionExceptions have no permission provided, only an error message!
channel.sendMessage("PermissionError kicking [")
.append(member.getEffectiveName()).append("]: ")
.append(error.getMessage()).queue();
}
else
{
channel.sendMessage("Unknown error while kicking [")
.append(member.getEffectiveName())
.append("]: <").append(error.getClass().getSimpleName()).append(">: ")
.append(error.getMessage()).queue();
}
});
}
}
}
else
{
channel.sendMessage("This is a Guild-Only command!").queue();
}
}
else if (msg.equals("!block"))
{
//This is an example of how to use the complete() method on RestAction. The complete method acts similarly to how
// JDABuilder's awaitReady() works, it waits until the request has been sent before continuing execution.
//Most developers probably wont need this and can just use queue. If you use complete, JDA will still handle ratelimit
// control, however if shouldQueue is false it won't queue the Request to be sent after the ratelimit retry after time is past. It
// will instead fire a RateLimitException!
//One of the major advantages of complete() is that it returns the object that queue's success consumer would have,
// but it does it in the same execution context as when the request was made. This may be important for most developers,
// but, honestly, queue is most likely what developers will want to use as it is faster.
try
{
//Note the fact that complete returns the Message object!
//The complete() overload queues the Message for execution and will return when the message was sent
//It does handle rate limits automatically
Message sentMessage = channel.sendMessage("I blocked and will return the message!").complete();
//This should only be used if you are expecting to handle rate limits yourself
//The completion will not succeed if a rate limit is breached and throw a RateLimitException
Message sentRatelimitMessage = channel.sendMessage("I expect rate limitation and know how to handle it!").complete(false);
System.out.println("Sent a message using blocking! Luckly I didn't get Ratelimited... MessageId: " + sentMessage.getId());
}
catch (RateLimitedException e)
{
System.out.println("Whoops! Got ratelimited when attempting to use a .complete() on a RestAction! RetryAfter: " + e.getRetryAfter());
}
//Note that RateLimitException is the only checked-exception thrown by .complete()
catch (RuntimeException e)
{
System.out.println("Unfortunately something went wrong when we tried to send the Message and .complete() threw an Exception.");
e.printStackTrace();
}
}
} } | public class class_name {
@Override
public void onMessageReceived(MessageReceivedEvent event)
{
//These are provided with every event in JDA
JDA jda = event.getJDA(); //JDA, the core of the api.
long responseNumber = event.getResponseNumber();//The amount of discord events that JDA has received since the last reconnect.
//Event specific information
User author = event.getAuthor(); //The user that sent the message
Message message = event.getMessage(); //The message that was received.
MessageChannel channel = event.getChannel(); //This is the MessageChannel that the message was sent to.
// This could be a TextChannel, PrivateChannel, or Group!
String msg = message.getContentDisplay(); //This returns a human readable version of the Message. Similar to
// what you would see in the client.
boolean bot = author.isBot(); //This boolean is useful to determine if the User that
// sent the Message is a BOT or not!
if (event.isFromType(ChannelType.TEXT)) //If this message was sent to a Guild TextChannel
{
//Because we now know that this message was sent in a Guild, we can do guild specific things
// Note, if you don't check the ChannelType before using these methods, they might return null due
// the message possibly not being from a Guild!
Guild guild = event.getGuild(); //The Guild that this message was sent in. (note, in the API, Guilds are Servers)
TextChannel textChannel = event.getTextChannel(); //The TextChannel that this message was sent to.
Member member = event.getMember(); //This Member that sent the message. Contains Guild specific information about the User!
String name;
if (message.isWebhookMessage())
{
name = author.getName(); //If this is a Webhook message, then there is no Member associated // depends on control dependency: [if], data = [none]
} // with the User, thus we default to the author for name.
else
{
name = member.getEffectiveName(); //This will either use the Member's nickname if they have one, // depends on control dependency: [if], data = [none]
} // otherwise it will default to their username. (User#getName())
System.out.printf("(%s)[%s]<%s>: %s\n", guild.getName(), textChannel.getName(), name, msg); // depends on control dependency: [if], data = [none]
}
else if (event.isFromType(ChannelType.PRIVATE)) //If this message was sent to a PrivateChannel
{
//The message was sent in a PrivateChannel.
//In this example we don't directly use the privateChannel, however, be sure, there are uses for it!
PrivateChannel privateChannel = event.getPrivateChannel();
System.out.printf("[PRIV]<%s>: %s\n", author.getName(), msg); // depends on control dependency: [if], data = [none]
}
else if (event.isFromType(ChannelType.GROUP)) //If this message was sent to a Group. This is CLIENT only!
{
//The message was sent in a Group. It should be noted that Groups are CLIENT only.
Group group = event.getGroup();
String groupName = group.getName() != null ? group.getName() : ""; //A group name can be null due to it being unnamed.
System.out.printf("[GRP: %s]<%s>: %s\n", groupName, author.getName(), msg);
}
//Now that you have a grasp on the things that you might see in an event, specifically MessageReceivedEvent,
// we will look at sending / responding to messages!
//This will be an extremely simplified example of command processing.
//Remember, in all of these .equals checks it is actually comparing
// message.getContentDisplay().equals, which is comparing a string to a string.
// If you did message.equals() it will fail because you would be comparing a Message to a String!
if (msg.equals("!ping"))
{
//This will send a message, "pong!", by constructing a RestAction and "queueing" the action with the Requester.
// By calling queue(), we send the Request to the Requester which will send it to discord. Using queue() or any
// of its different forms will handle ratelimiting for you automatically!
channel.sendMessage("pong!").queue();
}
else if (msg.equals("!roll"))
{
//In this case, we have an example showing how to use the Success consumer for a RestAction. The Success consumer
// will provide you with the object that results after you execute your RestAction. As a note, not all RestActions
// have object returns and will instead have Void returns. You can still use the success consumer to determine when
// the action has been completed!
Random rand = new Random();
int roll = rand.nextInt(6) + 1; //This results in 1 - 6 (instead of 0 - 5)
channel.sendMessage("Your roll: " + roll).queue(sentMessage -> //This is called a lambda statement. If you don't know
{ // what they are or how they work, try google!
if (roll < 3)
{
channel.sendMessage("The roll for messageId: " + sentMessage.getId() + " wasn't very good... Must be bad luck!\n").queue();
}
});
}
else if (msg.startsWith("!kick")) //Note, I used "startsWith, not equals.
{
//This is an admin command. That means that it requires specific permissions to use it, in this case
// it needs Permission.KICK_MEMBERS. We will have a check before we attempt to kick members to see
// if the logged in account actually has the permission, but considering something could change after our
// check we should also take into account the possibility that we don't have permission anymore, thus Discord
// response with a permission failure!
//We will use the error consumer, the second parameter in queue!
//We only want to deal with message sent in a Guild.
if (message.isFromType(ChannelType.TEXT))
{
//If no users are provided, we can't kick anyone!
if (message.getMentionedUsers().isEmpty())
{
channel.sendMessage("You must mention 1 or more Users to be kicked!").queue();
}
else
{
Guild guild = event.getGuild();
Member selfMember = guild.getSelfMember(); //This is the currently logged in account's Member object.
// Very similar to JDA#getSelfUser()!
//Now, we the the logged in account doesn't have permission to kick members.. well.. we can't kick!
if (!selfMember.hasPermission(Permission.KICK_MEMBERS))
{
channel.sendMessage("Sorry! I don't have permission to kick members in this Guild!").queue();
return; //We jump out of the method instead of using cascading if/else
}
//Loop over all mentioned users, kicking them one at a time. Mwauahahah!
List<User> mentionedUsers = message.getMentionedUsers();
for (User user : mentionedUsers)
{
Member member = guild.getMember(user); //We get the member object for each mentioned user to kick them!
//We need to make sure that we can interact with them. Interacting with a Member means you are higher
// in the Role hierarchy than they are. Remember, NO ONE is above the Guild's Owner. (Guild#getOwner())
if (!selfMember.canInteract(member))
{
// use the MessageAction to construct the content in StringBuilder syntax using append calls
channel.sendMessage("Cannot kick member: ")
.append(member.getEffectiveName())
.append(", they are higher in the hierarchy than I am!")
.queue();
continue; //Continue to the next mentioned user to be kicked.
}
//Remember, due to the fact that we're using queue we will never have to deal with RateLimits.
// JDA will do it all for you so long as you are using queue!
guild.getController().kick(member).queue(
success -> channel.sendMessage("Kicked ").append(member.getEffectiveName()).append("! Cya!").queue(),
error ->
{
//The failure consumer provides a throwable. In this case we want to check for a PermissionException.
if (error instanceof PermissionException)
{
PermissionException pe = (PermissionException) error;
Permission missingPermission = pe.getPermission(); //If you want to know exactly what permission is missing, this is how.
//Note: some PermissionExceptions have no permission provided, only an error message!
channel.sendMessage("PermissionError kicking [")
.append(member.getEffectiveName()).append("]: ")
.append(error.getMessage()).queue();
}
else
{
channel.sendMessage("Unknown error while kicking [")
.append(member.getEffectiveName())
.append("]: <").append(error.getClass().getSimpleName()).append(">: ")
.append(error.getMessage()).queue();
}
});
}
}
}
else
{
channel.sendMessage("This is a Guild-Only command!").queue();
}
}
else if (msg.equals("!block"))
{
//This is an example of how to use the complete() method on RestAction. The complete method acts similarly to how
// JDABuilder's awaitReady() works, it waits until the request has been sent before continuing execution.
//Most developers probably wont need this and can just use queue. If you use complete, JDA will still handle ratelimit
// control, however if shouldQueue is false it won't queue the Request to be sent after the ratelimit retry after time is past. It
// will instead fire a RateLimitException!
//One of the major advantages of complete() is that it returns the object that queue's success consumer would have,
// but it does it in the same execution context as when the request was made. This may be important for most developers,
// but, honestly, queue is most likely what developers will want to use as it is faster.
try
{
//Note the fact that complete returns the Message object!
//The complete() overload queues the Message for execution and will return when the message was sent
//It does handle rate limits automatically
Message sentMessage = channel.sendMessage("I blocked and will return the message!").complete();
//This should only be used if you are expecting to handle rate limits yourself
//The completion will not succeed if a rate limit is breached and throw a RateLimitException
Message sentRatelimitMessage = channel.sendMessage("I expect rate limitation and know how to handle it!").complete(false);
System.out.println("Sent a message using blocking! Luckly I didn't get Ratelimited... MessageId: " + sentMessage.getId());
}
catch (RateLimitedException e)
{
System.out.println("Whoops! Got ratelimited when attempting to use a .complete() on a RestAction! RetryAfter: " + e.getRetryAfter());
}
//Note that RateLimitException is the only checked-exception thrown by .complete()
catch (RuntimeException e)
{
System.out.println("Unfortunately something went wrong when we tried to send the Message and .complete() threw an Exception.");
e.printStackTrace();
}
}
} } |
public class class_name {
@SafeVarargs
public static Method getDeclaredMethod(final Class<?> cls, final String methodName, final Class<?>... parameterTypes) {
Map<String, Map<Class<?>[], Method>> methodNamePool = classDeclaredMethodPool.get(cls);
Map<Class<?>[], Method> methodPool = methodNamePool == null ? null : methodNamePool.get(methodName);
Method method = null;
if (methodPool != null) {
method = methodPool.get(parameterTypes);
}
if (method == null) {
method = internalGetDeclaredMethod(cls, methodName, parameterTypes);
// SHOULD NOT set it true here.
// if (method != null) {
// method.setAccessible(true);
// }
if (method != null) {
if (methodNamePool == null) {
methodNamePool = new ConcurrentHashMap<>();
classDeclaredMethodPool.put(cls, methodNamePool);
}
if (methodPool == null) {
methodPool = new ArrayHashMap<>(ConcurrentHashMap.class);
methodNamePool.put(methodName, methodPool);
}
methodPool.put(parameterTypes.clone(), method);
}
}
return method;
} } | public class class_name {
@SafeVarargs
public static Method getDeclaredMethod(final Class<?> cls, final String methodName, final Class<?>... parameterTypes) {
Map<String, Map<Class<?>[], Method>> methodNamePool = classDeclaredMethodPool.get(cls);
Map<Class<?>[], Method> methodPool = methodNamePool == null ? null : methodNamePool.get(methodName);
Method method = null;
if (methodPool != null) {
method = methodPool.get(parameterTypes);
// depends on control dependency: [if], data = [none]
}
if (method == null) {
method = internalGetDeclaredMethod(cls, methodName, parameterTypes);
// depends on control dependency: [if], data = [none]
// SHOULD NOT set it true here.
// if (method != null) {
// method.setAccessible(true);
// }
if (method != null) {
if (methodNamePool == null) {
methodNamePool = new ConcurrentHashMap<>();
// depends on control dependency: [if], data = [none]
classDeclaredMethodPool.put(cls, methodNamePool);
// depends on control dependency: [if], data = [none]
}
if (methodPool == null) {
methodPool = new ArrayHashMap<>(ConcurrentHashMap.class);
// depends on control dependency: [if], data = [none]
methodNamePool.put(methodName, methodPool);
// depends on control dependency: [if], data = [none]
}
methodPool.put(parameterTypes.clone(), method);
// depends on control dependency: [if], data = [none]
}
}
return method;
} } |
public class class_name {
private void fireMusicEnded() {
playing = false;
for (int i=0;i<listeners.size();i++) {
((MusicListener) listeners.get(i)).musicEnded(this);
}
} } | public class class_name {
private void fireMusicEnded() {
playing = false;
for (int i=0;i<listeners.size();i++) {
((MusicListener) listeners.get(i)).musicEnded(this);
// depends on control dependency: [for], data = [i]
}
} } |
public class class_name {
public void marshall(AdminConfirmSignUpRequest adminConfirmSignUpRequest, ProtocolMarshaller protocolMarshaller) {
if (adminConfirmSignUpRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(adminConfirmSignUpRequest.getUserPoolId(), USERPOOLID_BINDING);
protocolMarshaller.marshall(adminConfirmSignUpRequest.getUsername(), USERNAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(AdminConfirmSignUpRequest adminConfirmSignUpRequest, ProtocolMarshaller protocolMarshaller) {
if (adminConfirmSignUpRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(adminConfirmSignUpRequest.getUserPoolId(), USERPOOLID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(adminConfirmSignUpRequest.getUsername(), USERNAME_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 {
@Deprecated
public UnicodeSet applyPattern(String pattern,
ParsePosition pos,
SymbolTable symbols,
int options) {
// Need to build the pattern in a temporary string because
// _applyPattern calls add() etc., which set pat to empty.
boolean parsePositionWasNull = pos == null;
if (parsePositionWasNull) {
pos = new ParsePosition(0);
}
StringBuilder rebuiltPat = new StringBuilder();
RuleCharacterIterator chars =
new RuleCharacterIterator(pattern, symbols, pos);
applyPattern(chars, symbols, rebuiltPat, options);
if (chars.inVariable()) {
syntaxError(chars, "Extra chars in variable value");
}
pat = rebuiltPat.toString();
if (parsePositionWasNull) {
int i = pos.getIndex();
// Skip over trailing whitespace
if ((options & IGNORE_SPACE) != 0) {
i = PatternProps.skipWhiteSpace(pattern, i);
}
if (i != pattern.length()) {
throw new IllegalArgumentException("Parse of \"" + pattern +
"\" failed at " + i);
}
}
return this;
} } | public class class_name {
@Deprecated
public UnicodeSet applyPattern(String pattern,
ParsePosition pos,
SymbolTable symbols,
int options) {
// Need to build the pattern in a temporary string because
// _applyPattern calls add() etc., which set pat to empty.
boolean parsePositionWasNull = pos == null;
if (parsePositionWasNull) {
pos = new ParsePosition(0); // depends on control dependency: [if], data = [none]
}
StringBuilder rebuiltPat = new StringBuilder();
RuleCharacterIterator chars =
new RuleCharacterIterator(pattern, symbols, pos);
applyPattern(chars, symbols, rebuiltPat, options);
if (chars.inVariable()) {
syntaxError(chars, "Extra chars in variable value"); // depends on control dependency: [if], data = [none]
}
pat = rebuiltPat.toString();
if (parsePositionWasNull) {
int i = pos.getIndex();
// Skip over trailing whitespace
if ((options & IGNORE_SPACE) != 0) {
i = PatternProps.skipWhiteSpace(pattern, i); // depends on control dependency: [if], data = [none]
}
if (i != pattern.length()) {
throw new IllegalArgumentException("Parse of \"" + pattern +
"\" failed at " + i);
}
}
return this;
} } |
public class class_name {
private boolean download( URL target, File file )
{
_log.addDebug( "JarDiffHandler: Doing download" );
boolean ret = true;
boolean delete = false;
// use bufferedstream for better performance
BufferedInputStream in = null;
BufferedOutputStream out = null;
try
{
in = new BufferedInputStream( target.openStream() );
out = new BufferedOutputStream( new FileOutputStream( file ) );
int read = 0;
int totalRead = 0;
byte[] buf = new byte[BUF_SIZE];
while ( ( read = in.read( buf ) ) != -1 )
{
out.write( buf, 0, read );
totalRead += read;
}
_log.addDebug( "total read: " + totalRead );
_log.addDebug( "Wrote URL " + target.toString() + " to file " + file );
}
catch ( IOException ioe )
{
_log.addDebug( "Got exception while downloading resource: " + ioe );
ret = false;
if ( file != null )
{
delete = true;
}
}
finally
{
try
{
in.close();
in = null;
}
catch ( IOException ioe )
{
_log.addDebug( "Got exception while downloading resource: " + ioe );
}
try
{
out.close();
out = null;
}
catch ( IOException ioe )
{
_log.addDebug( "Got exception while downloading resource: " + ioe );
}
if ( delete )
{
file.delete();
}
}
return ret;
} } | public class class_name {
private boolean download( URL target, File file )
{
_log.addDebug( "JarDiffHandler: Doing download" );
boolean ret = true;
boolean delete = false;
// use bufferedstream for better performance
BufferedInputStream in = null;
BufferedOutputStream out = null;
try
{
in = new BufferedInputStream( target.openStream() ); // depends on control dependency: [try], data = [none]
out = new BufferedOutputStream( new FileOutputStream( file ) ); // depends on control dependency: [try], data = [none]
int read = 0;
int totalRead = 0;
byte[] buf = new byte[BUF_SIZE];
while ( ( read = in.read( buf ) ) != -1 )
{
out.write( buf, 0, read ); // depends on control dependency: [while], data = [none]
totalRead += read; // depends on control dependency: [while], data = [none]
}
_log.addDebug( "total read: " + totalRead ); // depends on control dependency: [try], data = [none]
_log.addDebug( "Wrote URL " + target.toString() + " to file " + file ); // depends on control dependency: [try], data = [none]
}
catch ( IOException ioe )
{
_log.addDebug( "Got exception while downloading resource: " + ioe );
ret = false;
if ( file != null )
{
delete = true; // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
finally
{
try
{
in.close(); // depends on control dependency: [try], data = [none]
in = null; // depends on control dependency: [try], data = [none]
}
catch ( IOException ioe )
{
_log.addDebug( "Got exception while downloading resource: " + ioe );
} // depends on control dependency: [catch], data = [none]
try
{
out.close(); // depends on control dependency: [try], data = [none]
out = null; // depends on control dependency: [try], data = [none]
}
catch ( IOException ioe )
{
_log.addDebug( "Got exception while downloading resource: " + ioe );
} // depends on control dependency: [catch], data = [none]
if ( delete )
{
file.delete(); // depends on control dependency: [if], data = [none]
}
}
return ret;
} } |
public class class_name {
public static Stack<String> reversePath(List<String> pathParts) {
Stack<String> pathStack = new Stack<String>();
if (pathParts != null) {
// Needs first extra argument at top of the stack
for (int i = pathParts.size() - 1;i >=0;i--) {
pathStack.push(pathParts.get(i));
}
}
return pathStack;
} } | public class class_name {
public static Stack<String> reversePath(List<String> pathParts) {
Stack<String> pathStack = new Stack<String>();
if (pathParts != null) {
// Needs first extra argument at top of the stack
for (int i = pathParts.size() - 1;i >=0;i--) {
pathStack.push(pathParts.get(i)); // depends on control dependency: [for], data = [i]
}
}
return pathStack;
} } |
public class class_name {
public List<Throwable> getCauses(Throwable t)
{
List<Throwable> causes = new LinkedList<Throwable>();
Throwable next = t;
while (next.getCause() != null)
{
next = next.getCause();
causes.add(next);
}
return causes;
} } | public class class_name {
public List<Throwable> getCauses(Throwable t)
{
List<Throwable> causes = new LinkedList<Throwable>();
Throwable next = t;
while (next.getCause() != null)
{
next = next.getCause(); // depends on control dependency: [while], data = [none]
causes.add(next); // depends on control dependency: [while], data = [none]
}
return causes;
} } |
public class class_name {
private void updateEnumOptions(EntityType entityType, Attribute attr, Attribute updatedAttr) {
if (attr.getDataType() == ENUM) {
if (updatedAttr.getDataType() == ENUM) {
// update check constraint
dropCheckConstraint(entityType, attr);
createCheckConstraint(entityType, updatedAttr);
} else {
// drop check constraint
dropCheckConstraint(entityType, attr);
}
} else {
if (updatedAttr.getDataType() == ENUM) {
createCheckConstraint(entityType, updatedAttr);
}
}
} } | public class class_name {
private void updateEnumOptions(EntityType entityType, Attribute attr, Attribute updatedAttr) {
if (attr.getDataType() == ENUM) {
if (updatedAttr.getDataType() == ENUM) {
// update check constraint
dropCheckConstraint(entityType, attr); // depends on control dependency: [if], data = [none]
createCheckConstraint(entityType, updatedAttr); // depends on control dependency: [if], data = [none]
} else {
// drop check constraint
dropCheckConstraint(entityType, attr); // depends on control dependency: [if], data = [none]
}
} else {
if (updatedAttr.getDataType() == ENUM) {
createCheckConstraint(entityType, updatedAttr); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static Downloader createDefaultDownloader(Context context) {
Downloader downloaderInstance = null;
try {
Class.forName("com.squareup.okhttp.OkHttpClient");
downloaderInstance = new OkHttpDownloader(context);
} catch (ClassNotFoundException ignored) {}
try {
Class.forName("okhttp3.OkHttpClient");
downloaderInstance = new OkHttp3Downloader(context);
} catch (ClassNotFoundException ignored) {}
if (downloaderInstance == null) {
downloaderInstance = new DefaultDownloader(context);
}
Log.d(TAG, "Downloader is " + downloaderInstance);
return downloaderInstance;
} } | public class class_name {
public static Downloader createDefaultDownloader(Context context) {
Downloader downloaderInstance = null;
try {
Class.forName("com.squareup.okhttp.OkHttpClient");
downloaderInstance = new OkHttpDownloader(context);
} catch (ClassNotFoundException ignored) {} // depends on control dependency: [catch], data = [none]
try {
Class.forName("okhttp3.OkHttpClient");
downloaderInstance = new OkHttp3Downloader(context);
} catch (ClassNotFoundException ignored) {} // depends on control dependency: [catch], data = [none]
if (downloaderInstance == null) {
downloaderInstance = new DefaultDownloader(context); // depends on control dependency: [if], data = [none]
}
Log.d(TAG, "Downloader is " + downloaderInstance);
return downloaderInstance;
} } |
public class class_name {
protected String buildQueryFilter(String streamId, String query) {
checkArgument(streamId != null, "streamId parameter cannot be null");
final String trimmedStreamId = streamId.trim();
checkArgument(!trimmedStreamId.isEmpty(), "streamId parameter cannot be empty");
final StringBuilder builder = new StringBuilder().append("streams:").append(trimmedStreamId);
if (query != null) {
final String trimmedQuery = query.trim();
if (!trimmedQuery.isEmpty() && !"*".equals(trimmedQuery)) {
builder.append(" AND (").append(trimmedQuery).append(")");
}
}
return builder.toString();
} } | public class class_name {
protected String buildQueryFilter(String streamId, String query) {
checkArgument(streamId != null, "streamId parameter cannot be null");
final String trimmedStreamId = streamId.trim();
checkArgument(!trimmedStreamId.isEmpty(), "streamId parameter cannot be empty");
final StringBuilder builder = new StringBuilder().append("streams:").append(trimmedStreamId);
if (query != null) {
final String trimmedQuery = query.trim();
if (!trimmedQuery.isEmpty() && !"*".equals(trimmedQuery)) {
builder.append(" AND (").append(trimmedQuery).append(")"); // depends on control dependency: [if], data = [none]
}
}
return builder.toString();
} } |
public class class_name {
public static Type[] getSupperGenericType(Object object) {
if (Proxy.isProxyClass(object.getClass())) {
object = ProxyBuilder.getProxyBuilder(object.hashCode()).getMostOriginalObject();
}
return getSupperGenericType(object.getClass());
} } | public class class_name {
public static Type[] getSupperGenericType(Object object) {
if (Proxy.isProxyClass(object.getClass())) {
object = ProxyBuilder.getProxyBuilder(object.hashCode()).getMostOriginalObject(); // depends on control dependency: [if], data = [none]
}
return getSupperGenericType(object.getClass());
} } |
public class class_name {
@Override
protected void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException {
//strip any path information that may get added by ArchiveAnalyzer, etc.
final File f = dependency.getActualFile();
final String fileName = FilenameUtils.removeExtension(f.getName());
final String ext = FilenameUtils.getExtension(f.getName());
if (!IGNORED_FILES.accept(f) && !"js".equals(ext)) {
//add version evidence
final DependencyVersion version = DependencyVersionUtil.parseVersion(fileName);
final String packageName = DependencyVersionUtil.parsePreVersion(fileName);
if (version != null) {
// If the version number is just a number like 2 or 23, reduce the confidence
// a shade. This should hopefully correct for cases like log4j.jar or
// struts2-core.jar
if (version.getVersionParts() == null || version.getVersionParts().size() < 2) {
dependency.addEvidence(EvidenceType.VERSION, "file", "version", version.toString(), Confidence.MEDIUM);
} else {
dependency.addEvidence(EvidenceType.VERSION, "file", "version", version.toString(), Confidence.HIGHEST);
}
dependency.addEvidence(EvidenceType.VERSION, "file", "name", packageName, Confidence.MEDIUM);
}
dependency.addEvidence(EvidenceType.PRODUCT, "file", "name", packageName, Confidence.HIGH);
dependency.addEvidence(EvidenceType.VENDOR, "file", "name", packageName, Confidence.HIGH);
}
} } | public class class_name {
@Override
protected void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException {
//strip any path information that may get added by ArchiveAnalyzer, etc.
final File f = dependency.getActualFile();
final String fileName = FilenameUtils.removeExtension(f.getName());
final String ext = FilenameUtils.getExtension(f.getName());
if (!IGNORED_FILES.accept(f) && !"js".equals(ext)) {
//add version evidence
final DependencyVersion version = DependencyVersionUtil.parseVersion(fileName);
final String packageName = DependencyVersionUtil.parsePreVersion(fileName);
if (version != null) {
// If the version number is just a number like 2 or 23, reduce the confidence
// a shade. This should hopefully correct for cases like log4j.jar or
// struts2-core.jar
if (version.getVersionParts() == null || version.getVersionParts().size() < 2) {
dependency.addEvidence(EvidenceType.VERSION, "file", "version", version.toString(), Confidence.MEDIUM); // depends on control dependency: [if], data = [none]
} else {
dependency.addEvidence(EvidenceType.VERSION, "file", "version", version.toString(), Confidence.HIGHEST); // depends on control dependency: [if], data = [none]
}
dependency.addEvidence(EvidenceType.VERSION, "file", "name", packageName, Confidence.MEDIUM); // depends on control dependency: [if], data = [none]
}
dependency.addEvidence(EvidenceType.PRODUCT, "file", "name", packageName, Confidence.HIGH);
dependency.addEvidence(EvidenceType.VENDOR, "file", "name", packageName, Confidence.HIGH);
}
} } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.