code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public static <E extends Exception> DataSet loadCSV(final Class<?> entityClass, final Reader csvReader, final Collection<String> selectColumnNames,
long offset, long count, final Try.Predicate<String[], E> filter) throws UncheckedIOException, E {
N.checkArgument(offset >= 0 && count >= 0, "'offset'=%s and 'count'=%s can't be negative", offset, count);
final BufferedReader br = csvReader instanceof BufferedReader ? (BufferedReader) csvReader : Objectory.createBufferedReader(csvReader);
final EntityInfo entityInfo = ParserUtil.getEntityInfo(entityClass);
try {
List<String> tmp = new ArrayList<>();
String line = br.readLine();
jsonParser.readString(tmp, line);
final String[] titles = tmp.toArray(new String[tmp.size()]);
final int columnCount = titles.length;
final Type<?>[] columnTypes = new Type<?>[columnCount];
final List<String> columnNameList = new ArrayList<>(selectColumnNames == null ? columnCount : selectColumnNames.size());
final List<List<Object>> columnList = new ArrayList<>(selectColumnNames == null ? columnCount : selectColumnNames.size());
final Set<String> selectPropNameSet = selectColumnNames == null ? null : new HashSet<>(selectColumnNames);
for (int i = 0; i < columnCount; i++) {
if (selectPropNameSet == null || selectPropNameSet.remove(titles[i])) {
PropInfo propInfo = entityInfo.getPropInfo(titles[i]);
if (propInfo == null && selectPropNameSet != null) {
throw new AbacusException(titles[i] + " is not defined in entity class: " + ClassUtil.getCanonicalClassName(entityClass));
}
if (propInfo != null) {
columnTypes[i] = propInfo.type;
columnNameList.add(titles[i]);
columnList.add(new ArrayList<>());
}
}
}
if (selectPropNameSet != null && selectPropNameSet.size() > 0) {
throw new AbacusException(selectColumnNames + " are not included in titles: " + N.toString(titles));
}
final String[] strs = new String[titles.length];
while (offset-- > 0 && br.readLine() != null) {
}
while (count > 0 && (line = br.readLine()) != null) {
jsonParser.readString(strs, line);
if (filter != null && filter.test(strs) == false) {
continue;
}
for (int i = 0, columnIndex = 0; i < columnCount; i++) {
if (columnTypes[i] != null) {
columnList.get(columnIndex++).add(columnTypes[i].valueOf(strs[i]));
}
}
count--;
}
return new RowDataSet(columnNameList, columnList);
} catch (IOException e) {
throw new UncheckedIOException(e);
} finally {
if (br != csvReader) {
Objectory.recycle(br);
}
}
} } | public class class_name {
public static <E extends Exception> DataSet loadCSV(final Class<?> entityClass, final Reader csvReader, final Collection<String> selectColumnNames,
long offset, long count, final Try.Predicate<String[], E> filter) throws UncheckedIOException, E {
N.checkArgument(offset >= 0 && count >= 0, "'offset'=%s and 'count'=%s can't be negative", offset, count);
final BufferedReader br = csvReader instanceof BufferedReader ? (BufferedReader) csvReader : Objectory.createBufferedReader(csvReader);
final EntityInfo entityInfo = ParserUtil.getEntityInfo(entityClass);
try {
List<String> tmp = new ArrayList<>();
String line = br.readLine();
jsonParser.readString(tmp, line);
final String[] titles = tmp.toArray(new String[tmp.size()]);
final int columnCount = titles.length;
final Type<?>[] columnTypes = new Type<?>[columnCount];
final List<String> columnNameList = new ArrayList<>(selectColumnNames == null ? columnCount : selectColumnNames.size());
final List<List<Object>> columnList = new ArrayList<>(selectColumnNames == null ? columnCount : selectColumnNames.size());
final Set<String> selectPropNameSet = selectColumnNames == null ? null : new HashSet<>(selectColumnNames);
for (int i = 0; i < columnCount; i++) {
if (selectPropNameSet == null || selectPropNameSet.remove(titles[i])) {
PropInfo propInfo = entityInfo.getPropInfo(titles[i]);
if (propInfo == null && selectPropNameSet != null) {
throw new AbacusException(titles[i] + " is not defined in entity class: " + ClassUtil.getCanonicalClassName(entityClass));
}
if (propInfo != null) {
columnTypes[i] = propInfo.type;
// depends on control dependency: [if], data = [none]
columnNameList.add(titles[i]);
// depends on control dependency: [if], data = [none]
columnList.add(new ArrayList<>());
// depends on control dependency: [if], data = [none]
}
}
}
if (selectPropNameSet != null && selectPropNameSet.size() > 0) {
throw new AbacusException(selectColumnNames + " are not included in titles: " + N.toString(titles));
}
final String[] strs = new String[titles.length];
while (offset-- > 0 && br.readLine() != null) {
}
while (count > 0 && (line = br.readLine()) != null) {
jsonParser.readString(strs, line);
// depends on control dependency: [while], data = [none]
if (filter != null && filter.test(strs) == false) {
continue;
}
for (int i = 0, columnIndex = 0; i < columnCount; i++) {
if (columnTypes[i] != null) {
columnList.get(columnIndex++).add(columnTypes[i].valueOf(strs[i]));
// depends on control dependency: [if], data = [(columnTypes[i]]
}
}
count--;
// depends on control dependency: [while], data = [none]
}
return new RowDataSet(columnNameList, columnList);
} catch (IOException e) {
throw new UncheckedIOException(e);
} finally {
if (br != csvReader) {
Objectory.recycle(br);
// depends on control dependency: [if], data = [(br]
}
}
} } |
public class class_name {
public boolean table() {
boolean isTable = false;
try {
WebElement webElement = element.getWebElement();
if ("table".equalsIgnoreCase(webElement.getTagName())) {
isTable = true;
}
} catch (NoSuchElementException e) {
log.info(e);
}
return isTable;
} } | public class class_name {
public boolean table() {
boolean isTable = false;
try {
WebElement webElement = element.getWebElement();
if ("table".equalsIgnoreCase(webElement.getTagName())) {
isTable = true; // depends on control dependency: [if], data = [none]
}
} catch (NoSuchElementException e) {
log.info(e);
} // depends on control dependency: [catch], data = [none]
return isTable;
} } |
public class class_name {
public static float entropy(float[] c) {
float e = 0.0f;
for(int i=0;i<c.length;i++){
if(c[i]!=0.0&&c[i]!=1){
e -= c[i]*Math.log(c[i]);
}
}
return e;
} } | public class class_name {
public static float entropy(float[] c) {
float e = 0.0f;
for(int i=0;i<c.length;i++){
if(c[i]!=0.0&&c[i]!=1){
e -= c[i]*Math.log(c[i]);
// depends on control dependency: [if], data = [(c[i]]
}
}
return e;
} } |
public class class_name {
public Policy addBucketIamMember(String bucketName, Role role, Identity identity) {
// [START add_bucket_iam_member]
// Initialize a Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();
// Get IAM Policy for a bucket
Policy policy = storage.getIamPolicy(bucketName);
// Add identity to Bucket-level IAM role
Policy updatedPolicy =
storage.setIamPolicy(bucketName, policy.toBuilder().addIdentity(role, identity).build());
if (updatedPolicy.getBindings().get(role).contains(identity)) {
System.out.printf("Added %s with role %s to %s\n", identity, role, bucketName);
}
// [END add_bucket_iam_member]
return updatedPolicy;
} } | public class class_name {
public Policy addBucketIamMember(String bucketName, Role role, Identity identity) {
// [START add_bucket_iam_member]
// Initialize a Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();
// Get IAM Policy for a bucket
Policy policy = storage.getIamPolicy(bucketName);
// Add identity to Bucket-level IAM role
Policy updatedPolicy =
storage.setIamPolicy(bucketName, policy.toBuilder().addIdentity(role, identity).build());
if (updatedPolicy.getBindings().get(role).contains(identity)) {
System.out.printf("Added %s with role %s to %s\n", identity, role, bucketName); // depends on control dependency: [if], data = [none]
}
// [END add_bucket_iam_member]
return updatedPolicy;
} } |
public class class_name {
public List<CmsResource> getResults(CmsObject cms, String collectorName, String parameter) throws CmsException {
synchronized (this) {
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_COLLECTOR_GET_RESULTS_START_0));
}
if (parameter == null) {
parameter = m_collectorParameter;
}
List<CmsResource> resources = new ArrayList<CmsResource>();
if (getWp().getList() != null) {
Iterator<CmsListItem> itItems = getListItems(parameter).iterator();
while (itItems.hasNext()) {
CmsListItem item = itItems.next();
resources.add(getResource(cms, item));
}
} else {
Map<String, String> params = CmsStringUtil.splitAsMap(
parameter,
I_CmsListResourceCollector.SEP_PARAM,
I_CmsListResourceCollector.SEP_KEYVAL);
resources = getInternalResources(cms, params);
}
if (LOG.isDebugEnabled()) {
LOG.debug(
Messages.get().getBundle().key(
Messages.LOG_COLLECTOR_GET_RESULTS_END_1,
new Integer(resources.size())));
}
return resources;
}
} } | public class class_name {
public List<CmsResource> getResults(CmsObject cms, String collectorName, String parameter) throws CmsException {
synchronized (this) {
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_COLLECTOR_GET_RESULTS_START_0)); // depends on control dependency: [if], data = [none]
}
if (parameter == null) {
parameter = m_collectorParameter; // depends on control dependency: [if], data = [none]
}
List<CmsResource> resources = new ArrayList<CmsResource>();
if (getWp().getList() != null) {
Iterator<CmsListItem> itItems = getListItems(parameter).iterator();
while (itItems.hasNext()) {
CmsListItem item = itItems.next();
resources.add(getResource(cms, item)); // depends on control dependency: [while], data = [none]
}
} else {
Map<String, String> params = CmsStringUtil.splitAsMap(
parameter,
I_CmsListResourceCollector.SEP_PARAM,
I_CmsListResourceCollector.SEP_KEYVAL);
resources = getInternalResources(cms, params); // depends on control dependency: [if], data = [none]
}
if (LOG.isDebugEnabled()) {
LOG.debug(
Messages.get().getBundle().key(
Messages.LOG_COLLECTOR_GET_RESULTS_END_1,
new Integer(resources.size()))); // depends on control dependency: [if], data = [none]
}
return resources;
}
} } |
public class class_name {
private void captureHierarchy(@Nullable View view, boolean start) {
if (view == null) {
return;
}
int id = view.getId();
if (mTargetIdExcludes != null && mTargetIdExcludes.contains(id)) {
return;
}
if (mTargetExcludes != null && mTargetExcludes.contains(view)) {
return;
}
if (mTargetTypeExcludes != null) {
int numTypes = mTargetTypeExcludes.size();
for (int i = 0; i < numTypes; ++i) {
if (mTargetTypeExcludes.get(i).isInstance(view)) {
return;
}
}
}
if (view.getParent() instanceof ViewGroup) {
TransitionValues values = new TransitionValues(view);
if (start) {
captureStartValues(values);
} else {
captureEndValues(values);
}
values.targetedTransitions.add(this);
capturePropagationValues(values);
if (start) {
addViewValues(mStartValues, view, values);
} else {
addViewValues(mEndValues, view, values);
}
}
if (view instanceof ViewGroup) {
// Don't traverse child hierarchy if there are any child-excludes on this view
if (mTargetIdChildExcludes != null && mTargetIdChildExcludes.contains(id)) {
return;
}
if (mTargetChildExcludes != null && mTargetChildExcludes.contains(view)) {
return;
}
if (mTargetTypeChildExcludes != null) {
int numTypes = mTargetTypeChildExcludes.size();
for (int i = 0; i < numTypes; ++i) {
if (mTargetTypeChildExcludes.get(i).isInstance(view)) {
return;
}
}
}
ViewGroup parent = (ViewGroup) view;
for (int i = 0; i < parent.getChildCount(); ++i) {
captureHierarchy(parent.getChildAt(i), start);
}
}
} } | public class class_name {
private void captureHierarchy(@Nullable View view, boolean start) {
if (view == null) {
return; // depends on control dependency: [if], data = [none]
}
int id = view.getId();
if (mTargetIdExcludes != null && mTargetIdExcludes.contains(id)) {
return; // depends on control dependency: [if], data = [none]
}
if (mTargetExcludes != null && mTargetExcludes.contains(view)) {
return; // depends on control dependency: [if], data = [none]
}
if (mTargetTypeExcludes != null) {
int numTypes = mTargetTypeExcludes.size();
for (int i = 0; i < numTypes; ++i) {
if (mTargetTypeExcludes.get(i).isInstance(view)) {
return; // depends on control dependency: [if], data = [none]
}
}
}
if (view.getParent() instanceof ViewGroup) {
TransitionValues values = new TransitionValues(view);
if (start) {
captureStartValues(values); // depends on control dependency: [if], data = [none]
} else {
captureEndValues(values); // depends on control dependency: [if], data = [none]
}
values.targetedTransitions.add(this); // depends on control dependency: [if], data = [none]
capturePropagationValues(values); // depends on control dependency: [if], data = [none]
if (start) {
addViewValues(mStartValues, view, values); // depends on control dependency: [if], data = [none]
} else {
addViewValues(mEndValues, view, values); // depends on control dependency: [if], data = [none]
}
}
if (view instanceof ViewGroup) {
// Don't traverse child hierarchy if there are any child-excludes on this view
if (mTargetIdChildExcludes != null && mTargetIdChildExcludes.contains(id)) {
return; // depends on control dependency: [if], data = [none]
}
if (mTargetChildExcludes != null && mTargetChildExcludes.contains(view)) {
return; // depends on control dependency: [if], data = [none]
}
if (mTargetTypeChildExcludes != null) {
int numTypes = mTargetTypeChildExcludes.size();
for (int i = 0; i < numTypes; ++i) {
if (mTargetTypeChildExcludes.get(i).isInstance(view)) {
return; // depends on control dependency: [if], data = [none]
}
}
}
ViewGroup parent = (ViewGroup) view;
for (int i = 0; i < parent.getChildCount(); ++i) {
captureHierarchy(parent.getChildAt(i), start); // depends on control dependency: [for], data = [i]
}
}
} } |
public class class_name {
@Override
public Citation convert(BELCitation bc) {
if (bc == null) {
return null;
}
Citation c = CommonModelFactory.getInstance().createCitation(
bc.getName());
if (bc.getPublicationDate() != null) {
Calendar date = Calendar.getInstance();
date.setTime(bc.getPublicationDate());
c.setDate(date);
}
c.setAuthors(bc.getAuthors());
c.setComment(bc.getComment());
c.setReference(bc.getReference());
c.setType(CitationType.fromString(bc.getType()));
return c;
} } | public class class_name {
@Override
public Citation convert(BELCitation bc) {
if (bc == null) {
return null; // depends on control dependency: [if], data = [none]
}
Citation c = CommonModelFactory.getInstance().createCitation(
bc.getName());
if (bc.getPublicationDate() != null) {
Calendar date = Calendar.getInstance();
date.setTime(bc.getPublicationDate()); // depends on control dependency: [if], data = [(bc.getPublicationDate()]
c.setDate(date); // depends on control dependency: [if], data = [none]
}
c.setAuthors(bc.getAuthors());
c.setComment(bc.getComment());
c.setReference(bc.getReference());
c.setType(CitationType.fromString(bc.getType()));
return c;
} } |
public class class_name {
boolean cleanupLocalisations() throws SIResourceException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "cleanupLocalisations");
// true if all localisations have been cleaned up successfully
boolean allCleanedUp = true;
// True if we determine calling reallocation is appropriate
boolean reallocationCanBeCalled = false;
//Check the destination has not already been deleted first
if (!isDeleted())
{
synchronized (this) //Stop cleanup happening while the destination is being altered
{
//synchronizes with updateLocalisationSet
//If the entire destination is to be deleted
//then all the localisations are to be deleted.
// 448943 Remove a check for !isReconciled - We dont need this
if (isToBeDeleted())
{
addAllLocalisationsForCleanUp();
}
allCleanedUp = _protoRealization.cleanupPremediatedItemStreams();
if (!isPubSub())
{
//If the entire destination is being deleted, clean up the remote get
//infrastructure
if (isToBeDeleted())
{
boolean remoteGetCleanup = _ptoPRealization.cleanupLocalisations();
if (allCleanedUp)
allCleanedUp = remoteGetCleanup;
}
else
{
// PK57432 We are not deleting the destination. Just perform
// any other localisation cleanup
reallocationCanBeCalled = true;
}
}
else
{
// For pub/sub, we'll want to remove any infrastructure associated with
// durable subscriptions since these are implemented as queue-like localizations.
if (isToBeDeleted())
{
boolean pubSubCleanedUp = _pubSubRealization.cleanupLocalisations();
if (allCleanedUp)
allCleanedUp = pubSubCleanedUp;
}
else
{
// We are not deleting the destination. Just perform
// any other localisation cleanup
reallocationCanBeCalled = true;
}
}
}
}
// PK57432 We must not hold any locks when we reallocate.
if (reallocationCanBeCalled)
{
boolean syncReallocRequiredCheck;
synchronized (this) {
syncReallocRequiredCheck = _isToBeReallocated;
_isToBeReallocated = false;
}
if (syncReallocRequiredCheck)
reallocateTransmissionStreams(null);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "cleanupLocalisations", Boolean.valueOf(allCleanedUp));
return allCleanedUp;
} } | public class class_name {
boolean cleanupLocalisations() throws SIResourceException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "cleanupLocalisations");
// true if all localisations have been cleaned up successfully
boolean allCleanedUp = true;
// True if we determine calling reallocation is appropriate
boolean reallocationCanBeCalled = false;
//Check the destination has not already been deleted first
if (!isDeleted())
{
synchronized (this) //Stop cleanup happening while the destination is being altered
{
//synchronizes with updateLocalisationSet
//If the entire destination is to be deleted
//then all the localisations are to be deleted.
// 448943 Remove a check for !isReconciled - We dont need this
if (isToBeDeleted())
{
addAllLocalisationsForCleanUp(); // depends on control dependency: [if], data = [none]
}
allCleanedUp = _protoRealization.cleanupPremediatedItemStreams();
if (!isPubSub())
{
//If the entire destination is being deleted, clean up the remote get
//infrastructure
if (isToBeDeleted())
{
boolean remoteGetCleanup = _ptoPRealization.cleanupLocalisations();
if (allCleanedUp)
allCleanedUp = remoteGetCleanup;
}
else
{
// PK57432 We are not deleting the destination. Just perform
// any other localisation cleanup
reallocationCanBeCalled = true; // depends on control dependency: [if], data = [none]
}
}
else
{
// For pub/sub, we'll want to remove any infrastructure associated with
// durable subscriptions since these are implemented as queue-like localizations.
if (isToBeDeleted())
{
boolean pubSubCleanedUp = _pubSubRealization.cleanupLocalisations();
if (allCleanedUp)
allCleanedUp = pubSubCleanedUp;
}
else
{
// We are not deleting the destination. Just perform
// any other localisation cleanup
reallocationCanBeCalled = true; // depends on control dependency: [if], data = [none]
}
}
}
}
// PK57432 We must not hold any locks when we reallocate.
if (reallocationCanBeCalled)
{
boolean syncReallocRequiredCheck;
synchronized (this) {
syncReallocRequiredCheck = _isToBeReallocated;
_isToBeReallocated = false;
}
if (syncReallocRequiredCheck)
reallocateTransmissionStreams(null);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "cleanupLocalisations", Boolean.valueOf(allCleanedUp));
return allCleanedUp;
} } |
public class class_name {
protected void updateSelection (int selidx)
{
// do nothing if this element is already selected
if (selidx == _selectedIndex) {
return;
}
// unhighlight the old component
if (_selectedIndex != -1) {
JLabel but = (JLabel)getComponent(_selectedIndex);
but.setBorder(DESELECTED_BORDER);
}
// save the new selection
_selectedIndex = selidx;
// if the selection is valid, highlight the new component
if (_selectedIndex != -1) {
JLabel but = (JLabel)getComponent(_selectedIndex);
but.setBorder(SELECTED_BORDER);
}
// fire an action performed to let listeners know about our
// changed selection
fireActionPerformed();
repaint();
} } | public class class_name {
protected void updateSelection (int selidx)
{
// do nothing if this element is already selected
if (selidx == _selectedIndex) {
return; // depends on control dependency: [if], data = [none]
}
// unhighlight the old component
if (_selectedIndex != -1) {
JLabel but = (JLabel)getComponent(_selectedIndex);
but.setBorder(DESELECTED_BORDER); // depends on control dependency: [if], data = [none]
}
// save the new selection
_selectedIndex = selidx;
// if the selection is valid, highlight the new component
if (_selectedIndex != -1) {
JLabel but = (JLabel)getComponent(_selectedIndex);
but.setBorder(SELECTED_BORDER); // depends on control dependency: [if], data = [none]
}
// fire an action performed to let listeners know about our
// changed selection
fireActionPerformed();
repaint();
} } |
public class class_name {
@Override
public final void setPriceCategory(final PriceCategory pPriceCategory) {
this.priceCategory = pPriceCategory;
if (this.itsId == null) {
this.itsId = new SeGoodsPriceId();
}
this.itsId.setPriceCategory(this.priceCategory);
} } | public class class_name {
@Override
public final void setPriceCategory(final PriceCategory pPriceCategory) {
this.priceCategory = pPriceCategory;
if (this.itsId == null) {
this.itsId = new SeGoodsPriceId(); // depends on control dependency: [if], data = [none]
}
this.itsId.setPriceCategory(this.priceCategory);
} } |
public class class_name {
private static DateTime parseDate(String dateStr, DateTime defaultDate, boolean floor) {
if ("now".equals(dateStr)) { //$NON-NLS-1$
return new DateTime();
}
if (dateStr.length() == 10) {
DateTime parsed = ISODateTimeFormat.date().withZone(DateTimeZone.UTC).parseDateTime(dateStr);
// If what we want is the floor, then just return it. But if we want the
// ceiling of the date, then we need to set the right params.
if (!floor) {
parsed = parsed.plusDays(1).minusMillis(1);
}
return parsed;
}
if (dateStr.length() == 20) {
return ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC).parseDateTime(dateStr);
}
if (dateStr.length() == 24) {
return ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC).parseDateTime(dateStr);
}
return defaultDate;
} } | public class class_name {
private static DateTime parseDate(String dateStr, DateTime defaultDate, boolean floor) {
if ("now".equals(dateStr)) { //$NON-NLS-1$
return new DateTime(); // depends on control dependency: [if], data = [none]
}
if (dateStr.length() == 10) {
DateTime parsed = ISODateTimeFormat.date().withZone(DateTimeZone.UTC).parseDateTime(dateStr);
// If what we want is the floor, then just return it. But if we want the
// ceiling of the date, then we need to set the right params.
if (!floor) {
parsed = parsed.plusDays(1).minusMillis(1); // depends on control dependency: [if], data = [none]
}
return parsed; // depends on control dependency: [if], data = [none]
}
if (dateStr.length() == 20) {
return ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC).parseDateTime(dateStr); // depends on control dependency: [if], data = [none]
}
if (dateStr.length() == 24) {
return ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC).parseDateTime(dateStr); // depends on control dependency: [if], data = [none]
}
return defaultDate;
} } |
public class class_name {
public static void checkStringListArgument(List<String> str, String variableName) {
if (null == str) {
throw new NullPointerException(ExceptionMessageMap.getMessage("000002")
+ " { variableName=[" + variableName + "] }");
}
if (str.size() == 0) {
throw new IllegalArgumentException(ExceptionMessageMap.getMessage("000002")
+ " { variableName=[" + variableName + "] }");
}
for (int i = 0; i < str.size(); i++) {
checkStringArgument(str.get(i), variableName);
}
} } | public class class_name {
public static void checkStringListArgument(List<String> str, String variableName) {
if (null == str) {
throw new NullPointerException(ExceptionMessageMap.getMessage("000002")
+ " { variableName=[" + variableName + "] }");
}
if (str.size() == 0) {
throw new IllegalArgumentException(ExceptionMessageMap.getMessage("000002")
+ " { variableName=[" + variableName + "] }");
}
for (int i = 0; i < str.size(); i++) {
checkStringArgument(str.get(i), variableName); // depends on control dependency: [for], data = [i]
}
} } |
public class class_name {
public void deleteInstance() {
System.out.println("\nDeleting Instance");
// [START bigtable_delete_instance]
try {
adminClient.deleteInstance(instanceId);
System.out.println("Instance deleted: " + instanceId);
} catch (NotFoundException e) {
System.err.println("Failed to delete non-existent instance: " + e.getMessage());
}
// [END bigtable_delete_instance]
} } | public class class_name {
public void deleteInstance() {
System.out.println("\nDeleting Instance");
// [START bigtable_delete_instance]
try {
adminClient.deleteInstance(instanceId); // depends on control dependency: [try], data = [none]
System.out.println("Instance deleted: " + instanceId); // depends on control dependency: [try], data = [none]
} catch (NotFoundException e) {
System.err.println("Failed to delete non-existent instance: " + e.getMessage());
} // depends on control dependency: [catch], data = [none]
// [END bigtable_delete_instance]
} } |
public class class_name {
@Override
public boolean isAvailable(final Object key, final Class<?> clas) {
this.logger.debug("@isAvailable :".concat(key.toString()).concat(" for class : ".concat(clas.toString())));
final Object Object = getCachableMap(clas).get(key);
if (Object == null) {
this.logger.debug("try to find it on the nullable cache");
this.logger.debug(getCachableMap(JKAbstractCacheManager.NULLABLE_MAP_CLASS).keySet().toString());
return getCachableMap(JKAbstractCacheManager.NULLABLE_MAP_CLASS).containsKey(key);
}
this.logger.debug("key ".concat(key.toString()).concat(Object != null ? " is available in the cache" : "is not svailable"));
return Object != null;
} } | public class class_name {
@Override
public boolean isAvailable(final Object key, final Class<?> clas) {
this.logger.debug("@isAvailable :".concat(key.toString()).concat(" for class : ".concat(clas.toString())));
final Object Object = getCachableMap(clas).get(key);
if (Object == null) {
this.logger.debug("try to find it on the nullable cache");
// depends on control dependency: [if], data = [none]
this.logger.debug(getCachableMap(JKAbstractCacheManager.NULLABLE_MAP_CLASS).keySet().toString());
// depends on control dependency: [if], data = [none]
return getCachableMap(JKAbstractCacheManager.NULLABLE_MAP_CLASS).containsKey(key);
// depends on control dependency: [if], data = [none]
}
this.logger.debug("key ".concat(key.toString()).concat(Object != null ? " is available in the cache" : "is not svailable"));
return Object != null;
} } |
public class class_name {
public void serviceInstall(ServiceComponent serviceComponent) {
// create object pools
for (SbbID sbbID : serviceComponent.getSbbIDs(sleeContainer.getComponentRepository())) {
// create the pool for the given SbbID
sbbPoolManagement.createObjectPool(serviceComponent.getServiceID(), sleeContainer.getComponentRepository().getComponentByID(sbbID),
sleeContainer.getTransactionManager());
}
} } | public class class_name {
public void serviceInstall(ServiceComponent serviceComponent) {
// create object pools
for (SbbID sbbID : serviceComponent.getSbbIDs(sleeContainer.getComponentRepository())) {
// create the pool for the given SbbID
sbbPoolManagement.createObjectPool(serviceComponent.getServiceID(), sleeContainer.getComponentRepository().getComponentByID(sbbID),
sleeContainer.getTransactionManager()); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
public SecurityTokenServiceClient buildClientForRelyingPartyTokenResponses(final SecurityToken securityToken,
final WSFederationRegisteredService service) {
val cxfBus = BusFactory.getDefaultBus();
val sts = new SecurityTokenServiceClient(cxfBus);
sts.setAddressingNamespace(StringUtils.defaultIfBlank(service.getAddressingNamespace(), WSFederationConstants.HTTP_WWW_W3_ORG_2005_08_ADDRESSING));
sts.setWsdlLocation(prepareWsdlLocation(service));
val namespace = StringUtils.defaultIfBlank(service.getNamespace(), WSFederationConstants.HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512);
sts.setServiceQName(new QName(namespace, service.getWsdlService()));
sts.setEndpointQName(new QName(namespace, service.getWsdlEndpoint()));
sts.setEnableAppliesTo(StringUtils.isNotBlank(service.getAppliesTo()));
sts.setOnBehalfOf(securityToken.getToken());
sts.setKeyType(WSFederationConstants.HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER);
sts.setTokenType(StringUtils.defaultIfBlank(service.getTokenType(), WSConstants.WSS_SAML2_TOKEN_TYPE));
if (StringUtils.isNotBlank(service.getPolicyNamespace())) {
sts.setWspNamespace(service.getPolicyNamespace());
}
return sts;
} } | public class class_name {
public SecurityTokenServiceClient buildClientForRelyingPartyTokenResponses(final SecurityToken securityToken,
final WSFederationRegisteredService service) {
val cxfBus = BusFactory.getDefaultBus();
val sts = new SecurityTokenServiceClient(cxfBus);
sts.setAddressingNamespace(StringUtils.defaultIfBlank(service.getAddressingNamespace(), WSFederationConstants.HTTP_WWW_W3_ORG_2005_08_ADDRESSING));
sts.setWsdlLocation(prepareWsdlLocation(service));
val namespace = StringUtils.defaultIfBlank(service.getNamespace(), WSFederationConstants.HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512);
sts.setServiceQName(new QName(namespace, service.getWsdlService()));
sts.setEndpointQName(new QName(namespace, service.getWsdlEndpoint()));
sts.setEnableAppliesTo(StringUtils.isNotBlank(service.getAppliesTo()));
sts.setOnBehalfOf(securityToken.getToken());
sts.setKeyType(WSFederationConstants.HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER);
sts.setTokenType(StringUtils.defaultIfBlank(service.getTokenType(), WSConstants.WSS_SAML2_TOKEN_TYPE));
if (StringUtils.isNotBlank(service.getPolicyNamespace())) {
sts.setWspNamespace(service.getPolicyNamespace()); // depends on control dependency: [if], data = [none]
}
return sts;
} } |
public class class_name {
public static void runExample(
AdManagerServices adManagerServices,
AdManagerSession session,
int activityGroupId,
long advertiserCompanyId)
throws RemoteException {
// Get the ActivityGroupService.
ActivityGroupServiceInterface activityGroupService =
adManagerServices.get(session, ActivityGroupServiceInterface.class);
// Create a statement to only select a single activity group by ID.
StatementBuilder statementBuilder =
new StatementBuilder()
.where("id = :id")
.orderBy("id ASC")
.limit(1)
.withBindVariableValue("id", activityGroupId);
// Get the activity group.
ActivityGroupPage page =
activityGroupService.getActivityGroupsByStatement(statementBuilder.toStatement());
ActivityGroup activityGroup = Iterables.getOnlyElement(Arrays.asList(page.getResults()));
// Update the companies.
activityGroup.setCompanyIds(
Longs.concat(activityGroup.getCompanyIds(), new long[] {advertiserCompanyId}));
// Update the activity group on the server.
ActivityGroup[] activityGroups =
activityGroupService.updateActivityGroups(new ActivityGroup[] {activityGroup});
for (ActivityGroup updatedActivityGroup : activityGroups) {
System.out.printf(
"Activity group with ID %d and name '%s' was updated.%n",
updatedActivityGroup.getId(), updatedActivityGroup.getName());
}
} } | public class class_name {
public static void runExample(
AdManagerServices adManagerServices,
AdManagerSession session,
int activityGroupId,
long advertiserCompanyId)
throws RemoteException {
// Get the ActivityGroupService.
ActivityGroupServiceInterface activityGroupService =
adManagerServices.get(session, ActivityGroupServiceInterface.class);
// Create a statement to only select a single activity group by ID.
StatementBuilder statementBuilder =
new StatementBuilder()
.where("id = :id")
.orderBy("id ASC")
.limit(1)
.withBindVariableValue("id", activityGroupId);
// Get the activity group.
ActivityGroupPage page =
activityGroupService.getActivityGroupsByStatement(statementBuilder.toStatement());
ActivityGroup activityGroup = Iterables.getOnlyElement(Arrays.asList(page.getResults()));
// Update the companies.
activityGroup.setCompanyIds(
Longs.concat(activityGroup.getCompanyIds(), new long[] {advertiserCompanyId}));
// Update the activity group on the server.
ActivityGroup[] activityGroups =
activityGroupService.updateActivityGroups(new ActivityGroup[] {activityGroup});
for (ActivityGroup updatedActivityGroup : activityGroups) {
System.out.printf(
"Activity group with ID %d and name '%s' was updated.%n",
updatedActivityGroup.getId(), updatedActivityGroup.getName()); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
protected void onAfterDeleteFromMemcached( @Nonnull final String sessionId ) {
final long start = System.currentTimeMillis();
final String validityInfoKey = _sessionIdFormat.createValidityInfoKeyName( sessionId );
_storage.delete( validityInfoKey );
if (_storeSecondaryBackup) {
try {
_storage.delete(_sessionIdFormat.createBackupKey(sessionId));
_storage.delete(_sessionIdFormat.createBackupKey(validityInfoKey));
} catch (Exception e) {
_log.info("Could not delete backup data for session " + sessionId + " (not critical, data will be evicted by memcached automatically).", e);
}
}
_stats.registerSince( NON_STICKY_AFTER_DELETE_FROM_MEMCACHED, start );
} } | public class class_name {
protected void onAfterDeleteFromMemcached( @Nonnull final String sessionId ) {
final long start = System.currentTimeMillis();
final String validityInfoKey = _sessionIdFormat.createValidityInfoKeyName( sessionId );
_storage.delete( validityInfoKey );
if (_storeSecondaryBackup) {
try {
_storage.delete(_sessionIdFormat.createBackupKey(sessionId)); // depends on control dependency: [try], data = [none]
_storage.delete(_sessionIdFormat.createBackupKey(validityInfoKey)); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
_log.info("Could not delete backup data for session " + sessionId + " (not critical, data will be evicted by memcached automatically).", e);
} // depends on control dependency: [catch], data = [none]
}
_stats.registerSince( NON_STICKY_AFTER_DELETE_FROM_MEMCACHED, start );
} } |
public class class_name {
public static Fraction getFraction(int numerator, int denominator) {
if (denominator == 0) {
throw new ArithmeticException("The denominator must not be zero");
}
if (denominator < 0) {
if (numerator == Integer.MIN_VALUE || denominator == Integer.MIN_VALUE) {
throw new ArithmeticException("overflow: can't negate");
}
numerator = -numerator;
denominator = -denominator;
}
return new Fraction(numerator, denominator);
} } | public class class_name {
public static Fraction getFraction(int numerator, int denominator) {
if (denominator == 0) {
throw new ArithmeticException("The denominator must not be zero");
}
if (denominator < 0) {
if (numerator == Integer.MIN_VALUE || denominator == Integer.MIN_VALUE) {
throw new ArithmeticException("overflow: can't negate");
}
numerator = -numerator; // depends on control dependency: [if], data = [none]
denominator = -denominator; // depends on control dependency: [if], data = [none]
}
return new Fraction(numerator, denominator);
} } |
public class class_name {
public final Set<T> values()
{
Set<T> convertedValues = new HashSet<>();
for (BinaryValue baw : values)
{
convertedValues.add(convert(baw));
}
return Collections.unmodifiableSet(convertedValues);
} } | public class class_name {
public final Set<T> values()
{
Set<T> convertedValues = new HashSet<>();
for (BinaryValue baw : values)
{
convertedValues.add(convert(baw)); // depends on control dependency: [for], data = [baw]
}
return Collections.unmodifiableSet(convertedValues);
} } |
public class class_name {
public CmsRelationFilter filterWeak() {
CmsRelationFilter filter = (CmsRelationFilter)clone();
if (filter.m_types.isEmpty()) {
filter.m_types.addAll(CmsRelationType.getAllWeak());
} else {
filter.m_types = new HashSet<CmsRelationType>(CmsRelationType.filterWeak(filter.m_types));
}
return filter;
} } | public class class_name {
public CmsRelationFilter filterWeak() {
CmsRelationFilter filter = (CmsRelationFilter)clone();
if (filter.m_types.isEmpty()) {
filter.m_types.addAll(CmsRelationType.getAllWeak()); // depends on control dependency: [if], data = [none]
} else {
filter.m_types = new HashSet<CmsRelationType>(CmsRelationType.filterWeak(filter.m_types)); // depends on control dependency: [if], data = [none]
}
return filter;
} } |
public class class_name {
@Override
public AbstractMessage nextElement()
{
if (endOfQueueReached)
throw new NoSuchElementException();
try
{
checkNotClosed();
AbstractMessage msg = fetchNext();
if (msg != null)
{
nextMessage = null; // Consume fetched message
// Make sure the message is fully deserialized and marked as read-only
msg.ensureDeserializationLevel(MessageSerializationLevel.FULL);
msg.markAsReadOnly();
return msg;
}
throw new NoSuchElementException();
}
catch (NoSuchElementException e)
{
throw e;
}
catch (JMSException e)
{
throw new IllegalStateException(e.toString());
}
} } | public class class_name {
@Override
public AbstractMessage nextElement()
{
if (endOfQueueReached)
throw new NoSuchElementException();
try
{
checkNotClosed(); // depends on control dependency: [try], data = [none]
AbstractMessage msg = fetchNext();
if (msg != null)
{
nextMessage = null; // Consume fetched message // depends on control dependency: [if], data = [none]
// Make sure the message is fully deserialized and marked as read-only
msg.ensureDeserializationLevel(MessageSerializationLevel.FULL); // depends on control dependency: [if], data = [none]
msg.markAsReadOnly(); // depends on control dependency: [if], data = [none]
return msg; // depends on control dependency: [if], data = [none]
}
throw new NoSuchElementException();
}
catch (NoSuchElementException e)
{
throw e;
} // depends on control dependency: [catch], data = [none]
catch (JMSException e)
{
throw new IllegalStateException(e.toString());
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@SuppressWarnings("unchecked")
private static void checkTypeParameter(List<String> errorMessages, Class type) {
// Only check classes and interfaces that extend Storable.
if (type != null && Storable.class.isAssignableFrom(type)) {
if (Storable.class == type) {
return;
}
} else {
return;
}
// Check all superclasses and interfaces.
checkTypeParameter(errorMessages, type.getSuperclass());
for (Class c : type.getInterfaces()) {
checkTypeParameter(errorMessages, c);
}
for (Type t : type.getGenericInterfaces()) {
if (t instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType)t;
if (pt.getRawType() == Storable.class) {
// Found exactly which parameter is passed directly to
// Storable. Make sure that it is in the proper bounds.
Type arg = pt.getActualTypeArguments()[0];
Class param;
if (arg instanceof ParameterizedType) {
Type raw = ((ParameterizedType)arg).getRawType();
if (raw instanceof Class) {
param = (Class)raw;
} else {
continue;
}
} else if (arg instanceof Class) {
param = (Class)arg;
} else if (arg instanceof TypeVariable) {
// TODO
continue;
} else {
continue;
}
if (Storable.class.isAssignableFrom(param)) {
if (!param.isAssignableFrom(type)) {
errorMessages.add
("Type parameter passed from " + type +
" to Storable must be a " + type.getName() + ": " + param);
return;
}
} else {
errorMessages.add
("Type parameter passed from " + type +
" to Storable must be a Storable: " + param);
return;
}
}
}
}
} } | public class class_name {
@SuppressWarnings("unchecked")
private static void checkTypeParameter(List<String> errorMessages, Class type) {
// Only check classes and interfaces that extend Storable.
if (type != null && Storable.class.isAssignableFrom(type)) {
if (Storable.class == type) {
return;
// depends on control dependency: [if], data = [none]
}
} else {
return;
// depends on control dependency: [if], data = [none]
}
// Check all superclasses and interfaces.
checkTypeParameter(errorMessages, type.getSuperclass());
for (Class c : type.getInterfaces()) {
checkTypeParameter(errorMessages, c);
// depends on control dependency: [for], data = [c]
}
for (Type t : type.getGenericInterfaces()) {
if (t instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType)t;
if (pt.getRawType() == Storable.class) {
// Found exactly which parameter is passed directly to
// Storable. Make sure that it is in the proper bounds.
Type arg = pt.getActualTypeArguments()[0];
Class param;
if (arg instanceof ParameterizedType) {
Type raw = ((ParameterizedType)arg).getRawType();
if (raw instanceof Class) {
param = (Class)raw;
// depends on control dependency: [if], data = [none]
} else {
continue;
}
} else if (arg instanceof Class) {
param = (Class)arg;
// depends on control dependency: [if], data = [none]
} else if (arg instanceof TypeVariable) {
// TODO
continue;
} else {
continue;
}
if (Storable.class.isAssignableFrom(param)) {
if (!param.isAssignableFrom(type)) {
errorMessages.add
("Type parameter passed from " + type +
" to Storable must be a " + type.getName() + ": " + param);
// depends on control dependency: [if], data = [none]
return;
// depends on control dependency: [if], data = [none]
}
} else {
errorMessages.add
("Type parameter passed from " + type +
" to Storable must be a Storable: " + param);
// depends on control dependency: [if], data = [none]
return;
// depends on control dependency: [if], data = [none]
}
}
}
}
} } |
public class class_name {
protected int removeHeapNode(int i)
{
int val = heap[i];
int rightMost = --size;
heap[i] = heap[rightMost];
heap[rightMost] = 0;
if(fastValueRemove == Mode.HASH)
{
valueIndexMap.remove(val);
if(size != 0)
valueIndexMap.put(heap[i], i);
}
else if(fastValueRemove == Mode.BOUNDED)
{
valueIndexStore[val] = -1;
}
heapDown(i);
return val;
} } | public class class_name {
protected int removeHeapNode(int i)
{
int val = heap[i];
int rightMost = --size;
heap[i] = heap[rightMost];
heap[rightMost] = 0;
if(fastValueRemove == Mode.HASH)
{
valueIndexMap.remove(val); // depends on control dependency: [if], data = [none]
if(size != 0)
valueIndexMap.put(heap[i], i);
}
else if(fastValueRemove == Mode.BOUNDED)
{
valueIndexStore[val] = -1; // depends on control dependency: [if], data = [none]
}
heapDown(i);
return val;
} } |
public class class_name {
public void setResourceAwsIamAccessKeyUserName(java.util.Collection<StringFilter> resourceAwsIamAccessKeyUserName) {
if (resourceAwsIamAccessKeyUserName == null) {
this.resourceAwsIamAccessKeyUserName = null;
return;
}
this.resourceAwsIamAccessKeyUserName = new java.util.ArrayList<StringFilter>(resourceAwsIamAccessKeyUserName);
} } | public class class_name {
public void setResourceAwsIamAccessKeyUserName(java.util.Collection<StringFilter> resourceAwsIamAccessKeyUserName) {
if (resourceAwsIamAccessKeyUserName == null) {
this.resourceAwsIamAccessKeyUserName = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.resourceAwsIamAccessKeyUserName = new java.util.ArrayList<StringFilter>(resourceAwsIamAccessKeyUserName);
} } |
public class class_name {
Object[] readNext(List<String> columnNames) throws IOException {
if (currentRowInFileIndex++ >= sasFileProperties.getRowCount() || eof) {
return null;
}
int bitOffset = sasFileProperties.isU64() ? PAGE_BIT_OFFSET_X64 : PAGE_BIT_OFFSET_X86;
switch (currentPageType) {
case PAGE_META_TYPE_1:
case PAGE_META_TYPE_2:
SubheaderPointer currentSubheaderPointer =
currentPageDataSubheaderPointers.get(currentRowOnPageIndex++);
((ProcessingDataSubheader) subheaderIndexToClass.get(SubheaderIndexes.DATA_SUBHEADER_INDEX))
.processSubheader(currentSubheaderPointer.offset, currentSubheaderPointer.length, columnNames);
if (currentRowOnPageIndex == currentPageDataSubheaderPointers.size()) {
readNextPage();
currentRowOnPageIndex = 0;
}
break;
case PAGE_MIX_TYPE:
int subheaderPointerLength = sasFileProperties.isU64() ? SUBHEADER_POINTER_LENGTH_X64
: SUBHEADER_POINTER_LENGTH_X86;
int alignCorrection = (bitOffset + SUBHEADER_POINTERS_OFFSET + currentPageSubheadersCount
* subheaderPointerLength) % BITS_IN_BYTE;
currentRow = processByteArrayWithData(bitOffset + SUBHEADER_POINTERS_OFFSET + alignCorrection
+ currentPageSubheadersCount * subheaderPointerLength + currentRowOnPageIndex++
* sasFileProperties.getRowLength(), sasFileProperties.getRowLength(), columnNames);
if (currentRowOnPageIndex == Math.min(sasFileProperties.getRowCount(),
sasFileProperties.getMixPageRowCount())) {
readNextPage();
currentRowOnPageIndex = 0;
}
break;
case PAGE_DATA_TYPE:
currentRow = processByteArrayWithData(bitOffset + SUBHEADER_POINTERS_OFFSET + currentRowOnPageIndex++
* sasFileProperties.getRowLength(), sasFileProperties.getRowLength(), columnNames);
if (currentRowOnPageIndex == currentPageBlockCount) {
readNextPage();
currentRowOnPageIndex = 0;
}
break;
default:
break;
}
return Arrays.copyOf(currentRow, currentRow.length);
} } | public class class_name {
Object[] readNext(List<String> columnNames) throws IOException {
if (currentRowInFileIndex++ >= sasFileProperties.getRowCount() || eof) {
return null;
}
int bitOffset = sasFileProperties.isU64() ? PAGE_BIT_OFFSET_X64 : PAGE_BIT_OFFSET_X86;
switch (currentPageType) {
case PAGE_META_TYPE_1:
case PAGE_META_TYPE_2:
SubheaderPointer currentSubheaderPointer =
currentPageDataSubheaderPointers.get(currentRowOnPageIndex++);
((ProcessingDataSubheader) subheaderIndexToClass.get(SubheaderIndexes.DATA_SUBHEADER_INDEX))
.processSubheader(currentSubheaderPointer.offset, currentSubheaderPointer.length, columnNames);
if (currentRowOnPageIndex == currentPageDataSubheaderPointers.size()) {
readNextPage(); // depends on control dependency: [if], data = [none]
currentRowOnPageIndex = 0; // depends on control dependency: [if], data = [none]
}
break;
case PAGE_MIX_TYPE:
int subheaderPointerLength = sasFileProperties.isU64() ? SUBHEADER_POINTER_LENGTH_X64
: SUBHEADER_POINTER_LENGTH_X86;
int alignCorrection = (bitOffset + SUBHEADER_POINTERS_OFFSET + currentPageSubheadersCount
* subheaderPointerLength) % BITS_IN_BYTE;
currentRow = processByteArrayWithData(bitOffset + SUBHEADER_POINTERS_OFFSET + alignCorrection
+ currentPageSubheadersCount * subheaderPointerLength + currentRowOnPageIndex++
* sasFileProperties.getRowLength(), sasFileProperties.getRowLength(), columnNames);
if (currentRowOnPageIndex == Math.min(sasFileProperties.getRowCount(),
sasFileProperties.getMixPageRowCount())) {
readNextPage(); // depends on control dependency: [if], data = [none]
currentRowOnPageIndex = 0; // depends on control dependency: [if], data = [none]
}
break;
case PAGE_DATA_TYPE:
currentRow = processByteArrayWithData(bitOffset + SUBHEADER_POINTERS_OFFSET + currentRowOnPageIndex++
* sasFileProperties.getRowLength(), sasFileProperties.getRowLength(), columnNames);
if (currentRowOnPageIndex == currentPageBlockCount) {
readNextPage(); // depends on control dependency: [if], data = [none]
currentRowOnPageIndex = 0; // depends on control dependency: [if], data = [none]
}
break;
default:
break;
}
return Arrays.copyOf(currentRow, currentRow.length);
} } |
public class class_name {
private Map<String, Map<String, Set<String>>> getDependencies(Context context,
Collection<JavaFileObject> explicitJFOs,
boolean cp) {
Map<String, Map<String, Set<String>>> result = new HashMap<>();
for (CompletionNode cnode : getDependencyNodes(context, explicitJFOs, true)) {
String fqDep = cnode.getClassSymbol().outermostClass().flatname.toString();
String depPkg = Util.pkgNameOfClassName(fqDep);
Map<String, Set<String>> depsForThisClass = result.get(depPkg);
if (depsForThisClass == null) {
result.put(depPkg, depsForThisClass = new HashMap<>());
}
Set<String> fqDeps = depsForThisClass.get(fqDep);
if (fqDeps == null) {
depsForThisClass.put(fqDep, fqDeps = new HashSet<>());
}
for (Node<?,?> depNode : getAllDependencies(cnode)) {
CompletionNode cDepNode = (CompletionNode) depNode;
// Symbol is not regarded to depend on itself.
if (cDepNode == cnode) {
continue;
}
// Skip anonymous classes
if (cDepNode.getClassSymbol().fullname == null) {
continue;
}
if (isSymbolRelevant(cp, cDepNode.getClassSymbol())) {
fqDeps.add(cDepNode.getClassSymbol().outermostClass().flatname.toString());
}
}
// The completion dependency graph is not transitively closed for inheritance relations.
// For sjavac's purposes however, a class depends on it's super super type, so below we
// make sure that we include super types.
for (ClassSymbol cs : allSupertypes(cnode.getClassSymbol())) {
if (isSymbolRelevant(cp, cs)) {
fqDeps.add(cs.outermostClass().flatname.toString());
}
}
}
return result;
} } | public class class_name {
private Map<String, Map<String, Set<String>>> getDependencies(Context context,
Collection<JavaFileObject> explicitJFOs,
boolean cp) {
Map<String, Map<String, Set<String>>> result = new HashMap<>();
for (CompletionNode cnode : getDependencyNodes(context, explicitJFOs, true)) {
String fqDep = cnode.getClassSymbol().outermostClass().flatname.toString();
String depPkg = Util.pkgNameOfClassName(fqDep);
Map<String, Set<String>> depsForThisClass = result.get(depPkg);
if (depsForThisClass == null) {
result.put(depPkg, depsForThisClass = new HashMap<>()); // depends on control dependency: [if], data = [none]
}
Set<String> fqDeps = depsForThisClass.get(fqDep);
if (fqDeps == null) {
depsForThisClass.put(fqDep, fqDeps = new HashSet<>()); // depends on control dependency: [if], data = [none]
}
for (Node<?,?> depNode : getAllDependencies(cnode)) {
CompletionNode cDepNode = (CompletionNode) depNode;
// Symbol is not regarded to depend on itself.
if (cDepNode == cnode) {
continue;
}
// Skip anonymous classes
if (cDepNode.getClassSymbol().fullname == null) {
continue;
}
if (isSymbolRelevant(cp, cDepNode.getClassSymbol())) {
fqDeps.add(cDepNode.getClassSymbol().outermostClass().flatname.toString()); // depends on control dependency: [if], data = [none]
}
}
// The completion dependency graph is not transitively closed for inheritance relations.
// For sjavac's purposes however, a class depends on it's super super type, so below we
// make sure that we include super types.
for (ClassSymbol cs : allSupertypes(cnode.getClassSymbol())) {
if (isSymbolRelevant(cp, cs)) {
fqDeps.add(cs.outermostClass().flatname.toString()); // depends on control dependency: [if], data = [none]
}
}
}
return result;
} } |
public class class_name {
public void updateChannelConfiguration(UpdateChannelConfiguration updateChannelConfiguration, Orderer orderer, byte[]... signers) throws TransactionException, InvalidArgumentException {
checkChannelState();
checkOrderer(orderer);
try {
final long startLastConfigIndex = getLastConfigIndex(orderer);
logger.trace(format("startLastConfigIndex: %d. Channel config wait time is: %d",
startLastConfigIndex, CHANNEL_CONFIG_WAIT_TIME));
sendUpdateChannel(updateChannelConfiguration.getUpdateChannelConfigurationAsBytes(), signers, orderer);
long currentLastConfigIndex = -1;
final long nanoTimeStart = System.nanoTime();
//Try to wait to see the channel got updated but don't fail if we don't see it.
do {
currentLastConfigIndex = getLastConfigIndex(orderer);
if (currentLastConfigIndex == startLastConfigIndex) {
final long duration = TimeUnit.MILLISECONDS.convert(System.nanoTime() - nanoTimeStart, TimeUnit.NANOSECONDS);
if (duration > CHANNEL_CONFIG_WAIT_TIME) {
logger.warn(format("Channel %s did not get updated last config after %d ms, Config wait time: %d ms. startLastConfigIndex: %d, currentLastConfigIndex: %d ",
name, duration, CHANNEL_CONFIG_WAIT_TIME, startLastConfigIndex, currentLastConfigIndex));
//waited long enough ..
currentLastConfigIndex = startLastConfigIndex - 1L; // just bail don't throw exception.
} else {
try {
Thread.sleep(ORDERER_RETRY_WAIT_TIME); //try again sleep
} catch (InterruptedException e) {
TransactionException te = new TransactionException("update channel thread Sleep", e);
logger.warn(te.getMessage(), te);
}
}
}
logger.trace(format("currentLastConfigIndex: %d", currentLastConfigIndex));
} while (currentLastConfigIndex == startLastConfigIndex);
} catch (TransactionException e) {
logger.error(format("Channel %s error: %s", name, e.getMessage()), e);
throw e;
} catch (Exception e) {
String msg = format("Channel %s error: %s", name, e.getMessage());
logger.error(msg, e);
throw new TransactionException(msg, e);
}
} } | public class class_name {
public void updateChannelConfiguration(UpdateChannelConfiguration updateChannelConfiguration, Orderer orderer, byte[]... signers) throws TransactionException, InvalidArgumentException {
checkChannelState();
checkOrderer(orderer);
try {
final long startLastConfigIndex = getLastConfigIndex(orderer);
logger.trace(format("startLastConfigIndex: %d. Channel config wait time is: %d",
startLastConfigIndex, CHANNEL_CONFIG_WAIT_TIME));
sendUpdateChannel(updateChannelConfiguration.getUpdateChannelConfigurationAsBytes(), signers, orderer);
long currentLastConfigIndex = -1;
final long nanoTimeStart = System.nanoTime();
//Try to wait to see the channel got updated but don't fail if we don't see it.
do {
currentLastConfigIndex = getLastConfigIndex(orderer);
if (currentLastConfigIndex == startLastConfigIndex) {
final long duration = TimeUnit.MILLISECONDS.convert(System.nanoTime() - nanoTimeStart, TimeUnit.NANOSECONDS);
if (duration > CHANNEL_CONFIG_WAIT_TIME) {
logger.warn(format("Channel %s did not get updated last config after %d ms, Config wait time: %d ms. startLastConfigIndex: %d, currentLastConfigIndex: %d ",
name, duration, CHANNEL_CONFIG_WAIT_TIME, startLastConfigIndex, currentLastConfigIndex)); // depends on control dependency: [if], data = [none]
//waited long enough ..
currentLastConfigIndex = startLastConfigIndex - 1L; // just bail don't throw exception. // depends on control dependency: [if], data = [none]
} else {
try {
Thread.sleep(ORDERER_RETRY_WAIT_TIME); //try again sleep // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
TransactionException te = new TransactionException("update channel thread Sleep", e);
logger.warn(te.getMessage(), te);
} // depends on control dependency: [catch], data = [none]
}
}
logger.trace(format("currentLastConfigIndex: %d", currentLastConfigIndex));
} while (currentLastConfigIndex == startLastConfigIndex);
} catch (TransactionException e) {
logger.error(format("Channel %s error: %s", name, e.getMessage()), e);
throw e;
} catch (Exception e) {
String msg = format("Channel %s error: %s", name, e.getMessage());
logger.error(msg, e);
throw new TransactionException(msg, e);
}
} } |
public class class_name {
private void setScanCriteria(Scan scan, String columnFamily, List<Map<String, Object>> columnsToOutput,
Filter filter)
{
if (filter != null)
{
scan.setFilter(filter);
}
} } | public class class_name {
private void setScanCriteria(Scan scan, String columnFamily, List<Map<String, Object>> columnsToOutput,
Filter filter)
{
if (filter != null)
{
scan.setFilter(filter);
// depends on control dependency: [if], data = [(filter]
}
} } |
public class class_name {
public static BidiGlobalDir decodeBidiGlobalDirFromPyOptions(String bidiIsRtlFn) {
if (bidiIsRtlFn == null || bidiIsRtlFn.isEmpty()) {
return null;
}
int dotIndex = bidiIsRtlFn.lastIndexOf('.');
Preconditions.checkArgument(
dotIndex > 0 && dotIndex < bidiIsRtlFn.length() - 1,
"If specified a bidiIsRtlFn must include the module path to allow for proper importing.");
// When importing the module, we'll using the constant name to avoid potential conflicts.
String fnName = bidiIsRtlFn.substring(dotIndex + 1) + "()";
return BidiGlobalDir.forIsRtlCodeSnippet(
IS_RTL_MODULE_ALIAS + '.' + fnName, null, SoyBackendKind.PYTHON_SRC);
} } | public class class_name {
public static BidiGlobalDir decodeBidiGlobalDirFromPyOptions(String bidiIsRtlFn) {
if (bidiIsRtlFn == null || bidiIsRtlFn.isEmpty()) {
return null; // depends on control dependency: [if], data = [none]
}
int dotIndex = bidiIsRtlFn.lastIndexOf('.');
Preconditions.checkArgument(
dotIndex > 0 && dotIndex < bidiIsRtlFn.length() - 1,
"If specified a bidiIsRtlFn must include the module path to allow for proper importing.");
// When importing the module, we'll using the constant name to avoid potential conflicts.
String fnName = bidiIsRtlFn.substring(dotIndex + 1) + "()";
return BidiGlobalDir.forIsRtlCodeSnippet(
IS_RTL_MODULE_ALIAS + '.' + fnName, null, SoyBackendKind.PYTHON_SRC);
} } |
public class class_name {
@SuppressWarnings("unchecked")
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
throws AuthenticationException {
String id;
if (AnonymousToken.isAnonymous(token)) {
// Only continue if an anonymous identity has been set
if (_anonymousId != null) {
id = _anonymousId;
} else {
return null;
}
} else {
id = ((ApiKeyAuthenticationToken) token).getPrincipal();
}
return getUncachedAuthenticationInfoForKey(id);
} } | public class class_name {
@SuppressWarnings("unchecked")
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
throws AuthenticationException {
String id;
if (AnonymousToken.isAnonymous(token)) {
// Only continue if an anonymous identity has been set
if (_anonymousId != null) {
id = _anonymousId; // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} else {
id = ((ApiKeyAuthenticationToken) token).getPrincipal();
}
return getUncachedAuthenticationInfoForKey(id);
} } |
public class class_name {
public Observable<ServiceResponse<Page<String>>> listWebAppsByHybridConnectionSinglePageAsync(final String resourceGroupName, final String name, final String namespaceName, final String relayName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (name == null) {
throw new IllegalArgumentException("Parameter name is required and cannot be null.");
}
if (namespaceName == null) {
throw new IllegalArgumentException("Parameter namespaceName is required and cannot be null.");
}
if (relayName == null) {
throw new IllegalArgumentException("Parameter relayName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.listWebAppsByHybridConnection(resourceGroupName, name, namespaceName, relayName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<String>>>>() {
@Override
public Observable<ServiceResponse<Page<String>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<String>> result = listWebAppsByHybridConnectionDelegate(response);
return Observable.just(new ServiceResponse<Page<String>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} } | public class class_name {
public Observable<ServiceResponse<Page<String>>> listWebAppsByHybridConnectionSinglePageAsync(final String resourceGroupName, final String name, final String namespaceName, final String relayName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (name == null) {
throw new IllegalArgumentException("Parameter name is required and cannot be null.");
}
if (namespaceName == null) {
throw new IllegalArgumentException("Parameter namespaceName is required and cannot be null.");
}
if (relayName == null) {
throw new IllegalArgumentException("Parameter relayName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.listWebAppsByHybridConnection(resourceGroupName, name, namespaceName, relayName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<String>>>>() {
@Override
public Observable<ServiceResponse<Page<String>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<String>> result = listWebAppsByHybridConnectionDelegate(response);
return Observable.just(new ServiceResponse<Page<String>>(result.body(), result.response())); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
return Observable.error(t);
} // depends on control dependency: [catch], data = [none]
}
});
} } |
public class class_name {
@NonNull
public List<List<LatLng>> getLatLngs() {
Polygon polygon = (Polygon) geometry;
List<List<LatLng>> latLngs = new ArrayList<>();
List<List<Point>> coordinates = polygon.coordinates();
if (coordinates != null) {
for (List<Point> innerPoints : coordinates) {
List<LatLng> innerList = new ArrayList<>();
for (Point point : innerPoints) {
innerList.add(new LatLng(point.latitude(), point.longitude()));
}
latLngs.add(innerList);
}
}
return latLngs;
} } | public class class_name {
@NonNull
public List<List<LatLng>> getLatLngs() {
Polygon polygon = (Polygon) geometry;
List<List<LatLng>> latLngs = new ArrayList<>();
List<List<Point>> coordinates = polygon.coordinates();
if (coordinates != null) {
for (List<Point> innerPoints : coordinates) {
List<LatLng> innerList = new ArrayList<>();
for (Point point : innerPoints) {
innerList.add(new LatLng(point.latitude(), point.longitude())); // depends on control dependency: [for], data = [point]
}
latLngs.add(innerList); // depends on control dependency: [for], data = [none]
}
}
return latLngs;
} } |
public class class_name {
public boolean isAnyCategorical(){
int cnt =0;
for(int i=0;i<_cols.length;++i) {
if( !_cols[i]._ignored && !_cols[i]._response && _cols[i]._isCategorical) {
cnt = 1;
break;
}
}
if(cnt ==1) return true;
else return false;
} } | public class class_name {
public boolean isAnyCategorical(){
int cnt =0;
for(int i=0;i<_cols.length;++i) {
if( !_cols[i]._ignored && !_cols[i]._response && _cols[i]._isCategorical) {
cnt = 1; // depends on control dependency: [if], data = [none]
break;
}
}
if(cnt ==1) return true;
else return false;
} } |
public class class_name {
private String getCacheKey(HttpServerExchange exchange) {
String host = null;
HeaderMap headerMap = exchange.getRequestHeaders();
if (headerMap != null) {
HeaderValues headerValues = headerMap.get(Header.X_FORWARDED_FOR.toHttpString());
if (headerValues != null) {
host = headerValues.element();
}
}
if (StringUtils.isBlank(host)) {
InetSocketAddress inetSocketAddress = exchange.getSourceAddress();
if (inetSocketAddress != null) {
host = inetSocketAddress.getHostString();
}
}
if (StringUtils.isNotBlank(host)) {
host = host.toLowerCase(Locale.ENGLISH);
}
String url = exchange.getRequestURL();
if (StringUtils.isNotBlank(url)) {
url = url.toLowerCase(Locale.ENGLISH);
}
return url + host;
} } | public class class_name {
private String getCacheKey(HttpServerExchange exchange) {
String host = null;
HeaderMap headerMap = exchange.getRequestHeaders();
if (headerMap != null) {
HeaderValues headerValues = headerMap.get(Header.X_FORWARDED_FOR.toHttpString());
if (headerValues != null) {
host = headerValues.element(); // depends on control dependency: [if], data = [none]
}
}
if (StringUtils.isBlank(host)) {
InetSocketAddress inetSocketAddress = exchange.getSourceAddress();
if (inetSocketAddress != null) {
host = inetSocketAddress.getHostString(); // depends on control dependency: [if], data = [none]
}
}
if (StringUtils.isNotBlank(host)) {
host = host.toLowerCase(Locale.ENGLISH); // depends on control dependency: [if], data = [none]
}
String url = exchange.getRequestURL();
if (StringUtils.isNotBlank(url)) {
url = url.toLowerCase(Locale.ENGLISH); // depends on control dependency: [if], data = [none]
}
return url + host;
} } |
public class class_name {
private Block getBlock(QueryConditonDatakey qcdk) {
Block clientBlock = new Block(qcdk.getStart(), qcdk.getCount());
if (clientBlock.getCount() > this.blockLength)
clientBlock.setCount(this.blockLength);
// create dataBlock get DataBase or cache;
List list = getBlockKeys(qcdk);
Block dataBlock = new Block(qcdk.getBlockStart(), list.size());
int currentStart = clientBlock.getStart() - dataBlock.getStart();
Block currentBlock = new Block(currentStart, clientBlock.getCount());
currentBlock.setList(list);
try {
// because clientBlock's length maybe not be equals to the
// dataBlock's length
// we need the last length:
// 1.the last block length is great than the clientBlock's
// length,the current block's length is the clientBlock's length
// 2.the last block length is less than the clientBlock's
// length,under this condition, there are two choice.
int lastCount = dataBlock.getCount() + dataBlock.getStart() - clientBlock.getStart();
Debug.logVerbose("[JdonFramework] lastCount=" + lastCount, module);
// 2 happened
if (lastCount < clientBlock.getCount()) {
// if 2 , two case:
// 1. if the dataBlock's length is this.blockLength(200),should
// have more dataBlocks.
if (dataBlock.getCount() == this.blockLength) {
// new datablock, we must support new start and new count
// the new start = old datablock's length + old datablock's
// start.
int newStartIndex = dataBlock.getStart() + dataBlock.getCount();
int newCount = clientBlock.getCount() - lastCount;
qcdk.setStart(newStartIndex);
qcdk.setCount(newCount);
Debug.logVerbose("[JdonFramework] newStartIndex=" + newStartIndex + " newCount=" + newCount, module);
Block nextBlock = getBlock(qcdk);
Debug.logVerbose("[JdonFramework] nextBlock.getCount()=" + nextBlock.getCount(), module);
currentBlock.setCount(currentBlock.getCount() + nextBlock.getCount());
} else {
// 2. if not, all datas just be here, clientBlock's count
// value maybe not correct.
currentBlock.setCount(lastCount);
}
}
} catch (Exception e) {
Debug.logError(" getBlock error" + e, module);
}
return currentBlock;
} } | public class class_name {
private Block getBlock(QueryConditonDatakey qcdk) {
Block clientBlock = new Block(qcdk.getStart(), qcdk.getCount());
if (clientBlock.getCount() > this.blockLength)
clientBlock.setCount(this.blockLength);
// create dataBlock get DataBase or cache;
List list = getBlockKeys(qcdk);
Block dataBlock = new Block(qcdk.getBlockStart(), list.size());
int currentStart = clientBlock.getStart() - dataBlock.getStart();
Block currentBlock = new Block(currentStart, clientBlock.getCount());
currentBlock.setList(list);
try {
// because clientBlock's length maybe not be equals to the
// dataBlock's length
// we need the last length:
// 1.the last block length is great than the clientBlock's
// length,the current block's length is the clientBlock's length
// 2.the last block length is less than the clientBlock's
// length,under this condition, there are two choice.
int lastCount = dataBlock.getCount() + dataBlock.getStart() - clientBlock.getStart();
Debug.logVerbose("[JdonFramework] lastCount=" + lastCount, module);
// depends on control dependency: [try], data = [none]
// 2 happened
if (lastCount < clientBlock.getCount()) {
// if 2 , two case:
// 1. if the dataBlock's length is this.blockLength(200),should
// have more dataBlocks.
if (dataBlock.getCount() == this.blockLength) {
// new datablock, we must support new start and new count
// the new start = old datablock's length + old datablock's
// start.
int newStartIndex = dataBlock.getStart() + dataBlock.getCount();
int newCount = clientBlock.getCount() - lastCount;
qcdk.setStart(newStartIndex);
// depends on control dependency: [if], data = [none]
qcdk.setCount(newCount);
// depends on control dependency: [if], data = [none]
Debug.logVerbose("[JdonFramework] newStartIndex=" + newStartIndex + " newCount=" + newCount, module);
// depends on control dependency: [if], data = [none]
Block nextBlock = getBlock(qcdk);
Debug.logVerbose("[JdonFramework] nextBlock.getCount()=" + nextBlock.getCount(), module);
// depends on control dependency: [if], data = [none]
currentBlock.setCount(currentBlock.getCount() + nextBlock.getCount());
// depends on control dependency: [if], data = [none]
} else {
// 2. if not, all datas just be here, clientBlock's count
// value maybe not correct.
currentBlock.setCount(lastCount);
// depends on control dependency: [if], data = [none]
}
}
} catch (Exception e) {
Debug.logError(" getBlock error" + e, module);
}
// depends on control dependency: [catch], data = [none]
return currentBlock;
} } |
public class class_name {
@Deprecated
public List<Index> listIndices() {
InputStream response = null;
try {
URI uri = new DatabaseURIHelper(db.getDBUri()).path("_index").build();
response = client.couchDbClient.get(uri);
return getResponseList(response, client.getGson(), DeserializationTypes.INDICES);
} finally {
close(response);
}
} } | public class class_name {
@Deprecated
public List<Index> listIndices() {
InputStream response = null;
try {
URI uri = new DatabaseURIHelper(db.getDBUri()).path("_index").build();
response = client.couchDbClient.get(uri); // depends on control dependency: [try], data = [none]
return getResponseList(response, client.getGson(), DeserializationTypes.INDICES); // depends on control dependency: [try], data = [none]
} finally {
close(response);
}
} } |
public class class_name {
private synchronized void maybeRun() {
if (inprogress==null && pending!=null) {
base.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
synchronized (AtmostOneTaskExecutor.this) {
// everyone who submits after this should form a next batch
inprogress = pending;
pending = null;
}
try {
inprogress.set(task.call());
} catch (Throwable t) {
LOGGER.log(Level.WARNING, null, t);
inprogress.setException(t);
} finally {
synchronized (AtmostOneTaskExecutor.this) {
// if next one is pending, get that scheduled
inprogress = null;
maybeRun();
}
}
return null;
}
});
}
} } | public class class_name {
private synchronized void maybeRun() {
if (inprogress==null && pending!=null) {
base.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
synchronized (AtmostOneTaskExecutor.this) {
// everyone who submits after this should form a next batch
inprogress = pending;
pending = null;
}
try {
inprogress.set(task.call());
} catch (Throwable t) {
LOGGER.log(Level.WARNING, null, t);
inprogress.setException(t);
} finally {
synchronized (AtmostOneTaskExecutor.this) {
// if next one is pending, get that scheduled
inprogress = null;
maybeRun();
}
}
return null;
}
}); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public final I getInvocation(Object protocolKey)
{
I invocation = null;
// XXX: see if can remove this
LruCache<Object,I> invocationCache = _invocationCache;
if (invocationCache != null) {
invocation = invocationCache.get(protocolKey);
}
if (invocation == null) {
return null;
}
else if (invocation.isModified()) {
return null;
}
else {
return invocation;
}
} } | public class class_name {
public final I getInvocation(Object protocolKey)
{
I invocation = null;
// XXX: see if can remove this
LruCache<Object,I> invocationCache = _invocationCache;
if (invocationCache != null) {
invocation = invocationCache.get(protocolKey); // depends on control dependency: [if], data = [none]
}
if (invocation == null) {
return null; // depends on control dependency: [if], data = [none]
}
else if (invocation.isModified()) {
return null; // depends on control dependency: [if], data = [none]
}
else {
return invocation; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public Response deleteResource(OperationContext context) {
context.
checkOperationSupport().
checkPreconditions();
try {
context.resource().delete();
return Response.noContent().build();
} catch (ApplicationExecutionException e) {
throw diagnoseApplicationExecutionException(context, e);
} catch (ApplicationContextException e) {
throw new InternalServerException(context,e);
}
} } | public class class_name {
@Override
public Response deleteResource(OperationContext context) {
context.
checkOperationSupport().
checkPreconditions();
try {
context.resource().delete(); // depends on control dependency: [try], data = [none]
return Response.noContent().build(); // depends on control dependency: [try], data = [none]
} catch (ApplicationExecutionException e) {
throw diagnoseApplicationExecutionException(context, e);
} catch (ApplicationContextException e) { // depends on control dependency: [catch], data = [none]
throw new InternalServerException(context,e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void submit(final ActiveContext context, final String command) {
try {
LOG.log(Level.INFO, "Send command {0} to context: {1}", new Object[]{command, context});
final JavaConfigurationBuilder cb = Tang.Factory.getTang().newConfigurationBuilder();
cb.addConfiguration(
TaskConfiguration.CONF
.set(TaskConfiguration.IDENTIFIER, context.getId() + "_task")
.set(TaskConfiguration.TASK, ShellTask.class)
.build()
);
cb.bindNamedParameter(Command.class, command);
context.submitTask(cb.build());
} catch (final BindException ex) {
LOG.log(Level.SEVERE, "Bad Task configuration for context: " + context.getId(), ex);
context.close();
throw new RuntimeException(ex);
}
} } | public class class_name {
private void submit(final ActiveContext context, final String command) {
try {
LOG.log(Level.INFO, "Send command {0} to context: {1}", new Object[]{command, context}); // depends on control dependency: [try], data = [none]
final JavaConfigurationBuilder cb = Tang.Factory.getTang().newConfigurationBuilder();
cb.addConfiguration(
TaskConfiguration.CONF
.set(TaskConfiguration.IDENTIFIER, context.getId() + "_task")
.set(TaskConfiguration.TASK, ShellTask.class)
.build()
); // depends on control dependency: [try], data = [none]
cb.bindNamedParameter(Command.class, command); // depends on control dependency: [try], data = [none]
context.submitTask(cb.build()); // depends on control dependency: [try], data = [none]
} catch (final BindException ex) {
LOG.log(Level.SEVERE, "Bad Task configuration for context: " + context.getId(), ex);
context.close();
throw new RuntimeException(ex);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public ByteBuffer getAttributeBuffer(int index) {
final VertexAttribute attribute = getAttribute(index);
if (attribute == null) {
return null;
}
return attribute.getData();
} } | public class class_name {
public ByteBuffer getAttributeBuffer(int index) {
final VertexAttribute attribute = getAttribute(index);
if (attribute == null) {
return null; // depends on control dependency: [if], data = [none]
}
return attribute.getData();
} } |
public class class_name {
@Override
public HistogramIterationValue next() {
// Move through the sub buckets and buckets until we hit the next reporting level:
while (!exhaustedSubBuckets()) {
countAtThisValue = histogram.getCountAtIndex(currentIndex);
if (freshSubBucket) { // Don't add unless we've incremented since last bucket...
totalCountToCurrentIndex += countAtThisValue;
totalValueToCurrentIndex += countAtThisValue * histogram.highestEquivalentValue(currentValueAtIndex);
freshSubBucket = false;
}
if (reachedIterationLevel()) {
long valueIteratedTo = getValueIteratedTo();
currentIterationValue.set(valueIteratedTo, prevValueIteratedTo, countAtThisValue,
(totalCountToCurrentIndex - totalCountToPrevIndex), totalCountToCurrentIndex,
totalValueToCurrentIndex, ((100.0 * totalCountToCurrentIndex) / arrayTotalCount),
getPercentileIteratedTo(), integerToDoubleValueConversionRatio);
prevValueIteratedTo = valueIteratedTo;
totalCountToPrevIndex = totalCountToCurrentIndex;
// move the next iteration level forward:
incrementIterationLevel();
if (histogram.getTotalCount() != savedHistogramTotalRawCount) {
throw new ConcurrentModificationException();
}
return currentIterationValue;
}
incrementSubBucket();
}
// Should not reach here. But possible for overflowed histograms under certain conditions
throw new ArrayIndexOutOfBoundsException();
} } | public class class_name {
@Override
public HistogramIterationValue next() {
// Move through the sub buckets and buckets until we hit the next reporting level:
while (!exhaustedSubBuckets()) {
countAtThisValue = histogram.getCountAtIndex(currentIndex); // depends on control dependency: [while], data = [none]
if (freshSubBucket) { // Don't add unless we've incremented since last bucket...
totalCountToCurrentIndex += countAtThisValue; // depends on control dependency: [if], data = [none]
totalValueToCurrentIndex += countAtThisValue * histogram.highestEquivalentValue(currentValueAtIndex); // depends on control dependency: [if], data = [none]
freshSubBucket = false; // depends on control dependency: [if], data = [none]
}
if (reachedIterationLevel()) {
long valueIteratedTo = getValueIteratedTo();
currentIterationValue.set(valueIteratedTo, prevValueIteratedTo, countAtThisValue,
(totalCountToCurrentIndex - totalCountToPrevIndex), totalCountToCurrentIndex,
totalValueToCurrentIndex, ((100.0 * totalCountToCurrentIndex) / arrayTotalCount),
getPercentileIteratedTo(), integerToDoubleValueConversionRatio); // depends on control dependency: [if], data = [none]
prevValueIteratedTo = valueIteratedTo; // depends on control dependency: [if], data = [none]
totalCountToPrevIndex = totalCountToCurrentIndex; // depends on control dependency: [if], data = [none]
// move the next iteration level forward:
incrementIterationLevel(); // depends on control dependency: [if], data = [none]
if (histogram.getTotalCount() != savedHistogramTotalRawCount) {
throw new ConcurrentModificationException();
}
return currentIterationValue; // depends on control dependency: [if], data = [none]
}
incrementSubBucket(); // depends on control dependency: [while], data = [none]
}
// Should not reach here. But possible for overflowed histograms under certain conditions
throw new ArrayIndexOutOfBoundsException();
} } |
public class class_name {
public ElementType<AnnotationType<T>> getOrCreateElement()
{
List<Node> nodeList = childNode.get("element");
if (nodeList != null && nodeList.size() > 0)
{
return new ElementTypeImpl<AnnotationType<T>>(this, "element", childNode, nodeList.get(0));
}
return createElement();
} } | public class class_name {
public ElementType<AnnotationType<T>> getOrCreateElement()
{
List<Node> nodeList = childNode.get("element");
if (nodeList != null && nodeList.size() > 0)
{
return new ElementTypeImpl<AnnotationType<T>>(this, "element", childNode, nodeList.get(0)); // depends on control dependency: [if], data = [none]
}
return createElement();
} } |
public class class_name {
public java.util.List<String> getRetentionConfigurationNames() {
if (retentionConfigurationNames == null) {
retentionConfigurationNames = new com.amazonaws.internal.SdkInternalList<String>();
}
return retentionConfigurationNames;
} } | public class class_name {
public java.util.List<String> getRetentionConfigurationNames() {
if (retentionConfigurationNames == null) {
retentionConfigurationNames = new com.amazonaws.internal.SdkInternalList<String>(); // depends on control dependency: [if], data = [none]
}
return retentionConfigurationNames;
} } |
public class class_name {
@SuppressWarnings("static-method")
protected Visibility applyMinMaxVisibility(Visibility visibility, MutableFieldDeclaration it, TransformationContext context) {
if (context.findTypeGlobally(Agent.class).isAssignableFrom(it.getDeclaringType())) {
if (visibility.compareTo(Visibility.PROTECTED) > 0) {
return Visibility.PROTECTED;
}
}
return visibility;
} } | public class class_name {
@SuppressWarnings("static-method")
protected Visibility applyMinMaxVisibility(Visibility visibility, MutableFieldDeclaration it, TransformationContext context) {
if (context.findTypeGlobally(Agent.class).isAssignableFrom(it.getDeclaringType())) {
if (visibility.compareTo(Visibility.PROTECTED) > 0) {
return Visibility.PROTECTED; // depends on control dependency: [if], data = [none]
}
}
return visibility;
} } |
public class class_name {
public boolean isDuplicateName(String name) {
if (name == null || name.trim().isEmpty()) {
return false;
}
List<AssignmentRow> as = view.getAssignmentRows();
if (as != null && !as.isEmpty()) {
int nameCount = 0;
for (AssignmentRow row : as) {
if (name.trim().compareTo(row.getName()) == 0) {
nameCount++;
if (nameCount > 1) {
return true;
}
}
}
}
return false;
} } | public class class_name {
public boolean isDuplicateName(String name) {
if (name == null || name.trim().isEmpty()) {
return false; // depends on control dependency: [if], data = [none]
}
List<AssignmentRow> as = view.getAssignmentRows();
if (as != null && !as.isEmpty()) {
int nameCount = 0;
for (AssignmentRow row : as) {
if (name.trim().compareTo(row.getName()) == 0) {
nameCount++; // depends on control dependency: [if], data = [none]
if (nameCount > 1) {
return true; // depends on control dependency: [if], data = [none]
}
}
}
}
return false;
} } |
public class class_name {
public void loadModel(final GVRResourceVolume fileVolume,
final GVRSceneObject model,
final EnumSet<GVRImportSettings> settings,
final boolean cacheEnabled,
final IAssetEvents handler)
{
Threads.spawn(new Runnable()
{
public void run()
{
String filePath = fileVolume.getFileName();
String ext = filePath.substring(filePath.length() - 3).toLowerCase();
AssetRequest assetRequest =
new AssetRequest(model, fileVolume, null, handler, false);
model.setName(assetRequest.getBaseName());
assetRequest.setImportSettings(settings);
assetRequest.useCache(cacheEnabled);
try
{
if (ext.equals("x3d"))
{
loadX3DModel(assetRequest, model);
}
else
{
loadJassimpModel(assetRequest, model);
}
}
catch (IOException ex)
{
// onModelError is generated in this case
}
}
});
} } | public class class_name {
public void loadModel(final GVRResourceVolume fileVolume,
final GVRSceneObject model,
final EnumSet<GVRImportSettings> settings,
final boolean cacheEnabled,
final IAssetEvents handler)
{
Threads.spawn(new Runnable()
{
public void run()
{
String filePath = fileVolume.getFileName();
String ext = filePath.substring(filePath.length() - 3).toLowerCase();
AssetRequest assetRequest =
new AssetRequest(model, fileVolume, null, handler, false);
model.setName(assetRequest.getBaseName());
assetRequest.setImportSettings(settings);
assetRequest.useCache(cacheEnabled);
try
{
if (ext.equals("x3d"))
{
loadX3DModel(assetRequest, model); // depends on control dependency: [if], data = [none]
}
else
{
loadJassimpModel(assetRequest, model); // depends on control dependency: [if], data = [none]
}
}
catch (IOException ex)
{
// onModelError is generated in this case
} // depends on control dependency: [catch], data = [none]
}
});
} } |
public class class_name {
public final DTMIterator getContextNodes()
{
try
{
DTMIterator cnl = getContextNodeList();
if (null != cnl)
return cnl.cloneWithReset();
else
return null; // for now... this might ought to be an empty iterator.
}
catch (CloneNotSupportedException cnse)
{
return null; // error reporting?
}
} } | public class class_name {
public final DTMIterator getContextNodes()
{
try
{
DTMIterator cnl = getContextNodeList();
if (null != cnl)
return cnl.cloneWithReset();
else
return null; // for now... this might ought to be an empty iterator.
}
catch (CloneNotSupportedException cnse)
{
return null; // error reporting?
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static <T> T createInternal(Config config, Class<T> clazz) {
if (((SimpleConfig)config).root().resolveStatus() != ResolveStatus.RESOLVED)
throw new ConfigException.NotResolved(
"need to Config#resolve() a config before using it to initialize a bean, see the API docs for Config#resolve()");
Map<String, AbstractConfigValue> configProps = new HashMap<String, AbstractConfigValue>();
Map<String, String> originalNames = new HashMap<String, String>();
for (Map.Entry<String, ConfigValue> configProp : config.root().entrySet()) {
String originalName = configProp.getKey();
String camelName = ConfigImplUtil.toCamelCase(originalName);
// if a setting is in there both as some hyphen name and the camel name,
// the camel one wins
if (originalNames.containsKey(camelName) && !originalName.equals(camelName)) {
// if we aren't a camel name to start with, we lose.
// if we are or we are the first matching key, we win.
} else {
configProps.put(camelName, (AbstractConfigValue) configProp.getValue());
originalNames.put(camelName, originalName);
}
}
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo(clazz);
} catch (IntrospectionException e) {
throw new ConfigException.BadBean("Could not get bean information for class " + clazz.getName(), e);
}
try {
List<PropertyDescriptor> beanProps = new ArrayList<PropertyDescriptor>();
for (PropertyDescriptor beanProp : beanInfo.getPropertyDescriptors()) {
if (beanProp.getReadMethod() == null || beanProp.getWriteMethod() == null) {
continue;
}
beanProps.add(beanProp);
}
// Try to throw all validation issues at once (this does not comprehensively
// find every issue, but it should find common ones).
List<ConfigException.ValidationProblem> problems = new ArrayList<ConfigException.ValidationProblem>();
for (PropertyDescriptor beanProp : beanProps) {
Method setter = beanProp.getWriteMethod();
Class<?> parameterClass = setter.getParameterTypes()[0];
ConfigValueType expectedType = getValueTypeOrNull(parameterClass);
if (expectedType != null) {
String name = originalNames.get(beanProp.getName());
if (name == null)
name = beanProp.getName();
Path path = Path.newKey(name);
AbstractConfigValue configValue = configProps.get(beanProp.getName());
if (configValue != null) {
SimpleConfig.checkValid(path, expectedType, configValue, problems);
} else {
if (!isOptionalProperty(clazz, beanProp)) {
SimpleConfig.addMissing(problems, expectedType, path, config.origin());
}
}
}
}
if (!problems.isEmpty()) {
throw new ConfigException.ValidationFailed(problems);
}
// Fill in the bean instance
T bean = clazz.newInstance();
for (PropertyDescriptor beanProp : beanProps) {
Method setter = beanProp.getWriteMethod();
Type parameterType = setter.getGenericParameterTypes()[0];
Class<?> parameterClass = setter.getParameterTypes()[0];
String configPropName = originalNames.get(beanProp.getName());
// Is the property key missing in the config?
if (configPropName == null) {
// If so, continue if the field is marked as @{link Optional}
if (isOptionalProperty(clazz, beanProp)) {
continue;
}
// Otherwise, raise a {@link Missing} exception right here
throw new ConfigException.Missing(beanProp.getName());
}
Object unwrapped = getValue(clazz, parameterType, parameterClass, config, configPropName);
setter.invoke(bean, unwrapped);
}
return bean;
} catch (InstantiationException e) {
throw new ConfigException.BadBean(clazz.getName() + " needs a public no-args constructor to be used as a bean", e);
} catch (IllegalAccessException e) {
throw new ConfigException.BadBean(clazz.getName() + " getters and setters are not accessible, they must be for use as a bean", e);
} catch (InvocationTargetException e) {
throw new ConfigException.BadBean("Calling bean method on " + clazz.getName() + " caused an exception", e);
}
} } | public class class_name {
public static <T> T createInternal(Config config, Class<T> clazz) {
if (((SimpleConfig)config).root().resolveStatus() != ResolveStatus.RESOLVED)
throw new ConfigException.NotResolved(
"need to Config#resolve() a config before using it to initialize a bean, see the API docs for Config#resolve()");
Map<String, AbstractConfigValue> configProps = new HashMap<String, AbstractConfigValue>();
Map<String, String> originalNames = new HashMap<String, String>();
for (Map.Entry<String, ConfigValue> configProp : config.root().entrySet()) {
String originalName = configProp.getKey();
String camelName = ConfigImplUtil.toCamelCase(originalName);
// if a setting is in there both as some hyphen name and the camel name,
// the camel one wins
if (originalNames.containsKey(camelName) && !originalName.equals(camelName)) {
// if we aren't a camel name to start with, we lose.
// if we are or we are the first matching key, we win.
} else {
configProps.put(camelName, (AbstractConfigValue) configProp.getValue()); // depends on control dependency: [if], data = [none]
originalNames.put(camelName, originalName); // depends on control dependency: [if], data = [none]
}
}
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo(clazz); // depends on control dependency: [try], data = [none]
} catch (IntrospectionException e) {
throw new ConfigException.BadBean("Could not get bean information for class " + clazz.getName(), e);
} // depends on control dependency: [catch], data = [none]
try {
List<PropertyDescriptor> beanProps = new ArrayList<PropertyDescriptor>();
for (PropertyDescriptor beanProp : beanInfo.getPropertyDescriptors()) {
if (beanProp.getReadMethod() == null || beanProp.getWriteMethod() == null) {
continue;
}
beanProps.add(beanProp); // depends on control dependency: [for], data = [beanProp]
}
// Try to throw all validation issues at once (this does not comprehensively
// find every issue, but it should find common ones).
List<ConfigException.ValidationProblem> problems = new ArrayList<ConfigException.ValidationProblem>();
for (PropertyDescriptor beanProp : beanProps) {
Method setter = beanProp.getWriteMethod();
Class<?> parameterClass = setter.getParameterTypes()[0];
ConfigValueType expectedType = getValueTypeOrNull(parameterClass);
if (expectedType != null) {
String name = originalNames.get(beanProp.getName());
if (name == null)
name = beanProp.getName();
Path path = Path.newKey(name);
AbstractConfigValue configValue = configProps.get(beanProp.getName());
if (configValue != null) {
SimpleConfig.checkValid(path, expectedType, configValue, problems); // depends on control dependency: [if], data = [none]
} else {
if (!isOptionalProperty(clazz, beanProp)) {
SimpleConfig.addMissing(problems, expectedType, path, config.origin()); // depends on control dependency: [if], data = [none]
}
}
}
}
if (!problems.isEmpty()) {
throw new ConfigException.ValidationFailed(problems);
}
// Fill in the bean instance
T bean = clazz.newInstance();
for (PropertyDescriptor beanProp : beanProps) {
Method setter = beanProp.getWriteMethod();
Type parameterType = setter.getGenericParameterTypes()[0];
Class<?> parameterClass = setter.getParameterTypes()[0];
String configPropName = originalNames.get(beanProp.getName());
// Is the property key missing in the config?
if (configPropName == null) {
// If so, continue if the field is marked as @{link Optional}
if (isOptionalProperty(clazz, beanProp)) {
continue;
}
// Otherwise, raise a {@link Missing} exception right here
throw new ConfigException.Missing(beanProp.getName());
}
Object unwrapped = getValue(clazz, parameterType, parameterClass, config, configPropName);
setter.invoke(bean, unwrapped); // depends on control dependency: [for], data = [none]
}
return bean; // depends on control dependency: [try], data = [none]
} catch (InstantiationException e) {
throw new ConfigException.BadBean(clazz.getName() + " needs a public no-args constructor to be used as a bean", e);
} catch (IllegalAccessException e) { // depends on control dependency: [catch], data = [none]
throw new ConfigException.BadBean(clazz.getName() + " getters and setters are not accessible, they must be for use as a bean", e);
} catch (InvocationTargetException e) { // depends on control dependency: [catch], data = [none]
throw new ConfigException.BadBean("Calling bean method on " + clazz.getName() + " caused an exception", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public void addProperty(final String key, final Object value) {
if (containsKey(key)) {
String newValue = get(key) + ',' + (value == null ? "" : value);
addOrModifyProperty(key, newValue);
} else {
addOrModifyProperty(key, value == null ? null : value.toString());
}
} } | public class class_name {
@Override
public void addProperty(final String key, final Object value) {
if (containsKey(key)) {
String newValue = get(key) + ',' + (value == null ? "" : value);
addOrModifyProperty(key, newValue); // depends on control dependency: [if], data = [none]
} else {
addOrModifyProperty(key, value == null ? null : value.toString()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@FFDCIgnore(NumberFormatException.class)
private boolean isSuccessStatusCode(String s) {
if (s == null) {
return false;
}
if ("2XX".equals(s) || "default".equals(s)) {
return true;
}
if (s.length() != 3) {
return false;
}
try {
final int i = Integer.parseInt(s);
return i >= 200 && i <= 299;
} catch (NumberFormatException nfe) {
return false;
}
} } | public class class_name {
@FFDCIgnore(NumberFormatException.class)
private boolean isSuccessStatusCode(String s) {
if (s == null) {
return false; // depends on control dependency: [if], data = [none]
}
if ("2XX".equals(s) || "default".equals(s)) {
return true; // depends on control dependency: [if], data = [none]
}
if (s.length() != 3) {
return false; // depends on control dependency: [if], data = [none]
}
try {
final int i = Integer.parseInt(s);
return i >= 200 && i <= 299; // depends on control dependency: [try], data = [none]
} catch (NumberFormatException nfe) {
return false;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void setRelationalDatabaseSnapshots(java.util.Collection<RelationalDatabaseSnapshot> relationalDatabaseSnapshots) {
if (relationalDatabaseSnapshots == null) {
this.relationalDatabaseSnapshots = null;
return;
}
this.relationalDatabaseSnapshots = new java.util.ArrayList<RelationalDatabaseSnapshot>(relationalDatabaseSnapshots);
} } | public class class_name {
public void setRelationalDatabaseSnapshots(java.util.Collection<RelationalDatabaseSnapshot> relationalDatabaseSnapshots) {
if (relationalDatabaseSnapshots == null) {
this.relationalDatabaseSnapshots = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.relationalDatabaseSnapshots = new java.util.ArrayList<RelationalDatabaseSnapshot>(relationalDatabaseSnapshots);
} } |
public class class_name {
public int read(char[] ch, int offset, int length) throws IOException {
/*
* The behavior of this method is _intended_ to be like this:
*
* 1. In case if we are working with UCS-2 data, `readUCS2` method
* handles the stuff.
*
* 2. For UCS-4 data method first looks if there is some data stored in
* the internal character buffer (fCharBuf). Usually this data is
* left from previous reading operation if there were any
* supplementary Unicode (ISO-10646) characters.
*
* 3. If buffer holds something, these chars are put directly in passed
* `ch` buffer (maximum `length` of them).
*
* 4. If char buffer ends and more data can be put into `ch`,
* then they are read from the underlying byte stream.
*
* 5. Method tries to read maximum possible number of bytes from
* InputStream, as if all read code points were from BMP (Basic
* Multilingual Plane).
*
* 6. Read UCS-4 characters are encoded to UTF-16 (which is native Java
* encoding) ant put into `ch` array.
*
* 7. It is possible that we end up with more chars than we can
* currently put into passed buffer due to the fact that
* supplementary Unicode characters are encoded into _two_ Java
* char's each. In this situation excess chars are stored in the
* internal char buffer (in reverse order, i.e. those read last
* are at the beginning of the `fCharBuf`). They are usually picked
* up during next call(s) to one of the `read` methods.
*/
if ((0 > offset)
|| (offset > ch.length)
|| (0 > length)
|| ((offset + length) > ch.length)
|| (0 > (offset + length))) {
throw new IndexOutOfBoundsException();
} else if (0 == length) {
return 0;
}
/*
* Well, it is clear that the code should be separated for
* UCS-2 and UCS-4 now with all that char buffer stuff around.
* Things are already getting nasty.
*/
if (fEncoding < 4) {
return readUCS2(ch, offset, length);
}
// First using chars from internal char buffer (if any)
int charsRead = 0;
while (charsRead <= length) {
if (0 != fCharCount) {
ch[offset + charsRead] = fCharBuf[--fCharCount];
charsRead++;
} else {
break;
}
}
// Reading remaining chars from InputStream.
if (0 != (length - charsRead)) {
/*
* Each output char (two for supplementary characters) will require
* us to read 4 input bytes. But as we cannot predict how many
* supplementary chars we will encounter, so we should try to read
* maximum possible number.
*/
int byteLength = (length - charsRead) << 2;
if (byteLength > fBuffer.length) {
byteLength = fBuffer.length;
}
int count = fInputStream.read(fBuffer, 0, byteLength);
if (-1 == count) {
return (0 == charsRead) ? (-1) : charsRead;
} else {
// try and make count be a multiple of the number of bytes we're
// looking for (simply reading 1 to 3 bytes from input stream to
// ensure the last code point is complete)
// this looks ugly, but it avoids an if at any rate...
int numToRead = ((4 - (count & 3)) & 3);
for (int i = 0; i < numToRead; i++) {
int charRead = fInputStream.read();
if (charRead == -1) {
// end of input; something likely went wrong! Pad buffer
// with zeros.
for (int j = i; j < numToRead; j++) fBuffer[count + j] = 0;
break;
} else {
fBuffer[count + i] = (byte) charRead;
}
}
count += numToRead;
// now count is a multiple of the right number of bytes
int numChars = count >> 2;
int curPos = 0;
/*
* `i` is index of currently processed char from InputStream.
* `charsCount` also counts number of chars that were (possibly)
* read from internal char buffer.
*/
int charsCount = charsRead;
int i;
for (i = 0; (i < numChars) && (length >= charsCount); i++) {
int b0 = fBuffer[curPos++] & 0xff;
int b1 = fBuffer[curPos++] & 0xff;
int b2 = fBuffer[curPos++] & 0xff;
int b3 = fBuffer[curPos++] & 0xff;
int codepoint;
if (UCS4BE == fEncoding) {
codepoint = ((b0 << 24) + (b1 << 16) + (b2 << 8) + b3);
} else {
codepoint = ((b3 << 24) + (b2 << 16) + (b1 << 8) + b0);
}
// Again, validity of this codepoint is never checked, this
// can yield problems sometimes.
if (!isSupplementaryCodePoint(codepoint)) {
ch[offset + charsCount] = (char) codepoint;
charsCount++;
} else {
// Checking if we can put another 2 chars in buffer.
if (2 <= (length - charsCount)) {
int cp1 = (codepoint - 0x10000) & 0xFFFFF;
ch[offset + charsCount] = (char) (0xD800 + (cp1 >>> 10));
ch[offset + charsCount + 1] = (char) (0xDC00 + (cp1 & 0x3FF));
charsCount += 2;
} else {
break; // END for
}
}
} // END for
// Storing data, that possibly remain in `fBuffer` into internal
// char buffer for future use :)
curPos = (numChars << 2) - 1;
for (int k = numChars; k > i; k--) {
// Reading bytes in reverse order
int b3 = fBuffer[curPos--] & 0xff;
int b2 = fBuffer[curPos--] & 0xff;
int b1 = fBuffer[curPos--] & 0xff;
int b0 = fBuffer[curPos--] & 0xff;
int codepoint;
if (UCS4BE == fEncoding) {
codepoint = ((b0 << 24) + (b1 << 16) + (b2 << 8) + b3);
} else {
codepoint = ((b3 << 24) + (b2 << 16) + (b1 << 8) + b0);
}
// Look if we need to increase buffer size
if (2 > (fCharBuf.length - k)) {
char[] newBuf = new char[fCharBuf.length << 1];
System.arraycopy(fCharBuf, 0, newBuf, 0, fCharBuf.length);
fCharBuf = newBuf;
}
if (!isSupplementaryCodePoint(codepoint)) {
fCharBuf[fCharCount++] = (char) codepoint;
} else {
int cp1 = (codepoint - 0x10000) & 0xFFFFF;
// In this case store low surrogate code unit first, so that
// it can be read back after high one.
fCharBuf[fCharCount++] = (char) (0xDC00 + ((char) cp1 & 0x3FF));
fCharBuf[fCharCount++] = (char) (0xD800 + (cp1 >>> 10));
}
} // END for
return charsCount;
} // END if (-1 == count) ELSE
} // END if (0 != (length - charsRead))
return charsRead;
} } | public class class_name {
public int read(char[] ch, int offset, int length) throws IOException {
/*
* The behavior of this method is _intended_ to be like this:
*
* 1. In case if we are working with UCS-2 data, `readUCS2` method
* handles the stuff.
*
* 2. For UCS-4 data method first looks if there is some data stored in
* the internal character buffer (fCharBuf). Usually this data is
* left from previous reading operation if there were any
* supplementary Unicode (ISO-10646) characters.
*
* 3. If buffer holds something, these chars are put directly in passed
* `ch` buffer (maximum `length` of them).
*
* 4. If char buffer ends and more data can be put into `ch`,
* then they are read from the underlying byte stream.
*
* 5. Method tries to read maximum possible number of bytes from
* InputStream, as if all read code points were from BMP (Basic
* Multilingual Plane).
*
* 6. Read UCS-4 characters are encoded to UTF-16 (which is native Java
* encoding) ant put into `ch` array.
*
* 7. It is possible that we end up with more chars than we can
* currently put into passed buffer due to the fact that
* supplementary Unicode characters are encoded into _two_ Java
* char's each. In this situation excess chars are stored in the
* internal char buffer (in reverse order, i.e. those read last
* are at the beginning of the `fCharBuf`). They are usually picked
* up during next call(s) to one of the `read` methods.
*/
if ((0 > offset)
|| (offset > ch.length)
|| (0 > length)
|| ((offset + length) > ch.length)
|| (0 > (offset + length))) {
throw new IndexOutOfBoundsException();
} else if (0 == length) {
return 0;
}
/*
* Well, it is clear that the code should be separated for
* UCS-2 and UCS-4 now with all that char buffer stuff around.
* Things are already getting nasty.
*/
if (fEncoding < 4) {
return readUCS2(ch, offset, length);
}
// First using chars from internal char buffer (if any)
int charsRead = 0;
while (charsRead <= length) {
if (0 != fCharCount) {
ch[offset + charsRead] = fCharBuf[--fCharCount];
charsRead++;
} else {
break;
}
}
// Reading remaining chars from InputStream.
if (0 != (length - charsRead)) {
/*
* Each output char (two for supplementary characters) will require
* us to read 4 input bytes. But as we cannot predict how many
* supplementary chars we will encounter, so we should try to read
* maximum possible number.
*/
int byteLength = (length - charsRead) << 2;
if (byteLength > fBuffer.length) {
byteLength = fBuffer.length;
}
int count = fInputStream.read(fBuffer, 0, byteLength);
if (-1 == count) {
return (0 == charsRead) ? (-1) : charsRead;
} else {
// try and make count be a multiple of the number of bytes we're
// looking for (simply reading 1 to 3 bytes from input stream to
// ensure the last code point is complete)
// this looks ugly, but it avoids an if at any rate...
int numToRead = ((4 - (count & 3)) & 3);
for (int i = 0; i < numToRead; i++) {
int charRead = fInputStream.read();
if (charRead == -1) {
// end of input; something likely went wrong! Pad buffer
// with zeros.
for (int j = i; j < numToRead; j++) fBuffer[count + j] = 0;
break;
} else {
fBuffer[count + i] = (byte) charRead;
}
}
count += numToRead;
// now count is a multiple of the right number of bytes
int numChars = count >> 2;
int curPos = 0;
/*
* `i` is index of currently processed char from InputStream.
* `charsCount` also counts number of chars that were (possibly)
* read from internal char buffer.
*/
int charsCount = charsRead;
int i;
for (i = 0; (i < numChars) && (length >= charsCount); i++) {
int b0 = fBuffer[curPos++] & 0xff;
int b1 = fBuffer[curPos++] & 0xff;
int b2 = fBuffer[curPos++] & 0xff;
int b3 = fBuffer[curPos++] & 0xff;
int codepoint;
if (UCS4BE == fEncoding) {
codepoint = ((b0 << 24) + (b1 << 16) + (b2 << 8) + b3); // depends on control dependency: [if], data = [none]
} else {
codepoint = ((b3 << 24) + (b2 << 16) + (b1 << 8) + b0); // depends on control dependency: [if], data = [none]
}
// Again, validity of this codepoint is never checked, this
// can yield problems sometimes.
if (!isSupplementaryCodePoint(codepoint)) {
ch[offset + charsCount] = (char) codepoint; // depends on control dependency: [if], data = [none]
charsCount++; // depends on control dependency: [if], data = [none]
} else {
// Checking if we can put another 2 chars in buffer.
if (2 <= (length - charsCount)) {
int cp1 = (codepoint - 0x10000) & 0xFFFFF;
ch[offset + charsCount] = (char) (0xD800 + (cp1 >>> 10)); // depends on control dependency: [if], data = [none]
ch[offset + charsCount + 1] = (char) (0xDC00 + (cp1 & 0x3FF)); // depends on control dependency: [if], data = [none]
charsCount += 2; // depends on control dependency: [if], data = [none]
} else {
break; // END for
}
}
} // END for
// Storing data, that possibly remain in `fBuffer` into internal
// char buffer for future use :)
curPos = (numChars << 2) - 1;
for (int k = numChars; k > i; k--) {
// Reading bytes in reverse order
int b3 = fBuffer[curPos--] & 0xff;
int b2 = fBuffer[curPos--] & 0xff;
int b1 = fBuffer[curPos--] & 0xff;
int b0 = fBuffer[curPos--] & 0xff;
int codepoint;
if (UCS4BE == fEncoding) {
codepoint = ((b0 << 24) + (b1 << 16) + (b2 << 8) + b3);
} else {
codepoint = ((b3 << 24) + (b2 << 16) + (b1 << 8) + b0);
}
// Look if we need to increase buffer size
if (2 > (fCharBuf.length - k)) {
char[] newBuf = new char[fCharBuf.length << 1];
System.arraycopy(fCharBuf, 0, newBuf, 0, fCharBuf.length);
fCharBuf = newBuf;
}
if (!isSupplementaryCodePoint(codepoint)) {
fCharBuf[fCharCount++] = (char) codepoint;
} else {
int cp1 = (codepoint - 0x10000) & 0xFFFFF;
// In this case store low surrogate code unit first, so that
// it can be read back after high one.
fCharBuf[fCharCount++] = (char) (0xDC00 + ((char) cp1 & 0x3FF));
fCharBuf[fCharCount++] = (char) (0xD800 + (cp1 >>> 10));
}
} // END for
return charsCount;
} // END if (-1 == count) ELSE
} // END if (0 != (length - charsRead))
return charsRead;
} } |
public class class_name {
void metaSave(PrintWriter out) {
synchronized (pendingReplications) {
out.println("Metasave: Blocks being replicated: " +
pendingReplications.size());
Iterator iter = pendingReplications.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
PendingInfo pendingBlock = (PendingInfo) entry.getValue();
Path filename = (Path) entry.getKey();
out.println(filename +
" StartTime: " + new Time(pendingBlock.timeStamp));
}
}
} } | public class class_name {
void metaSave(PrintWriter out) {
synchronized (pendingReplications) {
out.println("Metasave: Blocks being replicated: " +
pendingReplications.size());
Iterator iter = pendingReplications.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
PendingInfo pendingBlock = (PendingInfo) entry.getValue();
Path filename = (Path) entry.getKey();
out.println(filename +
" StartTime: " + new Time(pendingBlock.timeStamp)); // depends on control dependency: [while], data = [none]
}
}
} } |
public class class_name {
public static int validate(URL url, String output, String[] classpath)
{
if (url == null || !(url.toExternalForm().endsWith(".rar") || url.toExternalForm().endsWith(".rar/")))
return FAIL;
int exitCode = SUCCESS;
File destination = null;
URLClassLoader cl = null;
try
{
File f = new File(url.toURI());
if (!f.exists())
throw new IOException("Archive " + url.toExternalForm() + " doesnt exists");
File root = null;
if (f.isFile())
{
destination = new File(SecurityActions.getSystemProperty("java.io.tmpdir"), "/tmp/");
root = extract(f, destination);
}
else
{
root = f;
}
// Create classloader
URL[] allurls;
URL[] urls = getUrls(root);
if (classpath != null && classpath.length > 0)
{
List<URL> listUrl = new ArrayList<URL>();
for (URL u : urls)
listUrl.add(u);
for (String jar : classpath)
{
if (jar.endsWith(".jar"))
listUrl.add(new File(jar).toURI().toURL());
}
allurls = listUrl.toArray(new URL[listUrl.size()]);
}
else
allurls = urls;
cl = SecurityActions.createURLClassLoader(allurls, SecurityActions.getThreadContextClassLoader());
SecurityActions.setThreadContextClassLoader(cl);
// Parse metadata
MetadataFactory metadataFactory = new MetadataFactory();
Connector cmd = metadataFactory.getStandardMetaData(root);
// Annotation scanning
Annotations annotator = new Annotations();
AnnotationScanner scanner = AnnotationScannerFactory.getAnnotationScanner();
AnnotationRepository repository = scanner.scan(cl.getURLs(), cl);
cmd = annotator.merge(cmd, repository, cl);
File reportDirectory = new File(output);
if (!reportDirectory.exists() && !reportDirectory.mkdirs())
{
throw new IOException("The output directory '" + output + "' can't be created");
}
String reportName = url.getFile();
int lastSlashIndex = reportName.lastIndexOf("/");
int lastSepaIndex = reportName.lastIndexOf(File.separator);
int lastIndex = lastSlashIndex > lastSepaIndex ? lastSlashIndex : lastSepaIndex;
if (lastIndex != -1)
reportName = reportName.substring(lastIndex + 1);
reportName += ".log";
File report = new File(reportDirectory, reportName);
exitCode = validate(cmd, root, report, cl);
}
catch (ValidatorException ve)
{
exitCode = FAIL;
}
catch (Exception e)
{
e.printStackTrace();
exitCode = OTHER;
}
finally
{
SecurityActions.closeURLClassLoader(cl);
}
if (destination != null)
{
try
{
recursiveDelete(destination);
}
catch (IOException ioe)
{
// Ignore
}
}
return exitCode;
} } | public class class_name {
public static int validate(URL url, String output, String[] classpath)
{
if (url == null || !(url.toExternalForm().endsWith(".rar") || url.toExternalForm().endsWith(".rar/")))
return FAIL;
int exitCode = SUCCESS;
File destination = null;
URLClassLoader cl = null;
try
{
File f = new File(url.toURI());
if (!f.exists())
throw new IOException("Archive " + url.toExternalForm() + " doesnt exists");
File root = null;
if (f.isFile())
{
destination = new File(SecurityActions.getSystemProperty("java.io.tmpdir"), "/tmp/"); // depends on control dependency: [if], data = [none]
root = extract(f, destination); // depends on control dependency: [if], data = [none]
}
else
{
root = f; // depends on control dependency: [if], data = [none]
}
// Create classloader
URL[] allurls;
URL[] urls = getUrls(root);
if (classpath != null && classpath.length > 0)
{
List<URL> listUrl = new ArrayList<URL>();
for (URL u : urls)
listUrl.add(u);
for (String jar : classpath)
{
if (jar.endsWith(".jar"))
listUrl.add(new File(jar).toURI().toURL());
}
allurls = listUrl.toArray(new URL[listUrl.size()]); // depends on control dependency: [if], data = [none]
}
else
allurls = urls;
cl = SecurityActions.createURLClassLoader(allurls, SecurityActions.getThreadContextClassLoader()); // depends on control dependency: [try], data = [none]
SecurityActions.setThreadContextClassLoader(cl); // depends on control dependency: [try], data = [none]
// Parse metadata
MetadataFactory metadataFactory = new MetadataFactory();
Connector cmd = metadataFactory.getStandardMetaData(root);
// Annotation scanning
Annotations annotator = new Annotations();
AnnotationScanner scanner = AnnotationScannerFactory.getAnnotationScanner();
AnnotationRepository repository = scanner.scan(cl.getURLs(), cl);
cmd = annotator.merge(cmd, repository, cl); // depends on control dependency: [try], data = [none]
File reportDirectory = new File(output);
if (!reportDirectory.exists() && !reportDirectory.mkdirs())
{
throw new IOException("The output directory '" + output + "' can't be created");
}
String reportName = url.getFile();
int lastSlashIndex = reportName.lastIndexOf("/");
int lastSepaIndex = reportName.lastIndexOf(File.separator);
int lastIndex = lastSlashIndex > lastSepaIndex ? lastSlashIndex : lastSepaIndex;
if (lastIndex != -1)
reportName = reportName.substring(lastIndex + 1);
reportName += ".log"; // depends on control dependency: [try], data = [none]
File report = new File(reportDirectory, reportName);
exitCode = validate(cmd, root, report, cl); // depends on control dependency: [try], data = [none]
}
catch (ValidatorException ve)
{
exitCode = FAIL;
} // depends on control dependency: [catch], data = [none]
catch (Exception e)
{
e.printStackTrace();
exitCode = OTHER;
} // depends on control dependency: [catch], data = [none]
finally
{
SecurityActions.closeURLClassLoader(cl);
}
if (destination != null)
{
try
{
recursiveDelete(destination); // depends on control dependency: [try], data = [none]
}
catch (IOException ioe)
{
// Ignore
} // depends on control dependency: [catch], data = [none]
}
return exitCode;
} } |
public class class_name {
private void jComboBoxLineWidthActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxLineWidthActionPerformed
float lineWidth;
try {
lineWidth = Float.parseFloat(jComboBoxLineWidth.getSelectedItem().toString());
} catch (NumberFormatException ex) {
lineWidth = 1.0f;
}
parent.getGraphPanelChart().getChartSettings().setLineWidth(lineWidth);
refreshGraphPreview();
} } | public class class_name {
private void jComboBoxLineWidthActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxLineWidthActionPerformed
float lineWidth;
try {
lineWidth = Float.parseFloat(jComboBoxLineWidth.getSelectedItem().toString()); // depends on control dependency: [try], data = [none]
} catch (NumberFormatException ex) {
lineWidth = 1.0f;
} // depends on control dependency: [catch], data = [none]
parent.getGraphPanelChart().getChartSettings().setLineWidth(lineWidth);
refreshGraphPreview();
} } |
public class class_name {
@Override public String convertType(String _typeDesc, boolean useClassModel, boolean isLocal) {
if (_typeDesc.equals("Z") || _typeDesc.equals("boolean")) {
return (cvtBooleanToChar);
} else if (_typeDesc.equals("[Z") || _typeDesc.equals("boolean[]")) {
return isLocal ? (cvtBooleanArrayToChar) : (cvtBooleanArrayToCharStar);
} else if (_typeDesc.equals("B") || _typeDesc.equals("byte")) {
return (cvtByteToChar);
} else if (_typeDesc.equals("[B") || _typeDesc.equals("byte[]")) {
return isLocal ? (cvtByteArrayToChar) : (cvtByteArrayToCharStar);
} else if (_typeDesc.equals("C") || _typeDesc.equals("char")) {
return (cvtCharToShort);
} else if (_typeDesc.equals("[C") || _typeDesc.equals("char[]")) {
return isLocal ? (cvtCharArrayToShort) : (cvtCharArrayToShortStar);
} else if (_typeDesc.equals("[I") || _typeDesc.equals("int[]")) {
return isLocal ? (cvtIntArrayToInt) : (cvtIntArrayToIntStar);
} else if (_typeDesc.equals("[F") || _typeDesc.equals("float[]")) {
return isLocal ? (cvtFloatArrayToFloat) : (cvtFloatArrayToFloatStar);
} else if (_typeDesc.equals("[D") || _typeDesc.equals("double[]")) {
return isLocal ? (cvtDoubleArrayToDouble) : (cvtDoubleArrayToDoubleStar);
} else if (_typeDesc.equals("[J") || _typeDesc.equals("long[]")) {
return isLocal ? (cvtLongArrayToLong) : (cvtLongArrayToLongStar);
} else if (_typeDesc.equals("[S") || _typeDesc.equals("short[]")) {
return isLocal ? (cvtShortArrayToShort) : (cvtShortArrayToShortStar);
} else if ("[Ljava/util/concurrent/atomic/AtomicInteger;".equals(_typeDesc) ||
"[Ljava.util.concurrent.atomic.AtomicInteger;".equals(_typeDesc)) {
return (cvtIntArrayToIntStar);
}
// if we get this far, we haven't matched anything yet
if (useClassModel) {
return (ClassModel.convert(_typeDesc, "", true));
} else {
return _typeDesc;
}
} } | public class class_name {
@Override public String convertType(String _typeDesc, boolean useClassModel, boolean isLocal) {
if (_typeDesc.equals("Z") || _typeDesc.equals("boolean")) {
return (cvtBooleanToChar); // depends on control dependency: [if], data = [none]
} else if (_typeDesc.equals("[Z") || _typeDesc.equals("boolean[]")) {
return isLocal ? (cvtBooleanArrayToChar) : (cvtBooleanArrayToCharStar);
} else if (_typeDesc.equals("B") || _typeDesc.equals("byte")) {
return (cvtByteToChar); // depends on control dependency: [if], data = [none]
} else if (_typeDesc.equals("[B") || _typeDesc.equals("byte[]")) {
return isLocal ? (cvtByteArrayToChar) : (cvtByteArrayToCharStar);
} else if (_typeDesc.equals("C") || _typeDesc.equals("char")) {
return (cvtCharToShort); // depends on control dependency: [if], data = [none]
} else if (_typeDesc.equals("[C") || _typeDesc.equals("char[]")) {
return isLocal ? (cvtCharArrayToShort) : (cvtCharArrayToShortStar);
} else if (_typeDesc.equals("[I") || _typeDesc.equals("int[]")) {
return isLocal ? (cvtIntArrayToInt) : (cvtIntArrayToIntStar);
} else if (_typeDesc.equals("[F") || _typeDesc.equals("float[]")) {
return isLocal ? (cvtFloatArrayToFloat) : (cvtFloatArrayToFloatStar);
} else if (_typeDesc.equals("[D") || _typeDesc.equals("double[]")) {
return isLocal ? (cvtDoubleArrayToDouble) : (cvtDoubleArrayToDoubleStar);
} else if (_typeDesc.equals("[J") || _typeDesc.equals("long[]")) {
return isLocal ? (cvtLongArrayToLong) : (cvtLongArrayToLongStar);
} else if (_typeDesc.equals("[S") || _typeDesc.equals("short[]")) {
return isLocal ? (cvtShortArrayToShort) : (cvtShortArrayToShortStar);
} else if ("[Ljava/util/concurrent/atomic/AtomicInteger;".equals(_typeDesc) ||
"[Ljava.util.concurrent.atomic.AtomicInteger;".equals(_typeDesc)) {
return (cvtIntArrayToIntStar);
}
// if we get this far, we haven't matched anything yet
if (useClassModel) {
return (ClassModel.convert(_typeDesc, "", true));
} else {
return _typeDesc;
}
} } |
public class class_name {
public synchronized void clear() {
_layerCache.clear();
_moduleCache.clear();
_gzipCache.clear();
for (IGenericCache cache : _namedCaches.values()) {
cache.clear();
}
} } | public class class_name {
public synchronized void clear() {
_layerCache.clear();
_moduleCache.clear();
_gzipCache.clear();
for (IGenericCache cache : _namedCaches.values()) {
cache.clear();
// depends on control dependency: [for], data = [cache]
}
} } |
public class class_name {
List<JCAnnotation> annotationsOpt(Tag kind) {
if (token.kind != MONKEYS_AT) return List.nil(); // optimization
ListBuffer<JCAnnotation> buf = new ListBuffer<JCAnnotation>();
int prevmode = mode;
while (token.kind == MONKEYS_AT) {
int pos = token.pos;
nextToken();
buf.append(annotation(pos, kind));
}
lastmode = mode;
mode = prevmode;
List<JCAnnotation> annotations = buf.toList();
if (debugJSR308 && kind == Tag.TYPE_ANNOTATION)
System.out.println("TA: parsing " + annotations
+ " in " + log.currentSourceFile());
return annotations;
} } | public class class_name {
List<JCAnnotation> annotationsOpt(Tag kind) {
if (token.kind != MONKEYS_AT) return List.nil(); // optimization
ListBuffer<JCAnnotation> buf = new ListBuffer<JCAnnotation>();
int prevmode = mode;
while (token.kind == MONKEYS_AT) {
int pos = token.pos;
nextToken(); // depends on control dependency: [while], data = [none]
buf.append(annotation(pos, kind)); // depends on control dependency: [while], data = [none]
}
lastmode = mode;
mode = prevmode;
List<JCAnnotation> annotations = buf.toList();
if (debugJSR308 && kind == Tag.TYPE_ANNOTATION)
System.out.println("TA: parsing " + annotations
+ " in " + log.currentSourceFile());
return annotations;
} } |
public class class_name {
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
// should never happen
throw new RuntimeException("Coult not get package name: " + e);
}
} } | public class class_name {
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode; // depends on control dependency: [try], data = [none]
} catch (NameNotFoundException e) {
// should never happen
throw new RuntimeException("Coult not get package name: " + e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private boolean isOutOrBelow(Context current)
{
Context c = current.threadState.outctxt;
while (c != null)
{
if (c == current)
{
return true;
}
c = c.outer;
}
return false;
} } | public class class_name {
private boolean isOutOrBelow(Context current)
{
Context c = current.threadState.outctxt;
while (c != null)
{
if (c == current)
{
return true; // depends on control dependency: [if], data = [none]
}
c = c.outer; // depends on control dependency: [while], data = [none]
}
return false;
} } |
public class class_name {
public static String[] intersect(String[] arr1, String[] arr2) {
Map<String, Boolean> map = new HashMap<String, Boolean>();
LinkedList<String> list = new LinkedList<String>();
for (String str : arr1) {
if (!map.containsKey(str)) {
map.put(str, Boolean.FALSE);
}
}
for (String str : arr2) {
if (map.containsKey(str)) {
map.put(str, Boolean.TRUE);
}
}
for (Entry<String, Boolean> e : map.entrySet()) {
if (e.getValue().equals(Boolean.TRUE)) {
list.add(e.getKey());
}
}
String[] result = {};
return list.toArray(result);
} } | public class class_name {
public static String[] intersect(String[] arr1, String[] arr2) {
Map<String, Boolean> map = new HashMap<String, Boolean>();
LinkedList<String> list = new LinkedList<String>();
for (String str : arr1) {
if (!map.containsKey(str)) {
map.put(str, Boolean.FALSE); // depends on control dependency: [if], data = [none]
}
}
for (String str : arr2) {
if (map.containsKey(str)) {
map.put(str, Boolean.TRUE); // depends on control dependency: [if], data = [none]
}
}
for (Entry<String, Boolean> e : map.entrySet()) {
if (e.getValue().equals(Boolean.TRUE)) {
list.add(e.getKey()); // depends on control dependency: [if], data = [none]
}
}
String[] result = {};
return list.toArray(result);
} } |
public class class_name {
public SortedSet<T> firstSubset(SortedSet<T> set) {
if (this.rootNodes.isEmpty() || set == null || set.isEmpty()) {
return null;
}
return firstSubset(set, this.rootNodes);
} } | public class class_name {
public SortedSet<T> firstSubset(SortedSet<T> set) {
if (this.rootNodes.isEmpty() || set == null || set.isEmpty()) {
return null; // depends on control dependency: [if], data = [none]
}
return firstSubset(set, this.rootNodes);
} } |
public class class_name {
public TaskDeleteOptions withIfModifiedSince(DateTime ifModifiedSince) {
if (ifModifiedSince == null) {
this.ifModifiedSince = null;
} else {
this.ifModifiedSince = new DateTimeRfc1123(ifModifiedSince);
}
return this;
} } | public class class_name {
public TaskDeleteOptions withIfModifiedSince(DateTime ifModifiedSince) {
if (ifModifiedSince == null) {
this.ifModifiedSince = null; // depends on control dependency: [if], data = [none]
} else {
this.ifModifiedSince = new DateTimeRfc1123(ifModifiedSince); // depends on control dependency: [if], data = [(ifModifiedSince]
}
return this;
} } |
public class class_name {
public void startFragment(Fragment fragment, String tag, boolean canAddToBackstack) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, fragment);
if (canAddToBackstack) {
transaction.addToBackStack(tag);
}
transaction.commit();
} } | public class class_name {
public void startFragment(Fragment fragment, String tag, boolean canAddToBackstack) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, fragment);
if (canAddToBackstack) {
transaction.addToBackStack(tag); // depends on control dependency: [if], data = [none]
}
transaction.commit();
} } |
public class class_name {
public void addObjectResult(ObjectResult objResult) {
m_objResultList.add(objResult);
// Elevate batch-level status to warning if needed.
Status batchResult = getStatus();
if (batchResult == Status.OK && objResult.getStatus() != ObjectResult.Status.OK) {
setStatus(Status.WARNING);
}
if (objResult.isUpdated()) {
setHasUpdates(true);
}
} } | public class class_name {
public void addObjectResult(ObjectResult objResult) {
m_objResultList.add(objResult);
// Elevate batch-level status to warning if needed.
Status batchResult = getStatus();
if (batchResult == Status.OK && objResult.getStatus() != ObjectResult.Status.OK) {
setStatus(Status.WARNING);
// depends on control dependency: [if], data = [none]
}
if (objResult.isUpdated()) {
setHasUpdates(true);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public List<INextGenEvent> getEvents(Long startTime) {
ArrayList<INextGenEvent> eventList = null;
//Key events where key is equal to or greater (null if nothing is found)
Long eventKey = events.ceilingKey(startTime);
if(eventKey != null) {
eventList = events.get(eventKey);
currentEventTime = eventKey;
}
return eventList;
} } | public class class_name {
public List<INextGenEvent> getEvents(Long startTime) {
ArrayList<INextGenEvent> eventList = null;
//Key events where key is equal to or greater (null if nothing is found)
Long eventKey = events.ceilingKey(startTime);
if(eventKey != null) {
eventList = events.get(eventKey); // depends on control dependency: [if], data = [(eventKey]
currentEventTime = eventKey; // depends on control dependency: [if], data = [none]
}
return eventList;
} } |
public class class_name {
public ResponseBuilder getRepresentation(final ResponseBuilder builder) {
// Add NonRDFSource-related "describe*" link headers, provided this isn't an ACL resource
getResource().getBinaryMetadata().filter(ds -> !ACL.equals(getRequest().getExt())).ifPresent(ds -> {
final String base = getBaseBinaryIdentifier();
final String description = base + (base.contains("?") ? "&" : "?") + "ext=description";
if (syntax != null) {
builder.link(description, "canonical").link(base, "describes")
.link(base + "#description", "alternate");
} else {
builder.link(base, "canonical").link(description, "describedby")
.type(ds.getMimeType().orElse(APPLICATION_OCTET_STREAM));
}
});
// Add a "self" link header
builder.link(getSelfIdentifier(), "self");
// URI Template
builder.header(LINK_TEMPLATE,
"<" + getIdentifier() + "{?version}>; rel=\"" + Memento.Memento.getIRIString() + "\"");
// NonRDFSources responses (strong ETags, etc)
if (getResource().getBinaryMetadata().isPresent() && syntax == null) {
return getLdpNr(builder);
}
// RDFSource responses (weak ETags, etc)
final IRI profile = getProfile(getRequest().getAcceptableMediaTypes(), syntax);
return getLdpRs(builder, syntax, profile);
} } | public class class_name {
public ResponseBuilder getRepresentation(final ResponseBuilder builder) {
// Add NonRDFSource-related "describe*" link headers, provided this isn't an ACL resource
getResource().getBinaryMetadata().filter(ds -> !ACL.equals(getRequest().getExt())).ifPresent(ds -> {
final String base = getBaseBinaryIdentifier();
final String description = base + (base.contains("?") ? "&" : "?") + "ext=description";
if (syntax != null) {
builder.link(description, "canonical").link(base, "describes")
.link(base + "#description", "alternate"); // depends on control dependency: [if], data = [none]
} else {
builder.link(base, "canonical").link(description, "describedby")
.type(ds.getMimeType().orElse(APPLICATION_OCTET_STREAM)); // depends on control dependency: [if], data = [none]
}
});
// Add a "self" link header
builder.link(getSelfIdentifier(), "self");
// URI Template
builder.header(LINK_TEMPLATE,
"<" + getIdentifier() + "{?version}>; rel=\"" + Memento.Memento.getIRIString() + "\"");
// NonRDFSources responses (strong ETags, etc)
if (getResource().getBinaryMetadata().isPresent() && syntax == null) {
return getLdpNr(builder);
}
// RDFSource responses (weak ETags, etc)
final IRI profile = getProfile(getRequest().getAcceptableMediaTypes(), syntax);
return getLdpRs(builder, syntax, profile);
} } |
public class class_name {
private void replaceUnsolvedReference(Map<String, List<NamedConcreteElement>> concreteElementsMap, UnsolvedReference unsolvedReference) {
List<NamedConcreteElement> concreteElements = concreteElementsMap.get(unsolvedReference.getRef());
if (concreteElements != null){
Map<String, String> oldElementAttributes = unsolvedReference.getElement().getAttributesMap();
for (NamedConcreteElement concreteElement : concreteElements) {
NamedConcreteElement substitutionElementWrapper;
if (!unsolvedReference.isTypeRef()){
XsdNamedElements substitutionElement = concreteElement.getElement().clone(oldElementAttributes);
substitutionElementWrapper = (NamedConcreteElement) ReferenceBase.createFromXsd(substitutionElement);
} else {
substitutionElementWrapper = concreteElement;
}
unsolvedReference.getParent().replaceUnsolvedElements(substitutionElementWrapper);
}
} else {
storeUnsolvedItem(unsolvedReference);
}
} } | public class class_name {
private void replaceUnsolvedReference(Map<String, List<NamedConcreteElement>> concreteElementsMap, UnsolvedReference unsolvedReference) {
List<NamedConcreteElement> concreteElements = concreteElementsMap.get(unsolvedReference.getRef());
if (concreteElements != null){
Map<String, String> oldElementAttributes = unsolvedReference.getElement().getAttributesMap();
for (NamedConcreteElement concreteElement : concreteElements) {
NamedConcreteElement substitutionElementWrapper;
if (!unsolvedReference.isTypeRef()){
XsdNamedElements substitutionElement = concreteElement.getElement().clone(oldElementAttributes);
substitutionElementWrapper = (NamedConcreteElement) ReferenceBase.createFromXsd(substitutionElement); // depends on control dependency: [if], data = [none]
} else {
substitutionElementWrapper = concreteElement; // depends on control dependency: [if], data = [none]
}
unsolvedReference.getParent().replaceUnsolvedElements(substitutionElementWrapper); // depends on control dependency: [for], data = [none]
}
} else {
storeUnsolvedItem(unsolvedReference); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void saveInheritContainer(
final CmsInheritanceContainer inheritanceContainer,
final CmsGroupContainerElementPanel groupContainerElement) {
if (getGroupcontainer() != null) {
CmsRpcAction<Map<String, CmsContainerElementData>> action = new CmsRpcAction<Map<String, CmsContainerElementData>>() {
/**
* @see org.opencms.gwt.client.rpc.CmsRpcAction#execute()
*/
@Override
public void execute() {
start(0, true);
getContainerpageService().saveInheritanceContainer(
CmsCoreProvider.get().getStructureId(),
getData().getDetailId(),
inheritanceContainer,
getPageState(),
getLocale(),
this);
}
/**
* @see org.opencms.gwt.client.rpc.CmsRpcAction#onResponse(java.lang.Object)
*/
@Override
protected void onResponse(Map<String, CmsContainerElementData> result) {
stop(false);
m_elements.putAll(result);
try {
replaceContainerElement(groupContainerElement, result.get(groupContainerElement.getId()));
} catch (Exception e) {
CmsDebugLog.getInstance().printLine("Error replacing group container element");
}
addToRecentList(groupContainerElement.getId(), null);
CmsNotification.get().send(
Type.NORMAL,
Messages.get().key(Messages.GUI_NOTIFICATION_INHERITANCE_CONTAINER_SAVED_0));
}
};
action.execute();
}
} } | public class class_name {
public void saveInheritContainer(
final CmsInheritanceContainer inheritanceContainer,
final CmsGroupContainerElementPanel groupContainerElement) {
if (getGroupcontainer() != null) {
CmsRpcAction<Map<String, CmsContainerElementData>> action = new CmsRpcAction<Map<String, CmsContainerElementData>>() {
/**
* @see org.opencms.gwt.client.rpc.CmsRpcAction#execute()
*/
@Override
public void execute() {
start(0, true);
getContainerpageService().saveInheritanceContainer(
CmsCoreProvider.get().getStructureId(),
getData().getDetailId(),
inheritanceContainer,
getPageState(),
getLocale(),
this);
}
/**
* @see org.opencms.gwt.client.rpc.CmsRpcAction#onResponse(java.lang.Object)
*/
@Override
protected void onResponse(Map<String, CmsContainerElementData> result) {
stop(false);
m_elements.putAll(result);
try {
replaceContainerElement(groupContainerElement, result.get(groupContainerElement.getId())); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
CmsDebugLog.getInstance().printLine("Error replacing group container element");
} // depends on control dependency: [catch], data = [none]
addToRecentList(groupContainerElement.getId(), null);
CmsNotification.get().send(
Type.NORMAL,
Messages.get().key(Messages.GUI_NOTIFICATION_INHERITANCE_CONTAINER_SAVED_0));
}
};
action.execute(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setAttribute(String attributeName, Object value) {
synchronized (_iSession) {
if (!_iSession.isValid())
throw new IllegalStateException();
if (null != value) {
if (!(value instanceof HttpSessionBindingListener)) {
_iSession.setAttribute(attributeName, value, Boolean.FALSE);
} else {
_iSession.setAttribute(attributeName, value, Boolean.TRUE);
}
}
}
} } | public class class_name {
public void setAttribute(String attributeName, Object value) {
synchronized (_iSession) {
if (!_iSession.isValid())
throw new IllegalStateException();
if (null != value) {
if (!(value instanceof HttpSessionBindingListener)) {
_iSession.setAttribute(attributeName, value, Boolean.FALSE); // depends on control dependency: [if], data = [none]
} else {
_iSession.setAttribute(attributeName, value, Boolean.TRUE); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
public Workbook writeToExcel(List<? extends Object> datas, boolean hasTitle, Workbook workbook,
boolean transverse) {
if (CollectionUtil.safeIsEmpty(datas)) {
log.warn("给定数据集合为空");
return workbook;
}
datas = datas.parallelStream().filter(data -> data != null).collect(Collectors.toList());
if (datas.isEmpty()) {
log.warn("给定数据集合里的数据全是空");
return workbook;
}
//获取所有字段(包括父类的)
Field[] fields = ReflectUtil.getAllFields(datas.get(0).getClass());
log.info("获取可写入excel的字段");
List<Field> writeFields = new ArrayList<>();
for (Field field : fields) {
String name = field.getName();
log.debug("检查字段[{}]是否可以写入", name);
Class<?> type = field.getType();
List<ExcelDataWriter<?>> data = writers.values().stream()
.filter(excelData -> excelData.writeable(type)).collect(Collectors.toList());
if (data.isEmpty()) {
log.info("字段[{}]不能写入", name);
} else {
log.info("字段[{}]可以写入excel");
ExcelColumn column = field.getAnnotation(ExcelColumn.class);
if (column == null || !column.ignore()) {
writeFields.add(field);
}
}
}
log.debug("可写入excel的字段集合为:[{}]", writeFields);
log.debug("对可写入excel的字段集合排序");
Collections.sort(writeFields, COMPARATOR);
log.debug("可写入excel的字段集合排序完毕,构建标题列表");
List<Writer<?>> titles = null;
if (hasTitle) {
log.info("当前需要标题列表,构建...");
titles = new ArrayList<>(writeFields.size());
for (int i = 0; i < writeFields.size(); i++) {
Field field = writeFields.get(i);
ExcelColumn column = field.getAnnotation(ExcelColumn.class);
if (column == null || StringUtils.isEmpty(column.value())) {
titles.add(build(field.getName()));
} else {
titles.add(build(column.value()));
}
}
}
log.debug("构建单元格数据");
List<List<Writer<?>>> writeDatas = new ArrayList<>(datas.size());
for (int i = 0; i < datas.size(); i++) {
Object dataValue = datas.get(i);
//构建一行数据
List<Writer<?>> columnDatas = new ArrayList<>(writeFields.size());
//加入
writeDatas.add(columnDatas);
for (int j = 0; j < writeFields.size(); j++) {
Field field = writeFields.get(j);
try {
log.debug("获取[{}]中字段[{}]的值", dataValue, field.getName());
Object value = field.get(dataValue);
columnDatas.add(build(value));
} catch (IllegalAccessException e) {
log.warn("[{}]中字段[{}]不能读取", dataValue, field.getName(), e);
columnDatas.add(null);
}
}
}
log.debug("要写入的数据为:[{}]", writeDatas);
log.info("准备写入数据");
writeToExcel(titles, writeDatas, hasTitle, workbook, transverse);
log.info("标题列表为:[{}]", titles);
return workbook;
} } | public class class_name {
public Workbook writeToExcel(List<? extends Object> datas, boolean hasTitle, Workbook workbook,
boolean transverse) {
if (CollectionUtil.safeIsEmpty(datas)) {
log.warn("给定数据集合为空"); // depends on control dependency: [if], data = [none]
return workbook; // depends on control dependency: [if], data = [none]
}
datas = datas.parallelStream().filter(data -> data != null).collect(Collectors.toList());
if (datas.isEmpty()) {
log.warn("给定数据集合里的数据全是空"); // depends on control dependency: [if], data = [none]
return workbook; // depends on control dependency: [if], data = [none]
}
//获取所有字段(包括父类的)
Field[] fields = ReflectUtil.getAllFields(datas.get(0).getClass());
log.info("获取可写入excel的字段");
List<Field> writeFields = new ArrayList<>();
for (Field field : fields) {
String name = field.getName();
log.debug("检查字段[{}]是否可以写入", name); // depends on control dependency: [for], data = [none]
Class<?> type = field.getType();
List<ExcelDataWriter<?>> data = writers.values().stream()
.filter(excelData -> excelData.writeable(type)).collect(Collectors.toList());
if (data.isEmpty()) {
log.info("字段[{}]不能写入", name); // depends on control dependency: [if], data = [none]
} else {
log.info("字段[{}]可以写入excel"); // depends on control dependency: [if], data = [none]
ExcelColumn column = field.getAnnotation(ExcelColumn.class);
if (column == null || !column.ignore()) {
writeFields.add(field); // depends on control dependency: [if], data = [none]
}
}
}
log.debug("可写入excel的字段集合为:[{}]", writeFields);
log.debug("对可写入excel的字段集合排序");
Collections.sort(writeFields, COMPARATOR);
log.debug("可写入excel的字段集合排序完毕,构建标题列表");
List<Writer<?>> titles = null;
if (hasTitle) {
log.info("当前需要标题列表,构建..."); // depends on control dependency: [if], data = [none]
titles = new ArrayList<>(writeFields.size()); // depends on control dependency: [if], data = [none]
for (int i = 0; i < writeFields.size(); i++) {
Field field = writeFields.get(i);
ExcelColumn column = field.getAnnotation(ExcelColumn.class);
if (column == null || StringUtils.isEmpty(column.value())) {
titles.add(build(field.getName())); // depends on control dependency: [if], data = [none]
} else {
titles.add(build(column.value())); // depends on control dependency: [if], data = [(column]
}
}
}
log.debug("构建单元格数据");
List<List<Writer<?>>> writeDatas = new ArrayList<>(datas.size());
for (int i = 0; i < datas.size(); i++) {
Object dataValue = datas.get(i);
//构建一行数据
List<Writer<?>> columnDatas = new ArrayList<>(writeFields.size()); // depends on control dependency: [for], data = [none]
//加入
writeDatas.add(columnDatas); // depends on control dependency: [for], data = [none]
for (int j = 0; j < writeFields.size(); j++) {
Field field = writeFields.get(j);
try {
log.debug("获取[{}]中字段[{}]的值", dataValue, field.getName()); // depends on control dependency: [try], data = [none]
Object value = field.get(dataValue);
columnDatas.add(build(value)); // depends on control dependency: [try], data = [none]
} catch (IllegalAccessException e) {
log.warn("[{}]中字段[{}]不能读取", dataValue, field.getName(), e);
columnDatas.add(null);
} // depends on control dependency: [catch], data = [none]
}
}
log.debug("要写入的数据为:[{}]", writeDatas);
log.info("准备写入数据");
writeToExcel(titles, writeDatas, hasTitle, workbook, transverse);
log.info("标题列表为:[{}]", titles);
return workbook;
} } |
public class class_name {
public void marshall(JobExecutionsRolloutConfig jobExecutionsRolloutConfig, ProtocolMarshaller protocolMarshaller) {
if (jobExecutionsRolloutConfig == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(jobExecutionsRolloutConfig.getMaximumPerMinute(), MAXIMUMPERMINUTE_BINDING);
protocolMarshaller.marshall(jobExecutionsRolloutConfig.getExponentialRate(), EXPONENTIALRATE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(JobExecutionsRolloutConfig jobExecutionsRolloutConfig, ProtocolMarshaller protocolMarshaller) {
if (jobExecutionsRolloutConfig == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(jobExecutionsRolloutConfig.getMaximumPerMinute(), MAXIMUMPERMINUTE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(jobExecutionsRolloutConfig.getExponentialRate(), EXPONENTIALRATE_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void marshall(ExportJobsResponse exportJobsResponse, ProtocolMarshaller protocolMarshaller) {
if (exportJobsResponse == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(exportJobsResponse.getItem(), ITEM_BINDING);
protocolMarshaller.marshall(exportJobsResponse.getNextToken(), NEXTTOKEN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ExportJobsResponse exportJobsResponse, ProtocolMarshaller protocolMarshaller) {
if (exportJobsResponse == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(exportJobsResponse.getItem(), ITEM_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(exportJobsResponse.getNextToken(), NEXTTOKEN_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void outputObjects(XMLStructuredOutput output, int limit, @Nullable String marker, @Nullable String prefix) {
ListFileTreeVisitor visitor = new ListFileTreeVisitor(output, limit, marker, prefix);
output.beginOutput("ListBucketResult", Attribute.set("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/"));
output.property("Name", getName());
output.property("MaxKeys", limit);
output.property("Marker", marker);
output.property("Prefix", prefix);
try {
Files.walkFileTree(file.toPath(), visitor);
} catch (IOException e) {
Exceptions.handle(e);
}
output.property("IsTruncated", limit > 0 && visitor.getCount() > limit);
output.endOutput();
} } | public class class_name {
public void outputObjects(XMLStructuredOutput output, int limit, @Nullable String marker, @Nullable String prefix) {
ListFileTreeVisitor visitor = new ListFileTreeVisitor(output, limit, marker, prefix);
output.beginOutput("ListBucketResult", Attribute.set("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/"));
output.property("Name", getName());
output.property("MaxKeys", limit);
output.property("Marker", marker);
output.property("Prefix", prefix);
try {
Files.walkFileTree(file.toPath(), visitor); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
Exceptions.handle(e);
} // depends on control dependency: [catch], data = [none]
output.property("IsTruncated", limit > 0 && visitor.getCount() > limit);
output.endOutput();
} } |
public class class_name {
public static synchronized void init() {
if (initialized)
return;
if (tc.isEntryEnabled()) {
Tr.entry(tc, "init");
}
initialized = true;
//defaultLevel = StatConstants.STATISTIC_SET_EXTENDED;
defaultLevel = StatConstants.STATISTIC_SET_BASIC;
moduleRoot = new ModuleItem();
setInstrumentationLevel(defaultLevel);
//disabled = false;
try {
MBeanServer mServer = ManagementFactory.getPlatformMBeanServer();
ObjectName pmiMBean = new ObjectName(PmiConstants.MBEAN_NAME);
mServer.registerMBean(PmiCollaboratorFactory.getPmiCollaborator(), pmiMBean);
printAllMBeans();
} catch (Exception e) {
Tr.error(tc, "Unable to create Perf MBean.");
FFDCFilter.processException(e, "com.ibm.ws.pmi.server.PmiRegistry", "Init");
}
if (tc.isEntryEnabled()) {
Tr.exit(tc, "init");
}
} } | public class class_name {
public static synchronized void init() {
if (initialized)
return;
if (tc.isEntryEnabled()) {
Tr.entry(tc, "init"); // depends on control dependency: [if], data = [none]
}
initialized = true;
//defaultLevel = StatConstants.STATISTIC_SET_EXTENDED;
defaultLevel = StatConstants.STATISTIC_SET_BASIC;
moduleRoot = new ModuleItem();
setInstrumentationLevel(defaultLevel);
//disabled = false;
try {
MBeanServer mServer = ManagementFactory.getPlatformMBeanServer();
ObjectName pmiMBean = new ObjectName(PmiConstants.MBEAN_NAME);
mServer.registerMBean(PmiCollaboratorFactory.getPmiCollaborator(), pmiMBean); // depends on control dependency: [try], data = [none]
printAllMBeans(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
Tr.error(tc, "Unable to create Perf MBean.");
FFDCFilter.processException(e, "com.ibm.ws.pmi.server.PmiRegistry", "Init");
} // depends on control dependency: [catch], data = [none]
if (tc.isEntryEnabled()) {
Tr.exit(tc, "init"); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public String getJoinColumnName(final KunderaMetadata kunderaMetadata)
{
if(joinColumnName == null && isJoinedByPrimaryKey)
{
EntityMetadata joinClassMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, targetEntity);
joinColumnName = ((AbstractAttribute)joinClassMetadata.getIdAttribute()).getJPAColumnName();
}
if(joinTableMetadata != null)
{
joinColumnName = joinTableMetadata.getJoinColumns() != null? joinTableMetadata.getJoinColumns().iterator().next():null;
}
if(isBiDirectional())
{
// Give precedence to join column name!
if(biDirectionalField.isAnnotationPresent(JoinColumn.class))
{
joinColumnName = biDirectionalField.getAnnotation(JoinColumn.class).name();
}
}
return joinColumnName !=null? joinColumnName:property.getName();
} } | public class class_name {
public String getJoinColumnName(final KunderaMetadata kunderaMetadata)
{
if(joinColumnName == null && isJoinedByPrimaryKey)
{
EntityMetadata joinClassMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, targetEntity);
joinColumnName = ((AbstractAttribute)joinClassMetadata.getIdAttribute()).getJPAColumnName();
// depends on control dependency: [if], data = [none]
}
if(joinTableMetadata != null)
{
joinColumnName = joinTableMetadata.getJoinColumns() != null? joinTableMetadata.getJoinColumns().iterator().next():null;
// depends on control dependency: [if], data = [none]
}
if(isBiDirectional())
{
// Give precedence to join column name!
if(biDirectionalField.isAnnotationPresent(JoinColumn.class))
{
joinColumnName = biDirectionalField.getAnnotation(JoinColumn.class).name();
// depends on control dependency: [if], data = [none]
}
}
return joinColumnName !=null? joinColumnName:property.getName();
} } |
public class class_name {
private AuthenticationResult handleRedirect(HttpServletRequest req,
HttpServletResponse res,
WebRequest webRequest) {
AuthenticationResult authResult;
String loginURL = getFormLoginURL(req, webRequest, webAppSecurityConfig);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "form login URL: " + loginURL);
}
authResult = new AuthenticationResult(AuthResult.REDIRECT, loginURL);
if (allowToAddCookieToResponse(webAppSecurityConfig, req)) {
postParameterHelper.save(req, res, authResult);
ReferrerURLCookieHandler referrerURLHandler = webAppSecurityConfig.createReferrerURLCookieHandler();
// referrerURLHandler.setReferrerURLCookie(authResult, getReqURL(req));
Cookie c = referrerURLHandler.createReferrerURLCookie(ReferrerURLCookieHandler.REFERRER_URL_COOKIENAME, getReqURL(req), req);
authResult.setCookie(c);
}
return authResult;
} } | public class class_name {
private AuthenticationResult handleRedirect(HttpServletRequest req,
HttpServletResponse res,
WebRequest webRequest) {
AuthenticationResult authResult;
String loginURL = getFormLoginURL(req, webRequest, webAppSecurityConfig);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "form login URL: " + loginURL); // depends on control dependency: [if], data = [none]
}
authResult = new AuthenticationResult(AuthResult.REDIRECT, loginURL);
if (allowToAddCookieToResponse(webAppSecurityConfig, req)) {
postParameterHelper.save(req, res, authResult); // depends on control dependency: [if], data = [none]
ReferrerURLCookieHandler referrerURLHandler = webAppSecurityConfig.createReferrerURLCookieHandler();
// referrerURLHandler.setReferrerURLCookie(authResult, getReqURL(req));
Cookie c = referrerURLHandler.createReferrerURLCookie(ReferrerURLCookieHandler.REFERRER_URL_COOKIENAME, getReqURL(req), req);
authResult.setCookie(c); // depends on control dependency: [if], data = [none]
}
return authResult;
} } |
public class class_name {
public int allocate(
final int typeId,
final DirectBuffer keyBuffer,
final int keyOffset,
final int keyLength,
final DirectBuffer labelBuffer,
final int labelOffset,
final int labelLength)
{
final int counterId = nextCounterId();
checkCountersCapacity(counterId);
final int recordOffset = metaDataOffset(counterId);
checkMetaDataCapacity(recordOffset);
try
{
metaDataBuffer.putInt(recordOffset + TYPE_ID_OFFSET, typeId);
metaDataBuffer.putLong(recordOffset + FREE_FOR_REUSE_DEADLINE_OFFSET, NOT_FREE_TO_REUSE);
if (null != keyBuffer)
{
final int length = Math.min(keyLength, MAX_KEY_LENGTH);
metaDataBuffer.putBytes(recordOffset + KEY_OFFSET, keyBuffer, keyOffset, length);
}
final int length = Math.min(labelLength, MAX_LABEL_LENGTH);
metaDataBuffer.putInt(recordOffset + LABEL_OFFSET, length);
metaDataBuffer.putBytes(recordOffset + LABEL_OFFSET + SIZE_OF_INT, labelBuffer, labelOffset, length);
metaDataBuffer.putIntOrdered(recordOffset, RECORD_ALLOCATED);
}
catch (final Exception ex)
{
freeList.pushInt(counterId);
LangUtil.rethrowUnchecked(ex);
}
return counterId;
} } | public class class_name {
public int allocate(
final int typeId,
final DirectBuffer keyBuffer,
final int keyOffset,
final int keyLength,
final DirectBuffer labelBuffer,
final int labelOffset,
final int labelLength)
{
final int counterId = nextCounterId();
checkCountersCapacity(counterId);
final int recordOffset = metaDataOffset(counterId);
checkMetaDataCapacity(recordOffset);
try
{
metaDataBuffer.putInt(recordOffset + TYPE_ID_OFFSET, typeId); // depends on control dependency: [try], data = [none]
metaDataBuffer.putLong(recordOffset + FREE_FOR_REUSE_DEADLINE_OFFSET, NOT_FREE_TO_REUSE); // depends on control dependency: [try], data = [none]
if (null != keyBuffer)
{
final int length = Math.min(keyLength, MAX_KEY_LENGTH);
metaDataBuffer.putBytes(recordOffset + KEY_OFFSET, keyBuffer, keyOffset, length); // depends on control dependency: [if], data = [none]
}
final int length = Math.min(labelLength, MAX_LABEL_LENGTH);
metaDataBuffer.putInt(recordOffset + LABEL_OFFSET, length); // depends on control dependency: [try], data = [none]
metaDataBuffer.putBytes(recordOffset + LABEL_OFFSET + SIZE_OF_INT, labelBuffer, labelOffset, length); // depends on control dependency: [try], data = [none]
metaDataBuffer.putIntOrdered(recordOffset, RECORD_ALLOCATED); // depends on control dependency: [try], data = [none]
}
catch (final Exception ex)
{
freeList.pushInt(counterId);
LangUtil.rethrowUnchecked(ex);
} // depends on control dependency: [catch], data = [none]
return counterId;
} } |
public class class_name {
private void chooseSampleSqlAndConf(BufferedReader br) throws IOException {
while (true) {
printInstruction("Which sample SQL schema would you like to use?");
for (int i = 0; i < getSqlConfInfos().size(); i++) {
System.out.println(" " + (i + 1) + ") " + getSqlConfInfos().get(i).getName());
System.out.println(" " + getSqlConfInfos().get(i).getDescription());
if (getSqlConfInfos().get(i).getDescription2() != null) {
System.out.println(" " + getSqlConfInfos().get(i).getDescription2());
}
System.out.println("");
}
String choice = br.readLine();
if (isBlank(choice)) {
continue;
} else {
try {
sqlConfName = getSqlConfInfos().get(Integer.parseInt(choice) - 1).getName();
System.out.println("OK, using: " + sqlConfName);
} catch (Exception e) {
System.out.println("");
continue;
}
}
break;
}
} } | public class class_name {
private void chooseSampleSqlAndConf(BufferedReader br) throws IOException {
while (true) {
printInstruction("Which sample SQL schema would you like to use?");
for (int i = 0; i < getSqlConfInfos().size(); i++) {
System.out.println(" " + (i + 1) + ") " + getSqlConfInfos().get(i).getName()); // depends on control dependency: [for], data = [i]
System.out.println(" " + getSqlConfInfos().get(i).getDescription()); // depends on control dependency: [for], data = [i]
if (getSqlConfInfos().get(i).getDescription2() != null) {
System.out.println(" " + getSqlConfInfos().get(i).getDescription2()); // depends on control dependency: [if], data = [none]
}
System.out.println(""); // depends on control dependency: [for], data = [none]
}
String choice = br.readLine();
if (isBlank(choice)) {
continue;
} else {
try {
sqlConfName = getSqlConfInfos().get(Integer.parseInt(choice) - 1).getName(); // depends on control dependency: [try], data = [none]
System.out.println("OK, using: " + sqlConfName); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
System.out.println("");
continue;
} // depends on control dependency: [catch], data = [none]
}
break;
}
} } |
public class class_name {
void addMethodInfo(final MethodInfoList methodInfoList, final Map<String, ClassInfo> classNameToClassInfo) {
for (final MethodInfo mi : methodInfoList) {
// Index method annotations
addFieldOrMethodAnnotationInfo(mi.annotationInfo, /* isField = */ false, classNameToClassInfo);
// Index method parameter annotations
if (mi.parameterAnnotationInfo != null) {
for (int i = 0; i < mi.parameterAnnotationInfo.length; i++) {
final AnnotationInfo[] paramAnnotationInfoArr = mi.parameterAnnotationInfo[i];
if (paramAnnotationInfoArr != null) {
for (int j = 0; j < paramAnnotationInfoArr.length; j++) {
final AnnotationInfo methodParamAnnotationInfo = paramAnnotationInfoArr[j];
final ClassInfo annotationClassInfo = getOrCreateClassInfo(
methodParamAnnotationInfo.getName(), ANNOTATION_CLASS_MODIFIER,
classNameToClassInfo);
annotationClassInfo.addRelatedClass(RelType.CLASSES_WITH_METHOD_PARAMETER_ANNOTATION,
this);
this.addRelatedClass(RelType.METHOD_PARAMETER_ANNOTATIONS, annotationClassInfo);
}
}
}
}
}
if (this.methodInfo == null) {
this.methodInfo = methodInfoList;
} else {
this.methodInfo.addAll(methodInfoList);
}
} } | public class class_name {
void addMethodInfo(final MethodInfoList methodInfoList, final Map<String, ClassInfo> classNameToClassInfo) {
for (final MethodInfo mi : methodInfoList) {
// Index method annotations
addFieldOrMethodAnnotationInfo(mi.annotationInfo, /* isField = */ false, classNameToClassInfo); // depends on control dependency: [for], data = [mi]
// Index method parameter annotations
if (mi.parameterAnnotationInfo != null) {
for (int i = 0; i < mi.parameterAnnotationInfo.length; i++) {
final AnnotationInfo[] paramAnnotationInfoArr = mi.parameterAnnotationInfo[i];
if (paramAnnotationInfoArr != null) {
for (int j = 0; j < paramAnnotationInfoArr.length; j++) {
final AnnotationInfo methodParamAnnotationInfo = paramAnnotationInfoArr[j];
final ClassInfo annotationClassInfo = getOrCreateClassInfo(
methodParamAnnotationInfo.getName(), ANNOTATION_CLASS_MODIFIER,
classNameToClassInfo);
annotationClassInfo.addRelatedClass(RelType.CLASSES_WITH_METHOD_PARAMETER_ANNOTATION,
this); // depends on control dependency: [for], data = [none]
this.addRelatedClass(RelType.METHOD_PARAMETER_ANNOTATIONS, annotationClassInfo); // depends on control dependency: [for], data = [none]
}
}
}
}
}
if (this.methodInfo == null) {
this.methodInfo = methodInfoList; // depends on control dependency: [if], data = [none]
} else {
this.methodInfo.addAll(methodInfoList); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public RemoveInfo addElement(TreeElement elem)
{
// if the attributes are empty then there is nothing to add to lists
ArrayList attrs = elem.getAttributeList();
if (attrs == null || attrs.size() == 0)
return emptyRemoves;
// We will track all of the elements that we are removing from the current inheritence
// list set and return those back to the caller to stash away on the stack.
RemoveInfo removes = _removes;
if (removes == null)
removes = new RemoveInfo();
// walk all of the attributes
int cnt = attrs.size();
assert (cnt > 0);
for (int i = 0; i < cnt; i++) {
TreeHtmlAttributeInfo attr = (TreeHtmlAttributeInfo) attrs.get(i);
if (attr.isOnDiv()) {
addAttribute(TreeHtmlAttributeInfo.HTML_LOCATION_DIV, attr, removes);
}
if (attr.isOnIcon()) {
addAttribute(TreeHtmlAttributeInfo.HTML_LOCATION_ICON, attr, removes);
}
if (attr.isOnSelectionLink()) {
addAttribute(TreeHtmlAttributeInfo.HTML_LOCATION_SELECTION_LINK, attr, removes);
}
}
// if we didn't remove anything then we should simply stash the array list away for next time
// and return null.
if (removes.removes.size() == 0) {
_removes = removes;
removes = null;
}
else {
_removes = null;
}
return removes;
} } | public class class_name {
public RemoveInfo addElement(TreeElement elem)
{
// if the attributes are empty then there is nothing to add to lists
ArrayList attrs = elem.getAttributeList();
if (attrs == null || attrs.size() == 0)
return emptyRemoves;
// We will track all of the elements that we are removing from the current inheritence
// list set and return those back to the caller to stash away on the stack.
RemoveInfo removes = _removes;
if (removes == null)
removes = new RemoveInfo();
// walk all of the attributes
int cnt = attrs.size();
assert (cnt > 0);
for (int i = 0; i < cnt; i++) {
TreeHtmlAttributeInfo attr = (TreeHtmlAttributeInfo) attrs.get(i);
if (attr.isOnDiv()) {
addAttribute(TreeHtmlAttributeInfo.HTML_LOCATION_DIV, attr, removes); // depends on control dependency: [if], data = [none]
}
if (attr.isOnIcon()) {
addAttribute(TreeHtmlAttributeInfo.HTML_LOCATION_ICON, attr, removes); // depends on control dependency: [if], data = [none]
}
if (attr.isOnSelectionLink()) {
addAttribute(TreeHtmlAttributeInfo.HTML_LOCATION_SELECTION_LINK, attr, removes); // depends on control dependency: [if], data = [none]
}
}
// if we didn't remove anything then we should simply stash the array list away for next time
// and return null.
if (removes.removes.size() == 0) {
_removes = removes; // depends on control dependency: [if], data = [none]
removes = null; // depends on control dependency: [if], data = [none]
}
else {
_removes = null; // depends on control dependency: [if], data = [none]
}
return removes;
} } |
public class class_name {
public CacheManagerBuilder<T> withDefaultEventListenersThreadPool(String threadPoolAlias) {
CacheEventDispatcherFactoryConfiguration config = configBuilder.findServiceByClass(CacheEventDispatcherFactoryConfiguration.class);
if (config == null) {
return new CacheManagerBuilder<>(this, configBuilder.addService(new CacheEventDispatcherFactoryConfiguration(threadPoolAlias)));
} else {
ConfigurationBuilder builder = configBuilder.removeService(config);
return new CacheManagerBuilder<>(this, builder.addService(new CacheEventDispatcherFactoryConfiguration(threadPoolAlias)));
}
} } | public class class_name {
public CacheManagerBuilder<T> withDefaultEventListenersThreadPool(String threadPoolAlias) {
CacheEventDispatcherFactoryConfiguration config = configBuilder.findServiceByClass(CacheEventDispatcherFactoryConfiguration.class);
if (config == null) {
return new CacheManagerBuilder<>(this, configBuilder.addService(new CacheEventDispatcherFactoryConfiguration(threadPoolAlias))); // depends on control dependency: [if], data = [none]
} else {
ConfigurationBuilder builder = configBuilder.removeService(config);
return new CacheManagerBuilder<>(this, builder.addService(new CacheEventDispatcherFactoryConfiguration(threadPoolAlias))); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected String parseElementAfterString(StringBuilder content, String separator)
{
String element = null;
// Find the first non escaped separator (starting from the end of the content buffer).
int index = content.lastIndexOf(separator);
while (index != -1) {
// Check if the element is found and it's not escaped.
if (!shouldEscape(content, index)) {
element = content.substring(index + separator.length()).trim();
content.delete(index, content.length());
break;
}
if (index > 0) {
index = content.lastIndexOf(separator, index - 1);
} else {
break;
}
}
return element;
} } | public class class_name {
protected String parseElementAfterString(StringBuilder content, String separator)
{
String element = null;
// Find the first non escaped separator (starting from the end of the content buffer).
int index = content.lastIndexOf(separator);
while (index != -1) {
// Check if the element is found and it's not escaped.
if (!shouldEscape(content, index)) {
element = content.substring(index + separator.length()).trim(); // depends on control dependency: [if], data = [none]
content.delete(index, content.length()); // depends on control dependency: [if], data = [none]
break;
}
if (index > 0) {
index = content.lastIndexOf(separator, index - 1); // depends on control dependency: [if], data = [none]
} else {
break;
}
}
return element;
} } |
public class class_name {
protected ObjectPool setupPool(JdbcConnectionDescriptor jcd)
{
log.info("Create new ObjectPool for DBCP connections:" + jcd);
try
{
ClassHelper.newInstance(jcd.getDriver());
}
catch (InstantiationException e)
{
log.fatal("Unable to instantiate the driver class: " + jcd.getDriver() + " in ConnectionFactoryDBCImpl!" , e);
}
catch (IllegalAccessException e)
{
log.fatal("IllegalAccessException while instantiating the driver class: " + jcd.getDriver() + " in ConnectionFactoryDBCImpl!" , e);
}
catch (ClassNotFoundException e)
{
log.fatal("Could not find the driver class : " + jcd.getDriver() + " in ConnectionFactoryDBCImpl!" , e);
}
// Get the configuration for the connection pool
GenericObjectPool.Config conf = jcd.getConnectionPoolDescriptor().getObjectPoolConfig();
// Get the additional abandoned configuration
AbandonedConfig ac = jcd.getConnectionPoolDescriptor().getAbandonedConfig();
// Create the ObjectPool that serves as the actual pool of connections.
final ObjectPool connectionPool = createConnectionPool(conf, ac);
// Create a DriverManager-based ConnectionFactory that
// the connectionPool will use to create Connection instances
final org.apache.commons.dbcp.ConnectionFactory connectionFactory;
connectionFactory = createConnectionFactory(jcd);
// Create PreparedStatement object pool (if any)
KeyedObjectPoolFactory statementPoolFactory = createStatementPoolFactory(jcd);
// Set validation query and auto-commit mode
final String validationQuery;
final boolean defaultAutoCommit;
final boolean defaultReadOnly = false;
validationQuery = jcd.getConnectionPoolDescriptor().getValidationQuery();
defaultAutoCommit = (jcd.getUseAutoCommit() != JdbcConnectionDescriptor.AUTO_COMMIT_SET_FALSE);
//
// Now we'll create the PoolableConnectionFactory, which wraps
// the "real" Connections created by the ConnectionFactory with
// the classes that implement the pooling functionality.
//
final PoolableConnectionFactory poolableConnectionFactory;
poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
connectionPool,
statementPoolFactory,
validationQuery,
defaultReadOnly,
defaultAutoCommit,
ac);
return poolableConnectionFactory.getPool();
} } | public class class_name {
protected ObjectPool setupPool(JdbcConnectionDescriptor jcd)
{
log.info("Create new ObjectPool for DBCP connections:" + jcd);
try
{
ClassHelper.newInstance(jcd.getDriver());
// depends on control dependency: [try], data = [none]
}
catch (InstantiationException e)
{
log.fatal("Unable to instantiate the driver class: " + jcd.getDriver() + " in ConnectionFactoryDBCImpl!" , e);
}
// depends on control dependency: [catch], data = [none]
catch (IllegalAccessException e)
{
log.fatal("IllegalAccessException while instantiating the driver class: " + jcd.getDriver() + " in ConnectionFactoryDBCImpl!" , e);
}
// depends on control dependency: [catch], data = [none]
catch (ClassNotFoundException e)
{
log.fatal("Could not find the driver class : " + jcd.getDriver() + " in ConnectionFactoryDBCImpl!" , e);
}
// depends on control dependency: [catch], data = [none]
// Get the configuration for the connection pool
GenericObjectPool.Config conf = jcd.getConnectionPoolDescriptor().getObjectPoolConfig();
// Get the additional abandoned configuration
AbandonedConfig ac = jcd.getConnectionPoolDescriptor().getAbandonedConfig();
// Create the ObjectPool that serves as the actual pool of connections.
final ObjectPool connectionPool = createConnectionPool(conf, ac);
// Create a DriverManager-based ConnectionFactory that
// the connectionPool will use to create Connection instances
final org.apache.commons.dbcp.ConnectionFactory connectionFactory;
connectionFactory = createConnectionFactory(jcd);
// Create PreparedStatement object pool (if any)
KeyedObjectPoolFactory statementPoolFactory = createStatementPoolFactory(jcd);
// Set validation query and auto-commit mode
final String validationQuery;
final boolean defaultAutoCommit;
final boolean defaultReadOnly = false;
validationQuery = jcd.getConnectionPoolDescriptor().getValidationQuery();
defaultAutoCommit = (jcd.getUseAutoCommit() != JdbcConnectionDescriptor.AUTO_COMMIT_SET_FALSE);
//
// Now we'll create the PoolableConnectionFactory, which wraps
// the "real" Connections created by the ConnectionFactory with
// the classes that implement the pooling functionality.
//
final PoolableConnectionFactory poolableConnectionFactory;
poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
connectionPool,
statementPoolFactory,
validationQuery,
defaultReadOnly,
defaultAutoCommit,
ac);
return poolableConnectionFactory.getPool();
} } |
public class class_name {
public GetSdkTypesResult withItems(SdkType... items) {
if (this.items == null) {
setItems(new java.util.ArrayList<SdkType>(items.length));
}
for (SdkType ele : items) {
this.items.add(ele);
}
return this;
} } | public class class_name {
public GetSdkTypesResult withItems(SdkType... items) {
if (this.items == null) {
setItems(new java.util.ArrayList<SdkType>(items.length)); // depends on control dependency: [if], data = [none]
}
for (SdkType ele : items) {
this.items.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public void checkServerState(final AsyncCallback<Boolean> callback, final String standBy, final String success) {
// :read-attribute(name=process-type)
final ModelNode operation = new ModelNode();
operation.get(OP).set(READ_ATTRIBUTE_OPERATION);
operation.get(NAME).set("server-state");
operation.get(ADDRESS).setEmptyList();
dispatchAsync.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() {
@Override
public void onSuccess(DMRResponse result) {
ModelNode response = result.get();
if (response.isFailure()) {
callback.onFailure(new RuntimeException("Failed to poll server state"));
} else {
// TODO: only works when this response changes the reload state
String outcome = response.get(RESULT).asString();
boolean keepRunning = !outcome.equalsIgnoreCase("running");//reloadState.isStaleModel();
if (!keepRunning) {
// clear state
reloadState.reset();
Console.info(Console.MESSAGES.successful(success));
// clear reload state
eventBus.fireEvent(new ReloadEvent());
}
callback.onSuccess(keepRunning);
}
}
@Override
public void onFailure(Throwable caught) {
Console.getMessageCenter().notify(new Message(standBy, caught.getMessage(), Message.Severity.Warning));
}
});
} } | public class class_name {
public void checkServerState(final AsyncCallback<Boolean> callback, final String standBy, final String success) {
// :read-attribute(name=process-type)
final ModelNode operation = new ModelNode();
operation.get(OP).set(READ_ATTRIBUTE_OPERATION);
operation.get(NAME).set("server-state");
operation.get(ADDRESS).setEmptyList();
dispatchAsync.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() {
@Override
public void onSuccess(DMRResponse result) {
ModelNode response = result.get();
if (response.isFailure()) {
callback.onFailure(new RuntimeException("Failed to poll server state")); // depends on control dependency: [if], data = [none]
} else {
// TODO: only works when this response changes the reload state
String outcome = response.get(RESULT).asString();
boolean keepRunning = !outcome.equalsIgnoreCase("running");//reloadState.isStaleModel();
if (!keepRunning) {
// clear state
reloadState.reset(); // depends on control dependency: [if], data = [none]
Console.info(Console.MESSAGES.successful(success)); // depends on control dependency: [if], data = [none]
// clear reload state
eventBus.fireEvent(new ReloadEvent()); // depends on control dependency: [if], data = [none]
}
callback.onSuccess(keepRunning); // depends on control dependency: [if], data = [none]
}
}
@Override
public void onFailure(Throwable caught) {
Console.getMessageCenter().notify(new Message(standBy, caught.getMessage(), Message.Severity.Warning));
}
});
} } |
public class class_name {
public java.util.List<ScheduledInstance> getScheduledInstanceSet() {
if (scheduledInstanceSet == null) {
scheduledInstanceSet = new com.amazonaws.internal.SdkInternalList<ScheduledInstance>();
}
return scheduledInstanceSet;
} } | public class class_name {
public java.util.List<ScheduledInstance> getScheduledInstanceSet() {
if (scheduledInstanceSet == null) {
scheduledInstanceSet = new com.amazonaws.internal.SdkInternalList<ScheduledInstance>(); // depends on control dependency: [if], data = [none]
}
return scheduledInstanceSet;
} } |
public class class_name {
private void deleteApplication() {
ApplicationDefinition appDef = m_client.getAppDef(m_config.app);
if (appDef != null) {
m_logger.info("Deleting existing application: {}", appDef.getAppName());
m_client.deleteApplication(appDef.getAppName(), appDef.getKey());
}
} } | public class class_name {
private void deleteApplication() {
ApplicationDefinition appDef = m_client.getAppDef(m_config.app);
if (appDef != null) {
m_logger.info("Deleting existing application: {}", appDef.getAppName());
// depends on control dependency: [if], data = [none]
m_client.deleteApplication(appDef.getAppName(), appDef.getKey());
// depends on control dependency: [if], data = [(appDef]
}
} } |
public class class_name {
public static int lengthOfCodePointSafe(Slice utf8, int position)
{
int length = lengthOfCodePointFromStartByteSafe(utf8.getByte(position));
if (length < 0) {
return -length;
}
if (length == 1 || position + 1 >= utf8.length() || !isContinuationByte(utf8.getByteUnchecked(position + 1))) {
return 1;
}
if (length == 2 || position + 2 >= utf8.length() || !isContinuationByte(utf8.getByteUnchecked(position + 2))) {
return 2;
}
if (length == 3 || position + 3 >= utf8.length() || !isContinuationByte(utf8.getByteUnchecked(position + 3))) {
return 3;
}
if (length == 4 || position + 4 >= utf8.length() || !isContinuationByte(utf8.getByteUnchecked(position + 4))) {
return 4;
}
if (length == 5 || position + 5 >= utf8.length() || !isContinuationByte(utf8.getByteUnchecked(position + 5))) {
return 5;
}
if (length == 6) {
return 6;
}
return 1;
} } | public class class_name {
public static int lengthOfCodePointSafe(Slice utf8, int position)
{
int length = lengthOfCodePointFromStartByteSafe(utf8.getByte(position));
if (length < 0) {
return -length; // depends on control dependency: [if], data = [none]
}
if (length == 1 || position + 1 >= utf8.length() || !isContinuationByte(utf8.getByteUnchecked(position + 1))) {
return 1; // depends on control dependency: [if], data = [none]
}
if (length == 2 || position + 2 >= utf8.length() || !isContinuationByte(utf8.getByteUnchecked(position + 2))) {
return 2; // depends on control dependency: [if], data = [none]
}
if (length == 3 || position + 3 >= utf8.length() || !isContinuationByte(utf8.getByteUnchecked(position + 3))) {
return 3; // depends on control dependency: [if], data = [none]
}
if (length == 4 || position + 4 >= utf8.length() || !isContinuationByte(utf8.getByteUnchecked(position + 4))) {
return 4; // depends on control dependency: [if], data = [none]
}
if (length == 5 || position + 5 >= utf8.length() || !isContinuationByte(utf8.getByteUnchecked(position + 5))) {
return 5; // depends on control dependency: [if], data = [none]
}
if (length == 6) {
return 6; // depends on control dependency: [if], data = [none]
}
return 1;
} } |
public class class_name {
private void convertJdkPath(Launcher launcher, EnvVars extendedEnv) {
String separator = launcher.isUnix() ? "/" : "\\";
String java_home = extendedEnv.get("JAVA_HOME");
if (StringUtils.isNotEmpty(java_home)) {
if (!StringUtils.endsWith(java_home, separator)) {
java_home += separator;
}
extendedEnv.put("PATH+JDK", java_home + "bin");
}
} } | public class class_name {
private void convertJdkPath(Launcher launcher, EnvVars extendedEnv) {
String separator = launcher.isUnix() ? "/" : "\\";
String java_home = extendedEnv.get("JAVA_HOME");
if (StringUtils.isNotEmpty(java_home)) {
if (!StringUtils.endsWith(java_home, separator)) {
java_home += separator; // depends on control dependency: [if], data = [none]
}
extendedEnv.put("PATH+JDK", java_home + "bin"); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static String print(Constructor constructor) {
final StringBuilder builder = new StringBuilder(constructor.name);
if (! constructor.args.isEmpty()) {
builder.append("(");
boolean first = true;
for (Arg arg : constructor.args) {
if (first) {
first = false;
} else {
builder.append(", ");
}
builder.append(print(arg));
}
builder.append(")");
}
return builder.toString();
} } | public class class_name {
public static String print(Constructor constructor) {
final StringBuilder builder = new StringBuilder(constructor.name);
if (! constructor.args.isEmpty()) {
builder.append("("); // depends on control dependency: [if], data = [none]
boolean first = true;
for (Arg arg : constructor.args) {
if (first) {
first = false; // depends on control dependency: [if], data = [none]
} else {
builder.append(", "); // depends on control dependency: [if], data = [none]
}
builder.append(print(arg)); // depends on control dependency: [for], data = [arg]
}
builder.append(")"); // depends on control dependency: [if], data = [none]
}
return builder.toString();
} } |
public class class_name {
protected void loadChildExecutionsFromCache(ExecutionEntity execution, List<ExecutionEntity> childExecutions) {
List<ExecutionEntity> childrenOfThisExecution = execution.getExecutions();
if(childrenOfThisExecution != null) {
childExecutions.addAll(childrenOfThisExecution);
for (ExecutionEntity child : childrenOfThisExecution) {
loadChildExecutionsFromCache(child, childExecutions);
}
}
} } | public class class_name {
protected void loadChildExecutionsFromCache(ExecutionEntity execution, List<ExecutionEntity> childExecutions) {
List<ExecutionEntity> childrenOfThisExecution = execution.getExecutions();
if(childrenOfThisExecution != null) {
childExecutions.addAll(childrenOfThisExecution); // depends on control dependency: [if], data = [(childrenOfThisExecution]
for (ExecutionEntity child : childrenOfThisExecution) {
loadChildExecutionsFromCache(child, childExecutions); // depends on control dependency: [for], data = [child]
}
}
} } |
public class class_name {
public void checkAndCreateTable(String tabName, String colFamName) throws IOException {
HBaseAdmin hba;
try {
hba = new HBaseAdmin(this.getHbcfg());
if (hba.tableExists(tabName) == false) {
logger.debug("creating table " + tabName);
final HTableDescriptor tableDescriptor = new HTableDescriptor(tabName);
final HColumnDescriptor columnDescriptor = new HColumnDescriptor(colFamName);
columnDescriptor.setMaxVersions(MAX_VALUE);
tableDescriptor.addFamily(columnDescriptor);
hba.createTable(tableDescriptor);
} else {
logger.debug("already existent table " + tabName);
}
hba.close();
} catch (MasterNotRunningException e) {
throw new IOException(e);
} catch (ZooKeeperConnectionException e) {
throw new IOException(e);
} catch (IOException e) {
throw new IOException(e);
}
} } | public class class_name {
public void checkAndCreateTable(String tabName, String colFamName) throws IOException {
HBaseAdmin hba;
try {
hba = new HBaseAdmin(this.getHbcfg());
if (hba.tableExists(tabName) == false) {
logger.debug("creating table " + tabName); // depends on control dependency: [if], data = [none]
final HTableDescriptor tableDescriptor = new HTableDescriptor(tabName);
final HColumnDescriptor columnDescriptor = new HColumnDescriptor(colFamName);
columnDescriptor.setMaxVersions(MAX_VALUE); // depends on control dependency: [if], data = [none]
tableDescriptor.addFamily(columnDescriptor); // depends on control dependency: [if], data = [none]
hba.createTable(tableDescriptor); // depends on control dependency: [if], data = [none]
} else {
logger.debug("already existent table " + tabName); // depends on control dependency: [if], data = [none]
}
hba.close();
} catch (MasterNotRunningException e) {
throw new IOException(e);
} catch (ZooKeeperConnectionException e) {
throw new IOException(e);
} catch (IOException e) {
throw new IOException(e);
}
} } |
public class class_name {
@Override
public synchronized void start() {
if (running) {
return;
}
checkState(raftAgent != null);
checkState(initialized);
raftAgent.start();
running = true;
} } | public class class_name {
@Override
public synchronized void start() {
if (running) {
return; // depends on control dependency: [if], data = [none]
}
checkState(raftAgent != null);
checkState(initialized);
raftAgent.start();
running = true;
} } |
public class class_name {
public DatabaseAccessConfiguration swap(final DataSource dataSource) {
DataSourcePropertyProvider provider = DataSourcePropertyProviderLoader.getProvider(dataSource);
try {
String url = (String) findGetterMethod(dataSource, provider.getURLPropertyName()).invoke(dataSource);
String username = (String) findGetterMethod(dataSource, provider.getUsernamePropertyName()).invoke(dataSource);
String password = (String) findGetterMethod(dataSource, provider.getPasswordPropertyName()).invoke(dataSource);
return new DatabaseAccessConfiguration(url, username, password);
} catch (final ReflectiveOperationException ex) {
throw new ShardingException("Cannot swap data source type: `%s`, please provide an implementation from SPI `%s`",
dataSource.getClass().getName(), DataSourcePropertyProvider.class.getName());
}
} } | public class class_name {
public DatabaseAccessConfiguration swap(final DataSource dataSource) {
DataSourcePropertyProvider provider = DataSourcePropertyProviderLoader.getProvider(dataSource);
try {
String url = (String) findGetterMethod(dataSource, provider.getURLPropertyName()).invoke(dataSource);
String username = (String) findGetterMethod(dataSource, provider.getUsernamePropertyName()).invoke(dataSource);
String password = (String) findGetterMethod(dataSource, provider.getPasswordPropertyName()).invoke(dataSource);
return new DatabaseAccessConfiguration(url, username, password); // depends on control dependency: [try], data = [none]
} catch (final ReflectiveOperationException ex) {
throw new ShardingException("Cannot swap data source type: `%s`, please provide an implementation from SPI `%s`",
dataSource.getClass().getName(), DataSourcePropertyProvider.class.getName());
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static DML getUnoptimizedInstance(SourceRange sourceRange,
Operation... operations) {
// Build a duplicate list to "flatten" the DML block.
List<Operation> list = new LinkedList<Operation>();
// Inline operations from referenced DML blocks.
for (Operation op : operations) {
if (op instanceof DML) {
DML dml = (DML) op;
for (Operation dmlOp : dml.ops) {
list.add(dmlOp);
}
} else {
list.add(op);
}
}
Operation[] dmlOps = list.toArray(new Operation[list.size()]);
return new DML(sourceRange, dmlOps);
} } | public class class_name {
public static DML getUnoptimizedInstance(SourceRange sourceRange,
Operation... operations) {
// Build a duplicate list to "flatten" the DML block.
List<Operation> list = new LinkedList<Operation>();
// Inline operations from referenced DML blocks.
for (Operation op : operations) {
if (op instanceof DML) {
DML dml = (DML) op;
for (Operation dmlOp : dml.ops) {
list.add(dmlOp); // depends on control dependency: [for], data = [dmlOp]
}
} else {
list.add(op); // depends on control dependency: [if], data = [none]
}
}
Operation[] dmlOps = list.toArray(new Operation[list.size()]);
return new DML(sourceRange, dmlOps);
} } |
public class class_name {
protected AstNode parseCreateProcedureStatement( DdlTokenStream tokens,
AstNode parentNode ) throws ParsingException {
assert tokens != null;
assert parentNode != null;
markStartOfStatement(tokens);
/* ----------------------------------------------------------------------
CREATE [ OR REPLACE ] PROCEDURE [ schema. ] procedure_name
[ ( parameter_declaration [, parameter_declaration ] ) ]
[ AUTHID { CURRENT_USER | DEFINER ]
{ IS | AS }
{ [ declare_section ] body | call_spec | EXTERNAL} ;
call_spec = LANGUAGE { Java_declaration | C_declaration }
Java_declaration = JAVA NAME string
C_declaration =
C [ NAME name ]
LIBRARY lib_name
[ AGENT IN (argument[, argument ]...) ]
[ WITH CONTEXT ]
[ PARAMETERS (parameter[, parameter ]...) ]
parameter_declaration = parameter_name [ IN | { { OUT | { IN OUT }} [ NOCOPY ] } ] datatype [ { := | DEFAULT } expression ]
---------------------------------------------------------------------- */
boolean isReplace = tokens.canConsume(STMT_CREATE_OR_REPLACE_PROCEDURE);
tokens.canConsume(STMT_CREATE_PROCEDURE);
String name = parseName(tokens);
AstNode node = nodeFactory().node(name, parentNode, TYPE_CREATE_PROCEDURE_STATEMENT);
if (isReplace) {
// TODO: SET isReplace = TRUE to node (possibly a cnd mixin of "replaceable"
}
boolean ok = parseParameters(tokens, node);
if (ok) {
if (tokens.canConsume("AUTHID")) {
if (tokens.canConsume("CURRENT_USER")) {
node.setProperty(AUTHID_VALUE, "AUTHID CURRENT_USER");
} else {
tokens.consume("DEFINER");
node.setProperty(AUTHID_VALUE, "DEFINER");
}
}
}
parseUntilFwdSlash(tokens, false);
tokens.canConsume("/");
markEndOfStatement(tokens, node);
return node;
} } | public class class_name {
protected AstNode parseCreateProcedureStatement( DdlTokenStream tokens,
AstNode parentNode ) throws ParsingException {
assert tokens != null;
assert parentNode != null;
markStartOfStatement(tokens);
/* ----------------------------------------------------------------------
CREATE [ OR REPLACE ] PROCEDURE [ schema. ] procedure_name
[ ( parameter_declaration [, parameter_declaration ] ) ]
[ AUTHID { CURRENT_USER | DEFINER ]
{ IS | AS }
{ [ declare_section ] body | call_spec | EXTERNAL} ;
call_spec = LANGUAGE { Java_declaration | C_declaration }
Java_declaration = JAVA NAME string
C_declaration =
C [ NAME name ]
LIBRARY lib_name
[ AGENT IN (argument[, argument ]...) ]
[ WITH CONTEXT ]
[ PARAMETERS (parameter[, parameter ]...) ]
parameter_declaration = parameter_name [ IN | { { OUT | { IN OUT }} [ NOCOPY ] } ] datatype [ { := | DEFAULT } expression ]
---------------------------------------------------------------------- */
boolean isReplace = tokens.canConsume(STMT_CREATE_OR_REPLACE_PROCEDURE);
tokens.canConsume(STMT_CREATE_PROCEDURE);
String name = parseName(tokens);
AstNode node = nodeFactory().node(name, parentNode, TYPE_CREATE_PROCEDURE_STATEMENT);
if (isReplace) {
// TODO: SET isReplace = TRUE to node (possibly a cnd mixin of "replaceable"
}
boolean ok = parseParameters(tokens, node);
if (ok) {
if (tokens.canConsume("AUTHID")) {
if (tokens.canConsume("CURRENT_USER")) {
node.setProperty(AUTHID_VALUE, "AUTHID CURRENT_USER"); // depends on control dependency: [if], data = [none]
} else {
tokens.consume("DEFINER"); // depends on control dependency: [if], data = [none]
node.setProperty(AUTHID_VALUE, "DEFINER"); // depends on control dependency: [if], data = [none]
}
}
}
parseUntilFwdSlash(tokens, false);
tokens.canConsume("/");
markEndOfStatement(tokens, node);
return node;
} } |
public class class_name {
@Override
public boolean isUserInRole(String role, IExtendedRequest req) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "isUserInRole role = " + role);
}
if (role == null)
return false;
Subject subject = subjectManager.getCallerSubject();
if (subject == null) {
return false;
}
return wasch.isUserInRole(role, req, subject);
} } | public class class_name {
@Override
public boolean isUserInRole(String role, IExtendedRequest req) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "isUserInRole role = " + role); // depends on control dependency: [if], data = [none]
}
if (role == null)
return false;
Subject subject = subjectManager.getCallerSubject();
if (subject == null) {
return false; // depends on control dependency: [if], data = [none]
}
return wasch.isUserInRole(role, req, subject);
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.