code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
@Override
public EClass getIfcMaterial() {
if (ifcMaterialEClass == null) {
ifcMaterialEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers()
.get(356);
}
return ifcMaterialEClass;
} } | public class class_name {
@Override
public EClass getIfcMaterial() {
if (ifcMaterialEClass == null) {
ifcMaterialEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers()
.get(356);
// depends on control dependency: [if], data = [none]
}
return ifcMaterialEClass;
} } |
public class class_name {
public static double root(Function func, double x1, double x2, double tol, int maxIter) {
if (tol <= 0.0) {
throw new IllegalArgumentException("Invalid tolerance: " + tol);
}
if (maxIter <= 0) {
throw new IllegalArgumentException("Invalid maximum number of iterations: " + maxIter);
}
double a = x1, b = x2, c = x2, d = 0, e = 0, fa = func.f(a), fb = func.f(b), fc, p, q, r, s, xm;
if ((fa > 0.0 && fb > 0.0) || (fa < 0.0 && fb < 0.0)) {
throw new IllegalArgumentException("Root must be bracketed.");
}
fc = fb;
for (int iter = 1; iter <= maxIter; iter++) {
if ((fb > 0.0 && fc > 0.0) || (fb < 0.0 && fc < 0.0)) {
c = a;
fc = fa;
e = d = b - a;
}
if (abs(fc) < abs(fb)) {
a = b;
b = c;
c = a;
fa = fb;
fb = fc;
fc = fa;
}
tol = 2.0 * EPSILON * abs(b) + 0.5 * tol;
xm = 0.5 * (c - b);
if (iter % 10 == 0) {
logger.info(String.format("Brent: the root after %3d iterations: %.5g, error = %.5g", iter, b, xm));
}
if (abs(xm) <= tol || fb == 0.0) {
logger.info(String.format("Brent: the root after %3d iterations: %.5g, error = %.5g", iter, b, xm));
return b;
}
if (abs(e) >= tol && abs(fa) > abs(fb)) {
s = fb / fa;
if (a == c) {
p = 2.0 * xm * s;
q = 1.0 - s;
} else {
q = fa / fc;
r = fb / fc;
p = s * (2.0 * xm * q * (q - r) - (b - a) * (r - 1.0));
q = (q - 1.0) * (r - 1.0) * (s - 1.0);
}
if (p > 0.0) {
q = -q;
}
p = abs(p);
double min1 = 3.0 * xm * q - abs(tol * q);
double min2 = abs(e * q);
if (2.0 * p < (min1 < min2 ? min1 : min2)) {
e = d;
d = p / q;
} else {
d = xm;
e = d;
}
} else {
d = xm;
e = d;
}
a = b;
fa = fb;
if (abs(d) > tol) {
b += d;
} else {
b += copySign(tol, xm);
}
fb = func.f(b);
}
logger.error("Brent's method exceeded the maximum number of iterations.");
return b;
} } | public class class_name {
public static double root(Function func, double x1, double x2, double tol, int maxIter) {
if (tol <= 0.0) {
throw new IllegalArgumentException("Invalid tolerance: " + tol);
}
if (maxIter <= 0) {
throw new IllegalArgumentException("Invalid maximum number of iterations: " + maxIter);
}
double a = x1, b = x2, c = x2, d = 0, e = 0, fa = func.f(a), fb = func.f(b), fc, p, q, r, s, xm;
if ((fa > 0.0 && fb > 0.0) || (fa < 0.0 && fb < 0.0)) {
throw new IllegalArgumentException("Root must be bracketed.");
}
fc = fb;
for (int iter = 1; iter <= maxIter; iter++) {
if ((fb > 0.0 && fc > 0.0) || (fb < 0.0 && fc < 0.0)) {
c = a; // depends on control dependency: [if], data = [none]
fc = fa; // depends on control dependency: [if], data = [none]
e = d = b - a; // depends on control dependency: [if], data = [none]
}
if (abs(fc) < abs(fb)) {
a = b; // depends on control dependency: [if], data = [none]
b = c; // depends on control dependency: [if], data = [none]
c = a; // depends on control dependency: [if], data = [none]
fa = fb; // depends on control dependency: [if], data = [none]
fb = fc; // depends on control dependency: [if], data = [none]
fc = fa; // depends on control dependency: [if], data = [none]
}
tol = 2.0 * EPSILON * abs(b) + 0.5 * tol; // depends on control dependency: [for], data = [none]
xm = 0.5 * (c - b); // depends on control dependency: [for], data = [none]
if (iter % 10 == 0) {
logger.info(String.format("Brent: the root after %3d iterations: %.5g, error = %.5g", iter, b, xm)); // depends on control dependency: [if], data = [none]
}
if (abs(xm) <= tol || fb == 0.0) {
logger.info(String.format("Brent: the root after %3d iterations: %.5g, error = %.5g", iter, b, xm)); // depends on control dependency: [if], data = [none]
return b; // depends on control dependency: [if], data = [none]
}
if (abs(e) >= tol && abs(fa) > abs(fb)) {
s = fb / fa; // depends on control dependency: [if], data = [none]
if (a == c) {
p = 2.0 * xm * s; // depends on control dependency: [if], data = [none]
q = 1.0 - s; // depends on control dependency: [if], data = [none]
} else {
q = fa / fc; // depends on control dependency: [if], data = [none]
r = fb / fc; // depends on control dependency: [if], data = [none]
p = s * (2.0 * xm * q * (q - r) - (b - a) * (r - 1.0)); // depends on control dependency: [if], data = [none]
q = (q - 1.0) * (r - 1.0) * (s - 1.0); // depends on control dependency: [if], data = [none]
}
if (p > 0.0) {
q = -q; // depends on control dependency: [if], data = [none]
}
p = abs(p); // depends on control dependency: [if], data = [none]
double min1 = 3.0 * xm * q - abs(tol * q);
double min2 = abs(e * q);
if (2.0 * p < (min1 < min2 ? min1 : min2)) {
e = d; // depends on control dependency: [if], data = [none]
d = p / q; // depends on control dependency: [if], data = [none]
} else {
d = xm; // depends on control dependency: [if], data = [none]
e = d; // depends on control dependency: [if], data = [none]
}
} else {
d = xm; // depends on control dependency: [if], data = [none]
e = d; // depends on control dependency: [if], data = [none]
}
a = b; // depends on control dependency: [for], data = [none]
fa = fb; // depends on control dependency: [for], data = [none]
if (abs(d) > tol) {
b += d; // depends on control dependency: [if], data = [none]
} else {
b += copySign(tol, xm); // depends on control dependency: [if], data = [none]
}
fb = func.f(b); // depends on control dependency: [for], data = [none]
}
logger.error("Brent's method exceeded the maximum number of iterations.");
return b;
} } |
public class class_name {
public List<GROUP> getGroups(List<RESOURCE> resources) {
List<RESOURCE> sortedResources = new ArrayList<RESOURCE>(resources);
Collections.sort(sortedResources, new SortingComparator());
Map<Long, Integer> daysMap = computeDaysForResources(sortedResources);
Map<GroupAge, List<RESOURCE>> resourcesByAge = partitionPublishResourcesByAge(sortedResources, daysMap);
List<List<RESOURCE>> youngGroups = partitionYoungResources(resourcesByAge.get(GroupAge.young));
List<List<RESOURCE>> mediumGroups = partitionMediumResources(resourcesByAge.get(GroupAge.medium), daysMap);
List<RESOURCE> oldGroup = resourcesByAge.get(GroupAge.old);
List<GROUP> resultGroups = new ArrayList<GROUP>();
for (List<RESOURCE> groupRes : youngGroups) {
String name = getPublishGroupName(groupRes, GroupAge.young);
resultGroups.add(createGroup(name, groupRes));
}
for (List<RESOURCE> groupRes : mediumGroups) {
String name = getPublishGroupName(groupRes, GroupAge.medium);
resultGroups.add(createGroup(name, groupRes));
}
if (!oldGroup.isEmpty()) {
String oldName = getPublishGroupName(oldGroup, GroupAge.old);
resultGroups.add(createGroup(oldName, oldGroup));
}
return resultGroups;
} } | public class class_name {
public List<GROUP> getGroups(List<RESOURCE> resources) {
List<RESOURCE> sortedResources = new ArrayList<RESOURCE>(resources);
Collections.sort(sortedResources, new SortingComparator());
Map<Long, Integer> daysMap = computeDaysForResources(sortedResources);
Map<GroupAge, List<RESOURCE>> resourcesByAge = partitionPublishResourcesByAge(sortedResources, daysMap);
List<List<RESOURCE>> youngGroups = partitionYoungResources(resourcesByAge.get(GroupAge.young));
List<List<RESOURCE>> mediumGroups = partitionMediumResources(resourcesByAge.get(GroupAge.medium), daysMap);
List<RESOURCE> oldGroup = resourcesByAge.get(GroupAge.old);
List<GROUP> resultGroups = new ArrayList<GROUP>();
for (List<RESOURCE> groupRes : youngGroups) {
String name = getPublishGroupName(groupRes, GroupAge.young);
resultGroups.add(createGroup(name, groupRes)); // depends on control dependency: [for], data = [groupRes]
}
for (List<RESOURCE> groupRes : mediumGroups) {
String name = getPublishGroupName(groupRes, GroupAge.medium);
resultGroups.add(createGroup(name, groupRes)); // depends on control dependency: [for], data = [groupRes]
}
if (!oldGroup.isEmpty()) {
String oldName = getPublishGroupName(oldGroup, GroupAge.old);
resultGroups.add(createGroup(oldName, oldGroup)); // depends on control dependency: [if], data = [none]
}
return resultGroups;
} } |
public class class_name {
public boolean seek(String strSeekSign) throws DBException
{
Record recMain = this.getRecord();
BaseBuffer vector = new VectorBuffer(null);
KeyArea keyMain = recMain.getKeyArea(recMain.getDefaultOrder());
keyMain.setupKeyBuffer(vector, DBConstants.FILE_KEY_AREA);
this.setCurrentTable(this.getNextTable());
boolean bSuccess = super.seek(strSeekSign);
if (!bSuccess)
{ // Not found in the main table, try the other tables
Iterator<BaseTable> iterator = this.getTables();
while (iterator.hasNext())
{
BaseTable table = iterator.next();
if ((table != null) && (table != this.getNextTable()))
{
Record recAlt = table.getRecord();
recAlt.setKeyArea(recMain.getDefaultOrder());
KeyArea keyAlt = recAlt.getKeyArea(recMain.getDefaultOrder());
vector.resetPosition();
keyAlt.reverseKeyBuffer(vector, DBConstants.FILE_KEY_AREA); // Move these keys back to the record
bSuccess = recAlt.seek(strSeekSign);
if (bSuccess)
{
this.syncRecordToBase(recMain, recAlt, false);
this.setCurrentTable(table);
break;
}
}
}
}
vector.free();
return bSuccess;
} } | public class class_name {
public boolean seek(String strSeekSign) throws DBException
{
Record recMain = this.getRecord();
BaseBuffer vector = new VectorBuffer(null);
KeyArea keyMain = recMain.getKeyArea(recMain.getDefaultOrder());
keyMain.setupKeyBuffer(vector, DBConstants.FILE_KEY_AREA);
this.setCurrentTable(this.getNextTable());
boolean bSuccess = super.seek(strSeekSign);
if (!bSuccess)
{ // Not found in the main table, try the other tables
Iterator<BaseTable> iterator = this.getTables();
while (iterator.hasNext())
{
BaseTable table = iterator.next();
if ((table != null) && (table != this.getNextTable()))
{
Record recAlt = table.getRecord();
recAlt.setKeyArea(recMain.getDefaultOrder()); // depends on control dependency: [if], data = [none]
KeyArea keyAlt = recAlt.getKeyArea(recMain.getDefaultOrder());
vector.resetPosition(); // depends on control dependency: [if], data = [none]
keyAlt.reverseKeyBuffer(vector, DBConstants.FILE_KEY_AREA); // Move these keys back to the record // depends on control dependency: [if], data = [none]
bSuccess = recAlt.seek(strSeekSign); // depends on control dependency: [if], data = [none]
if (bSuccess)
{
this.syncRecordToBase(recMain, recAlt, false); // depends on control dependency: [if], data = [none]
this.setCurrentTable(table); // depends on control dependency: [if], data = [none]
break;
}
}
}
}
vector.free();
return bSuccess;
} } |
public class class_name {
void showCursor () {
updateCurrentLine();
if (cursorLine != firstLineShowing) {
int step = cursorLine >= firstLineShowing ? 1 : -1;
while (firstLineShowing > cursorLine || firstLineShowing + linesShowing - 1 < cursorLine) {
firstLineShowing += step;
}
}
} } | public class class_name {
void showCursor () {
updateCurrentLine();
if (cursorLine != firstLineShowing) {
int step = cursorLine >= firstLineShowing ? 1 : -1;
while (firstLineShowing > cursorLine || firstLineShowing + linesShowing - 1 < cursorLine) {
firstLineShowing += step; // depends on control dependency: [while], data = [none]
}
}
} } |
public class class_name {
static SecretKeySpec readSecretKey(DecryptionSetup ds) {
Keyed<?> ksObject = DKV.getGet(ds._keystore_id);
ByteVec ksVec = (ByteVec) (ksObject instanceof Frame ? ((Frame) ksObject).vec(0) : ksObject);
InputStream ksStream = ksVec.openStream(null /*job key*/);
try {
KeyStore keystore = KeyStore.getInstance(ds._keystore_type);
keystore.load(ksStream, ds._password);
if (! keystore.containsAlias(ds._key_alias)) {
throw new IllegalArgumentException("Alias for key not found");
}
java.security.Key key = keystore.getKey(ds._key_alias, ds._password);
return new SecretKeySpec(key.getEncoded(), key.getAlgorithm());
} catch (GeneralSecurityException e) {
throw new RuntimeException("Unable to load key " + ds._key_alias + " from keystore " + ds._keystore_id, e);
} catch (IOException e) {
throw new RuntimeException("Failed to read keystore " + ds._keystore_id, e);
}
} } | public class class_name {
static SecretKeySpec readSecretKey(DecryptionSetup ds) {
Keyed<?> ksObject = DKV.getGet(ds._keystore_id);
ByteVec ksVec = (ByteVec) (ksObject instanceof Frame ? ((Frame) ksObject).vec(0) : ksObject);
InputStream ksStream = ksVec.openStream(null /*job key*/);
try {
KeyStore keystore = KeyStore.getInstance(ds._keystore_type);
keystore.load(ksStream, ds._password); // depends on control dependency: [try], data = [none]
if (! keystore.containsAlias(ds._key_alias)) {
throw new IllegalArgumentException("Alias for key not found");
}
java.security.Key key = keystore.getKey(ds._key_alias, ds._password);
return new SecretKeySpec(key.getEncoded(), key.getAlgorithm()); // depends on control dependency: [try], data = [none]
} catch (GeneralSecurityException e) {
throw new RuntimeException("Unable to load key " + ds._key_alias + " from keystore " + ds._keystore_id, e);
} catch (IOException e) { // depends on control dependency: [catch], data = [none]
throw new RuntimeException("Failed to read keystore " + ds._keystore_id, e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static List<Dependency> getAllDependencies(final Module module) {
final Set<Dependency> dependencies = new HashSet<Dependency>();
final List<String> producedArtifacts = new ArrayList<String>();
for(final Artifact artifact: getAllArtifacts(module)){
producedArtifacts.add(artifact.getGavc());
}
dependencies.addAll(getAllDependencies(module, producedArtifacts));
return new ArrayList<Dependency>(dependencies);
} } | public class class_name {
public static List<Dependency> getAllDependencies(final Module module) {
final Set<Dependency> dependencies = new HashSet<Dependency>();
final List<String> producedArtifacts = new ArrayList<String>();
for(final Artifact artifact: getAllArtifacts(module)){
producedArtifacts.add(artifact.getGavc()); // depends on control dependency: [for], data = [artifact]
}
dependencies.addAll(getAllDependencies(module, producedArtifacts));
return new ArrayList<Dependency>(dependencies);
} } |
public class class_name {
protected void appendCopy(PointableRoaringArray highLowContainer, int startingIndex, int end) {
extendArray(end - startingIndex);
for (int i = startingIndex; i < end; ++i) {
this.keys[this.size] = highLowContainer.getKeyAtIndex(i);
this.values[this.size] = highLowContainer.getContainerAtIndex(i).clone();
this.size++;
}
} } | public class class_name {
protected void appendCopy(PointableRoaringArray highLowContainer, int startingIndex, int end) {
extendArray(end - startingIndex);
for (int i = startingIndex; i < end; ++i) {
this.keys[this.size] = highLowContainer.getKeyAtIndex(i); // depends on control dependency: [for], data = [i]
this.values[this.size] = highLowContainer.getContainerAtIndex(i).clone(); // depends on control dependency: [for], data = [i]
this.size++; // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
public static void main(String[] args) {
String icuApiVer;
if (ICU_VERSION.getMajor() <= 4) {
if (ICU_VERSION.getMinor() % 2 != 0) {
// Development mile stone
int major = ICU_VERSION.getMajor();
int minor = ICU_VERSION.getMinor() + 1;
if (minor >= 10) {
minor -= 10;
major++;
}
icuApiVer = "" + major + "." + minor + "M" + ICU_VERSION.getMilli();
} else {
icuApiVer = ICU_VERSION.getVersionString(2, 2);
}
} else {
if (ICU_VERSION.getMinor() == 0) {
// Development mile stone
icuApiVer = "" + ICU_VERSION.getMajor() + "M" + ICU_VERSION.getMilli();
} else {
icuApiVer = ICU_VERSION.getVersionString(2, 2);
}
}
System.out.println("International Components for Unicode for Java " + icuApiVer);
System.out.println("");
System.out.println("Implementation Version: " + ICU_VERSION.getVersionString(2, 4));
System.out.println("Unicode Data Version: " + UNICODE_VERSION.getVersionString(2, 4));
System.out.println("CLDR Data Version: " + LocaleData.getCLDRVersion().getVersionString(2, 4));
System.out.println("Time Zone Data Version: " + getTZDataVersion());
} } | public class class_name {
public static void main(String[] args) {
String icuApiVer;
if (ICU_VERSION.getMajor() <= 4) {
if (ICU_VERSION.getMinor() % 2 != 0) {
// Development mile stone
int major = ICU_VERSION.getMajor();
int minor = ICU_VERSION.getMinor() + 1;
if (minor >= 10) {
minor -= 10; // depends on control dependency: [if], data = [none]
major++; // depends on control dependency: [if], data = [none]
}
icuApiVer = "" + major + "." + minor + "M" + ICU_VERSION.getMilli(); // depends on control dependency: [if], data = [none]
} else {
icuApiVer = ICU_VERSION.getVersionString(2, 2); // depends on control dependency: [if], data = [none]
}
} else {
if (ICU_VERSION.getMinor() == 0) {
// Development mile stone
icuApiVer = "" + ICU_VERSION.getMajor() + "M" + ICU_VERSION.getMilli(); // depends on control dependency: [if], data = [none]
} else {
icuApiVer = ICU_VERSION.getVersionString(2, 2); // depends on control dependency: [if], data = [none]
}
}
System.out.println("International Components for Unicode for Java " + icuApiVer);
System.out.println("");
System.out.println("Implementation Version: " + ICU_VERSION.getVersionString(2, 4));
System.out.println("Unicode Data Version: " + UNICODE_VERSION.getVersionString(2, 4));
System.out.println("CLDR Data Version: " + LocaleData.getCLDRVersion().getVersionString(2, 4));
System.out.println("Time Zone Data Version: " + getTZDataVersion());
} } |
public class class_name {
public String nextToken()
{
if (m_tokenOffset_ < 0) {
if (m_nextOffset_ < 0) {
throw new NoSuchElementException("No more tokens in String");
}
// pre-calculations of tokens not done
if (m_returnDelimiters_) {
int tokenlimit = 0;
int c = UTF16.charAt(m_source_, m_nextOffset_);
boolean contains = delims == null
? m_delimiters_.contains(c)
: c < delims.length && delims[c];
if (contains) {
if (m_coalesceDelimiters_) {
tokenlimit = getNextNonDelimiter(m_nextOffset_);
} else {
tokenlimit = m_nextOffset_ + UTF16.getCharCount(c);
if (tokenlimit == m_length_) {
tokenlimit = -1;
}
}
}
else {
tokenlimit = getNextDelimiter(m_nextOffset_);
}
String result;
if (tokenlimit < 0) {
result = m_source_.substring(m_nextOffset_);
}
else {
result = m_source_.substring(m_nextOffset_, tokenlimit);
}
m_nextOffset_ = tokenlimit;
return result;
}
else {
int tokenlimit = getNextDelimiter(m_nextOffset_);
String result;
if (tokenlimit < 0) {
result = m_source_.substring(m_nextOffset_);
m_nextOffset_ = tokenlimit;
}
else {
result = m_source_.substring(m_nextOffset_, tokenlimit);
m_nextOffset_ = getNextNonDelimiter(tokenlimit);
}
return result;
}
}
// count was called before and we have all the tokens
if (m_tokenOffset_ >= m_tokenSize_) {
throw new NoSuchElementException("No more tokens in String");
}
String result;
if (m_tokenLimit_[m_tokenOffset_] >= 0) {
result = m_source_.substring(m_tokenStart_[m_tokenOffset_],
m_tokenLimit_[m_tokenOffset_]);
}
else {
result = m_source_.substring(m_tokenStart_[m_tokenOffset_]);
}
m_tokenOffset_ ++;
m_nextOffset_ = -1;
if (m_tokenOffset_ < m_tokenSize_) {
m_nextOffset_ = m_tokenStart_[m_tokenOffset_];
}
return result;
} } | public class class_name {
public String nextToken()
{
if (m_tokenOffset_ < 0) {
if (m_nextOffset_ < 0) {
throw new NoSuchElementException("No more tokens in String");
}
// pre-calculations of tokens not done
if (m_returnDelimiters_) {
int tokenlimit = 0;
int c = UTF16.charAt(m_source_, m_nextOffset_);
boolean contains = delims == null
? m_delimiters_.contains(c)
: c < delims.length && delims[c];
if (contains) {
if (m_coalesceDelimiters_) {
tokenlimit = getNextNonDelimiter(m_nextOffset_); // depends on control dependency: [if], data = [none]
} else {
tokenlimit = m_nextOffset_ + UTF16.getCharCount(c); // depends on control dependency: [if], data = [none]
if (tokenlimit == m_length_) {
tokenlimit = -1; // depends on control dependency: [if], data = [none]
}
}
}
else {
tokenlimit = getNextDelimiter(m_nextOffset_); // depends on control dependency: [if], data = [none]
}
String result;
if (tokenlimit < 0) {
result = m_source_.substring(m_nextOffset_); // depends on control dependency: [if], data = [none]
}
else {
result = m_source_.substring(m_nextOffset_, tokenlimit); // depends on control dependency: [if], data = [none]
}
m_nextOffset_ = tokenlimit; // depends on control dependency: [if], data = [none]
return result; // depends on control dependency: [if], data = [none]
}
else {
int tokenlimit = getNextDelimiter(m_nextOffset_);
String result;
if (tokenlimit < 0) {
result = m_source_.substring(m_nextOffset_); // depends on control dependency: [if], data = [none]
m_nextOffset_ = tokenlimit; // depends on control dependency: [if], data = [none]
}
else {
result = m_source_.substring(m_nextOffset_, tokenlimit); // depends on control dependency: [if], data = [none]
m_nextOffset_ = getNextNonDelimiter(tokenlimit); // depends on control dependency: [if], data = [(tokenlimit]
}
return result; // depends on control dependency: [if], data = [none]
}
}
// count was called before and we have all the tokens
if (m_tokenOffset_ >= m_tokenSize_) {
throw new NoSuchElementException("No more tokens in String");
}
String result;
if (m_tokenLimit_[m_tokenOffset_] >= 0) {
result = m_source_.substring(m_tokenStart_[m_tokenOffset_],
m_tokenLimit_[m_tokenOffset_]); // depends on control dependency: [if], data = [none]
}
else {
result = m_source_.substring(m_tokenStart_[m_tokenOffset_]); // depends on control dependency: [if], data = [none]
}
m_tokenOffset_ ++;
m_nextOffset_ = -1;
if (m_tokenOffset_ < m_tokenSize_) {
m_nextOffset_ = m_tokenStart_[m_tokenOffset_]; // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
@Override
public String getDescription() {
StringBuilder builder = new StringBuilder("class path resource [");
if (clazz != null) {
builder.append(ResourceUtils.classPackageAsResourcePath(clazz));
builder.append('/');
}
builder.append(path);
builder.append(']');
return builder.toString();
} } | public class class_name {
@Override
public String getDescription() {
StringBuilder builder = new StringBuilder("class path resource [");
if (clazz != null) {
builder.append(ResourceUtils.classPackageAsResourcePath(clazz)); // depends on control dependency: [if], data = [(clazz]
builder.append('/'); // depends on control dependency: [if], data = [none]
}
builder.append(path);
builder.append(']');
return builder.toString();
} } |
public class class_name {
public LdapContext getInnermostDelegateLdapContext() {
final LdapContext delegateLdapContext = this.getDelegateLdapContext();
if (delegateLdapContext instanceof DelegatingLdapContext) {
return ((DelegatingLdapContext)delegateLdapContext).getInnermostDelegateLdapContext();
}
return delegateLdapContext;
} } | public class class_name {
public LdapContext getInnermostDelegateLdapContext() {
final LdapContext delegateLdapContext = this.getDelegateLdapContext();
if (delegateLdapContext instanceof DelegatingLdapContext) {
return ((DelegatingLdapContext)delegateLdapContext).getInnermostDelegateLdapContext(); // depends on control dependency: [if], data = [none]
}
return delegateLdapContext;
} } |
public class class_name {
static public double xy(double[] x, double[] y) {
double result = 0.0;
for (int i = 0; i < x.length; i++) {
result += (x[i] * y[i]);
}
return (result);
} } | public class class_name {
static public double xy(double[] x, double[] y) {
double result = 0.0;
for (int i = 0; i < x.length; i++) {
result += (x[i] * y[i]); // depends on control dependency: [for], data = [i]
}
return (result);
} } |
public class class_name {
public void characters(char[] ch, int start, int length) throws RepositoryException
{
// property values
if (propertyInfo.getValues().size() > 0)
{
DecodedValue curPropValue = propertyInfo.getValues().get(propertyInfo.getValues().size() - 1);
if (curPropValue.isComplete())
{
return;
}
if (propertyInfo.getType() == PropertyType.BINARY || curPropValue.isBinary())
{
try
{
curPropValue.getBinaryDecoder().write(ch, start, length);
}
catch (IOException e)
{
throw new RepositoryException(e);
}
}
else
{
curPropValue.getStringBuffer().append(ch, start, length);
}
}
else
{
LOG.debug("Wrong XML content. Element 'sv:value' expected,"
+ " but SAX event 'characters' occured. characters:[" + new String(ch, start, length) + "]");
}
} } | public class class_name {
public void characters(char[] ch, int start, int length) throws RepositoryException
{
// property values
if (propertyInfo.getValues().size() > 0)
{
DecodedValue curPropValue = propertyInfo.getValues().get(propertyInfo.getValues().size() - 1);
if (curPropValue.isComplete())
{
return;
}
if (propertyInfo.getType() == PropertyType.BINARY || curPropValue.isBinary())
{
try
{
curPropValue.getBinaryDecoder().write(ch, start, length); // depends on control dependency: [try], data = [none]
}
catch (IOException e)
{
throw new RepositoryException(e);
} // depends on control dependency: [catch], data = [none]
}
else
{
curPropValue.getStringBuffer().append(ch, start, length);
}
}
else
{
LOG.debug("Wrong XML content. Element 'sv:value' expected,"
+ " but SAX event 'characters' occured. characters:[" + new String(ch, start, length) + "]");
}
} } |
public class class_name {
public static boolean isTrimmed(String str) {
int length;
if (str == null || (length = str.length()) == 0) {
return true;
}
return !Character.isWhitespace(str.charAt(0))
&& !Character.isWhitespace(str.charAt(length - 1));
} } | public class class_name {
public static boolean isTrimmed(String str) {
int length;
if (str == null || (length = str.length()) == 0) {
return true; // depends on control dependency: [if], data = [none]
}
return !Character.isWhitespace(str.charAt(0))
&& !Character.isWhitespace(str.charAt(length - 1));
} } |
public class class_name {
public static String intentToString(Intent intent) {
if (intent == null) {
return "null";
}
StringBuilder b = new StringBuilder(128);
b.append("Intent { ");
intentToShortString(intent, b);
b.append(" }");
return b.toString();
} } | public class class_name {
public static String intentToString(Intent intent) {
if (intent == null) {
return "null"; // depends on control dependency: [if], data = [none]
}
StringBuilder b = new StringBuilder(128);
b.append("Intent { ");
intentToShortString(intent, b);
b.append(" }");
return b.toString();
} } |
public class class_name {
public static String absoluteHrefOf(final String path) {
try {
return fromCurrentServletMapping().path(path).build().toString();
} catch (final IllegalStateException e) {
return path;
}
} } | public class class_name {
public static String absoluteHrefOf(final String path) {
try {
return fromCurrentServletMapping().path(path).build().toString(); // depends on control dependency: [try], data = [none]
} catch (final IllegalStateException e) {
return path;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public LocalDate getAdjustedDate(LocalDate date, DateRollConvention dateRollConvention) {
if(dateRollConvention == DateRollConvention.UNADJUSTED) {
return date;
}
else if(dateRollConvention == DateRollConvention.MODIFIED_FOLLOWING) {
LocalDate adjustedDate = getAdjustedDate(date, DateRollConvention.FOLLOWING);
if (adjustedDate.getMonth() != date.getMonth()){
return getAdjustedDate(date, DateRollConvention.PRECEDING);
} else {
return adjustedDate;
}
}
else if(dateRollConvention == DateRollConvention.MODIFIED_PRECEDING) {
LocalDate adjustedDate = getAdjustedDate(date, DateRollConvention.PRECEDING);
if (adjustedDate.getMonth() != date.getMonth()) {
return getAdjustedDate(date, DateRollConvention.FOLLOWING);
} else {
return adjustedDate;
}
}
else if(dateRollConvention == DateRollConvention.FOLLOWING || dateRollConvention == DateRollConvention.PRECEDING) {
int adjustment = dateRollConvention == DateRollConvention.FOLLOWING ? 1 : -1;
LocalDate adjustedDate = date;
while(!isBusinessday(adjustedDate)) {
adjustedDate = adjustedDate.plusDays(adjustment);
}
return adjustedDate;
}
throw new IllegalArgumentException("Unknown date roll convention.");
} } | public class class_name {
@Override
public LocalDate getAdjustedDate(LocalDate date, DateRollConvention dateRollConvention) {
if(dateRollConvention == DateRollConvention.UNADJUSTED) {
return date; // depends on control dependency: [if], data = [none]
}
else if(dateRollConvention == DateRollConvention.MODIFIED_FOLLOWING) {
LocalDate adjustedDate = getAdjustedDate(date, DateRollConvention.FOLLOWING);
if (adjustedDate.getMonth() != date.getMonth()){
return getAdjustedDate(date, DateRollConvention.PRECEDING); // depends on control dependency: [if], data = [none]
} else {
return adjustedDate; // depends on control dependency: [if], data = [none]
}
}
else if(dateRollConvention == DateRollConvention.MODIFIED_PRECEDING) {
LocalDate adjustedDate = getAdjustedDate(date, DateRollConvention.PRECEDING);
if (adjustedDate.getMonth() != date.getMonth()) {
return getAdjustedDate(date, DateRollConvention.FOLLOWING); // depends on control dependency: [if], data = [none]
} else {
return adjustedDate; // depends on control dependency: [if], data = [none]
}
}
else if(dateRollConvention == DateRollConvention.FOLLOWING || dateRollConvention == DateRollConvention.PRECEDING) {
int adjustment = dateRollConvention == DateRollConvention.FOLLOWING ? 1 : -1;
LocalDate adjustedDate = date;
while(!isBusinessday(adjustedDate)) {
adjustedDate = adjustedDate.plusDays(adjustment); // depends on control dependency: [while], data = [none]
}
return adjustedDate; // depends on control dependency: [if], data = [none]
}
throw new IllegalArgumentException("Unknown date roll convention.");
} } |
public class class_name {
public void applyDefaults() {
if (fillColor == null) {
fillColor = "#ffffff"; // white
}
if (strokeColor == null) {
strokeColor = "#000000"; // black
}
if (strokeOpacity == -1) {
strokeOpacity = 1; // fully opaque by default
}
if (fillOpacity == -1) {
fillOpacity = .5f; // 50% transparent by default
}
if (strokeWidth == -1) {
strokeWidth = 1; // white
}
} } | public class class_name {
public void applyDefaults() {
if (fillColor == null) {
fillColor = "#ffffff"; // white // depends on control dependency: [if], data = [none]
}
if (strokeColor == null) {
strokeColor = "#000000"; // black // depends on control dependency: [if], data = [none]
}
if (strokeOpacity == -1) {
strokeOpacity = 1; // fully opaque by default // depends on control dependency: [if], data = [none]
}
if (fillOpacity == -1) {
fillOpacity = .5f; // 50% transparent by default // depends on control dependency: [if], data = [none]
}
if (strokeWidth == -1) {
strokeWidth = 1; // white // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static void init(final String _appKey,
final Set<UUID> _loginRoles)
{
if (AppAccessHandler.HANDLER == null) {
AppAccessHandler.HANDLER = new AppAccessHandler(_appKey, _loginRoles);
}
} } | public class class_name {
public static void init(final String _appKey,
final Set<UUID> _loginRoles)
{
if (AppAccessHandler.HANDLER == null) {
AppAccessHandler.HANDLER = new AppAccessHandler(_appKey, _loginRoles); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void eInit(XtendTypeDeclaration container, IJvmTypeProvider context) {
setTypeResolutionContext(context);
if (this.sarlConstructor == null) {
this.container = container;
this.sarlConstructor = SarlFactory.eINSTANCE.createSarlConstructor();
this.sarlConstructor.setAnnotationInfo(XtendFactory.eINSTANCE.createXtendMember());
container.getMembers().add(this.sarlConstructor);
}
} } | public class class_name {
public void eInit(XtendTypeDeclaration container, IJvmTypeProvider context) {
setTypeResolutionContext(context);
if (this.sarlConstructor == null) {
this.container = container; // depends on control dependency: [if], data = [none]
this.sarlConstructor = SarlFactory.eINSTANCE.createSarlConstructor(); // depends on control dependency: [if], data = [none]
this.sarlConstructor.setAnnotationInfo(XtendFactory.eINSTANCE.createXtendMember()); // depends on control dependency: [if], data = [none]
container.getMembers().add(this.sarlConstructor); // depends on control dependency: [if], data = [(this.sarlConstructor]
}
} } |
public class class_name {
public static <E> ErrorMessageFactory shouldBeLenientEqualByAccepting(Object actual, List<String> rejectedFields,
List<Object> expectedValues, List<String> acceptedFields) {
if (rejectedFields.size() == 1) {
return new ShouldBeLenientEqualByAccepting(actual, rejectedFields.get(0), expectedValues.get(0), acceptedFields);
} else {
return new ShouldBeLenientEqualByAccepting(actual, rejectedFields, expectedValues, acceptedFields);
}
} } | public class class_name {
public static <E> ErrorMessageFactory shouldBeLenientEqualByAccepting(Object actual, List<String> rejectedFields,
List<Object> expectedValues, List<String> acceptedFields) {
if (rejectedFields.size() == 1) {
return new ShouldBeLenientEqualByAccepting(actual, rejectedFields.get(0), expectedValues.get(0), acceptedFields); // depends on control dependency: [if], data = [none]
} else {
return new ShouldBeLenientEqualByAccepting(actual, rejectedFields, expectedValues, acceptedFields); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void dispatchMessage(final SipProvider sipProvider, SipServletMessageImpl sipServletMessage) throws DispatcherException {
// final SipNetworkInterfaceManager sipNetworkInterfaceManager = sipApplicationDispatcher.getSipNetworkInterfaceManager();
final SipServletRequestImpl sipServletRequest = (SipServletRequestImpl) sipServletMessage;
if(logger.isInfoEnabled()) {
logger.info("Routing of Cancel Request " + sipServletRequest);
}
/*
* WARNING: routing of CANCEL is special because CANCEL does not contain Route headers as other requests related
* to the dialog. But still it has to be routed through the app path
* of the INVITE
*/
/* If there is a proxy with the request, let's try to send it directly there.
* This is needed because of CANCEL which is a subsequent request that might
* not have Routes. For example if the callee has'n responded the caller still
* doesn't know the route-record and just sends cancel to the outbound proxy.
*/
// boolean proxyCancel = false;
ServerTransaction cancelTransaction =
(ServerTransaction) sipServletRequest.getTransaction();
if(cancelTransaction != null && !TransactionState.TERMINATED.equals(cancelTransaction.getState())) {
if(logger.isDebugEnabled()) {
logger.debug("Sending 200 to Cancel " + sipServletRequest);
}
try {
// First we need to send OK ASAP because of retransmissions both for
//proxy or app
SipServletResponseImpl cancelResponse = (SipServletResponseImpl)
sipServletRequest.createResponse(200, "Canceling");
Response cancelJsipResponse = (Response) cancelResponse.getMessage();
cancelTransaction.sendResponse(cancelJsipResponse);
sipApplicationDispatcher.updateResponseStatistics(cancelJsipResponse, false);
} catch (SipException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Impossible to send the ok to the CANCEL", e);
} catch (InvalidArgumentException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Impossible to send the ok to the CANCEL", e);
}
if(logger.isDebugEnabled()) {
logger.debug("checking what to do with the CANCEL " + sipServletRequest);
}
DispatchTask dispatchTask = new CancelDispatchTask(sipServletRequest, sipProvider);
// Execute CANCEL without waiting for previous requests because if we wait for an INVITE to complete
// all responses will be already sent by the time the CANCEL is out of the queue.
this.sipApplicationDispatcher.getAsynchronousExecutor().execute(dispatchTask);
} else {
if(logger.isDebugEnabled()) {
logger.debug("Retransmission received for CANCEL " + sipServletRequest + ", transaction " + cancelTransaction);
if(cancelTransaction != null) {
logger.debug("Cancel Transaction state " + cancelTransaction.getState());
}
}
}
} } | public class class_name {
public void dispatchMessage(final SipProvider sipProvider, SipServletMessageImpl sipServletMessage) throws DispatcherException {
// final SipNetworkInterfaceManager sipNetworkInterfaceManager = sipApplicationDispatcher.getSipNetworkInterfaceManager();
final SipServletRequestImpl sipServletRequest = (SipServletRequestImpl) sipServletMessage;
if(logger.isInfoEnabled()) {
logger.info("Routing of Cancel Request " + sipServletRequest);
}
/*
* WARNING: routing of CANCEL is special because CANCEL does not contain Route headers as other requests related
* to the dialog. But still it has to be routed through the app path
* of the INVITE
*/
/* If there is a proxy with the request, let's try to send it directly there.
* This is needed because of CANCEL which is a subsequent request that might
* not have Routes. For example if the callee has'n responded the caller still
* doesn't know the route-record and just sends cancel to the outbound proxy.
*/
// boolean proxyCancel = false;
ServerTransaction cancelTransaction =
(ServerTransaction) sipServletRequest.getTransaction();
if(cancelTransaction != null && !TransactionState.TERMINATED.equals(cancelTransaction.getState())) {
if(logger.isDebugEnabled()) {
logger.debug("Sending 200 to Cancel " + sipServletRequest); // depends on control dependency: [if], data = [none]
}
try {
// First we need to send OK ASAP because of retransmissions both for
//proxy or app
SipServletResponseImpl cancelResponse = (SipServletResponseImpl)
sipServletRequest.createResponse(200, "Canceling");
Response cancelJsipResponse = (Response) cancelResponse.getMessage();
cancelTransaction.sendResponse(cancelJsipResponse); // depends on control dependency: [try], data = [none]
sipApplicationDispatcher.updateResponseStatistics(cancelJsipResponse, false); // depends on control dependency: [try], data = [none]
} catch (SipException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Impossible to send the ok to the CANCEL", e);
} catch (InvalidArgumentException e) { // depends on control dependency: [catch], data = [none]
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Impossible to send the ok to the CANCEL", e);
} // depends on control dependency: [catch], data = [none]
if(logger.isDebugEnabled()) {
logger.debug("checking what to do with the CANCEL " + sipServletRequest); // depends on control dependency: [if], data = [none]
}
DispatchTask dispatchTask = new CancelDispatchTask(sipServletRequest, sipProvider);
// Execute CANCEL without waiting for previous requests because if we wait for an INVITE to complete
// all responses will be already sent by the time the CANCEL is out of the queue.
this.sipApplicationDispatcher.getAsynchronousExecutor().execute(dispatchTask);
} else {
if(logger.isDebugEnabled()) {
logger.debug("Retransmission received for CANCEL " + sipServletRequest + ", transaction " + cancelTransaction); // depends on control dependency: [if], data = [none]
if(cancelTransaction != null) {
logger.debug("Cancel Transaction state " + cancelTransaction.getState()); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
private static Properties loadProperties()
{
Properties properties = new Properties();
boolean loaded = false;
String sysProperty = SecurityActions.getSystemProperty("ironjacamar.options");
if (sysProperty != null && !sysProperty.equals(""))
{
File file = new File(sysProperty);
if (file.exists())
{
FileInputStream fis = null;
try
{
fis = new FileInputStream(file);
properties.load(fis);
loaded = true;
}
catch (Throwable t)
{
// Ignore
}
finally
{
if (fis != null)
{
try
{
fis.close();
}
catch (IOException ioe)
{
//No op
}
}
}
}
}
if (!loaded)
{
File file = new File(IRONJACAMAR_PROPERTIES);
if (file.exists())
{
FileInputStream fis = null;
try
{
fis = new FileInputStream(file);
properties.load(fis);
loaded = true;
}
catch (Throwable t)
{
// Ignore
}
finally
{
if (fis != null)
{
try
{
fis.close();
}
catch (IOException ioe)
{
//No op
}
}
}
}
}
if (!loaded)
{
InputStream is = null;
try
{
ClassLoader cl = Main.class.getClassLoader();
is = cl.getResourceAsStream(IRONJACAMAR_PROPERTIES);
properties.load(is);
loaded = true;
}
catch (Throwable t)
{
// Ignore
}
finally
{
if (is != null)
{
try
{
is.close();
}
catch (IOException ioe)
{
// Nothing to do
}
}
}
}
return properties;
} } | public class class_name {
private static Properties loadProperties()
{
Properties properties = new Properties();
boolean loaded = false;
String sysProperty = SecurityActions.getSystemProperty("ironjacamar.options");
if (sysProperty != null && !sysProperty.equals(""))
{
File file = new File(sysProperty);
if (file.exists())
{
FileInputStream fis = null;
try
{
fis = new FileInputStream(file); // depends on control dependency: [try], data = [none]
properties.load(fis); // depends on control dependency: [try], data = [none]
loaded = true; // depends on control dependency: [try], data = [none]
}
catch (Throwable t)
{
// Ignore
} // depends on control dependency: [catch], data = [none]
finally
{
if (fis != null)
{
try
{
fis.close(); // depends on control dependency: [try], data = [none]
}
catch (IOException ioe)
{
//No op
} // depends on control dependency: [catch], data = [none]
}
}
}
}
if (!loaded)
{
File file = new File(IRONJACAMAR_PROPERTIES);
if (file.exists())
{
FileInputStream fis = null;
try
{
fis = new FileInputStream(file); // depends on control dependency: [try], data = [none]
properties.load(fis); // depends on control dependency: [try], data = [none]
loaded = true; // depends on control dependency: [try], data = [none]
}
catch (Throwable t)
{
// Ignore
} // depends on control dependency: [catch], data = [none]
finally
{
if (fis != null)
{
try
{
fis.close(); // depends on control dependency: [try], data = [none]
}
catch (IOException ioe)
{
//No op
} // depends on control dependency: [catch], data = [none]
}
}
}
}
if (!loaded)
{
InputStream is = null;
try
{
ClassLoader cl = Main.class.getClassLoader();
is = cl.getResourceAsStream(IRONJACAMAR_PROPERTIES); // depends on control dependency: [try], data = [none]
properties.load(is); // depends on control dependency: [try], data = [none]
loaded = true; // depends on control dependency: [try], data = [none]
}
catch (Throwable t)
{
// Ignore
} // depends on control dependency: [catch], data = [none]
finally
{
if (is != null)
{
try
{
is.close(); // depends on control dependency: [try], data = [none]
}
catch (IOException ioe)
{
// Nothing to do
} // depends on control dependency: [catch], data = [none]
}
}
}
return properties;
} } |
public class class_name {
public synchronized TrackedTorrent announce(TrackedTorrent torrent) {
TrackedTorrent existing = myTorrentsRepository.getTorrent(torrent.getHexInfoHash());
if (existing != null) {
logger.warn("Tracker already announced torrent with hash {}.", existing.getHexInfoHash());
return existing;
}
myTorrentsRepository.putIfAbsent(torrent.getHexInfoHash(), torrent);
logger.info("Registered new torrent with hash {}.", torrent.getHexInfoHash());
return torrent;
} } | public class class_name {
public synchronized TrackedTorrent announce(TrackedTorrent torrent) {
TrackedTorrent existing = myTorrentsRepository.getTorrent(torrent.getHexInfoHash());
if (existing != null) {
logger.warn("Tracker already announced torrent with hash {}.", existing.getHexInfoHash()); // depends on control dependency: [if], data = [none]
return existing; // depends on control dependency: [if], data = [none]
}
myTorrentsRepository.putIfAbsent(torrent.getHexInfoHash(), torrent);
logger.info("Registered new torrent with hash {}.", torrent.getHexInfoHash());
return torrent;
} } |
public class class_name {
protected <T> T query(StatementHandler stmtHandler, String sql, OutputHandler<T> outputHandler, QueryParameters params)
throws SQLException {
Connection conn = this.transactionHandler.getConnection();
if (sql == null) {
this.transactionHandler.rollback();
this.transactionHandler.closeConnection();
throw new SQLException("Null SQL statement");
}
if (outputHandler == null) {
this.transactionHandler.rollback();
this.transactionHandler.closeConnection();
throw new SQLException("Null OutputHandler");
}
if (((stmtHandler instanceof LazyStatementHandler) == false) && outputHandler instanceof LazyOutputHandler) {
throw new MjdbcRuntimeException("In order to use Lazy output handler - Lazy statement handler should be used...");
}
if (isTransactionManualMode() == false && stmtHandler instanceof LazyStatementHandler && outputHandler instanceof LazyOutputHandler) {
throw new MjdbcRuntimeException("In order to use Lazy statement handler along with Lazy output handler - " +
"this query runner service should be in manual transaction mode. Please look at setTransactionManualMode");
}
Statement stmt = null;
PreparedStatement pstmt = null;
List<QueryParameters> paramsList = null;
T result = null;
QueryParameters processedParams = null;
try {
if (params.size() > 0) {
stmt = this.prepareStatement(conn, outputHandler, sql, false);
} else {
stmt = this.createStatement(conn, outputHandler, sql);
}
// Input/Output is present only for PreparedStatement and CallableStatement
if (stmt instanceof PreparedStatement) {
processedParams = typeHandler.processInput(stmt, params);
stmtHandler.setStatement(stmt, processedParams);
}
if (stmt instanceof PreparedStatement) {
pstmt = (PreparedStatement) stmt;
pstmt.execute();
} else {
stmt.execute(sql);
}
if (stmt instanceof PreparedStatement) {
typeHandler.afterExecute(stmt, processedParams, params);
}
paramsList = stmtHandler.wrap(stmt);
// For LazyOutputHandlers output should not be processed and will be done by cache by itself
if ((outputHandler instanceof LazyOutputHandler) == false) {
paramsList = typeHandler.processOutput(stmt, paramsList);
} else {
// limiting size of cache in case LazyOutputHandler is used
if (this.overrider.hasOverride(MjdbcConstants.OVERRIDE_LAZY_CACHE_MAX_SIZE) == true) {
((QueryParametersLazyList) paramsList).setMaxCacheSize((Integer) this.overrider.getOverride(
MjdbcConstants.OVERRIDE_LAZY_CACHE_MAX_SIZE));
} else {
((QueryParametersLazyList) paramsList).setMaxCacheSize((Integer) MjdbcConfig.getDefaultLazyCacheMaxSize());
}
// changing the type of lazy output cache
if (outputHandler instanceof LazyScrollUpdateOutputHandler) {
((QueryParametersLazyList) paramsList).setType(QueryParametersLazyList.Type.UPDATE_SCROLL);
} else if (outputHandler instanceof LazyScrollOutputHandler) {
((QueryParametersLazyList) paramsList).setType(QueryParametersLazyList.Type.READ_ONLY_SCROLL);
} else if (outputHandler instanceof LazyUpdateOutputHandler) {
((QueryParametersLazyList) paramsList).setType(QueryParametersLazyList.Type.UPDATE_FORWARD);
}
}
result = outputHandler.handle(paramsList);
if (this.isTransactionManualMode() == false) {
this.transactionHandler.commit();
}
} catch (SQLException ex) {
if (this.isTransactionManualMode() == false) {
this.transactionHandler.rollback();
}
rethrow(conn, ex, sql, params);
} catch (MjdbcException ex) {
if (this.isTransactionManualMode() == false) {
this.transactionHandler.rollback();
}
ExceptionUtils.rethrow(ex);
} finally {
stmtHandler.beforeClose();
// Lazy output handler is responsible for closing statement
if ((outputHandler instanceof LazyOutputHandler) == false) {
MjdbcUtils.closeQuietly(stmt);
}
stmtHandler.afterClose();
this.transactionHandler.closeConnection();
}
return result;
} } | public class class_name {
protected <T> T query(StatementHandler stmtHandler, String sql, OutputHandler<T> outputHandler, QueryParameters params)
throws SQLException {
Connection conn = this.transactionHandler.getConnection();
if (sql == null) {
this.transactionHandler.rollback();
this.transactionHandler.closeConnection();
throw new SQLException("Null SQL statement");
}
if (outputHandler == null) {
this.transactionHandler.rollback();
this.transactionHandler.closeConnection();
throw new SQLException("Null OutputHandler");
}
if (((stmtHandler instanceof LazyStatementHandler) == false) && outputHandler instanceof LazyOutputHandler) {
throw new MjdbcRuntimeException("In order to use Lazy output handler - Lazy statement handler should be used...");
}
if (isTransactionManualMode() == false && stmtHandler instanceof LazyStatementHandler && outputHandler instanceof LazyOutputHandler) {
throw new MjdbcRuntimeException("In order to use Lazy statement handler along with Lazy output handler - " +
"this query runner service should be in manual transaction mode. Please look at setTransactionManualMode");
}
Statement stmt = null;
PreparedStatement pstmt = null;
List<QueryParameters> paramsList = null;
T result = null;
QueryParameters processedParams = null;
try {
if (params.size() > 0) {
stmt = this.prepareStatement(conn, outputHandler, sql, false); // depends on control dependency: [if], data = [none]
} else {
stmt = this.createStatement(conn, outputHandler, sql); // depends on control dependency: [if], data = [none]
}
// Input/Output is present only for PreparedStatement and CallableStatement
if (stmt instanceof PreparedStatement) {
processedParams = typeHandler.processInput(stmt, params); // depends on control dependency: [if], data = [none]
stmtHandler.setStatement(stmt, processedParams); // depends on control dependency: [if], data = [none]
}
if (stmt instanceof PreparedStatement) {
pstmt = (PreparedStatement) stmt; // depends on control dependency: [if], data = [none]
pstmt.execute(); // depends on control dependency: [if], data = [none]
} else {
stmt.execute(sql); // depends on control dependency: [if], data = [none]
}
if (stmt instanceof PreparedStatement) {
typeHandler.afterExecute(stmt, processedParams, params); // depends on control dependency: [if], data = [none]
}
paramsList = stmtHandler.wrap(stmt);
// For LazyOutputHandlers output should not be processed and will be done by cache by itself
if ((outputHandler instanceof LazyOutputHandler) == false) {
paramsList = typeHandler.processOutput(stmt, paramsList); // depends on control dependency: [if], data = [none]
} else {
// limiting size of cache in case LazyOutputHandler is used
if (this.overrider.hasOverride(MjdbcConstants.OVERRIDE_LAZY_CACHE_MAX_SIZE) == true) {
((QueryParametersLazyList) paramsList).setMaxCacheSize((Integer) this.overrider.getOverride(
MjdbcConstants.OVERRIDE_LAZY_CACHE_MAX_SIZE)); // depends on control dependency: [if], data = [none]
} else {
((QueryParametersLazyList) paramsList).setMaxCacheSize((Integer) MjdbcConfig.getDefaultLazyCacheMaxSize()); // depends on control dependency: [if], data = [none]
}
// changing the type of lazy output cache
if (outputHandler instanceof LazyScrollUpdateOutputHandler) {
((QueryParametersLazyList) paramsList).setType(QueryParametersLazyList.Type.UPDATE_SCROLL); // depends on control dependency: [if], data = [none]
} else if (outputHandler instanceof LazyScrollOutputHandler) {
((QueryParametersLazyList) paramsList).setType(QueryParametersLazyList.Type.READ_ONLY_SCROLL); // depends on control dependency: [if], data = [none]
} else if (outputHandler instanceof LazyUpdateOutputHandler) {
((QueryParametersLazyList) paramsList).setType(QueryParametersLazyList.Type.UPDATE_FORWARD); // depends on control dependency: [if], data = [none]
}
}
result = outputHandler.handle(paramsList);
if (this.isTransactionManualMode() == false) {
this.transactionHandler.commit(); // depends on control dependency: [if], data = [none]
}
} catch (SQLException ex) {
if (this.isTransactionManualMode() == false) {
this.transactionHandler.rollback(); // depends on control dependency: [if], data = [none]
}
rethrow(conn, ex, sql, params);
} catch (MjdbcException ex) {
if (this.isTransactionManualMode() == false) {
this.transactionHandler.rollback(); // depends on control dependency: [if], data = [none]
}
ExceptionUtils.rethrow(ex);
} finally {
stmtHandler.beforeClose();
// Lazy output handler is responsible for closing statement
if ((outputHandler instanceof LazyOutputHandler) == false) {
MjdbcUtils.closeQuietly(stmt); // depends on control dependency: [if], data = [none]
}
stmtHandler.afterClose();
this.transactionHandler.closeConnection();
}
return result;
} } |
public class class_name {
@Nullable
public IURLProtocol getProtocol (@Nullable final String sURL)
{
if (sURL == null)
return null;
// Is called often - so no Lambdas
m_aRWLock.readLock ().lock ();
try
{
for (final IURLProtocol aProtocol : m_aProtocols.values ())
if (aProtocol.isUsedInURL (sURL))
return aProtocol;
return null;
}
finally
{
m_aRWLock.readLock ().unlock ();
}
} } | public class class_name {
@Nullable
public IURLProtocol getProtocol (@Nullable final String sURL)
{
if (sURL == null)
return null;
// Is called often - so no Lambdas
m_aRWLock.readLock ().lock ();
try
{
for (final IURLProtocol aProtocol : m_aProtocols.values ())
if (aProtocol.isUsedInURL (sURL))
return aProtocol;
return null; // depends on control dependency: [try], data = [none]
}
finally
{
m_aRWLock.readLock ().unlock ();
}
} } |
public class class_name {
public void createResource(final InputStream inputStream, final String resourceName)
throws JaxRxException {
synchronized (resourceName) {
if (inputStream == null) {
throw new JaxRxException(400, "Bad user request");
} else {
try {
shred(inputStream, resourceName);
} catch (final TTException exce) {
throw new JaxRxException(exce);
}
}
}
} } | public class class_name {
public void createResource(final InputStream inputStream, final String resourceName)
throws JaxRxException {
synchronized (resourceName) {
if (inputStream == null) {
throw new JaxRxException(400, "Bad user request");
} else {
try {
shred(inputStream, resourceName); // depends on control dependency: [try], data = [none]
} catch (final TTException exce) {
throw new JaxRxException(exce);
} // depends on control dependency: [catch], data = [none]
}
}
} } |
public class class_name {
private void retry(int attempt, Throwable error, ErrorClassification errorClassification, Context recoveryContext, SettablePromise<T> recoveryResult) {
long backoffTime = _policy.getBackoffPolicy().nextBackoff(attempt, error);
if (errorClassification == ErrorClassification.UNRECOVERABLE) {
// For fatal errors there are no retries.
LOGGER.debug(String.format("Attempt %s of %s interrupted: %s", attempt, _name, error.getMessage()));
recoveryResult.fail(error);
} else if (_policy.getTerminationPolicy().shouldTerminate(attempt, System.currentTimeMillis() - _startedAt + backoffTime)) {
// Retry policy commands that no more retries should be done.
LOGGER.debug(String.format("Too many exceptions after attempt %s of %s, aborting: %s", attempt, _name, error.getMessage()));
recoveryResult.fail(error);
} else {
// Schedule a new retry task after a computed backoff timeout.
LOGGER.debug(String.format("Attempt %s of %s failed and will be retried after %s millis: %s", attempt, _name, backoffTime, error.getMessage()));
Task<T> retryTask = wrap(attempt);
Promises.propagateResult(retryTask, recoveryResult);
recoveryContext.createTimer(backoffTime, TimeUnit.MILLISECONDS, retryTask);
}
} } | public class class_name {
private void retry(int attempt, Throwable error, ErrorClassification errorClassification, Context recoveryContext, SettablePromise<T> recoveryResult) {
long backoffTime = _policy.getBackoffPolicy().nextBackoff(attempt, error);
if (errorClassification == ErrorClassification.UNRECOVERABLE) {
// For fatal errors there are no retries.
LOGGER.debug(String.format("Attempt %s of %s interrupted: %s", attempt, _name, error.getMessage())); // depends on control dependency: [if], data = [none]
recoveryResult.fail(error); // depends on control dependency: [if], data = [none]
} else if (_policy.getTerminationPolicy().shouldTerminate(attempt, System.currentTimeMillis() - _startedAt + backoffTime)) {
// Retry policy commands that no more retries should be done.
LOGGER.debug(String.format("Too many exceptions after attempt %s of %s, aborting: %s", attempt, _name, error.getMessage())); // depends on control dependency: [if], data = [none]
recoveryResult.fail(error); // depends on control dependency: [if], data = [none]
} else {
// Schedule a new retry task after a computed backoff timeout.
LOGGER.debug(String.format("Attempt %s of %s failed and will be retried after %s millis: %s", attempt, _name, backoffTime, error.getMessage())); // depends on control dependency: [if], data = [none]
Task<T> retryTask = wrap(attempt);
Promises.propagateResult(retryTask, recoveryResult); // depends on control dependency: [if], data = [none]
recoveryContext.createTimer(backoffTime, TimeUnit.MILLISECONDS, retryTask); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@PostMapping(value = "/v1/tickets", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<String> createTicketGrantingTicket(@RequestBody(required=false) final MultiValueMap<String, String> requestBody,
final HttpServletRequest request) {
try {
val tgtId = createTicketGrantingTicketForRequest(requestBody, request);
return createResponseEntityForTicket(request, tgtId);
} catch (final AuthenticationException e) {
return RestResourceUtils.createResponseEntityForAuthnFailure(e, request, applicationContext);
} catch (final BadRestRequestException e) {
LOGGER.error(e.getMessage(), e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
} } | public class class_name {
@PostMapping(value = "/v1/tickets", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<String> createTicketGrantingTicket(@RequestBody(required=false) final MultiValueMap<String, String> requestBody,
final HttpServletRequest request) {
try {
val tgtId = createTicketGrantingTicketForRequest(requestBody, request);
return createResponseEntityForTicket(request, tgtId); // depends on control dependency: [try], data = [none]
} catch (final AuthenticationException e) {
return RestResourceUtils.createResponseEntityForAuthnFailure(e, request, applicationContext);
} catch (final BadRestRequestException e) { // depends on control dependency: [catch], data = [none]
LOGGER.error(e.getMessage(), e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
} catch (final Exception e) { // depends on control dependency: [catch], data = [none]
LOGGER.error(e.getMessage(), e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void marshall(DeregisterTargetFromMaintenanceWindowRequest deregisterTargetFromMaintenanceWindowRequest, ProtocolMarshaller protocolMarshaller) {
if (deregisterTargetFromMaintenanceWindowRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deregisterTargetFromMaintenanceWindowRequest.getWindowId(), WINDOWID_BINDING);
protocolMarshaller.marshall(deregisterTargetFromMaintenanceWindowRequest.getWindowTargetId(), WINDOWTARGETID_BINDING);
protocolMarshaller.marshall(deregisterTargetFromMaintenanceWindowRequest.getSafe(), SAFE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DeregisterTargetFromMaintenanceWindowRequest deregisterTargetFromMaintenanceWindowRequest, ProtocolMarshaller protocolMarshaller) {
if (deregisterTargetFromMaintenanceWindowRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deregisterTargetFromMaintenanceWindowRequest.getWindowId(), WINDOWID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(deregisterTargetFromMaintenanceWindowRequest.getWindowTargetId(), WINDOWTARGETID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(deregisterTargetFromMaintenanceWindowRequest.getSafe(), SAFE_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 Object setInList(CachingPojoPath currentPath, PojoPathContext context, PojoPathState state, Object parentPojo, Object value, int index) {
Object arrayOrList = convertList(currentPath, context, state, parentPojo);
GenericBean<Object> arrayReceiver = new GenericBean<>();
Object convertedValue = value;
if (currentPath.parent != null) {
GenericType<?> collectionType = currentPath.parent.pojoType;
if (collectionType != null) {
GenericType<?> valueType = collectionType.getComponentType();
convertedValue = convert(currentPath, context, value, valueType.getAssignmentClass(), valueType);
}
}
Object result = getCollectionReflectionUtil().set(arrayOrList, index, convertedValue, arrayReceiver);
Object newArray = arrayReceiver.getValue();
if (newArray != null) {
if (currentPath.parent.parent == null) {
throw new PojoPathCreationException(state.rootPath.pojo, currentPath.getPojoPath());
}
Object parentParentPojo;
if (currentPath.parent.parent == null) {
parentParentPojo = state.rootPath.pojo;
} else {
parentParentPojo = currentPath.parent.parent.pojo;
}
set(currentPath.parent, context, state, parentParentPojo, newArray);
}
return result;
} } | public class class_name {
protected Object setInList(CachingPojoPath currentPath, PojoPathContext context, PojoPathState state, Object parentPojo, Object value, int index) {
Object arrayOrList = convertList(currentPath, context, state, parentPojo);
GenericBean<Object> arrayReceiver = new GenericBean<>();
Object convertedValue = value;
if (currentPath.parent != null) {
GenericType<?> collectionType = currentPath.parent.pojoType;
if (collectionType != null) {
GenericType<?> valueType = collectionType.getComponentType();
convertedValue = convert(currentPath, context, value, valueType.getAssignmentClass(), valueType); // depends on control dependency: [if], data = [none]
}
}
Object result = getCollectionReflectionUtil().set(arrayOrList, index, convertedValue, arrayReceiver);
Object newArray = arrayReceiver.getValue();
if (newArray != null) {
if (currentPath.parent.parent == null) {
throw new PojoPathCreationException(state.rootPath.pojo, currentPath.getPojoPath());
}
Object parentParentPojo;
if (currentPath.parent.parent == null) {
parentParentPojo = state.rootPath.pojo; // depends on control dependency: [if], data = [none]
} else {
parentParentPojo = currentPath.parent.parent.pojo; // depends on control dependency: [if], data = [none]
}
set(currentPath.parent, context, state, parentParentPojo, newArray); // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
private void understandSchema(String schema) throws JSONException {
JSONObject j1 = new JSONObject(schema);
JSONArray fields = j1.getJSONArray(FIELDS);
String fieldName;
String fieldTypeValue;
Object recName;
for (int k = 0; k < fields.length(); k++) {
if (fields.get(k) == null) {
continue;
}
JSONObject allEvents = new JSONObject(fields.get(k).toString());
Object name = allEvents.get(NAME);
if (name != null) {
if (name.toString().equalsIgnoreCase(EVENT)) {
JSONArray allTypeDetails = allEvents.getJSONArray(TYPE);
for (int i = 0; i < allTypeDetails.length(); i++) {
JSONObject actual = (JSONObject) allTypeDetails.get(i);
JSONArray types = actual.getJSONArray(FIELDS);
Map<String, String> typeDetails = new HashMap<String, String>();
for (int j = 0; j < types.length(); j++) {
if (types.getJSONObject(j) == null ) {
continue;
}
fieldName = types.getJSONObject(j).getString(NAME);
fieldTypeValue = types.getJSONObject(j).getString(TYPE);
if ((fieldName != null) && (fieldTypeValue != null)) {
typeDetails.put(fieldName, fieldTypeValue);
}
}
recName = actual.get(NAME);
if (recName != null) {
/* the next statement may throw an IllegalArgumentException if
* it finds a new string that's not part of the Hadoop2RecordType enum
* that way we know what types of events we are parsing
*/
fieldTypes.put(Hadoop2RecordType.valueOf(recName.toString()), typeDetails);
}
}
}
}
}
} } | public class class_name {
private void understandSchema(String schema) throws JSONException {
JSONObject j1 = new JSONObject(schema);
JSONArray fields = j1.getJSONArray(FIELDS);
String fieldName;
String fieldTypeValue;
Object recName;
for (int k = 0; k < fields.length(); k++) {
if (fields.get(k) == null) {
continue;
}
JSONObject allEvents = new JSONObject(fields.get(k).toString());
Object name = allEvents.get(NAME);
if (name != null) {
if (name.toString().equalsIgnoreCase(EVENT)) {
JSONArray allTypeDetails = allEvents.getJSONArray(TYPE);
for (int i = 0; i < allTypeDetails.length(); i++) {
JSONObject actual = (JSONObject) allTypeDetails.get(i);
JSONArray types = actual.getJSONArray(FIELDS);
Map<String, String> typeDetails = new HashMap<String, String>();
for (int j = 0; j < types.length(); j++) {
if (types.getJSONObject(j) == null ) {
continue;
}
fieldName = types.getJSONObject(j).getString(NAME); // depends on control dependency: [for], data = [j]
fieldTypeValue = types.getJSONObject(j).getString(TYPE); // depends on control dependency: [for], data = [j]
if ((fieldName != null) && (fieldTypeValue != null)) {
typeDetails.put(fieldName, fieldTypeValue); // depends on control dependency: [if], data = [none]
}
}
recName = actual.get(NAME); // depends on control dependency: [for], data = [none]
if (recName != null) {
/* the next statement may throw an IllegalArgumentException if
* it finds a new string that's not part of the Hadoop2RecordType enum
* that way we know what types of events we are parsing
*/
fieldTypes.put(Hadoop2RecordType.valueOf(recName.toString()), typeDetails); // depends on control dependency: [if], data = [(recName]
}
}
}
}
}
} } |
public class class_name {
public void unmark() {
// check if it's marked before removing the style class
if (marked) {
preferencesGroup.getRenderer().removeStyleClass(MARKED_STYLE_CLASS);
preferencesGroup.getRenderer().getTitleLabel().removeEventHandler(
MouseEvent.MOUSE_EXITED, unmarker
);
marked = !marked;
}
} } | public class class_name {
public void unmark() {
// check if it's marked before removing the style class
if (marked) {
preferencesGroup.getRenderer().removeStyleClass(MARKED_STYLE_CLASS); // depends on control dependency: [if], data = [none]
preferencesGroup.getRenderer().getTitleLabel().removeEventHandler(
MouseEvent.MOUSE_EXITED, unmarker
); // depends on control dependency: [if], data = [none]
marked = !marked; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
static String getIdlExceptionName(String exClassName, boolean mangleComponents)
{
StringBuilder idlName = new StringBuilder(256);
idlName.append("IDL:");
idlName.append(exClassName.replace('.', '/'));
if (exClassName.endsWith("Exception"))
{
idlName.setLength(idlName.length() - 7);
}
else
{
idlName.append("Ex");
}
if (mangleComponents) // PM94096
{
for (int begin = 0; begin < idlName.length();)
{
int end = idlName.indexOf("/", begin);
if (end == -1)
{
end = idlName.length();
}
if (idlName.charAt(begin) == '_')
{
idlName.insert(begin, 'J');
end++;
}
else
{
String comp = idlName.substring(begin, end);
if (isIDLKeyword(comp))
{
idlName.insert(begin, '_');
end++;
}
}
begin = end + 1;
}
}
idlName.append(":1.0");
return idlName.toString();
} } | public class class_name {
static String getIdlExceptionName(String exClassName, boolean mangleComponents)
{
StringBuilder idlName = new StringBuilder(256);
idlName.append("IDL:");
idlName.append(exClassName.replace('.', '/'));
if (exClassName.endsWith("Exception"))
{
idlName.setLength(idlName.length() - 7); // depends on control dependency: [if], data = [none]
}
else
{
idlName.append("Ex"); // depends on control dependency: [if], data = [none]
}
if (mangleComponents) // PM94096
{
for (int begin = 0; begin < idlName.length();)
{
int end = idlName.indexOf("/", begin);
if (end == -1)
{
end = idlName.length(); // depends on control dependency: [if], data = [none]
}
if (idlName.charAt(begin) == '_')
{
idlName.insert(begin, 'J'); // depends on control dependency: [if], data = [none]
end++; // depends on control dependency: [if], data = [none]
}
else
{
String comp = idlName.substring(begin, end);
if (isIDLKeyword(comp))
{
idlName.insert(begin, '_'); // depends on control dependency: [if], data = [none]
end++; // depends on control dependency: [if], data = [none]
}
}
begin = end + 1; // depends on control dependency: [for], data = [begin]
}
}
idlName.append(":1.0");
return idlName.toString();
} } |
public class class_name {
public void buildCluster(String secured) {
if (secured == null) {
this.cluster = Cluster.builder().addContactPoint(this.host).build();
this.cluster.getConfiguration().getQueryOptions()
.setConsistencyLevel(ConsistencyLevel.ONE);
} else {
try {
this.cluster = Cluster.builder().addContactPoint(this.host).withCredentials("user", "pass").withSSL().build();
} catch (Exception e) {
e.printStackTrace();
}
}
} } | public class class_name {
public void buildCluster(String secured) {
if (secured == null) {
this.cluster = Cluster.builder().addContactPoint(this.host).build(); // depends on control dependency: [if], data = [none]
this.cluster.getConfiguration().getQueryOptions()
.setConsistencyLevel(ConsistencyLevel.ONE); // depends on control dependency: [if], data = [none]
} else {
try {
this.cluster = Cluster.builder().addContactPoint(this.host).withCredentials("user", "pass").withSSL().build(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
@Override
public void endVisit(VariableDeclarationFragment fragment) {
//TODO(malvania): Add field to elementReferenceMap when field detection is enabled and the
// ElementUtil.getBinaryName() method doesn't break when called on a static block's
// ExecutableElement.
//String fieldID = stitchFieldIdentifier(fragment);
//elementReferenceMap.putIfAbsent(fieldID, new FieldReferenceNode(fragment));
Element element = fragment.getVariableElement().getEnclosingElement();
if (element instanceof TypeElement) {
TypeElement type = (TypeElement) element;
if (ElementUtil.isPublic(fragment.getVariableElement())) {
ClassReferenceNode node = (ClassReferenceNode) elementReferenceMap
.get(stitchClassIdentifier(type));
if (node == null) {
node = new ClassReferenceNode(type);
}
node.containsPublicField = true;
elementReferenceMap.putIfAbsent(stitchClassIdentifier(type), node);
}
}
} } | public class class_name {
@Override
public void endVisit(VariableDeclarationFragment fragment) {
//TODO(malvania): Add field to elementReferenceMap when field detection is enabled and the
// ElementUtil.getBinaryName() method doesn't break when called on a static block's
// ExecutableElement.
//String fieldID = stitchFieldIdentifier(fragment);
//elementReferenceMap.putIfAbsent(fieldID, new FieldReferenceNode(fragment));
Element element = fragment.getVariableElement().getEnclosingElement();
if (element instanceof TypeElement) {
TypeElement type = (TypeElement) element;
if (ElementUtil.isPublic(fragment.getVariableElement())) {
ClassReferenceNode node = (ClassReferenceNode) elementReferenceMap
.get(stitchClassIdentifier(type));
if (node == null) {
node = new ClassReferenceNode(type); // depends on control dependency: [if], data = [none]
}
node.containsPublicField = true; // depends on control dependency: [if], data = [none]
elementReferenceMap.putIfAbsent(stitchClassIdentifier(type), node); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private static Object readFromUriParam(Message m,
String parameterName,
Class<?> paramType,
Type genericType,
Annotation[] paramAnns,
MultivaluedMap<String, String> values,
String defaultValue,
boolean decoded) {
//CHECKSTYLE:ON
if ("".equals(parameterName)) {
return InjectionUtils.handleBean(paramType, paramAnns, values, ParameterType.PATH, m, decoded);
} else {
List<String> results = values.get(parameterName);
return InjectionUtils.createParameterObject(results,
paramType,
genericType,
paramAnns,
defaultValue,
decoded,
ParameterType.PATH,
m);
}
} } | public class class_name {
private static Object readFromUriParam(Message m,
String parameterName,
Class<?> paramType,
Type genericType,
Annotation[] paramAnns,
MultivaluedMap<String, String> values,
String defaultValue,
boolean decoded) {
//CHECKSTYLE:ON
if ("".equals(parameterName)) {
return InjectionUtils.handleBean(paramType, paramAnns, values, ParameterType.PATH, m, decoded); // depends on control dependency: [if], data = [none]
} else {
List<String> results = values.get(parameterName);
return InjectionUtils.createParameterObject(results,
paramType,
genericType,
paramAnns,
defaultValue,
decoded,
ParameterType.PATH,
m); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Content getTagletOutput(Doc holder, TagletWriter writer) {
SeeTag[] tags = holder.seeTags();
if (tags.length == 0 && holder instanceof MethodDoc) {
DocFinder.Output inheritedDoc =
DocFinder.search(new DocFinder.Input((MethodDoc) holder, this));
if (inheritedDoc.holder != null) {
tags = inheritedDoc.holder.seeTags();
}
}
return writer.seeTagOutput(holder, tags);
} } | public class class_name {
public Content getTagletOutput(Doc holder, TagletWriter writer) {
SeeTag[] tags = holder.seeTags();
if (tags.length == 0 && holder instanceof MethodDoc) {
DocFinder.Output inheritedDoc =
DocFinder.search(new DocFinder.Input((MethodDoc) holder, this));
if (inheritedDoc.holder != null) {
tags = inheritedDoc.holder.seeTags(); // depends on control dependency: [if], data = [none]
}
}
return writer.seeTagOutput(holder, tags);
} } |
public class class_name {
public void notifyMonitors(ProcessInstance processInstance, String event) {
// notify registered monitors
Process processVO = getMainProcessDefinition(processInstance);
Package pkg = PackageCache.getProcessPackage(processVO.getId());
// runtime context for enablement does not contain hydrated variables map (too expensive)
List<ProcessMonitor> monitors = MonitorRegistry.getInstance()
.getProcessMonitors(new ProcessRuntimeContext(pkg, processVO, processInstance,
getDataAccess().getPerformanceLevel(), isInService(), new HashMap<>()));
if (!monitors.isEmpty()) {
Map<String,Object> vars = new HashMap<>();
if (processInstance.getVariables() != null) {
for (VariableInstance var : processInstance.getVariables()) {
Object value = var.getData();
if (value instanceof DocumentReference) {
try {
Document docVO = getDocument((DocumentReference) value, false);
value = docVO == null ? null : docVO.getObject(var.getType(), pkg);
}
catch (DataAccessException ex) {
logger.severeException(ex.getMessage(), ex);
}
}
vars.put(var.getName(), value);
}
}
ProcessRuntimeContext runtimeContext = new ProcessRuntimeContext(pkg, processVO, processInstance,
getDataAccess().getPerformanceLevel(), isInService(), vars);
for (ProcessMonitor monitor : monitors) {
try {
if (monitor instanceof OfflineMonitor) {
@SuppressWarnings("unchecked")
OfflineMonitor<ProcessRuntimeContext> processOfflineMonitor = (OfflineMonitor<ProcessRuntimeContext>) monitor;
new OfflineMonitorTrigger<>(processOfflineMonitor, runtimeContext).fire(event);
}
else {
if (WorkStatus.LOGMSG_PROC_START.equals(event)) {
Map<String,Object> updated = monitor.onStart(runtimeContext);
if (updated != null) {
for (String varName : updated.keySet()) {
if (processInstance.getVariables() == null)
processInstance.setVariables(new ArrayList<>());
Variable varVO = processVO.getVariable(varName);
if (varVO == null || !varVO.isInput())
throw new ProcessException("Process '" + processVO.getFullLabel() + "' has no such input variable defined: " + varName);
if (processInstance.getVariable(varName) != null)
throw new ProcessException("Process '" + processVO.getFullLabel() + "' input variable already populated: " + varName);
if (VariableTranslator.isDocumentReferenceVariable(runtimeContext.getPackage(), varVO.getType())) {
DocumentReference docRef = createDocument(varVO.getType(), OwnerType.VARIABLE_INSTANCE, new Long(0),
updated.get(varName));
VariableInstance varInst = createVariableInstance(processInstance, varName, docRef);
updateDocumentInfo(docRef, processVO.getVariable(varInst.getName()).getType(), OwnerType.VARIABLE_INSTANCE,
varInst.getInstanceId(), null, null);
processInstance.getVariables().add(varInst);
}
else {
VariableInstance varInst = createVariableInstance(processInstance, varName, updated.get(varName));
processInstance.getVariables().add(varInst);
}
}
}
}
else if (WorkStatus.LOGMSG_PROC_ERROR.equals(event)) {
monitor.onError(runtimeContext);
}
else if (WorkStatus.LOGMSG_PROC_COMPLETE.equals(event)) {
monitor.onFinish(runtimeContext);
}
}
}
catch (Exception ex) {
logger.severeException(ex.getMessage(), ex);
}
}
}
} } | public class class_name {
public void notifyMonitors(ProcessInstance processInstance, String event) {
// notify registered monitors
Process processVO = getMainProcessDefinition(processInstance);
Package pkg = PackageCache.getProcessPackage(processVO.getId());
// runtime context for enablement does not contain hydrated variables map (too expensive)
List<ProcessMonitor> monitors = MonitorRegistry.getInstance()
.getProcessMonitors(new ProcessRuntimeContext(pkg, processVO, processInstance,
getDataAccess().getPerformanceLevel(), isInService(), new HashMap<>()));
if (!monitors.isEmpty()) {
Map<String,Object> vars = new HashMap<>();
if (processInstance.getVariables() != null) {
for (VariableInstance var : processInstance.getVariables()) {
Object value = var.getData();
if (value instanceof DocumentReference) {
try {
Document docVO = getDocument((DocumentReference) value, false);
value = docVO == null ? null : docVO.getObject(var.getType(), pkg); // depends on control dependency: [try], data = [none]
}
catch (DataAccessException ex) {
logger.severeException(ex.getMessage(), ex);
} // depends on control dependency: [catch], data = [none]
}
vars.put(var.getName(), value); // depends on control dependency: [for], data = [var]
}
}
ProcessRuntimeContext runtimeContext = new ProcessRuntimeContext(pkg, processVO, processInstance,
getDataAccess().getPerformanceLevel(), isInService(), vars);
for (ProcessMonitor monitor : monitors) {
try {
if (monitor instanceof OfflineMonitor) {
@SuppressWarnings("unchecked")
OfflineMonitor<ProcessRuntimeContext> processOfflineMonitor = (OfflineMonitor<ProcessRuntimeContext>) monitor;
new OfflineMonitorTrigger<>(processOfflineMonitor, runtimeContext).fire(event); // depends on control dependency: [if], data = [none]
}
else {
if (WorkStatus.LOGMSG_PROC_START.equals(event)) {
Map<String,Object> updated = monitor.onStart(runtimeContext);
if (updated != null) {
for (String varName : updated.keySet()) {
if (processInstance.getVariables() == null)
processInstance.setVariables(new ArrayList<>());
Variable varVO = processVO.getVariable(varName);
if (varVO == null || !varVO.isInput())
throw new ProcessException("Process '" + processVO.getFullLabel() + "' has no such input variable defined: " + varName);
if (processInstance.getVariable(varName) != null)
throw new ProcessException("Process '" + processVO.getFullLabel() + "' input variable already populated: " + varName);
if (VariableTranslator.isDocumentReferenceVariable(runtimeContext.getPackage(), varVO.getType())) {
DocumentReference docRef = createDocument(varVO.getType(), OwnerType.VARIABLE_INSTANCE, new Long(0),
updated.get(varName));
VariableInstance varInst = createVariableInstance(processInstance, varName, docRef);
updateDocumentInfo(docRef, processVO.getVariable(varInst.getName()).getType(), OwnerType.VARIABLE_INSTANCE,
varInst.getInstanceId(), null, null); // depends on control dependency: [if], data = [none]
processInstance.getVariables().add(varInst); // depends on control dependency: [if], data = [none]
}
else {
VariableInstance varInst = createVariableInstance(processInstance, varName, updated.get(varName));
processInstance.getVariables().add(varInst); // depends on control dependency: [if], data = [none]
}
}
}
}
else if (WorkStatus.LOGMSG_PROC_ERROR.equals(event)) {
monitor.onError(runtimeContext); // depends on control dependency: [if], data = [none]
}
else if (WorkStatus.LOGMSG_PROC_COMPLETE.equals(event)) {
monitor.onFinish(runtimeContext); // depends on control dependency: [if], data = [none]
}
}
}
catch (Exception ex) {
logger.severeException(ex.getMessage(), ex);
} // depends on control dependency: [catch], data = [none]
}
}
} } |
public class class_name {
public final void setProfileId(String profileId) {
boolean force = false;
if (Utility.isNullOrEmpty(this.profileId) || !this.profileId.equalsIgnoreCase(profileId)) {
// Clear out the old profilePicture before requesting for the new one.
setBlankProfilePicture();
force = true;
}
this.profileId = profileId;
refreshImage(force);
} } | public class class_name {
public final void setProfileId(String profileId) {
boolean force = false;
if (Utility.isNullOrEmpty(this.profileId) || !this.profileId.equalsIgnoreCase(profileId)) {
// Clear out the old profilePicture before requesting for the new one.
setBlankProfilePicture(); // depends on control dependency: [if], data = [none]
force = true; // depends on control dependency: [if], data = [none]
}
this.profileId = profileId;
refreshImage(force);
} } |
public class class_name {
private KamEdge wrapEdge(KamEdge kamEdge) {
if (kamEdge == null) {
return null;
}
TermParameter param = etp.get(kamEdge.getId());
if (param != null) {
return new OrthologousEdge(kamEdge, param);
}
return kamEdge;
} } | public class class_name {
private KamEdge wrapEdge(KamEdge kamEdge) {
if (kamEdge == null) {
return null; // depends on control dependency: [if], data = [none]
}
TermParameter param = etp.get(kamEdge.getId());
if (param != null) {
return new OrthologousEdge(kamEdge, param); // depends on control dependency: [if], data = [none]
}
return kamEdge;
} } |
public class class_name {
private void calculateIndexGroupByInfo(IndexScanPlanNode root,
IndexGroupByInfo gbInfo) {
String fromTableAlias = root.getTargetTableAlias();
assert(fromTableAlias != null);
Index index = root.getCatalogIndex();
if ( ! IndexType.isScannable(index.getType())) {
return;
}
ArrayList<AbstractExpression> bindings = new ArrayList<>();
gbInfo.m_coveredGroupByColumns = calculateGroupbyColumnsCovered(
index, fromTableAlias, bindings);
gbInfo.m_canBeFullySerialized =
(gbInfo.m_coveredGroupByColumns.size() ==
m_parsedSelect.groupByColumns().size());
} } | public class class_name {
private void calculateIndexGroupByInfo(IndexScanPlanNode root,
IndexGroupByInfo gbInfo) {
String fromTableAlias = root.getTargetTableAlias();
assert(fromTableAlias != null);
Index index = root.getCatalogIndex();
if ( ! IndexType.isScannable(index.getType())) {
return; // depends on control dependency: [if], data = [none]
}
ArrayList<AbstractExpression> bindings = new ArrayList<>();
gbInfo.m_coveredGroupByColumns = calculateGroupbyColumnsCovered(
index, fromTableAlias, bindings);
gbInfo.m_canBeFullySerialized =
(gbInfo.m_coveredGroupByColumns.size() ==
m_parsedSelect.groupByColumns().size());
} } |
public class class_name {
public final boolean commit()
throws LoginException
{
boolean ret = false;
if (this.mode == ActionCallback.Mode.ALL_PERSONS) {
for (final XMLPersonPrincipal personTmp : this.allPersons.values()) {
if (!this.subject.getPrincipals().contains(personTmp)) {
if (XMLUserLoginModule.LOG.isDebugEnabled()) {
XMLUserLoginModule.LOG.debug("commit person '" + personTmp + "'");
}
this.subject.getPrincipals().add(personTmp);
}
}
ret = true;
} else if (this.person != null) {
if (XMLUserLoginModule.LOG.isDebugEnabled()) {
XMLUserLoginModule.LOG.debug("commit of '" + this.person + "'");
}
if (!this.subject.getPrincipals().contains(this.person)) {
this.subject.getPrincipals().add(this.person);
for (final XMLRolePrincipal principal : this.person.getRoles()) {
this.subject.getPrincipals().add(principal);
}
for (final XMLGroupPrincipal principal : this.person.getGroups()) {
this.subject.getPrincipals().add(principal);
}
}
ret = true;
}
return ret;
} } | public class class_name {
public final boolean commit()
throws LoginException
{
boolean ret = false;
if (this.mode == ActionCallback.Mode.ALL_PERSONS) {
for (final XMLPersonPrincipal personTmp : this.allPersons.values()) {
if (!this.subject.getPrincipals().contains(personTmp)) {
if (XMLUserLoginModule.LOG.isDebugEnabled()) {
XMLUserLoginModule.LOG.debug("commit person '" + personTmp + "'"); // depends on control dependency: [if], data = [none]
}
this.subject.getPrincipals().add(personTmp); // depends on control dependency: [if], data = [none]
}
}
ret = true;
} else if (this.person != null) {
if (XMLUserLoginModule.LOG.isDebugEnabled()) {
XMLUserLoginModule.LOG.debug("commit of '" + this.person + "'");
}
if (!this.subject.getPrincipals().contains(this.person)) {
this.subject.getPrincipals().add(this.person);
for (final XMLRolePrincipal principal : this.person.getRoles()) {
this.subject.getPrincipals().add(principal); // depends on control dependency: [for], data = [principal]
}
for (final XMLGroupPrincipal principal : this.person.getGroups()) {
this.subject.getPrincipals().add(principal); // depends on control dependency: [for], data = [principal]
}
}
ret = true;
}
return ret;
} } |
public class class_name {
public Weighting createWeighting(HintsMap hintsMap, FlagEncoder encoder, Graph graph) {
String weightingStr = toLowerCase(hintsMap.getWeighting());
Weighting weighting = null;
if (encoder.supports(GenericWeighting.class)) {
weighting = new GenericWeighting((DataFlagEncoder) encoder, hintsMap);
} else if ("shortest".equalsIgnoreCase(weightingStr)) {
weighting = new ShortestWeighting(encoder);
} else if ("fastest".equalsIgnoreCase(weightingStr) || weightingStr.isEmpty()) {
if (encoder.supports(PriorityWeighting.class))
weighting = new PriorityWeighting(encoder, hintsMap);
else
weighting = new FastestWeighting(encoder, hintsMap);
} else if ("curvature".equalsIgnoreCase(weightingStr)) {
if (encoder.supports(CurvatureWeighting.class))
weighting = new CurvatureWeighting(encoder, hintsMap);
} else if ("short_fastest".equalsIgnoreCase(weightingStr)) {
weighting = new ShortFastestWeighting(encoder, hintsMap);
}
if (weighting == null)
throw new IllegalArgumentException("weighting " + weightingStr + " not supported");
if (hintsMap.has(Routing.BLOCK_AREA)) {
String blockAreaStr = hintsMap.get(Parameters.Routing.BLOCK_AREA, "");
GraphEdgeIdFinder.BlockArea blockArea = new GraphEdgeIdFinder(graph, locationIndex).
parseBlockArea(blockAreaStr, DefaultEdgeFilter.allEdges(encoder), hintsMap.getDouble("block_area.edge_id_max_area", 1000 * 1000));
return new BlockAreaWeighting(weighting, blockArea);
}
return weighting;
} } | public class class_name {
public Weighting createWeighting(HintsMap hintsMap, FlagEncoder encoder, Graph graph) {
String weightingStr = toLowerCase(hintsMap.getWeighting());
Weighting weighting = null;
if (encoder.supports(GenericWeighting.class)) {
weighting = new GenericWeighting((DataFlagEncoder) encoder, hintsMap); // depends on control dependency: [if], data = [none]
} else if ("shortest".equalsIgnoreCase(weightingStr)) {
weighting = new ShortestWeighting(encoder); // depends on control dependency: [if], data = [none]
} else if ("fastest".equalsIgnoreCase(weightingStr) || weightingStr.isEmpty()) {
if (encoder.supports(PriorityWeighting.class))
weighting = new PriorityWeighting(encoder, hintsMap);
else
weighting = new FastestWeighting(encoder, hintsMap);
} else if ("curvature".equalsIgnoreCase(weightingStr)) {
if (encoder.supports(CurvatureWeighting.class))
weighting = new CurvatureWeighting(encoder, hintsMap);
} else if ("short_fastest".equalsIgnoreCase(weightingStr)) {
weighting = new ShortFastestWeighting(encoder, hintsMap); // depends on control dependency: [if], data = [none]
}
if (weighting == null)
throw new IllegalArgumentException("weighting " + weightingStr + " not supported");
if (hintsMap.has(Routing.BLOCK_AREA)) {
String blockAreaStr = hintsMap.get(Parameters.Routing.BLOCK_AREA, "");
GraphEdgeIdFinder.BlockArea blockArea = new GraphEdgeIdFinder(graph, locationIndex).
parseBlockArea(blockAreaStr, DefaultEdgeFilter.allEdges(encoder), hintsMap.getDouble("block_area.edge_id_max_area", 1000 * 1000));
return new BlockAreaWeighting(weighting, blockArea); // depends on control dependency: [if], data = [none]
}
return weighting;
} } |
public class class_name {
private void createFieldMap(byte[] data)
{
int index = 0;
int lastDataBlockOffset = 0;
int dataBlockIndex = 0;
while (index < data.length)
{
long mask = MPPUtility.getInt(data, index + 0);
//mask = mask << 4;
int dataBlockOffset = MPPUtility.getShort(data, index + 4);
//int metaFlags = MPPUtility.getByte(data, index + 8);
FieldType type = getFieldType(MPPUtility.getInt(data, index + 12));
int category = MPPUtility.getShort(data, index + 20);
//int sizeInBytes = MPPUtility.getShort(data, index + 22);
//int metaIndex = MPPUtility.getInt(data, index + 24);
//
// Categories
//
// 02 - Short values [RATE_UNITS, WORKGROUP, ACCRUE, TIME_UNITS, PRIORITY, TASK_TYPE, CONSTRAINT, ACCRUE, PERCENTAGE, SHORT, WORK_UNITS] - BOOKING_TYPE, EARNED_VALUE_METHOD, DELIVERABLE_TYPE, RESOURCE_REQUEST_TYPE - we have as string in MPXJ????
// 03 - Int values [DURATION, INTEGER] - Recalc outline codes as Boolean?
// 05 - Rate, Number [RATE, NUMERIC]
// 08 - String (and some durations!!!) [STRING, DURATION]
// 0B - Boolean (meta block 0?) - [BOOLEAN]
// 13 - Date - [DATE]
// 48 - GUID - [GUID]
// 64 - Boolean (meta block 1?)- [BOOLEAN]
// 65 - Work, Currency [WORK, CURRENCY]
// 66 - Units [UNITS]
// 1D - Raw bytes [BINARY, ASCII_STRING] - Exception: outline code indexes, they are integers, but stored as part of a binary block
int varDataKey;
if (useTypeAsVarDataKey())
{
Integer substitute = substituteVarDataKey(type);
if (substitute == null)
{
varDataKey = (MPPUtility.getInt(data, index + 12) & 0x0000FFFF);
}
else
{
varDataKey = substitute.intValue();
}
}
else
{
varDataKey = MPPUtility.getByte(data, index + 6);
}
FieldLocation location;
int metaBlock;
switch (category)
{
case 0x0B:
{
location = FieldLocation.META_DATA;
metaBlock = 0;
break;
}
case 0x64:
{
location = FieldLocation.META_DATA;
metaBlock = 1;
break;
}
default:
{
metaBlock = 0;
if (dataBlockOffset != 65535)
{
location = FieldLocation.FIXED_DATA;
if (dataBlockOffset < lastDataBlockOffset)
{
++dataBlockIndex;
}
lastDataBlockOffset = dataBlockOffset;
int typeSize = getFixedDataFieldSize(type);
if (dataBlockOffset + typeSize > m_maxFixedDataSize[dataBlockIndex])
{
m_maxFixedDataSize[dataBlockIndex] = dataBlockOffset + typeSize;
}
}
else
{
if (varDataKey != 0)
{
location = FieldLocation.VAR_DATA;
}
else
{
location = FieldLocation.UNKNOWN;
}
}
break;
}
}
FieldItem item = new FieldItem(type, location, dataBlockIndex, dataBlockOffset, varDataKey, mask, metaBlock);
if (m_debug)
{
System.out.println(ByteArrayHelper.hexdump(data, index, 28, false) + " " + item + " mpxjDataType=" + item.getType().getDataType() + " index=" + index);
}
m_map.put(type, item);
index += 28;
}
} } | public class class_name {
private void createFieldMap(byte[] data)
{
int index = 0;
int lastDataBlockOffset = 0;
int dataBlockIndex = 0;
while (index < data.length)
{
long mask = MPPUtility.getInt(data, index + 0);
//mask = mask << 4;
int dataBlockOffset = MPPUtility.getShort(data, index + 4);
//int metaFlags = MPPUtility.getByte(data, index + 8);
FieldType type = getFieldType(MPPUtility.getInt(data, index + 12));
int category = MPPUtility.getShort(data, index + 20);
//int sizeInBytes = MPPUtility.getShort(data, index + 22);
//int metaIndex = MPPUtility.getInt(data, index + 24);
//
// Categories
//
// 02 - Short values [RATE_UNITS, WORKGROUP, ACCRUE, TIME_UNITS, PRIORITY, TASK_TYPE, CONSTRAINT, ACCRUE, PERCENTAGE, SHORT, WORK_UNITS] - BOOKING_TYPE, EARNED_VALUE_METHOD, DELIVERABLE_TYPE, RESOURCE_REQUEST_TYPE - we have as string in MPXJ????
// 03 - Int values [DURATION, INTEGER] - Recalc outline codes as Boolean?
// 05 - Rate, Number [RATE, NUMERIC]
// 08 - String (and some durations!!!) [STRING, DURATION]
// 0B - Boolean (meta block 0?) - [BOOLEAN]
// 13 - Date - [DATE]
// 48 - GUID - [GUID]
// 64 - Boolean (meta block 1?)- [BOOLEAN]
// 65 - Work, Currency [WORK, CURRENCY]
// 66 - Units [UNITS]
// 1D - Raw bytes [BINARY, ASCII_STRING] - Exception: outline code indexes, they are integers, but stored as part of a binary block
int varDataKey;
if (useTypeAsVarDataKey())
{
Integer substitute = substituteVarDataKey(type);
if (substitute == null)
{
varDataKey = (MPPUtility.getInt(data, index + 12) & 0x0000FFFF); // depends on control dependency: [if], data = [none]
}
else
{
varDataKey = substitute.intValue(); // depends on control dependency: [if], data = [none]
}
}
else
{
varDataKey = MPPUtility.getByte(data, index + 6); // depends on control dependency: [if], data = [none]
}
FieldLocation location;
int metaBlock;
switch (category)
{
case 0x0B:
{
location = FieldLocation.META_DATA;
metaBlock = 0;
break;
}
case 0x64:
{
location = FieldLocation.META_DATA;
metaBlock = 1; // depends on control dependency: [while], data = [none]
break;
}
default:
{
metaBlock = 0;
if (dataBlockOffset != 65535)
{
location = FieldLocation.FIXED_DATA; // depends on control dependency: [if], data = [none]
if (dataBlockOffset < lastDataBlockOffset)
{
++dataBlockIndex; // depends on control dependency: [if], data = [none]
}
lastDataBlockOffset = dataBlockOffset; // depends on control dependency: [if], data = [none]
int typeSize = getFixedDataFieldSize(type);
if (dataBlockOffset + typeSize > m_maxFixedDataSize[dataBlockIndex])
{
m_maxFixedDataSize[dataBlockIndex] = dataBlockOffset + typeSize; // depends on control dependency: [if], data = [none]
}
}
else
{
if (varDataKey != 0)
{
location = FieldLocation.VAR_DATA; // depends on control dependency: [if], data = [none]
}
else
{
location = FieldLocation.UNKNOWN; // depends on control dependency: [if], data = [none]
}
}
break;
}
}
FieldItem item = new FieldItem(type, location, dataBlockIndex, dataBlockOffset, varDataKey, mask, metaBlock);
if (m_debug)
{
System.out.println(ByteArrayHelper.hexdump(data, index, 28, false) + " " + item + " mpxjDataType=" + item.getType().getDataType() + " index=" + index);
}
m_map.put(type, item);
index += 28;
}
} } |
public class class_name {
@Nullable
CompiledTemplate.Factory selectDelTemplate(
String delTemplateName, String variant, Predicate<String> activeDelPackageSelector) {
TemplateData selectedTemplate =
selector.selectTemplate(delTemplateName, variant, activeDelPackageSelector);
if (selectedTemplate == null) {
return null;
}
if (selectedTemplate.factory == null) {
throw new IllegalArgumentException(
"cannot get a factory for the private template: " + selectedTemplate.soyTemplateName());
}
return selectedTemplate.factory;
} } | public class class_name {
@Nullable
CompiledTemplate.Factory selectDelTemplate(
String delTemplateName, String variant, Predicate<String> activeDelPackageSelector) {
TemplateData selectedTemplate =
selector.selectTemplate(delTemplateName, variant, activeDelPackageSelector);
if (selectedTemplate == null) {
return null; // depends on control dependency: [if], data = [none]
}
if (selectedTemplate.factory == null) {
throw new IllegalArgumentException(
"cannot get a factory for the private template: " + selectedTemplate.soyTemplateName()); // depends on control dependency: [if], data = [none]
}
return selectedTemplate.factory;
} } |
public class class_name {
public void setText(Document doc, String text)
{
StringReader reader = new StringReader(text);
HTMLEditorKit kit = (HTMLEditorKit) m_editorPane.getEditorKitForContentType(HTML_CONTENT);
try {
int iLength = doc.getLength();
if (iLength > 0)
doc.remove(0, iLength);
kit.read(reader, doc, 0);
} catch (IOException ex) {
ex.printStackTrace();
} catch (BadLocationException ex) {
ex.printStackTrace();
}
} } | public class class_name {
public void setText(Document doc, String text)
{
StringReader reader = new StringReader(text);
HTMLEditorKit kit = (HTMLEditorKit) m_editorPane.getEditorKitForContentType(HTML_CONTENT);
try {
int iLength = doc.getLength();
if (iLength > 0)
doc.remove(0, iLength);
kit.read(reader, doc, 0); // depends on control dependency: [try], data = [none]
} catch (IOException ex) {
ex.printStackTrace();
} catch (BadLocationException ex) { // depends on control dependency: [catch], data = [none]
ex.printStackTrace();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static Object arrayToString(final Object obj) {
if (obj != null && obj.getClass().isArray()) {
final int len = Array.getLength(obj);
final String[] strings = new String[len];
for (int i = 0; i < len; i++) {
strings[i] = String.valueOf(Array.get(obj, i));
}
return Arrays.toString(strings);
} else {
return obj;
}
} } | public class class_name {
public static Object arrayToString(final Object obj) {
if (obj != null && obj.getClass().isArray()) {
final int len = Array.getLength(obj);
final String[] strings = new String[len];
for (int i = 0; i < len; i++) {
strings[i] = String.valueOf(Array.get(obj, i)); // depends on control dependency: [for], data = [i]
}
return Arrays.toString(strings); // depends on control dependency: [if], data = [none]
} else {
return obj; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public StringifiedAccumulatorResult[] getAggregatedUserAccumulatorsStringified() {
Map<String, OptionalFailure<Accumulator<?, ?>>> userAccumulators = new HashMap<>();
for (ExecutionVertex vertex : taskVertices) {
Map<String, Accumulator<?, ?>> next = vertex.getCurrentExecutionAttempt().getUserAccumulators();
if (next != null) {
AccumulatorHelper.mergeInto(userAccumulators, next);
}
}
return StringifiedAccumulatorResult.stringifyAccumulatorResults(userAccumulators);
} } | public class class_name {
public StringifiedAccumulatorResult[] getAggregatedUserAccumulatorsStringified() {
Map<String, OptionalFailure<Accumulator<?, ?>>> userAccumulators = new HashMap<>();
for (ExecutionVertex vertex : taskVertices) {
Map<String, Accumulator<?, ?>> next = vertex.getCurrentExecutionAttempt().getUserAccumulators(); // depends on control dependency: [for], data = [vertex]
if (next != null) {
AccumulatorHelper.mergeInto(userAccumulators, next); // depends on control dependency: [if], data = [none]
}
}
return StringifiedAccumulatorResult.stringifyAccumulatorResults(userAccumulators);
} } |
public class class_name {
public static boolean startsWithUppercase(String str) {
if (isEmpty(str)) {
return false;
}
return Character.isUpperCase(str.charAt(0));
} } | public class class_name {
public static boolean startsWithUppercase(String str) {
if (isEmpty(str)) {
return false; // depends on control dependency: [if], data = [none]
}
return Character.isUpperCase(str.charAt(0));
} } |
public class class_name {
private JobRequest getJobRequest(int launchId, DbConn cnx)
{
Map<String, String> prms = RuntimeParameter.select_map(cnx, "jiprm_select_by_ji", launchId);
ResultSet rs = cnx.runSelect("history_select_reenqueue_by_id", launchId);
try
{
if (!rs.next())
{
throw new JqmInvalidRequestException("There is no past laucnh iwth ID " + launchId);
}
}
catch (SQLException e1)
{
throw new JqmClientException("Internal JQM API error", e1);
}
JobRequest jd = new JobRequest();
try
{
jd.setApplication(rs.getString(1));
jd.setApplicationName(rs.getString(2));
jd.setEmail(rs.getString(3));
jd.setKeyword1(rs.getString(4));
jd.setKeyword2(rs.getString(5));
jd.setKeyword3(rs.getString(6));
jd.setModule(rs.getString(7));
jd.setParentID(rs.getInt(8));
jd.setSessionID(rs.getString(9));
jd.setUser(rs.getString(10));
for (Map.Entry<String, String> p : prms.entrySet())
{
jd.addParameter(p.getKey(), p.getValue());
}
}
catch (SQLException e)
{
throw new JqmClientException("Could not extract History data for launch " + launchId, e);
}
return jd;
} } | public class class_name {
private JobRequest getJobRequest(int launchId, DbConn cnx)
{
Map<String, String> prms = RuntimeParameter.select_map(cnx, "jiprm_select_by_ji", launchId);
ResultSet rs = cnx.runSelect("history_select_reenqueue_by_id", launchId);
try
{
if (!rs.next())
{
throw new JqmInvalidRequestException("There is no past laucnh iwth ID " + launchId);
}
}
catch (SQLException e1)
{
throw new JqmClientException("Internal JQM API error", e1);
} // depends on control dependency: [catch], data = [none]
JobRequest jd = new JobRequest();
try
{
jd.setApplication(rs.getString(1)); // depends on control dependency: [try], data = [none]
jd.setApplicationName(rs.getString(2)); // depends on control dependency: [try], data = [none]
jd.setEmail(rs.getString(3)); // depends on control dependency: [try], data = [none]
jd.setKeyword1(rs.getString(4)); // depends on control dependency: [try], data = [none]
jd.setKeyword2(rs.getString(5)); // depends on control dependency: [try], data = [none]
jd.setKeyword3(rs.getString(6)); // depends on control dependency: [try], data = [none]
jd.setModule(rs.getString(7)); // depends on control dependency: [try], data = [none]
jd.setParentID(rs.getInt(8)); // depends on control dependency: [try], data = [none]
jd.setSessionID(rs.getString(9)); // depends on control dependency: [try], data = [none]
jd.setUser(rs.getString(10)); // depends on control dependency: [try], data = [none]
for (Map.Entry<String, String> p : prms.entrySet())
{
jd.addParameter(p.getKey(), p.getValue()); // depends on control dependency: [for], data = [p]
}
}
catch (SQLException e)
{
throw new JqmClientException("Could not extract History data for launch " + launchId, e);
} // depends on control dependency: [catch], data = [none]
return jd;
} } |
public class class_name {
private void setNetworkPipes( boolean isAreaNotAllDry ) throws Exception {
int length = inPipes.size();
networkPipes = new Pipe[length];
SimpleFeatureIterator stationsIter = inPipes.features();
boolean existOut = false;
int tmpOutIndex = 0;
try {
int t = 0;
while( stationsIter.hasNext() ) {
SimpleFeature feature = stationsIter.next();
try {
/*
* extract the value of the ID which is the position (minus
* 1) in the array.
*/
Number field = ((Number) feature.getAttribute(TrentoPFeatureType.ID_STR));
if (field == null) {
pm.errorMessage(msg.message("trentoP.error.number") + TrentoPFeatureType.ID_STR);
throw new IllegalArgumentException(msg.message("trentoP.error.number") + TrentoPFeatureType.ID_STR);
}
if (field.equals(pOutPipe)) {
tmpOutIndex = t;
existOut = true;
}
networkPipes[t] = new Pipe(feature, pMode, isAreaNotAllDry, pm);
t++;
} catch (NullPointerException e) {
pm.errorMessage(msg.message("trentop.illegalNet"));
throw new IllegalArgumentException(msg.message("trentop.illegalNet"));
}
}
} finally {
stationsIter.close();
}
if (!existOut) {
}
// set the id where drain of the outlet.
networkPipes[tmpOutIndex].setIdPipeWhereDrain(0);
networkPipes[tmpOutIndex].setIndexPipeWhereDrain(-1);
// start to construct the net.
int numberOfPoint = networkPipes[tmpOutIndex].point.length - 1;
findIdThatDrainsIntoIndex(tmpOutIndex, networkPipes[tmpOutIndex].point[0]);
findIdThatDrainsIntoIndex(tmpOutIndex, networkPipes[tmpOutIndex].point[numberOfPoint]);
List<Integer> missingId = new ArrayList<Integer>();
for( Pipe pipe : networkPipes ) {
if (pipe.getIdPipeWhereDrain() == null && pipe.getId() != pOutPipe) {
missingId.add(pipe.getId());
}
}
if (missingId.size() > 0) {
String errorMsg = "One of the following pipes doesn't have a connected pipe towards the outlet: "
+ Arrays.toString(missingId.toArray(new Integer[0]));
pm.errorMessage(msg.message(errorMsg));
throw new IllegalArgumentException(errorMsg);
}
verifyNet(networkPipes, pm);
} } | public class class_name {
private void setNetworkPipes( boolean isAreaNotAllDry ) throws Exception {
int length = inPipes.size();
networkPipes = new Pipe[length];
SimpleFeatureIterator stationsIter = inPipes.features();
boolean existOut = false;
int tmpOutIndex = 0;
try {
int t = 0;
while( stationsIter.hasNext() ) {
SimpleFeature feature = stationsIter.next();
try {
/*
* extract the value of the ID which is the position (minus
* 1) in the array.
*/
Number field = ((Number) feature.getAttribute(TrentoPFeatureType.ID_STR));
if (field == null) {
pm.errorMessage(msg.message("trentoP.error.number") + TrentoPFeatureType.ID_STR); // depends on control dependency: [if], data = [none]
throw new IllegalArgumentException(msg.message("trentoP.error.number") + TrentoPFeatureType.ID_STR);
}
if (field.equals(pOutPipe)) {
tmpOutIndex = t; // depends on control dependency: [if], data = [none]
existOut = true; // depends on control dependency: [if], data = [none]
}
networkPipes[t] = new Pipe(feature, pMode, isAreaNotAllDry, pm);
t++;
} catch (NullPointerException e) {
pm.errorMessage(msg.message("trentop.illegalNet"));
throw new IllegalArgumentException(msg.message("trentop.illegalNet"));
}
}
} finally {
stationsIter.close();
}
if (!existOut) {
}
// set the id where drain of the outlet.
networkPipes[tmpOutIndex].setIdPipeWhereDrain(0);
networkPipes[tmpOutIndex].setIndexPipeWhereDrain(-1);
// start to construct the net.
int numberOfPoint = networkPipes[tmpOutIndex].point.length - 1;
findIdThatDrainsIntoIndex(tmpOutIndex, networkPipes[tmpOutIndex].point[0]);
findIdThatDrainsIntoIndex(tmpOutIndex, networkPipes[tmpOutIndex].point[numberOfPoint]);
List<Integer> missingId = new ArrayList<Integer>();
for( Pipe pipe : networkPipes ) {
if (pipe.getIdPipeWhereDrain() == null && pipe.getId() != pOutPipe) {
missingId.add(pipe.getId());
}
}
if (missingId.size() > 0) {
String errorMsg = "One of the following pipes doesn't have a connected pipe towards the outlet: "
+ Arrays.toString(missingId.toArray(new Integer[0]));
pm.errorMessage(msg.message(errorMsg));
throw new IllegalArgumentException(errorMsg);
}
verifyNet(networkPipes, pm);
} } |
public class class_name {
protected void removeTargetListeners (Component comp)
{
comp.removeMouseListener(_targetListener);
comp.removeMouseMotionListener(_targetListener);
if (comp instanceof Container) { // again, always true for JComp...
Container cont = (Container) comp;
cont.removeContainerListener(_childListener);
for (int ii=0, nn=cont.getComponentCount(); ii < nn; ii++) {
removeTargetListeners(cont.getComponent(ii));
}
}
} } | public class class_name {
protected void removeTargetListeners (Component comp)
{
comp.removeMouseListener(_targetListener);
comp.removeMouseMotionListener(_targetListener);
if (comp instanceof Container) { // again, always true for JComp...
Container cont = (Container) comp;
cont.removeContainerListener(_childListener); // depends on control dependency: [if], data = [none]
for (int ii=0, nn=cont.getComponentCount(); ii < nn; ii++) {
removeTargetListeners(cont.getComponent(ii)); // depends on control dependency: [for], data = [ii]
}
}
} } |
public class class_name {
public boolean scheduleExecutorTask(Runnable task)
{
ClassLoader loader = Thread.currentThread().getContextClassLoader();
synchronized (_executorLock) {
_executorTaskCount++;
if (_executorTaskCount <= _executorTaskMax || _executorTaskMax < 0) {
boolean isPriority = false;
boolean isQueue = true;
boolean isWake = true;
return scheduleImpl(task, loader, MAX_EXPIRE, isPriority, isQueue, isWake);
}
else {
ExecutorQueueItem item = new ExecutorQueueItem(task, loader);
if (_executorQueueTail != null)
_executorQueueTail._next = item;
else
_executorQueueHead = item;
_executorQueueTail = item;
return false;
}
}
} } | public class class_name {
public boolean scheduleExecutorTask(Runnable task)
{
ClassLoader loader = Thread.currentThread().getContextClassLoader();
synchronized (_executorLock) {
_executorTaskCount++;
if (_executorTaskCount <= _executorTaskMax || _executorTaskMax < 0) {
boolean isPriority = false;
boolean isQueue = true;
boolean isWake = true;
return scheduleImpl(task, loader, MAX_EXPIRE, isPriority, isQueue, isWake); // depends on control dependency: [if], data = [none]
}
else {
ExecutorQueueItem item = new ExecutorQueueItem(task, loader);
if (_executorQueueTail != null)
_executorQueueTail._next = item;
else
_executorQueueHead = item;
_executorQueueTail = item; // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public void runAfterApplicationCreateBootstrap(
Instrumentation instrumentation, String[] bootstrapClasses) {
if (!isWithExtension) {
SelendroidLogger.error("Cannot run bootstrap. Must load an extension first.");
return;
}
for (String bootstrapClassName : bootstrapClasses) {
try {
SelendroidLogger.info("Running afterApplicationCreate bootstrap: " + bootstrapClassName);
loadBootstrap(bootstrapClassName).runAfterApplicationCreate(instrumentation);
SelendroidLogger.info("\"Running afterApplicationCreate bootstrap: " + bootstrapClassName);
} catch (Exception e) {
throw new SelendroidException(
"Cannot run bootstrap " + bootstrapClassName, e);
}
}
} } | public class class_name {
public void runAfterApplicationCreateBootstrap(
Instrumentation instrumentation, String[] bootstrapClasses) {
if (!isWithExtension) {
SelendroidLogger.error("Cannot run bootstrap. Must load an extension first."); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
for (String bootstrapClassName : bootstrapClasses) {
try {
SelendroidLogger.info("Running afterApplicationCreate bootstrap: " + bootstrapClassName); // depends on control dependency: [try], data = [none]
loadBootstrap(bootstrapClassName).runAfterApplicationCreate(instrumentation); // depends on control dependency: [try], data = [none]
SelendroidLogger.info("\"Running afterApplicationCreate bootstrap: " + bootstrapClassName); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SelendroidException(
"Cannot run bootstrap " + bootstrapClassName, e);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public int write(String words) {
if (mode.isWritable() == false)
throw new IllegalStateException("IOError: not opened for writing");
try {
raFile.write(words.getBytes());
} catch (IOException e) {
logger.log(Level.SEVERE, null, e);
throw new RuntimeException(e);
}
return words.getBytes().length;
} } | public class class_name {
public int write(String words) {
if (mode.isWritable() == false)
throw new IllegalStateException("IOError: not opened for writing");
try {
raFile.write(words.getBytes()); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
logger.log(Level.SEVERE, null, e);
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
return words.getBytes().length;
} } |
public class class_name {
@Override
public FatLfnDirectoryEntry getEntry(String name) {
name = name.trim().toLowerCase(Locale.ROOT);
final FatLfnDirectoryEntry entry = longNameIndex.get(name);
if (entry == null) {
if (!ShortName.canConvert(name)) return null;
return shortNameIndex.get(ShortName.get(name));
} else {
return entry;
}
} } | public class class_name {
@Override
public FatLfnDirectoryEntry getEntry(String name) {
name = name.trim().toLowerCase(Locale.ROOT);
final FatLfnDirectoryEntry entry = longNameIndex.get(name);
if (entry == null) {
if (!ShortName.canConvert(name)) return null;
return shortNameIndex.get(ShortName.get(name)); // depends on control dependency: [if], data = [none]
} else {
return entry; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public double getRequstURIPath(String prefix, double defvalue) {
String val = getRequstURIPath(prefix, null);
try {
return val == null ? defvalue : Double.parseDouble(val);
} catch (NumberFormatException e) {
return defvalue;
}
} } | public class class_name {
public double getRequstURIPath(String prefix, double defvalue) {
String val = getRequstURIPath(prefix, null);
try {
return val == null ? defvalue : Double.parseDouble(val);
// depends on control dependency: [try], data = [none]
} catch (NumberFormatException e) {
return defvalue;
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static String[] splitWithCommaOrSemicolon(String src) {
if (isEmpty(src)) {
return StringUtils.EMPTY_STRING_ARRAY;
}
String[] ss = split(src.replace(',', ';'), ";");
List<String> list = new ArrayList<String>();
for (String s : ss) {
if (!isBlank(s)) {
list.add(s.trim());
}
}
return list.toArray(new String[list.size()]);
} } | public class class_name {
public static String[] splitWithCommaOrSemicolon(String src) {
if (isEmpty(src)) {
return StringUtils.EMPTY_STRING_ARRAY; // depends on control dependency: [if], data = [none]
}
String[] ss = split(src.replace(',', ';'), ";");
List<String> list = new ArrayList<String>();
for (String s : ss) {
if (!isBlank(s)) {
list.add(s.trim()); // depends on control dependency: [if], data = [none]
}
}
return list.toArray(new String[list.size()]);
} } |
public class class_name {
protected Cooccurrence filterCooccurence(JCas jCas, Annotation enclosingAnnot,
Annotation annot1, Annotation annot2, String[] ids1, String[] ids2) {
if (annot1.getAddress() < annot2.getAddress()) {
return super.filterCooccurence(jCas, enclosingAnnot, annot1, annot2, ids1,
ids2);
} else {
return null;
}
} } | public class class_name {
protected Cooccurrence filterCooccurence(JCas jCas, Annotation enclosingAnnot,
Annotation annot1, Annotation annot2, String[] ids1, String[] ids2) {
if (annot1.getAddress() < annot2.getAddress()) {
return super.filterCooccurence(jCas, enclosingAnnot, annot1, annot2, ids1,
ids2); // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void marshall(StartGameSessionPlacementRequest startGameSessionPlacementRequest, ProtocolMarshaller protocolMarshaller) {
if (startGameSessionPlacementRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(startGameSessionPlacementRequest.getPlacementId(), PLACEMENTID_BINDING);
protocolMarshaller.marshall(startGameSessionPlacementRequest.getGameSessionQueueName(), GAMESESSIONQUEUENAME_BINDING);
protocolMarshaller.marshall(startGameSessionPlacementRequest.getGameProperties(), GAMEPROPERTIES_BINDING);
protocolMarshaller.marshall(startGameSessionPlacementRequest.getMaximumPlayerSessionCount(), MAXIMUMPLAYERSESSIONCOUNT_BINDING);
protocolMarshaller.marshall(startGameSessionPlacementRequest.getGameSessionName(), GAMESESSIONNAME_BINDING);
protocolMarshaller.marshall(startGameSessionPlacementRequest.getPlayerLatencies(), PLAYERLATENCIES_BINDING);
protocolMarshaller.marshall(startGameSessionPlacementRequest.getDesiredPlayerSessions(), DESIREDPLAYERSESSIONS_BINDING);
protocolMarshaller.marshall(startGameSessionPlacementRequest.getGameSessionData(), GAMESESSIONDATA_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(StartGameSessionPlacementRequest startGameSessionPlacementRequest, ProtocolMarshaller protocolMarshaller) {
if (startGameSessionPlacementRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(startGameSessionPlacementRequest.getPlacementId(), PLACEMENTID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(startGameSessionPlacementRequest.getGameSessionQueueName(), GAMESESSIONQUEUENAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(startGameSessionPlacementRequest.getGameProperties(), GAMEPROPERTIES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(startGameSessionPlacementRequest.getMaximumPlayerSessionCount(), MAXIMUMPLAYERSESSIONCOUNT_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(startGameSessionPlacementRequest.getGameSessionName(), GAMESESSIONNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(startGameSessionPlacementRequest.getPlayerLatencies(), PLAYERLATENCIES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(startGameSessionPlacementRequest.getDesiredPlayerSessions(), DESIREDPLAYERSESSIONS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(startGameSessionPlacementRequest.getGameSessionData(), GAMESESSIONDATA_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private static URI asRefBase( JsonString uri)
{
try
{
return
uri == null
? null
: new URI( uri.getChars().toString());
}
catch( Exception e)
{
throw new ProjectException( String.format( "Error defining reference base=%s", uri), e);
}
} } | public class class_name {
private static URI asRefBase( JsonString uri)
{
try
{
return
uri == null
? null
: new URI( uri.getChars().toString()); // depends on control dependency: [try], data = [none]
}
catch( Exception e)
{
throw new ProjectException( String.format( "Error defining reference base=%s", uri), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void setOtaUpdates(java.util.Collection<OTAUpdateSummary> otaUpdates) {
if (otaUpdates == null) {
this.otaUpdates = null;
return;
}
this.otaUpdates = new java.util.ArrayList<OTAUpdateSummary>(otaUpdates);
} } | public class class_name {
public void setOtaUpdates(java.util.Collection<OTAUpdateSummary> otaUpdates) {
if (otaUpdates == null) {
this.otaUpdates = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.otaUpdates = new java.util.ArrayList<OTAUpdateSummary>(otaUpdates);
} } |
public class class_name {
public static ZonedDateTime toDateTime(Object value, EvaluationContext ctx) {
if (value instanceof String) {
Temporal temporal = ctx.getDateParser().auto((String) value);
if (temporal != null) {
return toDateTime(temporal, ctx);
}
}
else if (value instanceof LocalDate) {
return ((LocalDate) value).atStartOfDay(ctx.getTimezone());
}
else if (value instanceof ZonedDateTime) {
return ((ZonedDateTime) value).withZoneSameInstant(ctx.getTimezone());
}
throw new EvaluationError("Can't convert '" + value + "' to a datetime");
} } | public class class_name {
public static ZonedDateTime toDateTime(Object value, EvaluationContext ctx) {
if (value instanceof String) {
Temporal temporal = ctx.getDateParser().auto((String) value);
if (temporal != null) {
return toDateTime(temporal, ctx); // depends on control dependency: [if], data = [(temporal]
}
}
else if (value instanceof LocalDate) {
return ((LocalDate) value).atStartOfDay(ctx.getTimezone()); // depends on control dependency: [if], data = [none]
}
else if (value instanceof ZonedDateTime) {
return ((ZonedDateTime) value).withZoneSameInstant(ctx.getTimezone()); // depends on control dependency: [if], data = [none]
}
throw new EvaluationError("Can't convert '" + value + "' to a datetime");
} } |
public class class_name {
@Override
protected void perform(final Wave wave) throws CommandException {
// Get the undo/redo flag to know which action to perform
if (wave.contains(UndoRedoWaves.UNDO_REDO)) {
// The flag is true perform undo action
if (wave.get(UndoRedoWaves.UNDO_REDO)) {
undo();
} else {
// The flag is false perform redo action
redo();
}
} else {
// If the flag is not set we must initialize the command
init(wave);
// Get existing wave data
final List<WaveData<?>> data = wave.waveDatas();
// and add the undoable command
data.add(WBuilder.waveData(UndoRedoWaves.UNDOABLE_COMMAND, this));
// in order to register it into the right command stack
callCommand(StackUpCommand.class, data.toArray(new WaveDataBase[data.size()]));
}
} } | public class class_name {
@Override
protected void perform(final Wave wave) throws CommandException {
// Get the undo/redo flag to know which action to perform
if (wave.contains(UndoRedoWaves.UNDO_REDO)) {
// The flag is true perform undo action
if (wave.get(UndoRedoWaves.UNDO_REDO)) {
undo();
// depends on control dependency: [if], data = [none]
} else {
// The flag is false perform redo action
redo();
// depends on control dependency: [if], data = [none]
}
} else {
// If the flag is not set we must initialize the command
init(wave);
// Get existing wave data
final List<WaveData<?>> data = wave.waveDatas();
// and add the undoable command
data.add(WBuilder.waveData(UndoRedoWaves.UNDOABLE_COMMAND, this));
// in order to register it into the right command stack
callCommand(StackUpCommand.class, data.toArray(new WaveDataBase[data.size()]));
}
} } |
public class class_name {
public boolean acquire(final Lock lock) {
lock.setUniqueId(this.uniqueId);
if (this.lockTimeout > 0) {
lock.setExpirationDate(ZonedDateTime.now(ZoneOffset.UTC).plusSeconds(this.lockTimeout));
} else {
lock.setExpirationDate(null);
}
var success = false;
try {
if (lock.getApplicationId() != null) {
this.entityManager.merge(lock);
} else {
lock.setApplicationId(this.applicationId);
this.entityManager.persist(lock);
}
success = true;
} catch (final Exception e) {
success = false;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[{}] could not obtain [{}] lock.", this.uniqueId, this.applicationId, e);
} else {
LOGGER.info("[{}] could not obtain [{}] lock.", this.uniqueId, this.applicationId);
}
}
return success;
} } | public class class_name {
public boolean acquire(final Lock lock) {
lock.setUniqueId(this.uniqueId);
if (this.lockTimeout > 0) {
lock.setExpirationDate(ZonedDateTime.now(ZoneOffset.UTC).plusSeconds(this.lockTimeout)); // depends on control dependency: [if], data = [(this.lockTimeout]
} else {
lock.setExpirationDate(null); // depends on control dependency: [if], data = [none]
}
var success = false;
try {
if (lock.getApplicationId() != null) {
this.entityManager.merge(lock); // depends on control dependency: [if], data = [none]
} else {
lock.setApplicationId(this.applicationId); // depends on control dependency: [if], data = [none]
this.entityManager.persist(lock); // depends on control dependency: [if], data = [none]
}
success = true; // depends on control dependency: [try], data = [none]
} catch (final Exception e) {
success = false;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[{}] could not obtain [{}] lock.", this.uniqueId, this.applicationId, e); // depends on control dependency: [if], data = [none]
} else {
LOGGER.info("[{}] could not obtain [{}] lock.", this.uniqueId, this.applicationId); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
return success;
} } |
public class class_name {
final void setJarFileUrls(List<String> jarFilePaths, JPAPXml pxml) {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "setJarFileUrls: root=" + ivPUnitRootURL.toExternalForm());
// 6.2.1.6 mapping-file, jar-file, class, exclude-unlisted-classes
//
// One or more JAR files may be specified using the jar-file elements instead of, or in
// addition to the mapping files specified in the mapping-file elements. If specified,
// these JAR files will be searched for managed persistence classes, and any mapping
// metadata annotations found on them will be processed, or they will be mapped using
// the mapping annotation defaults defined by this specification. Such JAR files are
// specified relative to the root of the persistence unit (e.g., utils/myUtils.jar).
//
// Note: See defect 413031 details for clarifications by spec owner regarding
// "relative to the root of the persistence unit" semantics
// The following code will loop through all entries in the <jar-file> stanza in
// the persistence.xml and determine the URL to the jar file regardless of whether
// we are running in standard or RAD/loose-config environments.
ivJarFileURLs.clear();
for (String jarFilePath : jarFilePaths) {
if (!addJarFileUrls(trim(jarFilePath), pxml)) {
Tr.error(tc, "INCORRECT_PU_JARFILE_URL_SPEC_CWWJP0024E", jarFilePath, getPersistenceUnitName());
}
}
if (isTraceOn && tc.isEntryEnabled()) {
URL[] allURLs = ivJarFileURLs.toArray(new URL[0]);
Tr.exit(tc, "setJarFileUrls : " + Arrays.toString(allURLs));
}
} } | public class class_name {
final void setJarFileUrls(List<String> jarFilePaths, JPAPXml pxml) {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "setJarFileUrls: root=" + ivPUnitRootURL.toExternalForm());
// 6.2.1.6 mapping-file, jar-file, class, exclude-unlisted-classes
//
// One or more JAR files may be specified using the jar-file elements instead of, or in
// addition to the mapping files specified in the mapping-file elements. If specified,
// these JAR files will be searched for managed persistence classes, and any mapping
// metadata annotations found on them will be processed, or they will be mapped using
// the mapping annotation defaults defined by this specification. Such JAR files are
// specified relative to the root of the persistence unit (e.g., utils/myUtils.jar).
//
// Note: See defect 413031 details for clarifications by spec owner regarding
// "relative to the root of the persistence unit" semantics
// The following code will loop through all entries in the <jar-file> stanza in
// the persistence.xml and determine the URL to the jar file regardless of whether
// we are running in standard or RAD/loose-config environments.
ivJarFileURLs.clear();
for (String jarFilePath : jarFilePaths) {
if (!addJarFileUrls(trim(jarFilePath), pxml)) {
Tr.error(tc, "INCORRECT_PU_JARFILE_URL_SPEC_CWWJP0024E", jarFilePath, getPersistenceUnitName()); // depends on control dependency: [if], data = [none]
}
}
if (isTraceOn && tc.isEntryEnabled()) {
URL[] allURLs = ivJarFileURLs.toArray(new URL[0]);
Tr.exit(tc, "setJarFileUrls : " + Arrays.toString(allURLs)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public NumberExpression<Long> countDistinct() {
if (countDistinct == null) {
countDistinct = Expressions.numberOperation(Long.class, Ops.AggOps.COUNT_DISTINCT_AGG, mixin);
}
return countDistinct;
} } | public class class_name {
public NumberExpression<Long> countDistinct() {
if (countDistinct == null) {
countDistinct = Expressions.numberOperation(Long.class, Ops.AggOps.COUNT_DISTINCT_AGG, mixin); // depends on control dependency: [if], data = [none]
}
return countDistinct;
} } |
public class class_name {
private byte[] _requestRaw(@NonNull Method m, @NonNull String url, @Nullable Map<String, String> urlParameters, @Nullable String json, @NonNull List<String> hostsArray, int connectTimeout, int readTimeout, @Nullable RequestOptions requestOptions) throws AlgoliaException {
String requestMethod;
List<Exception> errors = new ArrayList<>(hostsArray.size());
// for each host
for (String host : hostsArray) {
switch (m) {
case DELETE:
requestMethod = "DELETE";
break;
case GET:
requestMethod = "GET";
break;
case POST:
requestMethod = "POST";
break;
case PUT:
requestMethod = "PUT";
break;
default:
throw new IllegalArgumentException("Method " + m + " is not supported");
}
InputStream stream = null;
HttpURLConnection hostConnection = null;
try {
// Compute final URL parameters.
final Map<String, String> parameters = new HashMap<>();
if (urlParameters != null) {
parameters.putAll(urlParameters);
}
if (requestOptions != null) {
parameters.putAll(requestOptions.urlParameters);
}
// Build URL.
String urlString = "https://" + host + url;
if (!parameters.isEmpty()) {
urlString += "?" + AbstractQuery.build(parameters);
}
URL hostURL = new URL(urlString);
// Open connection.
hostConnection = (HttpURLConnection) hostURL.openConnection();
//set timeouts
hostConnection.setRequestMethod(requestMethod);
hostConnection.setConnectTimeout(connectTimeout);
hostConnection.setReadTimeout(readTimeout);
// Headers
hostConnection.setRequestProperty("Accept-Encoding", "gzip");
hostConnection.setRequestProperty("X-Algolia-Application-Id", this.applicationID);
// If API key is too big, send it in the request's body (if applicable).
if (this.apiKey != null && this.apiKey.length() > MAX_API_KEY_LENGTH && json != null) {
try {
final JSONObject body = new JSONObject(json);
body.put("apiKey", this.apiKey);
json = body.toString();
} catch (JSONException e) {
throw new AlgoliaException("Failed to patch JSON body");
}
} else {
hostConnection.setRequestProperty("X-Algolia-API-Key", this.apiKey);
}
// Client-level headers
for (Map.Entry<String, String> entry : this.headers.entrySet()) {
hostConnection.setRequestProperty(entry.getKey(), entry.getValue());
}
// Request-level headers
if (requestOptions != null) {
for (Map.Entry<String, String> entry : requestOptions.headers.entrySet()) {
hostConnection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
// set user agent
hostConnection.setRequestProperty("User-Agent", userAgentRaw);
// write JSON entity
if (json != null) {
if (!(requestMethod.equals("PUT") || requestMethod.equals("POST"))) {
throw new IllegalArgumentException("Method " + m + " cannot enclose entity");
}
hostConnection.setRequestProperty("Content-type", "application/json; charset=UTF-8");
hostConnection.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(hostConnection.getOutputStream(), "UTF-8");
writer.write(json);
writer.close();
}
// read response
int code = hostConnection.getResponseCode();
final boolean codeIsError = code / 100 != 2;
stream = codeIsError ? hostConnection.getErrorStream() : hostConnection.getInputStream();
// As per the official Java docs (not the Android docs):
// - `getErrorStream()` may return null => we have to handle this case.
// See <https://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html#getErrorStream()>.
// - `getInputStream()` should never return null... but let's err on the side of caution.
// See <https://docs.oracle.com/javase/7/docs/api/java/net/URLConnection.html#getInputStream()>.
if (stream == null) {
throw new IOException(String.format("Null stream when reading connection (status %d)", code));
}
hostStatuses.put(host, new HostStatus(true));
final byte[] rawResponse;
String encoding = hostConnection.getContentEncoding();
if (encoding != null && encoding.equals("gzip")) {
rawResponse = _toByteArray(new GZIPInputStream(stream));
} else {
rawResponse = _toByteArray(stream);
}
// handle http errors
if (codeIsError) {
if (code / 100 == 4) {
consumeQuietly(hostConnection);
throw new AlgoliaException(_getJSONObject(rawResponse).getString("message"), code);
} else {
consumeQuietly(hostConnection);
errors.add(new AlgoliaException(_toCharArray(stream), code));
continue;
}
}
return rawResponse;
} catch (JSONException e) { // fatal
consumeQuietly(hostConnection);
throw new AlgoliaException("Invalid JSON returned by server", e);
} catch (UnsupportedEncodingException e) { // fatal
consumeQuietly(hostConnection);
throw new AlgoliaException("Invalid encoding returned by server", e);
} catch (IOException e) { // host error, continue on the next host
hostStatuses.put(host, new HostStatus(false));
consumeQuietly(hostConnection);
errors.add(e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
String errorMessage = "All hosts failed: " + Arrays.toString(errors.toArray());
// When several errors occurred, use the last one as the cause for the returned exception.
Throwable lastError = errors.get(errors.size() - 1);
throw new AlgoliaException(errorMessage, lastError);
} } | public class class_name {
private byte[] _requestRaw(@NonNull Method m, @NonNull String url, @Nullable Map<String, String> urlParameters, @Nullable String json, @NonNull List<String> hostsArray, int connectTimeout, int readTimeout, @Nullable RequestOptions requestOptions) throws AlgoliaException {
String requestMethod;
List<Exception> errors = new ArrayList<>(hostsArray.size());
// for each host
for (String host : hostsArray) {
switch (m) {
case DELETE:
requestMethod = "DELETE";
break;
case GET:
requestMethod = "GET";
break;
case POST:
requestMethod = "POST";
break;
case PUT:
requestMethod = "PUT";
break;
default:
throw new IllegalArgumentException("Method " + m + " is not supported");
}
InputStream stream = null;
HttpURLConnection hostConnection = null;
try {
// Compute final URL parameters.
final Map<String, String> parameters = new HashMap<>();
if (urlParameters != null) {
parameters.putAll(urlParameters); // depends on control dependency: [if], data = [(urlParameters]
}
if (requestOptions != null) {
parameters.putAll(requestOptions.urlParameters); // depends on control dependency: [if], data = [(requestOptions]
}
// Build URL.
String urlString = "https://" + host + url;
if (!parameters.isEmpty()) {
urlString += "?" + AbstractQuery.build(parameters);
}
URL hostURL = new URL(urlString);
// Open connection.
hostConnection = (HttpURLConnection) hostURL.openConnection(); // depends on control dependency: [try], data = [none]
//set timeouts
hostConnection.setRequestMethod(requestMethod); // depends on control dependency: [try], data = [none]
hostConnection.setConnectTimeout(connectTimeout); // depends on control dependency: [try], data = [none]
hostConnection.setReadTimeout(readTimeout); // depends on control dependency: [try], data = [none]
// Headers
hostConnection.setRequestProperty("Accept-Encoding", "gzip"); // depends on control dependency: [try], data = [none]
hostConnection.setRequestProperty("X-Algolia-Application-Id", this.applicationID); // depends on control dependency: [try], data = [none]
// If API key is too big, send it in the request's body (if applicable).
if (this.apiKey != null && this.apiKey.length() > MAX_API_KEY_LENGTH && json != null) {
try {
final JSONObject body = new JSONObject(json);
body.put("apiKey", this.apiKey); // depends on control dependency: [try], data = [none]
json = body.toString(); // depends on control dependency: [try], data = [none]
} catch (JSONException e) {
throw new AlgoliaException("Failed to patch JSON body");
} // depends on control dependency: [catch], data = [none]
} else {
hostConnection.setRequestProperty("X-Algolia-API-Key", this.apiKey); // depends on control dependency: [if], data = [none]
}
// Client-level headers
for (Map.Entry<String, String> entry : this.headers.entrySet()) {
hostConnection.setRequestProperty(entry.getKey(), entry.getValue()); // depends on control dependency: [for], data = [entry]
}
// Request-level headers
if (requestOptions != null) {
for (Map.Entry<String, String> entry : requestOptions.headers.entrySet()) {
hostConnection.setRequestProperty(entry.getKey(), entry.getValue()); // depends on control dependency: [for], data = [entry]
}
}
// set user agent
hostConnection.setRequestProperty("User-Agent", userAgentRaw); // depends on control dependency: [try], data = [none]
// write JSON entity
if (json != null) {
if (!(requestMethod.equals("PUT") || requestMethod.equals("POST"))) {
throw new IllegalArgumentException("Method " + m + " cannot enclose entity");
}
hostConnection.setRequestProperty("Content-type", "application/json; charset=UTF-8"); // depends on control dependency: [if], data = [none]
hostConnection.setDoOutput(true); // depends on control dependency: [if], data = [none]
OutputStreamWriter writer = new OutputStreamWriter(hostConnection.getOutputStream(), "UTF-8");
writer.write(json); // depends on control dependency: [if], data = [(json]
writer.close(); // depends on control dependency: [if], data = [none]
}
// read response
int code = hostConnection.getResponseCode();
final boolean codeIsError = code / 100 != 2;
stream = codeIsError ? hostConnection.getErrorStream() : hostConnection.getInputStream(); // depends on control dependency: [try], data = [none]
// As per the official Java docs (not the Android docs):
// - `getErrorStream()` may return null => we have to handle this case.
// See <https://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html#getErrorStream()>.
// - `getInputStream()` should never return null... but let's err on the side of caution.
// See <https://docs.oracle.com/javase/7/docs/api/java/net/URLConnection.html#getInputStream()>.
if (stream == null) {
throw new IOException(String.format("Null stream when reading connection (status %d)", code));
}
hostStatuses.put(host, new HostStatus(true)); // depends on control dependency: [try], data = [none]
final byte[] rawResponse;
String encoding = hostConnection.getContentEncoding();
if (encoding != null && encoding.equals("gzip")) {
rawResponse = _toByteArray(new GZIPInputStream(stream)); // depends on control dependency: [if], data = [none]
} else {
rawResponse = _toByteArray(stream); // depends on control dependency: [if], data = [none]
}
// handle http errors
if (codeIsError) {
if (code / 100 == 4) {
consumeQuietly(hostConnection); // depends on control dependency: [if], data = [none]
throw new AlgoliaException(_getJSONObject(rawResponse).getString("message"), code);
} else {
consumeQuietly(hostConnection); // depends on control dependency: [if], data = [none]
errors.add(new AlgoliaException(_toCharArray(stream), code)); // depends on control dependency: [if], data = [none]
continue;
}
}
return rawResponse; // depends on control dependency: [try], data = [none]
} catch (JSONException e) { // fatal
consumeQuietly(hostConnection);
throw new AlgoliaException("Invalid JSON returned by server", e);
} catch (UnsupportedEncodingException e) { // fatal // depends on control dependency: [catch], data = [none]
consumeQuietly(hostConnection);
throw new AlgoliaException("Invalid encoding returned by server", e);
} catch (IOException e) { // host error, continue on the next host // depends on control dependency: [catch], data = [none]
hostStatuses.put(host, new HostStatus(false));
consumeQuietly(hostConnection);
errors.add(e);
} finally { // depends on control dependency: [catch], data = [none]
if (stream != null) {
try {
stream.close(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
}
}
}
String errorMessage = "All hosts failed: " + Arrays.toString(errors.toArray());
// When several errors occurred, use the last one as the cause for the returned exception.
Throwable lastError = errors.get(errors.size() - 1);
throw new AlgoliaException(errorMessage, lastError);
} } |
public class class_name {
private void ensureIndex(DS session, EntityTypeMetadata<NodeMetadata<L>> entityTypeMetadata,
IndexedPropertyMethodMetadata<IndexedPropertyMetadata> indexedProperty) {
if (indexedProperty != null) {
IndexedPropertyMetadata datastoreMetadata = indexedProperty.getDatastoreMetadata();
if (datastoreMetadata.isCreate()) {
L label = entityTypeMetadata.getDatastoreMetadata().getDiscriminator();
PrimitivePropertyMethodMetadata<PropertyMetadata> propertyMethodMetadata = indexedProperty.getPropertyMethodMetadata();
if (label != null && propertyMethodMetadata != null) {
ensureIndex(session, label, propertyMethodMetadata, datastoreMetadata.isUnique());
}
}
}
} } | public class class_name {
private void ensureIndex(DS session, EntityTypeMetadata<NodeMetadata<L>> entityTypeMetadata,
IndexedPropertyMethodMetadata<IndexedPropertyMetadata> indexedProperty) {
if (indexedProperty != null) {
IndexedPropertyMetadata datastoreMetadata = indexedProperty.getDatastoreMetadata();
if (datastoreMetadata.isCreate()) {
L label = entityTypeMetadata.getDatastoreMetadata().getDiscriminator();
PrimitivePropertyMethodMetadata<PropertyMetadata> propertyMethodMetadata = indexedProperty.getPropertyMethodMetadata();
if (label != null && propertyMethodMetadata != null) {
ensureIndex(session, label, propertyMethodMetadata, datastoreMetadata.isUnique()); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
public T findMatch(Q key) {
Object[] keyArray = matchFields.stream().map(mf -> mf.extract(key)).toArray();
int ordinal = hpki.getMatchingOrdinal(keyArray);
if (ordinal == -1) {
return null;
}
return uniqueTypeExtractor.extract(api, ordinal);
} } | public class class_name {
public T findMatch(Q key) {
Object[] keyArray = matchFields.stream().map(mf -> mf.extract(key)).toArray();
int ordinal = hpki.getMatchingOrdinal(keyArray);
if (ordinal == -1) {
return null; // depends on control dependency: [if], data = [none]
}
return uniqueTypeExtractor.extract(api, ordinal);
} } |
public class class_name {
public static void setTopBodyForParentBody(TemplateDirectiveBodyOverrideWraper topBody,
TemplateDirectiveBodyOverrideWraper overrideBody) {
TemplateDirectiveBodyOverrideWraper parent = overrideBody;
while (parent.parentBody != null) {
parent = parent.parentBody;
}
parent.parentBody = topBody;
} } | public class class_name {
public static void setTopBodyForParentBody(TemplateDirectiveBodyOverrideWraper topBody,
TemplateDirectiveBodyOverrideWraper overrideBody) {
TemplateDirectiveBodyOverrideWraper parent = overrideBody;
while (parent.parentBody != null) {
parent = parent.parentBody; // depends on control dependency: [while], data = [none]
}
parent.parentBody = topBody;
} } |
public class class_name {
protected void createEntries(final MutableAcl acl) {
if (acl.getEntries().isEmpty()) {
return;
}
jdbcOperations.batchUpdate(insertEntry, new BatchPreparedStatementSetter() {
public int getBatchSize() {
return acl.getEntries().size();
}
public void setValues(PreparedStatement stmt, int i) throws SQLException {
AccessControlEntry entry_ = acl.getEntries().get(i);
Assert.isTrue(entry_ instanceof AccessControlEntryImpl,
"Unknown ACE class");
AccessControlEntryImpl entry = (AccessControlEntryImpl) entry_;
stmt.setLong(1, ((Long) acl.getId()).longValue());
stmt.setInt(2, i);
stmt.setLong(3, createOrRetrieveSidPrimaryKey(entry.getSid(), true)
.longValue());
stmt.setInt(4, entry.getPermission().getMask());
stmt.setBoolean(5, entry.isGranting());
stmt.setBoolean(6, entry.isAuditSuccess());
stmt.setBoolean(7, entry.isAuditFailure());
}
});
} } | public class class_name {
protected void createEntries(final MutableAcl acl) {
if (acl.getEntries().isEmpty()) {
return; // depends on control dependency: [if], data = [none]
}
jdbcOperations.batchUpdate(insertEntry, new BatchPreparedStatementSetter() {
public int getBatchSize() {
return acl.getEntries().size();
}
public void setValues(PreparedStatement stmt, int i) throws SQLException {
AccessControlEntry entry_ = acl.getEntries().get(i);
Assert.isTrue(entry_ instanceof AccessControlEntryImpl,
"Unknown ACE class");
AccessControlEntryImpl entry = (AccessControlEntryImpl) entry_;
stmt.setLong(1, ((Long) acl.getId()).longValue());
stmt.setInt(2, i);
stmt.setLong(3, createOrRetrieveSidPrimaryKey(entry.getSid(), true)
.longValue());
stmt.setInt(4, entry.getPermission().getMask());
stmt.setBoolean(5, entry.isGranting());
stmt.setBoolean(6, entry.isAuditSuccess());
stmt.setBoolean(7, entry.isAuditFailure());
}
});
} } |
public class class_name {
public static byte[] gzipUncompress(byte[] bytes) {
if (bytes == null || bytes.length == 0) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
try {
GZIPInputStream ungzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = ungzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
} catch (IOException e) {
}
return out.toByteArray();
} } | public class class_name {
public static byte[] gzipUncompress(byte[] bytes) {
if (bytes == null || bytes.length == 0) {
return null; // depends on control dependency: [if], data = [none]
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
try {
GZIPInputStream ungzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = ungzip.read(buffer)) >= 0) {
out.write(buffer, 0, n); // depends on control dependency: [while], data = [none]
}
} catch (IOException e) {
} // depends on control dependency: [catch], data = [none]
return out.toByteArray();
} } |
public class class_name {
public void setTransactItems(java.util.Collection<TransactWriteItem> transactItems) {
if (transactItems == null) {
this.transactItems = null;
return;
}
this.transactItems = new java.util.ArrayList<TransactWriteItem>(transactItems);
} } | public class class_name {
public void setTransactItems(java.util.Collection<TransactWriteItem> transactItems) {
if (transactItems == null) {
this.transactItems = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.transactItems = new java.util.ArrayList<TransactWriteItem>(transactItems);
} } |
public class class_name {
public AbstractBooleanList times(int times) {
AbstractBooleanList newList = new BooleanArrayList(times*size());
for (int i=times; --i >= 0; ) {
newList.addAllOfFromTo(this,0,size()-1);
}
return newList;
} } | public class class_name {
public AbstractBooleanList times(int times) {
AbstractBooleanList newList = new BooleanArrayList(times*size());
for (int i=times; --i >= 0; ) {
newList.addAllOfFromTo(this,0,size()-1);
// depends on control dependency: [for], data = [none]
}
return newList;
} } |
public class class_name {
public synchronized void addConnector(Connector connector) {
if (connector.getProtocolHandler() instanceof SipProtocolHandler) {
final SipStandardService sipService = this.sipService;
sipService.addConnector(connector);
}
} } | public class class_name {
public synchronized void addConnector(Connector connector) {
if (connector.getProtocolHandler() instanceof SipProtocolHandler) {
final SipStandardService sipService = this.sipService;
sipService.addConnector(connector); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Geometry getGeometryN(int n) {
if (isEmpty()) {
return null;
}
if (n >= 0 && n < points.length) {
return points[n];
}
throw new ArrayIndexOutOfBoundsException(n);
// return this;
} } | public class class_name {
public Geometry getGeometryN(int n) {
if (isEmpty()) {
return null; // depends on control dependency: [if], data = [none]
}
if (n >= 0 && n < points.length) {
return points[n]; // depends on control dependency: [if], data = [none]
}
throw new ArrayIndexOutOfBoundsException(n);
// return this;
} } |
public class class_name {
@Override
public void run() {
try {
try {
turnsControl.waitTurns(1, "Robot starting"); // block at the beginning so that all
// robots start at the
// same time
} catch (BankInterruptedException exc) {
log.trace("[run] Interrupted before starting");
}
assert getData().isEnabled() : "Robot is disabled";
mainLoop();
log.debug("[run] Robot terminated gracefully");
} catch (Exception | Error all) {
log.error("[run] Problem running robot " + this, all);
die("Execution Error -- " + all);
}
} } | public class class_name {
@Override
public void run() {
try {
try {
turnsControl.waitTurns(1, "Robot starting"); // block at the beginning so that all // depends on control dependency: [try], data = [none]
// robots start at the
// same time
} catch (BankInterruptedException exc) {
log.trace("[run] Interrupted before starting");
} // depends on control dependency: [catch], data = [none]
assert getData().isEnabled() : "Robot is disabled";
mainLoop();
log.debug("[run] Robot terminated gracefully");
} catch (Exception | Error all) {
log.error("[run] Problem running robot " + this, all);
die("Execution Error -- " + all);
}
} } |
public class class_name {
@SuppressWarnings("PMD.SimplifyBooleanReturns")
private boolean differentAttributes(Method m1, Method m2) {
if (m1.getAnnotationEntries().length > 0 || m2.getAnnotationEntries().length > 0) {
return true;
}
int access1 = m1.getAccessFlags()
& (Const.ACC_PRIVATE | Const.ACC_PROTECTED | Const.ACC_PUBLIC | Const.ACC_FINAL);
int access2 = m2.getAccessFlags()
& (Const.ACC_PRIVATE | Const.ACC_PROTECTED | Const.ACC_PUBLIC | Const.ACC_FINAL);
m1.getAnnotationEntries();
if (access1 != access2) {
return true;
}
if (!thrownExceptions(m1).equals(thrownExceptions(m2))) {
return false;
}
return false;
} } | public class class_name {
@SuppressWarnings("PMD.SimplifyBooleanReturns")
private boolean differentAttributes(Method m1, Method m2) {
if (m1.getAnnotationEntries().length > 0 || m2.getAnnotationEntries().length > 0) {
return true; // depends on control dependency: [if], data = [none]
}
int access1 = m1.getAccessFlags()
& (Const.ACC_PRIVATE | Const.ACC_PROTECTED | Const.ACC_PUBLIC | Const.ACC_FINAL);
int access2 = m2.getAccessFlags()
& (Const.ACC_PRIVATE | Const.ACC_PROTECTED | Const.ACC_PUBLIC | Const.ACC_FINAL);
m1.getAnnotationEntries();
if (access1 != access2) {
return true; // depends on control dependency: [if], data = [none]
}
if (!thrownExceptions(m1).equals(thrownExceptions(m2))) {
return false; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
@Override
public final void processData(RD dataHolder) throws VectorPrintException, DocumentException {
if (dataHolder == null) {
throw new VectorPrintException("No data to process, does your DataCollector return a ReportDataHolder? Or perhaps you should override createReportBody if don't use a DataCollector.");
}
Deque containers = new LinkedList();
Datamappingstype dmt = null;
if (settings.containsKey(ReportConstants.DATAMAPPINGXML)) {
try {
dmt = DatamappingHelper.fromXML(
new InputStreamReader(
settings.getURLProperty(null, ReportConstants.DATAMAPPINGXML).openStream()
)
);
} catch (JAXBException ex) {
throw new VectorPrintException(ex);
} catch (MalformedURLException ex) {
throw new VectorPrintException(ex);
} catch (IOException ex) {
throw new VectorPrintException(ex);
}
}
if (dataHolder.getData() instanceof BlockingQueue) {
try {
BlockingQueue<IdData> bq = (BlockingQueue<IdData>) dataHolder.getData();
Object o;
IdData dw;
/*
* wait for data in a blocking way
*/
while ((dw = bq.take()) != null) {
o = dw.getData();
if (QUEUECONTROL.END.equals(o)) {
break;
} else if (o instanceof Throwable) {
throw new VectorPrintException((Throwable) o);
}
processDataObject(dw, containers, dmt);
}
} catch (InterruptedException ex) {
throw new VectorPrintException(ex);
}
} else {
IdData dw;
while ((dw = (IdData) dataHolder.getData().poll()) != null) {
processDataObject(dw, containers, dmt);
}
}
// process any containers not added to the document yet
if (!containers.isEmpty()) {
if (containers.getLast() instanceof Element) {
document.add((Element) containers.getLast());
} else {
throw new VectorPrintException(String.format("don't know what to do with container %s", containers.getLast().getClass().getName()));
}
}
} } | public class class_name {
@Override
public final void processData(RD dataHolder) throws VectorPrintException, DocumentException {
if (dataHolder == null) {
throw new VectorPrintException("No data to process, does your DataCollector return a ReportDataHolder? Or perhaps you should override createReportBody if don't use a DataCollector.");
}
Deque containers = new LinkedList();
Datamappingstype dmt = null;
if (settings.containsKey(ReportConstants.DATAMAPPINGXML)) {
try {
dmt = DatamappingHelper.fromXML(
new InputStreamReader(
settings.getURLProperty(null, ReportConstants.DATAMAPPINGXML).openStream()
)
); // depends on control dependency: [try], data = [none]
} catch (JAXBException ex) {
throw new VectorPrintException(ex);
} catch (MalformedURLException ex) { // depends on control dependency: [catch], data = [none]
throw new VectorPrintException(ex);
} catch (IOException ex) { // depends on control dependency: [catch], data = [none]
throw new VectorPrintException(ex);
} // depends on control dependency: [catch], data = [none]
}
if (dataHolder.getData() instanceof BlockingQueue) {
try {
BlockingQueue<IdData> bq = (BlockingQueue<IdData>) dataHolder.getData();
Object o;
IdData dw;
/*
* wait for data in a blocking way
*/
while ((dw = bq.take()) != null) {
o = dw.getData(); // depends on control dependency: [while], data = [none]
if (QUEUECONTROL.END.equals(o)) {
break;
} else if (o instanceof Throwable) {
throw new VectorPrintException((Throwable) o);
}
processDataObject(dw, containers, dmt); // depends on control dependency: [while], data = [none]
}
} catch (InterruptedException ex) {
throw new VectorPrintException(ex);
} // depends on control dependency: [catch], data = [none]
} else {
IdData dw;
while ((dw = (IdData) dataHolder.getData().poll()) != null) {
processDataObject(dw, containers, dmt); // depends on control dependency: [while], data = [none]
}
}
// process any containers not added to the document yet
if (!containers.isEmpty()) {
if (containers.getLast() instanceof Element) {
document.add((Element) containers.getLast());
} else {
throw new VectorPrintException(String.format("don't know what to do with container %s", containers.getLast().getClass().getName()));
}
}
} } |
public class class_name {
public void addWithLeftMargin(E tabContent, String tabName) {
tabContent.addStyleName(I_CmsLayoutBundle.INSTANCE.generalCss().cornerAll());
m_tabPanel.add(tabContent, CmsDomUtil.stripHtml(tabName));
int tabIndex = m_tabPanel.getWidgetIndex(tabContent);
Element tabElement = getTabElement(tabIndex);
if (tabElement != null) {
tabElement.addClassName(I_CmsLayoutBundle.INSTANCE.tabbedPanelCss().tabLeftMargin());
if (!m_panelStyle.equals(CmsTabbedPanelStyle.classicTabs)) {
tabElement.addClassName(I_CmsLayoutBundle.INSTANCE.generalCss().buttonCornerAll());
tabElement.addClassName(I_CmsLayoutBundle.INSTANCE.tabbedPanelCss().borderAll());
}
}
m_tabPanel.checkTabOverflow();
} } | public class class_name {
public void addWithLeftMargin(E tabContent, String tabName) {
tabContent.addStyleName(I_CmsLayoutBundle.INSTANCE.generalCss().cornerAll());
m_tabPanel.add(tabContent, CmsDomUtil.stripHtml(tabName));
int tabIndex = m_tabPanel.getWidgetIndex(tabContent);
Element tabElement = getTabElement(tabIndex);
if (tabElement != null) {
tabElement.addClassName(I_CmsLayoutBundle.INSTANCE.tabbedPanelCss().tabLeftMargin()); // depends on control dependency: [if], data = [none]
if (!m_panelStyle.equals(CmsTabbedPanelStyle.classicTabs)) {
tabElement.addClassName(I_CmsLayoutBundle.INSTANCE.generalCss().buttonCornerAll()); // depends on control dependency: [if], data = [none]
tabElement.addClassName(I_CmsLayoutBundle.INSTANCE.tabbedPanelCss().borderAll()); // depends on control dependency: [if], data = [none]
}
}
m_tabPanel.checkTabOverflow();
} } |
public class class_name {
public void updateBannerInstructionsWith(Milestone milestone) {
if (milestone instanceof BannerInstructionMilestone) {
BannerInstructions instructions = ((BannerInstructionMilestone) milestone).getBannerInstructions();
if (instructions == null || instructions.primary() == null) {
return;
}
BannerText primary = instructions.primary();
String primaryManeuverModifier = primary.modifier();
updateManeuverView(primary.type(), primaryManeuverModifier, primary.degrees());
updateDataFromBannerText(primary, instructions.secondary());
updateSubStep(instructions.sub(), primaryManeuverModifier);
}
} } | public class class_name {
public void updateBannerInstructionsWith(Milestone milestone) {
if (milestone instanceof BannerInstructionMilestone) {
BannerInstructions instructions = ((BannerInstructionMilestone) milestone).getBannerInstructions();
if (instructions == null || instructions.primary() == null) {
return; // depends on control dependency: [if], data = [none]
}
BannerText primary = instructions.primary();
String primaryManeuverModifier = primary.modifier();
updateManeuverView(primary.type(), primaryManeuverModifier, primary.degrees()); // depends on control dependency: [if], data = [none]
updateDataFromBannerText(primary, instructions.secondary()); // depends on control dependency: [if], data = [none]
updateSubStep(instructions.sub(), primaryManeuverModifier); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public TabularResult process(final InputStream inputStream, final Request request) {
CSVReader reader = new CSVReader(new InputStreamReader(inputStream));
try {
String[] headerRow = reader.readNext();
if (headerRow != null) {
HeaderDefinition headerDef = HeaderDefinition.of(Arrays.asList(headerRow));
List<Row> rows = new ArrayList<Row>();
String[] next = reader.readNext();
while (next != null) {
if (next.length > headerRow.length) {
// This row is not the same length as the header row, record how long it is so we can patch in a longer header afterwards.
String[] stretchedHeaderRow = new String[next.length];
System.arraycopy(headerRow, 0, stretchedHeaderRow, 0, headerRow.length);
for (int i = headerRow.length; i < next.length; i++) {
stretchedHeaderRow[i] = "Column " + i;
}
headerRow = stretchedHeaderRow;
headerDef = HeaderDefinition.of(Arrays.asList(headerRow)); // create a new header with the extended column labels.
// NOTE: we DON'T go back and patch rows that we've already created. This is because the only case the header is used is
// to look up rows by name, and given those rows don't contain data for those columns, the logic in Row now just returns
// null in that case (the case where you ask for a row that isn't present).
}
Row row = Row.of(headerDef, next);
rows.add(row);
next = reader.readNext();
}
reader.close();
return TabularResult.of(headerDef, rows);
} else {
reader.close();
throw new QuandlRuntimeException("No data returned");
}
} catch (IOException ioe) {
throw new QuandlRuntimeException("Error reading input stream", ioe);
}
} } | public class class_name {
public TabularResult process(final InputStream inputStream, final Request request) {
CSVReader reader = new CSVReader(new InputStreamReader(inputStream));
try {
String[] headerRow = reader.readNext();
if (headerRow != null) {
HeaderDefinition headerDef = HeaderDefinition.of(Arrays.asList(headerRow));
List<Row> rows = new ArrayList<Row>();
String[] next = reader.readNext();
while (next != null) {
if (next.length > headerRow.length) {
// This row is not the same length as the header row, record how long it is so we can patch in a longer header afterwards.
String[] stretchedHeaderRow = new String[next.length];
System.arraycopy(headerRow, 0, stretchedHeaderRow, 0, headerRow.length); // depends on control dependency: [if], data = [headerRow.length)]
for (int i = headerRow.length; i < next.length; i++) {
stretchedHeaderRow[i] = "Column " + i; // depends on control dependency: [for], data = [i]
}
headerRow = stretchedHeaderRow; // depends on control dependency: [if], data = [none]
headerDef = HeaderDefinition.of(Arrays.asList(headerRow)); // create a new header with the extended column labels. // depends on control dependency: [if], data = [none]
// NOTE: we DON'T go back and patch rows that we've already created. This is because the only case the header is used is
// to look up rows by name, and given those rows don't contain data for those columns, the logic in Row now just returns
// null in that case (the case where you ask for a row that isn't present).
}
Row row = Row.of(headerDef, next);
rows.add(row); // depends on control dependency: [while], data = [none]
next = reader.readNext(); // depends on control dependency: [while], data = [none]
}
reader.close(); // depends on control dependency: [if], data = [none]
return TabularResult.of(headerDef, rows); // depends on control dependency: [if], data = [none]
} else {
reader.close(); // depends on control dependency: [if], data = [none]
throw new QuandlRuntimeException("No data returned");
}
} catch (IOException ioe) {
throw new QuandlRuntimeException("Error reading input stream", ioe);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void setChainPolicy(String policyStr) {
if (policyStr.equalsIgnoreCase(ACCEPT_ON_MATCH)) {
matchReturnValue = ACCEPT;
noMatchReturnValue = NEUTRAL;
} else if (policyStr.equalsIgnoreCase(DENY_ON_MATCH)) {
matchReturnValue = DENY;
noMatchReturnValue = NEUTRAL;
} else if (policyStr.equalsIgnoreCase(ACCEPT_ON_NOMATCH)) {
matchReturnValue = NEUTRAL;
noMatchReturnValue = ACCEPT;
} else if (policyStr.equalsIgnoreCase(DENY_ON_NOMATCH)) {
matchReturnValue = NEUTRAL;
noMatchReturnValue = DENY;
} else {
LogLog.error("invalid chainPolicy: " + policyStr);
}
} } | public class class_name {
public void setChainPolicy(String policyStr) {
if (policyStr.equalsIgnoreCase(ACCEPT_ON_MATCH)) {
matchReturnValue = ACCEPT; // depends on control dependency: [if], data = [none]
noMatchReturnValue = NEUTRAL; // depends on control dependency: [if], data = [none]
} else if (policyStr.equalsIgnoreCase(DENY_ON_MATCH)) {
matchReturnValue = DENY; // depends on control dependency: [if], data = [none]
noMatchReturnValue = NEUTRAL; // depends on control dependency: [if], data = [none]
} else if (policyStr.equalsIgnoreCase(ACCEPT_ON_NOMATCH)) {
matchReturnValue = NEUTRAL; // depends on control dependency: [if], data = [none]
noMatchReturnValue = ACCEPT; // depends on control dependency: [if], data = [none]
} else if (policyStr.equalsIgnoreCase(DENY_ON_NOMATCH)) {
matchReturnValue = NEUTRAL; // depends on control dependency: [if], data = [none]
noMatchReturnValue = DENY; // depends on control dependency: [if], data = [none]
} else {
LogLog.error("invalid chainPolicy: " + policyStr); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void actionCommit() {
List<Throwable> errors = new ArrayList<Throwable>();
try {
// if new create it first
if (isNewUser()) {
// test the group name
CmsGroup group = null;
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(getGroup())) {
group = getCms().readGroup(getGroup());
}
if (group != null) {
if (group.getSimpleName().equals(OpenCms.getDefaultUsers().getGroupAdministrators())) {
// in case the administrators group is selected, the administrator role must be selected also
if (getRole().equals(NO_ROLE)) {
throw new CmsIllegalArgumentException(
Messages.get().container(Messages.ERR_ADD_TO_ADMINISTRATORS_GROUP_0));
}
CmsRole role = CmsRole.valueOfRoleName(getRole());
if (!CmsRole.ROOT_ADMIN.getRoleName().equals(role.getRoleName())
&& !CmsRole.ADMINISTRATOR.getRoleName().equals(role.getRoleName())) {
throw new CmsIllegalArgumentException(
Messages.get().container(Messages.ERR_ADD_TO_ADMINISTRATORS_GROUP_0));
}
} else if (group.getSimpleName().equals(OpenCms.getDefaultUsers().getGroupUsers())) {
// in case the users group is selected, the user should have at least one role
if (getRole().equals(NO_ROLE)) {
throw new CmsIllegalArgumentException(
Messages.get().container(Messages.ERR_ADD_TO_USERS_GROUP_0));
}
} else if (group.getSimpleName().equals(OpenCms.getDefaultUsers().getGroupGuests())) {
// in case the users group is selected, the user should have at least one role
if (!getRole().equals(NO_ROLE)) {
throw new CmsIllegalArgumentException(
Messages.get().container(Messages.ERR_ADD_TO_GUESTS_GROUP_0));
}
}
}
m_pwdInfo.validate();
CmsUser newUser = createUser(
m_paramOufqn + m_user.getSimpleName(),
m_pwdInfo.getNewPwd(),
m_user.getDescription(),
m_user.getAdditionalInfo());
newUser.setFirstname(m_user.getFirstname());
newUser.setLastname(m_user.getLastname());
newUser.setEmail(m_user.getEmail());
newUser.setAddress(m_user.getAddress());
newUser.setManaged(m_user.isManaged());
newUser.setEnabled(m_user.isEnabled());
m_user = newUser;
} else if (CmsStringUtil.isNotEmpty(m_pwdInfo.getNewPwd())) {
m_pwdInfo.validate();
getCms().setPassword(m_user.getName(), m_pwdInfo.getNewPwd());
}
// write the edited user
writeUser(m_user);
// set starting membership
if (isNewUser()) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(getGroup())) {
getCms().addUserToGroup(m_user.getName(), getGroup());
}
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(getRole()) && !getRole().equals(NO_ROLE)) {
OpenCms.getRoleManager().addUserToRole(
getCms(),
CmsRole.valueOfRoleName(getRole()).forOrgUnit(m_paramOufqn),
m_user.getName());
}
}
// set starting settings
CmsUserSettings settings = new CmsUserSettings(m_user);
settings.setLocale(CmsLocaleManager.getLocale(getLanguage()));
settings.setStartSite(getSite());
// set starting project
if (isNewUser()) {
settings.setStartProject(getParamOufqn() + getStartProject());
} else {
settings.setStartProject(getStartProject());
}
boolean webuserOu = false;
try {
webuserOu = OpenCms.getOrgUnitManager().readOrganizationalUnit(
getCms(),
getParamOufqn()).hasFlagWebuser();
} catch (CmsException e) {
// ignore
}
// only set the start folder for non web users
if (!webuserOu) {
CmsObject tmp = OpenCms.initCmsObject(getCms());
tmp.getRequestContext().setSiteRoot(getSite());
String folder = tmp.getRequestContext().removeSiteRoot(getStartFolder());
try {
CmsResource res = tmp.readResource(folder);
String siteRoot = OpenCms.getSiteManager().getSiteRoot(res.getRootPath());
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(siteRoot)
&& CmsStringUtil.isNotEmptyOrWhitespaceOnly(tmp.getRequestContext().getSiteRoot())
&& !tmp.getRequestContext().getSiteRoot().equals("/")) {
folder = res.getRootPath().substring(siteRoot.length());
}
} catch (CmsException e) {
throw new CmsIllegalArgumentException(
Messages.get().container(Messages.ERR_SELECTED_FOLDER_NOT_IN_SITE_0));
}
settings.setStartFolder(folder);
}
settings.setStartView(getStartView());
settings.save(getCms());
// refresh the list
Map<?, ?> objects = (Map<?, ?>)getSettings().getListObject();
if (objects != null) {
objects.remove(getListClass());
}
} catch (Throwable t) {
errors.add(t);
}
if (errors.isEmpty() && isNewUser()) {
if ((getParamCloseLink() != null) && (getParamCloseLink().indexOf("path=" + getListRootPath()) > -1)) {
// set closelink
Map<String, String[]> argMap = new HashMap<String, String[]>();
argMap.put(PARAM_USERID, new String[] {m_user.getId().toString()});
argMap.put("oufqn", new String[] {m_paramOufqn});
setParamCloseLink(CmsToolManager.linkForToolPath(getJsp(), getListRootPath() + "/edit", argMap));
}
}
// set the list of errors to display when saving failed
setCommitErrors(errors);
} } | public class class_name {
@Override
public void actionCommit() {
List<Throwable> errors = new ArrayList<Throwable>();
try {
// if new create it first
if (isNewUser()) {
// test the group name
CmsGroup group = null;
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(getGroup())) {
group = getCms().readGroup(getGroup()); // depends on control dependency: [if], data = [none]
}
if (group != null) {
if (group.getSimpleName().equals(OpenCms.getDefaultUsers().getGroupAdministrators())) {
// in case the administrators group is selected, the administrator role must be selected also
if (getRole().equals(NO_ROLE)) {
throw new CmsIllegalArgumentException(
Messages.get().container(Messages.ERR_ADD_TO_ADMINISTRATORS_GROUP_0));
}
CmsRole role = CmsRole.valueOfRoleName(getRole());
if (!CmsRole.ROOT_ADMIN.getRoleName().equals(role.getRoleName())
&& !CmsRole.ADMINISTRATOR.getRoleName().equals(role.getRoleName())) {
throw new CmsIllegalArgumentException(
Messages.get().container(Messages.ERR_ADD_TO_ADMINISTRATORS_GROUP_0));
}
} else if (group.getSimpleName().equals(OpenCms.getDefaultUsers().getGroupUsers())) {
// in case the users group is selected, the user should have at least one role
if (getRole().equals(NO_ROLE)) {
throw new CmsIllegalArgumentException(
Messages.get().container(Messages.ERR_ADD_TO_USERS_GROUP_0));
}
} else if (group.getSimpleName().equals(OpenCms.getDefaultUsers().getGroupGuests())) {
// in case the users group is selected, the user should have at least one role
if (!getRole().equals(NO_ROLE)) {
throw new CmsIllegalArgumentException(
Messages.get().container(Messages.ERR_ADD_TO_GUESTS_GROUP_0));
}
}
}
m_pwdInfo.validate(); // depends on control dependency: [if], data = [none]
CmsUser newUser = createUser(
m_paramOufqn + m_user.getSimpleName(),
m_pwdInfo.getNewPwd(),
m_user.getDescription(),
m_user.getAdditionalInfo());
newUser.setFirstname(m_user.getFirstname()); // depends on control dependency: [if], data = [none]
newUser.setLastname(m_user.getLastname()); // depends on control dependency: [if], data = [none]
newUser.setEmail(m_user.getEmail()); // depends on control dependency: [if], data = [none]
newUser.setAddress(m_user.getAddress()); // depends on control dependency: [if], data = [none]
newUser.setManaged(m_user.isManaged()); // depends on control dependency: [if], data = [none]
newUser.setEnabled(m_user.isEnabled()); // depends on control dependency: [if], data = [none]
m_user = newUser; // depends on control dependency: [if], data = [none]
} else if (CmsStringUtil.isNotEmpty(m_pwdInfo.getNewPwd())) {
m_pwdInfo.validate(); // depends on control dependency: [if], data = [none]
getCms().setPassword(m_user.getName(), m_pwdInfo.getNewPwd()); // depends on control dependency: [if], data = [none]
}
// write the edited user
writeUser(m_user); // depends on control dependency: [try], data = [none]
// set starting membership
if (isNewUser()) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(getGroup())) {
getCms().addUserToGroup(m_user.getName(), getGroup()); // depends on control dependency: [if], data = [none]
}
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(getRole()) && !getRole().equals(NO_ROLE)) {
OpenCms.getRoleManager().addUserToRole(
getCms(),
CmsRole.valueOfRoleName(getRole()).forOrgUnit(m_paramOufqn),
m_user.getName()); // depends on control dependency: [if], data = [none]
}
}
// set starting settings
CmsUserSettings settings = new CmsUserSettings(m_user);
settings.setLocale(CmsLocaleManager.getLocale(getLanguage())); // depends on control dependency: [try], data = [none]
settings.setStartSite(getSite()); // depends on control dependency: [try], data = [none]
// set starting project
if (isNewUser()) {
settings.setStartProject(getParamOufqn() + getStartProject()); // depends on control dependency: [if], data = [none]
} else {
settings.setStartProject(getStartProject()); // depends on control dependency: [if], data = [none]
}
boolean webuserOu = false;
try {
webuserOu = OpenCms.getOrgUnitManager().readOrganizationalUnit(
getCms(),
getParamOufqn()).hasFlagWebuser(); // depends on control dependency: [try], data = [none]
} catch (CmsException e) {
// ignore
} // depends on control dependency: [catch], data = [none]
// only set the start folder for non web users
if (!webuserOu) {
CmsObject tmp = OpenCms.initCmsObject(getCms());
tmp.getRequestContext().setSiteRoot(getSite()); // depends on control dependency: [if], data = [none]
String folder = tmp.getRequestContext().removeSiteRoot(getStartFolder());
try {
CmsResource res = tmp.readResource(folder);
String siteRoot = OpenCms.getSiteManager().getSiteRoot(res.getRootPath());
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(siteRoot)
&& CmsStringUtil.isNotEmptyOrWhitespaceOnly(tmp.getRequestContext().getSiteRoot())
&& !tmp.getRequestContext().getSiteRoot().equals("/")) {
folder = res.getRootPath().substring(siteRoot.length()); // depends on control dependency: [if], data = [none]
}
} catch (CmsException e) {
throw new CmsIllegalArgumentException(
Messages.get().container(Messages.ERR_SELECTED_FOLDER_NOT_IN_SITE_0));
} // depends on control dependency: [catch], data = [none]
settings.setStartFolder(folder); // depends on control dependency: [if], data = [none]
}
settings.setStartView(getStartView()); // depends on control dependency: [try], data = [none]
settings.save(getCms()); // depends on control dependency: [try], data = [none]
// refresh the list
Map<?, ?> objects = (Map<?, ?>)getSettings().getListObject(); // depends on control dependency: [try], data = [none] // depends on control dependency: [try], data = [none]
if (objects != null) {
objects.remove(getListClass()); // depends on control dependency: [if], data = [none]
}
} catch (Throwable t) {
errors.add(t);
} // depends on control dependency: [catch], data = [none]
if (errors.isEmpty() && isNewUser()) {
if ((getParamCloseLink() != null) && (getParamCloseLink().indexOf("path=" + getListRootPath()) > -1)) {
// set closelink
Map<String, String[]> argMap = new HashMap<String, String[]>();
argMap.put(PARAM_USERID, new String[] {m_user.getId().toString()}); // depends on control dependency: [if], data = [none]
argMap.put("oufqn", new String[] {m_paramOufqn}); // depends on control dependency: [if], data = [none]
setParamCloseLink(CmsToolManager.linkForToolPath(getJsp(), getListRootPath() + "/edit", argMap)); // depends on control dependency: [if], data = [none]
}
}
// set the list of errors to display when saving failed
setCommitErrors(errors);
} } |
public class class_name {
public String map(String name) {
String mapped = super.get(name);
if (mapped == null) {
mapped = String.format("%s%03d", BASENAME, count.incrementAndGet());
super.put(name, mapped);
}
return mapped;
} } | public class class_name {
public String map(String name) {
String mapped = super.get(name);
if (mapped == null) {
mapped = String.format("%s%03d", BASENAME, count.incrementAndGet()); // depends on control dependency: [if], data = [none]
super.put(name, mapped); // depends on control dependency: [if], data = [none]
}
return mapped;
} } |
public class class_name {
public void infer() {
scopes = StaticAnalysis.getScopes(expression);
expressionTypes = Maps.newHashMap();
constraints = ConstraintSet.empty();
for (Scope scope : scopes.getScopes()) {
for (String variable : scope.getBoundVariables()) {
int location = scope.getBindingIndex(variable);
if (!expressionTypes.containsKey(location)) {
expressionTypes.put(location, constraints.getFreshTypeVar());
}
}
}
populateExpressionTypes(0);
// TODO: root type.
solved = constraints.solve(typeDeclaration);
for (int k : expressionTypes.keySet()) {
expressionTypes.put(k, expressionTypes.get(k).substitute(solved.getBindings()));
}
} } | public class class_name {
public void infer() {
scopes = StaticAnalysis.getScopes(expression);
expressionTypes = Maps.newHashMap();
constraints = ConstraintSet.empty();
for (Scope scope : scopes.getScopes()) {
for (String variable : scope.getBoundVariables()) {
int location = scope.getBindingIndex(variable);
if (!expressionTypes.containsKey(location)) {
expressionTypes.put(location, constraints.getFreshTypeVar()); // depends on control dependency: [if], data = [none]
}
}
}
populateExpressionTypes(0);
// TODO: root type.
solved = constraints.solve(typeDeclaration);
for (int k : expressionTypes.keySet()) {
expressionTypes.put(k, expressionTypes.get(k).substitute(solved.getBindings())); // depends on control dependency: [for], data = [k]
}
} } |
public class class_name {
private AnnotationFS findCoverFS(CAS aCAS, AnnotationFS annot, Type coverFsType) {
// covering annotation
AnnotationFS coverFs = null;
// create a searchFS of the coverFsType with the annot boundaries to
// search for it.
FeatureStructure searchFs = aCAS.createAnnotation(coverFsType, annot.getBegin(), aCAS
.getDocumentText().length());
// get the coverFSType iterator from the CAS and move it "near" to the
// position of the created searchFS.
FSIterator<?> iterator = aCAS.getAnnotationIndex(coverFsType).iterator();
iterator.moveTo(searchFs);
// now the iterator can either point directly to the FS we are searching
// or it points to the next higher FS in the list. So we either have
// already found the correct one, of we maybe have to move the iterator to
// the previous position.
// check if the iterator at the current position is valid
if (iterator.isValid()) {
// iterator is valid, so we either have the correct annotation of we
// have to move to the
// previous one, lets check the current FS from the iterator
// get current FS
coverFs = (AnnotationFS) iterator.get();
// check if the coverFS covers the current match type annotation
if ((coverFs.getBegin() <= annot.getBegin()) && (coverFs.getEnd() >= annot.getEnd())) {
// we found the covering annotation
return coverFs;
}
// current coverFs does not cover the current match type annotation
// lets try to move iterator to the previous annotation and check
// again
iterator.moveToPrevious();
// check if the iterator is still valid after me move it to the
// previous FS
if (iterator.isValid()) {
// get FS
coverFs = (AnnotationFS) iterator.get();
// check the found coverFS covers the current match type
// annotation
if ((coverFs.getBegin() <= annot.getBegin()) && (coverFs.getEnd() >= annot.getEnd())) {
// we found the covering annotation
return coverFs;
}
}
}
// iterator is invalid lets try to move the iterator to the last FS and
// check the FS
iterator.moveToLast();
// check if the iterator is valid after we move it
if (iterator.isValid()) {
// get FS
coverFs = (AnnotationFS) iterator.get();
// check the found coverFS covers the current match type annotation
if ((coverFs.getBegin() <= annot.getBegin()) && (coverFs.getEnd() >= annot.getEnd())) {
// we found the covering annotation
return coverFs;
}
}
// no covering annotation found
return null;
} } | public class class_name {
private AnnotationFS findCoverFS(CAS aCAS, AnnotationFS annot, Type coverFsType) {
// covering annotation
AnnotationFS coverFs = null;
// create a searchFS of the coverFsType with the annot boundaries to
// search for it.
FeatureStructure searchFs = aCAS.createAnnotation(coverFsType, annot.getBegin(), aCAS
.getDocumentText().length());
// get the coverFSType iterator from the CAS and move it "near" to the
// position of the created searchFS.
FSIterator<?> iterator = aCAS.getAnnotationIndex(coverFsType).iterator();
iterator.moveTo(searchFs);
// now the iterator can either point directly to the FS we are searching
// or it points to the next higher FS in the list. So we either have
// already found the correct one, of we maybe have to move the iterator to
// the previous position.
// check if the iterator at the current position is valid
if (iterator.isValid()) {
// iterator is valid, so we either have the correct annotation of we
// have to move to the
// previous one, lets check the current FS from the iterator
// get current FS
coverFs = (AnnotationFS) iterator.get(); // depends on control dependency: [if], data = [none]
// check if the coverFS covers the current match type annotation
if ((coverFs.getBegin() <= annot.getBegin()) && (coverFs.getEnd() >= annot.getEnd())) {
// we found the covering annotation
return coverFs; // depends on control dependency: [if], data = [none]
}
// current coverFs does not cover the current match type annotation
// lets try to move iterator to the previous annotation and check
// again
iterator.moveToPrevious(); // depends on control dependency: [if], data = [none]
// check if the iterator is still valid after me move it to the
// previous FS
if (iterator.isValid()) {
// get FS
coverFs = (AnnotationFS) iterator.get(); // depends on control dependency: [if], data = [none]
// check the found coverFS covers the current match type
// annotation
if ((coverFs.getBegin() <= annot.getBegin()) && (coverFs.getEnd() >= annot.getEnd())) {
// we found the covering annotation
return coverFs; // depends on control dependency: [if], data = [none]
}
}
}
// iterator is invalid lets try to move the iterator to the last FS and
// check the FS
iterator.moveToLast();
// check if the iterator is valid after we move it
if (iterator.isValid()) {
// get FS
coverFs = (AnnotationFS) iterator.get(); // depends on control dependency: [if], data = [none]
// check the found coverFS covers the current match type annotation
if ((coverFs.getBegin() <= annot.getBegin()) && (coverFs.getEnd() >= annot.getEnd())) {
// we found the covering annotation
return coverFs; // depends on control dependency: [if], data = [none]
}
}
// no covering annotation found
return null;
} } |
public class class_name {
public static void injectContextProxiesAndApplication(AbstractResourceInfo cri,
Object instance,
Application app,
ProviderFactory factory) {
/** inject proxy for singleton only */
if (!cri.isSingleton())
return;
/** application inject has been done earlier. @see LibertyJaxRsServerFactoryBean.injectContextApplication() */
if (cri instanceof ApplicationInfo)
return;
JaxRsFactoryBeanCustomizer beanCustomizer = InjectionRuntimeContextHelper.findBeanCustomizer(instance.getClass(), cri.getBus());
Boolean isManagedBean = beanCustomizer == null ? false : true;
InjectionRuntimeContext irc = InjectionRuntimeContextHelper.getRuntimeContext();
synchronized (instance) {
for (Map.Entry<Class<?>, Method> entry : cri.getContextMethods().entrySet()) {
Method method = entry.getValue();
Object value = null;
Class<?> cls = method.getParameterTypes()[0];
if (cls == Application.class) {
value = app;
} else if (VALUE_CONTEXTS.contains(cls.getName()) && factory != null) {
ContextProvider<?> p = factory.createContextProvider(cls, null);
if (p != null) {
value = p.createContext(null);
}
} else {
value = cri.getContextSetterProxy(method);
}
if (isManagedBean)
irc.setRuntimeCtxObject(entry.getKey().getName(), value);
else
InjectionUtils.injectThroughMethod(instance, method, value);
}
for (Field f : cri.getContextFields()) {
Object value = null;
Class<?> cls = f.getType();
if (cls == Application.class) {
value = app;
} else if (VALUE_CONTEXTS.contains(cls.getName()) && factory != null) {
ContextProvider<?> p = factory.createContextProvider(cls, null);
if (p != null) {
value = p.createContext(null);
}
} else {
value = cri.getContextFieldProxy(f);
}
if (isManagedBean)
irc.setRuntimeCtxObject(f.getType().getName(), value);
else
InjectionUtils.injectFieldValue(f, instance, value);
}
}
Object o = null;
//replace singleton resource after context injection is done.
if (isManagedBean && (cri instanceof ClassResourceInfo)) {
o = beanCustomizer.onSingletonServiceInit(instance,
InjectionRuntimeContextHelper.getBeanCustomizerContext(beanCustomizer, cri.getBus()));
SingletonResourceProvider sp = new SingletonResourceProvider(o);
((ClassResourceInfo) cri).setResourceProvider(sp);
instance = o;
}
if (!isManagedBean && (cri instanceof ClassResourceInfo))
{
//call postConstruct method for singleton resource which are non-CDI/EJB
Method postConstructMethod = ResourceUtils.findPostConstructMethod(instance.getClass());
InjectionUtils.invokeLifeCycleMethod(instance, postConstructMethod);
}
} } | public class class_name {
public static void injectContextProxiesAndApplication(AbstractResourceInfo cri,
Object instance,
Application app,
ProviderFactory factory) {
/** inject proxy for singleton only */
if (!cri.isSingleton())
return;
/** application inject has been done earlier. @see LibertyJaxRsServerFactoryBean.injectContextApplication() */
if (cri instanceof ApplicationInfo)
return;
JaxRsFactoryBeanCustomizer beanCustomizer = InjectionRuntimeContextHelper.findBeanCustomizer(instance.getClass(), cri.getBus());
Boolean isManagedBean = beanCustomizer == null ? false : true;
InjectionRuntimeContext irc = InjectionRuntimeContextHelper.getRuntimeContext();
synchronized (instance) {
for (Map.Entry<Class<?>, Method> entry : cri.getContextMethods().entrySet()) {
Method method = entry.getValue();
Object value = null;
Class<?> cls = method.getParameterTypes()[0];
if (cls == Application.class) {
value = app; // depends on control dependency: [if], data = [none]
} else if (VALUE_CONTEXTS.contains(cls.getName()) && factory != null) {
ContextProvider<?> p = factory.createContextProvider(cls, null);
if (p != null) {
value = p.createContext(null); // depends on control dependency: [if], data = [null)]
}
} else {
value = cri.getContextSetterProxy(method); // depends on control dependency: [if], data = [none]
}
if (isManagedBean)
irc.setRuntimeCtxObject(entry.getKey().getName(), value);
else
InjectionUtils.injectThroughMethod(instance, method, value);
}
for (Field f : cri.getContextFields()) {
Object value = null;
Class<?> cls = f.getType();
if (cls == Application.class) {
value = app; // depends on control dependency: [if], data = [none]
} else if (VALUE_CONTEXTS.contains(cls.getName()) && factory != null) {
ContextProvider<?> p = factory.createContextProvider(cls, null);
if (p != null) {
value = p.createContext(null); // depends on control dependency: [if], data = [null)]
}
} else {
value = cri.getContextFieldProxy(f); // depends on control dependency: [if], data = [none]
}
if (isManagedBean)
irc.setRuntimeCtxObject(f.getType().getName(), value);
else
InjectionUtils.injectFieldValue(f, instance, value);
}
}
Object o = null;
//replace singleton resource after context injection is done.
if (isManagedBean && (cri instanceof ClassResourceInfo)) {
o = beanCustomizer.onSingletonServiceInit(instance,
InjectionRuntimeContextHelper.getBeanCustomizerContext(beanCustomizer, cri.getBus())); // depends on control dependency: [if], data = [none]
SingletonResourceProvider sp = new SingletonResourceProvider(o);
((ClassResourceInfo) cri).setResourceProvider(sp); // depends on control dependency: [if], data = [none]
instance = o; // depends on control dependency: [if], data = [none]
}
if (!isManagedBean && (cri instanceof ClassResourceInfo))
{
//call postConstruct method for singleton resource which are non-CDI/EJB
Method postConstructMethod = ResourceUtils.findPostConstructMethod(instance.getClass());
InjectionUtils.invokeLifeCycleMethod(instance, postConstructMethod); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected void notifyListeners (int event)
{
int size = _listeners.size();
for (int ii = 0; ii < size; ii++) {
_listeners.get(ii).modelChanged(event);
}
} } | public class class_name {
protected void notifyListeners (int event)
{
int size = _listeners.size();
for (int ii = 0; ii < size; ii++) {
_listeners.get(ii).modelChanged(event); // depends on control dependency: [for], data = [ii]
}
} } |
public class class_name {
public DbOrganization getOrganization(final DbArtifact dbArtifact) {
final DbModule module = getModule(dbArtifact);
if(module == null || module.getOrganization() == null){
return null;
}
return repositoryHandler.getOrganization(module.getOrganization());
} } | public class class_name {
public DbOrganization getOrganization(final DbArtifact dbArtifact) {
final DbModule module = getModule(dbArtifact);
if(module == null || module.getOrganization() == null){
return null; // depends on control dependency: [if], data = [none]
}
return repositoryHandler.getOrganization(module.getOrganization());
} } |
public class class_name {
protected ListItemHostWidget getRecycleableView(int dataIndex) {
ListItemHostWidget host = null;
try {
host = getHostView(dataIndex);
if (host != null) {
if (host.isRecycled()) {
Widget view = getViewFromAdapter(dataIndex, host);
if (view != null) {
setupHost(host, view, dataIndex);
}
}
boolean added = mContent.addChild(host, true);
host.layout();
Log.d(Log.SUBSYSTEM.LAYOUT, TAG, "getRecycleableView: item [%s] is added [%b] to the list",
host, added);
}
} catch (Exception e) {
Log.e(TAG, e, "getRecycleableView(%s): exception at %d: %s",
getName(), dataIndex, e.getMessage());
}
return host;
} } | public class class_name {
protected ListItemHostWidget getRecycleableView(int dataIndex) {
ListItemHostWidget host = null;
try {
host = getHostView(dataIndex); // depends on control dependency: [try], data = [none]
if (host != null) {
if (host.isRecycled()) {
Widget view = getViewFromAdapter(dataIndex, host);
if (view != null) {
setupHost(host, view, dataIndex); // depends on control dependency: [if], data = [none]
}
}
boolean added = mContent.addChild(host, true);
host.layout(); // depends on control dependency: [if], data = [none]
Log.d(Log.SUBSYSTEM.LAYOUT, TAG, "getRecycleableView: item [%s] is added [%b] to the list",
host, added); // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
Log.e(TAG, e, "getRecycleableView(%s): exception at %d: %s",
getName(), dataIndex, e.getMessage());
} // depends on control dependency: [catch], data = [none]
return host;
} } |
public class class_name {
@SuppressWarnings("unchecked")
private void writeRows(Cell templateCell, List<Object> items) {
val tmplRow = templateCell.getRow();
val fromRow = tmplRow.getRowNum();
val tmplCol = templateCell.getColumnIndex();
for (int i = 0, ii = items.size(); i < ii; ++i) {
val item = items.get(i);
val row = i == 0 ? tmplRow : sheet.createRow(fromRow + i);
if (row != tmplRow) {
row.setHeight(tmplRow.getHeight());
}
val fields = item.getClass().getDeclaredFields();
int cutoff = 0;
for (int j = 0; j < fields.length; ++j) {
val field = fields[j];
if (Fields.shouldIgnored(field, ExcelColIgnore.class)) {
++cutoff;
continue;
}
if (field.getName().endsWith("Tmpl")) {
++cutoff;
continue;
}
val fv = Fields.invokeField(field, item);
val excelCell = field.getAnnotation(ExcelCell.class);
int maxLen = excelCell == null ? 0 : excelCell.maxLineLen();
val cell = newCell(tmplRow, tmplCol + j - cutoff, i, row, fv, maxLen);
applyTemplateCellStyle(field, item, excelCell, cell);
}
emptyEndsCells(tmplRow, tmplCol, i, row, fields.length);
}
} } | public class class_name {
@SuppressWarnings("unchecked")
private void writeRows(Cell templateCell, List<Object> items) {
val tmplRow = templateCell.getRow();
val fromRow = tmplRow.getRowNum();
val tmplCol = templateCell.getColumnIndex();
for (int i = 0, ii = items.size(); i < ii; ++i) {
val item = items.get(i);
val row = i == 0 ? tmplRow : sheet.createRow(fromRow + i);
if (row != tmplRow) {
row.setHeight(tmplRow.getHeight()); // depends on control dependency: [if], data = [none]
}
val fields = item.getClass().getDeclaredFields();
int cutoff = 0;
for (int j = 0; j < fields.length; ++j) {
val field = fields[j];
if (Fields.shouldIgnored(field, ExcelColIgnore.class)) {
++cutoff; // depends on control dependency: [if], data = [none]
continue;
}
if (field.getName().endsWith("Tmpl")) {
++cutoff; // depends on control dependency: [if], data = [none]
continue;
}
val fv = Fields.invokeField(field, item);
val excelCell = field.getAnnotation(ExcelCell.class);
int maxLen = excelCell == null ? 0 : excelCell.maxLineLen();
val cell = newCell(tmplRow, tmplCol + j - cutoff, i, row, fv, maxLen);
applyTemplateCellStyle(field, item, excelCell, cell); // depends on control dependency: [for], data = [none]
}
emptyEndsCells(tmplRow, tmplCol, i, row, fields.length); // depends on control dependency: [for], data = [i]
}
} } |
public class class_name {
static AuthenticationType convertAuthToEnum(int resAuthType)
{
AuthenticationType authType = AuthenticationType.CONTAINER;
if (resAuthType == ResourceRef.AUTH_APPLICATION)
{
authType = AuthenticationType.APPLICATION;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "convertAuthToEnum : " + resAuthType + " -> " + authType);
return authType;
} } | public class class_name {
static AuthenticationType convertAuthToEnum(int resAuthType)
{
AuthenticationType authType = AuthenticationType.CONTAINER;
if (resAuthType == ResourceRef.AUTH_APPLICATION)
{
authType = AuthenticationType.APPLICATION; // depends on control dependency: [if], data = [none]
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "convertAuthToEnum : " + resAuthType + " -> " + authType);
return authType;
} } |
public class class_name {
public void setSuggesters(java.util.Collection<SuggesterStatus> suggesters) {
if (suggesters == null) {
this.suggesters = null;
return;
}
this.suggesters = new com.amazonaws.internal.SdkInternalList<SuggesterStatus>(suggesters);
} } | public class class_name {
public void setSuggesters(java.util.Collection<SuggesterStatus> suggesters) {
if (suggesters == null) {
this.suggesters = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.suggesters = new com.amazonaws.internal.SdkInternalList<SuggesterStatus>(suggesters);
} } |
public class class_name {
@SuppressWarnings("unchecked")
private int getVarArgsParmCount(String signature) {
if (SignatureBuilder.SIG_STRING_AND_OBJECT_TO_VOID.equals(signature)) {
return 1;
}
if (SIG_STRING_AND_TWO_OBJECTS_TO_VOID.equals(signature)) {
return 2;
}
OpcodeStack.Item item = stack.getStackItem(0);
LOUserValue<Integer> uv = (LOUserValue<Integer>) item.getUserValue();
if ((uv != null) && (uv.getType() == LOUserValue.LOType.ARRAY_SIZE)) {
Integer size = uv.getValue();
if (size != null) {
return Math.abs(size.intValue());
}
}
return -1;
} } | public class class_name {
@SuppressWarnings("unchecked")
private int getVarArgsParmCount(String signature) {
if (SignatureBuilder.SIG_STRING_AND_OBJECT_TO_VOID.equals(signature)) {
return 1; // depends on control dependency: [if], data = [none]
}
if (SIG_STRING_AND_TWO_OBJECTS_TO_VOID.equals(signature)) {
return 2; // depends on control dependency: [if], data = [none]
}
OpcodeStack.Item item = stack.getStackItem(0);
LOUserValue<Integer> uv = (LOUserValue<Integer>) item.getUserValue();
if ((uv != null) && (uv.getType() == LOUserValue.LOType.ARRAY_SIZE)) {
Integer size = uv.getValue();
if (size != null) {
return Math.abs(size.intValue()); // depends on control dependency: [if], data = [(size]
}
}
return -1;
} } |
public class class_name {
public void enqueue(TargetTransportPort port, Command command)
{
if (_logger.isDebugEnabled())
{
_logger.debug("enqueuing command: " + command + ", associated with TargetTransportPort: "
+ port);
}
try
{
Task task = this.getTaskFactory().getInstance(port, command);
assert task != null : "improper task factory implementation returned null task";
if (_logger.isDebugEnabled())
{
_logger.debug("successfully constructed task: " + task);
}
this.taskSet.offer(task); // non-blocking, task set sends any errors to transport port
}
catch (IllegalRequestException e)
{
port.writeResponse(command.getNexus(), command.getCommandReferenceNumber(),
Status.CHECK_CONDITION, ByteBuffer.wrap(e.encode()));
}
} } | public class class_name {
public void enqueue(TargetTransportPort port, Command command)
{
if (_logger.isDebugEnabled())
{
_logger.debug("enqueuing command: " + command + ", associated with TargetTransportPort: "
+ port); // depends on control dependency: [if], data = [none]
}
try
{
Task task = this.getTaskFactory().getInstance(port, command);
assert task != null : "improper task factory implementation returned null task";
if (_logger.isDebugEnabled())
{
_logger.debug("successfully constructed task: " + task);
}
this.taskSet.offer(task); // non-blocking, task set sends any errors to transport port
}
catch (IllegalRequestException e)
{
port.writeResponse(command.getNexus(), command.getCommandReferenceNumber(),
Status.CHECK_CONDITION, ByteBuffer.wrap(e.encode()));
}
} } |
public class class_name {
private PGPKeyRingGenerator createKeyRingGenerator(String userId, String password, int keySize) {
LOGGER.trace("createKeyRingGenerator(String, String, int)");
LOGGER.trace("User ID: {}, Password: {}, Key Size: {}", userId, password == null ? "not set" : "********", keySize);
PGPKeyRingGenerator generator = null;
try {
LOGGER.debug("Creating RSA key pair generator");
RSAKeyPairGenerator generator1 = new RSAKeyPairGenerator();
generator1.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001), getSecureRandom(), keySize, 12));
LOGGER.debug("Generating Signing Key Pair");
BcPGPKeyPair signingKeyPair = new BcPGPKeyPair(PGPPublicKey.RSA_SIGN, generator1.generateKeyPair(), new Date());
LOGGER.debug("Generating Encyption Key Pair");
BcPGPKeyPair encryptionKeyPair = new BcPGPKeyPair(PGPPublicKey.RSA_ENCRYPT, generator1.generateKeyPair(), new Date());
LOGGER.debug("Generating Signature Key Properties");
PGPSignatureSubpacketGenerator signatureSubpacketGenerator = new PGPSignatureSubpacketGenerator();
signatureSubpacketGenerator.setKeyFlags(false, KeyFlags.SIGN_DATA | KeyFlags.CERTIFY_OTHER);
signatureSubpacketGenerator.setPreferredSymmetricAlgorithms(false, getPreferredEncryptionAlgorithms());
signatureSubpacketGenerator.setPreferredHashAlgorithms(false, getPreferredHashingAlgorithms());
signatureSubpacketGenerator.setPreferredCompressionAlgorithms(false, getPreferredCompressionAlgorithms());
LOGGER.debug("Generating Encyption Key Properties");
PGPSignatureSubpacketGenerator encryptionSubpacketGenerator = new PGPSignatureSubpacketGenerator();
encryptionSubpacketGenerator.setKeyFlags(false, KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE);
LOGGER.info("Creating PGP Key Ring Generator");
generator = new PGPKeyRingGenerator(PGPPublicKey.RSA_SIGN, signingKeyPair, userId, new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1), signatureSubpacketGenerator.generate(), null, new BcPGPContentSignerBuilder(PGPPublicKey.RSA_SIGN, HashAlgorithmTags.SHA256), new BcPBESecretKeyEncryptorBuilder(getEncryptionAlgorithm()).build(password.toCharArray()));
generator.addSubKey(encryptionKeyPair, encryptionSubpacketGenerator.generate(), null);
} catch (PGPException e) {
LOGGER.error("{}", e.getMessage());
generator = null;
}
return generator;
} } | public class class_name {
private PGPKeyRingGenerator createKeyRingGenerator(String userId, String password, int keySize) {
LOGGER.trace("createKeyRingGenerator(String, String, int)");
LOGGER.trace("User ID: {}, Password: {}, Key Size: {}", userId, password == null ? "not set" : "********", keySize);
PGPKeyRingGenerator generator = null;
try {
LOGGER.debug("Creating RSA key pair generator"); // depends on control dependency: [try], data = [none]
RSAKeyPairGenerator generator1 = new RSAKeyPairGenerator();
generator1.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001), getSecureRandom(), keySize, 12)); // depends on control dependency: [try], data = [none]
LOGGER.debug("Generating Signing Key Pair"); // depends on control dependency: [try], data = [none]
BcPGPKeyPair signingKeyPair = new BcPGPKeyPair(PGPPublicKey.RSA_SIGN, generator1.generateKeyPair(), new Date());
LOGGER.debug("Generating Encyption Key Pair"); // depends on control dependency: [try], data = [none]
BcPGPKeyPair encryptionKeyPair = new BcPGPKeyPair(PGPPublicKey.RSA_ENCRYPT, generator1.generateKeyPair(), new Date());
LOGGER.debug("Generating Signature Key Properties"); // depends on control dependency: [try], data = [none]
PGPSignatureSubpacketGenerator signatureSubpacketGenerator = new PGPSignatureSubpacketGenerator();
signatureSubpacketGenerator.setKeyFlags(false, KeyFlags.SIGN_DATA | KeyFlags.CERTIFY_OTHER); // depends on control dependency: [try], data = [none]
signatureSubpacketGenerator.setPreferredSymmetricAlgorithms(false, getPreferredEncryptionAlgorithms()); // depends on control dependency: [try], data = [none]
signatureSubpacketGenerator.setPreferredHashAlgorithms(false, getPreferredHashingAlgorithms()); // depends on control dependency: [try], data = [none]
signatureSubpacketGenerator.setPreferredCompressionAlgorithms(false, getPreferredCompressionAlgorithms()); // depends on control dependency: [try], data = [none]
LOGGER.debug("Generating Encyption Key Properties"); // depends on control dependency: [try], data = [none]
PGPSignatureSubpacketGenerator encryptionSubpacketGenerator = new PGPSignatureSubpacketGenerator();
encryptionSubpacketGenerator.setKeyFlags(false, KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE); // depends on control dependency: [try], data = [none]
LOGGER.info("Creating PGP Key Ring Generator"); // depends on control dependency: [try], data = [none]
generator = new PGPKeyRingGenerator(PGPPublicKey.RSA_SIGN, signingKeyPair, userId, new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1), signatureSubpacketGenerator.generate(), null, new BcPGPContentSignerBuilder(PGPPublicKey.RSA_SIGN, HashAlgorithmTags.SHA256), new BcPBESecretKeyEncryptorBuilder(getEncryptionAlgorithm()).build(password.toCharArray())); // depends on control dependency: [try], data = [none]
generator.addSubKey(encryptionKeyPair, encryptionSubpacketGenerator.generate(), null); // depends on control dependency: [try], data = [none]
} catch (PGPException e) {
LOGGER.error("{}", e.getMessage());
generator = null;
} // depends on control dependency: [catch], data = [none]
return generator;
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.