code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
private ModelNode addNewAliasToList(ModelNode list, String alias) {
// check for empty string
if (alias == null || alias.equals(""))
return list ;
// check for undefined list (AS7-3476)
if (!list.isDefined()) {
list.setEmptyList();
}
ModelNode newList = list.clone() ;
List<ModelNode> listElements = list.asList();
boolean found = false;
for (ModelNode listElement : listElements) {
if (listElement.asString().equals(alias)) {
found = true;
}
}
if (!found) {
newList.add().set(alias);
}
return newList ;
} } | public class class_name {
private ModelNode addNewAliasToList(ModelNode list, String alias) {
// check for empty string
if (alias == null || alias.equals(""))
return list ;
// check for undefined list (AS7-3476)
if (!list.isDefined()) {
list.setEmptyList(); // depends on control dependency: [if], data = [none]
}
ModelNode newList = list.clone() ;
List<ModelNode> listElements = list.asList();
boolean found = false;
for (ModelNode listElement : listElements) {
if (listElement.asString().equals(alias)) {
found = true; // depends on control dependency: [if], data = [none]
}
}
if (!found) {
newList.add().set(alias); // depends on control dependency: [if], data = [none]
}
return newList ;
} } |
public class class_name {
public int getLastChild(int nodeHandle)
{
int identity = makeNodeIdentity(nodeHandle);
int child = _firstch(identity);
int lastChild = DTM.NULL;
while (child != DTM.NULL)
{
lastChild = child;
child = _nextsib(child);
}
return makeNodeHandle(lastChild);
} } | public class class_name {
public int getLastChild(int nodeHandle)
{
int identity = makeNodeIdentity(nodeHandle);
int child = _firstch(identity);
int lastChild = DTM.NULL;
while (child != DTM.NULL)
{
lastChild = child; // depends on control dependency: [while], data = [none]
child = _nextsib(child); // depends on control dependency: [while], data = [(child]
}
return makeNodeHandle(lastChild);
} } |
public class class_name {
protected String getBaseUploadUri() {
if (mSession != null && mSession.getAuthInfo() != null && mSession.getAuthInfo().getBaseDomain() != null){
return String.format(BoxConstants.BASE_UPLOAD_URI_TEMPLATE, mSession.getAuthInfo().getBaseDomain());
}
return mBaseUploadUri;
} } | public class class_name {
protected String getBaseUploadUri() {
if (mSession != null && mSession.getAuthInfo() != null && mSession.getAuthInfo().getBaseDomain() != null){
return String.format(BoxConstants.BASE_UPLOAD_URI_TEMPLATE, mSession.getAuthInfo().getBaseDomain()); // depends on control dependency: [if], data = [none]
}
return mBaseUploadUri;
} } |
public class class_name {
public void doTag()
throws IOException, JspException {
JspContext jspContext = getJspContext();
DataGridTagModel dgm = DataGridUtil.getDataGridTagModel(jspContext);
if(dgm == null)
throw new JspException(Bundle.getErrorString("DataGridTags_MissingDataGridModel"));
if(dgm.getRenderState() == DataGridTagModel.RENDER_STATE_FOOTER) {
JspFragment fragment = getJspBody();
if(fragment != null) {
StringWriter sw = new StringWriter();
TableRenderer tableRenderer = dgm.getTableRenderer();
assert tableRenderer != null;
StyleModel styleModel = dgm.getStyleModel();
assert styleModel != null;
AbstractRenderAppender appender = new WriteRenderAppender(jspContext);
if(dgm.isRenderRowGroups()) {
if(_tfootTag.styleClass == null)
_tfootTag.styleClass = styleModel.getTableFootClass();
tableRenderer.openTableFoot(_tfootTag, appender);
}
TrTag.State trState = null;
if(_renderRow) {
trState = new TrTag.State();
trState.styleClass = styleModel.getFooterRowClass();
tableRenderer.openFooterRow(trState, appender);
}
fragment.invoke(sw);
appender.append(sw.toString());
if(_renderRow) {
assert trState != null;
tableRenderer.closeFooterRow(appender);
}
if(dgm.isRenderRowGroups()) {
tableRenderer.closeTableFoot(appender);
String tfootScript = null;
if(_tfootTag.id != null) {
HttpServletRequest request = JspUtil.getRequest(getJspContext());
tfootScript = renderNameAndId(request, _tfootTag, null);
}
if(tfootScript != null)
appender.append(tfootScript);
}
}
}
} } | public class class_name {
public void doTag()
throws IOException, JspException {
JspContext jspContext = getJspContext();
DataGridTagModel dgm = DataGridUtil.getDataGridTagModel(jspContext);
if(dgm == null)
throw new JspException(Bundle.getErrorString("DataGridTags_MissingDataGridModel"));
if(dgm.getRenderState() == DataGridTagModel.RENDER_STATE_FOOTER) {
JspFragment fragment = getJspBody();
if(fragment != null) {
StringWriter sw = new StringWriter();
TableRenderer tableRenderer = dgm.getTableRenderer();
assert tableRenderer != null;
StyleModel styleModel = dgm.getStyleModel();
assert styleModel != null;
AbstractRenderAppender appender = new WriteRenderAppender(jspContext);
if(dgm.isRenderRowGroups()) {
if(_tfootTag.styleClass == null)
_tfootTag.styleClass = styleModel.getTableFootClass();
tableRenderer.openTableFoot(_tfootTag, appender); // depends on control dependency: [if], data = [none]
}
TrTag.State trState = null;
if(_renderRow) {
trState = new TrTag.State(); // depends on control dependency: [if], data = [none]
trState.styleClass = styleModel.getFooterRowClass(); // depends on control dependency: [if], data = [none]
tableRenderer.openFooterRow(trState, appender); // depends on control dependency: [if], data = [none]
}
fragment.invoke(sw); // depends on control dependency: [if], data = [none]
appender.append(sw.toString()); // depends on control dependency: [if], data = [none]
if(_renderRow) {
assert trState != null;
tableRenderer.closeFooterRow(appender); // depends on control dependency: [if], data = [none]
}
if(dgm.isRenderRowGroups()) {
tableRenderer.closeTableFoot(appender); // depends on control dependency: [if], data = [none]
String tfootScript = null;
if(_tfootTag.id != null) {
HttpServletRequest request = JspUtil.getRequest(getJspContext());
tfootScript = renderNameAndId(request, _tfootTag, null); // depends on control dependency: [if], data = [null)]
}
if(tfootScript != null)
appender.append(tfootScript);
}
}
}
} } |
public class class_name {
public boolean requireFirstTime(Attribute attribute) {
if (!attribute.isJavaBaseClass()) {
return ImportsContext.getCurrentImportsHolder().add(attribute.getFullType());
}
return false;
} } | public class class_name {
public boolean requireFirstTime(Attribute attribute) {
if (!attribute.isJavaBaseClass()) {
return ImportsContext.getCurrentImportsHolder().add(attribute.getFullType()); // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public LatLonPoint projToLatLon(ProjectionPoint world,
LatLonPointImpl result) {
double toLat, toLon;
double x = world.getX();
double y = world.getY();
double cosl;
int TOLERENCE = 1;
double xp, yp;
xp = cosRot * x + sinRot * y;
yp = -sinRot * x + cosRot * y;
toLat = Math.toDegrees(lat0) + Math.toDegrees(yp / radius);
//double lat2;
//lat2 = lat0 + Math.toDegrees(yp/radius);
cosl = Math.cos(Math.toRadians(toLat));
if (Math.abs(cosl) < TOLERANCE) {
toLon = Math.toDegrees(lon0);
} else {
toLon = Math.toDegrees(lon0)
+ Math.toDegrees(xp / cosl / radius);
}
toLon = LatLonPointImpl.lonNormal(toLon);
result.setLatitude(toLat);
result.setLongitude(toLon);
return result;
} } | public class class_name {
public LatLonPoint projToLatLon(ProjectionPoint world,
LatLonPointImpl result) {
double toLat, toLon;
double x = world.getX();
double y = world.getY();
double cosl;
int TOLERENCE = 1;
double xp, yp;
xp = cosRot * x + sinRot * y;
yp = -sinRot * x + cosRot * y;
toLat = Math.toDegrees(lat0) + Math.toDegrees(yp / radius);
//double lat2;
//lat2 = lat0 + Math.toDegrees(yp/radius);
cosl = Math.cos(Math.toRadians(toLat));
if (Math.abs(cosl) < TOLERANCE) {
toLon = Math.toDegrees(lon0); // depends on control dependency: [if], data = [none]
} else {
toLon = Math.toDegrees(lon0)
+ Math.toDegrees(xp / cosl / radius); // depends on control dependency: [if], data = [none]
}
toLon = LatLonPointImpl.lonNormal(toLon);
result.setLatitude(toLat);
result.setLongitude(toLon);
return result;
} } |
public class class_name {
@Override
public double[] getVotesForInstance(Instance inst) {
if (m_weights == null) {
return new double[inst.numClasses()];
}
double[] result = (inst.classAttribute().isNominal())
? new double[inst.numClasses()]
: new double[1];
if (inst.classAttribute().isNumeric()) {
double wx = dotProd(inst, m_weights[0], inst.classIndex());// * m_wScale;
double z = (wx + m_bias[0]);
result[0] = z;
return result;
}
for (int i = 0; i < m_weights.length; i++){
double wx = dotProd(inst, m_weights[i], inst.classIndex());// * m_wScale;
double z = (wx + m_bias[i]);
if (z <= 0) {
// z = 0;
if (m_loss == LOGLOSS) {
//result[0] = 1.0 / (1.0 + Math.exp(z));
//result[1] = 1.0 - result[0];
result[i] = 1.0 - 1.0 / (1.0 + Math.exp(z));
} else {
//result[0] = 1;
result[i] = 0;
}
} else {
if (m_loss == LOGLOSS) {
//result[1] = 1.0 / (1.0 + Math.exp(-z));
//result[0] = 1.0 - result[1];
result[i] = 1.0 / (1.0 + Math.exp(-z));
} else {
//result[1] = 1;
result[i] = 1;
}
}
}
return result;
} } | public class class_name {
@Override
public double[] getVotesForInstance(Instance inst) {
if (m_weights == null) {
return new double[inst.numClasses()]; // depends on control dependency: [if], data = [none]
}
double[] result = (inst.classAttribute().isNominal())
? new double[inst.numClasses()]
: new double[1];
if (inst.classAttribute().isNumeric()) {
double wx = dotProd(inst, m_weights[0], inst.classIndex());// * m_wScale;
double z = (wx + m_bias[0]);
result[0] = z; // depends on control dependency: [if], data = [none]
return result; // depends on control dependency: [if], data = [none]
}
for (int i = 0; i < m_weights.length; i++){
double wx = dotProd(inst, m_weights[i], inst.classIndex());// * m_wScale;
double z = (wx + m_bias[i]);
if (z <= 0) {
// z = 0;
if (m_loss == LOGLOSS) {
//result[0] = 1.0 / (1.0 + Math.exp(z));
//result[1] = 1.0 - result[0];
result[i] = 1.0 - 1.0 / (1.0 + Math.exp(z)); // depends on control dependency: [if], data = [none]
} else {
//result[0] = 1;
result[i] = 0; // depends on control dependency: [if], data = [none]
}
} else {
if (m_loss == LOGLOSS) {
//result[1] = 1.0 / (1.0 + Math.exp(-z));
//result[0] = 1.0 - result[1];
result[i] = 1.0 / (1.0 + Math.exp(-z)); // depends on control dependency: [if], data = [none]
} else {
//result[1] = 1;
result[i] = 1; // depends on control dependency: [if], data = [none]
}
}
}
return result;
} } |
public class class_name {
@Programmatic
public Clob downloadMetaModel() {
final Collection<ObjectSpecification> specifications = specificationLoader.allSpecifications();
final List<MetaModelRow> rows = Lists.newArrayList();
for (final ObjectSpecification spec : specifications) {
if (exclude(spec)) {
continue;
}
final List<ObjectAssociation> properties = spec.getAssociations(Contributed.EXCLUDED, ObjectAssociation.Filters.PROPERTIES);
for (final ObjectAssociation property : properties) {
final OneToOneAssociation otoa = (OneToOneAssociation) property;
if (exclude(otoa)) {
continue;
}
rows.add(new MetaModelRow(spec, otoa));
}
final List<ObjectAssociation> associations = spec.getAssociations(Contributed.EXCLUDED, ObjectAssociation.Filters.COLLECTIONS);
for (final ObjectAssociation collection : associations) {
final OneToManyAssociation otma = (OneToManyAssociation) collection;
if (exclude(otma)) {
continue;
}
rows.add(new MetaModelRow(spec, otma));
}
final List<ObjectAction> actions = spec.getObjectActions(Contributed.INCLUDED);
for (final ObjectAction action : actions) {
if (exclude(action)) {
continue;
}
rows.add(new MetaModelRow(spec, action));
}
}
Collections.sort(rows);
final StringBuilder buf = new StringBuilder();
buf.append(MetaModelRow.header()).append("\n");
for (final MetaModelRow row : rows) {
buf.append(row.asTextCsv()).append("\n");
}
return new Clob("metamodel.csv", mimeTypeTextCsv, buf.toString().toCharArray());
} } | public class class_name {
@Programmatic
public Clob downloadMetaModel() {
final Collection<ObjectSpecification> specifications = specificationLoader.allSpecifications();
final List<MetaModelRow> rows = Lists.newArrayList();
for (final ObjectSpecification spec : specifications) {
if (exclude(spec)) {
continue;
}
final List<ObjectAssociation> properties = spec.getAssociations(Contributed.EXCLUDED, ObjectAssociation.Filters.PROPERTIES);
for (final ObjectAssociation property : properties) {
final OneToOneAssociation otoa = (OneToOneAssociation) property;
if (exclude(otoa)) {
continue;
}
rows.add(new MetaModelRow(spec, otoa)); // depends on control dependency: [for], data = [none]
}
final List<ObjectAssociation> associations = spec.getAssociations(Contributed.EXCLUDED, ObjectAssociation.Filters.COLLECTIONS);
for (final ObjectAssociation collection : associations) {
final OneToManyAssociation otma = (OneToManyAssociation) collection;
if (exclude(otma)) {
continue;
}
rows.add(new MetaModelRow(spec, otma)); // depends on control dependency: [for], data = [none]
}
final List<ObjectAction> actions = spec.getObjectActions(Contributed.INCLUDED);
for (final ObjectAction action : actions) {
if (exclude(action)) {
continue;
}
rows.add(new MetaModelRow(spec, action)); // depends on control dependency: [for], data = [action]
}
}
Collections.sort(rows);
final StringBuilder buf = new StringBuilder();
buf.append(MetaModelRow.header()).append("\n");
for (final MetaModelRow row : rows) {
buf.append(row.asTextCsv()).append("\n"); // depends on control dependency: [for], data = [row]
}
return new Clob("metamodel.csv", mimeTypeTextCsv, buf.toString().toCharArray());
} } |
public class class_name {
public List<String> list(String path) {
ZipEntry entry;
Enumeration<? extends ZipEntry> e;
String name;
String separator;
String prefix;
int length;
List<String> result;
int idx;
e = zip.entries();
separator = Filesystem.SEPARATOR_STRING;
prefix = path.length() == 0 ? "" : path + separator;
length = prefix.length();
result = new ArrayList<>();
while (e.hasMoreElements()) {
entry = e.nextElement();
name = entry.getName();
if (name.length() > length && name.startsWith(prefix)) {
idx = name.indexOf(separator, length);
name = (idx == -1 ? name : name.substring(0, idx));
if (!result.contains(name) && name.length() > 0 /* happens for "/" entries ... */) {
result.add(name);
}
}
}
return result;
} } | public class class_name {
public List<String> list(String path) {
ZipEntry entry;
Enumeration<? extends ZipEntry> e;
String name;
String separator;
String prefix;
int length;
List<String> result;
int idx;
e = zip.entries();
separator = Filesystem.SEPARATOR_STRING;
prefix = path.length() == 0 ? "" : path + separator;
length = prefix.length();
result = new ArrayList<>();
while (e.hasMoreElements()) {
entry = e.nextElement(); // depends on control dependency: [while], data = [none]
name = entry.getName(); // depends on control dependency: [while], data = [none]
if (name.length() > length && name.startsWith(prefix)) {
idx = name.indexOf(separator, length); // depends on control dependency: [if], data = [none]
name = (idx == -1 ? name : name.substring(0, idx)); // depends on control dependency: [if], data = [none]
if (!result.contains(name) && name.length() > 0 /* happens for "/" entries ... */) {
result.add(name); // depends on control dependency: [if], data = [none]
}
}
}
return result;
} } |
public class class_name {
protected void updateObjectIdentity(MutableAcl acl) {
Long parentId = null;
if (acl.getParentAcl() != null) {
Assert.isInstanceOf(ObjectIdentityImpl.class, acl.getParentAcl()
.getObjectIdentity(),
"Implementation only supports ObjectIdentityImpl");
ObjectIdentityImpl oii = (ObjectIdentityImpl) acl.getParentAcl()
.getObjectIdentity();
parentId = retrieveObjectIdentityPrimaryKey(oii);
}
Assert.notNull(acl.getOwner(), "Owner is required in this implementation");
Long ownerSid = createOrRetrieveSidPrimaryKey(acl.getOwner(), true);
int count = jdbcOperations.update(updateObjectIdentity, parentId, ownerSid,
Boolean.valueOf(acl.isEntriesInheriting()), acl.getId());
if (count != 1) {
throw new NotFoundException("Unable to locate ACL to update");
}
} } | public class class_name {
protected void updateObjectIdentity(MutableAcl acl) {
Long parentId = null;
if (acl.getParentAcl() != null) {
Assert.isInstanceOf(ObjectIdentityImpl.class, acl.getParentAcl()
.getObjectIdentity(),
"Implementation only supports ObjectIdentityImpl"); // depends on control dependency: [if], data = [none]
ObjectIdentityImpl oii = (ObjectIdentityImpl) acl.getParentAcl()
.getObjectIdentity();
parentId = retrieveObjectIdentityPrimaryKey(oii); // depends on control dependency: [if], data = [none]
}
Assert.notNull(acl.getOwner(), "Owner is required in this implementation");
Long ownerSid = createOrRetrieveSidPrimaryKey(acl.getOwner(), true);
int count = jdbcOperations.update(updateObjectIdentity, parentId, ownerSid,
Boolean.valueOf(acl.isEntriesInheriting()), acl.getId());
if (count != 1) {
throw new NotFoundException("Unable to locate ACL to update");
}
} } |
public class class_name {
private List<JField> getFields(List<JField> allFields, JClassType type) {
JField[] fields = type.getFields();
for (JField field : fields) {
if (!field.isTransient() && !isXmlTransient(field)) {
allFields.add(field);
}
}
try {
JType objectType = find(Object.class, getLogger(), context);
if (!objectType.equals(type)) {
JClassType superType = type.getSuperclass();
return getFields(allFields, superType);
}
} catch (UnableToCompleteException e) {
// do nothing
}
return allFields;
} } | public class class_name {
private List<JField> getFields(List<JField> allFields, JClassType type) {
JField[] fields = type.getFields();
for (JField field : fields) {
if (!field.isTransient() && !isXmlTransient(field)) {
allFields.add(field); // depends on control dependency: [if], data = [none]
}
}
try {
JType objectType = find(Object.class, getLogger(), context);
if (!objectType.equals(type)) {
JClassType superType = type.getSuperclass();
return getFields(allFields, superType); // depends on control dependency: [if], data = [none]
}
} catch (UnableToCompleteException e) {
// do nothing
} // depends on control dependency: [catch], data = [none]
return allFields;
} } |
public class class_name {
@Override
@SuppressWarnings("unchecked")
public void execute()
{
setExecutionStatus(UIStructurBrowser.ExecutionStatus.EXECUTE);
final List<Return> ret;
try {
if (getTableUUID() == null) {
final Map<Instance, Boolean> map = new LinkedHashMap<>();
map.put(getInstance(), null);
executeTree(map, false);
} else {
final Map<Instance, Boolean> map = new LinkedHashMap<>();
if (!isCreateMode()) {
ret = getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE, ParameterValues.CLASS, this,
ParameterValues.INSTANCE, getInstance());
map.putAll((Map<Instance, Boolean>) ret.get(0).get(ReturnValues.VALUES));
}
executeTreeTable(map, false);
}
} catch (final EFapsException e) {
throw new RestartResponseException(new ErrorPage(e));
}
} } | public class class_name {
@Override
@SuppressWarnings("unchecked")
public void execute()
{
setExecutionStatus(UIStructurBrowser.ExecutionStatus.EXECUTE);
final List<Return> ret;
try {
if (getTableUUID() == null) {
final Map<Instance, Boolean> map = new LinkedHashMap<>();
map.put(getInstance(), null); // depends on control dependency: [if], data = [null)]
executeTree(map, false); // depends on control dependency: [if], data = [none]
} else {
final Map<Instance, Boolean> map = new LinkedHashMap<>();
if (!isCreateMode()) {
ret = getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE, ParameterValues.CLASS, this,
ParameterValues.INSTANCE, getInstance()); // depends on control dependency: [if], data = [none]
map.putAll((Map<Instance, Boolean>) ret.get(0).get(ReturnValues.VALUES)); // depends on control dependency: [if], data = [none]
}
executeTreeTable(map, false); // depends on control dependency: [if], data = [none]
}
} catch (final EFapsException e) {
throw new RestartResponseException(new ErrorPage(e));
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static byte[] toArray(ByteBuffer buffer) {
if (buffer.hasArray()) {
byte[] array = buffer.array();
int from = buffer.arrayOffset() + buffer.position();
return Arrays.copyOfRange(array, from, from + buffer.remaining());
} else {
byte[] to = new byte[buffer.remaining()];
buffer.slice().get(to);
return to;
}
} } | public class class_name {
public static byte[] toArray(ByteBuffer buffer) {
if (buffer.hasArray()) {
byte[] array = buffer.array();
int from = buffer.arrayOffset() + buffer.position();
return Arrays.copyOfRange(array, from, from + buffer.remaining()); // depends on control dependency: [if], data = [none]
} else {
byte[] to = new byte[buffer.remaining()];
buffer.slice().get(to); // depends on control dependency: [if], data = [none]
return to; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Deprecated
public static String getDefaultFile(CmsObject cms, String folder) {
if (folder.endsWith("/")) {
try {
CmsResource defaultFile = cms.readDefaultFile(folder);
if (defaultFile != null) {
return cms.getSitePath(defaultFile);
}
} catch (CmsException e) {
LOG.debug(e.getLocalizedMessage(), e);
}
return folder;
}
return null;
} } | public class class_name {
@Deprecated
public static String getDefaultFile(CmsObject cms, String folder) {
if (folder.endsWith("/")) {
try {
CmsResource defaultFile = cms.readDefaultFile(folder);
if (defaultFile != null) {
return cms.getSitePath(defaultFile); // depends on control dependency: [if], data = [(defaultFile]
}
} catch (CmsException e) {
LOG.debug(e.getLocalizedMessage(), e);
} // depends on control dependency: [catch], data = [none]
return folder; // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public DescribeSecurityGroupsResult withSecurityGroups(SecurityGroup... securityGroups) {
if (this.securityGroups == null) {
setSecurityGroups(new com.amazonaws.internal.SdkInternalList<SecurityGroup>(securityGroups.length));
}
for (SecurityGroup ele : securityGroups) {
this.securityGroups.add(ele);
}
return this;
} } | public class class_name {
public DescribeSecurityGroupsResult withSecurityGroups(SecurityGroup... securityGroups) {
if (this.securityGroups == null) {
setSecurityGroups(new com.amazonaws.internal.SdkInternalList<SecurityGroup>(securityGroups.length)); // depends on control dependency: [if], data = [none]
}
for (SecurityGroup ele : securityGroups) {
this.securityGroups.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public static Field[] getAnnotationFields(Class<?> clazz, Class<? extends Annotation> annotationClass) {
if (clazz == null || annotationClass == null) {
return null;
}
List<Field> fields = getAllFieldsOfClass0(clazz);
if (CollectionUtil.isEmpty(fields)) {
return null;
}
List<Field> list = CollectionUtil.createArrayList();
for (Field field : fields) {
if (null != field.getAnnotation(annotationClass)) {
list.add(field);
field.setAccessible(true);
}
}
return list.toArray(new Field[0]);
} } | public class class_name {
public static Field[] getAnnotationFields(Class<?> clazz, Class<? extends Annotation> annotationClass) {
if (clazz == null || annotationClass == null) {
return null; // depends on control dependency: [if], data = [none]
}
List<Field> fields = getAllFieldsOfClass0(clazz);
if (CollectionUtil.isEmpty(fields)) {
return null; // depends on control dependency: [if], data = [none]
}
List<Field> list = CollectionUtil.createArrayList();
for (Field field : fields) {
if (null != field.getAnnotation(annotationClass)) {
list.add(field); // depends on control dependency: [if], data = [none]
field.setAccessible(true); // depends on control dependency: [if], data = [none]
}
}
return list.toArray(new Field[0]);
} } |
public class class_name {
public static double choose(int n, int k) {
if (n < 0 || k < 0) {
throw new IllegalArgumentException(String.format("Invalid n = %d, k = %d", n, k));
}
if (n < k) {
return 0.0;
}
return Math.floor(0.5 + Math.exp(logChoose(n, k)));
} } | public class class_name {
public static double choose(int n, int k) {
if (n < 0 || k < 0) {
throw new IllegalArgumentException(String.format("Invalid n = %d, k = %d", n, k));
}
if (n < k) {
return 0.0; // depends on control dependency: [if], data = [none]
}
return Math.floor(0.5 + Math.exp(logChoose(n, k)));
} } |
public class class_name {
@Override
public void writeTo(T t, CodedOutputStream out) throws IOException {
for (FieldInfo fieldInfo : fieldInfos) {
Object value = FieldUtils.getField(t, fieldInfo.getField());
if (value != null) {
writeTo(fieldInfo, value, out);
}
}
} } | public class class_name {
@Override
public void writeTo(T t, CodedOutputStream out) throws IOException {
for (FieldInfo fieldInfo : fieldInfos) {
Object value = FieldUtils.getField(t, fieldInfo.getField());
if (value != null) {
writeTo(fieldInfo, value, out); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private Attribute parseAttribute(StreamTokenizer tokenizer) throws IOException, ParseException {
Attribute attribute = null;
// Get attribute name.
getNextToken(tokenizer);
String attributeName = tokenizer.sval;
getNextToken(tokenizer);
// Check if attribute is nominal.
if (tokenizer.ttype == StreamTokenizer.TT_WORD) {
// Attribute is real, integer, or string.
if (tokenizer.sval.equalsIgnoreCase(ARFF_ATTRIBUTE_REAL) ||
tokenizer.sval.equalsIgnoreCase(ARFF_ATTRIBUTE_INTEGER) ||
tokenizer.sval.equalsIgnoreCase(ARFF_ATTRIBUTE_NUMERIC)) {
attribute = new NumericAttribute(attributeName);
readTillEOL(tokenizer);
} else if (tokenizer.sval.equalsIgnoreCase(ARFF_ATTRIBUTE_STRING)) {
attribute = new StringAttribute(attributeName);
readTillEOL(tokenizer);
} else if (tokenizer.sval.equalsIgnoreCase(ARFF_ATTRIBUTE_DATE)) {
String format = null;
if (tokenizer.nextToken() != StreamTokenizer.TT_EOL) {
if ((tokenizer.ttype != StreamTokenizer.TT_WORD) && (tokenizer.ttype != '\'') && (tokenizer.ttype != '\"')) {
throw new ParseException("not a valid date format", tokenizer.lineno());
}
format = tokenizer.sval;
readTillEOL(tokenizer);
} else {
tokenizer.pushBack();
}
attribute = new DateAttribute(attributeName, null, format);
readTillEOL(tokenizer);
} else if (tokenizer.sval.equalsIgnoreCase(ARFF_ATTRIBUTE_RELATIONAL)) {
readTillEOL(tokenizer);
} else if (tokenizer.sval.equalsIgnoreCase(ARFF_END_SUBRELATION)) {
getNextToken(tokenizer);
} else {
throw new ParseException("Invalid attribute type or invalid enumeration", tokenizer.lineno());
}
} else {
// Attribute is nominal.
List<String> attributeValues = new ArrayList<>();
tokenizer.pushBack();
// Get values for nominal attribute.
if (tokenizer.nextToken() != '{') {
throw new ParseException("{ expected at beginning of enumeration", tokenizer.lineno());
}
while (tokenizer.nextToken() != '}') {
if (tokenizer.ttype == StreamTokenizer.TT_EOL) {
throw new ParseException("} expected at end of enumeration", tokenizer.lineno());
} else {
attributeValues.add(tokenizer.sval.trim());
}
}
String[] values = new String[attributeValues.size()];
for (int i = 0; i < values.length; i++) {
values[i] = attributeValues.get(i);
}
attribute = new NominalAttribute(attributeName, values);
}
getLastToken(tokenizer, false);
getFirstToken(tokenizer);
if (tokenizer.ttype == StreamTokenizer.TT_EOF) {
throw new ParseException(PREMATURE_END_OF_FILE, tokenizer.lineno());
}
return attribute;
} } | public class class_name {
private Attribute parseAttribute(StreamTokenizer tokenizer) throws IOException, ParseException {
Attribute attribute = null;
// Get attribute name.
getNextToken(tokenizer);
String attributeName = tokenizer.sval;
getNextToken(tokenizer);
// Check if attribute is nominal.
if (tokenizer.ttype == StreamTokenizer.TT_WORD) {
// Attribute is real, integer, or string.
if (tokenizer.sval.equalsIgnoreCase(ARFF_ATTRIBUTE_REAL) ||
tokenizer.sval.equalsIgnoreCase(ARFF_ATTRIBUTE_INTEGER) ||
tokenizer.sval.equalsIgnoreCase(ARFF_ATTRIBUTE_NUMERIC)) {
attribute = new NumericAttribute(attributeName); // depends on control dependency: [if], data = [none]
readTillEOL(tokenizer); // depends on control dependency: [if], data = [none]
} else if (tokenizer.sval.equalsIgnoreCase(ARFF_ATTRIBUTE_STRING)) {
attribute = new StringAttribute(attributeName); // depends on control dependency: [if], data = [none]
readTillEOL(tokenizer); // depends on control dependency: [if], data = [none]
} else if (tokenizer.sval.equalsIgnoreCase(ARFF_ATTRIBUTE_DATE)) {
String format = null;
if (tokenizer.nextToken() != StreamTokenizer.TT_EOL) {
if ((tokenizer.ttype != StreamTokenizer.TT_WORD) && (tokenizer.ttype != '\'') && (tokenizer.ttype != '\"')) {
throw new ParseException("not a valid date format", tokenizer.lineno());
}
format = tokenizer.sval; // depends on control dependency: [if], data = [none]
readTillEOL(tokenizer); // depends on control dependency: [if], data = [none]
} else {
tokenizer.pushBack(); // depends on control dependency: [if], data = [none]
}
attribute = new DateAttribute(attributeName, null, format); // depends on control dependency: [if], data = [none]
readTillEOL(tokenizer); // depends on control dependency: [if], data = [none]
} else if (tokenizer.sval.equalsIgnoreCase(ARFF_ATTRIBUTE_RELATIONAL)) {
readTillEOL(tokenizer); // depends on control dependency: [if], data = [none]
} else if (tokenizer.sval.equalsIgnoreCase(ARFF_END_SUBRELATION)) {
getNextToken(tokenizer); // depends on control dependency: [if], data = [none]
} else {
throw new ParseException("Invalid attribute type or invalid enumeration", tokenizer.lineno());
}
} else {
// Attribute is nominal.
List<String> attributeValues = new ArrayList<>();
tokenizer.pushBack();
// Get values for nominal attribute.
if (tokenizer.nextToken() != '{') {
throw new ParseException("{ expected at beginning of enumeration", tokenizer.lineno());
}
while (tokenizer.nextToken() != '}') {
if (tokenizer.ttype == StreamTokenizer.TT_EOL) {
throw new ParseException("} expected at end of enumeration", tokenizer.lineno());
} else {
attributeValues.add(tokenizer.sval.trim()); // depends on control dependency: [if], data = [none]
}
}
String[] values = new String[attributeValues.size()];
for (int i = 0; i < values.length; i++) {
values[i] = attributeValues.get(i); // depends on control dependency: [for], data = [i]
}
attribute = new NominalAttribute(attributeName, values);
}
getLastToken(tokenizer, false);
getFirstToken(tokenizer);
if (tokenizer.ttype == StreamTokenizer.TT_EOF) {
throw new ParseException(PREMATURE_END_OF_FILE, tokenizer.lineno());
}
return attribute;
} } |
public class class_name {
public T orElse(T defaultValue) {
T value = get();
if (value != null) {
return value;
}
return defaultValue;
} } | public class class_name {
public T orElse(T defaultValue) {
T value = get();
if (value != null) {
return value; // depends on control dependency: [if], data = [none]
}
return defaultValue;
} } |
public class class_name {
@Override
public CommerceCurrency fetchByPrimaryKey(Serializable primaryKey) {
Serializable serializable = entityCache.getResult(CommerceCurrencyModelImpl.ENTITY_CACHE_ENABLED,
CommerceCurrencyImpl.class, primaryKey);
if (serializable == nullModel) {
return null;
}
CommerceCurrency commerceCurrency = (CommerceCurrency)serializable;
if (commerceCurrency == null) {
Session session = null;
try {
session = openSession();
commerceCurrency = (CommerceCurrency)session.get(CommerceCurrencyImpl.class,
primaryKey);
if (commerceCurrency != null) {
cacheResult(commerceCurrency);
}
else {
entityCache.putResult(CommerceCurrencyModelImpl.ENTITY_CACHE_ENABLED,
CommerceCurrencyImpl.class, primaryKey, nullModel);
}
}
catch (Exception e) {
entityCache.removeResult(CommerceCurrencyModelImpl.ENTITY_CACHE_ENABLED,
CommerceCurrencyImpl.class, primaryKey);
throw processException(e);
}
finally {
closeSession(session);
}
}
return commerceCurrency;
} } | public class class_name {
@Override
public CommerceCurrency fetchByPrimaryKey(Serializable primaryKey) {
Serializable serializable = entityCache.getResult(CommerceCurrencyModelImpl.ENTITY_CACHE_ENABLED,
CommerceCurrencyImpl.class, primaryKey);
if (serializable == nullModel) {
return null; // depends on control dependency: [if], data = [none]
}
CommerceCurrency commerceCurrency = (CommerceCurrency)serializable;
if (commerceCurrency == null) {
Session session = null;
try {
session = openSession(); // depends on control dependency: [try], data = [none]
commerceCurrency = (CommerceCurrency)session.get(CommerceCurrencyImpl.class,
primaryKey); // depends on control dependency: [try], data = [none]
if (commerceCurrency != null) {
cacheResult(commerceCurrency); // depends on control dependency: [if], data = [(commerceCurrency]
}
else {
entityCache.putResult(CommerceCurrencyModelImpl.ENTITY_CACHE_ENABLED,
CommerceCurrencyImpl.class, primaryKey, nullModel); // depends on control dependency: [if], data = [none]
}
}
catch (Exception e) {
entityCache.removeResult(CommerceCurrencyModelImpl.ENTITY_CACHE_ENABLED,
CommerceCurrencyImpl.class, primaryKey);
throw processException(e);
} // depends on control dependency: [catch], data = [none]
finally {
closeSession(session);
}
}
return commerceCurrency;
} } |
public class class_name {
public static void closeWithWarn(Closeable closeable) {
if (BeanUtil.nonNull(closeable)) {
try {
closeable.close();
} catch (IOException e) {
LOG.warn("关闭流出错......", e);
}
}
} } | public class class_name {
public static void closeWithWarn(Closeable closeable) {
if (BeanUtil.nonNull(closeable)) {
try {
closeable.close(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
LOG.warn("关闭流出错......", e);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
private boolean isMatchGetter(String methodName, String fieldName, boolean isBooeanField) {
// 全部转为小写,忽略大小写比较
methodName = methodName.toLowerCase();
fieldName = fieldName.toLowerCase();
if (false == methodName.startsWith("get") && false == methodName.startsWith("is")) {
// 非标准Getter方法
return false;
}
if("getclass".equals(methodName)) {
//跳过getClass方法
return false;
}
// 针对Boolean类型特殊检查
if (isBooeanField) {
if (fieldName.startsWith("is")) {
// 字段已经是is开头
if (methodName.equals(fieldName) // isName -》 isName
|| methodName.equals("get" + fieldName)// isName -》 getIsName
|| methodName.equals("is" + fieldName)// isName -》 isIsName
) {
return true;
}
} else if (methodName.equals("is" + fieldName)) {
// 字段非is开头, name -》 isName
return true;
}
}
// 包括boolean的任何类型只有一种匹配情况:name -》 getName
return methodName.equals("get" + fieldName);
} } | public class class_name {
private boolean isMatchGetter(String methodName, String fieldName, boolean isBooeanField) {
// 全部转为小写,忽略大小写比较
methodName = methodName.toLowerCase();
fieldName = fieldName.toLowerCase();
if (false == methodName.startsWith("get") && false == methodName.startsWith("is")) {
// 非标准Getter方法
return false;
// depends on control dependency: [if], data = [none]
}
if("getclass".equals(methodName)) {
//跳过getClass方法
return false;
// depends on control dependency: [if], data = [none]
}
// 针对Boolean类型特殊检查
if (isBooeanField) {
if (fieldName.startsWith("is")) {
// 字段已经是is开头
if (methodName.equals(fieldName) // isName -》 isName
|| methodName.equals("get" + fieldName)// isName -》 getIsName
|| methodName.equals("is" + fieldName)// isName -》 isIsName
) {
return true;
// depends on control dependency: [if], data = []
}
} else if (methodName.equals("is" + fieldName)) {
// 字段非is开头, name -》 isName
return true;
// depends on control dependency: [if], data = [none]
}
}
// 包括boolean的任何类型只有一种匹配情况:name -》 getName
return methodName.equals("get" + fieldName);
} } |
public class class_name {
@Override
public boolean isDisabled() {
if (isFlagSet(ComponentModel.DISABLED_FLAG)) {
return true;
}
MenuContainer container = WebUtilities.getAncestorOfClass(MenuContainer.class, this);
if (container instanceof Disableable && ((Disableable) container).isDisabled()) {
return true;
}
return false;
} } | public class class_name {
@Override
public boolean isDisabled() {
if (isFlagSet(ComponentModel.DISABLED_FLAG)) {
return true; // depends on control dependency: [if], data = [none]
}
MenuContainer container = WebUtilities.getAncestorOfClass(MenuContainer.class, this);
if (container instanceof Disableable && ((Disableable) container).isDisabled()) {
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public <TContinuationResult> Task<TContinuationResult> onSuccessTask(
final Continuation<TResult, Task<TContinuationResult>> continuation, Executor executor,
final CancellationToken ct) {
return continueWithTask(new Continuation<TResult, Task<TContinuationResult>>() {
@Override
public Task<TContinuationResult> then(Task<TResult> task) {
if (ct != null && ct.isCancellationRequested()) {
return Task.cancelled();
}
if (task.isFaulted()) {
return Task.forError(task.getError());
} else if (task.isCancelled()) {
return Task.cancelled();
} else {
return task.continueWithTask(continuation);
}
}
}, executor);
} } | public class class_name {
public <TContinuationResult> Task<TContinuationResult> onSuccessTask(
final Continuation<TResult, Task<TContinuationResult>> continuation, Executor executor,
final CancellationToken ct) {
return continueWithTask(new Continuation<TResult, Task<TContinuationResult>>() {
@Override
public Task<TContinuationResult> then(Task<TResult> task) {
if (ct != null && ct.isCancellationRequested()) {
return Task.cancelled(); // depends on control dependency: [if], data = [none]
}
if (task.isFaulted()) {
return Task.forError(task.getError()); // depends on control dependency: [if], data = [none]
} else if (task.isCancelled()) {
return Task.cancelled(); // depends on control dependency: [if], data = [none]
} else {
return task.continueWithTask(continuation); // depends on control dependency: [if], data = [none]
}
}
}, executor);
} } |
public class class_name {
protected boolean isInTargets(String path) {
for (CmsPair<String, String> sourceTargetPair : m_sourceTargetPairs) {
String target = sourceTargetPair.getSecond();
if (CmsStringUtil.joinPaths(path, "/").startsWith(CmsStringUtil.joinPaths(target, "/"))) {
return true;
}
}
return false;
} } | public class class_name {
protected boolean isInTargets(String path) {
for (CmsPair<String, String> sourceTargetPair : m_sourceTargetPairs) {
String target = sourceTargetPair.getSecond();
if (CmsStringUtil.joinPaths(path, "/").startsWith(CmsStringUtil.joinPaths(target, "/"))) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
public java.util.List<CacheCluster> getCacheClusters() {
if (cacheClusters == null) {
cacheClusters = new com.amazonaws.internal.SdkInternalList<CacheCluster>();
}
return cacheClusters;
} } | public class class_name {
public java.util.List<CacheCluster> getCacheClusters() {
if (cacheClusters == null) {
cacheClusters = new com.amazonaws.internal.SdkInternalList<CacheCluster>(); // depends on control dependency: [if], data = [none]
}
return cacheClusters;
} } |
public class class_name {
private DictSegment lookforSegment(Character keyChar , int create){
DictSegment ds = null;
if(this.storeSize <= ARRAY_LENGTH_LIMIT){
//获取数组容器,如果数组未创建则创建数组
DictSegment[] segmentArray = getChildrenArray();
//搜寻数组
DictSegment keySegment = new DictSegment(keyChar);
int position = Arrays.binarySearch(segmentArray, 0 , this.storeSize, keySegment);
if(position >= 0){
ds = segmentArray[position];
}
//遍历数组后没有找到对应的segment
if(ds == null && create == 1){
ds = keySegment;
if(this.storeSize < ARRAY_LENGTH_LIMIT){
//数组容量未满,使用数组存储
segmentArray[this.storeSize] = ds;
//segment数目+1
this.storeSize++;
Arrays.sort(segmentArray , 0 , this.storeSize);
}else{
//数组容量已满,切换Map存储
//获取Map容器,如果Map未创建,则创建Map
Map<Character , DictSegment> segmentMap = getChildrenMap();
//将数组中的segment迁移到Map中
migrate(segmentArray , segmentMap);
//存储新的segment
segmentMap.put(keyChar, ds);
//segment数目+1 , 必须在释放数组前执行storeSize++ , 确保极端情况下,不会取到空的数组
this.storeSize++;
//释放当前的数组引用
this.childrenArray = null;
}
}
}else{
//获取Map容器,如果Map未创建,则创建Map
Map<Character , DictSegment> segmentMap = getChildrenMap();
//搜索Map
ds = (DictSegment)segmentMap.get(keyChar);
if(ds == null && create == 1){
//构造新的segment
ds = new DictSegment(keyChar);
segmentMap.put(keyChar , ds);
//当前节点存储segment数目+1
this.storeSize ++;
}
}
return ds;
} } | public class class_name {
private DictSegment lookforSegment(Character keyChar , int create){
DictSegment ds = null;
if(this.storeSize <= ARRAY_LENGTH_LIMIT){
//获取数组容器,如果数组未创建则创建数组
DictSegment[] segmentArray = getChildrenArray();
//搜寻数组
DictSegment keySegment = new DictSegment(keyChar);
int position = Arrays.binarySearch(segmentArray, 0 , this.storeSize, keySegment);
if(position >= 0){
ds = segmentArray[position]; // depends on control dependency: [if], data = [none]
}
//遍历数组后没有找到对应的segment
if(ds == null && create == 1){
ds = keySegment; // depends on control dependency: [if], data = [none]
if(this.storeSize < ARRAY_LENGTH_LIMIT){
//数组容量未满,使用数组存储
segmentArray[this.storeSize] = ds; // depends on control dependency: [if], data = [none]
//segment数目+1
this.storeSize++; // depends on control dependency: [if], data = [none]
Arrays.sort(segmentArray , 0 , this.storeSize); // depends on control dependency: [if], data = [none]
}else{
//数组容量已满,切换Map存储
//获取Map容器,如果Map未创建,则创建Map
Map<Character , DictSegment> segmentMap = getChildrenMap();
//将数组中的segment迁移到Map中
migrate(segmentArray , segmentMap); // depends on control dependency: [if], data = [none]
//存储新的segment
segmentMap.put(keyChar, ds); // depends on control dependency: [if], data = [none]
//segment数目+1 , 必须在释放数组前执行storeSize++ , 确保极端情况下,不会取到空的数组
this.storeSize++; // depends on control dependency: [if], data = [none]
//释放当前的数组引用
this.childrenArray = null; // depends on control dependency: [if], data = [none]
}
}
}else{
//获取Map容器,如果Map未创建,则创建Map
Map<Character , DictSegment> segmentMap = getChildrenMap();
//搜索Map
ds = (DictSegment)segmentMap.get(keyChar); // depends on control dependency: [if], data = [none]
if(ds == null && create == 1){
//构造新的segment
ds = new DictSegment(keyChar); // depends on control dependency: [if], data = [none]
segmentMap.put(keyChar , ds); // depends on control dependency: [if], data = [none]
//当前节点存储segment数目+1
this.storeSize ++; // depends on control dependency: [if], data = [none]
}
}
return ds;
} } |
public class class_name {
@Override
public JsonEntityBean getEntity(String entityType, String entityId, boolean populateChildren) {
// get the EntityEnum for the specified entity type
EntityEnum entityEnum = EntityEnum.getEntityEnum(entityType);
if (entityEnum == null) {
throw new IllegalArgumentException(
String.format("Parameter entityType has an unknown value of [%s]", entityType));
}
// if the entity type is a group, use the group service's findGroup method
// to locate it
if (entityEnum.isGroup()) {
// attempt to find the entity
IEntityGroup entity = GroupService.findGroup(entityId);
if (entity == null) {
return null;
} else {
JsonEntityBean jsonBean = new JsonEntityBean(entity, entityEnum);
if (populateChildren) {
Iterator<IGroupMember> members = entity.getChildren().iterator();
jsonBean = populateChildren(jsonBean, members);
}
if (jsonBean.getEntityType().isGroup()
|| EntityEnum.PERSON.equals(jsonBean.getEntityType())) {
IAuthorizationPrincipal principal = getPrincipalForEntity(jsonBean);
jsonBean.setPrincipalString(principal.getPrincipalString());
}
return jsonBean;
}
}
// otherwise use the getGroupMember method
else {
IGroupMember entity = GroupService.getGroupMember(entityId, entityEnum.getClazz());
if (entity == null || entity instanceof IEntityGroup) {
return null;
}
JsonEntityBean jsonBean = new JsonEntityBean(entity, entityEnum);
// the group member interface doesn't include the entity name, so
// we'll need to look that up manually
jsonBean.setName(lookupEntityName(jsonBean));
if (EntityEnum.GROUP.equals(jsonBean.getEntityType())
|| EntityEnum.PERSON.equals(jsonBean.getEntityType())) {
IAuthorizationPrincipal principal = getPrincipalForEntity(jsonBean);
jsonBean.setPrincipalString(principal.getPrincipalString());
}
return jsonBean;
}
} } | public class class_name {
@Override
public JsonEntityBean getEntity(String entityType, String entityId, boolean populateChildren) {
// get the EntityEnum for the specified entity type
EntityEnum entityEnum = EntityEnum.getEntityEnum(entityType);
if (entityEnum == null) {
throw new IllegalArgumentException(
String.format("Parameter entityType has an unknown value of [%s]", entityType));
}
// if the entity type is a group, use the group service's findGroup method
// to locate it
if (entityEnum.isGroup()) {
// attempt to find the entity
IEntityGroup entity = GroupService.findGroup(entityId);
if (entity == null) {
return null; // depends on control dependency: [if], data = [none]
} else {
JsonEntityBean jsonBean = new JsonEntityBean(entity, entityEnum);
if (populateChildren) {
Iterator<IGroupMember> members = entity.getChildren().iterator();
jsonBean = populateChildren(jsonBean, members); // depends on control dependency: [if], data = [none]
}
if (jsonBean.getEntityType().isGroup()
|| EntityEnum.PERSON.equals(jsonBean.getEntityType())) {
IAuthorizationPrincipal principal = getPrincipalForEntity(jsonBean);
jsonBean.setPrincipalString(principal.getPrincipalString()); // depends on control dependency: [if], data = [none]
}
return jsonBean; // depends on control dependency: [if], data = [none]
}
}
// otherwise use the getGroupMember method
else {
IGroupMember entity = GroupService.getGroupMember(entityId, entityEnum.getClazz());
if (entity == null || entity instanceof IEntityGroup) {
return null; // depends on control dependency: [if], data = [none]
}
JsonEntityBean jsonBean = new JsonEntityBean(entity, entityEnum);
// the group member interface doesn't include the entity name, so
// we'll need to look that up manually
jsonBean.setName(lookupEntityName(jsonBean)); // depends on control dependency: [if], data = [none]
if (EntityEnum.GROUP.equals(jsonBean.getEntityType())
|| EntityEnum.PERSON.equals(jsonBean.getEntityType())) {
IAuthorizationPrincipal principal = getPrincipalForEntity(jsonBean);
jsonBean.setPrincipalString(principal.getPrincipalString()); // depends on control dependency: [if], data = [none]
}
return jsonBean; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public int compare(Morsel o1, Morsel o2) {
if (o1.getMarker() != null && o2.getMarker() == null) {
return 1;
}
if (o2.getMarker() != null && o1.getMarker() == null) {
return -1;
}
int spaceCompare = o1.getSpaceId().compareTo(o2.getSpaceId());
if (spaceCompare == 0) {
return o1.getAccount().compareTo(o2.getAccount());
} else {
return spaceCompare;
}
} } | public class class_name {
@Override
public int compare(Morsel o1, Morsel o2) {
if (o1.getMarker() != null && o2.getMarker() == null) {
return 1; // depends on control dependency: [if], data = [none]
}
if (o2.getMarker() != null && o1.getMarker() == null) {
return -1; // depends on control dependency: [if], data = [none]
}
int spaceCompare = o1.getSpaceId().compareTo(o2.getSpaceId());
if (spaceCompare == 0) {
return o1.getAccount().compareTo(o2.getAccount()); // depends on control dependency: [if], data = [none]
} else {
return spaceCompare; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setOwner(String src, String username, String group
) throws IOException {
INode[] inodes = null;
writeLock();
try {
if (isInSafeMode()) {
throw new SafeModeException("Cannot set permission for " + src, safeMode);
}
inodes = dir.getExistingPathINodes(src);
if (isPermissionCheckingEnabled(inodes)) {
FSPermissionChecker pc = checkOwner(src, inodes);
if (!pc.isSuper) {
if (username != null && !pc.user.equals(username)) {
if (this.permissionAuditOnly) {
// do not throw the exception, we would like to only log.
LOG.warn("PermissionAudit failed on " + src +
": non-super user cannot change owner.");
} else {
throw new AccessControlException("Non-super user cannot change owner.");
}
}
if (group != null && !pc.containsGroup(group)) {
if (this.permissionAuditOnly) {
// do not throw the exception, we would like to only log.
LOG.warn("PermissionAudit failed on " + src +
": user does not belong to " + group + " .");
} else {
throw new AccessControlException("User does not belong to " + group
+ " .");
}
}
}
}
dir.setOwner(src, username, group);
} finally {
writeUnlock();
}
getEditLog().logSync(false);
if (auditLog.isInfoEnabled()) {
logAuditEvent(getCurrentUGI(),
Server.getRemoteIp(),
"setOwner", src, null, getLastINode(inodes));
}
} } | public class class_name {
public void setOwner(String src, String username, String group
) throws IOException {
INode[] inodes = null;
writeLock();
try {
if (isInSafeMode()) {
throw new SafeModeException("Cannot set permission for " + src, safeMode);
}
inodes = dir.getExistingPathINodes(src);
if (isPermissionCheckingEnabled(inodes)) {
FSPermissionChecker pc = checkOwner(src, inodes);
if (!pc.isSuper) {
if (username != null && !pc.user.equals(username)) {
if (this.permissionAuditOnly) {
// do not throw the exception, we would like to only log.
LOG.warn("PermissionAudit failed on " + src +
": non-super user cannot change owner."); // depends on control dependency: [if], data = [none]
} else {
throw new AccessControlException("Non-super user cannot change owner.");
}
}
if (group != null && !pc.containsGroup(group)) {
if (this.permissionAuditOnly) {
// do not throw the exception, we would like to only log.
LOG.warn("PermissionAudit failed on " + src +
": user does not belong to " + group + " ."); // depends on control dependency: [if], data = [none]
} else {
throw new AccessControlException("User does not belong to " + group
+ " .");
}
}
}
}
dir.setOwner(src, username, group);
} finally {
writeUnlock();
}
getEditLog().logSync(false);
if (auditLog.isInfoEnabled()) {
logAuditEvent(getCurrentUGI(),
Server.getRemoteIp(),
"setOwner", src, null, getLastINode(inodes));
}
} } |
public class class_name {
@Override
public int compareTo(Flow otherFlow) {
if (otherFlow == null) {
return -1;
}
return new CompareToBuilder().append(this.key, otherFlow.getFlowKey())
.toComparison();
} } | public class class_name {
@Override
public int compareTo(Flow otherFlow) {
if (otherFlow == null) {
return -1; // depends on control dependency: [if], data = [none]
}
return new CompareToBuilder().append(this.key, otherFlow.getFlowKey())
.toComparison();
} } |
public class class_name {
public void setActivePage(IEditorPart part) {
if (activeEditorPart == part)
return;
activeEditorPart = part;
IActionBars actionBars = getActionBars();
if (actionBars != null) {
ITextEditor editor = (part instanceof ITextEditor) ? (ITextEditor) part : null;
actionBars.setGlobalActionHandler(
ActionFactory.DELETE.getId(),
getAction(editor, ITextEditorActionConstants.DELETE));
actionBars.setGlobalActionHandler(
ActionFactory.UNDO.getId(),
getAction(editor, ITextEditorActionConstants.UNDO));
actionBars.setGlobalActionHandler(
ActionFactory.REDO.getId(),
getAction(editor, ITextEditorActionConstants.REDO));
actionBars.setGlobalActionHandler(
ActionFactory.CUT.getId(),
getAction(editor, ITextEditorActionConstants.CUT));
actionBars.setGlobalActionHandler(
ActionFactory.COPY.getId(),
getAction(editor, ITextEditorActionConstants.COPY));
actionBars.setGlobalActionHandler(
ActionFactory.PASTE.getId(),
getAction(editor, ITextEditorActionConstants.PASTE));
actionBars.setGlobalActionHandler(
ActionFactory.SELECT_ALL.getId(),
getAction(editor, ITextEditorActionConstants.SELECT_ALL));
actionBars.setGlobalActionHandler(
ActionFactory.FIND.getId(),
getAction(editor, ITextEditorActionConstants.FIND));
actionBars.setGlobalActionHandler(
IDEActionFactory.BOOKMARK.getId(),
getAction(editor, IDEActionFactory.BOOKMARK.getId()));
actionBars.updateActionBars();
}
} } | public class class_name {
public void setActivePage(IEditorPart part) {
if (activeEditorPart == part)
return;
activeEditorPart = part;
IActionBars actionBars = getActionBars();
if (actionBars != null) {
ITextEditor editor = (part instanceof ITextEditor) ? (ITextEditor) part : null;
actionBars.setGlobalActionHandler(
ActionFactory.DELETE.getId(),
getAction(editor, ITextEditorActionConstants.DELETE)); // depends on control dependency: [if], data = [none]
actionBars.setGlobalActionHandler(
ActionFactory.UNDO.getId(),
getAction(editor, ITextEditorActionConstants.UNDO)); // depends on control dependency: [if], data = [none]
actionBars.setGlobalActionHandler(
ActionFactory.REDO.getId(),
getAction(editor, ITextEditorActionConstants.REDO)); // depends on control dependency: [if], data = [none]
actionBars.setGlobalActionHandler(
ActionFactory.CUT.getId(),
getAction(editor, ITextEditorActionConstants.CUT)); // depends on control dependency: [if], data = [none]
actionBars.setGlobalActionHandler(
ActionFactory.COPY.getId(),
getAction(editor, ITextEditorActionConstants.COPY)); // depends on control dependency: [if], data = [none]
actionBars.setGlobalActionHandler(
ActionFactory.PASTE.getId(),
getAction(editor, ITextEditorActionConstants.PASTE)); // depends on control dependency: [if], data = [none]
actionBars.setGlobalActionHandler(
ActionFactory.SELECT_ALL.getId(),
getAction(editor, ITextEditorActionConstants.SELECT_ALL)); // depends on control dependency: [if], data = [none]
actionBars.setGlobalActionHandler(
ActionFactory.FIND.getId(),
getAction(editor, ITextEditorActionConstants.FIND)); // depends on control dependency: [if], data = [none]
actionBars.setGlobalActionHandler(
IDEActionFactory.BOOKMARK.getId(),
getAction(editor, IDEActionFactory.BOOKMARK.getId())); // depends on control dependency: [if], data = [none]
actionBars.updateActionBars(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public TransportApiResult<List<FareProduct>> getFareProducts(FareProductQueryOptions options)
{
if (options == null)
{
options = FareProductQueryOptions.defaultQueryOptions();
}
return TransportApiClientCalls.getFareProducts(tokenComponent, settings, options);
} } | public class class_name {
public TransportApiResult<List<FareProduct>> getFareProducts(FareProductQueryOptions options)
{
if (options == null)
{
options = FareProductQueryOptions.defaultQueryOptions();
// depends on control dependency: [if], data = [none]
}
return TransportApiClientCalls.getFareProducts(tokenComponent, settings, options);
} } |
public class class_name {
public void setSlf4jLogname(String logName)
{
// use length() == 0 instead of isEmpty() for Java 5 compatibility
if( logName.length() == 0 )
{
m_log = null;
}
else
{
m_log = LoggerFactory.getLogger(logName);
}
} } | public class class_name {
public void setSlf4jLogname(String logName)
{
// use length() == 0 instead of isEmpty() for Java 5 compatibility
if( logName.length() == 0 )
{
m_log = null; // depends on control dependency: [if], data = [none]
}
else
{
m_log = LoggerFactory.getLogger(logName); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public List<? extends Property> getLoginPropertyList() {
List<Property> props = new LinkedList<Property>();
if (loginConfigProperties == null) {
return props;
} else {
for (Map.Entry<String, String> entry : loginConfigProperties.entrySet())
props.add(new PropertyImpl(entry.getKey(), entry.getValue()));
return props;
}
}
/**
* Returns the container-managed auth alias
* that may be specified on the res-ref-properties or cmp-bean-properties
* in j2c.properties
* Used only by the SIB RA
*/
@Override
public String getContainerAlias() {
return _containerAlias;
}
/*
* Set methods for all fields
*/
/**
* Sets the sharing scope.
*
* @param i Expected to be one of <code>SHAREABLE</code> or <code>UNSHAREABLE</code>
* as defined by the constants in <code>com.ibm.websphere.csi.ResRef</code>
*/
protected void setSharingScope(int i) {
if (i == J2CConstants.CONNECTION_SHAREABLE) {
res_sharing_scope = true;
} else {
if (i == J2CConstants.CONNECTION_UNSHAREABLE) {
res_sharing_scope = false;
} else {
Tr.warning(TC, "INVALID_OR_UNEXPECTED_SETTING_J2CA0067", "sharing scope", i, false);
res_sharing_scope = false; // default to false if unexpected int value
}
}
}
/**
* Returns a readable view of the ConnectionManager res-xxx config data
*
* @return String representation of this CMConfigDataImpl instance
*/
@Override
public String toString() {
StringBuffer buf = new StringBuffer(256);
final String nl = CommonFunction.nl;
String res_sharing_scopeString = "UNSHAREABLE";
String res_isolation_levelString = "undefined";
String res_authString = "undefined";
if (res_sharing_scope == true) {
res_sharing_scopeString = "SHAREABLE";
}
switch (res_isolation_level) {
case java.sql.Connection.TRANSACTION_NONE:
res_isolation_levelString = "TRANSACTION_NONE";
break;
case java.sql.Connection.TRANSACTION_READ_UNCOMMITTED:
res_isolation_levelString = "TRANSACTION_READ_UNCOMMITTED";
break;
case java.sql.Connection.TRANSACTION_READ_COMMITTED:
res_isolation_levelString = "TRANSACTION_READ_COMMITTED";
break;
case java.sql.Connection.TRANSACTION_REPEATABLE_READ:
res_isolation_levelString = "TRANSACTION_REPEATABLE_READ";
break;
case java.sql.Connection.TRANSACTION_SERIALIZABLE:
res_isolation_levelString = "TRANSACTION_SERIALIZABLE";
break;
default:
break;
}
if (res_auth == J2CConstants.AUTHENTICATION_CONTAINER) {
res_authString = "CONTAINER";
} else {
if (res_auth == J2CConstants.AUTHENTICATION_APPLICATION) {
res_authString = "APPLICATION";
}
}
// key items
buf.append(nl);
buf.append("[Resource-ref CMConfigData key items]" + nl);
buf.append(nl);
// put buf.appends on multiple lines.
buf.append("\tres-sharing-scope: ");
int ss = (res_sharing_scope ? J2CConstants.CONNECTION_SHAREABLE : J2CConstants.CONNECTION_UNSHAREABLE);
buf.append(ss);
buf.append(" (");
buf.append(res_sharing_scopeString);
buf.append(")");
buf.append(nl);
buf.append("\tres-isolation-level: ");
buf.append(res_isolation_level);
buf.append(" (");
buf.append(res_isolation_levelString);
buf.append(")");
buf.append(nl);
buf.append("\tres-auth: ");
buf.append(res_auth);
buf.append(" (");
buf.append(res_authString);
buf.append(")");
buf.append(nl);
buf.append("\tcommitPriority ");
buf.append(_commitPriority);
buf.append(nl);
buf.append("\tbranchCoupling ");
buf.append(_branchCoupling);
buf.append(nl);
buf.append("\tloginConfigurationName: ");
buf.append(loginConfigurationName);
buf.append(nl);
buf.append("\tloginConfigProperties: ");
buf.append(loginConfigProperties);
buf.append(nl);
String resRefNameString = ((_resRefName == null) ? "not set" : _resRefName);
buf.append("\tResource ref name: ");
buf.append(resRefNameString);
buf.append(nl);
String qmidString = ((qmid == null) ? "not set" : qmid);
buf.append("\tQueue manager id: ");
buf.append(qmidString);
buf.append(nl);
return buf.toString();
}
/**
* @return _CfKey
*/
@Override
public String getCfKey() {
return _CfKey;
}
/**
* @param o A CMConfigDataImpl Object that will be compared.
*
* @return true if object o is equal to this CMConfigDataImpl.
*/
@Override
public boolean equals(Object o) {
boolean rVal = false;
if (o != null) { // obviously this cannot be null.
if (this == o) {
rVal = true;
} else {
try {
CMConfigDataImpl compare = (CMConfigDataImpl) o;
/*
* If the addresses are not equal and the cast is sucessful we need to check the individual members, otherwise continue on.
* Primitives are checked with ==, Objects are checked with == then .equals (if one of them is not null).
*/
// collapsed all the checks into just this comparison of cfDetailsKey, since that already included all the other constituents
if (this.cfDetailsKey == compare.cfDetailsKey || (this.cfDetailsKey != null && this.cfDetailsKey.equals(compare.cfDetailsKey))) {
rVal = true;
}
} catch (ClassCastException cce) {
rVal = false;
}
}
}
return rVal;
}
/**
* Generates a hashcode for the CMConfigData object. The hashcode is based on each member's
* hashcode (or value, for int members).
*
* @return the hashcode for this object.
*/
/* */
@Override
public int hashCode() {
int rVal = 0;
long tempHC = 0;
// collapsed hashCode into just that of cfDetailsKey, since it already included the other constituents
tempHC += cfDetailsKey.hashCode();
rVal = (Long.valueOf(tempHC / 10)).intValue();
return rVal;
}
/*
* This method rereates the CMConfigData Object from a stream - all the members will be
* re-initialized.
*/
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
/*
* Since this is a simple class all we have to do is read each member from the stream.
* the order has to remain identical to writeObject, so I've just gone alphabetically.
*
* If we change the serialversionUID, we may need to modify this method as well.
*/
if (TC.isEntryEnabled()) {
Tr.entry(this, TC, "readObject", stream);
}
ObjectInputStream.GetField getField = stream.readFields();
if (TC.isDebugEnabled()) {
for (int i = 0; i < serialPersistentFields.length; i++) {
String fieldName = serialPersistentFields[i].getName();
if (getField.defaulted(fieldName))
Tr.debug(this, TC, "Could not de-serialize field " + fieldName + " in class " +
getClass().getName() + "; default value will be used");
}
}
cf_name = (String) getField.get("cf_name", null);
cfDetailsKey = (String) getField.get("cfDetailsKey", null);
_CfKey = (String) getField.get("_CfKey", null);
jndiName = (String) getField.get("_PmiName", null);
res_auth = getField.get("res_auth", 999);
res_isolation_level = getField.get("res_isolation_level", 999);
res_resolution_control = getField.get("res_resolution_control", 999);
res_sharing_scope = getField.get("res_sharing_scope", false);
loginConfigurationName = (String) getField.get("loginConfigurationName", null);
loginConfigProperties = (HashMap<String, String>) getField.get("loginConfigProperties", null);
loginConfigPropsKeyString = (String) getField.get("loginConfigPropsKeyString", null);
_commitPriority = getField.get("_commitPriority", 0);
_branchCoupling = getField.get("_branchCoupling", 999);
qmid = (String) getField.get("qmid", null);
if (TC.isEntryEnabled())
Tr.exit(this, TC, "readObject", new Object[] {
cf_name,
cfDetailsKey,
_CfKey,
jndiName,
res_auth,
res_isolation_level,
res_resolution_control,
res_sharing_scope,
loginConfigurationName,
loginConfigProperties,
loginConfigPropsKeyString,
_containerAlias,
_commitPriority,
_branchCoupling
});
}
/*
* this method writes the CMConfigDataOjbect to a stream
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
/*
* Since this is a simple class all we have to do is write each member to the stream.
* the order has to remain identical to readObject, so I've just gone alphabetically.
*
* If we change the serialversionUID, we may need to modify this method as well.
*/
if (TC.isEntryEnabled()) {
Tr.entry(this, TC, "writeObject");
}
ObjectOutputStream.PutField putField = stream.putFields();
putField.put("cf_name", cf_name);
putField.put("cfDetailsKey", cfDetailsKey);
putField.put("_CfKey", _CfKey);
putField.put("_PmiName", jndiName);
putField.put("res_auth", res_auth);
putField.put("res_isolation_level", res_isolation_level);
putField.put("res_resolution_control", res_resolution_control);
putField.put("res_sharing_scope", res_sharing_scope);
putField.put("loginConfigurationName", loginConfigurationName);
putField.put("loginConfigProperties", loginConfigProperties);
putField.put("loginConfigPropsKeyString", loginConfigPropsKeyString);
putField.put("_commitPriority", _commitPriority);
putField.put("_branchCoupling", _branchCoupling);
putField.put("qmid", qmid);
stream.writeFields();
if (TC.isEntryEnabled()) {
Tr.exit(this, TC, "writeObject");
}
} } | public class class_name {
@Override
public List<? extends Property> getLoginPropertyList() {
List<Property> props = new LinkedList<Property>();
if (loginConfigProperties == null) {
return props; // depends on control dependency: [if], data = [none]
} else {
for (Map.Entry<String, String> entry : loginConfigProperties.entrySet())
props.add(new PropertyImpl(entry.getKey(), entry.getValue()));
return props; // depends on control dependency: [if], data = [none]
}
}
/**
* Returns the container-managed auth alias
* that may be specified on the res-ref-properties or cmp-bean-properties
* in j2c.properties
* Used only by the SIB RA
*/
@Override
public String getContainerAlias() {
return _containerAlias;
}
/*
* Set methods for all fields
*/
/**
* Sets the sharing scope.
*
* @param i Expected to be one of <code>SHAREABLE</code> or <code>UNSHAREABLE</code>
* as defined by the constants in <code>com.ibm.websphere.csi.ResRef</code>
*/
protected void setSharingScope(int i) {
if (i == J2CConstants.CONNECTION_SHAREABLE) {
res_sharing_scope = true; // depends on control dependency: [if], data = [none]
} else {
if (i == J2CConstants.CONNECTION_UNSHAREABLE) {
res_sharing_scope = false; // depends on control dependency: [if], data = [none]
} else {
Tr.warning(TC, "INVALID_OR_UNEXPECTED_SETTING_J2CA0067", "sharing scope", i, false); // depends on control dependency: [if], data = [none]
res_sharing_scope = false; // default to false if unexpected int value // depends on control dependency: [if], data = [none]
}
}
}
/**
* Returns a readable view of the ConnectionManager res-xxx config data
*
* @return String representation of this CMConfigDataImpl instance
*/
@Override
public String toString() {
StringBuffer buf = new StringBuffer(256);
final String nl = CommonFunction.nl;
String res_sharing_scopeString = "UNSHAREABLE";
String res_isolation_levelString = "undefined";
String res_authString = "undefined";
if (res_sharing_scope == true) {
res_sharing_scopeString = "SHAREABLE"; // depends on control dependency: [if], data = [none]
}
switch (res_isolation_level) {
case java.sql.Connection.TRANSACTION_NONE:
res_isolation_levelString = "TRANSACTION_NONE";
break;
case java.sql.Connection.TRANSACTION_READ_UNCOMMITTED:
res_isolation_levelString = "TRANSACTION_READ_UNCOMMITTED";
break;
case java.sql.Connection.TRANSACTION_READ_COMMITTED:
res_isolation_levelString = "TRANSACTION_READ_COMMITTED";
break;
case java.sql.Connection.TRANSACTION_REPEATABLE_READ:
res_isolation_levelString = "TRANSACTION_REPEATABLE_READ";
break;
case java.sql.Connection.TRANSACTION_SERIALIZABLE:
res_isolation_levelString = "TRANSACTION_SERIALIZABLE";
break;
default:
break;
}
if (res_auth == J2CConstants.AUTHENTICATION_CONTAINER) {
res_authString = "CONTAINER"; // depends on control dependency: [if], data = [none]
} else {
if (res_auth == J2CConstants.AUTHENTICATION_APPLICATION) {
res_authString = "APPLICATION"; // depends on control dependency: [if], data = [none]
}
}
// key items
buf.append(nl);
buf.append("[Resource-ref CMConfigData key items]" + nl);
buf.append(nl);
// put buf.appends on multiple lines.
buf.append("\tres-sharing-scope: ");
int ss = (res_sharing_scope ? J2CConstants.CONNECTION_SHAREABLE : J2CConstants.CONNECTION_UNSHAREABLE);
buf.append(ss);
buf.append(" (");
buf.append(res_sharing_scopeString);
buf.append(")");
buf.append(nl);
buf.append("\tres-isolation-level: ");
buf.append(res_isolation_level);
buf.append(" (");
buf.append(res_isolation_levelString);
buf.append(")");
buf.append(nl);
buf.append("\tres-auth: ");
buf.append(res_auth);
buf.append(" (");
buf.append(res_authString);
buf.append(")");
buf.append(nl);
buf.append("\tcommitPriority ");
buf.append(_commitPriority);
buf.append(nl);
buf.append("\tbranchCoupling ");
buf.append(_branchCoupling);
buf.append(nl);
buf.append("\tloginConfigurationName: ");
buf.append(loginConfigurationName);
buf.append(nl);
buf.append("\tloginConfigProperties: ");
buf.append(loginConfigProperties);
buf.append(nl);
String resRefNameString = ((_resRefName == null) ? "not set" : _resRefName);
buf.append("\tResource ref name: ");
buf.append(resRefNameString);
buf.append(nl);
String qmidString = ((qmid == null) ? "not set" : qmid);
buf.append("\tQueue manager id: ");
buf.append(qmidString);
buf.append(nl);
return buf.toString();
}
/**
* @return _CfKey
*/
@Override
public String getCfKey() {
return _CfKey;
}
/**
* @param o A CMConfigDataImpl Object that will be compared.
*
* @return true if object o is equal to this CMConfigDataImpl.
*/
@Override
public boolean equals(Object o) {
boolean rVal = false;
if (o != null) { // obviously this cannot be null.
if (this == o) {
rVal = true; // depends on control dependency: [if], data = [none]
} else {
try {
CMConfigDataImpl compare = (CMConfigDataImpl) o;
/*
* If the addresses are not equal and the cast is sucessful we need to check the individual members, otherwise continue on.
* Primitives are checked with ==, Objects are checked with == then .equals (if one of them is not null).
*/
// collapsed all the checks into just this comparison of cfDetailsKey, since that already included all the other constituents
if (this.cfDetailsKey == compare.cfDetailsKey || (this.cfDetailsKey != null && this.cfDetailsKey.equals(compare.cfDetailsKey))) {
rVal = true; // depends on control dependency: [if], data = [none]
}
} catch (ClassCastException cce) {
rVal = false;
} // depends on control dependency: [catch], data = [none]
}
}
return rVal;
}
/**
* Generates a hashcode for the CMConfigData object. The hashcode is based on each member's
* hashcode (or value, for int members).
*
* @return the hashcode for this object.
*/
/* */
@Override
public int hashCode() {
int rVal = 0;
long tempHC = 0;
// collapsed hashCode into just that of cfDetailsKey, since it already included the other constituents
tempHC += cfDetailsKey.hashCode();
rVal = (Long.valueOf(tempHC / 10)).intValue();
return rVal;
}
/*
* This method rereates the CMConfigData Object from a stream - all the members will be
* re-initialized.
*/
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
/*
* Since this is a simple class all we have to do is read each member from the stream.
* the order has to remain identical to writeObject, so I've just gone alphabetically.
*
* If we change the serialversionUID, we may need to modify this method as well.
*/
if (TC.isEntryEnabled()) {
Tr.entry(this, TC, "readObject", stream);
}
ObjectInputStream.GetField getField = stream.readFields();
if (TC.isDebugEnabled()) {
for (int i = 0; i < serialPersistentFields.length; i++) {
String fieldName = serialPersistentFields[i].getName();
if (getField.defaulted(fieldName))
Tr.debug(this, TC, "Could not de-serialize field " + fieldName + " in class " +
getClass().getName() + "; default value will be used");
}
}
cf_name = (String) getField.get("cf_name", null);
cfDetailsKey = (String) getField.get("cfDetailsKey", null);
_CfKey = (String) getField.get("_CfKey", null);
jndiName = (String) getField.get("_PmiName", null);
res_auth = getField.get("res_auth", 999);
res_isolation_level = getField.get("res_isolation_level", 999);
res_resolution_control = getField.get("res_resolution_control", 999);
res_sharing_scope = getField.get("res_sharing_scope", false);
loginConfigurationName = (String) getField.get("loginConfigurationName", null);
loginConfigProperties = (HashMap<String, String>) getField.get("loginConfigProperties", null);
loginConfigPropsKeyString = (String) getField.get("loginConfigPropsKeyString", null);
_commitPriority = getField.get("_commitPriority", 0);
_branchCoupling = getField.get("_branchCoupling", 999);
qmid = (String) getField.get("qmid", null);
if (TC.isEntryEnabled())
Tr.exit(this, TC, "readObject", new Object[] {
cf_name,
cfDetailsKey,
_CfKey,
jndiName,
res_auth,
res_isolation_level,
res_resolution_control,
res_sharing_scope,
loginConfigurationName,
loginConfigProperties,
loginConfigPropsKeyString,
_containerAlias,
_commitPriority,
_branchCoupling
});
}
/*
* this method writes the CMConfigDataOjbect to a stream
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
/*
* Since this is a simple class all we have to do is write each member to the stream.
* the order has to remain identical to readObject, so I've just gone alphabetically.
*
* If we change the serialversionUID, we may need to modify this method as well.
*/
if (TC.isEntryEnabled()) {
Tr.entry(this, TC, "writeObject");
}
ObjectOutputStream.PutField putField = stream.putFields();
putField.put("cf_name", cf_name);
putField.put("cfDetailsKey", cfDetailsKey);
putField.put("_CfKey", _CfKey);
putField.put("_PmiName", jndiName);
putField.put("res_auth", res_auth);
putField.put("res_isolation_level", res_isolation_level);
putField.put("res_resolution_control", res_resolution_control);
putField.put("res_sharing_scope", res_sharing_scope);
putField.put("loginConfigurationName", loginConfigurationName);
putField.put("loginConfigProperties", loginConfigProperties);
putField.put("loginConfigPropsKeyString", loginConfigPropsKeyString);
putField.put("_commitPriority", _commitPriority);
putField.put("_branchCoupling", _branchCoupling);
putField.put("qmid", qmid);
stream.writeFields();
if (TC.isEntryEnabled()) {
Tr.exit(this, TC, "writeObject");
}
} } |
public class class_name {
public static void cancelTasks(final Context context,
Class<? extends GroundyService> groundyServiceClass, final int groupId, final int reason,
final CancelListener cancelListener) {
if (groupId <= 0) {
throw new IllegalStateException("Group id must be greater than zero");
}
new GroundyServiceConnection(context, groundyServiceClass) {
@Override
protected void onGroundyServiceBound(GroundyService.GroundyServiceBinder binder) {
GroundyService.CancelGroupResponse cancelGroupResponse =
binder.cancelTasks(groupId, reason);
if (cancelListener != null) {
cancelListener.onCancelResult(groupId, cancelGroupResponse);
}
}
}.start();
} } | public class class_name {
public static void cancelTasks(final Context context,
Class<? extends GroundyService> groundyServiceClass, final int groupId, final int reason,
final CancelListener cancelListener) {
if (groupId <= 0) {
throw new IllegalStateException("Group id must be greater than zero");
}
new GroundyServiceConnection(context, groundyServiceClass) {
@Override
protected void onGroundyServiceBound(GroundyService.GroundyServiceBinder binder) {
GroundyService.CancelGroupResponse cancelGroupResponse =
binder.cancelTasks(groupId, reason);
if (cancelListener != null) {
cancelListener.onCancelResult(groupId, cancelGroupResponse); // depends on control dependency: [if], data = [none]
}
}
}.start();
} } |
public class class_name {
public static <T> Iterator<T> limit(final Iterator<? extends T> base, final CountingPredicate<? super T> filter) {
return new Iterator<T>() {
private T next;
private boolean end;
private int index=0;
public boolean hasNext() {
fetch();
return next!=null;
}
public T next() {
fetch();
T r = next;
next = null;
return r;
}
private void fetch() {
if (next==null && !end) {
if (base.hasNext()) {
next = base.next();
if (!filter.apply(index++,next)) {
next = null;
end = true;
}
} else {
end = true;
}
}
}
public void remove() {
throw new UnsupportedOperationException();
}
};
} } | public class class_name {
public static <T> Iterator<T> limit(final Iterator<? extends T> base, final CountingPredicate<? super T> filter) {
return new Iterator<T>() {
private T next;
private boolean end;
private int index=0;
public boolean hasNext() {
fetch();
return next!=null;
}
public T next() {
fetch();
T r = next;
next = null;
return r;
}
private void fetch() {
if (next==null && !end) {
if (base.hasNext()) {
next = base.next(); // depends on control dependency: [if], data = [none]
if (!filter.apply(index++,next)) {
next = null; // depends on control dependency: [if], data = [none]
end = true; // depends on control dependency: [if], data = [none]
}
} else {
end = true; // depends on control dependency: [if], data = [none]
}
}
}
public void remove() {
throw new UnsupportedOperationException();
}
};
} } |
public class class_name {
public void close() {
synchronized (receivers) {
Iterator i = receivers.iterator();
while (i.hasNext()) {
ReceiverQueue r = (ReceiverQueue) i.next();
r.onTransmissionClose();
}
closed = true;
receivers.clear();
}
} } | public class class_name {
public void close() {
synchronized (receivers) {
Iterator i = receivers.iterator();
while (i.hasNext()) {
ReceiverQueue r = (ReceiverQueue) i.next();
r.onTransmissionClose(); // depends on control dependency: [while], data = [none]
}
closed = true;
receivers.clear();
}
} } |
public class class_name {
protected final ServiceController<?> addHardcodedAbsolutePath(final ServiceTarget serviceTarget, final String pathName, final String path) {
ServiceController<?> controller = addAbsolutePathService(serviceTarget, pathName, path);
addPathEntry(pathName, path, null, true);
if (capabilityRegistry != null) {
RuntimeCapability<Void> pathCapability = PATH_CAPABILITY.fromBaseCapability(pathName);
capabilityRegistry.registerCapability(
new RuntimeCapabilityRegistration(pathCapability, CapabilityScope.GLOBAL, new RegistrationPoint(PathAddress.EMPTY_ADDRESS, null)));
}
return controller;
} } | public class class_name {
protected final ServiceController<?> addHardcodedAbsolutePath(final ServiceTarget serviceTarget, final String pathName, final String path) {
ServiceController<?> controller = addAbsolutePathService(serviceTarget, pathName, path);
addPathEntry(pathName, path, null, true);
if (capabilityRegistry != null) {
RuntimeCapability<Void> pathCapability = PATH_CAPABILITY.fromBaseCapability(pathName);
capabilityRegistry.registerCapability(
new RuntimeCapabilityRegistration(pathCapability, CapabilityScope.GLOBAL, new RegistrationPoint(PathAddress.EMPTY_ADDRESS, null))); // depends on control dependency: [if], data = [none]
}
return controller;
} } |
public class class_name {
public PKCS10CertificationRequest createSigningRequest(PrivateKey privateKey,
PublicKey publicKey, String subjectString) {
try {
logger.entry();
logger.debug("Creating the CSR...");
X500Principal subject = new X500Principal(subjectString);
ContentSigner signer = new JcaContentSignerBuilder(ASYMMETRIC_SIGNATURE_ALGORITHM).build(privateKey);
PKCS10CertificationRequest result = new JcaPKCS10CertificationRequestBuilder(subject, publicKey)
.setLeaveOffEmptyAttributes(true).build(signer);
logger.exit();
return result;
} catch (OperatorCreationException e) {
RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to generate a new certificate signing request.", e);
logger.error(exception.toString());
throw exception;
}
} } | public class class_name {
public PKCS10CertificationRequest createSigningRequest(PrivateKey privateKey,
PublicKey publicKey, String subjectString) {
try {
logger.entry();
// depends on control dependency: [try], data = [none]
logger.debug("Creating the CSR...");
// depends on control dependency: [try], data = [none]
X500Principal subject = new X500Principal(subjectString);
ContentSigner signer = new JcaContentSignerBuilder(ASYMMETRIC_SIGNATURE_ALGORITHM).build(privateKey);
PKCS10CertificationRequest result = new JcaPKCS10CertificationRequestBuilder(subject, publicKey)
.setLeaveOffEmptyAttributes(true).build(signer);
logger.exit();
// depends on control dependency: [try], data = [none]
return result;
// depends on control dependency: [try], data = [none]
} catch (OperatorCreationException e) {
RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to generate a new certificate signing request.", e);
logger.error(exception.toString());
throw exception;
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void validateAndSetQuery() {
if (start == null || start.isEmpty()) {
throw new IllegalArgumentException("Missing start time");
}
start_time = DateTime.parseDateTimeString(start, timezone);
if (end != null && !end.isEmpty()) {
end_time = DateTime.parseDateTimeString(end, timezone);
} else {
end_time = System.currentTimeMillis();
}
if (end_time <= start_time) {
throw new IllegalArgumentException(
"End time [" + end_time + "] must be greater than the start time ["
+ start_time +"]");
}
if (queries == null || queries.isEmpty()) {
throw new IllegalArgumentException("Missing queries");
}
// validate queries
int i = 0;
for (TSSubQuery sub : queries) {
sub.validateAndSetQuery();
final DownsamplingSpecification ds = sub.downsamplingSpecification();
if (ds != null && timezone != null && !timezone.isEmpty() &&
ds != DownsamplingSpecification.NO_DOWNSAMPLER) {
final TimeZone tz = DateTime.timezones.get(timezone);
if (tz == null) {
throw new IllegalArgumentException(
"The timezone specification could not be found");
}
ds.setTimezone(tz);
}
if (ds != null && use_calendar &&
ds != DownsamplingSpecification.NO_DOWNSAMPLER) {
ds.setUseCalendar(true);
}
sub.setIndex(i++);
}
} } | public class class_name {
public void validateAndSetQuery() {
if (start == null || start.isEmpty()) {
throw new IllegalArgumentException("Missing start time");
}
start_time = DateTime.parseDateTimeString(start, timezone);
if (end != null && !end.isEmpty()) {
end_time = DateTime.parseDateTimeString(end, timezone); // depends on control dependency: [if], data = [(end]
} else {
end_time = System.currentTimeMillis(); // depends on control dependency: [if], data = [none]
}
if (end_time <= start_time) {
throw new IllegalArgumentException(
"End time [" + end_time + "] must be greater than the start time ["
+ start_time +"]");
}
if (queries == null || queries.isEmpty()) {
throw new IllegalArgumentException("Missing queries");
}
// validate queries
int i = 0;
for (TSSubQuery sub : queries) {
sub.validateAndSetQuery(); // depends on control dependency: [for], data = [sub]
final DownsamplingSpecification ds = sub.downsamplingSpecification();
if (ds != null && timezone != null && !timezone.isEmpty() &&
ds != DownsamplingSpecification.NO_DOWNSAMPLER) {
final TimeZone tz = DateTime.timezones.get(timezone);
if (tz == null) {
throw new IllegalArgumentException(
"The timezone specification could not be found");
}
ds.setTimezone(tz); // depends on control dependency: [if], data = [none]
}
if (ds != null && use_calendar &&
ds != DownsamplingSpecification.NO_DOWNSAMPLER) {
ds.setUseCalendar(true); // depends on control dependency: [if], data = [none]
}
sub.setIndex(i++); // depends on control dependency: [for], data = [sub]
}
} } |
public class class_name {
void ReconstructPrivateDict(int Font,OffsetItem[] fdPrivate,IndexBaseItem[] fdPrivateBase,
OffsetItem[] fdSubrs)
{
// For each fdarray private dict check if that FD is used.
// if is used build a new one by changing the subrs offset
// Else do nothing
for (int i=0;i<fonts[Font].fdprivateOffsets.length;i++)
{
if (FDArrayUsed.containsKey(Integer.valueOf(i)))
{
// Mark beginning
OutputList.addLast(new MarkerItem(fdPrivate[i]));
fdPrivateBase[i] = new IndexBaseItem();
OutputList.addLast(fdPrivateBase[i]);
// Goto beginning of objects
seek(fonts[Font].fdprivateOffsets[i]);
while (getPosition() < fonts[Font].fdprivateOffsets[i]+fonts[Font].fdprivateLengths[i])
{
int p1 = getPosition();
getDictItem();
int p2 = getPosition();
// If the dictItem is the "Subrs" then,
// use marker for offset and write operator number
if (key=="Subrs") {
fdSubrs[i] = new DictOffsetItem();
OutputList.addLast(fdSubrs[i]);
OutputList.addLast(new UInt8Item((char)19)); // Subrs
}
// Else copy the entire range
else
OutputList.addLast(new RangeItem(buf,p1,p2-p1));
}
}
}
} } | public class class_name {
void ReconstructPrivateDict(int Font,OffsetItem[] fdPrivate,IndexBaseItem[] fdPrivateBase,
OffsetItem[] fdSubrs)
{
// For each fdarray private dict check if that FD is used.
// if is used build a new one by changing the subrs offset
// Else do nothing
for (int i=0;i<fonts[Font].fdprivateOffsets.length;i++)
{
if (FDArrayUsed.containsKey(Integer.valueOf(i)))
{
// Mark beginning
OutputList.addLast(new MarkerItem(fdPrivate[i])); // depends on control dependency: [if], data = [none]
fdPrivateBase[i] = new IndexBaseItem(); // depends on control dependency: [if], data = [none]
OutputList.addLast(fdPrivateBase[i]); // depends on control dependency: [if], data = [none]
// Goto beginning of objects
seek(fonts[Font].fdprivateOffsets[i]); // depends on control dependency: [if], data = [none]
while (getPosition() < fonts[Font].fdprivateOffsets[i]+fonts[Font].fdprivateLengths[i])
{
int p1 = getPosition();
getDictItem(); // depends on control dependency: [while], data = [none]
int p2 = getPosition();
// If the dictItem is the "Subrs" then,
// use marker for offset and write operator number
if (key=="Subrs") {
fdSubrs[i] = new DictOffsetItem(); // depends on control dependency: [if], data = [none]
OutputList.addLast(fdSubrs[i]); // depends on control dependency: [if], data = [none]
OutputList.addLast(new UInt8Item((char)19)); // Subrs // depends on control dependency: [if], data = [none]
}
// Else copy the entire range
else
OutputList.addLast(new RangeItem(buf,p1,p2-p1));
}
}
}
} } |
public class class_name {
public Map<String, String> parse(Map<String, String> style) {
Map<String, String> mapRtn = new HashMap<String, String>();
for (String pos : new String[] {null, TOP, RIGHT, BOTTOM, LEFT}) {
// border[-attr]
if (pos == null) {
setBorderAttr(mapRtn, pos, style.get(BORDER));
setBorderAttr(mapRtn, pos, style.get(BORDER + "-" + COLOR));
setBorderAttr(mapRtn, pos, style.get(BORDER + "-" + WIDTH));
setBorderAttr(mapRtn, pos, style.get(BORDER + "-" + STYLE));
}
// border-pos[-attr]
else {
setBorderAttr(mapRtn, pos, style.get(BORDER + "-" + pos));
for (String attr : new String[] {COLOR, WIDTH, STYLE}) {
String attrName = BORDER + "-" + pos + "-" + attr;
String attrValue = style.get(attrName);
if (StringUtils.isNotBlank(attrValue)) {
mapRtn.put(attrName, attrValue);
}
}
}
}
return mapRtn;
} } | public class class_name {
public Map<String, String> parse(Map<String, String> style) {
Map<String, String> mapRtn = new HashMap<String, String>();
for (String pos : new String[] {null, TOP, RIGHT, BOTTOM, LEFT}) {
// border[-attr]
if (pos == null) {
setBorderAttr(mapRtn, pos, style.get(BORDER)); // depends on control dependency: [if], data = [none]
setBorderAttr(mapRtn, pos, style.get(BORDER + "-" + COLOR)); // depends on control dependency: [if], data = [none]
setBorderAttr(mapRtn, pos, style.get(BORDER + "-" + WIDTH)); // depends on control dependency: [if], data = [none]
setBorderAttr(mapRtn, pos, style.get(BORDER + "-" + STYLE)); // depends on control dependency: [if], data = [none]
}
// border-pos[-attr]
else {
setBorderAttr(mapRtn, pos, style.get(BORDER + "-" + pos)); // depends on control dependency: [if], data = [none]
for (String attr : new String[] {COLOR, WIDTH, STYLE}) {
String attrName = BORDER + "-" + pos + "-" + attr;
String attrValue = style.get(attrName);
if (StringUtils.isNotBlank(attrValue)) {
mapRtn.put(attrName, attrValue); // depends on control dependency: [if], data = [none]
}
}
}
}
return mapRtn;
} } |
public class class_name {
public void marshall(AttributeType attributeType, ProtocolMarshaller protocolMarshaller) {
if (attributeType == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(attributeType.getName(), NAME_BINDING);
protocolMarshaller.marshall(attributeType.getValue(), VALUE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(AttributeType attributeType, ProtocolMarshaller protocolMarshaller) {
if (attributeType == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(attributeType.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(attributeType.getValue(), VALUE_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 void computeRotation(double run, double rise) {
// double alpha = Math.sqrt(run*run + rise*rise);
// c = run/alpha;
// s = rise/alpha;
if( Math.abs(rise) > Math.abs(run)) {
double k = run/rise;
double bottom = 1.0 + k*k;
double bottom_sq = Math.sqrt(bottom);
s2 = 1.0/bottom;
c2 = k*k/bottom;
cs = k/bottom;
s = 1.0/bottom_sq;
c = k/bottom_sq;
} else {
double t = rise/run;
double bottom = 1.0 + t*t;
double bottom_sq = Math.sqrt(bottom);
c2 = 1.0/bottom;
s2 = t*t/bottom;
cs = t/bottom;
c = 1.0/bottom_sq;
s = t/bottom_sq;
}
} } | public class class_name {
private void computeRotation(double run, double rise) {
// double alpha = Math.sqrt(run*run + rise*rise);
// c = run/alpha;
// s = rise/alpha;
if( Math.abs(rise) > Math.abs(run)) {
double k = run/rise;
double bottom = 1.0 + k*k;
double bottom_sq = Math.sqrt(bottom);
s2 = 1.0/bottom; // depends on control dependency: [if], data = [none]
c2 = k*k/bottom; // depends on control dependency: [if], data = [none]
cs = k/bottom; // depends on control dependency: [if], data = [none]
s = 1.0/bottom_sq; // depends on control dependency: [if], data = [none]
c = k/bottom_sq; // depends on control dependency: [if], data = [none]
} else {
double t = rise/run;
double bottom = 1.0 + t*t;
double bottom_sq = Math.sqrt(bottom);
c2 = 1.0/bottom; // depends on control dependency: [if], data = [none]
s2 = t*t/bottom; // depends on control dependency: [if], data = [none]
cs = t/bottom; // depends on control dependency: [if], data = [none]
c = 1.0/bottom_sq; // depends on control dependency: [if], data = [none]
s = t/bottom_sq; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void stop() {
if (msgRouter != null) {
TrConfigurator.unsetMessageRouter(msgRouter);
}
if (configListener != null) {
configListener.unregister();
}
} } | public class class_name {
public void stop() {
if (msgRouter != null) {
TrConfigurator.unsetMessageRouter(msgRouter); // depends on control dependency: [if], data = [(msgRouter]
}
if (configListener != null) {
configListener.unregister(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void readClassAttributes() throws IOException, ClassfileFormatException {
// Class attributes (including class annotations, class type variables, module info, etc.)
final int attributesCount = inputStreamOrByteBuffer.readUnsignedShort();
for (int i = 0; i < attributesCount; i++) {
final int attributeNameCpIdx = inputStreamOrByteBuffer.readUnsignedShort();
final int attributeLength = inputStreamOrByteBuffer.readInt();
if (scanSpec.enableAnnotationInfo //
&& (constantPoolStringEquals(attributeNameCpIdx, "RuntimeVisibleAnnotations")
|| (!scanSpec.disableRuntimeInvisibleAnnotations && constantPoolStringEquals(
attributeNameCpIdx, "RuntimeInvisibleAnnotations")))) {
final int annotationCount = inputStreamOrByteBuffer.readUnsignedShort();
if (annotationCount > 0) {
if (classAnnotations == null) {
classAnnotations = new AnnotationInfoList();
}
for (int m = 0; m < annotationCount; m++) {
classAnnotations.add(readAnnotation());
}
}
} else if (constantPoolStringEquals(attributeNameCpIdx, "InnerClasses")) {
final int numInnerClasses = inputStreamOrByteBuffer.readUnsignedShort();
for (int j = 0; j < numInnerClasses; j++) {
final int innerClassInfoCpIdx = inputStreamOrByteBuffer.readUnsignedShort();
final int outerClassInfoCpIdx = inputStreamOrByteBuffer.readUnsignedShort();
if (innerClassInfoCpIdx != 0 && outerClassInfoCpIdx != 0) {
if (classContainmentEntries == null) {
classContainmentEntries = new ArrayList<>();
}
classContainmentEntries.add(new SimpleEntry<>(getConstantPoolClassName(innerClassInfoCpIdx),
getConstantPoolClassName(outerClassInfoCpIdx)));
}
inputStreamOrByteBuffer.skip(2); // inner_name_idx
inputStreamOrByteBuffer.skip(2); // inner_class_access_flags
}
} else if (constantPoolStringEquals(attributeNameCpIdx, "Signature")) {
// Get class type signature, including type variables
typeSignature = getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort());
} else if (constantPoolStringEquals(attributeNameCpIdx, "EnclosingMethod")) {
final String innermostEnclosingClassName = getConstantPoolClassName(
inputStreamOrByteBuffer.readUnsignedShort());
final int enclosingMethodCpIdx = inputStreamOrByteBuffer.readUnsignedShort();
String definingMethodName;
if (enclosingMethodCpIdx == 0) {
// A cpIdx of 0 (which is an invalid value) is used for anonymous inner classes declared in
// class initializer code, e.g. assigned to a class field.
definingMethodName = "<clinit>";
} else {
definingMethodName = getConstantPoolString(enclosingMethodCpIdx, /* subFieldIdx = */ 0);
// Could also fetch method type signature using subFieldIdx = 1, if needed
}
// Link anonymous inner classes into the class with their containing method
if (classContainmentEntries == null) {
classContainmentEntries = new ArrayList<>();
}
classContainmentEntries.add(new SimpleEntry<>(className, innermostEnclosingClassName));
// Also store the fully-qualified name of the enclosing method, to mark this as an anonymous inner
// class
this.fullyQualifiedDefiningMethodName = innermostEnclosingClassName + "." + definingMethodName;
} else if (constantPoolStringEquals(attributeNameCpIdx, "Module")) {
final int moduleNameCpIdx = inputStreamOrByteBuffer.readUnsignedShort();
classpathElement.moduleNameFromModuleDescriptor = getConstantPoolString(moduleNameCpIdx);
// (Future work): parse the rest of the module descriptor fields, and add to ModuleInfo:
// https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.25
inputStreamOrByteBuffer.skip(attributeLength - 2);
} else {
inputStreamOrByteBuffer.skip(attributeLength);
}
}
} } | public class class_name {
private void readClassAttributes() throws IOException, ClassfileFormatException {
// Class attributes (including class annotations, class type variables, module info, etc.)
final int attributesCount = inputStreamOrByteBuffer.readUnsignedShort();
for (int i = 0; i < attributesCount; i++) {
final int attributeNameCpIdx = inputStreamOrByteBuffer.readUnsignedShort();
final int attributeLength = inputStreamOrByteBuffer.readInt();
if (scanSpec.enableAnnotationInfo //
&& (constantPoolStringEquals(attributeNameCpIdx, "RuntimeVisibleAnnotations")
|| (!scanSpec.disableRuntimeInvisibleAnnotations && constantPoolStringEquals(
attributeNameCpIdx, "RuntimeInvisibleAnnotations")))) {
final int annotationCount = inputStreamOrByteBuffer.readUnsignedShort();
if (annotationCount > 0) {
if (classAnnotations == null) {
classAnnotations = new AnnotationInfoList(); // depends on control dependency: [if], data = [none]
}
for (int m = 0; m < annotationCount; m++) {
classAnnotations.add(readAnnotation()); // depends on control dependency: [for], data = [none]
}
}
} else if (constantPoolStringEquals(attributeNameCpIdx, "InnerClasses")) {
final int numInnerClasses = inputStreamOrByteBuffer.readUnsignedShort();
for (int j = 0; j < numInnerClasses; j++) {
final int innerClassInfoCpIdx = inputStreamOrByteBuffer.readUnsignedShort();
final int outerClassInfoCpIdx = inputStreamOrByteBuffer.readUnsignedShort();
if (innerClassInfoCpIdx != 0 && outerClassInfoCpIdx != 0) {
if (classContainmentEntries == null) {
classContainmentEntries = new ArrayList<>();
}
classContainmentEntries.add(new SimpleEntry<>(getConstantPoolClassName(innerClassInfoCpIdx),
getConstantPoolClassName(outerClassInfoCpIdx)));
}
inputStreamOrByteBuffer.skip(2); // inner_name_idx
inputStreamOrByteBuffer.skip(2); // inner_class_access_flags
}
} else if (constantPoolStringEquals(attributeNameCpIdx, "Signature")) {
// Get class type signature, including type variables
typeSignature = getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort());
} else if (constantPoolStringEquals(attributeNameCpIdx, "EnclosingMethod")) {
final String innermostEnclosingClassName = getConstantPoolClassName(
inputStreamOrByteBuffer.readUnsignedShort());
final int enclosingMethodCpIdx = inputStreamOrByteBuffer.readUnsignedShort();
String definingMethodName;
if (enclosingMethodCpIdx == 0) {
// A cpIdx of 0 (which is an invalid value) is used for anonymous inner classes declared in
// class initializer code, e.g. assigned to a class field.
definingMethodName = "<clinit>";
} else {
definingMethodName = getConstantPoolString(enclosingMethodCpIdx, /* subFieldIdx = */ 0);
// Could also fetch method type signature using subFieldIdx = 1, if needed
}
// Link anonymous inner classes into the class with their containing method
if (classContainmentEntries == null) {
classContainmentEntries = new ArrayList<>();
}
classContainmentEntries.add(new SimpleEntry<>(className, innermostEnclosingClassName));
// Also store the fully-qualified name of the enclosing method, to mark this as an anonymous inner
// class
this.fullyQualifiedDefiningMethodName = innermostEnclosingClassName + "." + definingMethodName;
} else if (constantPoolStringEquals(attributeNameCpIdx, "Module")) {
final int moduleNameCpIdx = inputStreamOrByteBuffer.readUnsignedShort();
classpathElement.moduleNameFromModuleDescriptor = getConstantPoolString(moduleNameCpIdx);
// (Future work): parse the rest of the module descriptor fields, and add to ModuleInfo:
// https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.25
inputStreamOrByteBuffer.skip(attributeLength - 2);
} else {
inputStreamOrByteBuffer.skip(attributeLength);
}
}
} } |
public class class_name {
public Entity get(Transaction transaction, Key key) {
try {
return datastore.get(transaction, key);
} catch (EntityNotFoundException e) {
return null;
}
} } | public class class_name {
public Entity get(Transaction transaction, Key key) {
try {
return datastore.get(transaction, key); // depends on control dependency: [try], data = [none]
} catch (EntityNotFoundException e) {
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private boolean isIntegerConstant(String columnOrConstant) {
try {
Integer.parseInt(columnOrConstant.trim());
return true;
} catch (NumberFormatException e) {
return false;
}
} } | public class class_name {
private boolean isIntegerConstant(String columnOrConstant) {
try {
Integer.parseInt(columnOrConstant.trim()); // depends on control dependency: [try], data = [none]
return true; // depends on control dependency: [try], data = [none]
} catch (NumberFormatException e) {
return false;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void simplify() {
if (!simplified) {
if (conditionList.size() > 0) {
for (MtasCQLParserWordCondition c : conditionList) {
c.simplify();
// A & B & ( C & !D )
if (c.type().equals(type) && !c.not()) {
positiveQueryList.addAll(c.positiveQueryList);
negativeQueryList.addAll(c.negativeQueryList);
// A & B & !( C | !D )
} else if (!c.type().equals(type) && c.not()) {
positiveQueryList.addAll(c.negativeQueryList);
negativeQueryList.addAll(c.positiveQueryList);
// A & B & ( C )
} else if (c.isSingle() && !c.not()) {
positiveQueryList.addAll(c.positiveQueryList);
negativeQueryList.addAll(c.negativeQueryList);
// A & B & !( C )
} else if (c.isSingle() && c.not()) {
positiveQueryList.addAll(c.negativeQueryList);
negativeQueryList.addAll(c.positiveQueryList);
} else if (c.isSimplePositive()) {
// A | B | ( C & D )
if (c.type().equals(TYPE_AND)) {
MtasSpanQuery q = new MtasSpanAndQuery(c.positiveQueryList
.toArray(new MtasSpanQuery[c.positiveQueryList.size()]));
if (c.not()) {
negativeQueryList.add(q);
} else {
positiveQueryList.add(q);
}
// A & B & ( C | D )
} else {
MtasSpanQuery q = new MtasSpanOrQuery(c.positiveQueryList
.toArray(new MtasSpanQuery[c.positiveQueryList.size()]));
if (c.not()) {
negativeQueryList.add(q);
} else {
positiveQueryList.add(q);
}
}
} else if (c.isSimpleNegative()) {
// A | B | ( !C | !D )
if (c.type().equals(TYPE_OR)) {
MtasSpanQuery q = new MtasSpanAndQuery(c.negativeQueryList
.toArray(new MtasSpanQuery[c.negativeQueryList.size()]));
if (c.not()) {
positiveQueryList.add(q);
} else {
negativeQueryList.add(q);
}
// A | B | ( !C & !D )
} else {
MtasSpanQuery q = new MtasSpanOrQuery(c.negativeQueryList
.toArray(new MtasSpanQuery[c.negativeQueryList.size()]));
if (c.not()) {
positiveQueryList.add(q);
} else {
negativeQueryList.add(q);
}
}
} else {
// swap if necessary
if (this.isSimplePositive() && c.not()) {
c.swapType();
} else if (this.isSimpleNegative() && !c.not()) {
c.swapType();
}
// A | B | ( C & !D )
if (c.type().equals(TYPE_AND)) {
MtasSpanQuery positiveQuery = new MtasSpanAndQuery(
c.positiveQueryList
.toArray(new MtasSpanQuery[c.positiveQueryList.size()]));
MtasSpanQuery negativeQuery = new MtasSpanAndQuery(
c.negativeQueryList
.toArray(new MtasSpanQuery[c.negativeQueryList.size()]));
MtasSpanQuery q = new MtasSpanNotQuery(positiveQuery,
negativeQuery);
if (c.not()) {
negativeQueryList.add(q);
} else {
positiveQueryList.add(q);
}
// A & B & ( C | !D )
} else {
MtasSpanQuery positiveQuery = new MtasSpanOrQuery(
c.positiveQueryList
.toArray(new MtasSpanQuery[c.positiveQueryList.size()]));
MtasSpanQuery negativeQuery = new MtasSpanOrQuery(
c.negativeQueryList
.toArray(new MtasSpanQuery[c.negativeQueryList.size()]));
MtasSpanQuery q = new MtasSpanNotQuery(positiveQuery,
negativeQuery);
if (c.not()) {
negativeQueryList.add(q);
} else {
positiveQueryList.add(q);
}
}
}
}
conditionList.clear();
}
if (isSimpleNegative()) {
swapType();
}
simplified = true;
}
} } | public class class_name {
public void simplify() {
if (!simplified) {
if (conditionList.size() > 0) {
for (MtasCQLParserWordCondition c : conditionList) {
c.simplify(); // depends on control dependency: [for], data = [c]
// A & B & ( C & !D )
if (c.type().equals(type) && !c.not()) {
positiveQueryList.addAll(c.positiveQueryList); // depends on control dependency: [if], data = [none]
negativeQueryList.addAll(c.negativeQueryList); // depends on control dependency: [if], data = [none]
// A & B & !( C | !D )
} else if (!c.type().equals(type) && c.not()) {
positiveQueryList.addAll(c.negativeQueryList); // depends on control dependency: [if], data = [none]
negativeQueryList.addAll(c.positiveQueryList); // depends on control dependency: [if], data = [none]
// A & B & ( C )
} else if (c.isSingle() && !c.not()) {
positiveQueryList.addAll(c.positiveQueryList); // depends on control dependency: [if], data = [none]
negativeQueryList.addAll(c.negativeQueryList); // depends on control dependency: [if], data = [none]
// A & B & !( C )
} else if (c.isSingle() && c.not()) {
positiveQueryList.addAll(c.negativeQueryList); // depends on control dependency: [if], data = [none]
negativeQueryList.addAll(c.positiveQueryList); // depends on control dependency: [if], data = [none]
} else if (c.isSimplePositive()) {
// A | B | ( C & D )
if (c.type().equals(TYPE_AND)) {
MtasSpanQuery q = new MtasSpanAndQuery(c.positiveQueryList
.toArray(new MtasSpanQuery[c.positiveQueryList.size()]));
if (c.not()) {
negativeQueryList.add(q); // depends on control dependency: [if], data = [none]
} else {
positiveQueryList.add(q); // depends on control dependency: [if], data = [none]
}
// A & B & ( C | D )
} else {
MtasSpanQuery q = new MtasSpanOrQuery(c.positiveQueryList
.toArray(new MtasSpanQuery[c.positiveQueryList.size()]));
if (c.not()) {
negativeQueryList.add(q); // depends on control dependency: [if], data = [none]
} else {
positiveQueryList.add(q); // depends on control dependency: [if], data = [none]
}
}
} else if (c.isSimpleNegative()) {
// A | B | ( !C | !D )
if (c.type().equals(TYPE_OR)) {
MtasSpanQuery q = new MtasSpanAndQuery(c.negativeQueryList
.toArray(new MtasSpanQuery[c.negativeQueryList.size()]));
if (c.not()) {
positiveQueryList.add(q); // depends on control dependency: [if], data = [none]
} else {
negativeQueryList.add(q); // depends on control dependency: [if], data = [none]
}
// A | B | ( !C & !D )
} else {
MtasSpanQuery q = new MtasSpanOrQuery(c.negativeQueryList
.toArray(new MtasSpanQuery[c.negativeQueryList.size()]));
if (c.not()) {
positiveQueryList.add(q); // depends on control dependency: [if], data = [none]
} else {
negativeQueryList.add(q); // depends on control dependency: [if], data = [none]
}
}
} else {
// swap if necessary
if (this.isSimplePositive() && c.not()) {
c.swapType(); // depends on control dependency: [if], data = [none]
} else if (this.isSimpleNegative() && !c.not()) {
c.swapType(); // depends on control dependency: [if], data = [none]
}
// A | B | ( C & !D )
if (c.type().equals(TYPE_AND)) {
MtasSpanQuery positiveQuery = new MtasSpanAndQuery(
c.positiveQueryList
.toArray(new MtasSpanQuery[c.positiveQueryList.size()]));
MtasSpanQuery negativeQuery = new MtasSpanAndQuery(
c.negativeQueryList
.toArray(new MtasSpanQuery[c.negativeQueryList.size()]));
MtasSpanQuery q = new MtasSpanNotQuery(positiveQuery,
negativeQuery);
if (c.not()) {
negativeQueryList.add(q); // depends on control dependency: [if], data = [none]
} else {
positiveQueryList.add(q); // depends on control dependency: [if], data = [none]
}
// A & B & ( C | !D )
} else {
MtasSpanQuery positiveQuery = new MtasSpanOrQuery(
c.positiveQueryList
.toArray(new MtasSpanQuery[c.positiveQueryList.size()]));
MtasSpanQuery negativeQuery = new MtasSpanOrQuery(
c.negativeQueryList
.toArray(new MtasSpanQuery[c.negativeQueryList.size()]));
MtasSpanQuery q = new MtasSpanNotQuery(positiveQuery,
negativeQuery);
if (c.not()) {
negativeQueryList.add(q); // depends on control dependency: [if], data = [none]
} else {
positiveQueryList.add(q); // depends on control dependency: [if], data = [none]
}
}
}
}
conditionList.clear(); // depends on control dependency: [if], data = [none]
}
if (isSimpleNegative()) {
swapType(); // depends on control dependency: [if], data = [none]
}
simplified = true; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected final void setLeftMessage(@Nullable final CharSequence message,
@Nullable final Drawable icon, final boolean error) {
if (message != null) {
leftMessage.setText(message);
leftMessage.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
leftMessage.setTextColor(error ? getErrorColor() : getHelperTextColor());
leftMessage.setTag(error);
leftMessage.setVisibility(View.VISIBLE);
} else if (getHelperText() != null) {
setLeftMessage(getHelperText(), null, false);
} else {
leftMessage.setTag(false);
leftMessage.setVisibility(View.GONE);
}
} } | public class class_name {
protected final void setLeftMessage(@Nullable final CharSequence message,
@Nullable final Drawable icon, final boolean error) {
if (message != null) {
leftMessage.setText(message); // depends on control dependency: [if], data = [(message]
leftMessage.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null); // depends on control dependency: [if], data = [null)]
leftMessage.setTextColor(error ? getErrorColor() : getHelperTextColor()); // depends on control dependency: [if], data = [none]
leftMessage.setTag(error); // depends on control dependency: [if], data = [none]
leftMessage.setVisibility(View.VISIBLE); // depends on control dependency: [if], data = [none]
} else if (getHelperText() != null) {
setLeftMessage(getHelperText(), null, false); // depends on control dependency: [if], data = [(getHelperText()]
} else {
leftMessage.setTag(false); // depends on control dependency: [if], data = [none]
leftMessage.setVisibility(View.GONE); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private static boolean isAnnotated(Feature feature)
{
for (final Class<?> current : feature.getClass().getInterfaces())
{
if (current.isAnnotationPresent(FeatureInterface.class))
{
return true;
}
}
return feature.getClass().isAnnotationPresent(FeatureInterface.class);
} } | public class class_name {
private static boolean isAnnotated(Feature feature)
{
for (final Class<?> current : feature.getClass().getInterfaces())
{
if (current.isAnnotationPresent(FeatureInterface.class))
{
return true;
// depends on control dependency: [if], data = [none]
}
}
return feature.getClass().isAnnotationPresent(FeatureInterface.class);
} } |
public class class_name {
private JSONArray emitOperations(ObjectName objName) throws Exception {
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
MBeanInfo mBeanInfo = mBeanServer.getMBeanInfo(objName);
JSONArray ar = new JSONArray();
MBeanOperationInfo[] operations = mBeanInfo.getOperations();
for (MBeanOperationInfo operation : operations) {
JSONObject obj = new JSONObject();
obj.put("name", operation.getName());
obj.put("description", operation.getDescription());
obj.put("returnType", operation.getReturnType());
obj.put("impact", operation.getImpact());
JSONArray params = new JSONArray();
for (MBeanParameterInfo param : operation.getSignature()) {
JSONObject p = new JSONObject();
p.put("name", param.getName());
p.put("type", param.getType());
params.put(p);
}
obj.put("params", params);
ar.put(obj);
}
return ar;
} } | public class class_name {
private JSONArray emitOperations(ObjectName objName) throws Exception {
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
MBeanInfo mBeanInfo = mBeanServer.getMBeanInfo(objName);
JSONArray ar = new JSONArray();
MBeanOperationInfo[] operations = mBeanInfo.getOperations();
for (MBeanOperationInfo operation : operations) {
JSONObject obj = new JSONObject();
obj.put("name", operation.getName());
obj.put("description", operation.getDescription());
obj.put("returnType", operation.getReturnType());
obj.put("impact", operation.getImpact());
JSONArray params = new JSONArray();
for (MBeanParameterInfo param : operation.getSignature()) {
JSONObject p = new JSONObject();
p.put("name", param.getName()); // depends on control dependency: [for], data = [param]
p.put("type", param.getType()); // depends on control dependency: [for], data = [param]
params.put(p); // depends on control dependency: [for], data = [param]
}
obj.put("params", params);
ar.put(obj);
}
return ar;
} } |
public class class_name {
public InstrumentationResult instrument(byte[] input, InstrumentationSettings settings) {
Validate.notNull(input);
Validate.notNull(settings);
Validate.isTrue(input.length > 0);
// Read class as tree model -- because we're using SimpleClassNode, JSR blocks get inlined
ClassReader cr = new ClassReader(input);
ClassNode classNode = new SimpleClassNode();
cr.accept(classNode, 0);
// Recompute stackmap frames.
classNode = reconstructStackMapFrames(classNode);
// Apply passes.
InstrumentationPass[] passes = new InstrumentationPass[] {
new IdentifyInstrumentationPass(), // identify methods for instrumentation
new AnalyzeInstrumentationPass(), // analyze methods for instrumentation
new SerializationPreInstrumentationPass(), // create .coroutinesinfo files for methods to be instrumented
new PerformInstrumentationPass(), // perform instrumentation of methods
new SerializationPostInstrumentationPass(), // add fields needed for serializer/deserializer to identify versioning info
new AutoSerializableInstrumentationPass() // make class serializable + give serializationuid
};
InstrumentationState passState = new InstrumentationState(settings, classRepo);
for (InstrumentationPass pass : passes) {
pass.pass(classNode, passState);
ControlFlag controlFlag = passState.control();
switch (controlFlag) {
case CONTINUE_INSTRUMENT:
break;
case NO_INSTRUMENT:
return new InstrumentationResult(input); // class should not be instrumented -- return original data.
default:
throw new IllegalStateException(); // should never happen
}
}
// Write tree model back out as class -- NOTE: If we get a NegativeArraySizeException on classNode.accept(), it likely means that
// we're doing bad things with the stack. So, before writing the class out and returning
// it, we call verifyClassIntegrity() to check and make sure everything is okay.
// RE-ENABLE ONLY IF JVM COMPLAINS ABOUT INSTRUMENTED CLASSES AND YOU NEED TO DEBUG, KEEP COMMENTED OUT FOR PRODUCTION
// verifyClassIntegrity(classNode);
ClassWriter cw = new SimpleClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, classRepo);
classNode.accept(cw);
byte[] classData = cw.toByteArray();
Map<String, byte[]> extraFiles = passState.extraFiles();
return new InstrumentationResult(classData, extraFiles);
} } | public class class_name {
public InstrumentationResult instrument(byte[] input, InstrumentationSettings settings) {
Validate.notNull(input);
Validate.notNull(settings);
Validate.isTrue(input.length > 0);
// Read class as tree model -- because we're using SimpleClassNode, JSR blocks get inlined
ClassReader cr = new ClassReader(input);
ClassNode classNode = new SimpleClassNode();
cr.accept(classNode, 0);
// Recompute stackmap frames.
classNode = reconstructStackMapFrames(classNode);
// Apply passes.
InstrumentationPass[] passes = new InstrumentationPass[] {
new IdentifyInstrumentationPass(), // identify methods for instrumentation
new AnalyzeInstrumentationPass(), // analyze methods for instrumentation
new SerializationPreInstrumentationPass(), // create .coroutinesinfo files for methods to be instrumented
new PerformInstrumentationPass(), // perform instrumentation of methods
new SerializationPostInstrumentationPass(), // add fields needed for serializer/deserializer to identify versioning info
new AutoSerializableInstrumentationPass() // make class serializable + give serializationuid
};
InstrumentationState passState = new InstrumentationState(settings, classRepo);
for (InstrumentationPass pass : passes) {
pass.pass(classNode, passState); // depends on control dependency: [for], data = [pass]
ControlFlag controlFlag = passState.control();
switch (controlFlag) {
case CONTINUE_INSTRUMENT:
break;
case NO_INSTRUMENT:
return new InstrumentationResult(input); // class should not be instrumented -- return original data.
default:
throw new IllegalStateException(); // should never happen
}
}
// Write tree model back out as class -- NOTE: If we get a NegativeArraySizeException on classNode.accept(), it likely means that
// we're doing bad things with the stack. So, before writing the class out and returning
// it, we call verifyClassIntegrity() to check and make sure everything is okay.
// RE-ENABLE ONLY IF JVM COMPLAINS ABOUT INSTRUMENTED CLASSES AND YOU NEED TO DEBUG, KEEP COMMENTED OUT FOR PRODUCTION
// verifyClassIntegrity(classNode);
ClassWriter cw = new SimpleClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, classRepo);
classNode.accept(cw);
byte[] classData = cw.toByteArray();
Map<String, byte[]> extraFiles = passState.extraFiles();
return new InstrumentationResult(classData, extraFiles);
} } |
public class class_name {
public static Key MACHINE_DETECTION(String introduction, Voice voice) {
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("introduction", introduction);
if (voice != null) {
map.put("voice", voice.toString());
}
return createKey("machineDetection", map);
} } | public class class_name {
public static Key MACHINE_DETECTION(String introduction, Voice voice) {
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("introduction", introduction);
if (voice != null) {
map.put("voice", voice.toString()); // depends on control dependency: [if], data = [none]
}
return createKey("machineDetection", map);
} } |
public class class_name {
@Override
public boolean onSearchSignalReceived(String queryId, String queryJson) {
Utils.logCall(TAG, "onSearchSignalReceived", queryId, queryJson);
if (new SearchResponder(mSpf.getContext()).matches(queryJson)) {
// XXX #SearchRefactor
// - Merge with trigger query responder
// - Use the right persona to fetch baseinfo (app name can be found in query json)
// - Move everything in search maager and search performer classes
BaseInfo info = mSpf.getProfileManager().getBaseInfo(SPFPersona.getDefault());
mSpf.sendSearchResult(queryId, info);
return true;
}
return false;
} } | public class class_name {
@Override
public boolean onSearchSignalReceived(String queryId, String queryJson) {
Utils.logCall(TAG, "onSearchSignalReceived", queryId, queryJson);
if (new SearchResponder(mSpf.getContext()).matches(queryJson)) {
// XXX #SearchRefactor
// - Merge with trigger query responder
// - Use the right persona to fetch baseinfo (app name can be found in query json)
// - Move everything in search maager and search performer classes
BaseInfo info = mSpf.getProfileManager().getBaseInfo(SPFPersona.getDefault());
mSpf.sendSearchResult(queryId, info); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public boolean HasKeyID(String id) {
CBORObject thatObj = (id == null) ? null : CBORObject.FromObject(id);
CBORObject thisObj = get(KeyKeys.KeyId);
boolean result;
if (thatObj == null) {
result = (thisObj == null);
} else {
result = thatObj.equals(thisObj);
}
return result;
} } | public class class_name {
public boolean HasKeyID(String id) {
CBORObject thatObj = (id == null) ? null : CBORObject.FromObject(id);
CBORObject thisObj = get(KeyKeys.KeyId);
boolean result;
if (thatObj == null) {
result = (thisObj == null); // depends on control dependency: [if], data = [null)]
} else {
result = thatObj.equals(thisObj); // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
protected StringBuffer renderWrappedText(StringBuffer sb, int width,
int nextLineTabStop, String text)
{
int pos = findWrapPos(text, width, 0);
if (pos == -1)
{
sb.append(rtrim(text));
return sb;
}
sb.append(rtrim(text.substring(0, pos))).append(getNewLine());
if (nextLineTabStop >= width)
{
// stops infinite loop happening
nextLineTabStop = 1;
}
// all following lines must be padded with nextLineTabStop space characters
final String padding = createPadding(nextLineTabStop);
while (true)
{
text = padding + text.substring(pos).trim();
pos = findWrapPos(text, width, 0);
if (pos == -1)
{
sb.append(text);
return sb;
}
if (text.length() > width && pos == nextLineTabStop - 1)
{
pos = width;
}
sb.append(rtrim(text.substring(0, pos))).append(getNewLine());
}
} } | public class class_name {
protected StringBuffer renderWrappedText(StringBuffer sb, int width,
int nextLineTabStop, String text)
{
int pos = findWrapPos(text, width, 0);
if (pos == -1)
{
sb.append(rtrim(text)); // depends on control dependency: [if], data = [none]
return sb; // depends on control dependency: [if], data = [none]
}
sb.append(rtrim(text.substring(0, pos))).append(getNewLine());
if (nextLineTabStop >= width)
{
// stops infinite loop happening
nextLineTabStop = 1; // depends on control dependency: [if], data = [none]
}
// all following lines must be padded with nextLineTabStop space characters
final String padding = createPadding(nextLineTabStop);
while (true)
{
text = padding + text.substring(pos).trim(); // depends on control dependency: [while], data = [none]
pos = findWrapPos(text, width, 0); // depends on control dependency: [while], data = [none]
if (pos == -1)
{
sb.append(text); // depends on control dependency: [if], data = [none]
return sb; // depends on control dependency: [if], data = [none]
}
if (text.length() > width && pos == nextLineTabStop - 1)
{
pos = width; // depends on control dependency: [if], data = [none]
}
sb.append(rtrim(text.substring(0, pos))).append(getNewLine()); // depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
public synchronized void start() throws Exception {
Preconditions.checkState(mState != State.STARTED, "Cannot start while already started");
Preconditions.checkState(mState != State.DESTROYED, "Cannot start a destroyed cluster");
mWorkDir = AlluxioTestDirectory.createTemporaryDirectory(mClusterName);
mState = State.STARTED;
mMasterAddresses = generateMasterAddresses(mNumMasters);
LOG.info("Master addresses: {}", mMasterAddresses);
switch (mDeployMode) {
case UFS_NON_HA:
MasterNetAddress masterAddress = mMasterAddresses.get(0);
mProperties.put(PropertyKey.MASTER_JOURNAL_TYPE, JournalType.UFS.toString());
mProperties.put(PropertyKey.MASTER_HOSTNAME, masterAddress.getHostname());
mProperties.put(PropertyKey.MASTER_RPC_PORT, Integer.toString(masterAddress.getRpcPort()));
mProperties.put(PropertyKey.MASTER_WEB_PORT, Integer.toString(masterAddress.getWebPort()));
break;
case EMBEDDED:
List<String> journalAddresses = new ArrayList<>();
List<String> rpcAddresses = new ArrayList<>();
for (MasterNetAddress address : mMasterAddresses) {
journalAddresses
.add(String.format("%s:%d", address.getHostname(), address.getEmbeddedJournalPort()));
rpcAddresses.add(String.format("%s:%d", address.getHostname(), address.getRpcPort()));
}
mProperties.put(PropertyKey.MASTER_JOURNAL_TYPE, JournalType.EMBEDDED.toString());
mProperties.put(PropertyKey.MASTER_EMBEDDED_JOURNAL_ADDRESSES,
com.google.common.base.Joiner.on(",").join(journalAddresses));
mProperties.put(PropertyKey.MASTER_RPC_ADDRESSES,
com.google.common.base.Joiner.on(",").join(rpcAddresses));
break;
case ZOOKEEPER_HA:
mCuratorServer = mCloser.register(
new RestartableTestingServer(-1, AlluxioTestDirectory.createTemporaryDirectory("zk")));
mProperties.put(PropertyKey.MASTER_JOURNAL_TYPE, JournalType.UFS.toString());
mProperties.put(PropertyKey.ZOOKEEPER_ENABLED, "true");
mProperties.put(PropertyKey.ZOOKEEPER_ADDRESS, mCuratorServer.getConnectString());
break;
default:
throw new IllegalStateException("Unknown deploy mode: " + mDeployMode.toString());
}
for (Entry<PropertyKey, String> entry :
ConfigurationTestUtils.testConfigurationDefaults(ServerConfiguration.global(),
NetworkAddressUtils.getLocalHostName(
(int) ServerConfiguration.getMs(PropertyKey.NETWORK_HOST_RESOLUTION_TIMEOUT_MS)),
mWorkDir.getAbsolutePath()).entrySet()) {
// Don't overwrite explicitly set properties.
if (mProperties.containsKey(entry.getKey())) {
continue;
}
// Keep the default RPC timeout.
if (entry.getKey().equals(PropertyKey.USER_RPC_RETRY_MAX_DURATION)) {
continue;
}
mProperties.put(entry.getKey(), entry.getValue());
}
mProperties.put(PropertyKey.MASTER_MOUNT_TABLE_ROOT_UFS,
PathUtils.concatPath(mWorkDir, "underFSStorage"));
new File(mProperties.get(PropertyKey.MASTER_MOUNT_TABLE_ROOT_UFS)).mkdirs();
if (!mNoFormat) {
formatJournal();
}
writeConf();
ServerConfiguration.merge(mProperties, Source.RUNTIME);
// Start servers
LOG.info("Starting alluxio cluster {} with base directory {}", mClusterName,
mWorkDir.getAbsolutePath());
for (int i = 0; i < mNumMasters; i++) {
createMaster(i).start();
}
for (int i = 0; i < mNumWorkers; i++) {
createWorker(i).start();
}
System.out.printf("Starting alluxio cluster in directory %s%n", mWorkDir.getAbsolutePath());
} } | public class class_name {
public synchronized void start() throws Exception {
Preconditions.checkState(mState != State.STARTED, "Cannot start while already started");
Preconditions.checkState(mState != State.DESTROYED, "Cannot start a destroyed cluster");
mWorkDir = AlluxioTestDirectory.createTemporaryDirectory(mClusterName);
mState = State.STARTED;
mMasterAddresses = generateMasterAddresses(mNumMasters);
LOG.info("Master addresses: {}", mMasterAddresses);
switch (mDeployMode) {
case UFS_NON_HA:
MasterNetAddress masterAddress = mMasterAddresses.get(0);
mProperties.put(PropertyKey.MASTER_JOURNAL_TYPE, JournalType.UFS.toString());
mProperties.put(PropertyKey.MASTER_HOSTNAME, masterAddress.getHostname());
mProperties.put(PropertyKey.MASTER_RPC_PORT, Integer.toString(masterAddress.getRpcPort()));
mProperties.put(PropertyKey.MASTER_WEB_PORT, Integer.toString(masterAddress.getWebPort()));
break;
case EMBEDDED:
List<String> journalAddresses = new ArrayList<>();
List<String> rpcAddresses = new ArrayList<>();
for (MasterNetAddress address : mMasterAddresses) {
journalAddresses
.add(String.format("%s:%d", address.getHostname(), address.getEmbeddedJournalPort())); // depends on control dependency: [for], data = [none]
rpcAddresses.add(String.format("%s:%d", address.getHostname(), address.getRpcPort())); // depends on control dependency: [for], data = [address]
}
mProperties.put(PropertyKey.MASTER_JOURNAL_TYPE, JournalType.EMBEDDED.toString());
mProperties.put(PropertyKey.MASTER_EMBEDDED_JOURNAL_ADDRESSES,
com.google.common.base.Joiner.on(",").join(journalAddresses));
mProperties.put(PropertyKey.MASTER_RPC_ADDRESSES,
com.google.common.base.Joiner.on(",").join(rpcAddresses));
break;
case ZOOKEEPER_HA:
mCuratorServer = mCloser.register(
new RestartableTestingServer(-1, AlluxioTestDirectory.createTemporaryDirectory("zk")));
mProperties.put(PropertyKey.MASTER_JOURNAL_TYPE, JournalType.UFS.toString());
mProperties.put(PropertyKey.ZOOKEEPER_ENABLED, "true");
mProperties.put(PropertyKey.ZOOKEEPER_ADDRESS, mCuratorServer.getConnectString());
break;
default:
throw new IllegalStateException("Unknown deploy mode: " + mDeployMode.toString());
}
for (Entry<PropertyKey, String> entry :
ConfigurationTestUtils.testConfigurationDefaults(ServerConfiguration.global(),
NetworkAddressUtils.getLocalHostName(
(int) ServerConfiguration.getMs(PropertyKey.NETWORK_HOST_RESOLUTION_TIMEOUT_MS)),
mWorkDir.getAbsolutePath()).entrySet()) {
// Don't overwrite explicitly set properties.
if (mProperties.containsKey(entry.getKey())) {
continue;
}
// Keep the default RPC timeout.
if (entry.getKey().equals(PropertyKey.USER_RPC_RETRY_MAX_DURATION)) {
continue;
}
mProperties.put(entry.getKey(), entry.getValue());
}
mProperties.put(PropertyKey.MASTER_MOUNT_TABLE_ROOT_UFS,
PathUtils.concatPath(mWorkDir, "underFSStorage"));
new File(mProperties.get(PropertyKey.MASTER_MOUNT_TABLE_ROOT_UFS)).mkdirs();
if (!mNoFormat) {
formatJournal();
}
writeConf();
ServerConfiguration.merge(mProperties, Source.RUNTIME);
// Start servers
LOG.info("Starting alluxio cluster {} with base directory {}", mClusterName,
mWorkDir.getAbsolutePath());
for (int i = 0; i < mNumMasters; i++) {
createMaster(i).start();
}
for (int i = 0; i < mNumWorkers; i++) {
createWorker(i).start();
}
System.out.printf("Starting alluxio cluster in directory %s%n", mWorkDir.getAbsolutePath());
} } |
public class class_name {
public void publish(ServletContext context, @CheckForNull File home) {
LOGGER.log(Level.SEVERE, "Failed to initialize Jenkins",this);
WebApp.get(context).setApp(this);
if (home == null) {
return;
}
new GroovyHookScript("boot-failure", context, home, BootFailure.class.getClassLoader())
.bind("exception",this)
.bind("home",home)
.bind("servletContext", context)
.bind("attempts",loadAttempts(home))
.run();
} } | public class class_name {
public void publish(ServletContext context, @CheckForNull File home) {
LOGGER.log(Level.SEVERE, "Failed to initialize Jenkins",this);
WebApp.get(context).setApp(this);
if (home == null) {
return; // depends on control dependency: [if], data = [none]
}
new GroovyHookScript("boot-failure", context, home, BootFailure.class.getClassLoader())
.bind("exception",this)
.bind("home",home)
.bind("servletContext", context)
.bind("attempts",loadAttempts(home))
.run();
} } |
public class class_name {
public void setQuantity(Parameter newQuantity) {
if (newQuantity != quantity) {
NotificationChain msgs = null;
if (quantity != null)
msgs = ((InternalEObject)quantity).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - BpsimPackage.RESOURCE_PARAMETERS__QUANTITY, null, msgs);
if (newQuantity != null)
msgs = ((InternalEObject)newQuantity).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - BpsimPackage.RESOURCE_PARAMETERS__QUANTITY, null, msgs);
msgs = basicSetQuantity(newQuantity, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, BpsimPackage.RESOURCE_PARAMETERS__QUANTITY, newQuantity, newQuantity));
} } | public class class_name {
public void setQuantity(Parameter newQuantity) {
if (newQuantity != quantity) {
NotificationChain msgs = null;
if (quantity != null)
msgs = ((InternalEObject)quantity).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - BpsimPackage.RESOURCE_PARAMETERS__QUANTITY, null, msgs);
if (newQuantity != null)
msgs = ((InternalEObject)newQuantity).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - BpsimPackage.RESOURCE_PARAMETERS__QUANTITY, null, msgs);
msgs = basicSetQuantity(newQuantity, msgs); // depends on control dependency: [if], data = [(newQuantity]
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, BpsimPackage.RESOURCE_PARAMETERS__QUANTITY, newQuantity, newQuantity));
} } |
public class class_name {
private static String getHostName() {
String hostName = null;
try {
hostName = InetAddress.getLocalHost().getHostName();
}
catch (UnknownHostException ex) {
LOG.info("Unable to obtain hostName", ex);
hostName = "unknown";
}
return hostName;
} } | public class class_name {
private static String getHostName() {
String hostName = null;
try {
hostName = InetAddress.getLocalHost().getHostName(); // depends on control dependency: [try], data = [none]
}
catch (UnknownHostException ex) {
LOG.info("Unable to obtain hostName", ex);
hostName = "unknown";
} // depends on control dependency: [catch], data = [none]
return hostName;
} } |
public class class_name {
private void addClassToDoFromJars() {
if (!Utils.isNullOrEmpty(settings.getJarFiles())) {
try {
String[] files = settings.getJarFiles().split(";");
for (String path : files) {
File file = new File(path);
if (!file.isFile()) {
String jarPath = classLoader.getJar(path);
if (jarPath == null) {
getFileManager().logInfo("can't find " + path);
}
file = new File(new URI(jarPath));
}
getFileManager().logInfo("searching classes to wrappe in " + file.getAbsolutePath());
JarFile jf = new JarFile(file);
Enumeration<JarEntry> entries = jf.entries();
while (entries.hasMoreElements()) {
String clName = entries.nextElement().getName();
if (clName.endsWith(".class")) {
Class<?> clazz = classLoader.loadClass(clName.split("\\.")[0].replace('/', '.'));
if (clazz.isAnnotationPresent(Java4Cpp.class)) {
addClassToDo(clazz);
}
}
}
}
} catch (Exception e) {
throw new RuntimeException("Failed to load jar " + e.getMessage());
}
}
} } | public class class_name {
private void addClassToDoFromJars() {
if (!Utils.isNullOrEmpty(settings.getJarFiles())) {
try {
String[] files = settings.getJarFiles().split(";");
for (String path : files) {
File file = new File(path);
if (!file.isFile()) {
String jarPath = classLoader.getJar(path);
if (jarPath == null) {
getFileManager().logInfo("can't find " + path);
}
file = new File(new URI(jarPath));
}
getFileManager().logInfo("searching classes to wrappe in " + file.getAbsolutePath());
JarFile jf = new JarFile(file);
Enumeration<JarEntry> entries = jf.entries();
while (entries.hasMoreElements()) {
String clName = entries.nextElement().getName();
if (clName.endsWith(".class")) {
Class<?> clazz = classLoader.loadClass(clName.split("\\.")[0].replace('/', '.')); // depends on control dependency: [if], data = [none]
if (clazz.isAnnotationPresent(Java4Cpp.class)) {
addClassToDo(clazz); // depends on control dependency: [if], data = [none]
}
}
}
}
} catch (Exception e) {
throw new RuntimeException("Failed to load jar " + e.getMessage());
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public boolean respondToCancel(SipTransaction siptrans, int statusCode, String reasonPhrase,
int expires, ArrayList<Header> additionalHeaders, ArrayList<Header> replaceHeaders,
String body) {
initErrorInfo();
try {
if (parent.sendReply(siptrans, statusCode, reasonPhrase, null, null, expires,
additionalHeaders, replaceHeaders, body) == null) {
setException(parent.getException());
setErrorMessage(parent.getErrorMessage());
setReturnCode(parent.getReturnCode());
return false;
}
return true;
} catch (Exception ex) {
setException(ex);
setErrorMessage("Exception: " + ex.getClass().getName() + ": " + ex.getMessage());
setReturnCode(SipSession.EXCEPTION_ENCOUNTERED);
return false;
}
} } | public class class_name {
public boolean respondToCancel(SipTransaction siptrans, int statusCode, String reasonPhrase,
int expires, ArrayList<Header> additionalHeaders, ArrayList<Header> replaceHeaders,
String body) {
initErrorInfo();
try {
if (parent.sendReply(siptrans, statusCode, reasonPhrase, null, null, expires,
additionalHeaders, replaceHeaders, body) == null) {
setException(parent.getException()); // depends on control dependency: [if], data = [none]
setErrorMessage(parent.getErrorMessage()); // depends on control dependency: [if], data = [none]
setReturnCode(parent.getReturnCode()); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
return true; // depends on control dependency: [try], data = [none]
} catch (Exception ex) {
setException(ex);
setErrorMessage("Exception: " + ex.getClass().getName() + ": " + ex.getMessage());
setReturnCode(SipSession.EXCEPTION_ENCOUNTERED);
return false;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static void doExtendTraits(final ClassNode cNode, final SourceUnit unit, final CompilationUnit cu) {
if (cNode.isInterface()) return;
boolean isItselfTrait = Traits.isTrait(cNode);
SuperCallTraitTransformer superCallTransformer = new SuperCallTraitTransformer(unit);
if (isItselfTrait) {
checkTraitAllowed(cNode, unit);
return;
}
if (!cNode.getNameWithoutPackage().endsWith(Traits.TRAIT_HELPER)) {
List<ClassNode> traits = findTraits(cNode);
for (ClassNode trait : traits) {
TraitHelpersTuple helpers = Traits.findHelpers(trait);
applyTrait(trait, cNode, helpers);
superCallTransformer.visitClass(cNode);
if (unit!=null) {
ASTTransformationCollectorCodeVisitor collector = new ASTTransformationCollectorCodeVisitor(unit, cu.getTransformLoader());
collector.visitClass(cNode);
}
}
}
} } | public class class_name {
public static void doExtendTraits(final ClassNode cNode, final SourceUnit unit, final CompilationUnit cu) {
if (cNode.isInterface()) return;
boolean isItselfTrait = Traits.isTrait(cNode);
SuperCallTraitTransformer superCallTransformer = new SuperCallTraitTransformer(unit);
if (isItselfTrait) {
checkTraitAllowed(cNode, unit); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
if (!cNode.getNameWithoutPackage().endsWith(Traits.TRAIT_HELPER)) {
List<ClassNode> traits = findTraits(cNode);
for (ClassNode trait : traits) {
TraitHelpersTuple helpers = Traits.findHelpers(trait);
applyTrait(trait, cNode, helpers); // depends on control dependency: [for], data = [trait]
superCallTransformer.visitClass(cNode); // depends on control dependency: [for], data = [none]
if (unit!=null) {
ASTTransformationCollectorCodeVisitor collector = new ASTTransformationCollectorCodeVisitor(unit, cu.getTransformLoader());
collector.visitClass(cNode); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
private void deliverMessage(long destinationHSId, VoltMessage message) {
if (!m_hostMessenger.validateForeignHostId(m_hostId)) {
hostLog.warn(String.format("Message (%s) sent to site id: %s @ (%s) at %d from %s "
+ "which is a known failed host. The message will be dropped\n",
message.getClass().getSimpleName(),
CoreUtils.hsIdToString(destinationHSId),
m_socket.getRemoteSocketAddress().toString(),
m_hostMessenger.getHostId(),
CoreUtils.hsIdToString(message.m_sourceHSId)));
return;
}
Mailbox mailbox = m_hostMessenger.getMailbox(destinationHSId);
/*
* At this point we are OK with messages going to sites that don't exist
* because we are saying that things can come and go
*/
if (mailbox == null) {
hostLog.info(String.format("Message (%s) sent to unknown site id: %s @ (%s) at %d from %s \n",
message.getClass().getSimpleName(),
CoreUtils.hsIdToString(destinationHSId),
m_socket.getRemoteSocketAddress().toString(),
m_hostMessenger.getHostId(),
CoreUtils.hsIdToString(message.m_sourceHSId)));
/*
* If it is for the wrong host, that definitely isn't cool
*/
if (m_hostMessenger.getHostId() != (int)destinationHSId) {
VoltDB.crashLocalVoltDB("Received a message at wrong host", false, null);
}
return;
}
// deliver the message to the mailbox
mailbox.deliver(message);
} } | public class class_name {
private void deliverMessage(long destinationHSId, VoltMessage message) {
if (!m_hostMessenger.validateForeignHostId(m_hostId)) {
hostLog.warn(String.format("Message (%s) sent to site id: %s @ (%s) at %d from %s "
+ "which is a known failed host. The message will be dropped\n",
message.getClass().getSimpleName(),
CoreUtils.hsIdToString(destinationHSId),
m_socket.getRemoteSocketAddress().toString(),
m_hostMessenger.getHostId(),
CoreUtils.hsIdToString(message.m_sourceHSId))); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
Mailbox mailbox = m_hostMessenger.getMailbox(destinationHSId);
/*
* At this point we are OK with messages going to sites that don't exist
* because we are saying that things can come and go
*/
if (mailbox == null) {
hostLog.info(String.format("Message (%s) sent to unknown site id: %s @ (%s) at %d from %s \n",
message.getClass().getSimpleName(),
CoreUtils.hsIdToString(destinationHSId),
m_socket.getRemoteSocketAddress().toString(),
m_hostMessenger.getHostId(),
CoreUtils.hsIdToString(message.m_sourceHSId))); // depends on control dependency: [if], data = [none]
/*
* If it is for the wrong host, that definitely isn't cool
*/
if (m_hostMessenger.getHostId() != (int)destinationHSId) {
VoltDB.crashLocalVoltDB("Received a message at wrong host", false, null); // depends on control dependency: [if], data = [none]
}
return; // depends on control dependency: [if], data = [none]
}
// deliver the message to the mailbox
mailbox.deliver(message);
} } |
public class class_name {
public Coordinate nearest(Coordinate c) {
double len = this.getLength();
double u = (c.getX() - this.c1.getX()) * (this.c2.getX() - this.c1.getX()) + (c.getY() - this.c1.getY())
* (this.c2.getY() - this.c1.getY());
u = u / (len * len);
if (u < 0.00001 || u > 1) {
// Shortest point not within LineSegment, so take closest end-point.
LineSegment ls1 = new LineSegment(c, this.c1);
LineSegment ls2 = new LineSegment(c, this.c2);
double len1 = ls1.getLength();
double len2 = ls2.getLength();
if (len1 < len2) {
return this.c1;
}
return this.c2;
} else {
// Intersecting point is on the line, use the formula: P = P1 + u (P2 - P1)
double x1 = this.c1.getX() + u * (this.c2.getX() - this.c1.getX());
double y1 = this.c1.getY() + u * (this.c2.getY() - this.c1.getY());
return new Coordinate(x1, y1);
}
} } | public class class_name {
public Coordinate nearest(Coordinate c) {
double len = this.getLength();
double u = (c.getX() - this.c1.getX()) * (this.c2.getX() - this.c1.getX()) + (c.getY() - this.c1.getY())
* (this.c2.getY() - this.c1.getY());
u = u / (len * len);
if (u < 0.00001 || u > 1) {
// Shortest point not within LineSegment, so take closest end-point.
LineSegment ls1 = new LineSegment(c, this.c1);
LineSegment ls2 = new LineSegment(c, this.c2);
double len1 = ls1.getLength();
double len2 = ls2.getLength();
if (len1 < len2) {
return this.c1; // depends on control dependency: [if], data = [none]
}
return this.c2; // depends on control dependency: [if], data = [none]
} else {
// Intersecting point is on the line, use the formula: P = P1 + u (P2 - P1)
double x1 = this.c1.getX() + u * (this.c2.getX() - this.c1.getX());
double y1 = this.c1.getY() + u * (this.c2.getY() - this.c1.getY());
return new Coordinate(x1, y1); // depends on control dependency: [if], data = [1)]
}
} } |
public class class_name {
public static int writePointFeatureCollection(FeatureDatasetPoint pfDataset, String fileOut) throws IOException {
// extract the PointFeatureCollection
PointFeatureCollection pointFeatureCollection = null;
List<DsgFeatureCollection> featureCollectionList = pfDataset.getPointFeatureCollectionList();
for (DsgFeatureCollection featureCollection : featureCollectionList) {
if (featureCollection instanceof PointFeatureCollection)
pointFeatureCollection = (PointFeatureCollection) featureCollection;
}
if (null == pointFeatureCollection)
throw new IOException("There is no PointFeatureCollection in " + pfDataset.getLocation());
long start = System.currentTimeMillis();
FileOutputStream fos = new FileOutputStream(fileOut);
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(fos, 10000));
WriterCFPointDataset writer = null;
/* LOOK BAD
List<VariableSimpleIF> dataVars = new ArrayList<VariableSimpleIF>();
ucar.nc2.NetcdfFile ncfile = pfDataset.getNetcdfFile();
if ((ncfile == null) || !(ncfile instanceof NetcdfDataset)) {
dataVars.addAll(pfDataset.getDataVariables());
} else {
NetcdfDataset ncd = (NetcdfDataset) ncfile;
for (VariableSimpleIF vs : pfDataset.getDataVariables()) {
if (ncd.findCoordinateAxis(vs.getName()) == null)
dataVars.add(vs);
}
} */
int count = 0;
for (PointFeature pointFeature : pointFeatureCollection) {
StructureData data = pointFeature.getDataAll();
if (count == 0) {
EarthLocation loc = pointFeature.getLocation(); // LOOK we dont know this until we see the obs
String altUnits = Double.isNaN(loc.getAltitude()) ? null : "meters"; // LOOK units may be wrong
writer = new WriterCFPointDataset(out, pfDataset.getGlobalAttributes(), altUnits);
writer.writeHeader(pfDataset.getDataVariables(), -1);
}
writer.writeRecord(pointFeature, data);
count++;
}
writer.finish();
out.flush();
out.close();
long took = System.currentTimeMillis() - start;
System.out.printf("Write %d records from %s to %s took %d msecs %n", count, pfDataset.getLocation(), fileOut, took);
return count;
} } | public class class_name {
public static int writePointFeatureCollection(FeatureDatasetPoint pfDataset, String fileOut) throws IOException {
// extract the PointFeatureCollection
PointFeatureCollection pointFeatureCollection = null;
List<DsgFeatureCollection> featureCollectionList = pfDataset.getPointFeatureCollectionList();
for (DsgFeatureCollection featureCollection : featureCollectionList) {
if (featureCollection instanceof PointFeatureCollection)
pointFeatureCollection = (PointFeatureCollection) featureCollection;
}
if (null == pointFeatureCollection)
throw new IOException("There is no PointFeatureCollection in " + pfDataset.getLocation());
long start = System.currentTimeMillis();
FileOutputStream fos = new FileOutputStream(fileOut);
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(fos, 10000));
WriterCFPointDataset writer = null;
/* LOOK BAD
List<VariableSimpleIF> dataVars = new ArrayList<VariableSimpleIF>();
ucar.nc2.NetcdfFile ncfile = pfDataset.getNetcdfFile();
if ((ncfile == null) || !(ncfile instanceof NetcdfDataset)) {
dataVars.addAll(pfDataset.getDataVariables());
} else {
NetcdfDataset ncd = (NetcdfDataset) ncfile;
for (VariableSimpleIF vs : pfDataset.getDataVariables()) {
if (ncd.findCoordinateAxis(vs.getName()) == null)
dataVars.add(vs);
}
} */
int count = 0;
for (PointFeature pointFeature : pointFeatureCollection) {
StructureData data = pointFeature.getDataAll();
if (count == 0) {
EarthLocation loc = pointFeature.getLocation(); // LOOK we dont know this until we see the obs
String altUnits = Double.isNaN(loc.getAltitude()) ? null : "meters"; // LOOK units may be wrong
writer = new WriterCFPointDataset(out, pfDataset.getGlobalAttributes(), altUnits); // depends on control dependency: [if], data = [none]
writer.writeHeader(pfDataset.getDataVariables(), -1); // depends on control dependency: [if], data = [none]
}
writer.writeRecord(pointFeature, data);
count++;
}
writer.finish();
out.flush();
out.close();
long took = System.currentTimeMillis() - start;
System.out.printf("Write %d records from %s to %s took %d msecs %n", count, pfDataset.getLocation(), fileOut, took);
return count;
} } |
public class class_name {
public HttpRequest withHeader(String header, String value) {
if(Strings.isValid(header)) {
if(Strings.isValid(value)) {
headers.put(header, value);
} else {
withoutHeader(header);
}
}
return this;
} } | public class class_name {
public HttpRequest withHeader(String header, String value) {
if(Strings.isValid(header)) {
if(Strings.isValid(value)) {
headers.put(header, value); // depends on control dependency: [if], data = [none]
} else {
withoutHeader(header); // depends on control dependency: [if], data = [none]
}
}
return this;
} } |
public class class_name {
public int findLowestKey(int min) {
int lowest = Integer.MAX_VALUE;
int index = index(hash(min));
final int maxTry = capacity;
for (int i = 0; i < maxTry; i++) {
if (!slotIsFree(index)) {
int k = keys[index];
if (k == min) return min;
if (min < k && k < lowest) lowest = k;
}
index = nextIndex(index);
}
return lowest;
} } | public class class_name {
public int findLowestKey(int min) {
int lowest = Integer.MAX_VALUE;
int index = index(hash(min));
final int maxTry = capacity;
for (int i = 0; i < maxTry; i++) {
if (!slotIsFree(index)) {
int k = keys[index];
if (k == min) return min;
if (min < k && k < lowest) lowest = k;
}
index = nextIndex(index);
// depends on control dependency: [for], data = [none]
}
return lowest;
} } |
public class class_name {
private ClassLoader getDelegationClassLoader(String docletClassName) {
ClassLoader ctxCL = Thread.currentThread().getContextClassLoader();
ClassLoader sysCL = ClassLoader.getSystemClassLoader();
if (sysCL == null)
return ctxCL;
if (ctxCL == null)
return sysCL;
// Condition 1.
try {
sysCL.loadClass(docletClassName);
try {
ctxCL.loadClass(docletClassName);
} catch (ClassNotFoundException e) {
return sysCL;
}
} catch (ClassNotFoundException e) {
}
// Condition 2.
try {
if (getClass() == sysCL.loadClass(getClass().getName())) {
try {
if (getClass() != ctxCL.loadClass(getClass().getName()))
return sysCL;
} catch (ClassNotFoundException e) {
return sysCL;
}
}
} catch (ClassNotFoundException e) {
}
return ctxCL;
} } | public class class_name {
private ClassLoader getDelegationClassLoader(String docletClassName) {
ClassLoader ctxCL = Thread.currentThread().getContextClassLoader();
ClassLoader sysCL = ClassLoader.getSystemClassLoader();
if (sysCL == null)
return ctxCL;
if (ctxCL == null)
return sysCL;
// Condition 1.
try {
sysCL.loadClass(docletClassName); // depends on control dependency: [try], data = [none]
try {
ctxCL.loadClass(docletClassName); // depends on control dependency: [try], data = [none]
} catch (ClassNotFoundException e) {
return sysCL;
} // depends on control dependency: [catch], data = [none]
} catch (ClassNotFoundException e) {
} // depends on control dependency: [catch], data = [none]
// Condition 2.
try {
if (getClass() == sysCL.loadClass(getClass().getName())) {
try {
if (getClass() != ctxCL.loadClass(getClass().getName()))
return sysCL;
} catch (ClassNotFoundException e) {
return sysCL;
} // depends on control dependency: [catch], data = [none]
}
} catch (ClassNotFoundException e) {
} // depends on control dependency: [catch], data = [none]
return ctxCL;
} } |
public class class_name {
public boolean isInState(JComponent c) {
Component parent = c;
while (parent.getParent() != null) {
if (parent instanceof RootPaneContainer) {
break;
}
parent = parent.getParent();
}
if (parent instanceof JFrame) {
return (((JFrame) parent).getExtendedState() & Frame.MAXIMIZED_BOTH) != 0;
} else if (parent instanceof JInternalFrame) {
return ((JInternalFrame) parent).isMaximum();
}
return false;
} } | public class class_name {
public boolean isInState(JComponent c) {
Component parent = c;
while (parent.getParent() != null) {
if (parent instanceof RootPaneContainer) {
break;
}
parent = parent.getParent(); // depends on control dependency: [while], data = [none]
}
if (parent instanceof JFrame) {
return (((JFrame) parent).getExtendedState() & Frame.MAXIMIZED_BOTH) != 0; // depends on control dependency: [if], data = [none]
} else if (parent instanceof JInternalFrame) {
return ((JInternalFrame) parent).isMaximum(); // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public long getLoopDurationMs() {
if (mAnimationBackend == null) {
return 0;
}
if (mFrameScheduler != null) {
return mFrameScheduler.getLoopDurationMs();
}
int loopDurationMs = 0;
for (int i = 0; i < mAnimationBackend.getFrameCount(); i++) {
loopDurationMs += mAnimationBackend.getFrameDurationMs(i);
}
return loopDurationMs;
} } | public class class_name {
public long getLoopDurationMs() {
if (mAnimationBackend == null) {
return 0; // depends on control dependency: [if], data = [none]
}
if (mFrameScheduler != null) {
return mFrameScheduler.getLoopDurationMs(); // depends on control dependency: [if], data = [none]
}
int loopDurationMs = 0;
for (int i = 0; i < mAnimationBackend.getFrameCount(); i++) {
loopDurationMs += mAnimationBackend.getFrameDurationMs(i); // depends on control dependency: [for], data = [i]
}
return loopDurationMs;
} } |
public class class_name {
@Override
public void setChannels(final Set<String> channels) {
checkChannels(channels);
this.channels.clear();
this.channels.addAll(channels);
if (this.jedisPubSub.isSubscribed()) {
this.jedisPubSub.unsubscribe();
}
} } | public class class_name {
@Override
public void setChannels(final Set<String> channels) {
checkChannels(channels);
this.channels.clear();
this.channels.addAll(channels);
if (this.jedisPubSub.isSubscribed()) {
this.jedisPubSub.unsubscribe(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void saveImages( Element form )
throws IOException {
List<Element> images = DomUtils.getElementsByTagName( form, "img" );
int imageCount = 1;
for ( Element image : images ) {
if ( image.hasAttribute( "src" ) ) {
String src = image.getAttribute( "src" );
String imageFormat = parseImageFormat( src );
String testName = System.getProperty( "TestName" );
String imgName = parseImageName( testName );
URL url = new URL( src );
BufferedImage img = ImageIO.read( url );
File file = createImageFile( imageCount, imageFormat, imgName );
if ( !file.exists() ) {
file.getParentFile().mkdirs();
}
ImageIO.write( img, imageFormat, file );
imageCount++;
}
}
} } | public class class_name {
public void saveImages( Element form )
throws IOException {
List<Element> images = DomUtils.getElementsByTagName( form, "img" );
int imageCount = 1;
for ( Element image : images ) {
if ( image.hasAttribute( "src" ) ) {
String src = image.getAttribute( "src" );
String imageFormat = parseImageFormat( src );
String testName = System.getProperty( "TestName" );
String imgName = parseImageName( testName );
URL url = new URL( src );
BufferedImage img = ImageIO.read( url );
File file = createImageFile( imageCount, imageFormat, imgName );
if ( !file.exists() ) {
file.getParentFile().mkdirs(); // depends on control dependency: [if], data = [none]
}
ImageIO.write( img, imageFormat, file ); // depends on control dependency: [if], data = [none]
imageCount++; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
@Override
String doGetValueAsQueryToken(FhirContext theContext) {
if (getSystem() != null) {
if (getValue() != null) {
return ParameterUtil.escape(StringUtils.defaultString(getSystem())) + '|' + ParameterUtil.escape(getValue());
} else {
return ParameterUtil.escape(StringUtils.defaultString(getSystem())) + '|';
}
}
return ParameterUtil.escape(getValue());
} } | public class class_name {
@Override
String doGetValueAsQueryToken(FhirContext theContext) {
if (getSystem() != null) {
if (getValue() != null) {
return ParameterUtil.escape(StringUtils.defaultString(getSystem())) + '|' + ParameterUtil.escape(getValue()); // depends on control dependency: [if], data = [(getValue()]
} else {
return ParameterUtil.escape(StringUtils.defaultString(getSystem())) + '|'; // depends on control dependency: [if], data = [none]
}
}
return ParameterUtil.escape(getValue());
} } |
public class class_name {
public static @Nonnull double[][] fromJsonJLineString(@Nonnull JsonArray lineString) {
double[][] result = new double[lineString.size()][lineString.get(0).asArray().size()];
for(int i =0; i<lineString.size();i++) {
JsonArray subArray = lineString.get(i).asArray();
for(int j =0; j<subArray.size();j++) {
result[i][j] = subArray.get(j).asPrimitive().asDouble();
}
}
return result;
} } | public class class_name {
public static @Nonnull double[][] fromJsonJLineString(@Nonnull JsonArray lineString) {
double[][] result = new double[lineString.size()][lineString.get(0).asArray().size()];
for(int i =0; i<lineString.size();i++) {
JsonArray subArray = lineString.get(i).asArray();
for(int j =0; j<subArray.size();j++) {
result[i][j] = subArray.get(j).asPrimitive().asDouble(); // depends on control dependency: [for], data = [j]
}
}
return result;
} } |
public class class_name {
private String asJettyFriendlyPath(String path, String name) {
try {
new URL(path);
log.debug("Defer interpretation of {} URL '{}' to Jetty", name, path);
return path;
} catch (MalformedURLException e) {
//Expected. We've got a path and not a URL
Path p = Paths.get(path);
if (Files.exists(Paths.get(path))) {
//Jetty knows how to find files on the file system
log.debug("Located {} '{}' on file system", name, path);
return path;
} else {
//Maybe it's a resource on the Classpath. Jetty needs that converted to a URL.
//(e.g. "jar:file:/path/to/my.jar!<path>")
URL url = JettyServer.class.getResource(path);
if (url != null) {
log.debug("Located {} '{}' on Classpath", name, path);
return url.toExternalForm();
} else {
throw new IllegalArgumentException(String.format("%s '%s' not found", name, path));
}
}
}
} } | public class class_name {
private String asJettyFriendlyPath(String path, String name) {
try {
new URL(path); // depends on control dependency: [try], data = [none]
log.debug("Defer interpretation of {} URL '{}' to Jetty", name, path); // depends on control dependency: [try], data = [none]
return path; // depends on control dependency: [try], data = [none]
} catch (MalformedURLException e) {
//Expected. We've got a path and not a URL
Path p = Paths.get(path);
if (Files.exists(Paths.get(path))) {
//Jetty knows how to find files on the file system
log.debug("Located {} '{}' on file system", name, path); // depends on control dependency: [if], data = [none]
return path; // depends on control dependency: [if], data = [none]
} else {
//Maybe it's a resource on the Classpath. Jetty needs that converted to a URL.
//(e.g. "jar:file:/path/to/my.jar!<path>")
URL url = JettyServer.class.getResource(path);
if (url != null) {
log.debug("Located {} '{}' on Classpath", name, path); // depends on control dependency: [if], data = [none]
return url.toExternalForm(); // depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException(String.format("%s '%s' not found", name, path));
}
}
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
static void assignCustomUuids(@NonNull final Intent intent) {
// Added in SDK 4.3.0. Legacy DFU and Legacy bootloader share the same UUIDs.
Parcelable[] uuids = intent.getParcelableArrayExtra(DfuBaseService.EXTRA_CUSTOM_UUIDS_FOR_LEGACY_DFU);
if (uuids != null && uuids.length == 4) {
LegacyDfuImpl.DFU_SERVICE_UUID = uuids[0] != null ? ((ParcelUuid) uuids[0]).getUuid() : LegacyDfuImpl.DEFAULT_DFU_SERVICE_UUID;
LegacyDfuImpl.DFU_CONTROL_POINT_UUID = uuids[1] != null ? ((ParcelUuid) uuids[1]).getUuid() : LegacyDfuImpl.DEFAULT_DFU_CONTROL_POINT_UUID;
LegacyDfuImpl.DFU_PACKET_UUID = uuids[2] != null ? ((ParcelUuid) uuids[2]).getUuid() : LegacyDfuImpl.DEFAULT_DFU_PACKET_UUID;
LegacyDfuImpl.DFU_VERSION_UUID = uuids[3] != null ? ((ParcelUuid) uuids[3]).getUuid() : LegacyDfuImpl.DEFAULT_DFU_VERSION_UUID;
LegacyButtonlessDfuImpl.DFU_SERVICE_UUID = LegacyDfuImpl.DFU_SERVICE_UUID;
LegacyButtonlessDfuImpl.DFU_CONTROL_POINT_UUID = LegacyDfuImpl.DFU_CONTROL_POINT_UUID;
// No need for DFU Packet in buttonless DFU
LegacyButtonlessDfuImpl.DFU_VERSION_UUID = LegacyDfuImpl.DFU_VERSION_UUID;
} else {
LegacyDfuImpl.DFU_SERVICE_UUID = LegacyDfuImpl.DEFAULT_DFU_SERVICE_UUID;
LegacyDfuImpl.DFU_CONTROL_POINT_UUID = LegacyDfuImpl.DEFAULT_DFU_CONTROL_POINT_UUID;
LegacyDfuImpl.DFU_PACKET_UUID = LegacyDfuImpl.DEFAULT_DFU_PACKET_UUID;
LegacyDfuImpl.DFU_VERSION_UUID = LegacyDfuImpl.DEFAULT_DFU_VERSION_UUID;
LegacyButtonlessDfuImpl.DFU_SERVICE_UUID = LegacyDfuImpl.DEFAULT_DFU_SERVICE_UUID;
LegacyButtonlessDfuImpl.DFU_CONTROL_POINT_UUID = LegacyDfuImpl.DEFAULT_DFU_CONTROL_POINT_UUID;
LegacyButtonlessDfuImpl.DFU_VERSION_UUID = LegacyDfuImpl.DEFAULT_DFU_VERSION_UUID;
}
// Added in SDK 12
uuids = intent.getParcelableArrayExtra(DfuBaseService.EXTRA_CUSTOM_UUIDS_FOR_SECURE_DFU);
if (uuids != null && uuids.length == 3) {
SecureDfuImpl.DFU_SERVICE_UUID = uuids[0] != null ? ((ParcelUuid) uuids[0]).getUuid() : SecureDfuImpl.DEFAULT_DFU_SERVICE_UUID;
SecureDfuImpl.DFU_CONTROL_POINT_UUID = uuids[1] != null ? ((ParcelUuid) uuids[1]).getUuid() : SecureDfuImpl.DEFAULT_DFU_CONTROL_POINT_UUID;
SecureDfuImpl.DFU_PACKET_UUID = uuids[2] != null ? ((ParcelUuid) uuids[2]).getUuid() : SecureDfuImpl.DEFAULT_DFU_PACKET_UUID;
} else {
SecureDfuImpl.DFU_SERVICE_UUID = SecureDfuImpl.DEFAULT_DFU_SERVICE_UUID;
SecureDfuImpl.DFU_CONTROL_POINT_UUID = SecureDfuImpl.DEFAULT_DFU_CONTROL_POINT_UUID;
SecureDfuImpl.DFU_PACKET_UUID = SecureDfuImpl.DEFAULT_DFU_PACKET_UUID;
}
uuids = intent.getParcelableArrayExtra(DfuBaseService.EXTRA_CUSTOM_UUIDS_FOR_EXPERIMENTAL_BUTTONLESS_DFU);
if (uuids != null && uuids.length == 2) {
ExperimentalButtonlessDfuImpl.EXPERIMENTAL_BUTTONLESS_DFU_SERVICE_UUID = uuids[0] != null ? ((ParcelUuid) uuids[0]).getUuid() : ExperimentalButtonlessDfuImpl.DEFAULT_EXPERIMENTAL_BUTTONLESS_DFU_SERVICE_UUID;
ExperimentalButtonlessDfuImpl.EXPERIMENTAL_BUTTONLESS_DFU_UUID = uuids[1] != null ? ((ParcelUuid) uuids[1]).getUuid() : ExperimentalButtonlessDfuImpl.DEFAULT_EXPERIMENTAL_BUTTONLESS_DFU_UUID;
} else {
ExperimentalButtonlessDfuImpl.EXPERIMENTAL_BUTTONLESS_DFU_SERVICE_UUID = ExperimentalButtonlessDfuImpl.DEFAULT_EXPERIMENTAL_BUTTONLESS_DFU_SERVICE_UUID;
ExperimentalButtonlessDfuImpl.EXPERIMENTAL_BUTTONLESS_DFU_UUID = ExperimentalButtonlessDfuImpl.DEFAULT_EXPERIMENTAL_BUTTONLESS_DFU_UUID;
}
// Added in SDK 13
uuids = intent.getParcelableArrayExtra(DfuBaseService.EXTRA_CUSTOM_UUIDS_FOR_BUTTONLESS_DFU_WITHOUT_BOND_SHARING);
if (uuids != null && uuids.length == 2) {
ButtonlessDfuWithoutBondSharingImpl.BUTTONLESS_DFU_SERVICE_UUID = uuids[0] != null ? ((ParcelUuid) uuids[0]).getUuid() : ButtonlessDfuWithoutBondSharingImpl.DEFAULT_BUTTONLESS_DFU_SERVICE_UUID;
ButtonlessDfuWithoutBondSharingImpl.BUTTONLESS_DFU_UUID = uuids[1] != null ? ((ParcelUuid) uuids[1]).getUuid() : ButtonlessDfuWithoutBondSharingImpl.DEFAULT_BUTTONLESS_DFU_UUID;
} else {
ButtonlessDfuWithoutBondSharingImpl.BUTTONLESS_DFU_SERVICE_UUID = ButtonlessDfuWithoutBondSharingImpl.DEFAULT_BUTTONLESS_DFU_SERVICE_UUID;
ButtonlessDfuWithoutBondSharingImpl.BUTTONLESS_DFU_UUID = ButtonlessDfuWithoutBondSharingImpl.DEFAULT_BUTTONLESS_DFU_UUID;
}
// Added in SDK 14 (or later)
uuids = intent.getParcelableArrayExtra(DfuBaseService.EXTRA_CUSTOM_UUIDS_FOR_BUTTONLESS_DFU_WITH_BOND_SHARING);
if (uuids != null && uuids.length == 2) {
ButtonlessDfuWithBondSharingImpl.BUTTONLESS_DFU_SERVICE_UUID = uuids[0] != null ? ((ParcelUuid) uuids[0]).getUuid() : ButtonlessDfuWithBondSharingImpl.DEFAULT_BUTTONLESS_DFU_SERVICE_UUID;
ButtonlessDfuWithBondSharingImpl.BUTTONLESS_DFU_UUID = uuids[1] != null ? ((ParcelUuid) uuids[1]).getUuid() : ButtonlessDfuWithBondSharingImpl.DEFAULT_BUTTONLESS_DFU_UUID;
} else {
ButtonlessDfuWithBondSharingImpl.BUTTONLESS_DFU_SERVICE_UUID = ButtonlessDfuWithBondSharingImpl.DEFAULT_BUTTONLESS_DFU_SERVICE_UUID;
ButtonlessDfuWithBondSharingImpl.BUTTONLESS_DFU_UUID = ButtonlessDfuWithBondSharingImpl.DEFAULT_BUTTONLESS_DFU_UUID;
}
} } | public class class_name {
static void assignCustomUuids(@NonNull final Intent intent) {
// Added in SDK 4.3.0. Legacy DFU and Legacy bootloader share the same UUIDs.
Parcelable[] uuids = intent.getParcelableArrayExtra(DfuBaseService.EXTRA_CUSTOM_UUIDS_FOR_LEGACY_DFU);
if (uuids != null && uuids.length == 4) {
LegacyDfuImpl.DFU_SERVICE_UUID = uuids[0] != null ? ((ParcelUuid) uuids[0]).getUuid() : LegacyDfuImpl.DEFAULT_DFU_SERVICE_UUID; // depends on control dependency: [if], data = [none]
LegacyDfuImpl.DFU_CONTROL_POINT_UUID = uuids[1] != null ? ((ParcelUuid) uuids[1]).getUuid() : LegacyDfuImpl.DEFAULT_DFU_CONTROL_POINT_UUID; // depends on control dependency: [if], data = [none]
LegacyDfuImpl.DFU_PACKET_UUID = uuids[2] != null ? ((ParcelUuid) uuids[2]).getUuid() : LegacyDfuImpl.DEFAULT_DFU_PACKET_UUID; // depends on control dependency: [if], data = [none]
LegacyDfuImpl.DFU_VERSION_UUID = uuids[3] != null ? ((ParcelUuid) uuids[3]).getUuid() : LegacyDfuImpl.DEFAULT_DFU_VERSION_UUID; // depends on control dependency: [if], data = [none]
LegacyButtonlessDfuImpl.DFU_SERVICE_UUID = LegacyDfuImpl.DFU_SERVICE_UUID; // depends on control dependency: [if], data = [none]
LegacyButtonlessDfuImpl.DFU_CONTROL_POINT_UUID = LegacyDfuImpl.DFU_CONTROL_POINT_UUID; // depends on control dependency: [if], data = [none]
// No need for DFU Packet in buttonless DFU
LegacyButtonlessDfuImpl.DFU_VERSION_UUID = LegacyDfuImpl.DFU_VERSION_UUID; // depends on control dependency: [if], data = [none]
} else {
LegacyDfuImpl.DFU_SERVICE_UUID = LegacyDfuImpl.DEFAULT_DFU_SERVICE_UUID; // depends on control dependency: [if], data = [none]
LegacyDfuImpl.DFU_CONTROL_POINT_UUID = LegacyDfuImpl.DEFAULT_DFU_CONTROL_POINT_UUID; // depends on control dependency: [if], data = [none]
LegacyDfuImpl.DFU_PACKET_UUID = LegacyDfuImpl.DEFAULT_DFU_PACKET_UUID; // depends on control dependency: [if], data = [none]
LegacyDfuImpl.DFU_VERSION_UUID = LegacyDfuImpl.DEFAULT_DFU_VERSION_UUID; // depends on control dependency: [if], data = [none]
LegacyButtonlessDfuImpl.DFU_SERVICE_UUID = LegacyDfuImpl.DEFAULT_DFU_SERVICE_UUID; // depends on control dependency: [if], data = [none]
LegacyButtonlessDfuImpl.DFU_CONTROL_POINT_UUID = LegacyDfuImpl.DEFAULT_DFU_CONTROL_POINT_UUID; // depends on control dependency: [if], data = [none]
LegacyButtonlessDfuImpl.DFU_VERSION_UUID = LegacyDfuImpl.DEFAULT_DFU_VERSION_UUID; // depends on control dependency: [if], data = [none]
}
// Added in SDK 12
uuids = intent.getParcelableArrayExtra(DfuBaseService.EXTRA_CUSTOM_UUIDS_FOR_SECURE_DFU);
if (uuids != null && uuids.length == 3) {
SecureDfuImpl.DFU_SERVICE_UUID = uuids[0] != null ? ((ParcelUuid) uuids[0]).getUuid() : SecureDfuImpl.DEFAULT_DFU_SERVICE_UUID; // depends on control dependency: [if], data = [none]
SecureDfuImpl.DFU_CONTROL_POINT_UUID = uuids[1] != null ? ((ParcelUuid) uuids[1]).getUuid() : SecureDfuImpl.DEFAULT_DFU_CONTROL_POINT_UUID; // depends on control dependency: [if], data = [none]
SecureDfuImpl.DFU_PACKET_UUID = uuids[2] != null ? ((ParcelUuid) uuids[2]).getUuid() : SecureDfuImpl.DEFAULT_DFU_PACKET_UUID; // depends on control dependency: [if], data = [none]
} else {
SecureDfuImpl.DFU_SERVICE_UUID = SecureDfuImpl.DEFAULT_DFU_SERVICE_UUID; // depends on control dependency: [if], data = [none]
SecureDfuImpl.DFU_CONTROL_POINT_UUID = SecureDfuImpl.DEFAULT_DFU_CONTROL_POINT_UUID; // depends on control dependency: [if], data = [none]
SecureDfuImpl.DFU_PACKET_UUID = SecureDfuImpl.DEFAULT_DFU_PACKET_UUID; // depends on control dependency: [if], data = [none]
}
uuids = intent.getParcelableArrayExtra(DfuBaseService.EXTRA_CUSTOM_UUIDS_FOR_EXPERIMENTAL_BUTTONLESS_DFU);
if (uuids != null && uuids.length == 2) {
ExperimentalButtonlessDfuImpl.EXPERIMENTAL_BUTTONLESS_DFU_SERVICE_UUID = uuids[0] != null ? ((ParcelUuid) uuids[0]).getUuid() : ExperimentalButtonlessDfuImpl.DEFAULT_EXPERIMENTAL_BUTTONLESS_DFU_SERVICE_UUID; // depends on control dependency: [if], data = [none]
ExperimentalButtonlessDfuImpl.EXPERIMENTAL_BUTTONLESS_DFU_UUID = uuids[1] != null ? ((ParcelUuid) uuids[1]).getUuid() : ExperimentalButtonlessDfuImpl.DEFAULT_EXPERIMENTAL_BUTTONLESS_DFU_UUID; // depends on control dependency: [if], data = [none]
} else {
ExperimentalButtonlessDfuImpl.EXPERIMENTAL_BUTTONLESS_DFU_SERVICE_UUID = ExperimentalButtonlessDfuImpl.DEFAULT_EXPERIMENTAL_BUTTONLESS_DFU_SERVICE_UUID; // depends on control dependency: [if], data = [none]
ExperimentalButtonlessDfuImpl.EXPERIMENTAL_BUTTONLESS_DFU_UUID = ExperimentalButtonlessDfuImpl.DEFAULT_EXPERIMENTAL_BUTTONLESS_DFU_UUID; // depends on control dependency: [if], data = [none]
}
// Added in SDK 13
uuids = intent.getParcelableArrayExtra(DfuBaseService.EXTRA_CUSTOM_UUIDS_FOR_BUTTONLESS_DFU_WITHOUT_BOND_SHARING);
if (uuids != null && uuids.length == 2) {
ButtonlessDfuWithoutBondSharingImpl.BUTTONLESS_DFU_SERVICE_UUID = uuids[0] != null ? ((ParcelUuid) uuids[0]).getUuid() : ButtonlessDfuWithoutBondSharingImpl.DEFAULT_BUTTONLESS_DFU_SERVICE_UUID; // depends on control dependency: [if], data = [none]
ButtonlessDfuWithoutBondSharingImpl.BUTTONLESS_DFU_UUID = uuids[1] != null ? ((ParcelUuid) uuids[1]).getUuid() : ButtonlessDfuWithoutBondSharingImpl.DEFAULT_BUTTONLESS_DFU_UUID; // depends on control dependency: [if], data = [none]
} else {
ButtonlessDfuWithoutBondSharingImpl.BUTTONLESS_DFU_SERVICE_UUID = ButtonlessDfuWithoutBondSharingImpl.DEFAULT_BUTTONLESS_DFU_SERVICE_UUID; // depends on control dependency: [if], data = [none]
ButtonlessDfuWithoutBondSharingImpl.BUTTONLESS_DFU_UUID = ButtonlessDfuWithoutBondSharingImpl.DEFAULT_BUTTONLESS_DFU_UUID; // depends on control dependency: [if], data = [none]
}
// Added in SDK 14 (or later)
uuids = intent.getParcelableArrayExtra(DfuBaseService.EXTRA_CUSTOM_UUIDS_FOR_BUTTONLESS_DFU_WITH_BOND_SHARING);
if (uuids != null && uuids.length == 2) {
ButtonlessDfuWithBondSharingImpl.BUTTONLESS_DFU_SERVICE_UUID = uuids[0] != null ? ((ParcelUuid) uuids[0]).getUuid() : ButtonlessDfuWithBondSharingImpl.DEFAULT_BUTTONLESS_DFU_SERVICE_UUID; // depends on control dependency: [if], data = [none]
ButtonlessDfuWithBondSharingImpl.BUTTONLESS_DFU_UUID = uuids[1] != null ? ((ParcelUuid) uuids[1]).getUuid() : ButtonlessDfuWithBondSharingImpl.DEFAULT_BUTTONLESS_DFU_UUID; // depends on control dependency: [if], data = [none]
} else {
ButtonlessDfuWithBondSharingImpl.BUTTONLESS_DFU_SERVICE_UUID = ButtonlessDfuWithBondSharingImpl.DEFAULT_BUTTONLESS_DFU_SERVICE_UUID; // depends on control dependency: [if], data = [none]
ButtonlessDfuWithBondSharingImpl.BUTTONLESS_DFU_UUID = ButtonlessDfuWithBondSharingImpl.DEFAULT_BUTTONLESS_DFU_UUID; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void removeArgFromFunction(String varName, DifferentialFunction function) {
val args = function.args();
for (int i = 0; i < args.length; i++) {
if (args[i].getVarName().equals(varName)) {
/**
* Since we are removing the variable reference
* from the arguments we need to update both
* the reverse and forward arguments.
*/
val reverseArgs = incomingArgsReverse.get(function.getOwnName());
incomingArgs.remove(reverseArgs);
incomingArgsReverse.remove(function.getOwnName());
val newArgs = new ArrayList<String>(args.length - 1);
for (int arg = 0; arg < args.length; arg++) {
if (!reverseArgs[arg].equals(varName)) {
newArgs.add(reverseArgs[arg]);
}
}
val newArgsArr = newArgs.toArray(new String[newArgs.size()]);
incomingArgs.put(newArgsArr, function);
incomingArgsReverse.put(function.getOwnName(), newArgsArr);
//no further need to scan
break;
}
}
} } | public class class_name {
public void removeArgFromFunction(String varName, DifferentialFunction function) {
val args = function.args();
for (int i = 0; i < args.length; i++) {
if (args[i].getVarName().equals(varName)) {
/**
* Since we are removing the variable reference
* from the arguments we need to update both
* the reverse and forward arguments.
*/
val reverseArgs = incomingArgsReverse.get(function.getOwnName());
incomingArgs.remove(reverseArgs); // depends on control dependency: [if], data = [none]
incomingArgsReverse.remove(function.getOwnName()); // depends on control dependency: [if], data = [none]
val newArgs = new ArrayList<String>(args.length - 1);
for (int arg = 0; arg < args.length; arg++) {
if (!reverseArgs[arg].equals(varName)) {
newArgs.add(reverseArgs[arg]); // depends on control dependency: [if], data = [none]
}
}
val newArgsArr = newArgs.toArray(new String[newArgs.size()]);
incomingArgs.put(newArgsArr, function); // depends on control dependency: [if], data = [none]
incomingArgsReverse.put(function.getOwnName(), newArgsArr); // depends on control dependency: [if], data = [none]
//no further need to scan
break;
}
}
} } |
public class class_name {
public String encode(String text) {
Assert.notNull(text, "Text should not be null.");
text = text.toUpperCase();
final StringBuilder morseBuilder = new StringBuilder();
final int len = text.codePointCount(0, text.length());
for (int i = 0; i < len; i++) {
int codePoint = text.codePointAt(i);
String word = alphabets.get(codePoint);
if (word == null) {
word = Integer.toBinaryString(codePoint);
}
morseBuilder.append(word.replace('0', dit).replace('1', dah)).append(split);
}
return morseBuilder.toString();
} } | public class class_name {
public String encode(String text) {
Assert.notNull(text, "Text should not be null.");
text = text.toUpperCase();
final StringBuilder morseBuilder = new StringBuilder();
final int len = text.codePointCount(0, text.length());
for (int i = 0; i < len; i++) {
int codePoint = text.codePointAt(i);
String word = alphabets.get(codePoint);
if (word == null) {
word = Integer.toBinaryString(codePoint);
// depends on control dependency: [if], data = [none]
}
morseBuilder.append(word.replace('0', dit).replace('1', dah)).append(split);
// depends on control dependency: [for], data = [none]
}
return morseBuilder.toString();
} } |
public class class_name {
private Region remove(Region x) {
this.deletedNode = NULL_NODE;
this.root = remove(x, this.root);
Region d = this.deletedElement;
// deletedElement is set to null to free the reference,
// deletedNode is not freed as it will endup pointing to a valid node.
this.deletedElement = null;
if (d == null) {
return null;
} else {
return new Region(d);
}
} } | public class class_name {
private Region remove(Region x) {
this.deletedNode = NULL_NODE;
this.root = remove(x, this.root);
Region d = this.deletedElement;
// deletedElement is set to null to free the reference,
// deletedNode is not freed as it will endup pointing to a valid node.
this.deletedElement = null;
if (d == null) {
return null; // depends on control dependency: [if], data = [none]
} else {
return new Region(d); // depends on control dependency: [if], data = [(d]
}
} } |
public class class_name {
static String requestURI(HttpServletRequest request)
{
String uri = request.getRequestURI();
if (uri != null)
{
String contextPath = request.getContextPath();
int length = contextPath == null ? 0 : contextPath.length();
if (length > 0)
{
uri = uri.substring(length);
}
if (uri.equals("/"))
{
uri = "";
}
}
else
{
uri = "";
}
// according to the JACC specification, all colons within the request URI must be escaped.
if (uri.indexOf(':') > 0)
uri = uri.replaceAll(":", ENCODED_COLON);
return uri;
} } | public class class_name {
static String requestURI(HttpServletRequest request)
{
String uri = request.getRequestURI();
if (uri != null)
{
String contextPath = request.getContextPath();
int length = contextPath == null ? 0 : contextPath.length();
if (length > 0)
{
uri = uri.substring(length); // depends on control dependency: [if], data = [(length]
}
if (uri.equals("/"))
{
uri = ""; // depends on control dependency: [if], data = [none]
}
}
else
{
uri = ""; // depends on control dependency: [if], data = [none]
}
// according to the JACC specification, all colons within the request URI must be escaped.
if (uri.indexOf(':') > 0)
uri = uri.replaceAll(":", ENCODED_COLON);
return uri;
} } |
public class class_name {
final int doExec() {
int s; boolean completed;
if ((s = status) >= 0) {
try {
completed = exec();
} catch (Throwable rex) {
return setExceptionalCompletion(rex);
}
if (completed)
s = setCompletion(NORMAL);
}
return s;
} } | public class class_name {
final int doExec() {
int s; boolean completed;
if ((s = status) >= 0) {
try {
completed = exec(); // depends on control dependency: [try], data = [none]
} catch (Throwable rex) {
return setExceptionalCompletion(rex);
} // depends on control dependency: [catch], data = [none]
if (completed)
s = setCompletion(NORMAL);
}
return s;
} } |
public class class_name {
private boolean checkDimensions(CLIQUEUnit other, int e) {
for(int i = 0, j = 0; i < e; i++, j += 2) {
if(dims[i] != other.dims[i] || bounds[j] != other.bounds[j] || bounds[j + 1] != bounds[j + 1]) {
return false;
}
}
return true;
} } | public class class_name {
private boolean checkDimensions(CLIQUEUnit other, int e) {
for(int i = 0, j = 0; i < e; i++, j += 2) {
if(dims[i] != other.dims[i] || bounds[j] != other.bounds[j] || bounds[j + 1] != bounds[j + 1]) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
private WyalFile.VariableDeclaration[] generatePreconditionParameters(WyilFile.Decl.Callable declaration,
LocalEnvironment environment) {
Tuple<WyilFile.Decl.Variable> params = declaration.getParameters();
WyalFile.VariableDeclaration[] vars = new WyalFile.VariableDeclaration[params.size()];
// second, set initial environment
for (int i = 0; i != params.size(); ++i) {
WyilFile.Decl.Variable var = params.get(i);
vars[i] = environment.read(var);
}
return vars;
} } | public class class_name {
private WyalFile.VariableDeclaration[] generatePreconditionParameters(WyilFile.Decl.Callable declaration,
LocalEnvironment environment) {
Tuple<WyilFile.Decl.Variable> params = declaration.getParameters();
WyalFile.VariableDeclaration[] vars = new WyalFile.VariableDeclaration[params.size()];
// second, set initial environment
for (int i = 0; i != params.size(); ++i) {
WyilFile.Decl.Variable var = params.get(i);
vars[i] = environment.read(var); // depends on control dependency: [for], data = [i]
}
return vars;
} } |
public class class_name {
private ClientResponseImpl coreCall(Object... paramListIn) {
VoltTable[] results = null;
// use local var to avoid warnings about reassigning method argument
Object[] paramList = paramListIn;
try {
if ((m_paramTypes.length > 0) && (m_paramTypes[0] == ParameterSet.class)) {
assert(m_paramTypes.length == 1);
paramList = new Object[] { ParameterSet.fromArrayNoCopy(paramListIn) };
}
if (paramList.length != m_paramTypes.length) {
String msg = "PROCEDURE " + m_procedureName + " EXPECTS " + String.valueOf(m_paramTypes.length) +
" PARAMS, BUT RECEIVED " + String.valueOf(paramList.length);
m_statusCode = ClientResponse.GRACEFUL_FAILURE;
return ProcedureRunner.getErrorResponse(m_statusCode, m_appStatusCode, m_appStatusString, msg, null);
}
for (int i = 0; i < m_paramTypes.length; i++) {
try {
paramList[i] = ParameterConverter.tryToMakeCompatible(m_paramTypes[i], paramList[i]);
// check the result type in an assert
assert(ParameterConverter.verifyParameterConversion(paramList[i], m_paramTypes[i]));
} catch (Exception e) {
String msg = "PROCEDURE " + m_procedureName + " TYPE ERROR FOR PARAMETER " + i +
": " + e.toString();
m_statusCode = ClientResponse.GRACEFUL_FAILURE;
return ProcedureRunner.getErrorResponse(m_statusCode, m_appStatusCode, m_appStatusString, msg, null);
}
}
try {
m_procedure.m_runner = this;
Object rawResult = m_procMethod.invoke(m_procedure, paramList);
if (rawResult instanceof CompletableFuture<?>) {
final CompletableFuture<?> fut = (CompletableFuture<?>) rawResult;
fut.thenRun(() -> {
//
// Happy path. No exceptions thrown. Procedure work is complete.
//
Object innerRawResult = null;
ClientResponseImpl response = null;
try {
innerRawResult = fut.get();
} catch (InterruptedException | ExecutionException e) {
assert(false);
// this is a bad place to be, but it's hard to know if it's crash bad...
innerRawResult = new ClientResponseImpl(ClientResponseImpl.UNEXPECTED_FAILURE,
new VoltTable[0],
"Future returned from NTProc " + m_procedureName + " failed to complete.",
m_clientHandle);
}
if (innerRawResult instanceof ClientResponseImpl) {
response = (ClientResponseImpl) innerRawResult;
}
else {
try {
VoltTable[] r = ParameterConverter.getResultsFromRawResults(m_procedureName, innerRawResult);
response = responseFromTableArray(r);
} catch (Exception e) {
// this is a bad place to be, but it's hard to know if it's crash bad...
response = new ClientResponseImpl(ClientResponseImpl.GRACEFUL_FAILURE,
new VoltTable[0],
"Type " + innerRawResult.getClass().getName() +
" returned from NTProc \"" + m_procedureName +
"\" was not an acceptible VoltDB return type.",
m_clientHandle);
}
}
completeCall(response);
})
.exceptionally(e -> {
//
// Exception path. Some bit of async work threw something.
//
SerializableException se = null;
if (e instanceof SerializableException) {
se = (SerializableException) e;
}
String msg = "PROCEDURE " + m_procedureName + " THREW EXCEPTION: ";
if (se != null) {
msg += se.getMessage();
} else {
msg += e.toString();
}
m_statusCode = ClientResponse.GRACEFUL_FAILURE;
completeCall(ProcedureRunner.getErrorResponse(m_statusCode, m_appStatusCode, m_appStatusString, msg, se));
return null;
});
return null;
}
results = ParameterConverter.getResultsFromRawResults(m_procedureName, rawResult);
}
catch (IllegalAccessException e) {
// If reflection fails, invoke the same error handling that other exceptions do
throw new InvocationTargetException(e);
}
}
catch (InvocationTargetException itex) {
//itex.printStackTrace();
Throwable ex = itex.getCause();
if (CoreUtils.isStoredProcThrowableFatalToServer(ex)) {
// If the stored procedure attempted to do something other than linklibrary or instantiate
// a missing object that results in an error, throw the error and let the server deal with
// the condition as best as it can (usually a crashLocalVoltDB).
throw (Error)ex;
}
return ProcedureRunner.getErrorResponse(m_procedureName,
true,
0,
m_appStatusCode,
m_appStatusString,
null,
ex);
}
return responseFromTableArray(results);
} } | public class class_name {
private ClientResponseImpl coreCall(Object... paramListIn) {
VoltTable[] results = null;
// use local var to avoid warnings about reassigning method argument
Object[] paramList = paramListIn;
try {
if ((m_paramTypes.length > 0) && (m_paramTypes[0] == ParameterSet.class)) {
assert(m_paramTypes.length == 1); // depends on control dependency: [if], data = [none]
paramList = new Object[] { ParameterSet.fromArrayNoCopy(paramListIn) }; // depends on control dependency: [if], data = [none]
}
if (paramList.length != m_paramTypes.length) {
String msg = "PROCEDURE " + m_procedureName + " EXPECTS " + String.valueOf(m_paramTypes.length) +
" PARAMS, BUT RECEIVED " + String.valueOf(paramList.length); // depends on control dependency: [if], data = [(paramList.length]
m_statusCode = ClientResponse.GRACEFUL_FAILURE; // depends on control dependency: [if], data = [none]
return ProcedureRunner.getErrorResponse(m_statusCode, m_appStatusCode, m_appStatusString, msg, null); // depends on control dependency: [if], data = [none]
}
for (int i = 0; i < m_paramTypes.length; i++) {
try {
paramList[i] = ParameterConverter.tryToMakeCompatible(m_paramTypes[i], paramList[i]); // depends on control dependency: [try], data = [none]
// check the result type in an assert
assert(ParameterConverter.verifyParameterConversion(paramList[i], m_paramTypes[i])); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
String msg = "PROCEDURE " + m_procedureName + " TYPE ERROR FOR PARAMETER " + i +
": " + e.toString();
m_statusCode = ClientResponse.GRACEFUL_FAILURE;
return ProcedureRunner.getErrorResponse(m_statusCode, m_appStatusCode, m_appStatusString, msg, null);
} // depends on control dependency: [catch], data = [none]
}
try {
m_procedure.m_runner = this; // depends on control dependency: [try], data = [none]
Object rawResult = m_procMethod.invoke(m_procedure, paramList);
if (rawResult instanceof CompletableFuture<?>) {
final CompletableFuture<?> fut = (CompletableFuture<?>) rawResult;
fut.thenRun(() -> {
//
// Happy path. No exceptions thrown. Procedure work is complete.
//
Object innerRawResult = null;
ClientResponseImpl response = null;
try {
innerRawResult = fut.get(); // depends on control dependency: [try], data = [none]
} catch (InterruptedException | ExecutionException e) {
assert(false);
// this is a bad place to be, but it's hard to know if it's crash bad...
innerRawResult = new ClientResponseImpl(ClientResponseImpl.UNEXPECTED_FAILURE,
new VoltTable[0],
"Future returned from NTProc " + m_procedureName + " failed to complete.",
m_clientHandle);
} // depends on control dependency: [catch], data = [none]
if (innerRawResult instanceof ClientResponseImpl) {
response = (ClientResponseImpl) innerRawResult; // depends on control dependency: [if], data = [none]
}
else {
try {
VoltTable[] r = ParameterConverter.getResultsFromRawResults(m_procedureName, innerRawResult);
response = responseFromTableArray(r); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
// this is a bad place to be, but it's hard to know if it's crash bad...
response = new ClientResponseImpl(ClientResponseImpl.GRACEFUL_FAILURE,
new VoltTable[0],
"Type " + innerRawResult.getClass().getName() +
" returned from NTProc \"" + m_procedureName +
"\" was not an acceptible VoltDB return type.",
m_clientHandle);
} // depends on control dependency: [catch], data = [none]
}
completeCall(response);
})
.exceptionally(e -> {
//
// Exception path. Some bit of async work threw something.
//
SerializableException se = null;
if (e instanceof SerializableException) {
se = (SerializableException) e; // depends on control dependency: [if], data = [none]
}
String msg = "PROCEDURE " + m_procedureName + " THREW EXCEPTION: ";
if (se != null) {
msg += se.getMessage(); // depends on control dependency: [if], data = [none]
} else {
msg += e.toString(); // depends on control dependency: [if], data = [none]
}
m_statusCode = ClientResponse.GRACEFUL_FAILURE;
completeCall(ProcedureRunner.getErrorResponse(m_statusCode, m_appStatusCode, m_appStatusString, msg, se));
return null;
});
return null; // depends on control dependency: [if], data = [none]
}
results = ParameterConverter.getResultsFromRawResults(m_procedureName, rawResult); // depends on control dependency: [try], data = [none]
}
catch (IllegalAccessException e) {
// If reflection fails, invoke the same error handling that other exceptions do
throw new InvocationTargetException(e);
} // depends on control dependency: [catch], data = [none]
}
catch (InvocationTargetException itex) {
//itex.printStackTrace();
Throwable ex = itex.getCause();
if (CoreUtils.isStoredProcThrowableFatalToServer(ex)) {
// If the stored procedure attempted to do something other than linklibrary or instantiate
// a missing object that results in an error, throw the error and let the server deal with
// the condition as best as it can (usually a crashLocalVoltDB).
throw (Error)ex;
}
return ProcedureRunner.getErrorResponse(m_procedureName,
true,
0,
m_appStatusCode,
m_appStatusString,
null,
ex);
} // depends on control dependency: [catch], data = [none]
return responseFromTableArray(results);
} } |
public class class_name {
public boolean equalsString(String str)
{
int expLen = str.length();
// First the easy check; if we have a shared buf:
if (mInputStart >= 0) {
if (mInputLen != expLen) {
return false;
}
for (int i = 0; i < expLen; ++i) {
if (str.charAt(i) != mInputBuffer[mInputStart+i]) {
return false;
}
}
return true;
}
// Otherwise, segments:
if (expLen != size()) {
return false;
}
char[] seg;
if (mSegments == null || mSegments.size() == 0) {
// just one segment, still easy
seg = mCurrentSegment;
} else {
/* Ok; this is the sub-optimal case. Could obviously juggle through
* segments, but probably not worth the hassle, we seldom if ever
* get here...
*/
seg = contentsAsArray();
}
for (int i = 0; i < expLen; ++i) {
if (seg[i] != str.charAt(i)) {
return false;
}
}
return true;
} } | public class class_name {
public boolean equalsString(String str)
{
int expLen = str.length();
// First the easy check; if we have a shared buf:
if (mInputStart >= 0) {
if (mInputLen != expLen) {
return false; // depends on control dependency: [if], data = [none]
}
for (int i = 0; i < expLen; ++i) {
if (str.charAt(i) != mInputBuffer[mInputStart+i]) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true; // depends on control dependency: [if], data = [none]
}
// Otherwise, segments:
if (expLen != size()) {
return false; // depends on control dependency: [if], data = [none]
}
char[] seg;
if (mSegments == null || mSegments.size() == 0) {
// just one segment, still easy
seg = mCurrentSegment; // depends on control dependency: [if], data = [none]
} else {
/* Ok; this is the sub-optimal case. Could obviously juggle through
* segments, but probably not worth the hassle, we seldom if ever
* get here...
*/
seg = contentsAsArray(); // depends on control dependency: [if], data = [none]
}
for (int i = 0; i < expLen; ++i) {
if (seg[i] != str.charAt(i)) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
private static void splitMiddleSlashFromDigitalWords(List<Vertex> linkedArray)
{
if (linkedArray.size() < 2)
return;
ListIterator<Vertex> listIterator = linkedArray.listIterator();
Vertex next = listIterator.next();
Vertex current = next;
while (listIterator.hasNext())
{
next = listIterator.next();
// System.out.println("current:" + current + " next:" + next);
Nature currentNature = current.getNature();
if (currentNature == Nature.nx && (next.hasNature(Nature.q) || next.hasNature(Nature.n)))
{
String[] param = current.realWord.split("-", 1);
if (param.length == 2)
{
if (TextUtility.isAllNum(param[0]) && TextUtility.isAllNum(param[1]))
{
current = current.copy();
current.realWord = param[0];
current.confirmNature(Nature.m);
listIterator.previous();
listIterator.previous();
listIterator.set(current);
listIterator.next();
listIterator.add(Vertex.newPunctuationInstance("-"));
listIterator.add(Vertex.newNumberInstance(param[1]));
}
}
}
current = next;
}
// logger.trace("杠号识别后:" + Graph.parseResult(linkedArray));
} } | public class class_name {
private static void splitMiddleSlashFromDigitalWords(List<Vertex> linkedArray)
{
if (linkedArray.size() < 2)
return;
ListIterator<Vertex> listIterator = linkedArray.listIterator();
Vertex next = listIterator.next();
Vertex current = next;
while (listIterator.hasNext())
{
next = listIterator.next(); // depends on control dependency: [while], data = [none]
// System.out.println("current:" + current + " next:" + next);
Nature currentNature = current.getNature();
if (currentNature == Nature.nx && (next.hasNature(Nature.q) || next.hasNature(Nature.n)))
{
String[] param = current.realWord.split("-", 1);
if (param.length == 2)
{
if (TextUtility.isAllNum(param[0]) && TextUtility.isAllNum(param[1]))
{
current = current.copy(); // depends on control dependency: [if], data = [none]
current.realWord = param[0]; // depends on control dependency: [if], data = [none]
current.confirmNature(Nature.m); // depends on control dependency: [if], data = [none]
listIterator.previous(); // depends on control dependency: [if], data = [none]
listIterator.previous(); // depends on control dependency: [if], data = [none]
listIterator.set(current); // depends on control dependency: [if], data = [none]
listIterator.next(); // depends on control dependency: [if], data = [none]
listIterator.add(Vertex.newPunctuationInstance("-")); // depends on control dependency: [if], data = [none]
listIterator.add(Vertex.newNumberInstance(param[1])); // depends on control dependency: [if], data = [none]
}
}
}
current = next; // depends on control dependency: [while], data = [none]
}
// logger.trace("杠号识别后:" + Graph.parseResult(linkedArray));
} } |
public class class_name {
public static Method generateMethodBody(Method method, String... bodyLines) {
if (bodyLines != null) {
for (String bodyLine : bodyLines) {
method.addBodyLine(bodyLine);
}
}
return method;
} } | public class class_name {
public static Method generateMethodBody(Method method, String... bodyLines) {
if (bodyLines != null) {
for (String bodyLine : bodyLines) {
method.addBodyLine(bodyLine); // depends on control dependency: [for], data = [bodyLine]
}
}
return method;
} } |
public class class_name {
public int getNextDescendant(int subtreeRootHandle, int nodeHandle) {
subtreeRootHandle &= NODEHANDLE_MASK;
nodeHandle &= NODEHANDLE_MASK;
// Document root [Document Node? -- jjk] - no next-sib
if (nodeHandle == 0)
return NULL;
while (!m_isError) {
// Document done and node out of bounds
if (done && (nodeHandle > nodes.slotsUsed()))
break;
if (nodeHandle > subtreeRootHandle) {
nodes.readSlot(nodeHandle+1, gotslot);
if (gotslot[2] != 0) {
short type = (short) (gotslot[0] & 0xFFFF);
if (type == ATTRIBUTE_NODE) {
nodeHandle +=2;
} else {
int nextParentPos = gotslot[1];
if (nextParentPos >= subtreeRootHandle)
return (m_docHandle | (nodeHandle+1));
else
break;
}
} else if (!done) {
// Add wait logic here
} else
break;
} else {
nodeHandle++;
}
}
// Probably should throw error here like original instead of returning
return NULL;
} } | public class class_name {
public int getNextDescendant(int subtreeRootHandle, int nodeHandle) {
subtreeRootHandle &= NODEHANDLE_MASK;
nodeHandle &= NODEHANDLE_MASK;
// Document root [Document Node? -- jjk] - no next-sib
if (nodeHandle == 0)
return NULL;
while (!m_isError) {
// Document done and node out of bounds
if (done && (nodeHandle > nodes.slotsUsed()))
break;
if (nodeHandle > subtreeRootHandle) {
nodes.readSlot(nodeHandle+1, gotslot); // depends on control dependency: [if], data = [(nodeHandle]
if (gotslot[2] != 0) {
short type = (short) (gotslot[0] & 0xFFFF);
if (type == ATTRIBUTE_NODE) {
nodeHandle +=2; // depends on control dependency: [if], data = [none]
} else {
int nextParentPos = gotslot[1];
if (nextParentPos >= subtreeRootHandle)
return (m_docHandle | (nodeHandle+1));
else
break;
}
} else if (!done) {
// Add wait logic here
} else
break;
} else {
nodeHandle++; // depends on control dependency: [if], data = [none]
}
}
// Probably should throw error here like original instead of returning
return NULL;
} } |
public class class_name {
public JdbcConnectionDescriptor getDescriptor(PBKey pbKey)
{
JdbcConnectionDescriptor result = (JdbcConnectionDescriptor) jcdMap.get(pbKey);
if (result == null)
{
result = deepCopyOfFirstFound(pbKey.getAlias());
if (result != null)
{
result.setUserName(pbKey.getUser());
result.setPassWord(pbKey.getPassword());
// this build connection descriptor could not be the default connection
result.setDefaultConnection(false);
log.info("Automatic create of new jdbc-connection-descriptor for PBKey " + pbKey);
addDescriptor(result);
}
else
{
log.info("Could not find " + JdbcConnectionDescriptor.class.getName() + " for PBKey " + pbKey);
}
}
return result;
} } | public class class_name {
public JdbcConnectionDescriptor getDescriptor(PBKey pbKey)
{
JdbcConnectionDescriptor result = (JdbcConnectionDescriptor) jcdMap.get(pbKey);
if (result == null)
{
result = deepCopyOfFirstFound(pbKey.getAlias());
// depends on control dependency: [if], data = [none]
if (result != null)
{
result.setUserName(pbKey.getUser());
// depends on control dependency: [if], data = [none]
result.setPassWord(pbKey.getPassword());
// depends on control dependency: [if], data = [none]
// this build connection descriptor could not be the default connection
result.setDefaultConnection(false);
// depends on control dependency: [if], data = [none]
log.info("Automatic create of new jdbc-connection-descriptor for PBKey " + pbKey);
// depends on control dependency: [if], data = [none]
addDescriptor(result);
// depends on control dependency: [if], data = [(result]
}
else
{
log.info("Could not find " + JdbcConnectionDescriptor.class.getName() + " for PBKey " + pbKey);
// depends on control dependency: [if], data = [none]
}
}
return result;
} } |
public class class_name {
public final boolean roll(final LoggingEvent loggingEvent) {
boolean rolled = false;
if (this.isMaxFileSizeExceeded()) {
super.roll(loggingEvent.getTimeStamp());
rolled = true;
}
return rolled;
} } | public class class_name {
public final boolean roll(final LoggingEvent loggingEvent) {
boolean rolled = false;
if (this.isMaxFileSizeExceeded()) {
super.roll(loggingEvent.getTimeStamp()); // depends on control dependency: [if], data = [none]
rolled = true; // depends on control dependency: [if], data = [none]
}
return rolled;
} } |
public class class_name {
private ParseTree parseDoWhileStatement() {
SourcePosition start = getTreeStartLocation();
eat(TokenType.DO);
ParseTree body = parseStatement();
eat(TokenType.WHILE);
eat(TokenType.OPEN_PAREN);
ParseTree condition = parseExpression();
eat(TokenType.CLOSE_PAREN);
// The semicolon after the "do-while" is optional.
if (peek(TokenType.SEMI_COLON)) {
eat(TokenType.SEMI_COLON);
}
return new DoWhileStatementTree(getTreeLocation(start), body, condition);
} } | public class class_name {
private ParseTree parseDoWhileStatement() {
SourcePosition start = getTreeStartLocation();
eat(TokenType.DO);
ParseTree body = parseStatement();
eat(TokenType.WHILE);
eat(TokenType.OPEN_PAREN);
ParseTree condition = parseExpression();
eat(TokenType.CLOSE_PAREN);
// The semicolon after the "do-while" is optional.
if (peek(TokenType.SEMI_COLON)) {
eat(TokenType.SEMI_COLON); // depends on control dependency: [if], data = [none]
}
return new DoWhileStatementTree(getTreeLocation(start), body, condition);
} } |
public class class_name {
private void getEJBApplicationSubclasses(Set<Class<?>> classes, EJBEndpoint ejb, ClassLoader appClassloader) {
final String methodName = "getEJBApplicationSubclasses";
if (tc.isEntryEnabled()) {
Tr.entry(tc, methodName);
}
if (classes == null) {
if (tc.isEntryEnabled())
Tr.exit(tc, methodName, Collections.emptySet());
return;
}
Class<Application> appClass = Application.class;
final String ejbClassName = ejb.getClassName();
Class<?> c = null;
try {
c = appClassloader.loadClass(ejbClassName);
} catch (ClassNotFoundException e) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, methodName + " exit - due to Class Not Found for " + ejbClassName + ": " + e);
}
}
if (c != null && appClass.isAssignableFrom(c)) {
classes.add(c);
}
if (tc.isEntryEnabled())
Tr.exit(tc, methodName, classes);
} } | public class class_name {
private void getEJBApplicationSubclasses(Set<Class<?>> classes, EJBEndpoint ejb, ClassLoader appClassloader) {
final String methodName = "getEJBApplicationSubclasses";
if (tc.isEntryEnabled()) {
Tr.entry(tc, methodName);
}
if (classes == null) {
if (tc.isEntryEnabled())
Tr.exit(tc, methodName, Collections.emptySet());
return;
}
Class<Application> appClass = Application.class;
final String ejbClassName = ejb.getClassName();
Class<?> c = null;
try {
c = appClassloader.loadClass(ejbClassName);
} catch (ClassNotFoundException e) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, methodName + " exit - due to Class Not Found for " + ejbClassName + ": " + e); // depends on control dependency: [if], data = [none]
}
}
if (c != null && appClass.isAssignableFrom(c)) {
classes.add(c);
}
if (tc.isEntryEnabled())
Tr.exit(tc, methodName, classes);
} } |
public class class_name {
protected String getSpaceId(String bucketName) {
String spaceId = bucketName;
if (isSpace(bucketName)) {
spaceId = spaceId.substring(accessKeyId.length() + 1);
}
return spaceId;
} } | public class class_name {
protected String getSpaceId(String bucketName) {
String spaceId = bucketName;
if (isSpace(bucketName)) {
spaceId = spaceId.substring(accessKeyId.length() + 1); // depends on control dependency: [if], data = [none]
}
return spaceId;
} } |
public class class_name {
@Override
public void addAttribute(final ApiAttribute attribute) {
if (new ImageUtils().isImageWrapper(attribute)) {
getImages().add(attribute);
return;
}
getAttributes().add(attribute);
} } | public class class_name {
@Override
public void addAttribute(final ApiAttribute attribute) {
if (new ImageUtils().isImageWrapper(attribute)) {
getImages().add(attribute); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
getAttributes().add(attribute);
} } |
public class class_name {
public boolean requiresUserDataCheck(CmsObject cms, CmsUser user) {
if (user.isManaged()
|| user.isWebuser()
|| OpenCms.getDefaultUsers().isDefaultUser(user.getName())
|| OpenCms.getRoleManager().hasRole(cms, user.getName(), CmsRole.ROOT_ADMIN)) {
return false;
}
String lastCheckStr = (String)user.getAdditionalInfo().get(
CmsUserSettings.ADDITIONAL_INFO_LAST_USER_DATA_CHECK);
if (lastCheckStr == null) {
return !CmsStringUtil.isEmptyOrWhitespaceOnly(getUserDataCheckIntervalStr());
}
long lastCheck = Long.parseLong(lastCheckStr);
if ((System.currentTimeMillis() - lastCheck) > getUserDataCheckInterval()) {
return true;
}
return false;
} } | public class class_name {
public boolean requiresUserDataCheck(CmsObject cms, CmsUser user) {
if (user.isManaged()
|| user.isWebuser()
|| OpenCms.getDefaultUsers().isDefaultUser(user.getName())
|| OpenCms.getRoleManager().hasRole(cms, user.getName(), CmsRole.ROOT_ADMIN)) {
return false; // depends on control dependency: [if], data = [none]
}
String lastCheckStr = (String)user.getAdditionalInfo().get(
CmsUserSettings.ADDITIONAL_INFO_LAST_USER_DATA_CHECK);
if (lastCheckStr == null) {
return !CmsStringUtil.isEmptyOrWhitespaceOnly(getUserDataCheckIntervalStr()); // depends on control dependency: [if], data = [none]
}
long lastCheck = Long.parseLong(lastCheckStr);
if ((System.currentTimeMillis() - lastCheck) > getUserDataCheckInterval()) {
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
@Override
public boolean remove(Widget w) {
// Validate.
if (w.getParent() != this) {
return false;
}
// Orphan.
try {
orphan(w);
} finally {
// Physical detach.
Element elem = w.getElement();
// NOTE (issue #486): DO NOT call DOM.getParent() to correctly handle
// text node removing. Calling DOM.getParent(TEXT_NODE) will throw a
// NPE exception.
//DOM.getParent(elem).removeChild(elem);
elem.removeFromParent();
// Logical detach.
getChildren().remove(w);
}
return true;
} } | public class class_name {
@Override
public boolean remove(Widget w) {
// Validate.
if (w.getParent() != this) {
return false; // depends on control dependency: [if], data = [none]
}
// Orphan.
try {
orphan(w); // depends on control dependency: [try], data = [none]
} finally {
// Physical detach.
Element elem = w.getElement();
// NOTE (issue #486): DO NOT call DOM.getParent() to correctly handle
// text node removing. Calling DOM.getParent(TEXT_NODE) will throw a
// NPE exception.
//DOM.getParent(elem).removeChild(elem);
elem.removeFromParent();
// Logical detach.
getChildren().remove(w);
}
return true;
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.