code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public static DiscreteVariable sequence(String name, int size) {
List<Integer> values = null;
if (sequenceCache.containsKey(size)) {
values = sequenceCache.get(size);
} else {
values = Lists.newArrayList();
for (int i = 0; i < size; i++) {
values.add(i);
}
values = ImmutableList.copyOf(values);
sequenceCache.put(size, values);
}
return new DiscreteVariable(name, values);
} } | public class class_name {
public static DiscreteVariable sequence(String name, int size) {
List<Integer> values = null;
if (sequenceCache.containsKey(size)) {
values = sequenceCache.get(size); // depends on control dependency: [if], data = [none]
} else {
values = Lists.newArrayList(); // depends on control dependency: [if], data = [none]
for (int i = 0; i < size; i++) {
values.add(i); // depends on control dependency: [for], data = [i]
}
values = ImmutableList.copyOf(values); // depends on control dependency: [if], data = [none]
sequenceCache.put(size, values); // depends on control dependency: [if], data = [none]
}
return new DiscreteVariable(name, values);
} } |
public class class_name {
int insert(long start, long end, int n) {
splitAt(start);
splitAt(end);
int peak = 0;
for (Map.Entry<Long, int[]> e : data.tailMap(start).headMap(end).entrySet()) {
peak = max(peak, e.getValue()[0] += n);
}
return peak;
} } | public class class_name {
int insert(long start, long end, int n) {
splitAt(start);
splitAt(end);
int peak = 0;
for (Map.Entry<Long, int[]> e : data.tailMap(start).headMap(end).entrySet()) {
peak = max(peak, e.getValue()[0] += n); // depends on control dependency: [for], data = [e]
}
return peak;
} } |
public class class_name {
public Boolean send(String message) {
TextWebSocketFrame frame = new TextWebSocketFrame(message);
if (getCh() != null) {
getCh().writeAndFlush(frame);
return true;
}
return false;
} } | public class class_name {
public Boolean send(String message) {
TextWebSocketFrame frame = new TextWebSocketFrame(message);
if (getCh() != null) {
getCh().writeAndFlush(frame); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public ServiceReference<V> putReferenceIfAbsent(K key, ServiceReference<V> reference) {
// If the key is null we can't do anything
if (key == null)
return null;
if (reference == null) {
// If the reference is null we can't add it to the map but we could still return an existing on if there was one so check this
return getReference(key);
}
ConcurrentServiceReferenceElement<V> element = new ConcurrentServiceReferenceElement<V>(referenceName, reference);
ConcurrentServiceReferenceElement<V> existingEntry = elementMap.putIfAbsent(key, element);
if (existingEntry == null) {
return null;
} else {
return existingEntry.getReference();
}
} } | public class class_name {
public ServiceReference<V> putReferenceIfAbsent(K key, ServiceReference<V> reference) {
// If the key is null we can't do anything
if (key == null)
return null;
if (reference == null) {
// If the reference is null we can't add it to the map but we could still return an existing on if there was one so check this
return getReference(key); // depends on control dependency: [if], data = [none]
}
ConcurrentServiceReferenceElement<V> element = new ConcurrentServiceReferenceElement<V>(referenceName, reference);
ConcurrentServiceReferenceElement<V> existingEntry = elementMap.putIfAbsent(key, element);
if (existingEntry == null) {
return null; // depends on control dependency: [if], data = [none]
} else {
return existingEntry.getReference(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public final void setItsDate(final Date pItsDate) {
if (pItsDate == null) {
this.itsDate = null;
} else {
this.itsDate = new Date(pItsDate.getTime());
}
} } | public class class_name {
public final void setItsDate(final Date pItsDate) {
if (pItsDate == null) {
this.itsDate = null; // depends on control dependency: [if], data = [none]
} else {
this.itsDate = new Date(pItsDate.getTime()); // depends on control dependency: [if], data = [(pItsDate]
}
} } |
public class class_name {
protected static String getPartialEndedWord(String str, int pos){
assert(pos < str.length() && pos >= 0);
if( posIsAtWord(str, pos) ){
int prevSpace = findLastNonLetterOrDigit(str, pos);
return str.substring(prevSpace+1, pos+1);
}
return null;
} } | public class class_name {
protected static String getPartialEndedWord(String str, int pos){
assert(pos < str.length() && pos >= 0);
if( posIsAtWord(str, pos) ){
int prevSpace = findLastNonLetterOrDigit(str, pos);
return str.substring(prevSpace+1, pos+1); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public static void scheduleAsync(@NonNull final JobRequest.Builder baseBuilder, final long startMs, final long endMs,
@NonNull final JobRequest.JobScheduledCallback callback) {
JobPreconditions.checkNotNull(callback);
JobConfig.getExecutorService().execute(new Runnable() {
@Override
public void run() {
try {
int jobId = schedule(baseBuilder, startMs, endMs);
callback.onJobScheduled(jobId, baseBuilder.mTag, null);
} catch (Exception e) {
callback.onJobScheduled(JobRequest.JobScheduledCallback.JOB_ID_ERROR, baseBuilder.mTag, e);
}
}
});
} } | public class class_name {
public static void scheduleAsync(@NonNull final JobRequest.Builder baseBuilder, final long startMs, final long endMs,
@NonNull final JobRequest.JobScheduledCallback callback) {
JobPreconditions.checkNotNull(callback);
JobConfig.getExecutorService().execute(new Runnable() {
@Override
public void run() {
try {
int jobId = schedule(baseBuilder, startMs, endMs);
callback.onJobScheduled(jobId, baseBuilder.mTag, null); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
callback.onJobScheduled(JobRequest.JobScheduledCallback.JOB_ID_ERROR, baseBuilder.mTag, e);
} // depends on control dependency: [catch], data = [none]
}
});
} } |
public class class_name {
private <T> BindingInject<T> findBean(Key<T> key)
{
for (InjectProvider provider : _providerList) {
BindingInject<T> bean = (BindingInject) provider.lookup(key.rawClass());
if (bean != null) {
return bean;
}
}
return null;
} } | public class class_name {
private <T> BindingInject<T> findBean(Key<T> key)
{
for (InjectProvider provider : _providerList) {
BindingInject<T> bean = (BindingInject) provider.lookup(key.rawClass());
if (bean != null) {
return bean; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public static final KeyPressHandler getUpperAsciiKeyPressHandler() { // NOPMD it's thread save!
if (HandlerFactory.upperAsciiKeyPressHandler == null) {
synchronized (UpperAsciiKeyPressHandler.class) {
if (HandlerFactory.upperAsciiKeyPressHandler == null) {
HandlerFactory.upperAsciiKeyPressHandler = new UpperAsciiKeyPressHandler();
}
}
}
return HandlerFactory.upperAsciiKeyPressHandler;
} } | public class class_name {
public static final KeyPressHandler getUpperAsciiKeyPressHandler() { // NOPMD it's thread save!
if (HandlerFactory.upperAsciiKeyPressHandler == null) {
synchronized (UpperAsciiKeyPressHandler.class) { // depends on control dependency: [if], data = [none]
if (HandlerFactory.upperAsciiKeyPressHandler == null) {
HandlerFactory.upperAsciiKeyPressHandler = new UpperAsciiKeyPressHandler(); // depends on control dependency: [if], data = [none]
}
}
}
return HandlerFactory.upperAsciiKeyPressHandler;
} } |
public class class_name {
public SPIStatistic getStatistic(int id) {
for (int i = 0; i < _stats.length; i++) {
if (_stats[i] != null && _stats[i].getId() == id) {
return _stats[i];
/*
* ~~~~~~~~~~~~~~ commented ~~~~~~~~~~~~~~
* // do not check as it is done in individual statistic type
* if (_stats[i].isEnabled())
* return _stats[i];
* else
* return null;
* ~~~~~~~~~~~~~~ commented ~~~~~~~~~~~~~~
*/
}
}
return null;
} } | public class class_name {
public SPIStatistic getStatistic(int id) {
for (int i = 0; i < _stats.length; i++) {
if (_stats[i] != null && _stats[i].getId() == id) {
return _stats[i]; // depends on control dependency: [if], data = [none]
/*
* ~~~~~~~~~~~~~~ commented ~~~~~~~~~~~~~~
* // do not check as it is done in individual statistic type
* if (_stats[i].isEnabled())
* return _stats[i];
* else
* return null;
* ~~~~~~~~~~~~~~ commented ~~~~~~~~~~~~~~
*/
}
}
return null;
} } |
public class class_name {
@Override
public View findViewByPosition(int position) {
final int childCount = getChildCount();
if (childCount == 0) {
return null;
}
final int firstChild = getPosition(getChildAt(0));
final int viewPosition = position - firstChild;
if (viewPosition >= 0 && viewPosition < childCount) {
return getChildAt(viewPosition);
}
return null;
} } | public class class_name {
@Override
public View findViewByPosition(int position) {
final int childCount = getChildCount();
if (childCount == 0) {
return null; // depends on control dependency: [if], data = [none]
}
final int firstChild = getPosition(getChildAt(0));
final int viewPosition = position - firstChild;
if (viewPosition >= 0 && viewPosition < childCount) {
return getChildAt(viewPosition); // depends on control dependency: [if], data = [(viewPosition]
}
return null;
} } |
public class class_name {
@Pure
public SortedSet<Integer> toSortedSet() {
final SortedSet<Integer> theset = new TreeSet<>();
if (this.values != null) {
for (int idxStart = 0; idxStart < this.values.length - 1; idxStart += 2) {
for (int n = this.values[idxStart]; n <= this.values[idxStart + 1]; ++n) {
theset.add(n);
}
}
}
return theset;
} } | public class class_name {
@Pure
public SortedSet<Integer> toSortedSet() {
final SortedSet<Integer> theset = new TreeSet<>();
if (this.values != null) {
for (int idxStart = 0; idxStart < this.values.length - 1; idxStart += 2) {
for (int n = this.values[idxStart]; n <= this.values[idxStart + 1]; ++n) {
theset.add(n); // depends on control dependency: [for], data = [n]
}
}
}
return theset;
} } |
public class class_name {
public void setTerminationPolicies(java.util.Collection<String> terminationPolicies) {
if (terminationPolicies == null) {
this.terminationPolicies = null;
return;
}
this.terminationPolicies = new com.amazonaws.internal.SdkInternalList<String>(terminationPolicies);
} } | public class class_name {
public void setTerminationPolicies(java.util.Collection<String> terminationPolicies) {
if (terminationPolicies == null) {
this.terminationPolicies = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.terminationPolicies = new com.amazonaws.internal.SdkInternalList<String>(terminationPolicies);
} } |
public class class_name {
public DelayStat findRealtimeDelayStat(Long pipelineId) {
Assert.assertNotNull(pipelineId);
DelayStatDO delayStatDO = delayStatDao.findRealtimeDelayStat(pipelineId);
DelayStat delayStat = new DelayStat();
if (delayStatDO != null) {
delayStat = delayStatDOToModel(delayStatDO);
}
return delayStat;
} } | public class class_name {
public DelayStat findRealtimeDelayStat(Long pipelineId) {
Assert.assertNotNull(pipelineId);
DelayStatDO delayStatDO = delayStatDao.findRealtimeDelayStat(pipelineId);
DelayStat delayStat = new DelayStat();
if (delayStatDO != null) {
delayStat = delayStatDOToModel(delayStatDO); // depends on control dependency: [if], data = [(delayStatDO]
}
return delayStat;
} } |
public class class_name {
private Page findIndexPage(final SecurityContext securityContext, List<Page> pages, final EditMode edit) throws FrameworkException {
final PropertyKey<Integer> positionKey = StructrApp.key(Page.class, "position");
if (pages == null) {
pages = StructrApp.getInstance(securityContext).nodeQuery(Page.class).getAsList();
Collections.sort(pages, new GraphObjectComparator(positionKey, GraphObjectComparator.ASCENDING));
}
for (Page page : pages) {
if (securityContext.isVisible(page) && page.getProperty(positionKey) != null && ((EditMode.CONTENT.equals(edit) || isVisibleForSite(securityContext.getRequest(), page)) || (page.getEnableBasicAuth() && page.isVisibleToAuthenticatedUsers()))) {
return page;
}
}
return null;
} } | public class class_name {
private Page findIndexPage(final SecurityContext securityContext, List<Page> pages, final EditMode edit) throws FrameworkException {
final PropertyKey<Integer> positionKey = StructrApp.key(Page.class, "position");
if (pages == null) {
pages = StructrApp.getInstance(securityContext).nodeQuery(Page.class).getAsList();
Collections.sort(pages, new GraphObjectComparator(positionKey, GraphObjectComparator.ASCENDING));
}
for (Page page : pages) {
if (securityContext.isVisible(page) && page.getProperty(positionKey) != null && ((EditMode.CONTENT.equals(edit) || isVisibleForSite(securityContext.getRequest(), page)) || (page.getEnableBasicAuth() && page.isVisibleToAuthenticatedUsers()))) {
return page; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
@SuppressWarnings("WeakerAccess")
protected final void injectVariables(Map<String, String> variables, By element) {
if (element instanceof VariablesAware) {
((VariablesAware) element).setVariables(variables);
}
} } | public class class_name {
@SuppressWarnings("WeakerAccess")
protected final void injectVariables(Map<String, String> variables, By element) {
if (element instanceof VariablesAware) {
((VariablesAware) element).setVariables(variables); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void run() {
try {
String archiveName = "testApp-" + (++appCount) + ".war";
try {
WebArchive app = ShrinkWrap.create(WebArchive.class, archiveName);
for (Class<?> clazz : classes) {
app = app.addClass(clazz);
}
RemoteFile logFile = server.getDefaultLogFile();
server.setMarkToEndOfLog(logFile);
ShrinkHelper.exportArtifact(app, "tmp/apps");
server.copyFileToLibertyServerRoot("tmp/apps", "dropins", archiveName);
for (String stringToFind : stringsToFind) {
String logLine = server.waitForStringInLogUsingMark(stringToFind + "|" + APP_START_CODE + "|" + APP_FAIL_CODE);
assertThat(logLine, Matchers.containsPattern(stringToFind));
}
} finally {
server.deleteFileFromLibertyServerRoot("dropins/" + archiveName);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
} } | public class class_name {
public void run() {
try {
String archiveName = "testApp-" + (++appCount) + ".war";
try {
WebArchive app = ShrinkWrap.create(WebArchive.class, archiveName);
for (Class<?> clazz : classes) {
app = app.addClass(clazz); // depends on control dependency: [for], data = [clazz]
}
RemoteFile logFile = server.getDefaultLogFile();
server.setMarkToEndOfLog(logFile); // depends on control dependency: [try], data = [none]
ShrinkHelper.exportArtifact(app, "tmp/apps"); // depends on control dependency: [try], data = [none]
server.copyFileToLibertyServerRoot("tmp/apps", "dropins", archiveName); // depends on control dependency: [try], data = [none]
for (String stringToFind : stringsToFind) {
String logLine = server.waitForStringInLogUsingMark(stringToFind + "|" + APP_START_CODE + "|" + APP_FAIL_CODE);
assertThat(logLine, Matchers.containsPattern(stringToFind)); // depends on control dependency: [for], data = [stringToFind]
}
} finally {
server.deleteFileFromLibertyServerRoot("dropins/" + archiveName);
}
} catch (Exception e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected String createDefaultLogLine(String msg, int level, Date date, StackTraceElement trace) {
String[] levels = {"NON", "ERR", "WRN", "INF", "DBG", "DB2", "INT"};
StringBuffer ret = new StringBuffer(128);
ret.append("<").append(levels[level]).append("> ");
SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss.SSS");
ret.append("[").append(df.format(date)).append("] ");
Thread thread = Thread.currentThread();
ret.append("[").append(thread.getThreadGroup().getName());
ret.append("/").append(thread.getName()).append("] ");
String classname = trace.getClassName();
String hbciname = "org.kapott.hbci.";
if (classname != null && classname.startsWith(hbciname))
ret.append(classname.substring((hbciname).length())).append(": ");
if (msg == null)
msg = "";
StringBuffer escapedString = new StringBuffer();
int len = msg.length();
for (int i = 0; i < len; i++) {
char ch = msg.charAt(i);
int x = ch;
if ((x < 26 && x != 9 && x != 10 && x != 13) || ch == '\\') {
String temp = Integer.toString(x, 16);
if (temp.length() != 2)
temp = "0" + temp;
escapedString.append("\\").append(temp);
} else escapedString.append(ch);
}
ret.append(escapedString);
return ret.toString();
} } | public class class_name {
protected String createDefaultLogLine(String msg, int level, Date date, StackTraceElement trace) {
String[] levels = {"NON", "ERR", "WRN", "INF", "DBG", "DB2", "INT"};
StringBuffer ret = new StringBuffer(128);
ret.append("<").append(levels[level]).append("> ");
SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss.SSS");
ret.append("[").append(df.format(date)).append("] ");
Thread thread = Thread.currentThread();
ret.append("[").append(thread.getThreadGroup().getName());
ret.append("/").append(thread.getName()).append("] ");
String classname = trace.getClassName();
String hbciname = "org.kapott.hbci.";
if (classname != null && classname.startsWith(hbciname))
ret.append(classname.substring((hbciname).length())).append(": ");
if (msg == null)
msg = "";
StringBuffer escapedString = new StringBuffer();
int len = msg.length();
for (int i = 0; i < len; i++) {
char ch = msg.charAt(i);
int x = ch;
if ((x < 26 && x != 9 && x != 10 && x != 13) || ch == '\\') {
String temp = Integer.toString(x, 16);
if (temp.length() != 2)
temp = "0" + temp;
escapedString.append("\\").append(temp); // depends on control dependency: [if], data = [none]
} else escapedString.append(ch);
}
ret.append(escapedString);
return ret.toString();
} } |
public class class_name {
protected ICompilableTypeInternal isMemberOnEnclosingType(IReducedSymbol symbol)
{
if( !_cc().isNonStaticInnerClass() )
{
return null;
}
// If the symbol is on this class, or any ancestors, it's not enclosed
//noinspection SuspiciousMethodCalls
IType symbolClass = maybeUnwrapProxy( symbol.getGosuClass() );
if( getGosuClass().getAllTypesInHierarchy().contains( symbolClass ) )
{
return null;
}
ICompilableTypeInternal enclosingClass = _cc().getEnclosingType();
if( !(TypeLord.getOuterMostEnclosingClass( _cc().getEnclosingType() ) instanceof IGosuEnhancement) &&
symbolClass instanceof IGosuEnhancement )
{
symbolClass = ((IGosuEnhancement)symbolClass).getEnhancedType();
}
while( enclosingClass != null )
{
//noinspection SuspiciousMethodCalls
if( enclosingClass.getAllTypesInHierarchy().contains( symbolClass ) )
{
return enclosingClass;
}
enclosingClass = enclosingClass.getEnclosingType();
}
return null;
} } | public class class_name {
protected ICompilableTypeInternal isMemberOnEnclosingType(IReducedSymbol symbol)
{
if( !_cc().isNonStaticInnerClass() )
{
return null; // depends on control dependency: [if], data = [none]
}
// If the symbol is on this class, or any ancestors, it's not enclosed
//noinspection SuspiciousMethodCalls
IType symbolClass = maybeUnwrapProxy( symbol.getGosuClass() );
if( getGosuClass().getAllTypesInHierarchy().contains( symbolClass ) )
{
return null; // depends on control dependency: [if], data = [none]
}
ICompilableTypeInternal enclosingClass = _cc().getEnclosingType();
if( !(TypeLord.getOuterMostEnclosingClass( _cc().getEnclosingType() ) instanceof IGosuEnhancement) &&
symbolClass instanceof IGosuEnhancement )
{
symbolClass = ((IGosuEnhancement)symbolClass).getEnhancedType(); // depends on control dependency: [if], data = [none]
}
while( enclosingClass != null )
{
//noinspection SuspiciousMethodCalls
if( enclosingClass.getAllTypesInHierarchy().contains( symbolClass ) )
{
return enclosingClass; // depends on control dependency: [if], data = [none]
}
enclosingClass = enclosingClass.getEnclosingType(); // depends on control dependency: [while], data = [none]
}
return null;
} } |
public class class_name {
private long getJitterFreePTS(long bufferPts, long bufferSamplesNum) {
long correctedPts = 0;
long bufferDuration = (1000000 * bufferSamplesNum) / (mEncoderCore.mSampleRate);
bufferPts -= bufferDuration; // accounts for the delay of acquiring the audio buffer
if (totalSamplesNum == 0) {
// reset
startPTS = bufferPts;
totalSamplesNum = 0;
}
correctedPts = startPTS + (1000000 * totalSamplesNum) / (mEncoderCore.mSampleRate);
if(bufferPts - correctedPts >= 2*bufferDuration) {
// reset
startPTS = bufferPts;
totalSamplesNum = 0;
correctedPts = startPTS;
}
totalSamplesNum += bufferSamplesNum;
return correctedPts;
} } | public class class_name {
private long getJitterFreePTS(long bufferPts, long bufferSamplesNum) {
long correctedPts = 0;
long bufferDuration = (1000000 * bufferSamplesNum) / (mEncoderCore.mSampleRate);
bufferPts -= bufferDuration; // accounts for the delay of acquiring the audio buffer
if (totalSamplesNum == 0) {
// reset
startPTS = bufferPts; // depends on control dependency: [if], data = [none]
totalSamplesNum = 0; // depends on control dependency: [if], data = [none]
}
correctedPts = startPTS + (1000000 * totalSamplesNum) / (mEncoderCore.mSampleRate);
if(bufferPts - correctedPts >= 2*bufferDuration) {
// reset
startPTS = bufferPts; // depends on control dependency: [if], data = [none]
totalSamplesNum = 0; // depends on control dependency: [if], data = [none]
correctedPts = startPTS; // depends on control dependency: [if], data = [none]
}
totalSamplesNum += bufferSamplesNum;
return correctedPts;
} } |
public class class_name {
public List<NodeData> getChildNodesByPage(final NodeData parent, final int fromOrderNum)
{
// get list of children uuids
final Map<Integer, Set<String>> pages =
(Map<Integer, Set<String>>)cache.get(new CacheNodesByPageId(getOwnerId(), parent.getIdentifier()));
if (pages == null)
{
return null;
}
Set<String> set = pages.get(fromOrderNum);
if (set == null)
{
return null;
}
final List<NodeData> childs = new ArrayList<NodeData>();
for (String childId : set)
{
NodeData child = (NodeData)cache.get(new CacheId(getOwnerId(), childId));
if (child == null)
{
return null;
}
childs.add(child);
}
// order children by orderNumber, as HashSet returns children in other order
Collections.sort(childs, new NodesOrderComparator<NodeData>());
return childs;
} } | public class class_name {
public List<NodeData> getChildNodesByPage(final NodeData parent, final int fromOrderNum)
{
// get list of children uuids
final Map<Integer, Set<String>> pages =
(Map<Integer, Set<String>>)cache.get(new CacheNodesByPageId(getOwnerId(), parent.getIdentifier()));
if (pages == null)
{
return null;
// depends on control dependency: [if], data = [none]
}
Set<String> set = pages.get(fromOrderNum);
if (set == null)
{
return null;
// depends on control dependency: [if], data = [none]
}
final List<NodeData> childs = new ArrayList<NodeData>();
for (String childId : set)
{
NodeData child = (NodeData)cache.get(new CacheId(getOwnerId(), childId));
if (child == null)
{
return null;
// depends on control dependency: [if], data = [none]
}
childs.add(child);
// depends on control dependency: [for], data = [none]
}
// order children by orderNumber, as HashSet returns children in other order
Collections.sort(childs, new NodesOrderComparator<NodeData>());
return childs;
} } |
public class class_name {
public void setActiveScan(ActiveScan scan) {
this.scan = scan;
if (scan == null) {
return;
}
getHostSelect().removeAll();
for (HostProcess hp : scan.getHostProcesses()) {
getHostSelect().addItem(hp.getHostAndPort());
}
Thread thread = new Thread() {
@Override
public void run() {
while (!stopThread) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
updateProgress();
}});
try {
sleep(200);
} catch (InterruptedException e) {
// Ignore
}
}
}
};
thread.start();
} } | public class class_name {
public void setActiveScan(ActiveScan scan) {
this.scan = scan;
if (scan == null) {
return; // depends on control dependency: [if], data = [none]
}
getHostSelect().removeAll();
for (HostProcess hp : scan.getHostProcesses()) {
getHostSelect().addItem(hp.getHostAndPort()); // depends on control dependency: [for], data = [hp]
}
Thread thread = new Thread() {
@Override
public void run() {
while (!stopThread) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
updateProgress();
}}); // depends on control dependency: [while], data = [none]
try {
sleep(200); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
// Ignore
} // depends on control dependency: [catch], data = [none]
}
}
};
thread.start();
} } |
public class class_name {
public void onNotify(RequestEvent event, ActivityContextInterface aci) {
if (tracer.isFineEnabled())
tracer.fine("Received Notify, on activity: " + aci.getActivity() + "\nRequest:\n" + event.getRequest());
Request request = event.getRequest();
SubscriptionData subscriptionData = getSubscriptionDataCMP();
EventHeader eventHeader = (EventHeader) request.getHeader(EventHeader.NAME);
if (eventHeader == null || !eventHeader.getEventType().equals(subscriptionData.getEventPackage())) {
try {
Response badEventResponse = this.messageFactory.createResponse(Response.BAD_EVENT, request);
event.getServerTransaction().sendResponse(badEventResponse);
// TODO: terminate dialog?
} catch (Exception e) {
if (tracer.isSevereEnabled()) {
tracer.severe("Failed to create 489 answer to NOTIFY", e);
}
}
return;
} else {
try {
Response okResponse = this.messageFactory.createResponse(Response.OK, request);
event.getServerTransaction().sendResponse(okResponse);
} catch (Exception e) {
if (tracer.isSevereEnabled()) {
tracer.severe("Failed to create 200 answer to NOTIFY", e);
}
return;
}
}
// lets create Notify
Notify notify = new Notify();
notify.setSubscriber(subscriptionData.getSubscriberURI());
ContentTypeHeader contentType = (ContentTypeHeader) request.getHeader(ContentTypeHeader.NAME);
if (contentType != null) {
// use CT Header?
notify.setContentType(contentType.getContentType());
notify.setContentSubType(contentType.getContentSubType());
notify.setContent(new String(request.getRawContent()));
}
notify.setNotifier(subscriptionData.getNotifierURI());
// check, whats in header.
SubscriptionStateHeader subscriptionStateHeader = (SubscriptionStateHeader) request.getHeader(SubscriptionStateHeader.NAME);
SubscriptionStatus state = SubscriptionStatus.fromString(subscriptionStateHeader.getState());
notify.setStatus(state);
// do magic
switch (state) {
case active:
case pending:
// check for exp
if (subscriptionStateHeader.getExpires() != Notify.NO_TIMEOUT) {
notify.setExpires(subscriptionStateHeader.getExpires());
// set timer if needed
SubscribeRequestType subscribeRequestType = getSubscribeRequestTypeCMP();
if (subscribeRequestType == SubscribeRequestType.NEW || subscribeRequestType == SubscribeRequestType.REFRESH) {
startExpiresTimer(aci,subscriptionStateHeader.getExpires());
setSubscribeRequestTypeCMP(null);
}
}
break;
case waiting:
// nothing...
break;
case extension:
notify.setStatusExtension(subscriptionStateHeader.getState());
case terminated:
// check reason
String reasonString = subscriptionStateHeader.getReasonCode();
TerminationReason reason = TerminationReason.fromString(reasonString);
notify.setTerminationReason(reason);
if (reason != null) {
switch (reason) {
case rejected:
case noresource:
case deactivated:
case timeout:
break;
case probation:
case giveup:
if (subscriptionStateHeader.getRetryAfter() != Notify.NO_TIMEOUT) {
notify.setRetryAfter(subscriptionStateHeader.getRetryAfter());
}
break;
case extension:
notify.setTerminationReasonExtension(reasonString);
break;
}
}
break;
}
// deliver to parent
try {
SbbLocalObjectExt sbbLocalObjectExt = sbbContext.getSbbLocalObject();
if(state == SubscriptionStatus.terminated)
{
cancelExpiresTimer(aci);
aci.detach(sbbLocalObjectExt);
event.getDialog().delete();
}
((SubscriptionClientParentSbbLocalObject)sbbLocalObjectExt.getParent()).onNotify(notify, (SubscriptionClientChildSbbLocalObject) sbbLocalObjectExt);
} catch (Exception e) {
if (tracer.isSevereEnabled()) {
tracer.severe("Received exception from parent on notify callback", e);
}
}
} } | public class class_name {
public void onNotify(RequestEvent event, ActivityContextInterface aci) {
if (tracer.isFineEnabled())
tracer.fine("Received Notify, on activity: " + aci.getActivity() + "\nRequest:\n" + event.getRequest());
Request request = event.getRequest();
SubscriptionData subscriptionData = getSubscriptionDataCMP();
EventHeader eventHeader = (EventHeader) request.getHeader(EventHeader.NAME);
if (eventHeader == null || !eventHeader.getEventType().equals(subscriptionData.getEventPackage())) {
try {
Response badEventResponse = this.messageFactory.createResponse(Response.BAD_EVENT, request);
event.getServerTransaction().sendResponse(badEventResponse); // depends on control dependency: [try], data = [none]
// TODO: terminate dialog?
} catch (Exception e) {
if (tracer.isSevereEnabled()) {
tracer.severe("Failed to create 489 answer to NOTIFY", e); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
return; // depends on control dependency: [if], data = [none]
} else {
try {
Response okResponse = this.messageFactory.createResponse(Response.OK, request);
event.getServerTransaction().sendResponse(okResponse); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
if (tracer.isSevereEnabled()) {
tracer.severe("Failed to create 200 answer to NOTIFY", e); // depends on control dependency: [if], data = [none]
}
return;
} // depends on control dependency: [catch], data = [none]
}
// lets create Notify
Notify notify = new Notify();
notify.setSubscriber(subscriptionData.getSubscriberURI());
ContentTypeHeader contentType = (ContentTypeHeader) request.getHeader(ContentTypeHeader.NAME);
if (contentType != null) {
// use CT Header?
notify.setContentType(contentType.getContentType()); // depends on control dependency: [if], data = [(contentType]
notify.setContentSubType(contentType.getContentSubType()); // depends on control dependency: [if], data = [(contentType]
notify.setContent(new String(request.getRawContent())); // depends on control dependency: [if], data = [none]
}
notify.setNotifier(subscriptionData.getNotifierURI());
// check, whats in header.
SubscriptionStateHeader subscriptionStateHeader = (SubscriptionStateHeader) request.getHeader(SubscriptionStateHeader.NAME);
SubscriptionStatus state = SubscriptionStatus.fromString(subscriptionStateHeader.getState());
notify.setStatus(state);
// do magic
switch (state) {
case active:
case pending:
// check for exp
if (subscriptionStateHeader.getExpires() != Notify.NO_TIMEOUT) {
notify.setExpires(subscriptionStateHeader.getExpires()); // depends on control dependency: [if], data = [(subscriptionStateHeader.getExpires()]
// set timer if needed
SubscribeRequestType subscribeRequestType = getSubscribeRequestTypeCMP();
if (subscribeRequestType == SubscribeRequestType.NEW || subscribeRequestType == SubscribeRequestType.REFRESH) {
startExpiresTimer(aci,subscriptionStateHeader.getExpires()); // depends on control dependency: [if], data = [none]
setSubscribeRequestTypeCMP(null); // depends on control dependency: [if], data = [none]
}
}
break;
case waiting:
// nothing...
break;
case extension:
notify.setStatusExtension(subscriptionStateHeader.getState());
case terminated:
// check reason
String reasonString = subscriptionStateHeader.getReasonCode();
TerminationReason reason = TerminationReason.fromString(reasonString);
notify.setTerminationReason(reason);
if (reason != null) {
switch (reason) {
case rejected:
case noresource:
case deactivated:
case timeout:
break;
case probation:
case giveup:
if (subscriptionStateHeader.getRetryAfter() != Notify.NO_TIMEOUT) {
notify.setRetryAfter(subscriptionStateHeader.getRetryAfter()); // depends on control dependency: [if], data = [(subscriptionStateHeader.getRetryAfter()]
}
break;
case extension:
notify.setTerminationReasonExtension(reasonString);
break;
}
}
break;
}
// deliver to parent
try {
SbbLocalObjectExt sbbLocalObjectExt = sbbContext.getSbbLocalObject();
if(state == SubscriptionStatus.terminated)
{
cancelExpiresTimer(aci); // depends on control dependency: [if], data = [none]
aci.detach(sbbLocalObjectExt); // depends on control dependency: [if], data = [none]
event.getDialog().delete(); // depends on control dependency: [if], data = [none]
}
((SubscriptionClientParentSbbLocalObject)sbbLocalObjectExt.getParent()).onNotify(notify, (SubscriptionClientChildSbbLocalObject) sbbLocalObjectExt); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
if (tracer.isSevereEnabled()) {
tracer.severe("Received exception from parent on notify callback", e); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public List<ESigItem> findItems(ESigFilter filter) {
List<ESigItem> list = new ArrayList<ESigItem>();
if (filter == null) {
list.addAll(items);
} else {
for (ESigItem item : items) {
if (filter.matches(item)) {
list.add(item);
}
}
}
return list;
} } | public class class_name {
public List<ESigItem> findItems(ESigFilter filter) {
List<ESigItem> list = new ArrayList<ESigItem>();
if (filter == null) {
list.addAll(items); // depends on control dependency: [if], data = [none]
} else {
for (ESigItem item : items) {
if (filter.matches(item)) {
list.add(item); // depends on control dependency: [if], data = [none]
}
}
}
return list;
} } |
public class class_name {
protected Boolean _hasSideEffects(XVariableDeclaration expression, ISideEffectContext context) {
if (hasSideEffects(expression.getRight(), context)) {
return true;
}
context.declareVariable(expression.getIdentifier(), expression.getRight());
return false;
} } | public class class_name {
protected Boolean _hasSideEffects(XVariableDeclaration expression, ISideEffectContext context) {
if (hasSideEffects(expression.getRight(), context)) {
return true; // depends on control dependency: [if], data = [none]
}
context.declareVariable(expression.getIdentifier(), expression.getRight());
return false;
} } |
public class class_name {
@Override
public CsvFile readData(String filePath) throws IOException, InvalidFileException {
Path path = Paths.get(filePath);
List<Object[]> tokensList = new ArrayList<Object[]>();
try (BufferedReader reader = Files.newBufferedReader(path, charset);) {
String line = null;
while (!StringUtils.isEmpty(line = reader.readLine())) {
String[] tokens = line.split(separator, -1);
tokensList.add(tokens);
}
}
CsvFile result = new CsvFile();
result.setData(tokensList);
return result;
} } | public class class_name {
@Override
public CsvFile readData(String filePath) throws IOException, InvalidFileException {
Path path = Paths.get(filePath);
List<Object[]> tokensList = new ArrayList<Object[]>();
try (BufferedReader reader = Files.newBufferedReader(path, charset);) {
String line = null;
while (!StringUtils.isEmpty(line = reader.readLine())) {
String[] tokens = line.split(separator, -1);
tokensList.add(tokens);
// depends on control dependency: [while], data = [none]
}
}
CsvFile result = new CsvFile();
result.setData(tokensList);
return result;
} } |
public class class_name {
public void setTunnelConnections( Iterable<String> pathAndSpecList ) throws JSchException {
Map<String, Set<Tunnel>> tunnelMap = new HashMap<String, Set<Tunnel>>();
for ( String pathAndSpecString : pathAndSpecList ) {
String[] pathAndSpec = pathAndSpecString.trim().split( "\\|" );
Set<Tunnel> tunnelList = tunnelMap.get( pathAndSpec[0] );
if ( tunnelList == null ) {
tunnelList = new HashSet<Tunnel>();
tunnelMap.put( pathAndSpec[0], tunnelList );
}
tunnelList.add( new Tunnel( pathAndSpec[1] ) );
}
tunnelConnections = new ArrayList<TunnelConnection>();
SessionFactoryCache sessionFactoryCache = new SessionFactoryCache( baseSessionFactory );
for ( String path : tunnelMap.keySet() ) {
tunnelConnections.add( new TunnelConnection( sessionFactoryCache.getSessionFactory( path ),
new ArrayList<Tunnel>( tunnelMap.get( path ) ) ) );
}
} } | public class class_name {
public void setTunnelConnections( Iterable<String> pathAndSpecList ) throws JSchException {
Map<String, Set<Tunnel>> tunnelMap = new HashMap<String, Set<Tunnel>>();
for ( String pathAndSpecString : pathAndSpecList ) {
String[] pathAndSpec = pathAndSpecString.trim().split( "\\|" );
Set<Tunnel> tunnelList = tunnelMap.get( pathAndSpec[0] );
if ( tunnelList == null ) {
tunnelList = new HashSet<Tunnel>(); // depends on control dependency: [if], data = [none]
tunnelMap.put( pathAndSpec[0], tunnelList ); // depends on control dependency: [if], data = [none]
}
tunnelList.add( new Tunnel( pathAndSpec[1] ) );
}
tunnelConnections = new ArrayList<TunnelConnection>();
SessionFactoryCache sessionFactoryCache = new SessionFactoryCache( baseSessionFactory );
for ( String path : tunnelMap.keySet() ) {
tunnelConnections.add( new TunnelConnection( sessionFactoryCache.getSessionFactory( path ),
new ArrayList<Tunnel>( tunnelMap.get( path ) ) ) );
}
} } |
public class class_name {
public void actionChangeSecureExport() throws JspException {
// save initialized instance of this class in request attribute for included sub-elements
getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, this);
String filename = getParamResource();
try {
// lock resource if auto lock is enabled
checkLock(getParamResource());
// write the properties
writeProperty(CmsPropertyDefinition.PROPERTY_EXPORT, getParamExport());
writeProperty(CmsPropertyDefinition.PROPERTY_EXPORTNAME, getParamExportname());
writeProperty(CmsPropertyDefinition.PROPERTY_SECURE, getParamSecure());
// change the flag of the resource so that it is internal
CmsResource resource = getCms().readResource(filename, CmsResourceFilter.IGNORE_EXPIRATION);
if (resource.isInternal() && !Boolean.valueOf(getParamIntern()).booleanValue()) {
getCms().chflags(filename, resource.getFlags() & (~CmsResource.FLAG_INTERNAL));
} else if (!resource.isInternal() && Boolean.valueOf(getParamIntern()).booleanValue()) {
getCms().chflags(filename, resource.getFlags() | CmsResource.FLAG_INTERNAL);
}
actionCloseDialog();
} catch (Throwable e) {
// error during change of secure settings, show error dialog
includeErrorpage(this, e);
}
} } | public class class_name {
public void actionChangeSecureExport() throws JspException {
// save initialized instance of this class in request attribute for included sub-elements
getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, this);
String filename = getParamResource();
try {
// lock resource if auto lock is enabled
checkLock(getParamResource());
// write the properties
writeProperty(CmsPropertyDefinition.PROPERTY_EXPORT, getParamExport());
writeProperty(CmsPropertyDefinition.PROPERTY_EXPORTNAME, getParamExportname());
writeProperty(CmsPropertyDefinition.PROPERTY_SECURE, getParamSecure());
// change the flag of the resource so that it is internal
CmsResource resource = getCms().readResource(filename, CmsResourceFilter.IGNORE_EXPIRATION);
if (resource.isInternal() && !Boolean.valueOf(getParamIntern()).booleanValue()) {
getCms().chflags(filename, resource.getFlags() & (~CmsResource.FLAG_INTERNAL)); // depends on control dependency: [if], data = [none]
} else if (!resource.isInternal() && Boolean.valueOf(getParamIntern()).booleanValue()) {
getCms().chflags(filename, resource.getFlags() | CmsResource.FLAG_INTERNAL); // depends on control dependency: [if], data = [none]
}
actionCloseDialog();
} catch (Throwable e) {
// error during change of secure settings, show error dialog
includeErrorpage(this, e);
}
} } |
public class class_name {
protected void processGeneratedBigIntegerKey(Model<?> model, String pKey, Object v) {
if (v instanceof BigInteger) {
model.set(pKey, (BigInteger)v);
} else if (v instanceof Number) {
Number n = (Number)v;
model.set(pKey, BigInteger.valueOf(n.longValue()));
} else {
model.set(pKey, v);
}
} } | public class class_name {
protected void processGeneratedBigIntegerKey(Model<?> model, String pKey, Object v) {
if (v instanceof BigInteger) {
model.set(pKey, (BigInteger)v);
// depends on control dependency: [if], data = [none]
} else if (v instanceof Number) {
Number n = (Number)v;
model.set(pKey, BigInteger.valueOf(n.longValue()));
// depends on control dependency: [if], data = [none]
} else {
model.set(pKey, v);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private boolean isDomainAlwaysInScope(String domain) {
for (DomainAlwaysInScopeMatcher domainInScope : domainsAlwaysInScope) {
if (domainInScope.matches(domain)) {
return true;
}
}
return false;
} } | public class class_name {
private boolean isDomainAlwaysInScope(String domain) {
for (DomainAlwaysInScopeMatcher domainInScope : domainsAlwaysInScope) {
if (domainInScope.matches(domain)) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
@Deprecated
@ObjectiveCName("formatDialogText:")
public String formatDialogText(Dialog dialog) {
// Detecting if dialog is empty
if (dialog.getSenderId() == 0) {
return "";
} else {
String contentText = formatContentText(dialog.getSenderId(),
dialog.getMessageType(), dialog.getText(), dialog.getRelatedUid(),
dialog.isChannel());
if (dialog.getPeer().getPeerType() == PeerType.GROUP && !dialog.isChannel()) {
if (!isLargeDialogMessage(dialog.getMessageType())) {
return formatPerformerName(dialog.getSenderId()) + ": " + contentText;
} else {
return contentText;
}
} else {
return contentText;
}
}
} } | public class class_name {
@Deprecated
@ObjectiveCName("formatDialogText:")
public String formatDialogText(Dialog dialog) {
// Detecting if dialog is empty
if (dialog.getSenderId() == 0) {
return ""; // depends on control dependency: [if], data = [none]
} else {
String contentText = formatContentText(dialog.getSenderId(),
dialog.getMessageType(), dialog.getText(), dialog.getRelatedUid(),
dialog.isChannel());
if (dialog.getPeer().getPeerType() == PeerType.GROUP && !dialog.isChannel()) {
if (!isLargeDialogMessage(dialog.getMessageType())) {
return formatPerformerName(dialog.getSenderId()) + ": " + contentText; // depends on control dependency: [if], data = [none]
} else {
return contentText; // depends on control dependency: [if], data = [none]
}
} else {
return contentText; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public ComputeNodeListNextOptions withOcpDate(DateTime ocpDate) {
if (ocpDate == null) {
this.ocpDate = null;
} else {
this.ocpDate = new DateTimeRfc1123(ocpDate);
}
return this;
} } | public class class_name {
public ComputeNodeListNextOptions withOcpDate(DateTime ocpDate) {
if (ocpDate == null) {
this.ocpDate = null; // depends on control dependency: [if], data = [none]
} else {
this.ocpDate = new DateTimeRfc1123(ocpDate); // depends on control dependency: [if], data = [(ocpDate]
}
return this;
} } |
public class class_name {
private void readTasks(Project project)
{
Project.Tasks tasks = project.getTasks();
if (tasks != null)
{
int tasksWithoutIDCount = 0;
for (Project.Tasks.Task task : tasks.getTask())
{
Task mpxjTask = readTask(task);
if (mpxjTask.getID() == null)
{
++tasksWithoutIDCount;
}
}
for (Project.Tasks.Task task : tasks.getTask())
{
readPredecessors(task);
}
//
// MS Project will happily read tasks from an MSPDI file without IDs,
// it will just generate ID values based on the task order in the file.
// If we find that there are no ID values present, we'll do the same.
//
if (tasksWithoutIDCount == tasks.getTask().size())
{
m_projectFile.getTasks().renumberIDs();
}
}
m_projectFile.updateStructure();
} } | public class class_name {
private void readTasks(Project project)
{
Project.Tasks tasks = project.getTasks();
if (tasks != null)
{
int tasksWithoutIDCount = 0;
for (Project.Tasks.Task task : tasks.getTask())
{
Task mpxjTask = readTask(task);
if (mpxjTask.getID() == null)
{
++tasksWithoutIDCount; // depends on control dependency: [if], data = [none]
}
}
for (Project.Tasks.Task task : tasks.getTask())
{
readPredecessors(task); // depends on control dependency: [for], data = [task]
}
//
// MS Project will happily read tasks from an MSPDI file without IDs,
// it will just generate ID values based on the task order in the file.
// If we find that there are no ID values present, we'll do the same.
//
if (tasksWithoutIDCount == tasks.getTask().size())
{
m_projectFile.getTasks().renumberIDs(); // depends on control dependency: [if], data = [none]
}
}
m_projectFile.updateStructure();
} } |
public class class_name {
private static int decode4to3(byte[] src,
int len,
byte[] dest,
int offset) {
// Example: Dk or Dk==
if (len == 2 || (src[2] == EQUALS_SIGN && src[3] == EQUALS_SIGN)) {
int outBuff = (validate(src[0]) << 18) |
(validate(src[1]) << 12);
dest[offset] = (byte) (outBuff >>> 16);
return 1;
}
// Example: DkL or DkL=
if (len == 3 || src[3] == EQUALS_SIGN) {
int outBuff = (validate(src[0]) << 18) |
(validate(src[1]) << 12) |
(validate(src[2]) << 6);
dest[offset] = (byte) (outBuff >>> 16);
dest[offset + 1] = (byte) (outBuff >>> 8);
return 2;
}
// Example: DkLE
int outBuff = (validate(src[0]) << 18) |
(validate(src[1]) << 12) |
(validate(src[2]) << 6) |
(validate(src[3]));
dest[offset] = (byte) (outBuff >>> 16);
dest[offset + 1] = (byte) (outBuff >>> 8);
dest[offset + 2] = (byte) (outBuff);
return 3;
} } | public class class_name {
private static int decode4to3(byte[] src,
int len,
byte[] dest,
int offset) {
// Example: Dk or Dk==
if (len == 2 || (src[2] == EQUALS_SIGN && src[3] == EQUALS_SIGN)) {
int outBuff = (validate(src[0]) << 18) |
(validate(src[1]) << 12);
dest[offset] = (byte) (outBuff >>> 16); // depends on control dependency: [if], data = [none]
return 1; // depends on control dependency: [if], data = [none]
}
// Example: DkL or DkL=
if (len == 3 || src[3] == EQUALS_SIGN) {
int outBuff = (validate(src[0]) << 18) |
(validate(src[1]) << 12) |
(validate(src[2]) << 6);
dest[offset] = (byte) (outBuff >>> 16); // depends on control dependency: [if], data = [none]
dest[offset + 1] = (byte) (outBuff >>> 8); // depends on control dependency: [if], data = [none]
return 2; // depends on control dependency: [if], data = [none]
}
// Example: DkLE
int outBuff = (validate(src[0]) << 18) |
(validate(src[1]) << 12) |
(validate(src[2]) << 6) |
(validate(src[3]));
dest[offset] = (byte) (outBuff >>> 16);
dest[offset + 1] = (byte) (outBuff >>> 8);
dest[offset + 2] = (byte) (outBuff);
return 3;
} } |
public class class_name {
public ListDeploymentInstancesResult withInstancesList(String... instancesList) {
if (this.instancesList == null) {
setInstancesList(new com.amazonaws.internal.SdkInternalList<String>(instancesList.length));
}
for (String ele : instancesList) {
this.instancesList.add(ele);
}
return this;
} } | public class class_name {
public ListDeploymentInstancesResult withInstancesList(String... instancesList) {
if (this.instancesList == null) {
setInstancesList(new com.amazonaws.internal.SdkInternalList<String>(instancesList.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : instancesList) {
this.instancesList.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
@RequestMapping(params = {"query", "queryId"})
public ModelAndView showSearchResults(
PortletRequest request,
@RequestParam(value = "query") String query,
@RequestParam(value = "queryId") String queryId) {
final Map<String, Object> model = new HashMap<>();
model.put("query", query);
// Determine if the new REST search should be used
if (isRestSearch(request)) {
// we only need query, so the model at this point is sufficient
return new ModelAndView("/jsp/Search/searchRest", model);
}
ConcurrentMap<String, List<Tuple<SearchResult, String>>> results =
new ConcurrentHashMap<>();
final PortalSearchResults portalSearchResults =
this.getPortalSearchResults(request, queryId);
if (portalSearchResults != null) {
results = portalSearchResults.getResults();
}
results.forEach(
(key, value) -> {
value.sort(Comparator.comparingInt(tuple -> tuple.first.getRank()));
});
logger.debug("Search results for query '{}' are: {}", query, results);
model.put("results", results);
model.put("defaultTabKey", this.defaultTabKey);
model.put("tabKeys", this.tabKeys);
final boolean isMobile = isMobile(request);
String viewName = isMobile ? "/jsp/Search/mobileSearch" : "/jsp/Search/search";
return new ModelAndView(viewName, model);
} } | public class class_name {
@RequestMapping(params = {"query", "queryId"})
public ModelAndView showSearchResults(
PortletRequest request,
@RequestParam(value = "query") String query,
@RequestParam(value = "queryId") String queryId) {
final Map<String, Object> model = new HashMap<>();
model.put("query", query);
// Determine if the new REST search should be used
if (isRestSearch(request)) {
// we only need query, so the model at this point is sufficient
return new ModelAndView("/jsp/Search/searchRest", model); // depends on control dependency: [if], data = [none]
}
ConcurrentMap<String, List<Tuple<SearchResult, String>>> results =
new ConcurrentHashMap<>();
final PortalSearchResults portalSearchResults =
this.getPortalSearchResults(request, queryId);
if (portalSearchResults != null) {
results = portalSearchResults.getResults(); // depends on control dependency: [if], data = [none]
}
results.forEach(
(key, value) -> {
value.sort(Comparator.comparingInt(tuple -> tuple.first.getRank()));
});
logger.debug("Search results for query '{}' are: {}", query, results);
model.put("results", results);
model.put("defaultTabKey", this.defaultTabKey);
model.put("tabKeys", this.tabKeys);
final boolean isMobile = isMobile(request);
String viewName = isMobile ? "/jsp/Search/mobileSearch" : "/jsp/Search/search";
return new ModelAndView(viewName, model);
} } |
public class class_name {
public UserDetail withUserPolicyList(PolicyDetail... userPolicyList) {
if (this.userPolicyList == null) {
setUserPolicyList(new com.amazonaws.internal.SdkInternalList<PolicyDetail>(userPolicyList.length));
}
for (PolicyDetail ele : userPolicyList) {
this.userPolicyList.add(ele);
}
return this;
} } | public class class_name {
public UserDetail withUserPolicyList(PolicyDetail... userPolicyList) {
if (this.userPolicyList == null) {
setUserPolicyList(new com.amazonaws.internal.SdkInternalList<PolicyDetail>(userPolicyList.length)); // depends on control dependency: [if], data = [none]
}
for (PolicyDetail ele : userPolicyList) {
this.userPolicyList.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
private Budget getBudget() {
Budget budget = Budget.Factory.newInstance();
Map<Integer, String> budgetMap = new HashMap<>();
for (AnswerContract questionnaireAnswer : getPropDevQuestionAnswerService().getQuestionnaireAnswers(pdDoc.getDevelopmentProposal().getProposalNumber(), getNamespace(), getFormName())) {
String answer = questionnaireAnswer.getAnswer();
if (answer != null) {
switch (getQuestionAnswerService().findQuestionById(questionnaireAnswer.getQuestionId()).getQuestionSeqId()) {
case SENIOR_FELL:
budgetMap.put(SENIOR_FELL, answer);
break;
case OTHER_SUPP_SOURCE:
budgetMap.put(OTHER_SUPP_SOURCE, answer);
break;
case SUPP_SOURCE:
budgetMap.put(SUPP_SOURCE, answer);
break;
case SUPP_FUNDING_AMT:
budgetMap.put(SUPP_FUNDING_AMT, answer);
break;
case SUPP_MONTHS:
budgetMap.put(SUPP_MONTHS, answer);
break;
case SUPP_TYPE:
budgetMap.put(SUPP_TYPE, answer);
break;
case SALARY_MONTH:
budgetMap.put(SALARY_MONTH, answer);
break;
case ACAD_PERIOD:
budgetMap.put(ACAD_PERIOD, answer);
break;
case BASE_SALARY:
budgetMap.put(BASE_SALARY, answer);
break;
default:
break;
}
}
}
budget.setTuitionAndFeesRequested(YesNoDataType.N_NO);
if(getInstitutionalBaseSalary(budgetMap)!=null){
budget.setInstitutionalBaseSalary(getInstitutionalBaseSalary(budgetMap));
}
budget.setFederalStipendRequested(getFederalStipendRequested());
if(getSupplementationFromOtherSources(budgetMap)!=null){
budget.setSupplementationFromOtherSources(getSupplementationFromOtherSources(budgetMap));
}
setTutionRequestedYears(budget);
return budget;
} } | public class class_name {
private Budget getBudget() {
Budget budget = Budget.Factory.newInstance();
Map<Integer, String> budgetMap = new HashMap<>();
for (AnswerContract questionnaireAnswer : getPropDevQuestionAnswerService().getQuestionnaireAnswers(pdDoc.getDevelopmentProposal().getProposalNumber(), getNamespace(), getFormName())) {
String answer = questionnaireAnswer.getAnswer();
if (answer != null) {
switch (getQuestionAnswerService().findQuestionById(questionnaireAnswer.getQuestionId()).getQuestionSeqId()) {
case SENIOR_FELL:
budgetMap.put(SENIOR_FELL, answer);
break;
case OTHER_SUPP_SOURCE:
budgetMap.put(OTHER_SUPP_SOURCE, answer);
break;
case SUPP_SOURCE:
budgetMap.put(SUPP_SOURCE, answer);
break;
case SUPP_FUNDING_AMT:
budgetMap.put(SUPP_FUNDING_AMT, answer);
break;
case SUPP_MONTHS:
budgetMap.put(SUPP_MONTHS, answer);
break;
case SUPP_TYPE:
budgetMap.put(SUPP_TYPE, answer);
break;
case SALARY_MONTH:
budgetMap.put(SALARY_MONTH, answer);
break;
case ACAD_PERIOD:
budgetMap.put(ACAD_PERIOD, answer);
break;
case BASE_SALARY:
budgetMap.put(BASE_SALARY, answer);
break;
default:
break;
}
}
}
budget.setTuitionAndFeesRequested(YesNoDataType.N_NO);
if(getInstitutionalBaseSalary(budgetMap)!=null){
budget.setInstitutionalBaseSalary(getInstitutionalBaseSalary(budgetMap)); // depends on control dependency: [if], data = [(getInstitutionalBaseSalary(budgetMap)]
}
budget.setFederalStipendRequested(getFederalStipendRequested());
if(getSupplementationFromOtherSources(budgetMap)!=null){
budget.setSupplementationFromOtherSources(getSupplementationFromOtherSources(budgetMap)); // depends on control dependency: [if], data = [(getSupplementationFromOtherSources(budgetMap)]
}
setTutionRequestedYears(budget);
return budget;
} } |
public class class_name {
public WebSocketStepPublisher publish() {
if (connected.getAndSet(true) == false) {
try {
log.info("Connecting");
boolean connected = chorusWebSocketClient.connectBlocking();
if ( ! connected) {
throw new StepPublisherException("Failed to connect to WebSocketsManagerImpl");
}
ConnectMessage connect = new ConnectMessage(chorusClientId, "".equals(description) ? chorusClientId : description);
chorusWebSocketClient.sendMessage(connect);
log.info("Publishing steps");
stepInvokers.values().stream().forEach(invoker -> {
publishStep(invoker);
});
log.info("Sending Aligned");
StepsAlignedMessage stepsAlignedMessage = new StepsAlignedMessage(chorusClientId);
chorusWebSocketClient.sendMessage(stepsAlignedMessage);
} catch (Exception e) {
throw new ChorusException("Failed to connect and publish steps", e);
}
}
return this;
} } | public class class_name {
public WebSocketStepPublisher publish() {
if (connected.getAndSet(true) == false) {
try {
log.info("Connecting");
boolean connected = chorusWebSocketClient.connectBlocking();
if ( ! connected) {
throw new StepPublisherException("Failed to connect to WebSocketsManagerImpl");
}
ConnectMessage connect = new ConnectMessage(chorusClientId, "".equals(description) ? chorusClientId : description);
chorusWebSocketClient.sendMessage(connect);
log.info("Publishing steps");
stepInvokers.values().stream().forEach(invoker -> {
publishStep(invoker);
});
log.info("Sending Aligned");
StepsAlignedMessage stepsAlignedMessage = new StepsAlignedMessage(chorusClientId);
chorusWebSocketClient.sendMessage(stepsAlignedMessage); // depends on control dependency: [if], data = [none]
} catch (Exception e) {
throw new ChorusException("Failed to connect and publish steps", e);
}
}
return this;
} } |
public class class_name {
boolean isJenkinsServerSecuredWithCSRF(String url) throws BuildDriverException {
try {
JenkinsBuildDriverModuleConfig config = configuration
.getModuleConfig(new PncConfigProvider<JenkinsBuildDriverModuleConfig>(JenkinsBuildDriverModuleConfig.class));
String username = config.getUsername();
String password = config.getPassword();
if (url == null || username == null || password == null) {
throw new BuildDriverException("Missing config to instantiate " + JenkinsBuildDriver.DRIVER_ID + ".");
}
try {
JenkinsHttpClient jenkinsHttpClient = new JenkinsHttpClient(new URI(url), username, password);
try {
jenkinsHttpClient.get("/crumbIssuer/api/xml");
return true ;
} catch (IOException e) {
return false;
}
} catch (URISyntaxException e) {
throw new BuildDriverException("Cannot instantiate " + JenkinsBuildDriver.DRIVER_ID + ". Make sure you are using valid url: " + url, e);
}
} catch (ConfigurationParseException e) {
throw new BuildDriverException("Cannot read configuration for " + JenkinsBuildDriver.DRIVER_ID + ".", e); }
} } | public class class_name {
boolean isJenkinsServerSecuredWithCSRF(String url) throws BuildDriverException {
try {
JenkinsBuildDriverModuleConfig config = configuration
.getModuleConfig(new PncConfigProvider<JenkinsBuildDriverModuleConfig>(JenkinsBuildDriverModuleConfig.class));
String username = config.getUsername();
String password = config.getPassword();
if (url == null || username == null || password == null) {
throw new BuildDriverException("Missing config to instantiate " + JenkinsBuildDriver.DRIVER_ID + ".");
}
try {
JenkinsHttpClient jenkinsHttpClient = new JenkinsHttpClient(new URI(url), username, password);
try {
jenkinsHttpClient.get("/crumbIssuer/api/xml"); // depends on control dependency: [try], data = [none]
return true ; // depends on control dependency: [try], data = [none]
} catch (IOException e) {
return false;
} // depends on control dependency: [catch], data = [none]
} catch (URISyntaxException e) {
throw new BuildDriverException("Cannot instantiate " + JenkinsBuildDriver.DRIVER_ID + ". Make sure you are using valid url: " + url, e);
}
} catch (ConfigurationParseException e) {
throw new BuildDriverException("Cannot read configuration for " + JenkinsBuildDriver.DRIVER_ID + ".", e); }
} } |
public class class_name {
public void addMouseListenerToHeaderInTable(JTable table)
{
table.setColumnSelectionAllowed(false);
MouseListener mouseListener = new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
if (e.getSource() instanceof JTableHeader)
{ // Always
JTableHeader tableHeader = (JTableHeader)e.getSource();
TableColumnModel columnModel = tableHeader.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int column = tableHeader.getTable().convertColumnIndexToModel(viewColumn);
if(e.getClickCount() == 1 && column != -1)
{
boolean order = Constants.ASCENDING;
if ((e.getModifiers() & InputEvent.SHIFT_MASK) != 0)
order = !order;
if (!(tableHeader.getDefaultRenderer() instanceof SortableHeaderRenderer))
tableHeader.setDefaultRenderer(new SortableHeaderRenderer(tableHeader.getDefaultRenderer())); // Set up header renderer the first time
if ((((SortableHeaderRenderer)tableHeader.getDefaultRenderer()).getSortedByColumn() == viewColumn)
&& (((SortableHeaderRenderer)tableHeader.getDefaultRenderer()).getSortedOrder() == order))
order = !order;
column = columnToFieldColumn(column);
boolean bSuccess = sortByColumn(column, order);
if (bSuccess)
setSortedByColumn(tableHeader, viewColumn, order);
}
}
}
};
table.getTableHeader().addMouseListener(mouseListener);
} } | public class class_name {
public void addMouseListenerToHeaderInTable(JTable table)
{
table.setColumnSelectionAllowed(false);
MouseListener mouseListener = new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
if (e.getSource() instanceof JTableHeader)
{ // Always
JTableHeader tableHeader = (JTableHeader)e.getSource();
TableColumnModel columnModel = tableHeader.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int column = tableHeader.getTable().convertColumnIndexToModel(viewColumn);
if(e.getClickCount() == 1 && column != -1)
{
boolean order = Constants.ASCENDING;
if ((e.getModifiers() & InputEvent.SHIFT_MASK) != 0)
order = !order;
if (!(tableHeader.getDefaultRenderer() instanceof SortableHeaderRenderer))
tableHeader.setDefaultRenderer(new SortableHeaderRenderer(tableHeader.getDefaultRenderer())); // Set up header renderer the first time
if ((((SortableHeaderRenderer)tableHeader.getDefaultRenderer()).getSortedByColumn() == viewColumn)
&& (((SortableHeaderRenderer)tableHeader.getDefaultRenderer()).getSortedOrder() == order))
order = !order;
column = columnToFieldColumn(column); // depends on control dependency: [if], data = [none]
boolean bSuccess = sortByColumn(column, order);
if (bSuccess)
setSortedByColumn(tableHeader, viewColumn, order);
}
}
}
};
table.getTableHeader().addMouseListener(mouseListener);
} } |
public class class_name {
@Override
public void updateDeployments(Iterable<Deployment> deployments) {
Deployment oldDeployment = deploymentColumn.getSelectedItem();
Deployment newDeployment = null;
if (oldDeployment != null) {
for (Deployment d : deployments) {
if (d.getName().equals(oldDeployment.getName())) {
newDeployment = d;
}
}
}
deploymentColumn.updateFrom(Lists.newArrayList(deployments), newDeployment);
} } | public class class_name {
@Override
public void updateDeployments(Iterable<Deployment> deployments) {
Deployment oldDeployment = deploymentColumn.getSelectedItem();
Deployment newDeployment = null;
if (oldDeployment != null) {
for (Deployment d : deployments) {
if (d.getName().equals(oldDeployment.getName())) {
newDeployment = d; // depends on control dependency: [if], data = [none]
}
}
}
deploymentColumn.updateFrom(Lists.newArrayList(deployments), newDeployment);
} } |
public class class_name {
public void arc(float x1, float y1, float x2, float y2, float startAng, float extent) {
ArrayList ar = bezierArc(x1, y1, x2, y2, startAng, extent);
if (ar.isEmpty())
return;
float pt[] = (float [])ar.get(0);
moveTo(pt[0], pt[1]);
for (int k = 0; k < ar.size(); ++k) {
pt = (float [])ar.get(k);
curveTo(pt[2], pt[3], pt[4], pt[5], pt[6], pt[7]);
}
} } | public class class_name {
public void arc(float x1, float y1, float x2, float y2, float startAng, float extent) {
ArrayList ar = bezierArc(x1, y1, x2, y2, startAng, extent);
if (ar.isEmpty())
return;
float pt[] = (float [])ar.get(0);
moveTo(pt[0], pt[1]);
for (int k = 0; k < ar.size(); ++k) {
pt = (float [])ar.get(k); // depends on control dependency: [for], data = [k]
curveTo(pt[2], pt[3], pt[4], pt[5], pt[6], pt[7]); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
public void marshall(CreateGeoMatchSetRequest createGeoMatchSetRequest, ProtocolMarshaller protocolMarshaller) {
if (createGeoMatchSetRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createGeoMatchSetRequest.getName(), NAME_BINDING);
protocolMarshaller.marshall(createGeoMatchSetRequest.getChangeToken(), CHANGETOKEN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(CreateGeoMatchSetRequest createGeoMatchSetRequest, ProtocolMarshaller protocolMarshaller) {
if (createGeoMatchSetRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createGeoMatchSetRequest.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createGeoMatchSetRequest.getChangeToken(), CHANGETOKEN_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 final void setItemId(final Long pItemId) {
this.itemId = pItemId;
if (this.itsId == null) {
this.itsId = new IdI18nSpecificInList();
}
this.itsId.setItemId(this.itemId);
} } | public class class_name {
public final void setItemId(final Long pItemId) {
this.itemId = pItemId;
if (this.itsId == null) {
this.itsId = new IdI18nSpecificInList(); // depends on control dependency: [if], data = [none]
}
this.itsId.setItemId(this.itemId);
} } |
public class class_name {
public boolean getBoolean(String name, boolean defaultValue) {
String valueString = getTrimmed(name);
if (null == valueString || "".equals(valueString)) {
return defaultValue;
}
valueString = valueString.toLowerCase();
if ("true".equals(valueString)) {
return true;
} else if ("false".equals(valueString)) {
return false;
} else {
return defaultValue;
}
} } | public class class_name {
public boolean getBoolean(String name, boolean defaultValue) {
String valueString = getTrimmed(name);
if (null == valueString || "".equals(valueString)) {
return defaultValue; // depends on control dependency: [if], data = [none]
}
valueString = valueString.toLowerCase();
if ("true".equals(valueString)) {
return true; // depends on control dependency: [if], data = [none]
} else if ("false".equals(valueString)) {
return false; // depends on control dependency: [if], data = [none]
} else {
return defaultValue; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public java.util.List<String> getEcsClusterArns() {
if (ecsClusterArns == null) {
ecsClusterArns = new com.amazonaws.internal.SdkInternalList<String>();
}
return ecsClusterArns;
} } | public class class_name {
public java.util.List<String> getEcsClusterArns() {
if (ecsClusterArns == null) {
ecsClusterArns = new com.amazonaws.internal.SdkInternalList<String>(); // depends on control dependency: [if], data = [none]
}
return ecsClusterArns;
} } |
public class class_name {
public Scheduler getScheduler() {
if (scheduler == null) {
scheduler = new Scheduler();
scheduler.setDaemon(true);
scheduler.start();
}
return scheduler;
} } | public class class_name {
public Scheduler getScheduler() {
if (scheduler == null) {
scheduler = new Scheduler(); // depends on control dependency: [if], data = [none]
scheduler.setDaemon(true); // depends on control dependency: [if], data = [none]
scheduler.start(); // depends on control dependency: [if], data = [none]
}
return scheduler;
} } |
public class class_name {
@SuppressWarnings({"SameParameterValue", "WeakerAccess"})
public static void createMetadataCache(final SlotReference slot, final int playlistId,
final File cache, final MetadataCacheCreationListener listener)
throws Exception {
ConnectionManager.ClientTask<Object> task = new ConnectionManager.ClientTask<Object>() {
@SuppressWarnings("SameReturnValue")
@Override
public Object useClient(Client client) throws Exception {
final List<Message> trackList;
if (playlistId == 0) {
trackList = MetadataFinder.getInstance().getFullTrackList(slot.slot, client, 0);
} else {
trackList = MetadataFinder.getInstance().getPlaylistItems(slot.slot, 0, playlistId, false, client);
}
MetadataCache.copyTracksToCache(trackList, playlistId, client, slot, cache, listener);
return null;
}
};
if (cache.exists() && !cache.delete()) {
logger.warn("Unable to delete cache file, {}", cache);
}
ConnectionManager.getInstance().invokeWithClientSession(slot.player, task, "building metadata cache");
} } | public class class_name {
@SuppressWarnings({"SameParameterValue", "WeakerAccess"})
public static void createMetadataCache(final SlotReference slot, final int playlistId,
final File cache, final MetadataCacheCreationListener listener)
throws Exception {
ConnectionManager.ClientTask<Object> task = new ConnectionManager.ClientTask<Object>() {
@SuppressWarnings("SameReturnValue")
@Override
public Object useClient(Client client) throws Exception {
final List<Message> trackList;
if (playlistId == 0) {
trackList = MetadataFinder.getInstance().getFullTrackList(slot.slot, client, 0); // depends on control dependency: [if], data = [0)]
} else {
trackList = MetadataFinder.getInstance().getPlaylistItems(slot.slot, 0, playlistId, false, client); // depends on control dependency: [if], data = [none]
}
MetadataCache.copyTracksToCache(trackList, playlistId, client, slot, cache, listener);
return null;
}
};
if (cache.exists() && !cache.delete()) {
logger.warn("Unable to delete cache file, {}", cache);
}
ConnectionManager.getInstance().invokeWithClientSession(slot.player, task, "building metadata cache");
} } |
public class class_name {
public java.lang.String getResult() {
java.lang.Object ref = result_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
result_ = s;
}
return s;
}
} } | public class class_name {
public java.lang.String getResult() {
java.lang.Object ref = result_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref; // depends on control dependency: [if], data = [none]
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
result_ = s; // depends on control dependency: [if], data = [none]
}
return s; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setBackgroundColor(final Color COLOR) {
if (null == backgroundColor) {
_backgroundColor = COLOR;
fireTileEvent(REDRAW_EVENT);
} else {
backgroundColor.set(COLOR);
}
} } | public class class_name {
public void setBackgroundColor(final Color COLOR) {
if (null == backgroundColor) {
_backgroundColor = COLOR; // depends on control dependency: [if], data = [none]
fireTileEvent(REDRAW_EVENT); // depends on control dependency: [if], data = [none]
} else {
backgroundColor.set(COLOR); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void insertSequence(final List<Group> groups) {
if (groups != null && !groups.isEmpty() && !sequenceMap.containsValue(groups)) {
sequenceMap.put(groups.get(0).getSequence(), groups);
}
} } | public class class_name {
public void insertSequence(final List<Group> groups) {
if (groups != null && !groups.isEmpty() && !sequenceMap.containsValue(groups)) {
sequenceMap.put(groups.get(0).getSequence(), groups); // depends on control dependency: [if], data = [(groups]
}
} } |
public class class_name {
@SuppressWarnings("unchecked")
private Repository<Entity> decorateRepository(
Repository<Entity> repository, DecoratorConfiguration configuration) {
Map<String, Map<String, Object>> parameterMap = getParameterMap(configuration);
List<DecoratorParameters> decoratorParameters =
configuration.getDecoratorParameters().collect(toList());
for (DecoratorParameters decoratorParam : decoratorParameters) {
DynamicRepositoryDecoratorFactory factory =
factories.get(decoratorParam.getDecorator().getId());
if (factory != null) {
repository =
factory.createDecoratedRepository(repository, parameterMap.get(factory.getId()));
}
}
return repository;
} } | public class class_name {
@SuppressWarnings("unchecked")
private Repository<Entity> decorateRepository(
Repository<Entity> repository, DecoratorConfiguration configuration) {
Map<String, Map<String, Object>> parameterMap = getParameterMap(configuration);
List<DecoratorParameters> decoratorParameters =
configuration.getDecoratorParameters().collect(toList());
for (DecoratorParameters decoratorParam : decoratorParameters) {
DynamicRepositoryDecoratorFactory factory =
factories.get(decoratorParam.getDecorator().getId());
if (factory != null) {
repository =
factory.createDecoratedRepository(repository, parameterMap.get(factory.getId())); // depends on control dependency: [if], data = [none]
}
}
return repository;
} } |
public class class_name {
private static int partition(Object[] a, int start, int end, Comparator<Object> cmp) {
final int p = median(a, start, end, cmp);
final Object pivot = a[p];
a[p] = a[start];
a[start] = pivot;
int i = start;
int j = end + 1;
while (true) {
while (cmp.compare(a[++i], pivot) < 0) {
if (i == end) {
break;
}
}
while (cmp.compare(a[--j], pivot) >= 0) {
if (j == start) {
break;
}
}
if (i >= j) {
break;
}
swap(a, i, j);
}
swap(a, start, j);
return j;
} } | public class class_name {
private static int partition(Object[] a, int start, int end, Comparator<Object> cmp) {
final int p = median(a, start, end, cmp);
final Object pivot = a[p];
a[p] = a[start];
a[start] = pivot;
int i = start;
int j = end + 1;
while (true) {
while (cmp.compare(a[++i], pivot) < 0) {
if (i == end) {
break;
}
}
while (cmp.compare(a[--j], pivot) >= 0) {
if (j == start) {
break;
}
}
if (i >= j) {
break;
}
swap(a, i, j); // depends on control dependency: [while], data = [none]
}
swap(a, start, j);
return j;
} } |
public class class_name {
private boolean refreshChildPadding(int i, ChildDrawable r) {
if (r.mDrawable != null) {
final Rect rect = mTmpRect;
r.mDrawable.getPadding(rect);
if (rect.left != mPaddingL[i] || rect.top != mPaddingT[i] ||
rect.right != mPaddingR[i] || rect.bottom != mPaddingB[i]) {
mPaddingL[i] = rect.left;
mPaddingT[i] = rect.top;
mPaddingR[i] = rect.right;
mPaddingB[i] = rect.bottom;
return true;
}
}
return false;
} } | public class class_name {
private boolean refreshChildPadding(int i, ChildDrawable r) {
if (r.mDrawable != null) {
final Rect rect = mTmpRect;
r.mDrawable.getPadding(rect); // depends on control dependency: [if], data = [none]
if (rect.left != mPaddingL[i] || rect.top != mPaddingT[i] ||
rect.right != mPaddingR[i] || rect.bottom != mPaddingB[i]) {
mPaddingL[i] = rect.left; // depends on control dependency: [if], data = [none]
mPaddingT[i] = rect.top; // depends on control dependency: [if], data = [none]
mPaddingR[i] = rect.right; // depends on control dependency: [if], data = [none]
mPaddingB[i] = rect.bottom; // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
public static boolean isBetweenDate(Date startDate, Date endDate, Date specificDate) {
long startTm = getDateCeil(startDate).getTimeInMillis();
long endTm = getDateCeil(endDate).getTimeInMillis();
long specificTm = getDateCeil(specificDate).getTimeInMillis();
if (startTm <= specificTm && endTm >= specificTm) {
return true;
}
return false;
} } | public class class_name {
public static boolean isBetweenDate(Date startDate, Date endDate, Date specificDate) {
long startTm = getDateCeil(startDate).getTimeInMillis();
long endTm = getDateCeil(endDate).getTimeInMillis();
long specificTm = getDateCeil(specificDate).getTimeInMillis();
if (startTm <= specificTm && endTm >= specificTm) {
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
private double[] parseVector(String s) {
String[] entries = WHITESPACE_PATTERN.split(s);
double[] d = new double[entries.length];
for(int i = 0; i < entries.length; i++) {
try {
d[i] = ParseUtil.parseDouble(entries[i]);
}
catch(NumberFormatException e) {
throw new AbortException("Could not parse vector.");
}
}
return d;
} } | public class class_name {
private double[] parseVector(String s) {
String[] entries = WHITESPACE_PATTERN.split(s);
double[] d = new double[entries.length];
for(int i = 0; i < entries.length; i++) {
try {
d[i] = ParseUtil.parseDouble(entries[i]); // depends on control dependency: [try], data = [none]
}
catch(NumberFormatException e) {
throw new AbortException("Could not parse vector.");
} // depends on control dependency: [catch], data = [none]
}
return d;
} } |
public class class_name {
public List<FacesConfigFlowDefinitionViewType<FacesConfigFlowDefinitionType<T>>> getAllView()
{
List<FacesConfigFlowDefinitionViewType<FacesConfigFlowDefinitionType<T>>> list = new ArrayList<FacesConfigFlowDefinitionViewType<FacesConfigFlowDefinitionType<T>>>();
List<Node> nodeList = childNode.get("view");
for(Node node: nodeList)
{
FacesConfigFlowDefinitionViewType<FacesConfigFlowDefinitionType<T>> type = new FacesConfigFlowDefinitionViewTypeImpl<FacesConfigFlowDefinitionType<T>>(this, "view", childNode, node);
list.add(type);
}
return list;
} } | public class class_name {
public List<FacesConfigFlowDefinitionViewType<FacesConfigFlowDefinitionType<T>>> getAllView()
{
List<FacesConfigFlowDefinitionViewType<FacesConfigFlowDefinitionType<T>>> list = new ArrayList<FacesConfigFlowDefinitionViewType<FacesConfigFlowDefinitionType<T>>>();
List<Node> nodeList = childNode.get("view");
for(Node node: nodeList)
{
FacesConfigFlowDefinitionViewType<FacesConfigFlowDefinitionType<T>> type = new FacesConfigFlowDefinitionViewTypeImpl<FacesConfigFlowDefinitionType<T>>(this, "view", childNode, node);
list.add(type); // depends on control dependency: [for], data = [none]
}
return list;
} } |
public class class_name {
protected String createRoleQuery(String mainQuery, boolean includeSubOus, boolean readRoles) {
String sqlQuery = m_sqlManager.readQuery(mainQuery);
sqlQuery += " ";
if (includeSubOus) {
sqlQuery += m_sqlManager.readQuery("C_GROUPS_GROUP_OU_LIKE_1");
} else {
sqlQuery += m_sqlManager.readQuery("C_GROUPS_GROUP_OU_EQUALS_1");
}
sqlQuery += AND_CONDITION;
if (readRoles) {
sqlQuery += m_sqlManager.readQuery("C_GROUPS_SELECT_ROLES_1");
} else {
sqlQuery += m_sqlManager.readQuery("C_GROUPS_SELECT_GROUPS_1");
}
sqlQuery += " ";
sqlQuery += m_sqlManager.readQuery("C_GROUPS_ORDER_0");
return sqlQuery;
} } | public class class_name {
protected String createRoleQuery(String mainQuery, boolean includeSubOus, boolean readRoles) {
String sqlQuery = m_sqlManager.readQuery(mainQuery);
sqlQuery += " ";
if (includeSubOus) {
sqlQuery += m_sqlManager.readQuery("C_GROUPS_GROUP_OU_LIKE_1"); // depends on control dependency: [if], data = [none]
} else {
sqlQuery += m_sqlManager.readQuery("C_GROUPS_GROUP_OU_EQUALS_1"); // depends on control dependency: [if], data = [none]
}
sqlQuery += AND_CONDITION;
if (readRoles) {
sqlQuery += m_sqlManager.readQuery("C_GROUPS_SELECT_ROLES_1"); // depends on control dependency: [if], data = [none]
} else {
sqlQuery += m_sqlManager.readQuery("C_GROUPS_SELECT_GROUPS_1"); // depends on control dependency: [if], data = [none]
}
sqlQuery += " ";
sqlQuery += m_sqlManager.readQuery("C_GROUPS_ORDER_0");
return sqlQuery;
} } |
public class class_name {
public static boolean compareStreams( InputStream in1, InputStream in2 )
throws IOException
{
boolean moreOnIn1;
do
{
int v1 = in1.read();
int v2 = in2.read();
if( v1 != v2 )
{
return false;
}
moreOnIn1 = v1 != -1;
}
while( moreOnIn1 );
boolean noMoreOnIn2Either = in2.read() == -1;
return noMoreOnIn2Either;
} } | public class class_name {
public static boolean compareStreams( InputStream in1, InputStream in2 )
throws IOException
{
boolean moreOnIn1;
do
{
int v1 = in1.read();
int v2 = in2.read();
if( v1 != v2 )
{
return false; // depends on control dependency: [if], data = [none]
}
moreOnIn1 = v1 != -1;
}
while( moreOnIn1 );
boolean noMoreOnIn2Either = in2.read() == -1;
return noMoreOnIn2Either;
} } |
public class class_name {
private static void writeRow(final PrintWriter writer, final UicStats.Stat stat) {
writer.print("<tr>");
writer.print("<td>" + stat.getClassName() + "</td>");
writer.print("<td>" + stat.getModelStateAsString() + "</td>");
if (stat.getSerializedSize() > 0) {
writer.print("<td>" + stat.getSerializedSize() + "</td>");
} else {
writer.print("<td> </td>");
}
writer.print("<td>" + stat.getRef() + "</td>");
writer.print("<td>" + stat.getName() + "</td>");
if (stat.getComment() == null) {
writer.print("<td> </td>");
} else {
writer.print("<td>" + stat.getComment() + "</td>");
}
writer.println("</tr>");
} } | public class class_name {
private static void writeRow(final PrintWriter writer, final UicStats.Stat stat) {
writer.print("<tr>");
writer.print("<td>" + stat.getClassName() + "</td>");
writer.print("<td>" + stat.getModelStateAsString() + "</td>");
if (stat.getSerializedSize() > 0) {
writer.print("<td>" + stat.getSerializedSize() + "</td>"); // depends on control dependency: [if], data = [none]
} else {
writer.print("<td> </td>"); // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
}
writer.print("<td>" + stat.getRef() + "</td>");
writer.print("<td>" + stat.getName() + "</td>");
if (stat.getComment() == null) {
writer.print("<td> </td>"); // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
} else {
writer.print("<td>" + stat.getComment() + "</td>"); // depends on control dependency: [if], data = [none]
}
writer.println("</tr>");
} } |
public class class_name {
public static double parseDouble(final byte[] str, final int start, final int end) {
if(start >= end) {
throw EMPTY_STRING;
}
// Current position and character.
int pos = start;
byte cur = str[pos];
// Match for NaN spellings
if(matchNaN(str, cur, pos, end)) {
return Double.NaN;
}
// Match sign
boolean isNegative = (cur == '-');
// Carefully consume the - character, update c and i:
if((isNegative || (cur == '+')) && (++pos < end)) {
cur = str[pos];
}
if(matchInf(str, cur, pos, end)) {
return isNegative ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
}
// Begin parsing real numbers!
if(((cur < '0') || (cur > '9')) && (cur != '.')) {
throw NOT_A_NUMBER;
}
// Parse digits into a long, remember offset of decimal point.
long decimal = 0;
int decimalPoint = -1;
while(true) {
final int digit = cur - '0';
if((digit >= 0) && (digit <= 9)) {
final long tmp = (decimal << 3) + (decimal << 1) + digit;
if(tmp >= decimal) {
decimal = tmp; // Otherwise, silently ignore the extra digits.
}
else if(++decimalPoint == 0) { // Because we ignored the digit
throw PRECISION_OVERFLOW;
}
}
else if((cur == '.') && (decimalPoint < 0)) {
decimalPoint = pos;
}
else { // No more digits, or a second dot.
break;
}
if(++pos >= end) {
break;
}
cur = str[pos];
}
// We need the offset from the back for adjusting the exponent:
// Note that we need the current value of i!
decimalPoint = (decimalPoint >= 0) ? pos - decimalPoint - 1 : 0;
// Reads exponent.
int exp = 0;
if((pos + 1 < end) && ((cur == 'E') || (cur == 'e'))) {
cur = str[++pos];
final boolean isNegativeExp = (cur == '-');
if((isNegativeExp || (cur == '+')) && (++pos < end)) {
cur = str[pos];
}
if((cur < '0') || (cur > '9')) { // At least one digit required.
throw INVALID_EXPONENT;
}
while(true) {
final int digit = cur - '0';
if(digit < 0 || digit > 9) {
break;
}
exp = (exp << 3) + (exp << 1) + digit;
if(exp > Double.MAX_EXPONENT) {
throw EXPONENT_OVERFLOW;
}
if(++pos >= end) {
break;
}
cur = str[pos];
}
exp = isNegativeExp ? -exp : exp;
}
// Adjust exponent by the offset of the dot in our long.
exp = decimalPoint > 0 ? (exp - decimalPoint) : exp;
if(pos != end) {
throw TRAILING_CHARACTERS;
}
return BitsUtil.lpow10(isNegative ? -decimal : decimal, exp);
} } | public class class_name {
public static double parseDouble(final byte[] str, final int start, final int end) {
if(start >= end) {
throw EMPTY_STRING;
}
// Current position and character.
int pos = start;
byte cur = str[pos];
// Match for NaN spellings
if(matchNaN(str, cur, pos, end)) {
return Double.NaN; // depends on control dependency: [if], data = [none]
}
// Match sign
boolean isNegative = (cur == '-');
// Carefully consume the - character, update c and i:
if((isNegative || (cur == '+')) && (++pos < end)) {
cur = str[pos]; // depends on control dependency: [if], data = [none]
}
if(matchInf(str, cur, pos, end)) {
return isNegative ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; // depends on control dependency: [if], data = [none]
}
// Begin parsing real numbers!
if(((cur < '0') || (cur > '9')) && (cur != '.')) {
throw NOT_A_NUMBER;
}
// Parse digits into a long, remember offset of decimal point.
long decimal = 0;
int decimalPoint = -1;
while(true) {
final int digit = cur - '0';
if((digit >= 0) && (digit <= 9)) {
final long tmp = (decimal << 3) + (decimal << 1) + digit;
if(tmp >= decimal) {
decimal = tmp; // Otherwise, silently ignore the extra digits. // depends on control dependency: [if], data = [none]
}
else if(++decimalPoint == 0) { // Because we ignored the digit
throw PRECISION_OVERFLOW;
}
}
else if((cur == '.') && (decimalPoint < 0)) {
decimalPoint = pos; // depends on control dependency: [if], data = [none]
}
else { // No more digits, or a second dot.
break;
}
if(++pos >= end) {
break;
}
cur = str[pos]; // depends on control dependency: [while], data = [none]
}
// We need the offset from the back for adjusting the exponent:
// Note that we need the current value of i!
decimalPoint = (decimalPoint >= 0) ? pos - decimalPoint - 1 : 0;
// Reads exponent.
int exp = 0;
if((pos + 1 < end) && ((cur == 'E') || (cur == 'e'))) {
cur = str[++pos]; // depends on control dependency: [if], data = [none]
final boolean isNegativeExp = (cur == '-');
if((isNegativeExp || (cur == '+')) && (++pos < end)) {
cur = str[pos]; // depends on control dependency: [if], data = [none]
}
if((cur < '0') || (cur > '9')) { // At least one digit required.
throw INVALID_EXPONENT;
}
while(true) {
final int digit = cur - '0';
if(digit < 0 || digit > 9) {
break;
}
exp = (exp << 3) + (exp << 1) + digit; // depends on control dependency: [while], data = [none]
if(exp > Double.MAX_EXPONENT) {
throw EXPONENT_OVERFLOW;
}
if(++pos >= end) {
break;
}
cur = str[pos]; // depends on control dependency: [while], data = [none]
}
exp = isNegativeExp ? -exp : exp; // depends on control dependency: [if], data = [none]
}
// Adjust exponent by the offset of the dot in our long.
exp = decimalPoint > 0 ? (exp - decimalPoint) : exp;
if(pos != end) {
throw TRAILING_CHARACTERS;
}
return BitsUtil.lpow10(isNegative ? -decimal : decimal, exp);
} } |
public class class_name {
public double getLongitudeSpan() {
if (this.mapView.getWidth() > 0 && this.mapView.getHeight() > 0) {
LatLong left = fromPixels(0, 0);
LatLong right = fromPixels(this.mapView.getWidth(), 0);
return Math.abs(left.longitude - right.longitude);
}
throw new IllegalStateException(INVALID_MAP_VIEW_DIMENSIONS);
} } | public class class_name {
public double getLongitudeSpan() {
if (this.mapView.getWidth() > 0 && this.mapView.getHeight() > 0) {
LatLong left = fromPixels(0, 0);
LatLong right = fromPixels(this.mapView.getWidth(), 0);
return Math.abs(left.longitude - right.longitude); // depends on control dependency: [if], data = [none]
}
throw new IllegalStateException(INVALID_MAP_VIEW_DIMENSIONS);
} } |
public class class_name {
public TaskDeleteOptions withOcpDate(DateTime ocpDate) {
if (ocpDate == null) {
this.ocpDate = null;
} else {
this.ocpDate = new DateTimeRfc1123(ocpDate);
}
return this;
} } | public class class_name {
public TaskDeleteOptions withOcpDate(DateTime ocpDate) {
if (ocpDate == null) {
this.ocpDate = null; // depends on control dependency: [if], data = [none]
} else {
this.ocpDate = new DateTimeRfc1123(ocpDate); // depends on control dependency: [if], data = [(ocpDate]
}
return this;
} } |
public class class_name {
protected void addSearchField(
CmsXmlContentDefinition contentDefinition,
CmsSearchField field,
I_CmsXmlContentHandler.MappingType type) {
Locale locale = null;
if (field instanceof CmsSolrField) {
locale = ((CmsSolrField)field).getLocale();
}
String key = CmsXmlUtils.concatXpath(locale != null ? locale.toString() : null, field.getName());
switch (type) {
case PAGE:
m_searchFieldsPage.put(key, field);
break;
case ELEMENT:
default:
m_searchFields.put(key, field);
break;
}
} } | public class class_name {
protected void addSearchField(
CmsXmlContentDefinition contentDefinition,
CmsSearchField field,
I_CmsXmlContentHandler.MappingType type) {
Locale locale = null;
if (field instanceof CmsSolrField) {
locale = ((CmsSolrField)field).getLocale(); // depends on control dependency: [if], data = [none]
}
String key = CmsXmlUtils.concatXpath(locale != null ? locale.toString() : null, field.getName());
switch (type) {
case PAGE:
m_searchFieldsPage.put(key, field);
break;
case ELEMENT:
default:
m_searchFields.put(key, field);
break;
}
} } |
public class class_name {
public void setSorting(List<SortProperty> newSorting) {
Validate.notNull(newSorting, "Sorting required");
if (!sorting.equals(newSorting)) {
sorting.clear();
sorting.addAll(newSorting);
selectionIndex = -1;
clearCache();
}
} } | public class class_name {
public void setSorting(List<SortProperty> newSorting) {
Validate.notNull(newSorting, "Sorting required");
if (!sorting.equals(newSorting)) {
sorting.clear(); // depends on control dependency: [if], data = [none]
sorting.addAll(newSorting); // depends on control dependency: [if], data = [none]
selectionIndex = -1; // depends on control dependency: [if], data = [none]
clearCache(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private String buildPrimaryKey(final IClassContainer container) {
final Map<Field, FieldContainer> containerMap = container.getFormatSupported(Format.SQL);
for (Map.Entry<Field, FieldContainer> entry : containerMap.entrySet()) {
if (entry.getValue().isEnumerable()) {
return entry.getValue().getExportName();
} else if (entry.getKey().getName().equalsIgnoreCase("id")
|| entry.getKey().getName().equalsIgnoreCase("uid")) {
return entry.getValue().getExportName();
}
}
return containerMap.entrySet().iterator().next().getValue().getExportName();
} } | public class class_name {
private String buildPrimaryKey(final IClassContainer container) {
final Map<Field, FieldContainer> containerMap = container.getFormatSupported(Format.SQL);
for (Map.Entry<Field, FieldContainer> entry : containerMap.entrySet()) {
if (entry.getValue().isEnumerable()) {
return entry.getValue().getExportName(); // depends on control dependency: [if], data = [none]
} else if (entry.getKey().getName().equalsIgnoreCase("id")
|| entry.getKey().getName().equalsIgnoreCase("uid")) {
return entry.getValue().getExportName(); // depends on control dependency: [if], data = [none]
}
}
return containerMap.entrySet().iterator().next().getValue().getExportName();
} } |
public class class_name {
protected List<String> buildArgumentList() {
// Use file.separator as a wild guess as to whether this is Windows
final List<String> args = new ArrayList<>();
if (!StringUtils.isEmpty(getSettings().getString(Settings.KEYS.ANALYZER_ASSEMBLY_DOTNET_PATH))) {
args.add(getSettings().getString(Settings.KEYS.ANALYZER_ASSEMBLY_DOTNET_PATH));
} else if (isDotnetPath()) {
args.add("dotnet");
} else {
return null;
}
args.add(grokAssembly.getPath());
return args;
} } | public class class_name {
protected List<String> buildArgumentList() {
// Use file.separator as a wild guess as to whether this is Windows
final List<String> args = new ArrayList<>();
if (!StringUtils.isEmpty(getSettings().getString(Settings.KEYS.ANALYZER_ASSEMBLY_DOTNET_PATH))) {
args.add(getSettings().getString(Settings.KEYS.ANALYZER_ASSEMBLY_DOTNET_PATH)); // depends on control dependency: [if], data = [none]
} else if (isDotnetPath()) {
args.add("dotnet"); // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
args.add(grokAssembly.getPath());
return args;
} } |
public class class_name {
public void setTrajectoryInfo( Dimension trajDim, Variable trajVar,
Dimension timeDim, Variable timeVar,
Variable latVar, Variable lonVar, Variable elevVar )
throws IOException
{
this.trajDim = trajDim;
this.trajVar = trajVar;
this.timeDim = timeDim;
this.timeVar = timeVar;
this.latVar = latVar;
this.lonVar = lonVar;
this.elevVar = elevVar;
trajectoryNumPoint = this.timeDim.getLength();
timeVarUnitsString = this.timeVar.findAttribute( "units" ).getStringValue();
// Check that time, lat, lon, elev units are acceptable.
if ( DateUnit.getStandardDate( timeVarUnitsString ) == null )
throw new IllegalArgumentException( "Units of time variable <" + timeVarUnitsString + "> not a date unit." );
String latVarUnitsString = this.latVar.findAttribute( "units" ).getStringValue();
if ( !SimpleUnit.isCompatible( latVarUnitsString, "degrees_north" ) )
throw new IllegalArgumentException( "Units of lat var <" + latVarUnitsString + "> not compatible with \"degrees_north\"." );
String lonVarUnitsString = this.lonVar.findAttribute( "units" ).getStringValue();
if ( !SimpleUnit.isCompatible( lonVarUnitsString, "degrees_east" ) )
throw new IllegalArgumentException( "Units of lon var <" + lonVarUnitsString + "> not compatible with \"degrees_east\"." );
String elevVarUnitsString = this.elevVar.findAttribute( "units" ).getStringValue();
if ( !SimpleUnit.isCompatible( elevVarUnitsString, "meters" ) )
throw new IllegalArgumentException( "Units of elev var <" + elevVarUnitsString + "> not compatible with \"meters\"." );
try
{
elevVarUnitsConversionFactor = getMetersConversionFactor( elevVarUnitsString );
}
catch ( Exception e )
{
throw new IllegalArgumentException( "Exception on getMetersConversionFactor() for the units of elev var <" + elevVarUnitsString + ">." );
}
if ( this.netcdfDataset.hasUnlimitedDimension() && this.netcdfDataset.getUnlimitedDimension().equals( timeDim))
{
this.netcdfDataset.sendIospMessage(NetcdfFile.IOSP_MESSAGE_ADD_RECORD_STRUCTURE);
this.recordVar = (Structure) this.netcdfDataset.getRootGroup().findVariable( "record");
} else {
this.recordVar = new StructurePseudo( this.netcdfDataset, null, "record", timeDim);
}
// @todo HACK, HACK, HACK - remove once addRecordStructure() deals with ncd attribute changes.
Variable latVarInRecVar = this.recordVar.findVariable( this.latVar.getFullNameEscaped() );
Attribute latVarUnitsAtt = latVarInRecVar.findAttribute( "units");
if ( latVarUnitsAtt != null && !latVarUnitsString.equals( latVarUnitsAtt.getStringValue() ) )
latVarInRecVar.addAttribute( new Attribute( "units", latVarUnitsString ) );
Variable lonVarInRecVar = this.recordVar.findVariable( this.lonVar.getFullNameEscaped() );
Attribute lonVarUnitsAtt = lonVarInRecVar.findAttribute( "units" );
if ( lonVarUnitsAtt != null && !lonVarUnitsString.equals( lonVarUnitsAtt.getStringValue() ) )
lonVarInRecVar.addAttribute( new Attribute( "units", lonVarUnitsString ) );
Variable elevVarInRecVar = this.recordVar.findVariable( this.elevVar.getFullNameEscaped() );
Attribute elevVarUnitsAtt = elevVarInRecVar.findAttribute( "units" );
if ( elevVarUnitsAtt != null && !elevVarUnitsString.equals( elevVarUnitsAtt.getStringValue() ) )
elevVarInRecVar.addAttribute( new Attribute( "units", elevVarUnitsString ) );
trajectoryVarsMap = new HashMap();
for ( Iterator it = this.netcdfDataset.getRootGroup().getVariables().iterator(); it.hasNext(); )
{
Variable curVar = (Variable) it.next();
if ( curVar.getRank() >= 2 &&
// !curVar.equals( this.trajVar) && // These two are both one dimensional arrays
// !curVar.equals( this.timeVar) && //
! curVar.equals( this.latVar) &&
! curVar.equals( this.lonVar) &&
! curVar.equals( this.elevVar) &&
( this.recordVar == null ? true : ! curVar.equals( this.recordVar)))
{
MyTypedDataVariable typedVar = new MyTypedDataVariable( new VariableDS( null, curVar, true ) );
dataVariables.add( typedVar);
trajectoryVarsMap.put( typedVar.getShortName(), typedVar);
}
}
Range startPointRange = null;
Range endPointRange = null;
try
{
startPointRange = new Range( 0, 0);
endPointRange = new Range( trajectoryNumPoint-1, trajectoryNumPoint-1);
}
catch ( InvalidRangeException e )
{
IOException ioe = new IOException( "Start or end point range invalid: " + e.getMessage());
ioe.initCause( e);
throw( ioe);
}
List section0 = new ArrayList(1);
List section1 = new ArrayList(1);
section0.add( startPointRange);
section1.add( endPointRange);
Array startTimeArray;
Array endTimeArray;
try
{
startTimeArray = this.timeVar.read( section0);
endTimeArray = this.timeVar.read( section1);
}
catch ( InvalidRangeException e )
{
IOException ioe = new IOException( "Invalid range during read of start or end point: " + e.getMessage());
ioe.initCause( e);
throw( ioe);
}
String startTimeString;
String endTimeString;
if ( this.timeVar.getDataType().equals( DataType.DOUBLE))
{
startTimeString = startTimeArray.getDouble( startTimeArray.getIndex() ) + " " + timeVarUnitsString;
endTimeString = endTimeArray.getDouble( endTimeArray.getIndex() ) + " " + timeVarUnitsString;
}
else if ( this.timeVar.getDataType().equals( DataType.FLOAT))
{
startTimeString = startTimeArray.getFloat( startTimeArray.getIndex() ) + " " + timeVarUnitsString;
endTimeString = endTimeArray.getFloat( endTimeArray.getIndex() ) + " " + timeVarUnitsString;
}
else if ( this.timeVar.getDataType().equals( DataType.INT ) )
{
startTimeString = startTimeArray.getInt( startTimeArray.getIndex() ) + " " + timeVarUnitsString;
endTimeString = endTimeArray.getInt( endTimeArray.getIndex() ) + " " + timeVarUnitsString;
}
else
{
String tmpMsg = "Time var <" + this.timeVar.getFullName() + "> is not a double, float, or integer <" + timeVar.getDataType().toString() + ">.";
//log.error( tmpMsg );
throw new IllegalArgumentException( tmpMsg);
}
startDate = DateUnit.getStandardDate( startTimeString );
endDate = DateUnit.getStandardDate( endTimeString);
trajectoryIds = new ArrayList();
trajectories = new ArrayList();
trajectoriesMap = new HashMap();
Array trajArray = this.trajVar.read();
Index index = trajArray.getIndex();
for ( int i = 0; i < trajArray.getSize(); i++ )
{
String curTrajId;
if ( this.trajVar.getDataType().equals( DataType.STRING ) )
{
curTrajId = (String) trajArray.getObject( index.set( i ) );
}
else if ( this.trajVar.getDataType().equals( DataType.DOUBLE ) )
{
curTrajId = String.valueOf( trajArray.getDouble( index.set( i ) ) );
}
else if ( this.trajVar.getDataType().equals( DataType.FLOAT ) )
{
curTrajId = String.valueOf( trajArray.getFloat( index.set( i ) ) );
}
else if ( this.trajVar.getDataType().equals( DataType.INT ) )
{
curTrajId = String.valueOf( trajArray.getInt( index.set( i ) ) );
}
else
{
String tmpMsg = "Trajectory var <" + this.trajVar.getFullName() + "> is not a string, double, float, or integer <" + this.trajVar.getDataType().toString() + ">.";
//log.error( tmpMsg );
throw new IllegalStateException( tmpMsg );
}
MultiTrajectory curTraj = new MultiTrajectory( curTrajId, i, trajectoryNumPoint, startDate, endDate,
this.trajVar, this.timeVar, timeVarUnitsString,
this.latVar, this.lonVar, this.elevVar,
dataVariables, trajectoryVarsMap );
trajectoryIds.add( curTrajId);
trajectories.add( curTraj);
trajectoriesMap.put( curTrajId, curTraj );
}
} } | public class class_name {
public void setTrajectoryInfo( Dimension trajDim, Variable trajVar,
Dimension timeDim, Variable timeVar,
Variable latVar, Variable lonVar, Variable elevVar )
throws IOException
{
this.trajDim = trajDim;
this.trajVar = trajVar;
this.timeDim = timeDim;
this.timeVar = timeVar;
this.latVar = latVar;
this.lonVar = lonVar;
this.elevVar = elevVar;
trajectoryNumPoint = this.timeDim.getLength();
timeVarUnitsString = this.timeVar.findAttribute( "units" ).getStringValue();
// Check that time, lat, lon, elev units are acceptable.
if ( DateUnit.getStandardDate( timeVarUnitsString ) == null )
throw new IllegalArgumentException( "Units of time variable <" + timeVarUnitsString + "> not a date unit." );
String latVarUnitsString = this.latVar.findAttribute( "units" ).getStringValue();
if ( !SimpleUnit.isCompatible( latVarUnitsString, "degrees_north" ) )
throw new IllegalArgumentException( "Units of lat var <" + latVarUnitsString + "> not compatible with \"degrees_north\"." );
String lonVarUnitsString = this.lonVar.findAttribute( "units" ).getStringValue();
if ( !SimpleUnit.isCompatible( lonVarUnitsString, "degrees_east" ) )
throw new IllegalArgumentException( "Units of lon var <" + lonVarUnitsString + "> not compatible with \"degrees_east\"." );
String elevVarUnitsString = this.elevVar.findAttribute( "units" ).getStringValue();
if ( !SimpleUnit.isCompatible( elevVarUnitsString, "meters" ) )
throw new IllegalArgumentException( "Units of elev var <" + elevVarUnitsString + "> not compatible with \"meters\"." );
try
{
elevVarUnitsConversionFactor = getMetersConversionFactor( elevVarUnitsString );
}
catch ( Exception e )
{
throw new IllegalArgumentException( "Exception on getMetersConversionFactor() for the units of elev var <" + elevVarUnitsString + ">." );
}
if ( this.netcdfDataset.hasUnlimitedDimension() && this.netcdfDataset.getUnlimitedDimension().equals( timeDim))
{
this.netcdfDataset.sendIospMessage(NetcdfFile.IOSP_MESSAGE_ADD_RECORD_STRUCTURE);
this.recordVar = (Structure) this.netcdfDataset.getRootGroup().findVariable( "record");
} else {
this.recordVar = new StructurePseudo( this.netcdfDataset, null, "record", timeDim);
}
// @todo HACK, HACK, HACK - remove once addRecordStructure() deals with ncd attribute changes.
Variable latVarInRecVar = this.recordVar.findVariable( this.latVar.getFullNameEscaped() );
Attribute latVarUnitsAtt = latVarInRecVar.findAttribute( "units");
if ( latVarUnitsAtt != null && !latVarUnitsString.equals( latVarUnitsAtt.getStringValue() ) )
latVarInRecVar.addAttribute( new Attribute( "units", latVarUnitsString ) );
Variable lonVarInRecVar = this.recordVar.findVariable( this.lonVar.getFullNameEscaped() );
Attribute lonVarUnitsAtt = lonVarInRecVar.findAttribute( "units" );
if ( lonVarUnitsAtt != null && !lonVarUnitsString.equals( lonVarUnitsAtt.getStringValue() ) )
lonVarInRecVar.addAttribute( new Attribute( "units", lonVarUnitsString ) );
Variable elevVarInRecVar = this.recordVar.findVariable( this.elevVar.getFullNameEscaped() );
Attribute elevVarUnitsAtt = elevVarInRecVar.findAttribute( "units" );
if ( elevVarUnitsAtt != null && !elevVarUnitsString.equals( elevVarUnitsAtt.getStringValue() ) )
elevVarInRecVar.addAttribute( new Attribute( "units", elevVarUnitsString ) );
trajectoryVarsMap = new HashMap();
for ( Iterator it = this.netcdfDataset.getRootGroup().getVariables().iterator(); it.hasNext(); )
{
Variable curVar = (Variable) it.next();
if ( curVar.getRank() >= 2 &&
// !curVar.equals( this.trajVar) && // These two are both one dimensional arrays
// !curVar.equals( this.timeVar) && //
! curVar.equals( this.latVar) &&
! curVar.equals( this.lonVar) &&
! curVar.equals( this.elevVar) &&
( this.recordVar == null ? true : ! curVar.equals( this.recordVar)))
{
MyTypedDataVariable typedVar = new MyTypedDataVariable( new VariableDS( null, curVar, true ) );
dataVariables.add( typedVar); // depends on control dependency: [if], data = [none]
trajectoryVarsMap.put( typedVar.getShortName(), typedVar); // depends on control dependency: [if], data = [none]
}
}
Range startPointRange = null;
Range endPointRange = null;
try
{
startPointRange = new Range( 0, 0);
endPointRange = new Range( trajectoryNumPoint-1, trajectoryNumPoint-1);
}
catch ( InvalidRangeException e )
{
IOException ioe = new IOException( "Start or end point range invalid: " + e.getMessage());
ioe.initCause( e);
throw( ioe);
}
List section0 = new ArrayList(1);
List section1 = new ArrayList(1);
section0.add( startPointRange);
section1.add( endPointRange);
Array startTimeArray;
Array endTimeArray;
try
{
startTimeArray = this.timeVar.read( section0);
endTimeArray = this.timeVar.read( section1);
}
catch ( InvalidRangeException e )
{
IOException ioe = new IOException( "Invalid range during read of start or end point: " + e.getMessage());
ioe.initCause( e);
throw( ioe);
}
String startTimeString;
String endTimeString;
if ( this.timeVar.getDataType().equals( DataType.DOUBLE))
{
startTimeString = startTimeArray.getDouble( startTimeArray.getIndex() ) + " " + timeVarUnitsString;
endTimeString = endTimeArray.getDouble( endTimeArray.getIndex() ) + " " + timeVarUnitsString;
}
else if ( this.timeVar.getDataType().equals( DataType.FLOAT))
{
startTimeString = startTimeArray.getFloat( startTimeArray.getIndex() ) + " " + timeVarUnitsString;
endTimeString = endTimeArray.getFloat( endTimeArray.getIndex() ) + " " + timeVarUnitsString;
}
else if ( this.timeVar.getDataType().equals( DataType.INT ) )
{
startTimeString = startTimeArray.getInt( startTimeArray.getIndex() ) + " " + timeVarUnitsString;
endTimeString = endTimeArray.getInt( endTimeArray.getIndex() ) + " " + timeVarUnitsString;
}
else
{
String tmpMsg = "Time var <" + this.timeVar.getFullName() + "> is not a double, float, or integer <" + timeVar.getDataType().toString() + ">.";
//log.error( tmpMsg );
throw new IllegalArgumentException( tmpMsg);
}
startDate = DateUnit.getStandardDate( startTimeString );
endDate = DateUnit.getStandardDate( endTimeString);
trajectoryIds = new ArrayList();
trajectories = new ArrayList();
trajectoriesMap = new HashMap();
Array trajArray = this.trajVar.read();
Index index = trajArray.getIndex();
for ( int i = 0; i < trajArray.getSize(); i++ )
{
String curTrajId;
if ( this.trajVar.getDataType().equals( DataType.STRING ) )
{
curTrajId = (String) trajArray.getObject( index.set( i ) );
}
else if ( this.trajVar.getDataType().equals( DataType.DOUBLE ) )
{
curTrajId = String.valueOf( trajArray.getDouble( index.set( i ) ) );
}
else if ( this.trajVar.getDataType().equals( DataType.FLOAT ) )
{
curTrajId = String.valueOf( trajArray.getFloat( index.set( i ) ) );
}
else if ( this.trajVar.getDataType().equals( DataType.INT ) )
{
curTrajId = String.valueOf( trajArray.getInt( index.set( i ) ) );
}
else
{
String tmpMsg = "Trajectory var <" + this.trajVar.getFullName() + "> is not a string, double, float, or integer <" + this.trajVar.getDataType().toString() + ">.";
//log.error( tmpMsg );
throw new IllegalStateException( tmpMsg );
}
MultiTrajectory curTraj = new MultiTrajectory( curTrajId, i, trajectoryNumPoint, startDate, endDate,
this.trajVar, this.timeVar, timeVarUnitsString,
this.latVar, this.lonVar, this.elevVar,
dataVariables, trajectoryVarsMap );
trajectoryIds.add( curTrajId);
trajectories.add( curTraj);
trajectoriesMap.put( curTrajId, curTraj );
}
} } |
public class class_name {
private List<TimephasedCost> getTimephasedActualCostFixedAmount()
{
List<TimephasedCost> result = new LinkedList<TimephasedCost>();
double actualCost = getActualCost().doubleValue();
if (actualCost > 0)
{
AccrueType accrueAt = getResource().getAccrueAt();
if (accrueAt == AccrueType.START)
{
result.add(splitCostStart(getCalendar(), actualCost, getActualStart()));
}
else
if (accrueAt == AccrueType.END)
{
result.add(splitCostEnd(getCalendar(), actualCost, getActualFinish()));
}
else
{
//for prorated, we have to deal with it differently; have to 'fill up' each
//day with the standard amount before going to the next one
double numWorkingDays = getCalendar().getWork(getStart(), getFinish(), TimeUnit.DAYS).getDuration();
double standardAmountPerDay = getCost().doubleValue() / numWorkingDays;
result.addAll(splitCostProrated(getCalendar(), actualCost, standardAmountPerDay, getActualStart()));
}
}
return result;
} } | public class class_name {
private List<TimephasedCost> getTimephasedActualCostFixedAmount()
{
List<TimephasedCost> result = new LinkedList<TimephasedCost>();
double actualCost = getActualCost().doubleValue();
if (actualCost > 0)
{
AccrueType accrueAt = getResource().getAccrueAt();
if (accrueAt == AccrueType.START)
{
result.add(splitCostStart(getCalendar(), actualCost, getActualStart())); // depends on control dependency: [if], data = [none]
}
else
if (accrueAt == AccrueType.END)
{
result.add(splitCostEnd(getCalendar(), actualCost, getActualFinish())); // depends on control dependency: [if], data = [none]
}
else
{
//for prorated, we have to deal with it differently; have to 'fill up' each
//day with the standard amount before going to the next one
double numWorkingDays = getCalendar().getWork(getStart(), getFinish(), TimeUnit.DAYS).getDuration();
double standardAmountPerDay = getCost().doubleValue() / numWorkingDays;
result.addAll(splitCostProrated(getCalendar(), actualCost, standardAmountPerDay, getActualStart())); // depends on control dependency: [if], data = [none]
}
}
return result;
} } |
public class class_name {
private void readEmbeddable(Object key, List<String> columnsToSelect, EntityMetadata entityMetadata,
MetamodelImpl metamodel, Table schemaTable, RecordValue value, Attribute attribute)
{
EmbeddableType embeddableId = metamodel.embeddable(((AbstractAttribute) attribute).getBindableJavaType());
Set<Attribute> embeddedAttributes = embeddableId.getAttributes();
for (Attribute embeddedAttrib : embeddedAttributes)
{
String columnName = ((AbstractAttribute) embeddedAttrib).getJPAColumnName();
Object embeddedColumn = PropertyAccessorHelper.getObject(key, (Field) embeddedAttrib.getJavaMember());
// either null or empty or contains that column
if (eligibleToFetch(columnsToSelect, columnName))
{
NoSqlDBUtils.add(schemaTable.getField(columnName), value, embeddedColumn, columnName);
}
}
} } | public class class_name {
private void readEmbeddable(Object key, List<String> columnsToSelect, EntityMetadata entityMetadata,
MetamodelImpl metamodel, Table schemaTable, RecordValue value, Attribute attribute)
{
EmbeddableType embeddableId = metamodel.embeddable(((AbstractAttribute) attribute).getBindableJavaType());
Set<Attribute> embeddedAttributes = embeddableId.getAttributes();
for (Attribute embeddedAttrib : embeddedAttributes)
{
String columnName = ((AbstractAttribute) embeddedAttrib).getJPAColumnName();
Object embeddedColumn = PropertyAccessorHelper.getObject(key, (Field) embeddedAttrib.getJavaMember());
// either null or empty or contains that column
if (eligibleToFetch(columnsToSelect, columnName))
{
NoSqlDBUtils.add(schemaTable.getField(columnName), value, embeddedColumn, columnName); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private void checkNonNullParam(Location location, ConstantPoolGen cpg, TypeDataflow typeDataflow,
InvokeInstruction invokeInstruction, BitSet nullArgSet, BitSet definitelyNullArgSet) {
if (inExplicitCatchNullBlock(location)) {
return;
}
boolean caught = inIndirectCatchNullBlock(location);
if (caught && skipIfInsideCatchNull()) {
return;
}
if (invokeInstruction instanceof INVOKEDYNAMIC) {
return;
}
XMethod m = XFactory.createXMethod(invokeInstruction, cpg);
INullnessAnnotationDatabase db = AnalysisContext.currentAnalysisContext().getNullnessAnnotationDatabase();
SignatureParser sigParser = new SignatureParser(invokeInstruction.getSignature(cpg));
for (int i = nullArgSet.nextSetBit(0); i >= 0; i = nullArgSet.nextSetBit(i + 1)) {
if (db.parameterMustBeNonNull(m, i)) {
boolean definitelyNull = definitelyNullArgSet.get(i);
if (DEBUG_NULLARG) {
System.out.println("Checking " + m);
System.out.println("QQQ2: " + i + " -- " + i + " is null");
System.out.println("QQQ nullArgSet: " + nullArgSet);
System.out.println("QQQ dnullArgSet: " + definitelyNullArgSet);
}
BugAnnotation variableAnnotation = null;
try {
ValueNumberFrame vnaFrame = classContext.getValueNumberDataflow(method).getFactAtLocation(location);
ValueNumber valueNumber = vnaFrame.getArgument(invokeInstruction, cpg, i, sigParser);
variableAnnotation = ValueNumberSourceInfo.findAnnotationFromValueNumber(method, location, valueNumber,
vnaFrame, "VALUE_OF");
} catch (DataflowAnalysisException e) {
AnalysisContext.logError("error", e);
} catch (CFGBuilderException e) {
AnalysisContext.logError("error", e);
}
int priority = definitelyNull ? HIGH_PRIORITY : NORMAL_PRIORITY;
if (caught) {
priority++;
}
if (m.isPrivate() && priority == HIGH_PRIORITY) {
priority = NORMAL_PRIORITY;
}
String description = definitelyNull ? "INT_NULL_ARG" : "INT_MAYBE_NULL_ARG";
WarningPropertySet<WarningProperty> propertySet = new WarningPropertySet<>();
Set<Location> derefLocationSet = Collections.singleton(location);
addPropertiesForDereferenceLocations(propertySet, derefLocationSet, false);
boolean duplicated = isDuplicated(propertySet, location.getHandle().getPosition(), false);
if (duplicated) {
return;
}
BugInstance warning = new BugInstance(this, "NP_NONNULL_PARAM_VIOLATION", priority)
.addClassAndMethod(classContext.getJavaClass(), method).addMethod(m)
.describe(MethodAnnotation.METHOD_CALLED).addParameterAnnotation(i, description)
.addOptionalAnnotation(variableAnnotation).addSourceLine(classContext, method, location);
propertySet.decorateBugInstance(warning);
bugReporter.reportBug(warning);
}
}
} } | public class class_name {
private void checkNonNullParam(Location location, ConstantPoolGen cpg, TypeDataflow typeDataflow,
InvokeInstruction invokeInstruction, BitSet nullArgSet, BitSet definitelyNullArgSet) {
if (inExplicitCatchNullBlock(location)) {
return; // depends on control dependency: [if], data = [none]
}
boolean caught = inIndirectCatchNullBlock(location);
if (caught && skipIfInsideCatchNull()) {
return; // depends on control dependency: [if], data = [none]
}
if (invokeInstruction instanceof INVOKEDYNAMIC) {
return; // depends on control dependency: [if], data = [none]
}
XMethod m = XFactory.createXMethod(invokeInstruction, cpg);
INullnessAnnotationDatabase db = AnalysisContext.currentAnalysisContext().getNullnessAnnotationDatabase();
SignatureParser sigParser = new SignatureParser(invokeInstruction.getSignature(cpg));
for (int i = nullArgSet.nextSetBit(0); i >= 0; i = nullArgSet.nextSetBit(i + 1)) {
if (db.parameterMustBeNonNull(m, i)) {
boolean definitelyNull = definitelyNullArgSet.get(i);
if (DEBUG_NULLARG) {
System.out.println("Checking " + m); // depends on control dependency: [if], data = [none]
System.out.println("QQQ2: " + i + " -- " + i + " is null"); // depends on control dependency: [if], data = [none]
System.out.println("QQQ nullArgSet: " + nullArgSet); // depends on control dependency: [if], data = [none]
System.out.println("QQQ dnullArgSet: " + definitelyNullArgSet); // depends on control dependency: [if], data = [none]
}
BugAnnotation variableAnnotation = null;
try {
ValueNumberFrame vnaFrame = classContext.getValueNumberDataflow(method).getFactAtLocation(location);
ValueNumber valueNumber = vnaFrame.getArgument(invokeInstruction, cpg, i, sigParser);
variableAnnotation = ValueNumberSourceInfo.findAnnotationFromValueNumber(method, location, valueNumber,
vnaFrame, "VALUE_OF"); // depends on control dependency: [try], data = [none]
} catch (DataflowAnalysisException e) {
AnalysisContext.logError("error", e);
} catch (CFGBuilderException e) { // depends on control dependency: [catch], data = [none]
AnalysisContext.logError("error", e);
} // depends on control dependency: [catch], data = [none]
int priority = definitelyNull ? HIGH_PRIORITY : NORMAL_PRIORITY;
if (caught) {
priority++; // depends on control dependency: [if], data = [none]
}
if (m.isPrivate() && priority == HIGH_PRIORITY) {
priority = NORMAL_PRIORITY; // depends on control dependency: [if], data = [none]
}
String description = definitelyNull ? "INT_NULL_ARG" : "INT_MAYBE_NULL_ARG";
WarningPropertySet<WarningProperty> propertySet = new WarningPropertySet<>();
Set<Location> derefLocationSet = Collections.singleton(location);
addPropertiesForDereferenceLocations(propertySet, derefLocationSet, false); // depends on control dependency: [if], data = [none]
boolean duplicated = isDuplicated(propertySet, location.getHandle().getPosition(), false);
if (duplicated) {
return; // depends on control dependency: [if], data = [none]
}
BugInstance warning = new BugInstance(this, "NP_NONNULL_PARAM_VIOLATION", priority)
.addClassAndMethod(classContext.getJavaClass(), method).addMethod(m)
.describe(MethodAnnotation.METHOD_CALLED).addParameterAnnotation(i, description)
.addOptionalAnnotation(variableAnnotation).addSourceLine(classContext, method, location);
propertySet.decorateBugInstance(warning); // depends on control dependency: [if], data = [none]
bugReporter.reportBug(warning); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public ExtServletContext getServletContext(HttpContext httpContext) {
synchronized (this.contextMap) {
ExtServletContext context = this.contextMap.get(httpContext);
if (context == null) {
context = addServletContext(httpContext);
}
return context;
}
} } | public class class_name {
public ExtServletContext getServletContext(HttpContext httpContext) {
synchronized (this.contextMap) {
ExtServletContext context = this.contextMap.get(httpContext);
if (context == null) {
context = addServletContext(httpContext); // depends on control dependency: [if], data = [none]
}
return context;
}
} } |
public class class_name {
@Override
public synchronized void becomeNonCron() {
verifyCanScheduleState();
if (JobChangeLog.isEnabled()) {
JobChangeLog.log("#job ...Becoming non-cron: {}", toString());
}
cron4jId.ifPresent(id -> {
cron4jTask.becomeNonCrom();
cron4jNow.getCron4jScheduler().deschedule(id);
cron4jId = OptionalThing.empty();
});
} } | public class class_name {
@Override
public synchronized void becomeNonCron() {
verifyCanScheduleState();
if (JobChangeLog.isEnabled()) {
JobChangeLog.log("#job ...Becoming non-cron: {}", toString()); // depends on control dependency: [if], data = [none]
}
cron4jId.ifPresent(id -> {
cron4jTask.becomeNonCrom();
cron4jNow.getCron4jScheduler().deschedule(id);
cron4jId = OptionalThing.empty();
});
} } |
public class class_name {
public static List<String> getMustacheKeys(final String template) {
final Set<String> keys = new HashSet<>();
if (StringUtils.isNotEmpty(template)) {
final Matcher matcher = MUSTACHE_PATTERN.matcher(template);
while(matcher.find()) {
keys.add(matcher.group(1));
}
}
return new ArrayList<>(keys);
} } | public class class_name {
public static List<String> getMustacheKeys(final String template) {
final Set<String> keys = new HashSet<>();
if (StringUtils.isNotEmpty(template)) {
final Matcher matcher = MUSTACHE_PATTERN.matcher(template);
while(matcher.find()) {
keys.add(matcher.group(1)); // depends on control dependency: [while], data = [none]
}
}
return new ArrayList<>(keys);
} } |
public class class_name {
public <V extends Object, C extends RTSpan<V>> void applyEffect(Effect<V, C> effect, V value) {
if (mUseRTFormatting && !mIsSelectionChanging && !mIsSaving) {
Spannable oldSpannable = mIgnoreTextChanges ? null : cloneSpannable();
effect.applyToSelection(this, value);
synchronized (this) {
if (mListener != null && !mIgnoreTextChanges) {
Spannable newSpannable = cloneSpannable();
mListener.onTextChanged(this, oldSpannable, newSpannable, getSelectionStart(), getSelectionEnd(),
getSelectionStart(), getSelectionEnd());
}
mLayoutChanged = true;
}
}
} } | public class class_name {
public <V extends Object, C extends RTSpan<V>> void applyEffect(Effect<V, C> effect, V value) {
if (mUseRTFormatting && !mIsSelectionChanging && !mIsSaving) {
Spannable oldSpannable = mIgnoreTextChanges ? null : cloneSpannable();
effect.applyToSelection(this, value); // depends on control dependency: [if], data = [none]
synchronized (this) { // depends on control dependency: [if], data = [none]
if (mListener != null && !mIgnoreTextChanges) {
Spannable newSpannable = cloneSpannable();
mListener.onTextChanged(this, oldSpannable, newSpannable, getSelectionStart(), getSelectionEnd(),
getSelectionStart(), getSelectionEnd()); // depends on control dependency: [if], data = [none]
}
mLayoutChanged = true;
}
}
} } |
public class class_name {
@SuppressWarnings("unchecked")
private void decreaseKey(Node<K, V> n, K newKey) {
int c = ((Comparable<? super K>) newKey).compareTo(n.key);
if (c > 0) {
throw new IllegalArgumentException("Keys can only be decreased!");
}
n.key = newKey;
if (c == 0) {
return;
}
if (n.next == null) {
throw new IllegalArgumentException("Invalid handle!");
}
// if not root and heap order violation
Node<K, V> y = n.parent;
if (y != null && ((Comparable<? super K>) n.key).compareTo(y.key) < 0) {
cut(n, y);
cascadingCut(y);
}
// update minimum root
if (((Comparable<? super K>) n.key).compareTo(minRoot.key) < 0) {
minRoot = n;
}
} } | public class class_name {
@SuppressWarnings("unchecked")
private void decreaseKey(Node<K, V> n, K newKey) {
int c = ((Comparable<? super K>) newKey).compareTo(n.key);
if (c > 0) {
throw new IllegalArgumentException("Keys can only be decreased!");
}
n.key = newKey;
if (c == 0) {
return; // depends on control dependency: [if], data = [none]
}
if (n.next == null) {
throw new IllegalArgumentException("Invalid handle!");
}
// if not root and heap order violation
Node<K, V> y = n.parent;
if (y != null && ((Comparable<? super K>) n.key).compareTo(y.key) < 0) {
cut(n, y); // depends on control dependency: [if], data = [none]
cascadingCut(y); // depends on control dependency: [if], data = [(y]
}
// update minimum root
if (((Comparable<? super K>) n.key).compareTo(minRoot.key) < 0) {
minRoot = n; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public MPConnection removeConnection(MEConnection conn)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "removeConnection", new Object[] { conn });
MPConnection mpConn;
synchronized(_mpConnectionsByMEConnection)
{
//remove the MPConnection from the 'by MEConnection' cache
mpConn = _mpConnectionsByMEConnection.remove(conn);
if(mpConn != null)
{
//remove it from the 'by cellule' cache also
_mpConnectionsByMEUuid.remove(mpConn.getRemoteMEUuid());
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "removeConnection", mpConn);
return mpConn;
} } | public class class_name {
public MPConnection removeConnection(MEConnection conn)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "removeConnection", new Object[] { conn });
MPConnection mpConn;
synchronized(_mpConnectionsByMEConnection)
{
//remove the MPConnection from the 'by MEConnection' cache
mpConn = _mpConnectionsByMEConnection.remove(conn);
if(mpConn != null)
{
//remove it from the 'by cellule' cache also
_mpConnectionsByMEUuid.remove(mpConn.getRemoteMEUuid()); // depends on control dependency: [if], data = [(mpConn]
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "removeConnection", mpConn);
return mpConn;
} } |
public class class_name {
protected List<Parameter> getParameters(Type type, List<Annotation> annotations, Set<Type> typesToSkip) {
if (!hasValidAnnotations(annotations) || isApiParamHidden(annotations)) {
return Collections.emptyList();
}
Iterator<SwaggerExtension> chain = SwaggerExtensions.chain();
List<Parameter> parameters = new ArrayList<>();
Class<?> cls = TypeUtils.getRawType(type, type);
LOG.debug("Looking for path/query/header/form/cookie params in " + cls);
if (chain.hasNext()) {
SwaggerExtension extension = chain.next();
LOG.debug("trying extension " + extension);
parameters = extension.extractParameters(annotations, type, typesToSkip, chain);
}
if (!parameters.isEmpty()) {
for (Parameter parameter : parameters) {
ParameterProcessor.applyAnnotations(swagger, parameter, type, annotations);
}
} else {
LOG.debug("Looking for body params in " + cls);
// parameters is guaranteed to be empty at this point, replace it with a mutable collection
parameters = Lists.newArrayList();
if (!typesToSkip.contains(type)) {
Parameter param = ParameterProcessor.applyAnnotations(swagger, null, type, annotations);
if (param != null) {
parameters.add(param);
}
}
}
return parameters;
} } | public class class_name {
protected List<Parameter> getParameters(Type type, List<Annotation> annotations, Set<Type> typesToSkip) {
if (!hasValidAnnotations(annotations) || isApiParamHidden(annotations)) {
return Collections.emptyList(); // depends on control dependency: [if], data = [none]
}
Iterator<SwaggerExtension> chain = SwaggerExtensions.chain();
List<Parameter> parameters = new ArrayList<>();
Class<?> cls = TypeUtils.getRawType(type, type);
LOG.debug("Looking for path/query/header/form/cookie params in " + cls);
if (chain.hasNext()) {
SwaggerExtension extension = chain.next();
LOG.debug("trying extension " + extension); // depends on control dependency: [if], data = [none]
parameters = extension.extractParameters(annotations, type, typesToSkip, chain); // depends on control dependency: [if], data = [none]
}
if (!parameters.isEmpty()) {
for (Parameter parameter : parameters) {
ParameterProcessor.applyAnnotations(swagger, parameter, type, annotations); // depends on control dependency: [for], data = [parameter]
}
} else {
LOG.debug("Looking for body params in " + cls); // depends on control dependency: [if], data = [none]
// parameters is guaranteed to be empty at this point, replace it with a mutable collection
parameters = Lists.newArrayList(); // depends on control dependency: [if], data = [none]
if (!typesToSkip.contains(type)) {
Parameter param = ParameterProcessor.applyAnnotations(swagger, null, type, annotations);
if (param != null) {
parameters.add(param); // depends on control dependency: [if], data = [(param]
}
}
}
return parameters;
} } |
public class class_name {
public String generate(HTMLLinkPolicy links, List<StructureDefinition> structures) {
ST shex_def = tmplt(SHEX_TEMPLATE);
String start_cmd;
if(completeModel || structures.get(0).getKind().equals(StructureDefinition.StructureDefinitionKind.RESOURCE))
// || structures.get(0).getKind().equals(StructureDefinition.StructureDefinitionKind.COMPLEXTYPE))
start_cmd = completeModel? tmplt(ALL_START_TEMPLATE).render() :
tmplt(START_TEMPLATE).add("id", structures.get(0).getId()).render();
else
start_cmd = "";
shex_def.add("header", tmplt(HEADER_TEMPLATE).
add("start", start_cmd).
add("fhir", FHIR).
add("fhirvs", FHIR_VS).render());
Collections.sort(structures, new SortById());
StringBuilder shapeDefinitions = new StringBuilder();
// For unknown reasons, the list of structures carries duplicates. We remove them
// Also, it is possible for the same sd to have multiple hashes...
uniq_structures = new LinkedList<StructureDefinition>();
uniq_structure_urls = new HashSet<String>();
for (StructureDefinition sd : structures) {
if (!uniq_structure_urls.contains(sd.getUrl())) {
uniq_structures.add(sd);
uniq_structure_urls.add(sd.getUrl());
}
}
for (StructureDefinition sd : uniq_structures) {
shapeDefinitions.append(genShapeDefinition(sd, true));
}
shapeDefinitions.append(emitInnerTypes());
if(doDatatypes) {
shapeDefinitions.append("\n#---------------------- Data Types -------------------\n");
while (emittedDatatypes.size() < datatypes.size() ||
emittedInnerTypes.size() < innerTypes.size()) {
shapeDefinitions.append(emitDataTypes());
shapeDefinitions.append(emitInnerTypes());
}
}
shapeDefinitions.append("\n#---------------------- Reference Types -------------------\n");
for(String r: references) {
shapeDefinitions.append("\n").append(tmplt(TYPED_REFERENCE_TEMPLATE).add("refType", r).render()).append("\n");
if (!"Resource".equals(r) && !known_resources.contains(r))
shapeDefinitions.append("\n").append(tmplt(TARGET_REFERENCE_TEMPLATE).add("refType", r).render()).append("\n");
}
shex_def.add("shapeDefinitions", shapeDefinitions);
if(completeModel && known_resources.size() > 0) {
shapeDefinitions.append("\n").append(tmplt(COMPLETE_RESOURCE_TEMPLATE)
.add("resources", StringUtils.join(known_resources, "> OR\n\t@<")).render());
List<String> all_entries = new ArrayList<String>();
for(String kr: known_resources)
all_entries.add(tmplt(ALL_ENTRY_TEMPLATE).add("id", kr).render());
shapeDefinitions.append("\n").append(tmplt(ALL_TEMPLATE)
.add("all_entries", StringUtils.join(all_entries, " OR\n\t")).render());
}
shapeDefinitions.append("\n#---------------------- Value Sets ------------------------\n");
for(ValueSet vs: required_value_sets)
shapeDefinitions.append("\n").append(genValueSet(vs));
return shex_def.render();
}
/**
* Emit a ShEx definition for the supplied StructureDefinition
* @param sd Structure definition to emit
* @param top_level True means outermost type, False means recursively called
* @return ShEx definition
*/
private String genShapeDefinition(StructureDefinition sd, boolean top_level) {
// xhtml is treated as an atom
if("xhtml".equals(sd.getName()) || (completeModel && "Resource".equals(sd.getName())))
return "";
ST shape_defn;
// Resources are either incomplete items or consist of everything that is defined as a resource (completeModel)
if("Resource".equals(sd.getName())) {
shape_defn = tmplt(RESOURCE_SHAPE_TEMPLATE);
known_resources.add(sd.getName());
} else {
shape_defn = tmplt(SHAPE_DEFINITION_TEMPLATE).add("id", sd.getId());
if (sd.getKind().equals(StructureDefinition.StructureDefinitionKind.RESOURCE)) {
// || sd.getKind().equals(StructureDefinition.StructureDefinitionKind.COMPLEXTYPE)) {
known_resources.add(sd.getName());
ST resource_decl = tmplt(RESOURCE_DECL_TEMPLATE).
add("id", sd.getId()).
add("root", tmplt(ROOT_TEMPLATE));
// add("root", top_level ? tmplt(ROOT_TEMPLATE) : "");
shape_defn.add("resourceDecl", resource_decl.render());
} else {
shape_defn.add("resourceDecl", "");
}
}
// Generate the defining elements
List<String> elements = new ArrayList<String>();
// Add the additional entries for special types
String sdn = sd.getName();
if (sdn.equals("Coding"))
elements.add(tmplt(CONCEPT_REFERENCE_TEMPLATE).render());
else if (sdn.equals("CodeableConcept"))
elements.add(tmplt(CONCEPT_REFERENCES_TEMPLATE).render());
else if (sdn.equals("Reference"))
elements.add(tmplt(RESOURCE_LINK_TEMPLATE).render());
// else if (sdn.equals("Extension"))
// return tmplt(EXTENSION_TEMPLATE).render();
String root_comment = null;
for (ElementDefinition ed : sd.getSnapshot().getElement()) {
if(!ed.getPath().contains("."))
root_comment = ed.getShort();
else if (StringUtils.countMatches(ed.getPath(), ".") == 1 && !"0".equals(ed.getMax())) {
elements.add(genElementDefinition(sd, ed));
}
}
shape_defn.add("elements", StringUtils.join(elements, "\n"));
shape_defn.add("comment", root_comment == null? " " : "# " + root_comment);
return shape_defn.render();
} } | public class class_name {
public String generate(HTMLLinkPolicy links, List<StructureDefinition> structures) {
ST shex_def = tmplt(SHEX_TEMPLATE);
String start_cmd;
if(completeModel || structures.get(0).getKind().equals(StructureDefinition.StructureDefinitionKind.RESOURCE))
// || structures.get(0).getKind().equals(StructureDefinition.StructureDefinitionKind.COMPLEXTYPE))
start_cmd = completeModel? tmplt(ALL_START_TEMPLATE).render() :
tmplt(START_TEMPLATE).add("id", structures.get(0).getId()).render();
else
start_cmd = "";
shex_def.add("header", tmplt(HEADER_TEMPLATE).
add("start", start_cmd).
add("fhir", FHIR).
add("fhirvs", FHIR_VS).render());
Collections.sort(structures, new SortById());
StringBuilder shapeDefinitions = new StringBuilder();
// For unknown reasons, the list of structures carries duplicates. We remove them
// Also, it is possible for the same sd to have multiple hashes...
uniq_structures = new LinkedList<StructureDefinition>();
uniq_structure_urls = new HashSet<String>();
for (StructureDefinition sd : structures) {
if (!uniq_structure_urls.contains(sd.getUrl())) {
uniq_structures.add(sd);
// depends on control dependency: [if], data = [none]
uniq_structure_urls.add(sd.getUrl());
// depends on control dependency: [if], data = [none]
}
}
for (StructureDefinition sd : uniq_structures) {
shapeDefinitions.append(genShapeDefinition(sd, true));
// depends on control dependency: [for], data = [sd]
}
shapeDefinitions.append(emitInnerTypes());
if(doDatatypes) {
shapeDefinitions.append("\n#---------------------- Data Types -------------------\n");
// depends on control dependency: [if], data = [none]
while (emittedDatatypes.size() < datatypes.size() ||
emittedInnerTypes.size() < innerTypes.size()) {
shapeDefinitions.append(emitDataTypes());
// depends on control dependency: [while], data = [none]
shapeDefinitions.append(emitInnerTypes());
// depends on control dependency: [while], data = [none]
}
}
shapeDefinitions.append("\n#---------------------- Reference Types -------------------\n");
for(String r: references) {
shapeDefinitions.append("\n").append(tmplt(TYPED_REFERENCE_TEMPLATE).add("refType", r).render()).append("\n");
// depends on control dependency: [for], data = [r]
if (!"Resource".equals(r) && !known_resources.contains(r))
shapeDefinitions.append("\n").append(tmplt(TARGET_REFERENCE_TEMPLATE).add("refType", r).render()).append("\n");
}
shex_def.add("shapeDefinitions", shapeDefinitions);
if(completeModel && known_resources.size() > 0) {
shapeDefinitions.append("\n").append(tmplt(COMPLETE_RESOURCE_TEMPLATE)
.add("resources", StringUtils.join(known_resources, "> OR\n\t@<")).render());
// depends on control dependency: [if], data = [none]
List<String> all_entries = new ArrayList<String>();
for(String kr: known_resources)
all_entries.add(tmplt(ALL_ENTRY_TEMPLATE).add("id", kr).render());
shapeDefinitions.append("\n").append(tmplt(ALL_TEMPLATE)
.add("all_entries", StringUtils.join(all_entries, " OR\n\t")).render());
// depends on control dependency: [if], data = [none]
}
shapeDefinitions.append("\n#---------------------- Value Sets ------------------------\n");
for(ValueSet vs: required_value_sets)
shapeDefinitions.append("\n").append(genValueSet(vs));
return shex_def.render();
}
/**
* Emit a ShEx definition for the supplied StructureDefinition
* @param sd Structure definition to emit
* @param top_level True means outermost type, False means recursively called
* @return ShEx definition
*/
private String genShapeDefinition(StructureDefinition sd, boolean top_level) {
// xhtml is treated as an atom
if("xhtml".equals(sd.getName()) || (completeModel && "Resource".equals(sd.getName())))
return "";
ST shape_defn;
// Resources are either incomplete items or consist of everything that is defined as a resource (completeModel)
if("Resource".equals(sd.getName())) {
shape_defn = tmplt(RESOURCE_SHAPE_TEMPLATE);
// depends on control dependency: [if], data = [none]
known_resources.add(sd.getName());
// depends on control dependency: [if], data = [none]
} else {
shape_defn = tmplt(SHAPE_DEFINITION_TEMPLATE).add("id", sd.getId());
// depends on control dependency: [if], data = [none]
if (sd.getKind().equals(StructureDefinition.StructureDefinitionKind.RESOURCE)) {
// || sd.getKind().equals(StructureDefinition.StructureDefinitionKind.COMPLEXTYPE)) {
known_resources.add(sd.getName());
// depends on control dependency: [if], data = [none]
ST resource_decl = tmplt(RESOURCE_DECL_TEMPLATE).
add("id", sd.getId()).
add("root", tmplt(ROOT_TEMPLATE));
// add("root", top_level ? tmplt(ROOT_TEMPLATE) : "");
shape_defn.add("resourceDecl", resource_decl.render());
// depends on control dependency: [if], data = [none]
} else {
shape_defn.add("resourceDecl", "");
// depends on control dependency: [if], data = [none]
}
}
// Generate the defining elements
List<String> elements = new ArrayList<String>();
// Add the additional entries for special types
String sdn = sd.getName();
if (sdn.equals("Coding"))
elements.add(tmplt(CONCEPT_REFERENCE_TEMPLATE).render());
else if (sdn.equals("CodeableConcept"))
elements.add(tmplt(CONCEPT_REFERENCES_TEMPLATE).render());
else if (sdn.equals("Reference"))
elements.add(tmplt(RESOURCE_LINK_TEMPLATE).render());
// else if (sdn.equals("Extension"))
// return tmplt(EXTENSION_TEMPLATE).render();
String root_comment = null;
for (ElementDefinition ed : sd.getSnapshot().getElement()) {
if(!ed.getPath().contains("."))
root_comment = ed.getShort();
else if (StringUtils.countMatches(ed.getPath(), ".") == 1 && !"0".equals(ed.getMax())) {
elements.add(genElementDefinition(sd, ed));
// depends on control dependency: [if], data = [none]
}
}
shape_defn.add("elements", StringUtils.join(elements, "\n"));
shape_defn.add("comment", root_comment == null? " " : "# " + root_comment);
return shape_defn.render();
} } |
public class class_name {
public static HashMap<String, Double> contentElementsToHistogram(NodeList nodes) {
final HashMap<String, Double> histogram = new HashMap<>();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
String contentElementName = node.getTextContent().trim();
// increment frequency by 1
histogram.put(contentElementName, histogram.getOrDefault(contentElementName, 0.0) + 1.0);
}
return histogram;
} } | public class class_name {
public static HashMap<String, Double> contentElementsToHistogram(NodeList nodes) {
final HashMap<String, Double> histogram = new HashMap<>();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
String contentElementName = node.getTextContent().trim();
// increment frequency by 1
histogram.put(contentElementName, histogram.getOrDefault(contentElementName, 0.0) + 1.0); // depends on control dependency: [for], data = [none]
}
return histogram;
} } |
public class class_name {
@Override
public String getBhRestToken() {
String bhRestToken = null;
try {
bhRestToken = restSession.getBhRestToken();
} catch (RestApiException e) {
log.error("Error getting bhRestToken! ", e);
}
return bhRestToken;
} } | public class class_name {
@Override
public String getBhRestToken() {
String bhRestToken = null;
try {
bhRestToken = restSession.getBhRestToken(); // depends on control dependency: [try], data = [none]
} catch (RestApiException e) {
log.error("Error getting bhRestToken! ", e);
} // depends on control dependency: [catch], data = [none]
return bhRestToken;
} } |
public class class_name {
public static boolean isPotentiallyEncryptedString(String string) {
checkNotNull(string, "string");
// String is base64 encoded
byte[] encryptedBytes;
try {
encryptedBytes = BaseEncoding.base64().omitPadding().decode(string);
} catch (IllegalArgumentException e) {
return false;
}
return isPotentiallyEncryptedBytes(encryptedBytes);
} } | public class class_name {
public static boolean isPotentiallyEncryptedString(String string) {
checkNotNull(string, "string");
// String is base64 encoded
byte[] encryptedBytes;
try {
encryptedBytes = BaseEncoding.base64().omitPadding().decode(string); // depends on control dependency: [try], data = [none]
} catch (IllegalArgumentException e) {
return false;
} // depends on control dependency: [catch], data = [none]
return isPotentiallyEncryptedBytes(encryptedBytes);
} } |
public class class_name {
private void setValueForOtherLocales(CmsObject cms, I_CmsXmlContentValue value, String requiredParent) {
if (!value.isSimpleType()) {
throw new IllegalArgumentException();
}
for (Locale locale : getLocales()) {
if (locale.equals(value.getLocale())) {
continue;
}
String valuePath = value.getPath();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(requiredParent) || hasValue(requiredParent, locale)) {
ensureParentValues(cms, valuePath, locale);
if (hasValue(valuePath, locale)) {
I_CmsXmlContentValue localeValue = getValue(valuePath, locale);
localeValue.setStringValue(cms, value.getStringValue(cms));
} else {
int index = CmsXmlUtils.getXpathIndexInt(valuePath) - 1;
I_CmsXmlContentValue localeValue = addValue(cms, valuePath, locale, index);
localeValue.setStringValue(cms, value.getStringValue(cms));
}
}
}
} } | public class class_name {
private void setValueForOtherLocales(CmsObject cms, I_CmsXmlContentValue value, String requiredParent) {
if (!value.isSimpleType()) {
throw new IllegalArgumentException();
}
for (Locale locale : getLocales()) {
if (locale.equals(value.getLocale())) {
continue;
}
String valuePath = value.getPath();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(requiredParent) || hasValue(requiredParent, locale)) {
ensureParentValues(cms, valuePath, locale); // depends on control dependency: [if], data = [none]
if (hasValue(valuePath, locale)) {
I_CmsXmlContentValue localeValue = getValue(valuePath, locale);
localeValue.setStringValue(cms, value.getStringValue(cms)); // depends on control dependency: [if], data = [none]
} else {
int index = CmsXmlUtils.getXpathIndexInt(valuePath) - 1;
I_CmsXmlContentValue localeValue = addValue(cms, valuePath, locale, index);
localeValue.setStringValue(cms, value.getStringValue(cms)); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
public void controlsToFields()
{
super.controlsToFields();
for (int iRowIndex = 0; iRowIndex < m_vComponentCache.size(); iRowIndex++)
{
ComponentCache componentCache = (ComponentCache)m_vComponentCache.elementAt(iRowIndex);
if (componentCache != null)
{ // Move the data to the model
for (int iColumnIndex = 0; iColumnIndex < componentCache.m_rgcompoments.length; iColumnIndex++)
{
this.dataToField(componentCache, iRowIndex, iColumnIndex);
}
}
}
} } | public class class_name {
public void controlsToFields()
{
super.controlsToFields();
for (int iRowIndex = 0; iRowIndex < m_vComponentCache.size(); iRowIndex++)
{
ComponentCache componentCache = (ComponentCache)m_vComponentCache.elementAt(iRowIndex);
if (componentCache != null)
{ // Move the data to the model
for (int iColumnIndex = 0; iColumnIndex < componentCache.m_rgcompoments.length; iColumnIndex++)
{
this.dataToField(componentCache, iRowIndex, iColumnIndex); // depends on control dependency: [for], data = [iColumnIndex]
}
}
}
} } |
public class class_name {
<R> R wrapSqlException(SqlAction<R> action) {
try {
return action.perform();
} catch (SQLException sqlException) {
throw excTranslator.translate("StreamResultSetExtractor", sql, sqlException);
}
} } | public class class_name {
<R> R wrapSqlException(SqlAction<R> action) {
try {
return action.perform(); // depends on control dependency: [try], data = [none]
} catch (SQLException sqlException) {
throw excTranslator.translate("StreamResultSetExtractor", sql, sqlException);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public final EObject ruleXAnnotationOrExpression() throws RecognitionException {
EObject current = null;
EObject this_XAnnotation_0 = null;
EObject this_XExpression_1 = null;
enterRule();
try {
// InternalSARL.g:11988:2: ( (this_XAnnotation_0= ruleXAnnotation | this_XExpression_1= ruleXExpression ) )
// InternalSARL.g:11989:2: (this_XAnnotation_0= ruleXAnnotation | this_XExpression_1= ruleXExpression )
{
// InternalSARL.g:11989:2: (this_XAnnotation_0= ruleXAnnotation | this_XExpression_1= ruleXExpression )
int alt297=2;
int LA297_0 = input.LA(1);
if ( (LA297_0==105) ) {
alt297=1;
}
else if ( ((LA297_0>=RULE_STRING && LA297_0<=RULE_RICH_TEXT_START)||(LA297_0>=RULE_HEX && LA297_0<=RULE_DECIMAL)||LA297_0==25||(LA297_0>=28 && LA297_0<=29)||LA297_0==36||(LA297_0>=39 && LA297_0<=40)||(LA297_0>=42 && LA297_0<=45)||(LA297_0>=48 && LA297_0<=49)||LA297_0==51||LA297_0==55||(LA297_0>=60 && LA297_0<=63)||(LA297_0>=67 && LA297_0<=68)||(LA297_0>=73 && LA297_0<=75)||(LA297_0>=78 && LA297_0<=96)||LA297_0==106||LA297_0==129||(LA297_0>=131 && LA297_0<=140)) ) {
alt297=2;
}
else {
if (state.backtracking>0) {state.failed=true; return current;}
NoViableAltException nvae =
new NoViableAltException("", 297, 0, input);
throw nvae;
}
switch (alt297) {
case 1 :
// InternalSARL.g:11990:3: this_XAnnotation_0= ruleXAnnotation
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXAnnotationOrExpressionAccess().getXAnnotationParserRuleCall_0());
}
pushFollow(FOLLOW_2);
this_XAnnotation_0=ruleXAnnotation();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current = this_XAnnotation_0;
afterParserOrEnumRuleCall();
}
}
break;
case 2 :
// InternalSARL.g:11999:3: this_XExpression_1= ruleXExpression
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXAnnotationOrExpressionAccess().getXExpressionParserRuleCall_1());
}
pushFollow(FOLLOW_2);
this_XExpression_1=ruleXExpression();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current = this_XExpression_1;
afterParserOrEnumRuleCall();
}
}
break;
}
}
if ( state.backtracking==0 ) {
leaveRule();
}
}
catch (RecognitionException re) {
recover(input,re);
appendSkippedTokens();
}
finally {
}
return current;
} } | public class class_name {
public final EObject ruleXAnnotationOrExpression() throws RecognitionException {
EObject current = null;
EObject this_XAnnotation_0 = null;
EObject this_XExpression_1 = null;
enterRule();
try {
// InternalSARL.g:11988:2: ( (this_XAnnotation_0= ruleXAnnotation | this_XExpression_1= ruleXExpression ) )
// InternalSARL.g:11989:2: (this_XAnnotation_0= ruleXAnnotation | this_XExpression_1= ruleXExpression )
{
// InternalSARL.g:11989:2: (this_XAnnotation_0= ruleXAnnotation | this_XExpression_1= ruleXExpression )
int alt297=2;
int LA297_0 = input.LA(1);
if ( (LA297_0==105) ) {
alt297=1; // depends on control dependency: [if], data = [none]
}
else if ( ((LA297_0>=RULE_STRING && LA297_0<=RULE_RICH_TEXT_START)||(LA297_0>=RULE_HEX && LA297_0<=RULE_DECIMAL)||LA297_0==25||(LA297_0>=28 && LA297_0<=29)||LA297_0==36||(LA297_0>=39 && LA297_0<=40)||(LA297_0>=42 && LA297_0<=45)||(LA297_0>=48 && LA297_0<=49)||LA297_0==51||LA297_0==55||(LA297_0>=60 && LA297_0<=63)||(LA297_0>=67 && LA297_0<=68)||(LA297_0>=73 && LA297_0<=75)||(LA297_0>=78 && LA297_0<=96)||LA297_0==106||LA297_0==129||(LA297_0>=131 && LA297_0<=140)) ) {
alt297=2; // depends on control dependency: [if], data = [none]
}
else {
if (state.backtracking>0) {state.failed=true; return current;} // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
NoViableAltException nvae =
new NoViableAltException("", 297, 0, input);
throw nvae;
}
switch (alt297) {
case 1 :
// InternalSARL.g:11990:3: this_XAnnotation_0= ruleXAnnotation
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXAnnotationOrExpressionAccess().getXAnnotationParserRuleCall_0()); // depends on control dependency: [if], data = [none]
}
pushFollow(FOLLOW_2);
this_XAnnotation_0=ruleXAnnotation();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current = this_XAnnotation_0; // depends on control dependency: [if], data = [none]
afterParserOrEnumRuleCall(); // depends on control dependency: [if], data = [none]
}
}
break;
case 2 :
// InternalSARL.g:11999:3: this_XExpression_1= ruleXExpression
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXAnnotationOrExpressionAccess().getXExpressionParserRuleCall_1()); // depends on control dependency: [if], data = [none]
}
pushFollow(FOLLOW_2);
this_XExpression_1=ruleXExpression();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current = this_XExpression_1; // depends on control dependency: [if], data = [none]
afterParserOrEnumRuleCall(); // depends on control dependency: [if], data = [none]
}
}
break;
}
}
if ( state.backtracking==0 ) {
leaveRule(); // depends on control dependency: [if], data = [none]
}
}
catch (RecognitionException re) {
recover(input,re);
appendSkippedTokens();
}
finally {
}
return current;
} } |
public class class_name {
public MethodMember getCurrentMethod(String name, String descriptor) {
if (liveVersion == null) {
return getMethod(name, descriptor);
}
else {
return liveVersion.getReloadableMethod(name, descriptor);
}
} } | public class class_name {
public MethodMember getCurrentMethod(String name, String descriptor) {
if (liveVersion == null) {
return getMethod(name, descriptor); // depends on control dependency: [if], data = [none]
}
else {
return liveVersion.getReloadableMethod(name, descriptor); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static MmtfSummaryDataBean getStructureInfo(Structure structure) {
MmtfSummaryDataBean mmtfSummaryDataBean = new MmtfSummaryDataBean();
// Get all the atoms
List<Atom> theseAtoms = new ArrayList<>();
List<Chain> allChains = new ArrayList<>();
Map<String, Integer> chainIdToIndexMap = new LinkedHashMap<>();
int chainCounter = 0;
int bondCount = 0;
mmtfSummaryDataBean.setAllAtoms(theseAtoms);
mmtfSummaryDataBean.setAllChains(allChains);
mmtfSummaryDataBean.setChainIdToIndexMap(chainIdToIndexMap);
for (int i=0; i<structure.nrModels(); i++){
List<Chain> chains = structure.getModel(i);
allChains.addAll(chains);
for (Chain chain : chains) {
String idOne = chain.getId();
if (!chainIdToIndexMap.containsKey(idOne)) {
chainIdToIndexMap.put(idOne, chainCounter);
}
chainCounter++;
for (Group g : chain.getAtomGroups()) {
for(Atom atom: getAtomsForGroup(g)){
theseAtoms.add(atom);
// If both atoms are in the group
if (atom.getBonds()!=null){
bondCount+=atom.getBonds().size();
}
}
}
}
}
// Assumes all bonds are referenced twice
mmtfSummaryDataBean.setNumBonds(bondCount/2);
return mmtfSummaryDataBean;
} } | public class class_name {
public static MmtfSummaryDataBean getStructureInfo(Structure structure) {
MmtfSummaryDataBean mmtfSummaryDataBean = new MmtfSummaryDataBean();
// Get all the atoms
List<Atom> theseAtoms = new ArrayList<>();
List<Chain> allChains = new ArrayList<>();
Map<String, Integer> chainIdToIndexMap = new LinkedHashMap<>();
int chainCounter = 0;
int bondCount = 0;
mmtfSummaryDataBean.setAllAtoms(theseAtoms);
mmtfSummaryDataBean.setAllChains(allChains);
mmtfSummaryDataBean.setChainIdToIndexMap(chainIdToIndexMap);
for (int i=0; i<structure.nrModels(); i++){
List<Chain> chains = structure.getModel(i);
allChains.addAll(chains); // depends on control dependency: [for], data = [none]
for (Chain chain : chains) {
String idOne = chain.getId();
if (!chainIdToIndexMap.containsKey(idOne)) {
chainIdToIndexMap.put(idOne, chainCounter); // depends on control dependency: [if], data = [none]
}
chainCounter++; // depends on control dependency: [for], data = [chain]
for (Group g : chain.getAtomGroups()) {
for(Atom atom: getAtomsForGroup(g)){
theseAtoms.add(atom); // depends on control dependency: [for], data = [atom]
// If both atoms are in the group
if (atom.getBonds()!=null){
bondCount+=atom.getBonds().size(); // depends on control dependency: [if], data = [none]
}
}
}
}
}
// Assumes all bonds are referenced twice
mmtfSummaryDataBean.setNumBonds(bondCount/2);
return mmtfSummaryDataBean;
} } |
public class class_name {
protected void resync(int XAEntries) {
if (tc.isEntryEnabled())
Tr.entry(tc, "resync", XAEntries);
try {
boolean XArecovered = (XAEntries == 0);
boolean auditRecovery = ConfigurationProviderManager.getConfigurationProvider().getAuditRecovery();
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (auditRecovery) {
Tr.audit(tc, "WTRN0134_RECOVERING_XARMS", XAEntries);
}
int retryAttempts = 0;
final int configuredWait = ConfigurationProviderManager.getConfigurationProvider().getHeuristicRetryInterval();
int retryWait = (configuredWait <= 0) ? TransactionImpl.defaultRetryTime : configuredWait;
boolean callRecoveryComplete = true;
boolean stopProcessing = shutdownInProgress();
while (!stopProcessing) {
if (retryAttempts > 0 && tc.isDebugEnabled())
Tr.debug(tc, "Retrying resync");
// Get list of current recovered transactions
TransactionImpl[] recoveredTransactions = getRecoveringTransactions();
// Contact the XA RMs and get the indoubt XIDs. Match any with our transactions, or else
// roll back the ones that we have no information about. If some fail to recover, we retry
// later.
if (!XArecovered) {
// Build a list of transaction Xids to check with each recovered RM
final Xid[] txnXids = new Xid[recoveredTransactions.length];
for (int i = 0; i < recoveredTransactions.length; i++) {
txnXids[i] = recoveredTransactions[i].getXid();
}
// plt recover will return early if shutdown is detected.
XArecovered = getPartnerLogTable().recover(this, cl, txnXids);
}
if (XArecovered) {
// If there are any transactions, proceed with recover.
for (int i = 0; i < recoveredTransactions.length; i++) {
if (stopProcessing = shutdownInProgress()) {
break;
}
try {
//LIDB3645: don't recover JCA inbound tx in recovery-mode
if (!(recoveryOnlyMode && recoveredTransactions[i].isRAImport())) {
recoveredTransactions[i].recover();
if (recoveryOnlyMode) {
if (recoveredTransactions[i].getTransactionState().getState() != TransactionState.STATE_NONE) {
Tr.warning(tc, "WTRN0114_TRAN_RETRY_NEEDED",
new Object[] { recoveredTransactions[i].getTranName(),
retryWait });
}
}
}
} catch (Throwable exc) {
FFDCFilter.processException(exc, "com.ibm.tx.jta.impl.RecoveryManager.resync", "1654", this);
Tr.error(tc, "WTRN0016_EXC_DURING_RECOVERY", exc);
}
}
}
if (stopProcessing = shutdownInProgress()) {
break;
}
boolean waitForTxComplete;
if (recoveryOnlyMode || _waitForRecovery) {
waitForTxComplete = !recoveryModeTxnsComplete();
} else {
waitForTxComplete = (_recoveringTransactions.size() > 0);
}
if (!XArecovered || waitForTxComplete) {
if (retryAttempts == 0 && !recoveryOnlyMode && _failureScopeController.localFailureScope()) {
// Call recoveryComplete after first attempt through the loop except for recoveryOnlyMode
// when we are the local server. For recoveryOnlyMode we call recoveryComplete once we
// have fully completed recovery as this is a indication to shutdown the server.
// For the other case of local recovery, recoveryComplete indicates that we are far enough
// through recovery to allow further HA recovery to be enabled by joining their HA groups
// if everything was successful or shutdown the server if anything failed.
// For peer recovery we only call recoveryComplete once we have stopped any recovery action
// as this is used as a "lock" to wait on failback log tidy up.
// So this does not indicate that recovery has completed...
recoveryComplete();
callRecoveryComplete = false;
}
// Not yet completed recovery - wait a while and retry again
// Retry xa resources until complete... Note: we check txn retries in TransactionImpl
// and if they "timeout" they will get removed from _recoveringTransactions.
retryAttempts++;
// Extend the retry interval the same as for a normal transaction...
if (retryAttempts % 10 == 0 && retryWait < Integer.MAX_VALUE / 2) {
retryWait *= 2;
}
synchronized (_recoveryMonitor) {
long timeout = retryWait * 1000L;
long startTime = System.currentTimeMillis();
long startTimeout = timeout;
while (!_shutdownInProgress) {
try {
if (tc.isDebugEnabled())
Tr.debug(tc, "Resync retry in " + timeout + " milliseconds");
_recoveryMonitor.wait(timeout);
} catch (InterruptedException e) {
// No FFDC Code Needed.
if (tc.isDebugEnabled())
Tr.debug(tc, "Resync wait interrupted");
}
if (_shutdownInProgress) {
break;
}
long elapsedTime = System.currentTimeMillis() - startTime;
if (elapsedTime < startTimeout) {
timeout = startTimeout - elapsedTime;
} else {
break;
}
}
}
stopProcessing = shutdownInProgress();
} else {
if (tc.isDebugEnabled())
Tr.debug(tc, "Resync completed");
break;
}
}
if (stopProcessing) {
// stopProcessing is either the local server closing down or peer recovery being halted for a failurescope.
if (_failureScopeController.localFailureScope()) {
if (tc.isDebugEnabled())
Tr.debug(tc, "local failure scope resync interupted");
// FailureScopeController.shutdown() closes the logs
} else {
if (tc.isDebugEnabled())
Tr.debug(tc, "Non-local failure scope resync interupted");
// FailureScopeController.shutdown() does the tidy up and closes the logs
// Don't bother checking that we have no recovering transactions and XArecovered
// since recoveryComplete has already been called so we'd need extra synchronization
// with the shutdown thread.
}
}
// If we have completed resync normally, take this opportunity to clean out the partner log
// if all the trans have completed
else if (XArecovered && (_recoveringTransactions.size() == 0)) {
// NOTE TO REVIEWERS - should we close the logs here or in shutdown?
// shutdown is always called. We should not remove the RM from _activeRecoveryManagers
// until shutdown as we may recieve commit/rollback for completed transactions.
// NOTE it is NOT possible that shutdown is racing us to close the logs - it will be waiting in prepareToShutdown
if (tc.isDebugEnabled())
Tr.debug(tc, "Clearing any unused partners from partner log");
if (!_failureScopeController.localFailureScope()) {
// flag the RM as cleanRemoteShutdown - this stops a shutdown thread trying to close the logs too
// on the off chance that it is also running.
_cleanRemoteShutdown = true;
// Even though we think we have recovered everything, we need to
// check that there are no partners left because of some bad internal failure
// which may allow us to now corrupt the logs
// @D656080 - dont clean up logs for HA cases - if we have completed
// recovery the transactions will be marked complete. We will perform a
// XARM recovery on the next restart and clean up the partners at this point...
try /* @PK31789A */
{ /* @PK31789A */
// preShutdown will ensure that the tranlog is forced. @PK31789A
preShutdown(true); /* @D656080C */
} /* @PK31789A */
catch (Exception e) /* @PK31789A */
{ /* @PK31789A */
// no FFDC required. @PK31789A
} /* @PK31789A */
postShutdown(true); // Close the partner log
} else /* @PK31789A */
{ /* @PK31789A */
// Ensure all end-tran records processed before we delete partners
boolean failed = false; /* @PK31789A */
if ((_tranLog != null) && (_tranLog instanceof DistributedRecoveryLog)) /* @PK31789A */
{ /* @PK31789A */
try /* @PK31789A */
{
// keypoint will ensure that the tranlog is forced. @PK31789A
// If there are any exceptions, then it is not safe to @PK31789A
// tidy up the partnerlog (clearUnused skipped). @PK31789A
((DistributedRecoveryLog) _tranLog).keypoint(); /* @PK31789A */
} /* @PK31789A */
catch (Exception exc2) /* @PK31789A */
{ /* @PK31789A */
FFDCFilter.processException(exc2, "com.ibm.tx.jta.impl.RecoveryManager.resync", "1974", this); /* @PK31789A */
if (tc.isDebugEnabled())
Tr.debug(tc, "keypoint of transaction log failed ... partner log will not be tidied", exc2); /* @PK31789A */
failed = true; /* @PK31789A */
} /* @PK31789A */
} /* @PK31789A */
if (!failed) /* @PK31789A */
{
getPartnerLogTable().clearUnused(); /* @PK31789A */
if (auditRecovery)
Tr.audit(tc, "WTRN0133_RECOVERY_COMPLETE");
}
} /* @PK31789A */
if (callRecoveryComplete)
recoveryComplete();
} else {
// Should only get here if we are in recoveryOnlyMode for local server.
if (tc.isDebugEnabled())
Tr.debug(tc, "Transactions were active. Not clearing any unused partners from partner log");
if (callRecoveryComplete)
recoveryComplete();
}
} catch (RuntimeException r) {
FFDCFilter.processException(r, "com.ibm.tx.jta.impl.RecoveryManager.resync", "1729", this);
resyncComplete(r);
if (tc.isEntryEnabled())
Tr.exit(tc, "resync", r);
throw r;
}
resyncComplete(null);
if (tc.isEntryEnabled())
Tr.exit(tc, "resync");
} } | public class class_name {
protected void resync(int XAEntries) {
if (tc.isEntryEnabled())
Tr.entry(tc, "resync", XAEntries);
try {
boolean XArecovered = (XAEntries == 0);
boolean auditRecovery = ConfigurationProviderManager.getConfigurationProvider().getAuditRecovery();
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (auditRecovery) {
Tr.audit(tc, "WTRN0134_RECOVERING_XARMS", XAEntries); // depends on control dependency: [if], data = [none]
}
int retryAttempts = 0;
final int configuredWait = ConfigurationProviderManager.getConfigurationProvider().getHeuristicRetryInterval();
int retryWait = (configuredWait <= 0) ? TransactionImpl.defaultRetryTime : configuredWait;
boolean callRecoveryComplete = true;
boolean stopProcessing = shutdownInProgress();
while (!stopProcessing) {
if (retryAttempts > 0 && tc.isDebugEnabled())
Tr.debug(tc, "Retrying resync");
// Get list of current recovered transactions
TransactionImpl[] recoveredTransactions = getRecoveringTransactions();
// Contact the XA RMs and get the indoubt XIDs. Match any with our transactions, or else
// roll back the ones that we have no information about. If some fail to recover, we retry
// later.
if (!XArecovered) {
// Build a list of transaction Xids to check with each recovered RM
final Xid[] txnXids = new Xid[recoveredTransactions.length];
for (int i = 0; i < recoveredTransactions.length; i++) {
txnXids[i] = recoveredTransactions[i].getXid(); // depends on control dependency: [for], data = [i]
}
// plt recover will return early if shutdown is detected.
XArecovered = getPartnerLogTable().recover(this, cl, txnXids); // depends on control dependency: [if], data = [none]
}
if (XArecovered) {
// If there are any transactions, proceed with recover.
for (int i = 0; i < recoveredTransactions.length; i++) {
if (stopProcessing = shutdownInProgress()) {
break;
}
try {
//LIDB3645: don't recover JCA inbound tx in recovery-mode
if (!(recoveryOnlyMode && recoveredTransactions[i].isRAImport())) {
recoveredTransactions[i].recover(); // depends on control dependency: [if], data = [none]
if (recoveryOnlyMode) {
if (recoveredTransactions[i].getTransactionState().getState() != TransactionState.STATE_NONE) {
Tr.warning(tc, "WTRN0114_TRAN_RETRY_NEEDED",
new Object[] { recoveredTransactions[i].getTranName(),
retryWait }); // depends on control dependency: [if], data = [none]
}
}
}
} catch (Throwable exc) {
FFDCFilter.processException(exc, "com.ibm.tx.jta.impl.RecoveryManager.resync", "1654", this);
Tr.error(tc, "WTRN0016_EXC_DURING_RECOVERY", exc);
} // depends on control dependency: [catch], data = [none]
}
}
if (stopProcessing = shutdownInProgress()) {
break;
}
boolean waitForTxComplete;
if (recoveryOnlyMode || _waitForRecovery) {
waitForTxComplete = !recoveryModeTxnsComplete(); // depends on control dependency: [if], data = [none]
} else {
waitForTxComplete = (_recoveringTransactions.size() > 0); // depends on control dependency: [if], data = [none]
}
if (!XArecovered || waitForTxComplete) {
if (retryAttempts == 0 && !recoveryOnlyMode && _failureScopeController.localFailureScope()) {
// Call recoveryComplete after first attempt through the loop except for recoveryOnlyMode
// when we are the local server. For recoveryOnlyMode we call recoveryComplete once we
// have fully completed recovery as this is a indication to shutdown the server.
// For the other case of local recovery, recoveryComplete indicates that we are far enough
// through recovery to allow further HA recovery to be enabled by joining their HA groups
// if everything was successful or shutdown the server if anything failed.
// For peer recovery we only call recoveryComplete once we have stopped any recovery action
// as this is used as a "lock" to wait on failback log tidy up.
// So this does not indicate that recovery has completed...
recoveryComplete(); // depends on control dependency: [if], data = [none]
callRecoveryComplete = false; // depends on control dependency: [if], data = [none]
}
// Not yet completed recovery - wait a while and retry again
// Retry xa resources until complete... Note: we check txn retries in TransactionImpl
// and if they "timeout" they will get removed from _recoveringTransactions.
retryAttempts++; // depends on control dependency: [if], data = [none]
// Extend the retry interval the same as for a normal transaction...
if (retryAttempts % 10 == 0 && retryWait < Integer.MAX_VALUE / 2) {
retryWait *= 2; // depends on control dependency: [if], data = [none]
}
synchronized (_recoveryMonitor) { // depends on control dependency: [if], data = [none]
long timeout = retryWait * 1000L;
long startTime = System.currentTimeMillis();
long startTimeout = timeout;
while (!_shutdownInProgress) {
try {
if (tc.isDebugEnabled())
Tr.debug(tc, "Resync retry in " + timeout + " milliseconds");
_recoveryMonitor.wait(timeout); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
// No FFDC Code Needed.
if (tc.isDebugEnabled())
Tr.debug(tc, "Resync wait interrupted");
} // depends on control dependency: [catch], data = [none]
if (_shutdownInProgress) {
break;
}
long elapsedTime = System.currentTimeMillis() - startTime;
if (elapsedTime < startTimeout) {
timeout = startTimeout - elapsedTime; // depends on control dependency: [if], data = [none]
} else {
break;
}
}
}
stopProcessing = shutdownInProgress(); // depends on control dependency: [if], data = [none]
} else {
if (tc.isDebugEnabled())
Tr.debug(tc, "Resync completed");
break;
}
}
if (stopProcessing) {
// stopProcessing is either the local server closing down or peer recovery being halted for a failurescope.
if (_failureScopeController.localFailureScope()) {
if (tc.isDebugEnabled())
Tr.debug(tc, "local failure scope resync interupted");
// FailureScopeController.shutdown() closes the logs
} else {
if (tc.isDebugEnabled())
Tr.debug(tc, "Non-local failure scope resync interupted");
// FailureScopeController.shutdown() does the tidy up and closes the logs
// Don't bother checking that we have no recovering transactions and XArecovered
// since recoveryComplete has already been called so we'd need extra synchronization
// with the shutdown thread.
}
}
// If we have completed resync normally, take this opportunity to clean out the partner log
// if all the trans have completed
else if (XArecovered && (_recoveringTransactions.size() == 0)) {
// NOTE TO REVIEWERS - should we close the logs here or in shutdown?
// shutdown is always called. We should not remove the RM from _activeRecoveryManagers
// until shutdown as we may recieve commit/rollback for completed transactions.
// NOTE it is NOT possible that shutdown is racing us to close the logs - it will be waiting in prepareToShutdown
if (tc.isDebugEnabled())
Tr.debug(tc, "Clearing any unused partners from partner log");
if (!_failureScopeController.localFailureScope()) {
// flag the RM as cleanRemoteShutdown - this stops a shutdown thread trying to close the logs too
// on the off chance that it is also running.
_cleanRemoteShutdown = true; // depends on control dependency: [if], data = [none]
// Even though we think we have recovered everything, we need to
// check that there are no partners left because of some bad internal failure
// which may allow us to now corrupt the logs
// @D656080 - dont clean up logs for HA cases - if we have completed
// recovery the transactions will be marked complete. We will perform a
// XARM recovery on the next restart and clean up the partners at this point...
try /* @PK31789A */
{ /* @PK31789A */
// preShutdown will ensure that the tranlog is forced. @PK31789A
preShutdown(true); /* @D656080C */ // depends on control dependency: [try], data = [none]
} /* @PK31789A */
catch (Exception e) /* @PK31789A */
{ /* @PK31789A */
// no FFDC required. @PK31789A
} /* @PK31789A */ // depends on control dependency: [catch], data = [none]
postShutdown(true); // Close the partner log // depends on control dependency: [if], data = [none]
} else /* @PK31789A */
{ /* @PK31789A */
// Ensure all end-tran records processed before we delete partners
boolean failed = false; /* @PK31789A */
if ((_tranLog != null) && (_tranLog instanceof DistributedRecoveryLog)) /* @PK31789A */
{ /* @PK31789A */
try /* @PK31789A */
{
// keypoint will ensure that the tranlog is forced. @PK31789A
// If there are any exceptions, then it is not safe to @PK31789A
// tidy up the partnerlog (clearUnused skipped). @PK31789A
((DistributedRecoveryLog) _tranLog).keypoint(); /* @PK31789A */ // depends on control dependency: [try], data = [none]
} /* @PK31789A */
catch (Exception exc2) /* @PK31789A */
{ /* @PK31789A */
FFDCFilter.processException(exc2, "com.ibm.tx.jta.impl.RecoveryManager.resync", "1974", this); /* @PK31789A */
if (tc.isDebugEnabled())
Tr.debug(tc, "keypoint of transaction log failed ... partner log will not be tidied", exc2); /* @PK31789A */
failed = true; /* @PK31789A */
} /* @PK31789A */ // depends on control dependency: [catch], data = [none]
} /* @PK31789A */
if (!failed) /* @PK31789A */
{
getPartnerLogTable().clearUnused(); /* @PK31789A */ // depends on control dependency: [if], data = [none]
if (auditRecovery)
Tr.audit(tc, "WTRN0133_RECOVERY_COMPLETE");
}
} /* @PK31789A */
if (callRecoveryComplete)
recoveryComplete();
} else {
// Should only get here if we are in recoveryOnlyMode for local server.
if (tc.isDebugEnabled())
Tr.debug(tc, "Transactions were active. Not clearing any unused partners from partner log");
if (callRecoveryComplete)
recoveryComplete();
}
} catch (RuntimeException r) {
FFDCFilter.processException(r, "com.ibm.tx.jta.impl.RecoveryManager.resync", "1729", this);
resyncComplete(r);
if (tc.isEntryEnabled())
Tr.exit(tc, "resync", r);
throw r;
} // depends on control dependency: [catch], data = [none]
resyncComplete(null);
if (tc.isEntryEnabled())
Tr.exit(tc, "resync");
} } |
public class class_name {
public DescribeSMBFileSharesResult withSMBFileShareInfoList(SMBFileShareInfo... sMBFileShareInfoList) {
if (this.sMBFileShareInfoList == null) {
setSMBFileShareInfoList(new com.amazonaws.internal.SdkInternalList<SMBFileShareInfo>(sMBFileShareInfoList.length));
}
for (SMBFileShareInfo ele : sMBFileShareInfoList) {
this.sMBFileShareInfoList.add(ele);
}
return this;
} } | public class class_name {
public DescribeSMBFileSharesResult withSMBFileShareInfoList(SMBFileShareInfo... sMBFileShareInfoList) {
if (this.sMBFileShareInfoList == null) {
setSMBFileShareInfoList(new com.amazonaws.internal.SdkInternalList<SMBFileShareInfo>(sMBFileShareInfoList.length)); // depends on control dependency: [if], data = [none]
}
for (SMBFileShareInfo ele : sMBFileShareInfoList) {
this.sMBFileShareInfoList.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
@Override
protected boolean onRequestFocusInDescendants(int direction,
Rect previouslyFocusedRect) {
int index;
int increment;
int end;
int count = getChildCount();
if ((direction & FOCUS_FORWARD) != 0) {
index = 0;
increment = 1;
end = count;
} else {
index = count - 1;
increment = -1;
end = -1;
}
for (int i = index; i != end; i += increment) {
View child = getChildAt(i);
if (child.getVisibility() == VISIBLE) {
ItemInfo ii = infoForChild(child);
if (ii != null && ii.position == mCurItem) {
if (child.requestFocus(direction, previouslyFocusedRect)) {
return true;
}
}
}
}
return false;
} } | public class class_name {
@Override
protected boolean onRequestFocusInDescendants(int direction,
Rect previouslyFocusedRect) {
int index;
int increment;
int end;
int count = getChildCount();
if ((direction & FOCUS_FORWARD) != 0) {
index = 0; // depends on control dependency: [if], data = [none]
increment = 1; // depends on control dependency: [if], data = [none]
end = count; // depends on control dependency: [if], data = [none]
} else {
index = count - 1; // depends on control dependency: [if], data = [none]
increment = -1; // depends on control dependency: [if], data = [none]
end = -1; // depends on control dependency: [if], data = [none]
}
for (int i = index; i != end; i += increment) {
View child = getChildAt(i);
if (child.getVisibility() == VISIBLE) {
ItemInfo ii = infoForChild(child);
if (ii != null && ii.position == mCurItem) {
if (child.requestFocus(direction, previouslyFocusedRect)) {
return true; // depends on control dependency: [if], data = [none]
}
}
}
}
return false;
} } |
public class class_name {
public void setBillingRecords(java.util.Collection<BillingRecord> billingRecords) {
if (billingRecords == null) {
this.billingRecords = null;
return;
}
this.billingRecords = new com.amazonaws.internal.SdkInternalList<BillingRecord>(billingRecords);
} } | public class class_name {
public void setBillingRecords(java.util.Collection<BillingRecord> billingRecords) {
if (billingRecords == null) {
this.billingRecords = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.billingRecords = new com.amazonaws.internal.SdkInternalList<BillingRecord>(billingRecords);
} } |
public class class_name {
private void scheduleSendTask(boolean runNow) {
TimerTask task = new TimerTask() {
@Override
public void run() {
byte[] packet;
try {
packet = packets.get(0);
} catch (IndexOutOfBoundsException e) {
// No packets left; return without scheduling another run
return;
}
charc.setValue(packet);
boolean result = gattClient.writeCharacteristic(charc);
if (result) {
packets.remove(0);
int id = ids.remove(0);
retries = 0;
if (onPacketSent != null) {
onPacketSent.onResult(id);
}
Log.d(TAG, "Packet " + id + " sent after " + retries + " retries");
} else {
retries++;
}
scheduleSendTask(false);
}
};
if (runNow) {
task.run();
} else {
sendTimer.schedule(task, SEND_INTERVAL);
}
} } | public class class_name {
private void scheduleSendTask(boolean runNow) {
TimerTask task = new TimerTask() {
@Override
public void run() {
byte[] packet;
try {
packet = packets.get(0); // depends on control dependency: [try], data = [none]
} catch (IndexOutOfBoundsException e) {
// No packets left; return without scheduling another run
return;
} // depends on control dependency: [catch], data = [none]
charc.setValue(packet);
boolean result = gattClient.writeCharacteristic(charc);
if (result) {
packets.remove(0); // depends on control dependency: [if], data = [none]
int id = ids.remove(0);
retries = 0; // depends on control dependency: [if], data = [none]
if (onPacketSent != null) {
onPacketSent.onResult(id); // depends on control dependency: [if], data = [none]
}
Log.d(TAG, "Packet " + id + " sent after " + retries + " retries"); // depends on control dependency: [if], data = [none]
} else {
retries++; // depends on control dependency: [if], data = [none]
}
scheduleSendTask(false);
}
};
if (runNow) {
task.run(); // depends on control dependency: [if], data = [none]
} else {
sendTimer.schedule(task, SEND_INTERVAL); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static RecursionDetection detectRecursiveInjection(Throwable t) {
RecursionDetection rd;
boolean recursiveInjection = false;
boolean logged = false;
Throwable cause = t;
Throwable lastCause = null;
while (cause != null && cause != lastCause) {
if (cause instanceof StackOverflowError ||
cause instanceof RecursiveInjectionException) {
recursiveInjection = true;
if (cause instanceof RecursiveInjectionException &&
((RecursiveInjectionException) cause).ivLogged) {
logged = true;
break;
}
}
lastCause = cause;
cause = cause.getCause();
}
if (recursiveInjection && logged) {
rd = RecursionDetection.RecursiveAlreadyLogged;
} else if (recursiveInjection) {
rd = RecursionDetection.Recursive;
} else {
rd = RecursionDetection.NotRecursive;
}
return rd;
} } | public class class_name {
public static RecursionDetection detectRecursiveInjection(Throwable t) {
RecursionDetection rd;
boolean recursiveInjection = false;
boolean logged = false;
Throwable cause = t;
Throwable lastCause = null;
while (cause != null && cause != lastCause) {
if (cause instanceof StackOverflowError ||
cause instanceof RecursiveInjectionException) {
recursiveInjection = true; // depends on control dependency: [if], data = [none]
if (cause instanceof RecursiveInjectionException &&
((RecursiveInjectionException) cause).ivLogged) {
logged = true; // depends on control dependency: [if], data = [none]
break;
}
}
lastCause = cause; // depends on control dependency: [while], data = [none]
cause = cause.getCause(); // depends on control dependency: [while], data = [none]
}
if (recursiveInjection && logged) {
rd = RecursionDetection.RecursiveAlreadyLogged; // depends on control dependency: [if], data = [none]
} else if (recursiveInjection) {
rd = RecursionDetection.Recursive; // depends on control dependency: [if], data = [none]
} else {
rd = RecursionDetection.NotRecursive; // depends on control dependency: [if], data = [none]
}
return rd;
} } |
public class class_name {
private void updateTable(KsDef ksDef, TableInfo tableInfo) throws Exception
{
for (CfDef cfDef : ksDef.getCf_defs())
{
if (cfDef.getName().equals(tableInfo.getTableName())
&& cfDef.getColumn_type().equals(ColumnFamilyType.getInstanceOf(tableInfo.getType()).name()))
{
boolean toUpdate = false;
if (cfDef.getColumn_type().equals(STANDARDCOLUMNFAMILY))
{
for (ColumnInfo columnInfo : tableInfo.getColumnMetadatas())
{
toUpdate = isCfDefUpdated(columnInfo, cfDef, isCql3Enabled(tableInfo),
isCounterColumnType(tableInfo, null), tableInfo) ? true : toUpdate;
}
}
if (toUpdate)
{
cassandra_client.system_update_column_family(cfDef);
}
createIndexUsingThrift(tableInfo, cfDef);
break;
}
}
} } | public class class_name {
private void updateTable(KsDef ksDef, TableInfo tableInfo) throws Exception
{
for (CfDef cfDef : ksDef.getCf_defs())
{
if (cfDef.getName().equals(tableInfo.getTableName())
&& cfDef.getColumn_type().equals(ColumnFamilyType.getInstanceOf(tableInfo.getType()).name()))
{
boolean toUpdate = false;
if (cfDef.getColumn_type().equals(STANDARDCOLUMNFAMILY))
{
for (ColumnInfo columnInfo : tableInfo.getColumnMetadatas())
{
toUpdate = isCfDefUpdated(columnInfo, cfDef, isCql3Enabled(tableInfo),
isCounterColumnType(tableInfo, null), tableInfo) ? true : toUpdate; // depends on control dependency: [for], data = [columnInfo]
}
}
if (toUpdate)
{
cassandra_client.system_update_column_family(cfDef); // depends on control dependency: [if], data = [none]
}
createIndexUsingThrift(tableInfo, cfDef);
break;
}
}
} } |
public class class_name {
public static void setLocation(HttpServletRequest request, HttpServletResponse response, String location) {
if(request.getAttribute(IS_INCLUDED_REQUEST_ATTRIBUTE_NAME) == null) {
// Not included, setHeader directly
response.setHeader("Location", location);
} else {
// Is included, set attribute so top level tag can perform actual setHeader call
request.setAttribute(LOCATION_REQUEST_ATTRIBUTE_NAME, location);
}
} } | public class class_name {
public static void setLocation(HttpServletRequest request, HttpServletResponse response, String location) {
if(request.getAttribute(IS_INCLUDED_REQUEST_ATTRIBUTE_NAME) == null) {
// Not included, setHeader directly
response.setHeader("Location", location); // depends on control dependency: [if], data = [none]
} else {
// Is included, set attribute so top level tag can perform actual setHeader call
request.setAttribute(LOCATION_REQUEST_ATTRIBUTE_NAME, location); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public final boolean negotiate (TargetServer target, final LoginStage loginStage, final boolean leadingConnection, final boolean initialPdu, final String key, final String values, final Collection<String> responseKeyValuePairs) {
// (re)check key (just in case), this should have been checked before
// calling this method
if (!matchKey(key)) {
fail("\"" + key + "\" does not match key in" + keySet);
return false;
}
// prevent renegotiation and remember this negotiation
if (alreadyNegotiated) {
fail("illegal renegotiation");
return false;
}
alreadyNegotiated = true;
// check use code
if (!use.checkUse(loginStage, leadingConnection, initialPdu)) {
fail("wrong use: " + use + ", " + loginStage + ", " + leadingConnection + ", " + initialPdu);
return false;
}
// transform values to appropriate type
final Object offer = parseOffer(target, values);
if (offer == null) {
fail("value format error: " + values);
return false;
}
// check if values are in the protocol-conform range/set of values
if (!inProtocolValueRange(offer)) {
fail("illegal values offered: " + values);
return false;
}
// *** declare ***
if (negotiationType == NegotiationType.DECLARED) {
// save received value ...
processDeclaration(offer);
// ... and accept silently
negotiationStatus = NegotiationStatus.ACCEPTED;
return true;
}
// *** negotiate ***
if (negotiationType == NegotiationType.NEGOTIATED) {
String negotiatedValue;// will be returned as value part
if (negotiationStatus == NegotiationStatus.IRRELEVANT)
negotiatedValue = TextKeyword.IRRELEVANT;
else
negotiatedValue = processNegotiation(offer);
String reply;
// reply, remember outcome, log, and return
if (negotiatedValue == null) {// no commonly supported values
reply = TextParameter.toKeyValuePair(key, TextKeyword.REJECT);
responseKeyValuePairs.add(reply);
fail("rejected value(s): " + values);
return false;
}// else
reply = TextParameter.toKeyValuePair(key, negotiatedValue);
responseKeyValuePairs.add(reply);
return true;
}
// we should not be here
fail("initialization error: negotiationType == null");
return false;
} } | public class class_name {
public final boolean negotiate (TargetServer target, final LoginStage loginStage, final boolean leadingConnection, final boolean initialPdu, final String key, final String values, final Collection<String> responseKeyValuePairs) {
// (re)check key (just in case), this should have been checked before
// calling this method
if (!matchKey(key)) {
fail("\"" + key + "\" does not match key in" + keySet);
// depends on control dependency: [if], data = [none]
return false;
// depends on control dependency: [if], data = [none]
}
// prevent renegotiation and remember this negotiation
if (alreadyNegotiated) {
fail("illegal renegotiation");
// depends on control dependency: [if], data = [none]
return false;
// depends on control dependency: [if], data = [none]
}
alreadyNegotiated = true;
// check use code
if (!use.checkUse(loginStage, leadingConnection, initialPdu)) {
fail("wrong use: " + use + ", " + loginStage + ", " + leadingConnection + ", " + initialPdu);
// depends on control dependency: [if], data = [none]
return false;
// depends on control dependency: [if], data = [none]
}
// transform values to appropriate type
final Object offer = parseOffer(target, values);
if (offer == null) {
fail("value format error: " + values);
// depends on control dependency: [if], data = [none]
return false;
// depends on control dependency: [if], data = [none]
}
// check if values are in the protocol-conform range/set of values
if (!inProtocolValueRange(offer)) {
fail("illegal values offered: " + values);
// depends on control dependency: [if], data = [none]
return false;
// depends on control dependency: [if], data = [none]
}
// *** declare ***
if (negotiationType == NegotiationType.DECLARED) {
// save received value ...
processDeclaration(offer);
// depends on control dependency: [if], data = [none]
// ... and accept silently
negotiationStatus = NegotiationStatus.ACCEPTED;
// depends on control dependency: [if], data = [none]
return true;
// depends on control dependency: [if], data = [none]
}
// *** negotiate ***
if (negotiationType == NegotiationType.NEGOTIATED) {
String negotiatedValue;// will be returned as value part
if (negotiationStatus == NegotiationStatus.IRRELEVANT)
negotiatedValue = TextKeyword.IRRELEVANT;
else
negotiatedValue = processNegotiation(offer);
String reply;
// reply, remember outcome, log, and return
if (negotiatedValue == null) {// no commonly supported values
reply = TextParameter.toKeyValuePair(key, TextKeyword.REJECT);
// depends on control dependency: [if], data = [none]
responseKeyValuePairs.add(reply);
// depends on control dependency: [if], data = [none]
fail("rejected value(s): " + values);
// depends on control dependency: [if], data = [none]
return false;
// depends on control dependency: [if], data = [none]
}// else
reply = TextParameter.toKeyValuePair(key, negotiatedValue);
// depends on control dependency: [if], data = [none]
responseKeyValuePairs.add(reply);
// depends on control dependency: [if], data = [none]
return true;
// depends on control dependency: [if], data = [none]
}
// we should not be here
fail("initialization error: negotiationType == null");
return false;
} } |
public class class_name {
@Override
public Byte convert(Object value) {
if (value instanceof Number) {
double d = ((Number)value).doubleValue();
if (Double.isNaN(d) || Math.round(d)!=d) throw new IllegalArgumentException("Not a valid byte: " + value);
long l = ((Number)value).longValue();
if (l>=Byte.MIN_VALUE && l<=Byte.MAX_VALUE) return Byte.valueOf((byte)l);
else throw new IllegalArgumentException("Value too large for byte: " + value);
} else if (value instanceof String) {
return Byte.parseByte((String)value);
} else return null;
} } | public class class_name {
@Override
public Byte convert(Object value) {
if (value instanceof Number) {
double d = ((Number)value).doubleValue();
if (Double.isNaN(d) || Math.round(d)!=d) throw new IllegalArgumentException("Not a valid byte: " + value);
long l = ((Number)value).longValue();
if (l>=Byte.MIN_VALUE && l<=Byte.MAX_VALUE) return Byte.valueOf((byte)l);
else throw new IllegalArgumentException("Value too large for byte: " + value);
} else if (value instanceof String) {
return Byte.parseByte((String)value); // depends on control dependency: [if], data = [none]
} else return null;
} } |
public class class_name {
public CreateDeploymentRequest withLayerIds(String... layerIds) {
if (this.layerIds == null) {
setLayerIds(new com.amazonaws.internal.SdkInternalList<String>(layerIds.length));
}
for (String ele : layerIds) {
this.layerIds.add(ele);
}
return this;
} } | public class class_name {
public CreateDeploymentRequest withLayerIds(String... layerIds) {
if (this.layerIds == null) {
setLayerIds(new com.amazonaws.internal.SdkInternalList<String>(layerIds.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : layerIds) {
this.layerIds.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.