code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public static void isReferrerHostValid(final String currentReqURL, final String storedReq, final List<String> domainList) throws RuntimeException {
Boolean isValid = false;
isValid = java.security.AccessController.doPrivileged(new java.security.PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
Boolean _isValid = false;
URL referrerURL = null;
URL currentURL = null;
try {
referrerURL = new URL(storedReq);
currentURL = new URL(currentReqURL);
if (referrerURL != null && currentURL != null) {
String referrerHost = referrerURL.getHost();
String currentReqHost = currentURL.getHost();
if (referrerHost != null && currentReqHost != null
&& (referrerHost.equalsIgnoreCase(currentReqHost) || isReferrerHostMatchDomainNameList(referrerHost, domainList))) {
_isValid = true;
}
}
} catch (MalformedURLException me) {
//if referrerURL==null then storedReq is not a valid URL. Otherwise, currentURL is invalid
if (referrerURL == null) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "WASReqURL:" + storedReq + " is a MalformedURL.");
}
RuntimeException e = new RuntimeException("WASReqURL:" + "'" + storedReq + "'" + " is not a valid URL.", me);
throw e;
} else {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "currentURL:" + currentReqURL + " is a MalformedURL.");
}
RuntimeException e = new RuntimeException("The request URL:" + "'" + currentReqURL + "'"
+ " is not a valid URL.", me);
throw e;
}
}
return _isValid;
}
});
if (!isValid) {
RuntimeException e = new RuntimeException("WASReqURL:" + "'" + storedReq + "'"
+ " hostname does not match current request hostname: " + "'" + currentReqURL
+ "'");
throw e;
}
return;
} } | public class class_name {
public static void isReferrerHostValid(final String currentReqURL, final String storedReq, final List<String> domainList) throws RuntimeException {
Boolean isValid = false;
isValid = java.security.AccessController.doPrivileged(new java.security.PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
Boolean _isValid = false;
URL referrerURL = null;
URL currentURL = null;
try {
referrerURL = new URL(storedReq); // depends on control dependency: [try], data = [none]
currentURL = new URL(currentReqURL); // depends on control dependency: [try], data = [none]
if (referrerURL != null && currentURL != null) {
String referrerHost = referrerURL.getHost();
String currentReqHost = currentURL.getHost();
if (referrerHost != null && currentReqHost != null
&& (referrerHost.equalsIgnoreCase(currentReqHost) || isReferrerHostMatchDomainNameList(referrerHost, domainList))) {
_isValid = true; // depends on control dependency: [if], data = [none]
}
}
} catch (MalformedURLException me) {
//if referrerURL==null then storedReq is not a valid URL. Otherwise, currentURL is invalid
if (referrerURL == null) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "WASReqURL:" + storedReq + " is a MalformedURL."); // depends on control dependency: [if], data = [none]
}
RuntimeException e = new RuntimeException("WASReqURL:" + "'" + storedReq + "'" + " is not a valid URL.", me);
throw e;
} else {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "currentURL:" + currentReqURL + " is a MalformedURL."); // depends on control dependency: [if], data = [none]
}
RuntimeException e = new RuntimeException("The request URL:" + "'" + currentReqURL + "'"
+ " is not a valid URL.", me);
throw e;
}
} // depends on control dependency: [catch], data = [none]
return _isValid;
}
});
if (!isValid) {
RuntimeException e = new RuntimeException("WASReqURL:" + "'" + storedReq + "'"
+ " hostname does not match current request hostname: " + "'" + currentReqURL
+ "'");
throw e;
}
return;
} } |
public class class_name {
public static Batch batchFilteredWith( final Batch batch,
final RowFilter filter ) {
if (batch == null || batch.isEmpty() || batch.rowCount() == 0 || filter == null || batch.width() < 1) return batch;
return new Batch() {
private boolean atNext = false;
@Override
public int width() {
return batch.width();
}
@Override
public boolean isEmpty() {
return batch.isEmpty();
}
@Override
public String getWorkspaceName() {
return batch.getWorkspaceName();
}
@Override
public long rowCount() {
return -1L;
}
@Override
public CachedNode getNode() {
return batch.getNode();
}
@Override
public CachedNode getNode( int index ) {
return batch.getNode(index);
}
@Override
public float getScore() {
return batch.getScore();
}
@Override
public float getScore( int index ) {
return batch.getScore(index);
}
@Override
public boolean hasNext() {
return findNext();
}
@Override
public void nextRow() {
if (findNext()) {
atNext = false;
return;
}
throw new NoSuchElementException();
}
private boolean findNext() {
if (!atNext) {
while (batch.hasNext()) {
batch.nextRow();
// See if the batch's current row satisfies the filter ...
if (filter.isCurrentRowValid(batch)) {
atNext = true;
break;
}
}
}
return atNext;
}
@Override
public String toString() {
return "(filtered-batch " + filter + " on " + batch + ")";
}
};
} } | public class class_name {
public static Batch batchFilteredWith( final Batch batch,
final RowFilter filter ) {
if (batch == null || batch.isEmpty() || batch.rowCount() == 0 || filter == null || batch.width() < 1) return batch;
return new Batch() {
private boolean atNext = false;
@Override
public int width() {
return batch.width();
}
@Override
public boolean isEmpty() {
return batch.isEmpty();
}
@Override
public String getWorkspaceName() {
return batch.getWorkspaceName();
}
@Override
public long rowCount() {
return -1L;
}
@Override
public CachedNode getNode() {
return batch.getNode();
}
@Override
public CachedNode getNode( int index ) {
return batch.getNode(index);
}
@Override
public float getScore() {
return batch.getScore();
}
@Override
public float getScore( int index ) {
return batch.getScore(index);
}
@Override
public boolean hasNext() {
return findNext();
}
@Override
public void nextRow() {
if (findNext()) {
atNext = false; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
throw new NoSuchElementException();
}
private boolean findNext() {
if (!atNext) {
while (batch.hasNext()) {
batch.nextRow(); // depends on control dependency: [while], data = [none]
// See if the batch's current row satisfies the filter ...
if (filter.isCurrentRowValid(batch)) {
atNext = true; // depends on control dependency: [if], data = [none]
break;
}
}
}
return atNext;
}
@Override
public String toString() {
return "(filtered-batch " + filter + " on " + batch + ")";
}
};
} } |
public class class_name {
public String getHeader(String header) {
if (headers == null) {
return null;
}
return headers.get(header);
} } | public class class_name {
public String getHeader(String header) {
if (headers == null) {
return null; // depends on control dependency: [if], data = [none]
}
return headers.get(header);
} } |
public class class_name {
private int selectRightToLeft( int col , int[] scores ) {
// see how far it can search
int localMax = Math.min(imageWidth-regionWidth,col+maxDisparity)-col-minDisparity;
int indexBest = 0;
int indexScore = col;
int scoreBest = scores[col];
indexScore += imageWidth+1;
for( int i = 1; i < localMax; i++ ,indexScore += imageWidth+1) {
int s = scores[indexScore];
if( s < scoreBest ) {
scoreBest = s;
indexBest = i;
}
}
return indexBest;
} } | public class class_name {
private int selectRightToLeft( int col , int[] scores ) {
// see how far it can search
int localMax = Math.min(imageWidth-regionWidth,col+maxDisparity)-col-minDisparity;
int indexBest = 0;
int indexScore = col;
int scoreBest = scores[col];
indexScore += imageWidth+1;
for( int i = 1; i < localMax; i++ ,indexScore += imageWidth+1) {
int s = scores[indexScore];
if( s < scoreBest ) {
scoreBest = s; // depends on control dependency: [if], data = [none]
indexBest = i; // depends on control dependency: [if], data = [none]
}
}
return indexBest;
} } |
public class class_name {
public static LoggerContext getContext() {
try {
return factory.getContext(FQCN, null, null, true);
} catch (final IllegalStateException ex) {
LOGGER.warn(ex.getMessage() + " Using SimpleLogger");
return new SimpleLoggerContextFactory().getContext(FQCN, null, null, true);
}
} } | public class class_name {
public static LoggerContext getContext() {
try {
return factory.getContext(FQCN, null, null, true); // depends on control dependency: [try], data = [none]
} catch (final IllegalStateException ex) {
LOGGER.warn(ex.getMessage() + " Using SimpleLogger");
return new SimpleLoggerContextFactory().getContext(FQCN, null, null, true);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static final long[] computeIndexOffsets(int[] sizes) {
long[] indexOffsets = new long[sizes.length];
for (int i = sizes.length - 1; i >= 0; i--) {
if (i == sizes.length - 1) {
indexOffsets[i] = 1;
} else {
indexOffsets[i] = indexOffsets[i + 1] * ((long) sizes[i + 1]);
}
}
return indexOffsets;
} } | public class class_name {
public static final long[] computeIndexOffsets(int[] sizes) {
long[] indexOffsets = new long[sizes.length];
for (int i = sizes.length - 1; i >= 0; i--) {
if (i == sizes.length - 1) {
indexOffsets[i] = 1; // depends on control dependency: [if], data = [none]
} else {
indexOffsets[i] = indexOffsets[i + 1] * ((long) sizes[i + 1]); // depends on control dependency: [if], data = [none]
}
}
return indexOffsets;
} } |
public class class_name {
public CompactSketch<S> getResult() {
sketch_.trim();
if (theta_ < sketch_.theta_) {
sketch_.setThetaLong(theta_);
sketch_.rebuild();
}
return sketch_.compact();
} } | public class class_name {
public CompactSketch<S> getResult() {
sketch_.trim();
if (theta_ < sketch_.theta_) {
sketch_.setThetaLong(theta_); // depends on control dependency: [if], data = [(theta_]
sketch_.rebuild(); // depends on control dependency: [if], data = [none]
}
return sketch_.compact();
} } |
public class class_name {
@Override
public String toXML(org.jivesoftware.smack.packet.XmlEnvironment enclosingNamespace) {
StringBuilder buf = new StringBuilder();
buf.append('<').append(getElementName()).append(" xmlns=\"").append(getNamespace()).append(
"\">");
// Loop through all roster entries and append them to the string buffer
for (Iterator<RemoteRosterEntry> i = getRosterEntries(); i.hasNext();) {
RemoteRosterEntry remoteRosterEntry = i.next();
buf.append(remoteRosterEntry.toXML());
}
buf.append("</").append(getElementName()).append('>');
return buf.toString();
} } | public class class_name {
@Override
public String toXML(org.jivesoftware.smack.packet.XmlEnvironment enclosingNamespace) {
StringBuilder buf = new StringBuilder();
buf.append('<').append(getElementName()).append(" xmlns=\"").append(getNamespace()).append(
"\">");
// Loop through all roster entries and append them to the string buffer
for (Iterator<RemoteRosterEntry> i = getRosterEntries(); i.hasNext();) {
RemoteRosterEntry remoteRosterEntry = i.next();
buf.append(remoteRosterEntry.toXML()); // depends on control dependency: [for], data = [none]
}
buf.append("</").append(getElementName()).append('>');
return buf.toString();
} } |
public class class_name {
public boolean evaluate(List<Object> objects, String sql) throws SQLException {
synchronized (this) {
String actualSql = sql == null ? this.sql : sql;
PreparedStatement actualStmnt = null;
try {
actualStmnt = sql == null ? this.stmnt : prepareStatement(sql);
this.objects = objects;
actualStmnt.execute();
ResultSet rs = actualStmnt.getResultSet();
if (!rs.next()) {
throw new IllegalArgumentException("Expected at least one returned row. SQL evaluated: " + actualSql);
}
boolean result = true;
do {
result &= rs.getBoolean(1);
} while (rs.next());
return result;
} finally {
if (sql != null && actualStmnt != null) {
actualStmnt.close();
}
}
}
} } | public class class_name {
public boolean evaluate(List<Object> objects, String sql) throws SQLException {
synchronized (this) {
String actualSql = sql == null ? this.sql : sql;
PreparedStatement actualStmnt = null;
try {
actualStmnt = sql == null ? this.stmnt : prepareStatement(sql); // depends on control dependency: [try], data = [none]
this.objects = objects; // depends on control dependency: [try], data = [none]
actualStmnt.execute(); // depends on control dependency: [try], data = [none]
ResultSet rs = actualStmnt.getResultSet();
if (!rs.next()) {
throw new IllegalArgumentException("Expected at least one returned row. SQL evaluated: " + actualSql);
}
boolean result = true;
do {
result &= rs.getBoolean(1);
} while (rs.next());
return result; // depends on control dependency: [try], data = [none]
} finally {
if (sql != null && actualStmnt != null) {
actualStmnt.close(); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
private boolean lessThanOrEqual(
byte[] a,
byte[] b)
{
if (a.length <= b.length)
{
for (int i = 0; i != a.length; i++)
{
int l = a[i] & 0xff;
int r = b[i] & 0xff;
if (r > l)
{
return true;
}
else if (l > r)
{
return false;
}
}
return true;
}
else
{
for (int i = 0; i != b.length; i++)
{
int l = a[i] & 0xff;
int r = b[i] & 0xff;
if (r > l)
{
return true;
}
else if (l > r)
{
return false;
}
}
return false;
}
} } | public class class_name {
private boolean lessThanOrEqual(
byte[] a,
byte[] b)
{
if (a.length <= b.length)
{
for (int i = 0; i != a.length; i++)
{
int l = a[i] & 0xff;
int r = b[i] & 0xff;
if (r > l)
{
return true; // depends on control dependency: [if], data = [none]
}
else if (l > r)
{
return false; // depends on control dependency: [if], data = [none]
}
}
return true; // depends on control dependency: [if], data = [none]
}
else
{
for (int i = 0; i != b.length; i++)
{
int l = a[i] & 0xff;
int r = b[i] & 0xff;
if (r > l)
{
return true; // depends on control dependency: [if], data = [none]
}
else if (l > r)
{
return false; // depends on control dependency: [if], data = [none]
}
}
return false; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public LinkedHashMap<String, Field> fieldsToMap( // NOSONAR
List<com.google.cloud.bigquery.Field> schema,
List<FieldValue> values
) {
checkState(
schema.size() == values.size(),
"Schema '{}' and Values '{}' sizes do not match.",
schema.size(),
values.size()
);
LinkedHashMap<String, Field> root = new LinkedHashMap<>();
for (int i = 0; i < values.size(); i++) {
FieldValue value = values.get(i);
com.google.cloud.bigquery.Field field = schema.get(i);
if (value.getAttribute().equals(FieldValue.Attribute.PRIMITIVE)) {
root.put(field.getName(), fromPrimitiveField(field, value));
} else if (value.getAttribute().equals(FieldValue.Attribute.RECORD)) {
root.put(
field.getName(),
Field.create(fieldsToMap(field.getSubFields(), value.getRecordValue()))
);
} else if (value.getAttribute().equals(FieldValue.Attribute.REPEATED)) {
root.put(field.getName(), Field.create(fromRepeatedField(field, value.getRepeatedValue())));
}
}
return root;
} } | public class class_name {
public LinkedHashMap<String, Field> fieldsToMap( // NOSONAR
List<com.google.cloud.bigquery.Field> schema,
List<FieldValue> values
) {
checkState(
schema.size() == values.size(),
"Schema '{}' and Values '{}' sizes do not match.",
schema.size(),
values.size()
);
LinkedHashMap<String, Field> root = new LinkedHashMap<>();
for (int i = 0; i < values.size(); i++) {
FieldValue value = values.get(i);
com.google.cloud.bigquery.Field field = schema.get(i);
if (value.getAttribute().equals(FieldValue.Attribute.PRIMITIVE)) {
root.put(field.getName(), fromPrimitiveField(field, value)); // depends on control dependency: [if], data = [none]
} else if (value.getAttribute().equals(FieldValue.Attribute.RECORD)) {
root.put(
field.getName(),
Field.create(fieldsToMap(field.getSubFields(), value.getRecordValue()))
); // depends on control dependency: [if], data = [none]
} else if (value.getAttribute().equals(FieldValue.Attribute.REPEATED)) {
root.put(field.getName(), Field.create(fromRepeatedField(field, value.getRepeatedValue()))); // depends on control dependency: [if], data = [none]
}
}
return root;
} } |
public class class_name {
@InterfaceStability.Uncommitted
public N1qlParams rawParam(String name, Object value) {
if (this.rawParams == null) {
this.rawParams = new HashMap<String, Object>();
}
if (!JsonValue.checkType(value)) {
throw new IllegalArgumentException("Only JSON types are supported.");
}
rawParams.put(name, value);
return this;
} } | public class class_name {
@InterfaceStability.Uncommitted
public N1qlParams rawParam(String name, Object value) {
if (this.rawParams == null) {
this.rawParams = new HashMap<String, Object>(); // depends on control dependency: [if], data = [none]
}
if (!JsonValue.checkType(value)) {
throw new IllegalArgumentException("Only JSON types are supported.");
}
rawParams.put(name, value);
return this;
} } |
public class class_name {
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(url.getPort());
while (true) {
// Create one script per socket connection.
// This is purposefully not caching the Script
// so that the script source file can be changed on the fly,
// as each connection is made to the server.
//FIXME: Groovy has other mechanisms specifically for watching to see if source code changes.
// We should probably be using that here.
// See also the comment about the fact we recompile a script that can't change.
Script script = groovy.parse(source);
new GroovyClientConnection(script, autoOutput, serverSocket.accept());
}
} catch (Exception e) {
e.printStackTrace();
}
} } | public class class_name {
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(url.getPort());
while (true) {
// Create one script per socket connection.
// This is purposefully not caching the Script
// so that the script source file can be changed on the fly,
// as each connection is made to the server.
//FIXME: Groovy has other mechanisms specifically for watching to see if source code changes.
// We should probably be using that here.
// See also the comment about the fact we recompile a script that can't change.
Script script = groovy.parse(source);
new GroovyClientConnection(script, autoOutput, serverSocket.accept()); // depends on control dependency: [while], data = [none]
}
} catch (Exception e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public DBCluster withAssociatedRoles(DBClusterRole... associatedRoles) {
if (this.associatedRoles == null) {
setAssociatedRoles(new com.amazonaws.internal.SdkInternalList<DBClusterRole>(associatedRoles.length));
}
for (DBClusterRole ele : associatedRoles) {
this.associatedRoles.add(ele);
}
return this;
} } | public class class_name {
public DBCluster withAssociatedRoles(DBClusterRole... associatedRoles) {
if (this.associatedRoles == null) {
setAssociatedRoles(new com.amazonaws.internal.SdkInternalList<DBClusterRole>(associatedRoles.length)); // depends on control dependency: [if], data = [none]
}
for (DBClusterRole ele : associatedRoles) {
this.associatedRoles.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public void writeString(String value)
throws IOException
{
int offset = _offset;
byte[] buffer = _buffer;
if (SIZE <= offset + 16) {
flushBuffer();
offset = _offset;
}
if (value == null) {
buffer[offset++] = (byte) 'N';
_offset = offset;
}
else {
int length = value.length();
int strOffset = 0;
while (length > 0x8000) {
int sublen = 0x8000;
offset = _offset;
if (SIZE <= offset + 16) {
flushBuffer();
offset = _offset;
}
// chunk can't end in high surrogate
char tail = value.charAt(strOffset + sublen - 1);
if (0xd800 <= tail && tail <= 0xdbff)
sublen--;
buffer[offset + 0] = (byte) BC_STRING_CHUNK;
buffer[offset + 1] = (byte) (sublen >> 8);
buffer[offset + 2] = (byte) (sublen);
_offset = offset + 3;
printString(value, strOffset, sublen);
length -= sublen;
strOffset += sublen;
}
offset = _offset;
if (SIZE <= offset + 16) {
flushBuffer();
offset = _offset;
}
if (length <= STRING_DIRECT_MAX) {
buffer[offset++] = (byte) (BC_STRING_DIRECT + length);
}
else if (length <= STRING_SHORT_MAX) {
buffer[offset++] = (byte) (BC_STRING_SHORT + (length >> 8));
buffer[offset++] = (byte) (length);
}
else {
buffer[offset++] = (byte) ('S');
buffer[offset++] = (byte) (length >> 8);
buffer[offset++] = (byte) (length);
}
_offset = offset;
printString(value, strOffset, length);
}
} } | public class class_name {
public void writeString(String value)
throws IOException
{
int offset = _offset;
byte[] buffer = _buffer;
if (SIZE <= offset + 16) {
flushBuffer();
offset = _offset;
}
if (value == null) {
buffer[offset++] = (byte) 'N';
_offset = offset;
}
else {
int length = value.length();
int strOffset = 0;
while (length > 0x8000) {
int sublen = 0x8000;
offset = _offset;
if (SIZE <= offset + 16) {
flushBuffer(); // depends on control dependency: [if], data = [none]
offset = _offset; // depends on control dependency: [if], data = [none]
}
// chunk can't end in high surrogate
char tail = value.charAt(strOffset + sublen - 1);
if (0xd800 <= tail && tail <= 0xdbff)
sublen--;
buffer[offset + 0] = (byte) BC_STRING_CHUNK;
buffer[offset + 1] = (byte) (sublen >> 8);
buffer[offset + 2] = (byte) (sublen);
_offset = offset + 3;
printString(value, strOffset, sublen);
length -= sublen;
strOffset += sublen;
}
offset = _offset;
if (SIZE <= offset + 16) {
flushBuffer();
offset = _offset;
}
if (length <= STRING_DIRECT_MAX) {
buffer[offset++] = (byte) (BC_STRING_DIRECT + length);
}
else if (length <= STRING_SHORT_MAX) {
buffer[offset++] = (byte) (BC_STRING_SHORT + (length >> 8));
buffer[offset++] = (byte) (length);
}
else {
buffer[offset++] = (byte) ('S');
buffer[offset++] = (byte) (length >> 8);
buffer[offset++] = (byte) (length);
}
_offset = offset;
printString(value, strOffset, length);
}
} } |
public class class_name {
static final boolean compareBuffer(final byte[] buf1, final int offset1, final byte[] buf2,
final int offset2, final int len) {
for (int i = 0; i < len; i++) {
final byte b1 = buf1[offset1 + i];
final byte b2 = buf2[offset2 + i];
if (b1 != b2) {
return false;
}
}
return true;
} } | public class class_name {
static final boolean compareBuffer(final byte[] buf1, final int offset1, final byte[] buf2,
final int offset2, final int len) {
for (int i = 0; i < len; i++) {
final byte b1 = buf1[offset1 + i];
final byte b2 = buf2[offset2 + i];
if (b1 != b2) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
@Override
public void updateCounterDetails(final Counter incomingCounter)
{
Preconditions.checkNotNull(incomingCounter);
// First, assert the counter is in a proper state. If done consistently (i.e., in a TX, then this will function
// as an effective CounterData lock).
// Second, Update the counter details.
ObjectifyService.ofy().transact(new Work<Void>()
{
@Override
public Void run()
{
// First, load the incomingCounter from the datastore via a transactional get to ensure it has the
// proper state.
final Optional<CounterData> optCounterData = getCounterData(incomingCounter.getName());
// //////////////
// ShortCircuit: Can't update a counter that doesn't exist!
// //////////////
if (!optCounterData.isPresent())
{
throw new NoCounterExistsException(incomingCounter.getName());
}
final CounterData counterDataInDatastore = optCounterData.get();
// Make sure the stored counter is currently in an updatable state!
assertCounterDetailsMutatable(incomingCounter.getName(), counterDataInDatastore.getCounterStatus());
// Make sure the incoming counter status is a validly settable status
assertValidExternalCounterStatus(incomingCounter.getName(), incomingCounter.getCounterStatus());
// NOTE: READ_ONLY_COUNT status means the count can't be incremented/decremented. However, it's details
// can still be mutated.
// NOTE: The counterName/counterId may not change!
// Update the Description
counterDataInDatastore.setDescription(incomingCounter.getDescription());
// Update the numShards. Aside from setting this value, nothing explicitly needs to happen in the
// datastore since shards will be created when a counter in incremented (if the shard doesn't already
// exist). However, if the number of shards is being reduced, then throw an exception since this
// requires counter shard reduction and some extra thinking. We can't allow the shard-count to go down
// unless we collapse the entire counter's shards into a single shard or zero, and it's ambiguous if
// this is even required. Note that if we allow this numShards value to decrease without capturing
// the count from any of the shards that might no longer be used, then we might lose counts from the
// shards that would no longer be factored into the #getCount method.
if (incomingCounter.getNumShards() < counterDataInDatastore.getNumShards())
{
throw new IllegalArgumentException(
"Reducing the number of counter shards is not currently allowed! See https://github.com/instacount/appengine-counter/issues/4 for more details.");
}
counterDataInDatastore.setNumShards(incomingCounter.getNumShards());
// The Exception above disallows any invalid states.
counterDataInDatastore.setCounterStatus(incomingCounter.getCounterStatus());
// Update the CounterDataIndexes
counterDataInDatastore.setIndexes(
incomingCounter.getIndexes() == null ? CounterIndexes.none() : incomingCounter.getIndexes());
// Update the counter in the datastore.
ObjectifyService.ofy().save().entity(counterDataInDatastore).now();
// return null to satisfy Java...
return null;
}
});
} } | public class class_name {
@Override
public void updateCounterDetails(final Counter incomingCounter)
{
Preconditions.checkNotNull(incomingCounter);
// First, assert the counter is in a proper state. If done consistently (i.e., in a TX, then this will function
// as an effective CounterData lock).
// Second, Update the counter details.
ObjectifyService.ofy().transact(new Work<Void>()
{
@Override
public Void run()
{
// First, load the incomingCounter from the datastore via a transactional get to ensure it has the
// proper state.
final Optional<CounterData> optCounterData = getCounterData(incomingCounter.getName());
// //////////////
// ShortCircuit: Can't update a counter that doesn't exist!
// //////////////
if (!optCounterData.isPresent())
{
throw new NoCounterExistsException(incomingCounter.getName());
}
final CounterData counterDataInDatastore = optCounterData.get();
// Make sure the stored counter is currently in an updatable state!
assertCounterDetailsMutatable(incomingCounter.getName(), counterDataInDatastore.getCounterStatus());
// Make sure the incoming counter status is a validly settable status
assertValidExternalCounterStatus(incomingCounter.getName(), incomingCounter.getCounterStatus());
// NOTE: READ_ONLY_COUNT status means the count can't be incremented/decremented. However, it's details
// can still be mutated.
// NOTE: The counterName/counterId may not change!
// Update the Description
counterDataInDatastore.setDescription(incomingCounter.getDescription());
// Update the numShards. Aside from setting this value, nothing explicitly needs to happen in the
// datastore since shards will be created when a counter in incremented (if the shard doesn't already
// exist). However, if the number of shards is being reduced, then throw an exception since this
// requires counter shard reduction and some extra thinking. We can't allow the shard-count to go down
// unless we collapse the entire counter's shards into a single shard or zero, and it's ambiguous if
// this is even required. Note that if we allow this numShards value to decrease without capturing
// the count from any of the shards that might no longer be used, then we might lose counts from the
// shards that would no longer be factored into the #getCount method.
if (incomingCounter.getNumShards() < counterDataInDatastore.getNumShards())
{
throw new IllegalArgumentException(
"Reducing the number of counter shards is not currently allowed! See https://github.com/instacount/appengine-counter/issues/4 for more details.");
}
counterDataInDatastore.setNumShards(incomingCounter.getNumShards());
// The Exception above disallows any invalid states.
counterDataInDatastore.setCounterStatus(incomingCounter.getCounterStatus()); // depends on control dependency: [if], data = [none]
// Update the CounterDataIndexes
counterDataInDatastore.setIndexes(
incomingCounter.getIndexes() == null ? CounterIndexes.none() : incomingCounter.getIndexes()); // depends on control dependency: [if], data = [none]
// Update the counter in the datastore.
ObjectifyService.ofy().save().entity(counterDataInDatastore).now(); // depends on control dependency: [if], data = [none]
// return null to satisfy Java...
return null; // depends on control dependency: [if], data = [none]
}
});
} } |
public class class_name {
public Date setStartDate(Date time)
{
try {
this.getTable().edit();
this.getField("StartDateTime").setData(time);
this.getTable().set(this);
this.getTable().seek(null); // Read this record
} catch (Exception ex) {
ex.printStackTrace();
}
return this.getStartDate();
} } | public class class_name {
public Date setStartDate(Date time)
{
try {
this.getTable().edit(); // depends on control dependency: [try], data = [none]
this.getField("StartDateTime").setData(time); // depends on control dependency: [try], data = [none]
this.getTable().set(this); // depends on control dependency: [try], data = [none]
this.getTable().seek(null); // Read this record // depends on control dependency: [try], data = [none]
} catch (Exception ex) {
ex.printStackTrace();
} // depends on control dependency: [catch], data = [none]
return this.getStartDate();
} } |
public class class_name {
protected String properties(TQProperty<?>... props) {
StringBuilder selectProps = new StringBuilder(50);
for (int i = 0; i < props.length; i++) {
if (i > 0) {
selectProps.append(",");
}
selectProps.append(props[i].propertyName());
}
return selectProps.toString();
} } | public class class_name {
protected String properties(TQProperty<?>... props) {
StringBuilder selectProps = new StringBuilder(50);
for (int i = 0; i < props.length; i++) {
if (i > 0) {
selectProps.append(","); // depends on control dependency: [if], data = [none]
}
selectProps.append(props[i].propertyName()); // depends on control dependency: [for], data = [i]
}
return selectProps.toString();
} } |
public class class_name {
public String getJsonOrgUnitList() {
List<CmsOrganizationalUnit> allOus = getOus();
List<JSONObject> jsonOus = new ArrayList<JSONObject>(allOus.size());
int index = 0;
for (CmsOrganizationalUnit ou : allOus) {
JSONObject jsonObj = new JSONObject();
try {
// 1: OU fully qualified name
jsonObj.put("name", ou.getName());
// 2: OU display name
jsonObj.put("displayname", ou.getDisplayName(m_locale));
// 3: OU simple name
jsonObj.put("simplename", ou.getSimpleName());
// 4: OU description
jsonObj.put("description", ou.getDescription(m_locale));
// 5: selection flag
boolean isSelected = false;
if (ou.getName().equals(m_oufqn)
|| (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_oufqn)
&& ou.getName().equals(m_oufqn.substring(1)))) {
isSelected = true;
}
jsonObj.put("active", isSelected);
// 6: level of the OU
jsonObj.put("level", CmsResource.getPathLevel(ou.getName()));
// 7: OU index
jsonObj.put("index", index);
// add the generated JSON object to the result list
jsonOus.add(jsonObj);
index++;
} catch (JSONException e) {
// error creating JSON object, skip this OU
}
}
// generate a JSON array from the JSON object list
JSONArray jsonArr = new JSONArray(jsonOus);
return jsonArr.toString();
} } | public class class_name {
public String getJsonOrgUnitList() {
List<CmsOrganizationalUnit> allOus = getOus();
List<JSONObject> jsonOus = new ArrayList<JSONObject>(allOus.size());
int index = 0;
for (CmsOrganizationalUnit ou : allOus) {
JSONObject jsonObj = new JSONObject();
try {
// 1: OU fully qualified name
jsonObj.put("name", ou.getName()); // depends on control dependency: [try], data = [none]
// 2: OU display name
jsonObj.put("displayname", ou.getDisplayName(m_locale)); // depends on control dependency: [try], data = [none]
// 3: OU simple name
jsonObj.put("simplename", ou.getSimpleName()); // depends on control dependency: [try], data = [none]
// 4: OU description
jsonObj.put("description", ou.getDescription(m_locale)); // depends on control dependency: [try], data = [none]
// 5: selection flag
boolean isSelected = false;
if (ou.getName().equals(m_oufqn)
|| (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_oufqn)
&& ou.getName().equals(m_oufqn.substring(1)))) {
isSelected = true; // depends on control dependency: [if], data = [none]
}
jsonObj.put("active", isSelected); // depends on control dependency: [try], data = [none]
// 6: level of the OU
jsonObj.put("level", CmsResource.getPathLevel(ou.getName())); // depends on control dependency: [try], data = [none]
// 7: OU index
jsonObj.put("index", index); // depends on control dependency: [try], data = [none]
// add the generated JSON object to the result list
jsonOus.add(jsonObj); // depends on control dependency: [try], data = [none]
index++; // depends on control dependency: [try], data = [none]
} catch (JSONException e) {
// error creating JSON object, skip this OU
} // depends on control dependency: [catch], data = [none]
}
// generate a JSON array from the JSON object list
JSONArray jsonArr = new JSONArray(jsonOus);
return jsonArr.toString();
} } |
public class class_name {
public static String unescapeHtml(String s) {
int amp = s.indexOf('&');
if (amp < 0) { // Fast path.
return s;
}
int n = s.length();
StringBuilder sb = new StringBuilder(n);
int pos = 0;
do {
// All numeric entities and all named entities can be represented in less than 12 chars, so
// avoid any O(n**2) problem on "&&&&&&&&&" by not looking for ; more than 12 chars out.
int end = -1;
int entityLimit = Math.min(n, amp + 12);
for (int i = amp + 1; i < entityLimit; ++i) {
if (s.charAt(i) == ';') {
end = i + 1;
break;
}
}
int cp = -1;
if (end == -1) {
cp = -1;
} else {
if (s.charAt(amp + 1) == '#') { // Decode a numeric entity
char ch = s.charAt(amp + 2);
try {
if (ch == 'x' || ch == 'X') { // hex
// & # x A B C D ;
// ^ ^ ^ ^ ^
// amp + 0 1 2 3 end - 1
cp = Integer.parseInt(s.substring(amp + 3, end - 1), 16);
} else { // decimal
// & # 1 6 0 ;
// ^ ^ ^ ^
// amp + 0 1 2 end - 1
cp = Integer.parseInt(s.substring(amp + 2, end - 1), 10);
}
} catch (NumberFormatException ex) {
cp = -1; // Malformed numeric entity
}
} else {
// & q u o t ;
// ^ ^
// amp end
Integer cpI = HTML_ENTITY_TO_CODEPOINT.get(s.substring(amp, end));
cp = cpI != null ? cpI.intValue() : -1;
}
}
if (cp == -1) { // Don't decode
end = amp + 1;
} else {
sb.append(s, pos, amp);
sb.appendCodePoint(cp);
pos = end;
}
amp = s.indexOf('&', end);
} while (amp >= 0);
return sb.append(s, pos, n).toString();
} } | public class class_name {
public static String unescapeHtml(String s) {
int amp = s.indexOf('&');
if (amp < 0) { // Fast path.
return s; // depends on control dependency: [if], data = [none]
}
int n = s.length();
StringBuilder sb = new StringBuilder(n);
int pos = 0;
do {
// All numeric entities and all named entities can be represented in less than 12 chars, so
// avoid any O(n**2) problem on "&&&&&&&&&" by not looking for ; more than 12 chars out.
int end = -1;
int entityLimit = Math.min(n, amp + 12);
for (int i = amp + 1; i < entityLimit; ++i) {
if (s.charAt(i) == ';') {
end = i + 1; // depends on control dependency: [if], data = [none]
break;
}
}
int cp = -1;
if (end == -1) {
cp = -1; // depends on control dependency: [if], data = [none]
} else {
if (s.charAt(amp + 1) == '#') { // Decode a numeric entity
char ch = s.charAt(amp + 2);
try {
if (ch == 'x' || ch == 'X') { // hex
// & # x A B C D ;
// ^ ^ ^ ^ ^
// amp + 0 1 2 3 end - 1
cp = Integer.parseInt(s.substring(amp + 3, end - 1), 16); // depends on control dependency: [if], data = [none]
} else { // decimal
// & # 1 6 0 ;
// ^ ^ ^ ^
// amp + 0 1 2 end - 1
cp = Integer.parseInt(s.substring(amp + 2, end - 1), 10); // depends on control dependency: [if], data = [none]
}
} catch (NumberFormatException ex) {
cp = -1; // Malformed numeric entity
} // depends on control dependency: [catch], data = [none]
} else {
// & q u o t ;
// ^ ^
// amp end
Integer cpI = HTML_ENTITY_TO_CODEPOINT.get(s.substring(amp, end));
cp = cpI != null ? cpI.intValue() : -1; // depends on control dependency: [if], data = [none]
}
}
if (cp == -1) { // Don't decode
end = amp + 1; // depends on control dependency: [if], data = [none]
} else {
sb.append(s, pos, amp); // depends on control dependency: [if], data = [none]
sb.appendCodePoint(cp); // depends on control dependency: [if], data = [(cp]
pos = end; // depends on control dependency: [if], data = [none]
}
amp = s.indexOf('&', end);
} while (amp >= 0);
return sb.append(s, pos, n).toString();
} } |
public class class_name {
@OverrideOnDemand
protected boolean isLogRequest (@Nonnull final HttpServletRequest aHttpRequest,
@Nonnull final HttpServletResponse aHttpResponse)
{
boolean bLog = isGloballyEnabled () && m_aLogger.isInfoEnabled ();
if (bLog)
{
// Check for excluded path
final String sRequestURI = ServletHelper.getRequestRequestURI (aHttpRequest);
for (final String sExcludedPath : m_aExcludedPaths)
if (sRequestURI.startsWith (sExcludedPath))
{
bLog = false;
break;
}
}
return bLog;
} } | public class class_name {
@OverrideOnDemand
protected boolean isLogRequest (@Nonnull final HttpServletRequest aHttpRequest,
@Nonnull final HttpServletResponse aHttpResponse)
{
boolean bLog = isGloballyEnabled () && m_aLogger.isInfoEnabled ();
if (bLog)
{
// Check for excluded path
final String sRequestURI = ServletHelper.getRequestRequestURI (aHttpRequest);
for (final String sExcludedPath : m_aExcludedPaths)
if (sRequestURI.startsWith (sExcludedPath))
{
bLog = false; // depends on control dependency: [if], data = [none]
break;
}
}
return bLog;
} } |
public class class_name {
public ITimer createInvalidator() {
if (_smc.getUseSeparateSessionInvalidatorThreadPool()){
//START PM74718
SessionInvalidatorWithThreadPool invalidator = new SessionInvalidatorWithThreadPool();
invalidator.setDelay(_smc.getDelayForInvalidationAlarmDuringServerStartup());
//END PM74718
return invalidator;
}
else{
SessionInvalidator invalidator = new SessionInvalidator();
invalidator.setDelay(_smc.getDelayForInvalidationAlarmDuringServerStartup());
return invalidator;
}
} } | public class class_name {
public ITimer createInvalidator() {
if (_smc.getUseSeparateSessionInvalidatorThreadPool()){
//START PM74718
SessionInvalidatorWithThreadPool invalidator = new SessionInvalidatorWithThreadPool();
invalidator.setDelay(_smc.getDelayForInvalidationAlarmDuringServerStartup()); // depends on control dependency: [if], data = [none]
//END PM74718
return invalidator; // depends on control dependency: [if], data = [none]
}
else{
SessionInvalidator invalidator = new SessionInvalidator();
invalidator.setDelay(_smc.getDelayForInvalidationAlarmDuringServerStartup()); // depends on control dependency: [if], data = [none]
return invalidator; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private int followVar(char[] array, int currentIndex, boolean fullSyntax, VelocityParserContext context)
{
int i = currentIndex;
while (i < array.length) {
if (fullSyntax && array[i] == '}') {
++i;
break;
} else if (array[i] == '.') {
try {
i = getMethodOrProperty(array, i, null, context);
} catch (InvalidVelocityException e) {
LOGGER.debug("Not a valid method at char [{}]", i, e);
break;
}
} else if (array[i] == '[') {
i = getTableElement(array, i, null, context);
break;
} else {
break;
}
}
return i;
} } | public class class_name {
private int followVar(char[] array, int currentIndex, boolean fullSyntax, VelocityParserContext context)
{
int i = currentIndex;
while (i < array.length) {
if (fullSyntax && array[i] == '}') {
++i; // depends on control dependency: [if], data = [none]
break;
} else if (array[i] == '.') {
try {
i = getMethodOrProperty(array, i, null, context); // depends on control dependency: [try], data = [none]
} catch (InvalidVelocityException e) {
LOGGER.debug("Not a valid method at char [{}]", i, e);
break;
} // depends on control dependency: [catch], data = [none]
} else if (array[i] == '[') {
i = getTableElement(array, i, null, context); // depends on control dependency: [if], data = [none]
break;
} else {
break;
}
}
return i;
} } |
public class class_name {
public void onWorkspaceRemove(String workspaceName)
{
long dataSize;
try
{
dataSize = quotaPersister.getWorkspaceDataSize(rName, workspaceName);
}
catch (UnknownDataSizeException e)
{
return;
}
ChangesItem changesItem = new ChangesItem();
changesItem.updateWorkspaceChangedSize(-dataSize);
WorkspaceQuotaContext context =
new WorkspaceQuotaContext(workspaceName, rName, null, null, null, null, quotaPersister, null, null);
Runnable task = new ApplyPersistedChangesTask(context, changesItem);
task.run();
quotaPersister.setWorkspaceDataSize(rName, workspaceName, dataSize); // workaround
} } | public class class_name {
public void onWorkspaceRemove(String workspaceName)
{
long dataSize;
try
{
dataSize = quotaPersister.getWorkspaceDataSize(rName, workspaceName); // depends on control dependency: [try], data = [none]
}
catch (UnknownDataSizeException e)
{
return;
} // depends on control dependency: [catch], data = [none]
ChangesItem changesItem = new ChangesItem();
changesItem.updateWorkspaceChangedSize(-dataSize);
WorkspaceQuotaContext context =
new WorkspaceQuotaContext(workspaceName, rName, null, null, null, null, quotaPersister, null, null);
Runnable task = new ApplyPersistedChangesTask(context, changesItem);
task.run();
quotaPersister.setWorkspaceDataSize(rName, workspaceName, dataSize); // workaround
} } |
public class class_name {
public EnvironmentConfig setEnvMonitorTxnsExpirationTimeout(final int timeout) {
if (timeout != 0 && timeout < 1000) {
throw new InvalidSettingException("Transaction timeout should be greater than a second");
}
setSetting(ENV_MONITOR_TXNS_EXPIRATION_TIMEOUT, timeout);
if (timeout > 0 && timeout < getEnvMonitorTxnsCheckFreq()) {
setEnvMonitorTxnsCheckFreq(timeout);
}
return this;
} } | public class class_name {
public EnvironmentConfig setEnvMonitorTxnsExpirationTimeout(final int timeout) {
if (timeout != 0 && timeout < 1000) {
throw new InvalidSettingException("Transaction timeout should be greater than a second");
}
setSetting(ENV_MONITOR_TXNS_EXPIRATION_TIMEOUT, timeout);
if (timeout > 0 && timeout < getEnvMonitorTxnsCheckFreq()) {
setEnvMonitorTxnsCheckFreq(timeout); // depends on control dependency: [if], data = [(timeout]
}
return this;
} } |
public class class_name {
private Project findProjectInDirectory(Resource<?> target, ProjectProvider projectProvider,
Predicate<Project> filter)
{
Project result = null;
Imported<ProjectCache> caches = getCaches();
if (projectProvider.containsProject(target))
{
boolean cached = false;
for (ProjectCache cache : caches)
{
result = cache.get(target);
if (result != null && !filter.accept(result))
{
result = null;
}
if (result != null)
{
cached = true;
break;
}
}
if (result == null)
{
result = projectProvider.createProject(target);
}
if (result != null && !filter.accept(result))
{
result = null;
}
if (result != null && !cached)
{
registerAvailableFacets(result);
cacheProject(result);
}
}
return result;
} } | public class class_name {
private Project findProjectInDirectory(Resource<?> target, ProjectProvider projectProvider,
Predicate<Project> filter)
{
Project result = null;
Imported<ProjectCache> caches = getCaches();
if (projectProvider.containsProject(target))
{
boolean cached = false;
for (ProjectCache cache : caches)
{
result = cache.get(target); // depends on control dependency: [for], data = [cache]
if (result != null && !filter.accept(result))
{
result = null; // depends on control dependency: [if], data = [none]
}
if (result != null)
{
cached = true; // depends on control dependency: [if], data = [none]
break;
}
}
if (result == null)
{
result = projectProvider.createProject(target); // depends on control dependency: [if], data = [none]
}
if (result != null && !filter.accept(result))
{
result = null; // depends on control dependency: [if], data = [none]
}
if (result != null && !cached)
{
registerAvailableFacets(result); // depends on control dependency: [if], data = [(result]
cacheProject(result); // depends on control dependency: [if], data = [(result]
}
}
return result;
} } |
public class class_name {
public static void shuffle(Object[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length) {
throw new IndexOutOfBoundsException("Illegal subarray range");
}
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi - i + 1); // between i and hi
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
} } | public class class_name {
public static void shuffle(Object[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length) {
throw new IndexOutOfBoundsException("Illegal subarray range");
}
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi - i + 1); // between i and hi
Object temp = a[i];
a[i] = a[r]; // depends on control dependency: [for], data = [i]
a[r] = temp; // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
private Belief getResultAtIndex(Set<Belief> results, int index) {
Belief belief = null;
if (!(results == null || index < 0 || index >= results.size())) {
int idx = 0;
for (Belief b : results) {
if (idx == index) {
belief = b;
break;
}
idx++;
}
}
return belief;
} } | public class class_name {
private Belief getResultAtIndex(Set<Belief> results, int index) {
Belief belief = null;
if (!(results == null || index < 0 || index >= results.size())) {
int idx = 0;
for (Belief b : results) {
if (idx == index) {
belief = b; // depends on control dependency: [if], data = [none]
break;
}
idx++; // depends on control dependency: [for], data = [none]
}
}
return belief;
} } |
public class class_name {
public MockResponse handleGet(String path) {
MockResponse response = new MockResponse();
List<String> items = new ArrayList<>();
AttributeSet query = attributeExtractor.extract(path);
for (Map.Entry<AttributeSet, String> entry : map.entrySet()) {
if (entry.getKey().matches(query)) {
LOGGER.debug("Entry found for query {} : {}", query, entry);
items.add(entry.getValue());
}
}
if (query.containsKey(KubernetesAttributesExtractor.NAME)) {
if (!items.isEmpty()) {
response.setBody(items.get(0));
response.setResponseCode(200);
} else {
response.setResponseCode(404);
}
} else {
response.setBody(responseComposer.compose(items));
response.setResponseCode(200);
}
return response;
} } | public class class_name {
public MockResponse handleGet(String path) {
MockResponse response = new MockResponse();
List<String> items = new ArrayList<>();
AttributeSet query = attributeExtractor.extract(path);
for (Map.Entry<AttributeSet, String> entry : map.entrySet()) {
if (entry.getKey().matches(query)) {
LOGGER.debug("Entry found for query {} : {}", query, entry); // depends on control dependency: [if], data = [none]
items.add(entry.getValue()); // depends on control dependency: [if], data = [none]
}
}
if (query.containsKey(KubernetesAttributesExtractor.NAME)) {
if (!items.isEmpty()) {
response.setBody(items.get(0)); // depends on control dependency: [if], data = [none]
response.setResponseCode(200); // depends on control dependency: [if], data = [none]
} else {
response.setResponseCode(404); // depends on control dependency: [if], data = [none]
}
} else {
response.setBody(responseComposer.compose(items)); // depends on control dependency: [if], data = [none]
response.setResponseCode(200); // depends on control dependency: [if], data = [none]
}
return response;
} } |
public class class_name {
protected Map<ByteBuffer, AbstractType> getValidatorMap(CfDef cfDef) throws IOException
{
Map<ByteBuffer, AbstractType> validators = new HashMap<ByteBuffer, AbstractType>();
for (ColumnDef cd : cfDef.getColumn_metadata())
{
if (cd.getValidation_class() != null && !cd.getValidation_class().isEmpty())
{
AbstractType validator = null;
try
{
validator = TypeParser.parse(cd.getValidation_class());
if (validator instanceof CounterColumnType)
validator = LongType.instance;
validators.put(cd.name, validator);
}
catch (ConfigurationException e)
{
throw new IOException(e);
}
catch (SyntaxException e)
{
throw new IOException(e);
}
}
}
return validators;
} } | public class class_name {
protected Map<ByteBuffer, AbstractType> getValidatorMap(CfDef cfDef) throws IOException
{
Map<ByteBuffer, AbstractType> validators = new HashMap<ByteBuffer, AbstractType>();
for (ColumnDef cd : cfDef.getColumn_metadata())
{
if (cd.getValidation_class() != null && !cd.getValidation_class().isEmpty())
{
AbstractType validator = null;
try
{
validator = TypeParser.parse(cd.getValidation_class()); // depends on control dependency: [try], data = [none]
if (validator instanceof CounterColumnType)
validator = LongType.instance;
validators.put(cd.name, validator); // depends on control dependency: [try], data = [none]
}
catch (ConfigurationException e)
{
throw new IOException(e);
} // depends on control dependency: [catch], data = [none]
catch (SyntaxException e)
{
throw new IOException(e);
} // depends on control dependency: [catch], data = [none]
}
}
return validators;
} } |
public class class_name {
@Override
public JSONObject toJsonObject() throws JSONException
{
JSONObject returnVal = super.toJsonObject();
//Sum Decimals...
if(this.getSumDecimals() != null)
{
returnVal.put(JSONMapping.SUM_DECIMALS, this.getSumDecimals());
}
//Table Field Records...
if(this.getTableRecords() != null && !this.getTableRecords().isEmpty())
{
JSONArray assoFormsArr = new JSONArray();
for(Form toAdd :this.getTableRecords())
{
assoFormsArr.put(toAdd.toJsonObject());
}
returnVal.put(JSONMapping.TABLE_RECORDS, assoFormsArr);
}
return returnVal;
} } | public class class_name {
@Override
public JSONObject toJsonObject() throws JSONException
{
JSONObject returnVal = super.toJsonObject();
//Sum Decimals...
if(this.getSumDecimals() != null)
{
returnVal.put(JSONMapping.SUM_DECIMALS, this.getSumDecimals());
}
//Table Field Records...
if(this.getTableRecords() != null && !this.getTableRecords().isEmpty())
{
JSONArray assoFormsArr = new JSONArray();
for(Form toAdd :this.getTableRecords())
{
assoFormsArr.put(toAdd.toJsonObject()); // depends on control dependency: [for], data = [toAdd]
}
returnVal.put(JSONMapping.TABLE_RECORDS, assoFormsArr);
}
return returnVal;
} } |
public class class_name {
@Override
public void update(IEntityLock lock, Date newExpiration, Integer newLockType)
throws LockingException {
Connection conn = null;
try {
conn = RDBMServices.getConnection();
if (newLockType != null) {
primDeleteExpired(new Date(), lock.getEntityType(), lock.getEntityKey(), conn);
}
primUpdate(lock, newExpiration, newLockType, conn);
} catch (SQLException sqle) {
throw new LockingException("Problem updating " + lock, sqle);
} finally {
RDBMServices.releaseConnection(conn);
}
} } | public class class_name {
@Override
public void update(IEntityLock lock, Date newExpiration, Integer newLockType)
throws LockingException {
Connection conn = null;
try {
conn = RDBMServices.getConnection();
if (newLockType != null) {
primDeleteExpired(new Date(), lock.getEntityType(), lock.getEntityKey(), conn); // depends on control dependency: [if], data = [none]
}
primUpdate(lock, newExpiration, newLockType, conn);
} catch (SQLException sqle) {
throw new LockingException("Problem updating " + lock, sqle);
} finally {
RDBMServices.releaseConnection(conn);
}
} } |
public class class_name {
public final BatchRequest batch(HttpRequestInitializer httpRequestInitializer) {
BatchRequest batch =
new BatchRequest(getRequestFactory().getTransport(), httpRequestInitializer);
if (Strings.isNullOrEmpty(batchPath)) {
batch.setBatchUrl(new GenericUrl(getRootUrl() + "batch"));
} else {
batch.setBatchUrl(new GenericUrl(getRootUrl() + batchPath));
}
return batch;
} } | public class class_name {
public final BatchRequest batch(HttpRequestInitializer httpRequestInitializer) {
BatchRequest batch =
new BatchRequest(getRequestFactory().getTransport(), httpRequestInitializer);
if (Strings.isNullOrEmpty(batchPath)) {
batch.setBatchUrl(new GenericUrl(getRootUrl() + "batch")); // depends on control dependency: [if], data = [none]
} else {
batch.setBatchUrl(new GenericUrl(getRootUrl() + batchPath)); // depends on control dependency: [if], data = [none]
}
return batch;
} } |
public class class_name {
public void setProductArn(java.util.Collection<StringFilter> productArn) {
if (productArn == null) {
this.productArn = null;
return;
}
this.productArn = new java.util.ArrayList<StringFilter>(productArn);
} } | public class class_name {
public void setProductArn(java.util.Collection<StringFilter> productArn) {
if (productArn == null) {
this.productArn = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.productArn = new java.util.ArrayList<StringFilter>(productArn);
} } |
public class class_name {
private void loadLanguageInfo() {
// load coarse map
coarseMap = new HashMap<>();
try {
try (BufferedReader br = new BufferedReader(new FileReader(options.unimapFile))) {
String str;
while ((str = br.readLine()) != null) {
String[] data = str.split("\\s+");
coarseMap.put(data[0], data[1]);
}
}
coarseMap.put("<root-POS>", "ROOT");
} catch (Exception e) {
logger.warn("Couldn't find coarse POS map for this language");
}
// fill conj word
conjWord = new HashSet<>();
conjWord.add("and");
conjWord.add("or");
} } | public class class_name {
private void loadLanguageInfo() {
// load coarse map
coarseMap = new HashMap<>();
try {
try (BufferedReader br = new BufferedReader(new FileReader(options.unimapFile))) {
String str;
while ((str = br.readLine()) != null) {
String[] data = str.split("\\s+");
coarseMap.put(data[0], data[1]); // depends on control dependency: [while], data = [none]
}
}
coarseMap.put("<root-POS>", "ROOT");
} catch (Exception e) {
logger.warn("Couldn't find coarse POS map for this language");
} // depends on control dependency: [catch], data = [none]
// fill conj word
conjWord = new HashSet<>();
conjWord.add("and");
conjWord.add("or");
} } |
public class class_name {
public void setHeader(String name, String value)
{
boolean found = false;
if ((name == null) || name.equals(""))
throw new IllegalArgumentException("Illegal MimeHeader name");
for(int i = 0; i < headers.size(); i++) {
MimeHeader hdr = (MimeHeader) headers.elementAt(i);
if (hdr.getName().equalsIgnoreCase(name)) {
if (!found) {
headers.setElementAt(new MimeHeader(hdr.getName(),
value), i);
found = true;
}
else
headers.removeElementAt(i--);
}
}
if (!found)
addHeader(name, value);
} } | public class class_name {
public void setHeader(String name, String value)
{
boolean found = false;
if ((name == null) || name.equals(""))
throw new IllegalArgumentException("Illegal MimeHeader name");
for(int i = 0; i < headers.size(); i++) {
MimeHeader hdr = (MimeHeader) headers.elementAt(i);
if (hdr.getName().equalsIgnoreCase(name)) {
if (!found) {
headers.setElementAt(new MimeHeader(hdr.getName(),
value), i); // depends on control dependency: [if], data = [none]
found = true; // depends on control dependency: [if], data = [none]
}
else
headers.removeElementAt(i--);
}
}
if (!found)
addHeader(name, value);
} } |
public class class_name {
protected void processRemainingReferences(APMSpanBuilder builder, Reference primaryRef) {
// Check if other references
for (Reference ref : builder.references) {
if (primaryRef == ref) {
continue;
}
// Setup correlation ids for other references
if (ref.getReferredTo() instanceof APMSpan) {
APMSpan referenced = (APMSpan) ref.getReferredTo();
String nodeId = referenced.getNodePath();
getNodeBuilder().addCorrelationId(new CorrelationIdentifier(Scope.CausedBy, nodeId));
} else if (ref.getReferredTo() instanceof APMSpanBuilder
&& ((APMSpanBuilder) ref.getReferredTo()).state().containsKey(Constants.HAWKULAR_APM_ID)) {
getNodeBuilder().addCorrelationId(new CorrelationIdentifier(Scope.Interaction,
((APMSpanBuilder) ref.getReferredTo()).state().get(Constants.HAWKULAR_APM_ID).toString()));
}
}
} } | public class class_name {
protected void processRemainingReferences(APMSpanBuilder builder, Reference primaryRef) {
// Check if other references
for (Reference ref : builder.references) {
if (primaryRef == ref) {
continue;
}
// Setup correlation ids for other references
if (ref.getReferredTo() instanceof APMSpan) {
APMSpan referenced = (APMSpan) ref.getReferredTo();
String nodeId = referenced.getNodePath();
getNodeBuilder().addCorrelationId(new CorrelationIdentifier(Scope.CausedBy, nodeId)); // depends on control dependency: [if], data = [none]
} else if (ref.getReferredTo() instanceof APMSpanBuilder
&& ((APMSpanBuilder) ref.getReferredTo()).state().containsKey(Constants.HAWKULAR_APM_ID)) {
getNodeBuilder().addCorrelationId(new CorrelationIdentifier(Scope.Interaction,
((APMSpanBuilder) ref.getReferredTo()).state().get(Constants.HAWKULAR_APM_ID).toString())); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public void listDirectory(TreeParent node,
IElementCollector collector,
IProgressMonitor monitor) {
monitor.beginTask(Messages.getString("pending"), 1); //$NON-NLS-1$
monitor.worked(1);
GuvnorRepository rep = node.getGuvnorRepository();
try {
IWebDavClient webdav = WebDavServerCache.getWebDavClient(rep.getLocation());
if (webdav == null) {
webdav = WebDavClientFactory.createClient(new URL(rep.getLocation()));
WebDavServerCache.cacheWebDavClient(rep.getLocation(), webdav);
}
Map<String, ResourceProperties> listing = null;
try {
listing = webdav.listDirectory(node.getFullPath());
} catch (WebDavException wde) {
if (wde.getErrorCode() != IResponse.SC_UNAUTHORIZED) {
// If not an authentication failure, we don't know what to do with it
throw wde;
}
boolean retry = PlatformUtils.getInstance().authenticateForServer(
node.getGuvnorRepository().getLocation(), webdav);
if (retry) {
listing = webdav.listDirectory(node.getFullPath());
}
}
if (listing != null) {
for (String s: listing.keySet()) {
ResourceProperties resProps = listing.get(s);
TreeObject o = null;
if (resProps.isDirectory()) {
Type childType;
switch (getNodeType()) {
case REPOSITORY:
if (s.startsWith("snapshot")) {
childType = Type.SNAPSHOTS;
} else if (s.startsWith("packages")) {
childType = Type.PACKAGES;
} else if (s.startsWith("globalarea")) {
childType = Type.GLOBALS;
} else {
childType = Type.PACKAGE;
}
break;
case SNAPSHOTS:
childType = Type.SNAPSHOT_PACKAGE;
break;
case SNAPSHOT_PACKAGE:
childType = Type.SNAPSHOT;
break;
default:
childType = Type.PACKAGE;
}
o = new TreeParent(s, childType);
} else {
o = new TreeObject(s, Type.RESOURCE);
}
o.setGuvnorRepository(rep);
o.setResourceProps(resProps);
node.addChild(o);
collector.add(o, monitor);
}
}
monitor.worked(1);
} catch (WebDavException e) {
if (e.getErrorCode() == IResponse.SC_UNAUTHORIZED) {
PlatformUtils.reportAuthenticationFailure();
} else {
if (e.getErrorCode() == IResponse.SC_NOT_IMPLEMENTED) {
Activator.getDefault().displayMessage(IStatus.ERROR,
Messages.getString("rep.connect.fail")); //$NON-NLS-1$
} else {
Activator.getDefault().displayError(IStatus.ERROR, e.getMessage(), e, true);
}
}
} catch (ConnectException ce) {
Activator.getDefault().
displayMessage(IStatus.ERROR,
Messages.getString("rep.connect.fail")); //$NON-NLS-1$
} catch (Exception e) {
Activator.getDefault().displayError(IStatus.ERROR, e.getMessage(), e, true);
}
} } | public class class_name {
public void listDirectory(TreeParent node,
IElementCollector collector,
IProgressMonitor monitor) {
monitor.beginTask(Messages.getString("pending"), 1); //$NON-NLS-1$
monitor.worked(1);
GuvnorRepository rep = node.getGuvnorRepository();
try {
IWebDavClient webdav = WebDavServerCache.getWebDavClient(rep.getLocation());
if (webdav == null) {
webdav = WebDavClientFactory.createClient(new URL(rep.getLocation())); // depends on control dependency: [if], data = [none]
WebDavServerCache.cacheWebDavClient(rep.getLocation(), webdav); // depends on control dependency: [if], data = [none]
}
Map<String, ResourceProperties> listing = null;
try {
listing = webdav.listDirectory(node.getFullPath()); // depends on control dependency: [try], data = [none]
} catch (WebDavException wde) {
if (wde.getErrorCode() != IResponse.SC_UNAUTHORIZED) {
// If not an authentication failure, we don't know what to do with it
throw wde;
}
boolean retry = PlatformUtils.getInstance().authenticateForServer(
node.getGuvnorRepository().getLocation(), webdav);
if (retry) {
listing = webdav.listDirectory(node.getFullPath()); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
if (listing != null) {
for (String s: listing.keySet()) {
ResourceProperties resProps = listing.get(s);
TreeObject o = null;
if (resProps.isDirectory()) {
Type childType;
switch (getNodeType()) {
case REPOSITORY:
if (s.startsWith("snapshot")) {
childType = Type.SNAPSHOTS; // depends on control dependency: [if], data = [none]
} else if (s.startsWith("packages")) {
childType = Type.PACKAGES; // depends on control dependency: [if], data = [none]
} else if (s.startsWith("globalarea")) {
childType = Type.GLOBALS; // depends on control dependency: [if], data = [none]
} else {
childType = Type.PACKAGE; // depends on control dependency: [if], data = [none]
}
break;
case SNAPSHOTS:
childType = Type.SNAPSHOT_PACKAGE;
break;
case SNAPSHOT_PACKAGE:
childType = Type.SNAPSHOT;
break;
default:
childType = Type.PACKAGE;
}
o = new TreeParent(s, childType); // depends on control dependency: [for], data = [s]
} else { // depends on control dependency: [if], data = [none]
o = new TreeObject(s, Type.RESOURCE);
}
o.setGuvnorRepository(rep); // depends on control dependency: [if], data = [none]
o.setResourceProps(resProps); // depends on control dependency: [if], data = [none]
node.addChild(o); // depends on control dependency: [if], data = [none]
collector.add(o, monitor); // depends on control dependency: [if], data = [none]
}
}
monitor.worked(1);
} catch (WebDavException e) {
if (e.getErrorCode() == IResponse.SC_UNAUTHORIZED) {
PlatformUtils.reportAuthenticationFailure();
} else {
if (e.getErrorCode() == IResponse.SC_NOT_IMPLEMENTED) {
Activator.getDefault().displayMessage(IStatus.ERROR,
Messages.getString("rep.connect.fail")); //$NON-NLS-1$
} else {
Activator.getDefault().displayError(IStatus.ERROR, e.getMessage(), e, true);
}
}
} catch (ConnectException ce) {
Activator.getDefault().
displayMessage(IStatus.ERROR,
Messages.getString("rep.connect.fail")); //$NON-NLS-1$
} catch (Exception e) {
Activator.getDefault().displayError(IStatus.ERROR, e.getMessage(), e, true);
}
} } |
public class class_name {
protected List<Point> simplifyPoints(double simplifyTolerance,
List<Point> points) {
List<Point> simplifiedPoints = null;
if (simplifyGeometries) {
// Reproject to web mercator if not in meters
if (projection != null && !projection.isUnit(Units.METRES)) {
ProjectionTransform toWebMercator = projection
.getTransformation(WEB_MERCATOR_PROJECTION);
points = toWebMercator.transform(points);
}
// Simplify the points
simplifiedPoints = GeometryUtils.simplifyPoints(points,
simplifyTolerance);
// Reproject back to the original projection
if (projection != null && !projection.isUnit(Units.METRES)) {
ProjectionTransform fromWebMercator = WEB_MERCATOR_PROJECTION
.getTransformation(projection);
simplifiedPoints = fromWebMercator.transform(simplifiedPoints);
}
} else {
simplifiedPoints = points;
}
return simplifiedPoints;
} } | public class class_name {
protected List<Point> simplifyPoints(double simplifyTolerance,
List<Point> points) {
List<Point> simplifiedPoints = null;
if (simplifyGeometries) {
// Reproject to web mercator if not in meters
if (projection != null && !projection.isUnit(Units.METRES)) {
ProjectionTransform toWebMercator = projection
.getTransformation(WEB_MERCATOR_PROJECTION);
points = toWebMercator.transform(points); // depends on control dependency: [if], data = [none]
}
// Simplify the points
simplifiedPoints = GeometryUtils.simplifyPoints(points,
simplifyTolerance); // depends on control dependency: [if], data = [none]
// Reproject back to the original projection
if (projection != null && !projection.isUnit(Units.METRES)) {
ProjectionTransform fromWebMercator = WEB_MERCATOR_PROJECTION
.getTransformation(projection);
simplifiedPoints = fromWebMercator.transform(simplifiedPoints); // depends on control dependency: [if], data = [none]
}
} else {
simplifiedPoints = points; // depends on control dependency: [if], data = [none]
}
return simplifiedPoints;
} } |
public class class_name {
protected Exception decryptMessage(boolean async) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "decryptMessage");
}
Exception exception = null;
// Storage for the result of calling the SSL engine
SSLEngineResult result = null;
// Status of the SSL engine.
Status status = null;
// Access output buffer to give to SSL engine. Attempt to use buffers from app channel.
getDecryptedNetworkBuffers();
final int packetSize = getConnLink().getPacketBufferSize();
final int appBufferSize = getConnLink().getAppBufferSize();
try {
while (true) {
// JSSE (as of JDK 6 11/2010) requires at least the packet-size
// of available space in the output buffers or it blindly returns
// the BUFFER_OVERFLOW result
if (appBufferSize > availableDecryptionSpace()) {
expandDecryptedNetBuffer();
}
// Protect JSSE from potential SSL packet sizes that are too big.
int savedLimit = SSLUtils.adjustBufferForJSSE(netBuffer, packetSize);
// These limits will be reset only if the result of the unwrap is
// "OK". Otherwise, they will not be changed. Try to reuse this array.
if ((decryptedNetLimitInfo == null)
|| (decryptedNetLimitInfo.length != decryptedNetBuffers.length)) {
decryptedNetLimitInfo = new int[decryptedNetBuffers.length];
}
SSLUtils.getBufferLimits(decryptedNetBuffers, decryptedNetLimitInfo);
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "before unwrap:\r\n\tnetBuf: "
+ SSLUtils.getBufferTraceInfo(netBuffer)
+ "\r\n\tdecNetBuffers: " + SSLUtils.getBufferTraceInfo(decryptedNetBuffers));
}
// Call the SSL engine to decrypt the request.
result = getConnLink().getSSLEngine().unwrap(
this.netBuffer.getWrappedByteBuffer(),
SSLUtils.getWrappedByteBuffers(decryptedNetBuffers));
if (0 < result.bytesProduced()) {
SSLUtils.flipBuffers(decryptedNetBuffers, result.bytesProduced());
}
status = result.getStatus();
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "after unwrap:\r\n\tnetBuf: "
+ SSLUtils.getBufferTraceInfo(netBuffer)
+ "\r\n\tdecNetBuffers: " + SSLUtils.getBufferTraceInfo(decryptedNetBuffers)
+ "\r\n\tstatus=" + status
+ " HSstatus=" + result.getHandshakeStatus()
+ " consumed=" + result.bytesConsumed()
+ " produced=" + result.bytesProduced());
}
// If a limit modification was saved, restore it.
if (-1 != savedLimit) {
this.netBuffer.limit(savedLimit);
}
// Record the number of bytes produced.
bytesProduced += result.bytesProduced();
// check CLOSED status first, recent JDKs are showing the status=CLOSED
// and hsstatus=NEED_WRAP when receiving the connection closed message
// from the other end. Our call to flushCloseDown() later will handle
// the write of our own 23 bytes of connection closure
if (status == Status.CLOSED) {
exception = sessionClosedException;
break;
}
// Handle the SSL engine result
// Note: check handshake status first as renegotations could be requested
// at any point and the Status is secondary to the handshake status
if ((result.getHandshakeStatus() == HandshakeStatus.NEED_TASK)
|| (result.getHandshakeStatus() == HandshakeStatus.NEED_WRAP)
|| (result.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP)) {
try {
result = doHandshake(async);
} catch (IOException e) {
// no FFDC required
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Caught exception during SSL handshake, " + e);
}
exception = e;
break;
}
// Check to see if handshake was done synchronously.
if (result != null) {
// Handshake was done synchronously. Verify results.
status = result.getStatus();
if (result.getHandshakeStatus() == HandshakeStatus.FINISHED) {
// Handshake finished. Need to read more per original request.
exception = readNeededInternalException;
// No error here. Just inform caller.
break;
} else if (status == Status.OK) {
// Handshake complete and initial request already read and decrypted.
prepareDataForNextChannel();
break;
} else {
// Unknown result from handshake. All other results should have thrown exceptions.
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Unhandled result from SSL engine: " + status);
}
exception = new SSLException("Unhandled result from SSL engine: " + status);
break;
}
}
// Handshake is being handled asynchronously.
break;
}
else if (status == Status.OK) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "OK result from the SSL engine,"
+ " callerReqAlloc=" + getJITAllocateAction()
+ " decNetBuffRelReq=" + decryptedNetBufferReleaseRequired);
}
if (bytesRequested > bytesProduced) {
// More data needs to be decrypted.
// 431992 - only change pos/lim if something was produced
if (0 < result.bytesProduced()) {
// Prepare the output buffer, preventing overwrites and
// opening up space closed by JSSE.
SSLUtils.positionToLimit(decryptedNetBuffers);
// Reset the limits saved for the decryptedNetBuffers.
SSLUtils.setBufferLimits(decryptedNetBuffers, decryptedNetLimitInfo);
}
// Check if all the data has been read from the netBuffers.
if (this.netBuffer.remaining() == 0) {
// No more data available. More must be read. Reused
// exception instance (save new object).
exception = readNeededInternalException;
break;
}
// More data is available. Loop around and decrypt again.
continue;
}
// Data has been decrypted.
break;
}
else if (status == Status.BUFFER_OVERFLOW) {
// The output buffers provided to the SSL engine were not big
// enough. A bigger buffer must be supplied. If we can build
// a bigger buffer and call again, build it. Prepare the output
// buffer, preventing overwrites and opening up space closed by JSSE.
expandDecryptedNetBuffer();
// Try again with the bigger buffer array.
continue;
}
else if (status == Status.BUFFER_UNDERFLOW) {
// The engine was not able to unwrap the incoming data because there were not
// source bytes available to make a complete packet.
// More data needs to be read into the input buffer. Alert
// calling method to keep reading.
exception = readNeededInternalException;
// No error here. Just inform caller.
break;
}
else {
exception = new SSLException("Unknown result from ssl engine not handled yet: " + status);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Unknown result from ssl engine not handled yet: " + status);
}
break;
}
} // end while
} catch (SSLException ssle) {
// no FFDC required
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Caught exception during decryption, " + ssle);
}
exception = ssle;
cleanupDecBuffers();
} catch (Exception up) {
synchronized (closeSync) {
// if close has been called then assume this exception was due to a race condition
// with the close logic and consume the exception without FFDC. Otherwise rethrow
// as the logic did before this change.
if (!closeCalled) {
throw up;
}
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "decryptMessage: " + exception);
}
return exception;
} } | public class class_name {
protected Exception decryptMessage(boolean async) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "decryptMessage"); // depends on control dependency: [if], data = [none]
}
Exception exception = null;
// Storage for the result of calling the SSL engine
SSLEngineResult result = null;
// Status of the SSL engine.
Status status = null;
// Access output buffer to give to SSL engine. Attempt to use buffers from app channel.
getDecryptedNetworkBuffers();
final int packetSize = getConnLink().getPacketBufferSize();
final int appBufferSize = getConnLink().getAppBufferSize();
try {
while (true) {
// JSSE (as of JDK 6 11/2010) requires at least the packet-size
// of available space in the output buffers or it blindly returns
// the BUFFER_OVERFLOW result
if (appBufferSize > availableDecryptionSpace()) {
expandDecryptedNetBuffer(); // depends on control dependency: [if], data = [none]
}
// Protect JSSE from potential SSL packet sizes that are too big.
int savedLimit = SSLUtils.adjustBufferForJSSE(netBuffer, packetSize);
// These limits will be reset only if the result of the unwrap is
// "OK". Otherwise, they will not be changed. Try to reuse this array.
if ((decryptedNetLimitInfo == null)
|| (decryptedNetLimitInfo.length != decryptedNetBuffers.length)) {
decryptedNetLimitInfo = new int[decryptedNetBuffers.length]; // depends on control dependency: [if], data = [none]
}
SSLUtils.getBufferLimits(decryptedNetBuffers, decryptedNetLimitInfo); // depends on control dependency: [while], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "before unwrap:\r\n\tnetBuf: "
+ SSLUtils.getBufferTraceInfo(netBuffer)
+ "\r\n\tdecNetBuffers: " + SSLUtils.getBufferTraceInfo(decryptedNetBuffers)); // depends on control dependency: [if], data = [none]
}
// Call the SSL engine to decrypt the request.
result = getConnLink().getSSLEngine().unwrap(
this.netBuffer.getWrappedByteBuffer(),
SSLUtils.getWrappedByteBuffers(decryptedNetBuffers)); // depends on control dependency: [while], data = [none]
if (0 < result.bytesProduced()) {
SSLUtils.flipBuffers(decryptedNetBuffers, result.bytesProduced()); // depends on control dependency: [if], data = [result.bytesProduced())]
}
status = result.getStatus(); // depends on control dependency: [while], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "after unwrap:\r\n\tnetBuf: "
+ SSLUtils.getBufferTraceInfo(netBuffer)
+ "\r\n\tdecNetBuffers: " + SSLUtils.getBufferTraceInfo(decryptedNetBuffers)
+ "\r\n\tstatus=" + status
+ " HSstatus=" + result.getHandshakeStatus()
+ " consumed=" + result.bytesConsumed()
+ " produced=" + result.bytesProduced()); // depends on control dependency: [if], data = [none]
}
// If a limit modification was saved, restore it.
if (-1 != savedLimit) {
this.netBuffer.limit(savedLimit); // depends on control dependency: [if], data = [savedLimit)]
}
// Record the number of bytes produced.
bytesProduced += result.bytesProduced(); // depends on control dependency: [while], data = [none]
// check CLOSED status first, recent JDKs are showing the status=CLOSED
// and hsstatus=NEED_WRAP when receiving the connection closed message
// from the other end. Our call to flushCloseDown() later will handle
// the write of our own 23 bytes of connection closure
if (status == Status.CLOSED) {
exception = sessionClosedException; // depends on control dependency: [if], data = [none]
break;
}
// Handle the SSL engine result
// Note: check handshake status first as renegotations could be requested
// at any point and the Status is secondary to the handshake status
if ((result.getHandshakeStatus() == HandshakeStatus.NEED_TASK)
|| (result.getHandshakeStatus() == HandshakeStatus.NEED_WRAP)
|| (result.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP)) {
try {
result = doHandshake(async); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
// no FFDC required
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Caught exception during SSL handshake, " + e); // depends on control dependency: [if], data = [none]
}
exception = e;
break;
} // depends on control dependency: [catch], data = [none]
// Check to see if handshake was done synchronously.
if (result != null) {
// Handshake was done synchronously. Verify results.
status = result.getStatus(); // depends on control dependency: [if], data = [none]
if (result.getHandshakeStatus() == HandshakeStatus.FINISHED) {
// Handshake finished. Need to read more per original request.
exception = readNeededInternalException; // depends on control dependency: [if], data = [none]
// No error here. Just inform caller.
break;
} else if (status == Status.OK) {
// Handshake complete and initial request already read and decrypted.
prepareDataForNextChannel(); // depends on control dependency: [if], data = [none]
break;
} else {
// Unknown result from handshake. All other results should have thrown exceptions.
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Unhandled result from SSL engine: " + status); // depends on control dependency: [if], data = [none]
}
exception = new SSLException("Unhandled result from SSL engine: " + status); // depends on control dependency: [if], data = [none]
break;
}
}
// Handshake is being handled asynchronously.
break;
}
else if (status == Status.OK) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "OK result from the SSL engine,"
+ " callerReqAlloc=" + getJITAllocateAction()
+ " decNetBuffRelReq=" + decryptedNetBufferReleaseRequired); // depends on control dependency: [if], data = [none]
}
if (bytesRequested > bytesProduced) {
// More data needs to be decrypted.
// 431992 - only change pos/lim if something was produced
if (0 < result.bytesProduced()) {
// Prepare the output buffer, preventing overwrites and
// opening up space closed by JSSE.
SSLUtils.positionToLimit(decryptedNetBuffers); // depends on control dependency: [if], data = [none]
// Reset the limits saved for the decryptedNetBuffers.
SSLUtils.setBufferLimits(decryptedNetBuffers, decryptedNetLimitInfo); // depends on control dependency: [if], data = [none]
}
// Check if all the data has been read from the netBuffers.
if (this.netBuffer.remaining() == 0) {
// No more data available. More must be read. Reused
// exception instance (save new object).
exception = readNeededInternalException; // depends on control dependency: [if], data = [none]
break;
}
// More data is available. Loop around and decrypt again.
continue;
}
// Data has been decrypted.
break;
}
else if (status == Status.BUFFER_OVERFLOW) {
// The output buffers provided to the SSL engine were not big
// enough. A bigger buffer must be supplied. If we can build
// a bigger buffer and call again, build it. Prepare the output
// buffer, preventing overwrites and opening up space closed by JSSE.
expandDecryptedNetBuffer(); // depends on control dependency: [if], data = [none]
// Try again with the bigger buffer array.
continue;
}
else if (status == Status.BUFFER_UNDERFLOW) {
// The engine was not able to unwrap the incoming data because there were not
// source bytes available to make a complete packet.
// More data needs to be read into the input buffer. Alert
// calling method to keep reading.
exception = readNeededInternalException; // depends on control dependency: [if], data = [none]
// No error here. Just inform caller.
break;
}
else {
exception = new SSLException("Unknown result from ssl engine not handled yet: " + status); // depends on control dependency: [if], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Unknown result from ssl engine not handled yet: " + status); // depends on control dependency: [if], data = [none]
}
break;
}
} // end while
} catch (SSLException ssle) {
// no FFDC required
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Caught exception during decryption, " + ssle); // depends on control dependency: [if], data = [none]
}
exception = ssle;
cleanupDecBuffers();
} catch (Exception up) { // depends on control dependency: [catch], data = [none]
synchronized (closeSync) {
// if close has been called then assume this exception was due to a race condition
// with the close logic and consume the exception without FFDC. Otherwise rethrow
// as the logic did before this change.
if (!closeCalled) {
throw up;
}
}
} // depends on control dependency: [catch], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "decryptMessage: " + exception); // depends on control dependency: [if], data = [none]
}
return exception;
} } |
public class class_name {
public void setVpcEndpoints(java.util.Collection<VpcEndpoint> vpcEndpoints) {
if (vpcEndpoints == null) {
this.vpcEndpoints = null;
return;
}
this.vpcEndpoints = new com.amazonaws.internal.SdkInternalList<VpcEndpoint>(vpcEndpoints);
} } | public class class_name {
public void setVpcEndpoints(java.util.Collection<VpcEndpoint> vpcEndpoints) {
if (vpcEndpoints == null) {
this.vpcEndpoints = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.vpcEndpoints = new com.amazonaws.internal.SdkInternalList<VpcEndpoint>(vpcEndpoints);
} } |
public class class_name {
public String getCharacterEncoding() {
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15
logger.entering(CLASS_NAME,"getCharacterEncoding","["+this+"]");
}
if (_encoding == null) {
setDefaultResponseEncoding();
}
// 311717
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15
logger.exiting(CLASS_NAME,"getCharacterEncoding", " encoding --> " + _encoding);
}
return _encoding;
} } | public class class_name {
public String getCharacterEncoding() {
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15
logger.entering(CLASS_NAME,"getCharacterEncoding","["+this+"]"); // depends on control dependency: [if], data = [none]
}
if (_encoding == null) {
setDefaultResponseEncoding(); // depends on control dependency: [if], data = [none]
}
// 311717
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15
logger.exiting(CLASS_NAME,"getCharacterEncoding", " encoding --> " + _encoding); // depends on control dependency: [if], data = [none]
}
return _encoding;
} } |
public class class_name {
public static Unit getUnitByUnitClass(Class<? extends Unit> unitClass) {
readWriteLock.readLock().lock();
try {
return searchUnitByClass.get(unitClass);
} finally {
readWriteLock.readLock().unlock();
}
} } | public class class_name {
public static Unit getUnitByUnitClass(Class<? extends Unit> unitClass) {
readWriteLock.readLock().lock();
try {
return searchUnitByClass.get(unitClass); // depends on control dependency: [try], data = [none]
} finally {
readWriteLock.readLock().unlock();
}
} } |
public class class_name {
public void setRawParameters(Hashtable params)
{
if (WCCustomProperties.CHECK_REQUEST_OBJECT_IN_USE){
checkRequestObjectInUse();
}
//321485
if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15
logger.logp(Level.FINE, CLASS_NAME,"setRawParameters", "");
}
SRTServletRequestThreadData.getInstance().setParameters(params);
} } | public class class_name {
public void setRawParameters(Hashtable params)
{
if (WCCustomProperties.CHECK_REQUEST_OBJECT_IN_USE){
checkRequestObjectInUse(); // depends on control dependency: [if], data = [none]
}
//321485
if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15
logger.logp(Level.FINE, CLASS_NAME,"setRawParameters", ""); // depends on control dependency: [if], data = [none]
}
SRTServletRequestThreadData.getInstance().setParameters(params);
} } |
public class class_name {
public void toFile(File file) throws IOException {
String[] sitemap = toStringArray();
try(BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
for (String string : sitemap) {
writer.write(string);
}
}
} } | public class class_name {
public void toFile(File file) throws IOException {
String[] sitemap = toStringArray();
try(BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
for (String string : sitemap) {
writer.write(string); // depends on control dependency: [for], data = [string]
}
}
} } |
public class class_name {
public List<JSTypeExpression> getExtendedInterfaces() {
if (info == null || info.extendedInterfaces == null) {
return ImmutableList.of();
}
return Collections.unmodifiableList(info.extendedInterfaces);
} } | public class class_name {
public List<JSTypeExpression> getExtendedInterfaces() {
if (info == null || info.extendedInterfaces == null) {
return ImmutableList.of(); // depends on control dependency: [if], data = [none]
}
return Collections.unmodifiableList(info.extendedInterfaces);
} } |
public class class_name {
public String getCharset(String contentType) {
String charSet = knownCharsets.get(contentType);
if (charSet != null) {
return charSet;
}
// Special cases
if (contentType.startsWith("text/") || contentType.endsWith("+json") || contentType.endsWith("+xml")) {
return "UTF-8";
}
return "BINARY";
} } | public class class_name {
public String getCharset(String contentType) {
String charSet = knownCharsets.get(contentType);
if (charSet != null) {
return charSet; // depends on control dependency: [if], data = [none]
}
// Special cases
if (contentType.startsWith("text/") || contentType.endsWith("+json") || contentType.endsWith("+xml")) {
return "UTF-8"; // depends on control dependency: [if], data = [none]
}
return "BINARY";
} } |
public class class_name {
public Optional<List<FieldSchema>> getPartitionKeys() {
String serialzed = this.getProp(HIVE_PARTITION_KEYS);
if (serialzed == null) {
return Optional.absent();
}
List<FieldSchema> deserialized = GSON.fromJson(serialzed, FIELD_SCHEMA_TYPE);
return Optional.of(deserialized);
} } | public class class_name {
public Optional<List<FieldSchema>> getPartitionKeys() {
String serialzed = this.getProp(HIVE_PARTITION_KEYS);
if (serialzed == null) {
return Optional.absent(); // depends on control dependency: [if], data = [none]
}
List<FieldSchema> deserialized = GSON.fromJson(serialzed, FIELD_SCHEMA_TYPE);
return Optional.of(deserialized);
} } |
public class class_name {
public PageSnapshot cropAround(WebElement element, int offsetX, int offsetY) {
try{
image = ImageProcessor.cropAround(image, new Coordinates(element,devicePixelRatio), offsetX, offsetY);
}catch(RasterFormatException rfe){
throw new ElementOutsideViewportException(ELEMENT_OUT_OF_VIEWPORT_EX_MESSAGE,rfe);
}
return this;
} } | public class class_name {
public PageSnapshot cropAround(WebElement element, int offsetX, int offsetY) {
try{
image = ImageProcessor.cropAround(image, new Coordinates(element,devicePixelRatio), offsetX, offsetY); // depends on control dependency: [try], data = [none]
}catch(RasterFormatException rfe){
throw new ElementOutsideViewportException(ELEMENT_OUT_OF_VIEWPORT_EX_MESSAGE,rfe);
} // depends on control dependency: [catch], data = [none]
return this;
} } |
public class class_name {
protected void performShrinkage( I transform , int numLevels ) {
// step through each layer in the pyramid.
for( int i = 0; i < numLevels; i++ ) {
int w = transform.width;
int h = transform.height;
int ww = w/2;
int hh = h/2;
Number threshold;
I subband;
// HL
subband = transform.subimage(ww,0,w,hh, null);
threshold = computeThreshold(subband);
rule.process(subband,threshold);
// System.out.print("HL = "+threshold);
// LH
subband = transform.subimage(0,hh,ww,h, null);
threshold = computeThreshold(subband);
rule.process(subband,threshold);
// System.out.print(" LH = "+threshold);
// HH
subband = transform.subimage(ww,hh,w,h, null);
threshold = computeThreshold(subband);
rule.process(subband,threshold);
// System.out.println(" HH = "+threshold);
transform = transform.subimage(0,0,ww,hh, null);
}
} } | public class class_name {
protected void performShrinkage( I transform , int numLevels ) {
// step through each layer in the pyramid.
for( int i = 0; i < numLevels; i++ ) {
int w = transform.width;
int h = transform.height;
int ww = w/2;
int hh = h/2;
Number threshold;
I subband;
// HL
subband = transform.subimage(ww,0,w,hh, null); // depends on control dependency: [for], data = [none]
threshold = computeThreshold(subband); // depends on control dependency: [for], data = [none]
rule.process(subband,threshold); // depends on control dependency: [for], data = [none]
// System.out.print("HL = "+threshold);
// LH
subband = transform.subimage(0,hh,ww,h, null); // depends on control dependency: [for], data = [none]
threshold = computeThreshold(subband); // depends on control dependency: [for], data = [none]
rule.process(subband,threshold); // depends on control dependency: [for], data = [none]
// System.out.print(" LH = "+threshold);
// HH
subband = transform.subimage(ww,hh,w,h, null); // depends on control dependency: [for], data = [none]
threshold = computeThreshold(subband); // depends on control dependency: [for], data = [none]
rule.process(subband,threshold); // depends on control dependency: [for], data = [none]
// System.out.println(" HH = "+threshold);
transform = transform.subimage(0,0,ww,hh, null); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
public BatchSuspendUserResult withUserErrors(UserError... userErrors) {
if (this.userErrors == null) {
setUserErrors(new java.util.ArrayList<UserError>(userErrors.length));
}
for (UserError ele : userErrors) {
this.userErrors.add(ele);
}
return this;
} } | public class class_name {
public BatchSuspendUserResult withUserErrors(UserError... userErrors) {
if (this.userErrors == null) {
setUserErrors(new java.util.ArrayList<UserError>(userErrors.length)); // depends on control dependency: [if], data = [none]
}
for (UserError ele : userErrors) {
this.userErrors.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public static String convertStreamToString(InputStream is, String charset) {
if (is == null) return null;
StringBuilder sb = new StringBuilder();
String line;
long linecount = 0;
long size = 0;
try {
// TODO: Can this be a performance killer if many many lines or is BufferedReader handling that in a good way?
boolean emptyBuffer = true;
BufferedReader reader = new BufferedReader(new InputStreamReader(new BOMStripperInputStream(is), charset));
while ((line = reader.readLine()) != null) {
// Skip adding line break before the first line
if (emptyBuffer) {
emptyBuffer = false;
} else {
sb.append('\n');
size++;
}
sb.append(line);
linecount++;
size += line.length();
if (logger.isTraceEnabled()) {
if (linecount % 50000 == 0) {
logger.trace("Lines read: {}, {} characters and counting...", linecount, size);
printMemUsage();
}
}
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (logger.isTraceEnabled()) {
logger.trace("Lines read: {}, {} characters", linecount, size);
printMemUsage();
}
// Ignore exceptions on call to the close method
try {if (is != null) is.close();} catch (IOException e) {}
}
return sb.toString();
} } | public class class_name {
public static String convertStreamToString(InputStream is, String charset) {
if (is == null) return null;
StringBuilder sb = new StringBuilder();
String line;
long linecount = 0;
long size = 0;
try {
// TODO: Can this be a performance killer if many many lines or is BufferedReader handling that in a good way?
boolean emptyBuffer = true;
BufferedReader reader = new BufferedReader(new InputStreamReader(new BOMStripperInputStream(is), charset));
while ((line = reader.readLine()) != null) {
// Skip adding line break before the first line
if (emptyBuffer) {
emptyBuffer = false; // depends on control dependency: [if], data = [none]
} else {
sb.append('\n'); // depends on control dependency: [if], data = [none]
size++; // depends on control dependency: [if], data = [none]
}
sb.append(line); // depends on control dependency: [while], data = [none]
linecount++; // depends on control dependency: [while], data = [none]
size += line.length(); // depends on control dependency: [while], data = [none]
if (logger.isTraceEnabled()) {
if (linecount % 50000 == 0) {
logger.trace("Lines read: {}, {} characters and counting...", linecount, size); // depends on control dependency: [if], data = [none]
printMemUsage(); // depends on control dependency: [if], data = [none]
}
}
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally { // depends on control dependency: [catch], data = [none]
if (logger.isTraceEnabled()) {
logger.trace("Lines read: {}, {} characters", linecount, size); // depends on control dependency: [if], data = [none]
printMemUsage(); // depends on control dependency: [if], data = [none]
}
// Ignore exceptions on call to the close method
try {if (is != null) is.close();} catch (IOException e) {} // depends on control dependency: [catch], data = [none]
}
return sb.toString();
} } |
public class class_name {
public int getWidth(String text) {
if (vertical)
return text.length() * 1000;
int total = 0;
if (fontSpecific) {
char cc[] = text.toCharArray();
int len = cc.length;
for (int k = 0; k < len; ++k) {
char c = cc[k];
if ((c & 0xff00) == 0 || (c & 0xff00) == 0xf000)
total += getRawWidth(c & 0xff, null);
}
}
else {
int len = text.length();
for (int k = 0; k < len; ++k) {
if (Utilities.isSurrogatePair(text, k)) {
total += getRawWidth(Utilities.convertToUtf32(text, k), encoding);
++k;
}
else
total += getRawWidth(text.charAt(k), encoding);
}
}
return total;
} } | public class class_name {
public int getWidth(String text) {
if (vertical)
return text.length() * 1000;
int total = 0;
if (fontSpecific) {
char cc[] = text.toCharArray();
int len = cc.length;
for (int k = 0; k < len; ++k) {
char c = cc[k];
if ((c & 0xff00) == 0 || (c & 0xff00) == 0xf000)
total += getRawWidth(c & 0xff, null);
}
}
else {
int len = text.length();
for (int k = 0; k < len; ++k) {
if (Utilities.isSurrogatePair(text, k)) {
total += getRawWidth(Utilities.convertToUtf32(text, k), encoding); // depends on control dependency: [if], data = [none]
++k; // depends on control dependency: [if], data = [none]
}
else
total += getRawWidth(text.charAt(k), encoding);
}
}
return total;
} } |
public class class_name {
public Field getFormFieldValueFor(
FormFieldMapping formFieldMappingParam,
Long formContainerIdParam,
boolean includeTableFieldFormRecordInfoParam
) {
if(formFieldMappingParam == null) {
return null;
}
//First attempt to fetch from the cache...
if(this.getCacheUtil() != null) {
CacheUtil.CachedFieldValue cachedFieldValue =
this.getCacheUtil().getCachedFieldValueFrom(
formFieldMappingParam.formDefinitionId,
formContainerIdParam,
formFieldMappingParam.formFieldId);
if(cachedFieldValue != null)
{
Field field = cachedFieldValue.getCachedFieldValueAsField();
if(field != null)
{
field.setFieldName(formFieldMappingParam.name);
return field;
}
}
}
//Now use a database lookup...
Field returnVal = null;
PreparedStatement preparedStatement = null, preparedStatementForTblInfo = null;
ResultSet resultSet = null,resultSetForTblInfo = null;
try {
ISyntax syntax = SyntaxFactory.getInstance().getFieldValueSyntaxFor(
this.getSQLTypeFromConnection(),
formFieldMappingParam);
if(syntax != null) {
preparedStatement = this.getConnection().prepareStatement(
syntax.getPreparedStatement());
preparedStatement.setLong(1, formFieldMappingParam.formDefinitionId);
preparedStatement.setLong(2, formFieldMappingParam.formFieldId);
preparedStatement.setLong(3, formContainerIdParam);
resultSet = preparedStatement.executeQuery();
}
switch (formFieldMappingParam.dataType.intValue()) {
//Text...
case UtilGlobal.FieldTypeId._1_TEXT:
if(resultSet.next()) {
returnVal = new Field(
formFieldMappingParam.name,
resultSet.getString(1),
Field.Type.Text);
}
break;
//True False...
case UtilGlobal.FieldTypeId._2_TRUE_FALSE:
if(resultSet.next()) {
returnVal = new Field(
formFieldMappingParam.name,
resultSet.getBoolean(1),
Field.Type.TrueFalse);
}
break;
//Paragraph Text...
case UtilGlobal.FieldTypeId._3_PARAGRAPH_TEXT:
if(resultSet.next()) {
returnVal = new Field(
formFieldMappingParam.name,
resultSet.getString(1),
Field.Type.ParagraphText);
}
break;
//Multiple Choice...
case UtilGlobal.FieldTypeId._4_MULTI_CHOICE:
MultiChoice multiChoice = new MultiChoice();
List<String> selectedValues = new ArrayList();
while(resultSet.next()) {
selectedValues.add(resultSet.getString(1));
}
multiChoice.setSelectedMultiChoices(selectedValues);
if(!selectedValues.isEmpty()) {
returnVal = new Field(
formFieldMappingParam.name,
multiChoice);
}
break;
//Date Time...
case UtilGlobal.FieldTypeId._5_DATE_TIME:
if(resultSet.next()) {
returnVal = new Field(
formFieldMappingParam.name,
resultSet.getDate(1),
Field.Type.DateTime);
}
break;
//Decimal...
case UtilGlobal.FieldTypeId._6_DECIMAL:
if(resultSet.next()) {
returnVal = new Field(
formFieldMappingParam.name,
resultSet.getDouble(1),
Field.Type.Decimal);
}
break;
//Table Field...
case UtilGlobal.FieldTypeId._7_TABLE_FIELD:
List<Long> formContainerIds = new ArrayList();
while(resultSet.next()) {
formContainerIds.add(resultSet.getLong(1));
}
//Break if empty...
if(formContainerIds.isEmpty()) {
break;
}
TableField tableField = new TableField();
final List<Form> formRecords = new ArrayList();
//Populate all the ids for forms...
formContainerIds.forEach(formContId -> {
formRecords.add(new Form(formContId));
});
//Retrieve the info for the table record...
if(includeTableFieldFormRecordInfoParam) {
ISyntax syntaxForFormContInfo = SyntaxFactory.getInstance().getSyntaxFor(
this.getSQLTypeFromConnection(),
ISyntax.ProcedureMapping.Form.GetFormContainerInfo);
preparedStatementForTblInfo = this.getConnection().prepareStatement(
syntaxForFormContInfo.getPreparedStatement());
for(Form formRecordToSetInfoOn : formRecords) {
preparedStatementForTblInfo.setLong(
1, formRecordToSetInfoOn.getId());
resultSetForTblInfo = preparedStatementForTblInfo.executeQuery();
if(resultSetForTblInfo.next()) {
Long formTypeId = resultSetForTblInfo.getLong(
SQLFormUtil.SQLColumnIndex._02_FORM_TYPE);
formRecordToSetInfoOn.setFormTypeId(formTypeId);
formRecordToSetInfoOn.setFormType(
this.sqlFormDefinitionUtil == null ? null :
this.sqlFormDefinitionUtil.getFormDefinitionIdAndTitle().get(formTypeId)
);
formRecordToSetInfoOn.setTitle(resultSetForTblInfo.getString(
SQLFormUtil.SQLColumnIndex._03_TITLE));
Date created = resultSetForTblInfo.getDate(SQLFormUtil.SQLColumnIndex._04_CREATED);
Date lastUpdated = resultSetForTblInfo.getDate(SQLFormUtil.SQLColumnIndex._05_LAST_UPDATED);
//Created...
if(created != null)
{
formRecordToSetInfoOn.setDateCreated(new Date(created.getTime()));
}
//Last Updated...
if(lastUpdated != null)
{
formRecordToSetInfoOn.setDateLastUpdated(new Date(lastUpdated.getTime()));
}
}
}
}
tableField.setTableRecords(formRecords);
returnVal = new Field(
formFieldMappingParam.name,
tableField,
Field.Type.Table);
//TODO __8__ encrypted field...
break;
//Label...
case UtilGlobal.FieldTypeId._9_LABEL:
returnVal = new Field(
formFieldMappingParam.name,
formFieldMappingParam.description,
Field.Type.Label);
break;
default:
throw new SQLException("Unable to map '"+
formContainerIdParam.intValue() +"', to Form Field value.");
}
return returnVal;
} catch (SQLException sqlError) {
throw new FluidSQLException(sqlError);
} finally {
this.closeStatement(preparedStatement);
this.closeStatement(preparedStatementForTblInfo);
}
} } | public class class_name {
public Field getFormFieldValueFor(
FormFieldMapping formFieldMappingParam,
Long formContainerIdParam,
boolean includeTableFieldFormRecordInfoParam
) {
if(formFieldMappingParam == null) {
return null; // depends on control dependency: [if], data = [none]
}
//First attempt to fetch from the cache...
if(this.getCacheUtil() != null) {
CacheUtil.CachedFieldValue cachedFieldValue =
this.getCacheUtil().getCachedFieldValueFrom(
formFieldMappingParam.formDefinitionId,
formContainerIdParam,
formFieldMappingParam.formFieldId);
if(cachedFieldValue != null)
{
Field field = cachedFieldValue.getCachedFieldValueAsField();
if(field != null)
{
field.setFieldName(formFieldMappingParam.name); // depends on control dependency: [if], data = [none]
return field; // depends on control dependency: [if], data = [none]
}
}
}
//Now use a database lookup...
Field returnVal = null;
PreparedStatement preparedStatement = null, preparedStatementForTblInfo = null;
ResultSet resultSet = null,resultSetForTblInfo = null;
try {
ISyntax syntax = SyntaxFactory.getInstance().getFieldValueSyntaxFor(
this.getSQLTypeFromConnection(),
formFieldMappingParam);
if(syntax != null) {
preparedStatement = this.getConnection().prepareStatement(
syntax.getPreparedStatement()); // depends on control dependency: [if], data = [none]
preparedStatement.setLong(1, formFieldMappingParam.formDefinitionId); // depends on control dependency: [if], data = [none]
preparedStatement.setLong(2, formFieldMappingParam.formFieldId); // depends on control dependency: [if], data = [none]
preparedStatement.setLong(3, formContainerIdParam); // depends on control dependency: [if], data = [none]
resultSet = preparedStatement.executeQuery(); // depends on control dependency: [if], data = [none]
}
switch (formFieldMappingParam.dataType.intValue()) {
//Text...
case UtilGlobal.FieldTypeId._1_TEXT:
if(resultSet.next()) {
returnVal = new Field(
formFieldMappingParam.name,
resultSet.getString(1),
Field.Type.Text); // depends on control dependency: [if], data = [none]
}
break;
//True False...
case UtilGlobal.FieldTypeId._2_TRUE_FALSE:
if(resultSet.next()) {
returnVal = new Field(
formFieldMappingParam.name,
resultSet.getBoolean(1),
Field.Type.TrueFalse);
}
break;
//Paragraph Text...
case UtilGlobal.FieldTypeId._3_PARAGRAPH_TEXT:
if(resultSet.next()) {
returnVal = new Field(
formFieldMappingParam.name,
resultSet.getString(1),
Field.Type.ParagraphText);
}
break;
//Multiple Choice...
case UtilGlobal.FieldTypeId._4_MULTI_CHOICE:
MultiChoice multiChoice = new MultiChoice();
List<String> selectedValues = new ArrayList();
while(resultSet.next()) {
selectedValues.add(resultSet.getString(1)); // depends on control dependency: [while], data = [none]
}
multiChoice.setSelectedMultiChoices(selectedValues);
if(!selectedValues.isEmpty()) {
returnVal = new Field(
formFieldMappingParam.name,
multiChoice); // depends on control dependency: [if], data = [none]
}
break;
//Date Time...
case UtilGlobal.FieldTypeId._5_DATE_TIME:
if(resultSet.next()) {
returnVal = new Field(
formFieldMappingParam.name,
resultSet.getDate(1),
Field.Type.DateTime);
}
break;
//Decimal...
case UtilGlobal.FieldTypeId._6_DECIMAL:
if(resultSet.next()) {
returnVal = new Field(
formFieldMappingParam.name,
resultSet.getDouble(1),
Field.Type.Decimal);
}
break;
//Table Field...
case UtilGlobal.FieldTypeId._7_TABLE_FIELD:
List<Long> formContainerIds = new ArrayList();
while(resultSet.next()) {
formContainerIds.add(resultSet.getLong(1));
}
//Break if empty...
if(formContainerIds.isEmpty()) {
break;
}
TableField tableField = new TableField();
final List<Form> formRecords = new ArrayList();
//Populate all the ids for forms...
formContainerIds.forEach(formContId -> {
formRecords.add(new Form(formContId));
});
//Retrieve the info for the table record...
if(includeTableFieldFormRecordInfoParam) {
ISyntax syntaxForFormContInfo = SyntaxFactory.getInstance().getSyntaxFor(
this.getSQLTypeFromConnection(),
ISyntax.ProcedureMapping.Form.GetFormContainerInfo);
preparedStatementForTblInfo = this.getConnection().prepareStatement(
syntaxForFormContInfo.getPreparedStatement());
for(Form formRecordToSetInfoOn : formRecords) {
preparedStatementForTblInfo.setLong(
1, formRecordToSetInfoOn.getId());
resultSetForTblInfo = preparedStatementForTblInfo.executeQuery();
if(resultSetForTblInfo.next()) {
Long formTypeId = resultSetForTblInfo.getLong(
SQLFormUtil.SQLColumnIndex._02_FORM_TYPE);
formRecordToSetInfoOn.setFormTypeId(formTypeId);
formRecordToSetInfoOn.setFormType(
this.sqlFormDefinitionUtil == null ? null :
this.sqlFormDefinitionUtil.getFormDefinitionIdAndTitle().get(formTypeId)
);
formRecordToSetInfoOn.setTitle(resultSetForTblInfo.getString(
SQLFormUtil.SQLColumnIndex._03_TITLE));
Date created = resultSetForTblInfo.getDate(SQLFormUtil.SQLColumnIndex._04_CREATED);
Date lastUpdated = resultSetForTblInfo.getDate(SQLFormUtil.SQLColumnIndex._05_LAST_UPDATED);
//Created...
if(created != null)
{
formRecordToSetInfoOn.setDateCreated(new Date(created.getTime()));
}
//Last Updated...
if(lastUpdated != null)
{
formRecordToSetInfoOn.setDateLastUpdated(new Date(lastUpdated.getTime()));
}
}
}
}
tableField.setTableRecords(formRecords);
returnVal = new Field(
formFieldMappingParam.name,
tableField,
Field.Type.Table);
//TODO __8__ encrypted field...
break;
//Label...
case UtilGlobal.FieldTypeId._9_LABEL:
returnVal = new Field(
formFieldMappingParam.name,
formFieldMappingParam.description,
Field.Type.Label);
break;
default:
throw new SQLException("Unable to map '"+
formContainerIdParam.intValue() +"', to Form Field value.");
}
return returnVal;
} catch (SQLException sqlError) {
throw new FluidSQLException(sqlError);
} finally {
this.closeStatement(preparedStatement);
this.closeStatement(preparedStatementForTblInfo);
}
} } |
public class class_name {
public void marshall(ObjectAttributeRange objectAttributeRange, ProtocolMarshaller protocolMarshaller) {
if (objectAttributeRange == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(objectAttributeRange.getAttributeKey(), ATTRIBUTEKEY_BINDING);
protocolMarshaller.marshall(objectAttributeRange.getRange(), RANGE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ObjectAttributeRange objectAttributeRange, ProtocolMarshaller protocolMarshaller) {
if (objectAttributeRange == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(objectAttributeRange.getAttributeKey(), ATTRIBUTEKEY_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(objectAttributeRange.getRange(), RANGE_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected static void buildSetMethod(final Class< ? > originalClass,
final String className,
final Class< ? > superClass,
final Method setterMethod,
final Class< ? > fieldType,
final ClassWriter cw) {
MethodVisitor mv;
// set method
{
Method overridingMethod;
try {
overridingMethod = superClass.getMethod( getOverridingSetMethodName( fieldType ),
Object.class, fieldType.isPrimitive() ? fieldType : Object.class );
} catch ( final Exception e ) {
throw new RuntimeException( "This is a bug. Please report back to JBoss Rules team.",
e );
}
mv = cw.visitMethod( Opcodes.ACC_PUBLIC,
overridingMethod.getName(),
Type.getMethodDescriptor( overridingMethod ),
null,
null );
mv.visitCode();
final Label l0 = new Label();
mv.visitLabel( l0 );
mv.visitVarInsn( Opcodes.ALOAD,
1 );
mv.visitTypeInsn( Opcodes.CHECKCAST,
Type.getInternalName( originalClass ) );
mv.visitVarInsn( Type.getType( fieldType ).getOpcode( Opcodes.ILOAD ),
2 );
if ( !fieldType.isPrimitive() ) {
mv.visitTypeInsn( Opcodes.CHECKCAST,
Type.getInternalName( fieldType ) );
}
if ( originalClass.isInterface() ) {
mv.visitMethodInsn( Opcodes.INVOKEINTERFACE,
Type.getInternalName( originalClass ),
setterMethod.getName(),
Type.getMethodDescriptor( setterMethod ) );
} else {
mv.visitMethodInsn( Opcodes.INVOKEVIRTUAL,
Type.getInternalName( originalClass ),
setterMethod.getName(),
Type.getMethodDescriptor( setterMethod ) );
}
mv.visitInsn( Opcodes.RETURN );
final Label l1 = new Label();
mv.visitLabel( l1 );
mv.visitLocalVariable( "this",
"L" + className + ";",
null,
l0,
l1,
0 );
mv.visitLocalVariable( "bean",
Type.getDescriptor( Object.class ),
null,
l0,
l1,
1 );
mv.visitLocalVariable( "value",
Type.getDescriptor( fieldType ),
null,
l0,
l1,
2 );
mv.visitMaxs( 0,
0 );
mv.visitEnd();
}
} } | public class class_name {
protected static void buildSetMethod(final Class< ? > originalClass,
final String className,
final Class< ? > superClass,
final Method setterMethod,
final Class< ? > fieldType,
final ClassWriter cw) {
MethodVisitor mv;
// set method
{
Method overridingMethod;
try {
overridingMethod = superClass.getMethod( getOverridingSetMethodName( fieldType ),
Object.class, fieldType.isPrimitive() ? fieldType : Object.class ); // depends on control dependency: [try], data = [none]
} catch ( final Exception e ) {
throw new RuntimeException( "This is a bug. Please report back to JBoss Rules team.",
e );
} // depends on control dependency: [catch], data = [none]
mv = cw.visitMethod( Opcodes.ACC_PUBLIC,
overridingMethod.getName(),
Type.getMethodDescriptor( overridingMethod ),
null,
null );
mv.visitCode();
final Label l0 = new Label();
mv.visitLabel( l0 );
mv.visitVarInsn( Opcodes.ALOAD,
1 );
mv.visitTypeInsn( Opcodes.CHECKCAST,
Type.getInternalName( originalClass ) );
mv.visitVarInsn( Type.getType( fieldType ).getOpcode( Opcodes.ILOAD ),
2 );
if ( !fieldType.isPrimitive() ) {
mv.visitTypeInsn( Opcodes.CHECKCAST,
Type.getInternalName( fieldType ) ); // depends on control dependency: [if], data = [none]
}
if ( originalClass.isInterface() ) {
mv.visitMethodInsn( Opcodes.INVOKEINTERFACE,
Type.getInternalName( originalClass ),
setterMethod.getName(),
Type.getMethodDescriptor( setterMethod ) ); // depends on control dependency: [if], data = [none]
} else {
mv.visitMethodInsn( Opcodes.INVOKEVIRTUAL,
Type.getInternalName( originalClass ),
setterMethod.getName(),
Type.getMethodDescriptor( setterMethod ) ); // depends on control dependency: [if], data = [none]
}
mv.visitInsn( Opcodes.RETURN );
final Label l1 = new Label();
mv.visitLabel( l1 );
mv.visitLocalVariable( "this",
"L" + className + ";",
null,
l0,
l1,
0 );
mv.visitLocalVariable( "bean",
Type.getDescriptor( Object.class ),
null,
l0,
l1,
1 );
mv.visitLocalVariable( "value",
Type.getDescriptor( fieldType ),
null,
l0,
l1,
2 );
mv.visitMaxs( 0,
0 );
mv.visitEnd();
}
} } |
public class class_name {
private void checkForUnusedLocalVar(Var v, Reference unusedAssignment) {
if (!v.isLocal()) {
return;
}
JSDocInfo jsDoc = NodeUtil.getBestJSDocInfo(unusedAssignment.getNode());
if (jsDoc != null && jsDoc.hasTypedefType()) {
return;
}
boolean inGoogScope = false;
Scope s = v.getScope();
if (s.isFunctionBlockScope()) {
Node function = s.getRootNode().getParent();
Node callee = function.getPrevious();
inGoogScope = callee != null && callee.matchesQualifiedName("goog.scope");
}
if (inGoogScope) {
// No warning.
return;
}
if (s.isModuleScope()) {
Node statement = NodeUtil.getEnclosingStatement(v.getNode());
if (NodeUtil.isNameDeclaration(statement)) {
Node lhs = statement.getFirstChild();
Node rhs = lhs.getFirstChild();
if (rhs != null
&& (NodeUtil.isCallTo(rhs, "goog.forwardDeclare")
|| NodeUtil.isCallTo(rhs, "goog.requireType")
|| NodeUtil.isCallTo(rhs, "goog.require")
|| rhs.isQualifiedName())) {
// No warning. module imports will be caught by the unused-require check, and if the
// right side is a qualified name then this is likely an alias used in type annotations.
return;
}
}
}
compiler.report(JSError.make(unusedAssignment.getNode(), UNUSED_LOCAL_ASSIGNMENT, v.name));
} } | public class class_name {
private void checkForUnusedLocalVar(Var v, Reference unusedAssignment) {
if (!v.isLocal()) {
return; // depends on control dependency: [if], data = [none]
}
JSDocInfo jsDoc = NodeUtil.getBestJSDocInfo(unusedAssignment.getNode());
if (jsDoc != null && jsDoc.hasTypedefType()) {
return; // depends on control dependency: [if], data = [none]
}
boolean inGoogScope = false;
Scope s = v.getScope();
if (s.isFunctionBlockScope()) {
Node function = s.getRootNode().getParent();
Node callee = function.getPrevious();
inGoogScope = callee != null && callee.matchesQualifiedName("goog.scope"); // depends on control dependency: [if], data = [none]
}
if (inGoogScope) {
// No warning.
return; // depends on control dependency: [if], data = [none]
}
if (s.isModuleScope()) {
Node statement = NodeUtil.getEnclosingStatement(v.getNode());
if (NodeUtil.isNameDeclaration(statement)) {
Node lhs = statement.getFirstChild();
Node rhs = lhs.getFirstChild();
if (rhs != null
&& (NodeUtil.isCallTo(rhs, "goog.forwardDeclare")
|| NodeUtil.isCallTo(rhs, "goog.requireType")
|| NodeUtil.isCallTo(rhs, "goog.require")
|| rhs.isQualifiedName())) {
// No warning. module imports will be caught by the unused-require check, and if the
// right side is a qualified name then this is likely an alias used in type annotations.
return; // depends on control dependency: [if], data = [none]
}
}
}
compiler.report(JSError.make(unusedAssignment.getNode(), UNUSED_LOCAL_ASSIGNMENT, v.name));
} } |
public class class_name {
private String[] list(File file) {
String[] files = (String[]) fileListMap.get(file);
if (files == null) {
files = file.list();
if (files != null) {
fileListMap.put(file, files);
}
}
return files;
} } | public class class_name {
private String[] list(File file) {
String[] files = (String[]) fileListMap.get(file);
if (files == null) {
files = file.list(); // depends on control dependency: [if], data = [none]
if (files != null) {
fileListMap.put(file, files); // depends on control dependency: [if], data = [none]
}
}
return files;
} } |
public class class_name {
public void alertOpen() {
if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) {
logger.logp(Level.FINE, CLASS_NAME,"alertOpen()", "");
}
if (WCCustomProperties.CHECK_REQUEST_OBJECT_IN_USE){
checkRequestObjectInUse();
}
_srtRequestHelper._InputStreamClosed=false;
} } | public class class_name {
public void alertOpen() {
if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) {
logger.logp(Level.FINE, CLASS_NAME,"alertOpen()", ""); // depends on control dependency: [if], data = [none]
}
if (WCCustomProperties.CHECK_REQUEST_OBJECT_IN_USE){
checkRequestObjectInUse(); // depends on control dependency: [if], data = [none]
}
_srtRequestHelper._InputStreamClosed=false;
} } |
public class class_name {
@Override
public GeneratedPosition generatedPositionFor(String source, int line, int column, Bias bias) {
if (this.sourceRoot != null) {
source = Util.relative(this.sourceRoot, source);
}
if (!this._sources.has(source)) {
return new GeneratedPosition();
}
int source_ = this._sources.indexOf(source);
ParsedMapping needle = new ParsedMapping(null, null, line, column, source_, null);
if (bias == null) {
bias = Bias.GREATEST_LOWER_BOUND;
}
int index = _findMapping(needle, this._originalMappings(), "originalLine", "originalColumn",
(mapping1, mapping2) -> Util.compareByOriginalPositions(mapping1, mapping2, true), bias);
if (index >= 0) {
ParsedMapping mapping = this._originalMappings().get(index);
if (mapping.source == needle.source) {
return new GeneratedPosition(mapping.generatedLine != null ? mapping.generatedLine : null,
mapping.generatedColumn != null ? mapping.generatedColumn : null,
mapping.lastGeneratedColumn != null ? mapping.lastGeneratedColumn : null);
}
}
return new GeneratedPosition();
} } | public class class_name {
@Override
public GeneratedPosition generatedPositionFor(String source, int line, int column, Bias bias) {
if (this.sourceRoot != null) {
source = Util.relative(this.sourceRoot, source); // depends on control dependency: [if], data = [(this.sourceRoot]
}
if (!this._sources.has(source)) {
return new GeneratedPosition(); // depends on control dependency: [if], data = [none]
}
int source_ = this._sources.indexOf(source);
ParsedMapping needle = new ParsedMapping(null, null, line, column, source_, null);
if (bias == null) {
bias = Bias.GREATEST_LOWER_BOUND; // depends on control dependency: [if], data = [none]
}
int index = _findMapping(needle, this._originalMappings(), "originalLine", "originalColumn",
(mapping1, mapping2) -> Util.compareByOriginalPositions(mapping1, mapping2, true), bias);
if (index >= 0) {
ParsedMapping mapping = this._originalMappings().get(index);
if (mapping.source == needle.source) {
return new GeneratedPosition(mapping.generatedLine != null ? mapping.generatedLine : null,
mapping.generatedColumn != null ? mapping.generatedColumn : null,
mapping.lastGeneratedColumn != null ? mapping.lastGeneratedColumn : null); // depends on control dependency: [if], data = [none]
}
}
return new GeneratedPosition();
} } |
public class class_name {
private static void trimZeros(IntList set)
{
// loop over ALL_ZEROS_LITERAL words
int w;
int last = set.length() - 1;
do {
w = set.get(last);
if (w == ConciseSetUtils.ALL_ZEROS_LITERAL) {
set.set(last, 0);
last--;
} else if (ConciseSetUtils.isZeroSequence(w)) {
if (ConciseSetUtils.isSequenceWithNoBits(w)) {
set.set(last, 0);
last--;
} else {
// convert the sequence in a 1-bit literal word
set.set(last, ConciseSetUtils.getLiteral(w, false));
return;
}
} else {
// one sequence or literal
return;
}
if (set.isEmpty() || last == -1) {
return;
}
} while (true);
} } | public class class_name {
private static void trimZeros(IntList set)
{
// loop over ALL_ZEROS_LITERAL words
int w;
int last = set.length() - 1;
do {
w = set.get(last);
if (w == ConciseSetUtils.ALL_ZEROS_LITERAL) {
set.set(last, 0); // depends on control dependency: [if], data = [none]
last--; // depends on control dependency: [if], data = [none]
} else if (ConciseSetUtils.isZeroSequence(w)) {
if (ConciseSetUtils.isSequenceWithNoBits(w)) {
set.set(last, 0); // depends on control dependency: [if], data = [none]
last--; // depends on control dependency: [if], data = [none]
} else {
// convert the sequence in a 1-bit literal word
set.set(last, ConciseSetUtils.getLiteral(w, false)); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
} else {
// one sequence or literal
return; // depends on control dependency: [if], data = [none]
}
if (set.isEmpty() || last == -1) {
return; // depends on control dependency: [if], data = [none]
}
} while (true);
} } |
public class class_name {
public void readEntries(BufferedReader lineReader, ErrorCallBack errorCallBack) throws IOException {
final MagicEntry[] levelParents = new MagicEntry[MAX_LEVELS];
MagicEntry previousEntry = null;
while (true) {
String line = lineReader.readLine();
if (line == null) {
break;
}
// skip blanks and comments
if (line.length() == 0 || line.charAt(0) == '#') {
continue;
}
MagicEntry entry;
try {
// we need the previous entry because of mime-type, etc. which augment the previous line
entry = MagicEntryParser.parseLine(previousEntry, line, errorCallBack);
if (entry == null) {
continue;
}
} catch (IllegalArgumentException e) {
if (errorCallBack != null) {
errorCallBack.error(line, e.getMessage(), e);
}
continue;
}
int level = entry.getLevel();
if (previousEntry == null && level != 0) {
if (errorCallBack != null) {
errorCallBack.error(line, "first entry of the file but the level " + level + " should be 0", null);
}
continue;
}
if (level == 0) {
// top level entry
entryList.add(entry);
} else if (levelParents[level - 1] == null) {
if (errorCallBack != null) {
errorCallBack.error(line,
"entry has level " + level + " but no parent entry with level " + (level - 1), null);
}
continue;
} else {
// we are a child of the one above us
levelParents[level - 1].addChild(entry);
}
levelParents[level] = entry;
previousEntry = entry;
}
} } | public class class_name {
public void readEntries(BufferedReader lineReader, ErrorCallBack errorCallBack) throws IOException {
final MagicEntry[] levelParents = new MagicEntry[MAX_LEVELS];
MagicEntry previousEntry = null;
while (true) {
String line = lineReader.readLine();
if (line == null) {
break;
}
// skip blanks and comments
if (line.length() == 0 || line.charAt(0) == '#') {
continue;
}
MagicEntry entry;
try {
// we need the previous entry because of mime-type, etc. which augment the previous line
entry = MagicEntryParser.parseLine(previousEntry, line, errorCallBack); // depends on control dependency: [try], data = [none]
if (entry == null) {
continue;
}
} catch (IllegalArgumentException e) {
if (errorCallBack != null) {
errorCallBack.error(line, e.getMessage(), e); // depends on control dependency: [if], data = [none]
}
continue;
} // depends on control dependency: [catch], data = [none]
int level = entry.getLevel();
if (previousEntry == null && level != 0) {
if (errorCallBack != null) {
errorCallBack.error(line, "first entry of the file but the level " + level + " should be 0", null); // depends on control dependency: [if], data = [null)]
}
continue;
}
if (level == 0) {
// top level entry
entryList.add(entry); // depends on control dependency: [if], data = [none]
} else if (levelParents[level - 1] == null) {
if (errorCallBack != null) {
errorCallBack.error(line,
"entry has level " + level + " but no parent entry with level " + (level - 1), null); // depends on control dependency: [if], data = [none]
}
continue;
} else {
// we are a child of the one above us
levelParents[level - 1].addChild(entry); // depends on control dependency: [if], data = [none]
}
levelParents[level] = entry;
previousEntry = entry;
}
} } |
public class class_name {
public void marshall(Destination destination, ProtocolMarshaller protocolMarshaller) {
if (destination == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(destination.getS3Destination(), S3DESTINATION_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(Destination destination, ProtocolMarshaller protocolMarshaller) {
if (destination == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(destination.getS3Destination(), S3DESTINATION_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
final List<DataSources> dataSourcesList = deploymentUnit.getAttachmentList(DsXmlDeploymentParsingProcessor.DATA_SOURCES_ATTACHMENT_KEY);
final boolean legacySecurityPresent = phaseContext.getDeploymentUnit().hasAttachment(SecurityAttachments.SECURITY_ENABLED);
for(DataSources dataSources : dataSourcesList) {
if (dataSources.getDrivers() != null && dataSources.getDrivers().size() > 0) {
ConnectorLogger.DS_DEPLOYER_LOGGER.driversElementNotSupported(deploymentUnit.getName());
}
ServiceTarget serviceTarget = phaseContext.getServiceTarget();
if (dataSources.getDataSource() != null && dataSources.getDataSource().size() > 0) {
for (int i = 0; i < dataSources.getDataSource().size(); i++) {
DataSource ds = (DataSource)dataSources.getDataSource().get(i);
if (ds.isEnabled() && ds.getDriver() != null) {
try {
final String jndiName = Util.cleanJndiName(ds.getJndiName(), ds.isUseJavaContext());
LocalDataSourceService lds = new LocalDataSourceService(jndiName, ContextNames.bindInfoFor(jndiName));
lds.getDataSourceConfigInjector().inject(buildDataSource(ds));
final String dsName = ds.getJndiName();
final PathAddress addr = getDataSourceAddress(dsName, deploymentUnit, false);
installManagementModel(ds, deploymentUnit, addr);
// TODO why have we been ignoring a configured legacy security domain but no legacy security present?
boolean useLegacySecurity = legacySecurityPresent && isLegacySecurityRequired(ds.getSecurity());
startDataSource(lds, jndiName, ds.getDriver(), serviceTarget,
getRegistration(false, deploymentUnit), getResource(dsName, false, deploymentUnit), dsName, useLegacySecurity, ds.isJTA(), support);
} catch (Exception e) {
throw ConnectorLogger.ROOT_LOGGER.exceptionDeployingDatasource(e, ds.getJndiName());
}
} else {
ConnectorLogger.DS_DEPLOYER_LOGGER.debugf("Ignoring: %s", ds.getJndiName());
}
}
}
if (dataSources.getXaDataSource() != null && dataSources.getXaDataSource().size() > 0) {
for (int i = 0; i < dataSources.getXaDataSource().size(); i++) {
XaDataSource xads = (XaDataSource)dataSources.getXaDataSource().get(i);
if (xads.isEnabled() && xads.getDriver() != null) {
try {
String jndiName = Util.cleanJndiName(xads.getJndiName(), xads.isUseJavaContext());
XaDataSourceService xds = new XaDataSourceService(jndiName, ContextNames.bindInfoFor(jndiName));
xds.getDataSourceConfigInjector().inject(buildXaDataSource(xads));
final String dsName = xads.getJndiName();
final PathAddress addr = getDataSourceAddress(dsName, deploymentUnit, true);
installManagementModel(xads, deploymentUnit, addr);
final Credential credential = xads.getRecovery() == null? null: xads.getRecovery().getCredential();
// TODO why have we been ignoring a configured legacy security domain but no legacy security present?
boolean useLegacySecurity = legacySecurityPresent && (isLegacySecurityRequired(xads.getSecurity())
|| isLegacySecurityRequired(credential));
startDataSource(xds, jndiName, xads.getDriver(), serviceTarget,
getRegistration(true, deploymentUnit), getResource(dsName, true, deploymentUnit), dsName, useLegacySecurity, true, support);
} catch (Exception e) {
throw ConnectorLogger.ROOT_LOGGER.exceptionDeployingDatasource(e, xads.getJndiName());
}
} else {
ConnectorLogger.DS_DEPLOYER_LOGGER.debugf("Ignoring %s", xads.getJndiName());
}
}
}
}
} } | public class class_name {
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
final List<DataSources> dataSourcesList = deploymentUnit.getAttachmentList(DsXmlDeploymentParsingProcessor.DATA_SOURCES_ATTACHMENT_KEY);
final boolean legacySecurityPresent = phaseContext.getDeploymentUnit().hasAttachment(SecurityAttachments.SECURITY_ENABLED);
for(DataSources dataSources : dataSourcesList) {
if (dataSources.getDrivers() != null && dataSources.getDrivers().size() > 0) {
ConnectorLogger.DS_DEPLOYER_LOGGER.driversElementNotSupported(deploymentUnit.getName()); // depends on control dependency: [if], data = [none]
}
ServiceTarget serviceTarget = phaseContext.getServiceTarget();
if (dataSources.getDataSource() != null && dataSources.getDataSource().size() > 0) {
for (int i = 0; i < dataSources.getDataSource().size(); i++) {
DataSource ds = (DataSource)dataSources.getDataSource().get(i);
if (ds.isEnabled() && ds.getDriver() != null) {
try {
final String jndiName = Util.cleanJndiName(ds.getJndiName(), ds.isUseJavaContext());
LocalDataSourceService lds = new LocalDataSourceService(jndiName, ContextNames.bindInfoFor(jndiName));
lds.getDataSourceConfigInjector().inject(buildDataSource(ds)); // depends on control dependency: [try], data = [none]
final String dsName = ds.getJndiName();
final PathAddress addr = getDataSourceAddress(dsName, deploymentUnit, false);
installManagementModel(ds, deploymentUnit, addr); // depends on control dependency: [try], data = [none]
// TODO why have we been ignoring a configured legacy security domain but no legacy security present?
boolean useLegacySecurity = legacySecurityPresent && isLegacySecurityRequired(ds.getSecurity());
startDataSource(lds, jndiName, ds.getDriver(), serviceTarget,
getRegistration(false, deploymentUnit), getResource(dsName, false, deploymentUnit), dsName, useLegacySecurity, ds.isJTA(), support); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw ConnectorLogger.ROOT_LOGGER.exceptionDeployingDatasource(e, ds.getJndiName());
} // depends on control dependency: [catch], data = [none]
} else {
ConnectorLogger.DS_DEPLOYER_LOGGER.debugf("Ignoring: %s", ds.getJndiName()); // depends on control dependency: [if], data = [none]
}
}
}
if (dataSources.getXaDataSource() != null && dataSources.getXaDataSource().size() > 0) {
for (int i = 0; i < dataSources.getXaDataSource().size(); i++) {
XaDataSource xads = (XaDataSource)dataSources.getXaDataSource().get(i);
if (xads.isEnabled() && xads.getDriver() != null) {
try {
String jndiName = Util.cleanJndiName(xads.getJndiName(), xads.isUseJavaContext());
XaDataSourceService xds = new XaDataSourceService(jndiName, ContextNames.bindInfoFor(jndiName));
xds.getDataSourceConfigInjector().inject(buildXaDataSource(xads)); // depends on control dependency: [try], data = [none]
final String dsName = xads.getJndiName();
final PathAddress addr = getDataSourceAddress(dsName, deploymentUnit, true);
installManagementModel(xads, deploymentUnit, addr); // depends on control dependency: [try], data = [none]
final Credential credential = xads.getRecovery() == null? null: xads.getRecovery().getCredential();
// TODO why have we been ignoring a configured legacy security domain but no legacy security present?
boolean useLegacySecurity = legacySecurityPresent && (isLegacySecurityRequired(xads.getSecurity())
|| isLegacySecurityRequired(credential));
startDataSource(xds, jndiName, xads.getDriver(), serviceTarget,
getRegistration(true, deploymentUnit), getResource(dsName, true, deploymentUnit), dsName, useLegacySecurity, true, support); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw ConnectorLogger.ROOT_LOGGER.exceptionDeployingDatasource(e, xads.getJndiName());
} // depends on control dependency: [catch], data = [none]
} else {
ConnectorLogger.DS_DEPLOYER_LOGGER.debugf("Ignoring %s", xads.getJndiName()); // depends on control dependency: [if], data = [none]
}
}
}
}
} } |
public class class_name {
public String defaultString(final Object target, final Object defaultValue) {
if (target == null) {
if (defaultValue == null) {
return "null";
}
return defaultValue.toString();
}
String targetString = target.toString();
if (StringUtils.isEmptyOrWhitespace(targetString)) {
if (defaultValue == null) {
return "null";
}
return defaultValue.toString();
}
return targetString;
} } | public class class_name {
public String defaultString(final Object target, final Object defaultValue) {
if (target == null) {
if (defaultValue == null) {
return "null"; // depends on control dependency: [if], data = [none]
}
return defaultValue.toString(); // depends on control dependency: [if], data = [none]
}
String targetString = target.toString();
if (StringUtils.isEmptyOrWhitespace(targetString)) {
if (defaultValue == null) {
return "null"; // depends on control dependency: [if], data = [none]
}
return defaultValue.toString(); // depends on control dependency: [if], data = [none]
}
return targetString;
} } |
public class class_name {
public void setRoundaboutAngle(@FloatRange(from = 60f, to = 300f) float roundaboutAngle) {
if (ROUNDABOUT_MANEUVER_TYPES.contains(maneuverType) && this.roundaboutAngle != roundaboutAngle) {
updateRoundaboutAngle(roundaboutAngle);
invalidate();
}
} } | public class class_name {
public void setRoundaboutAngle(@FloatRange(from = 60f, to = 300f) float roundaboutAngle) {
if (ROUNDABOUT_MANEUVER_TYPES.contains(maneuverType) && this.roundaboutAngle != roundaboutAngle) {
updateRoundaboutAngle(roundaboutAngle); // depends on control dependency: [if], data = [roundaboutAngle)]
invalidate(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void queueActionLocked(DeltaType actionType, Object obj) {
String id = this.keyOf(obj);
// If object is supposed to be deleted (last event is Deleted),
// then we should ignore Sync events, because it would result in
// recreation of this object.
if (actionType == DeltaType.Sync && this.willObjectBeDeletedLocked(id)) {
return;
}
Deque<MutablePair<DeltaType, Object>> deltas = items.get(id);
if (deltas == null) {
Deque<MutablePair<DeltaType, Object>> deltaList = new LinkedList<>();
deltaList.add(new MutablePair(actionType, obj));
deltas = new LinkedList<>(deltaList);
} else {
deltas.add(new MutablePair<DeltaType, Object>(actionType, obj));
}
// TODO(yue9944882): Eliminate the force class casting here
Deque<MutablePair<DeltaType, Object>> combinedDeltaList =
combineDeltas((LinkedList<MutablePair<DeltaType, Object>>) deltas);
boolean exist = items.containsKey(id);
if (combinedDeltaList != null && combinedDeltaList.size() > 0) {
if (!exist) {
this.queue.add(id);
}
this.items.put(id, new LinkedList<>(combinedDeltaList));
notEmpty.signalAll();
} else {
this.items.remove(id);
}
} } | public class class_name {
private void queueActionLocked(DeltaType actionType, Object obj) {
String id = this.keyOf(obj);
// If object is supposed to be deleted (last event is Deleted),
// then we should ignore Sync events, because it would result in
// recreation of this object.
if (actionType == DeltaType.Sync && this.willObjectBeDeletedLocked(id)) {
return; // depends on control dependency: [if], data = [none]
}
Deque<MutablePair<DeltaType, Object>> deltas = items.get(id);
if (deltas == null) {
Deque<MutablePair<DeltaType, Object>> deltaList = new LinkedList<>();
deltaList.add(new MutablePair(actionType, obj)); // depends on control dependency: [if], data = [none]
deltas = new LinkedList<>(deltaList); // depends on control dependency: [if], data = [none]
} else {
deltas.add(new MutablePair<DeltaType, Object>(actionType, obj)); // depends on control dependency: [if], data = [none]
}
// TODO(yue9944882): Eliminate the force class casting here
Deque<MutablePair<DeltaType, Object>> combinedDeltaList =
combineDeltas((LinkedList<MutablePair<DeltaType, Object>>) deltas);
boolean exist = items.containsKey(id);
if (combinedDeltaList != null && combinedDeltaList.size() > 0) {
if (!exist) {
this.queue.add(id); // depends on control dependency: [if], data = [none]
}
this.items.put(id, new LinkedList<>(combinedDeltaList)); // depends on control dependency: [if], data = [(combinedDeltaList]
notEmpty.signalAll(); // depends on control dependency: [if], data = [none]
} else {
this.items.remove(id); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static int[] sort(float[] c) {
HashMap<Integer, Float> map = new HashMap<Integer, Float>();
for (int i = 0; i < c.length; i++) {
if (c[i] != 0.0) {
map.put(i, Math.abs(c[i]));
}
}
ArrayList<Map.Entry<Integer, Float>> list = new ArrayList<Map.Entry<Integer, Float>>(
map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer, Float>>() {
@Override
public int compare(Entry<Integer, Float> o1,
Entry<Integer, Float> o2) {
if (o2.getValue() > o1.getValue()) {
return 1;
} else if (o1.getValue() > o2.getValue()) {
return -1;
} else {
return 0;
}
}
});
int[] idx = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
idx[i] = list.get(i).getKey();
}
return idx;
} } | public class class_name {
public static int[] sort(float[] c) {
HashMap<Integer, Float> map = new HashMap<Integer, Float>();
for (int i = 0; i < c.length; i++) {
if (c[i] != 0.0) {
map.put(i, Math.abs(c[i]));
// depends on control dependency: [if], data = [(c[i]]
}
}
ArrayList<Map.Entry<Integer, Float>> list = new ArrayList<Map.Entry<Integer, Float>>(
map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer, Float>>() {
@Override
public int compare(Entry<Integer, Float> o1,
Entry<Integer, Float> o2) {
if (o2.getValue() > o1.getValue()) {
return 1;
// depends on control dependency: [if], data = [none]
} else if (o1.getValue() > o2.getValue()) {
return -1;
// depends on control dependency: [if], data = [none]
} else {
return 0;
// depends on control dependency: [if], data = [none]
}
}
});
int[] idx = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
idx[i] = list.get(i).getKey();
// depends on control dependency: [for], data = [i]
}
return idx;
} } |
public class class_name {
protected List<String> searchResultToRobotUrlStrings(String resultHost, String scheme) {
ArrayList<String> list = new ArrayList<String>();
if (resultHost.startsWith("www")) {
if (resultHost.startsWith("www.")) {
list.add(hostToRobotUrlString(resultHost, scheme));
list.add(hostToRobotUrlString(resultHost.substring(4), scheme));
} else {
Matcher m = WWWN_PATTERN.matcher(resultHost);
if(m.find()) {
String massagedHost = resultHost.substring(m.end());
list.add(hostToRobotUrlString("www." + massagedHost, scheme));
list.add(hostToRobotUrlString(massagedHost, scheme));
}
list.add(hostToRobotUrlString(resultHost, scheme));
}
} else {
list.add(hostToRobotUrlString(resultHost, scheme));
list.add(hostToRobotUrlString("www." + resultHost, scheme));
}
return list;
} } | public class class_name {
protected List<String> searchResultToRobotUrlStrings(String resultHost, String scheme) {
ArrayList<String> list = new ArrayList<String>();
if (resultHost.startsWith("www")) {
if (resultHost.startsWith("www.")) {
list.add(hostToRobotUrlString(resultHost, scheme)); // depends on control dependency: [if], data = [none]
list.add(hostToRobotUrlString(resultHost.substring(4), scheme)); // depends on control dependency: [if], data = [none]
} else {
Matcher m = WWWN_PATTERN.matcher(resultHost);
if(m.find()) {
String massagedHost = resultHost.substring(m.end());
list.add(hostToRobotUrlString("www." + massagedHost, scheme)); // depends on control dependency: [if], data = [none]
list.add(hostToRobotUrlString(massagedHost, scheme)); // depends on control dependency: [if], data = [none]
}
list.add(hostToRobotUrlString(resultHost, scheme)); // depends on control dependency: [if], data = [none]
}
} else {
list.add(hostToRobotUrlString(resultHost, scheme)); // depends on control dependency: [if], data = [none]
list.add(hostToRobotUrlString("www." + resultHost, scheme)); // depends on control dependency: [if], data = [none]
}
return list;
} } |
public class class_name {
public static String encodeString(String value) {
int estimatedSize = 0;
final int len = value.length();
// estimate output string size to find out whether encoding is required and avoid reallocations in string builder
for (int i = 0; i < len; ++i) {
final char ch = value.charAt(i);
if (ch <= ' ' || ch == ',') {
estimatedSize += 3;
continue;
}
++estimatedSize;
}
if (value.length() == estimatedSize) {
return value; // return value as is - it does not contain any special characters
}
final StringBuilder builder = new StringBuilder(estimatedSize);
for (int i = 0; i < len; ++i) {
final char ch = value.charAt(i);
if (ch <= ' ') {
builder.append("%20");
continue;
}
if (ch == ',') {
builder.append("%2c");
continue;
}
builder.append(ch);
}
return builder.toString();
} } | public class class_name {
public static String encodeString(String value) {
int estimatedSize = 0;
final int len = value.length();
// estimate output string size to find out whether encoding is required and avoid reallocations in string builder
for (int i = 0; i < len; ++i) {
final char ch = value.charAt(i);
if (ch <= ' ' || ch == ',') {
estimatedSize += 3; // depends on control dependency: [if], data = [none]
continue;
}
++estimatedSize; // depends on control dependency: [for], data = [none]
}
if (value.length() == estimatedSize) {
return value; // return value as is - it does not contain any special characters // depends on control dependency: [if], data = [none]
}
final StringBuilder builder = new StringBuilder(estimatedSize);
for (int i = 0; i < len; ++i) {
final char ch = value.charAt(i);
if (ch <= ' ') {
builder.append("%20"); // depends on control dependency: [if], data = [none]
continue;
}
if (ch == ',') {
builder.append("%2c"); // depends on control dependency: [if], data = [none]
continue;
}
builder.append(ch); // depends on control dependency: [for], data = [none]
}
return builder.toString();
} } |
public class class_name {
private LexemePath judge(QuickSortSet.Cell lexemeCell , int fullTextLength){
//候选路径集合
TreeSet<LexemePath> pathOptions = new TreeSet<LexemePath>();
//候选结果路径
LexemePath option = new LexemePath();
//对crossPath进行一次遍历,同时返回本次遍历中有冲突的Lexeme栈
Stack<QuickSortSet.Cell> lexemeStack = this.forwardPath(lexemeCell , option);
//当前词元链并非最理想的,加入候选路径集合
pathOptions.add(option.copy());
//存在歧义词,处理
QuickSortSet.Cell c = null;
while(!lexemeStack.isEmpty()){
c = lexemeStack.pop();
//回滚词元链
this.backPath(c.getLexeme() , option);
//从歧义词位置开始,递归,生成可选方案
this.forwardPath(c , option);
pathOptions.add(option.copy());
}
//返回集合中的最优方案
return pathOptions.first();
} } | public class class_name {
private LexemePath judge(QuickSortSet.Cell lexemeCell , int fullTextLength){
//候选路径集合
TreeSet<LexemePath> pathOptions = new TreeSet<LexemePath>();
//候选结果路径
LexemePath option = new LexemePath();
//对crossPath进行一次遍历,同时返回本次遍历中有冲突的Lexeme栈
Stack<QuickSortSet.Cell> lexemeStack = this.forwardPath(lexemeCell , option);
//当前词元链并非最理想的,加入候选路径集合
pathOptions.add(option.copy());
//存在歧义词,处理
QuickSortSet.Cell c = null;
while(!lexemeStack.isEmpty()){
c = lexemeStack.pop();
// depends on control dependency: [while], data = [none]
//回滚词元链
this.backPath(c.getLexeme() , option);
// depends on control dependency: [while], data = [none]
//从歧义词位置开始,递归,生成可选方案
this.forwardPath(c , option);
// depends on control dependency: [while], data = [none]
pathOptions.add(option.copy());
// depends on control dependency: [while], data = [none]
}
//返回集合中的最优方案
return pathOptions.first();
} } |
public class class_name {
public Point3d[] get3DCoordinatesForLigands(IAtom refAtom, IAtomContainer noCoords, IAtomContainer withCoords,
IAtom atomC, int nwanted, double length, double angle) throws CDKException {
Point3d newPoints[] = new Point3d[1];
if (noCoords.getAtomCount() == 0 && withCoords.getAtomCount() == 0) {
return newPoints;
}
// too many ligands at present
if (withCoords.getAtomCount() > 3) {
return newPoints;
}
IBond.Order refMaxBondOrder = refAtom.getMaxBondOrder();
if (refAtom.getFormalNeighbourCount() == 1) {
// WTF???
} else if (refAtom.getFormalNeighbourCount() == 2 || refMaxBondOrder == IBond.Order.TRIPLE) {
//sp
if (angle == -1) {
angle = SP_ANGLE;
}
newPoints[0] = get3DCoordinatesForSPLigands(refAtom, withCoords, length, angle);
} else if (refAtom.getFormalNeighbourCount() == 3 || (refMaxBondOrder == IBond.Order.DOUBLE)) {
//sp2
if (angle == -1) {
angle = SP2_ANGLE;
}
try {
newPoints = get3DCoordinatesForSP2Ligands(refAtom, noCoords, withCoords, atomC, length, angle);
} catch (Exception ex1) {
// logger.debug("Get3DCoordinatesForLigandsERROR: Cannot place SP2 Ligands due to:" + ex1.toString());
throw new CDKException("Cannot place sp2 substituents\n" + ex1.getMessage(), ex1);
}
} else {
//sp3
try {
newPoints = get3DCoordinatesForSP3Ligands(refAtom, noCoords, withCoords, atomC, nwanted, length, angle);
} catch (Exception ex1) {
// logger.debug("Get3DCoordinatesForLigandsERROR: Cannot place SP3 Ligands due to:" + ex1.toString());
throw new CDKException("Cannot place sp3 substituents\n" + ex1.getMessage(), ex1);
}
}
//logger.debug("...Ready "+newPoints.length+" "+newPoints[0].toString());
return newPoints;
} } | public class class_name {
public Point3d[] get3DCoordinatesForLigands(IAtom refAtom, IAtomContainer noCoords, IAtomContainer withCoords,
IAtom atomC, int nwanted, double length, double angle) throws CDKException {
Point3d newPoints[] = new Point3d[1];
if (noCoords.getAtomCount() == 0 && withCoords.getAtomCount() == 0) {
return newPoints;
}
// too many ligands at present
if (withCoords.getAtomCount() > 3) {
return newPoints;
}
IBond.Order refMaxBondOrder = refAtom.getMaxBondOrder();
if (refAtom.getFormalNeighbourCount() == 1) {
// WTF???
} else if (refAtom.getFormalNeighbourCount() == 2 || refMaxBondOrder == IBond.Order.TRIPLE) {
//sp
if (angle == -1) {
angle = SP_ANGLE; // depends on control dependency: [if], data = [none]
}
newPoints[0] = get3DCoordinatesForSPLigands(refAtom, withCoords, length, angle);
} else if (refAtom.getFormalNeighbourCount() == 3 || (refMaxBondOrder == IBond.Order.DOUBLE)) {
//sp2
if (angle == -1) {
angle = SP2_ANGLE; // depends on control dependency: [if], data = [none]
}
try {
newPoints = get3DCoordinatesForSP2Ligands(refAtom, noCoords, withCoords, atomC, length, angle); // depends on control dependency: [try], data = [none]
} catch (Exception ex1) {
// logger.debug("Get3DCoordinatesForLigandsERROR: Cannot place SP2 Ligands due to:" + ex1.toString());
throw new CDKException("Cannot place sp2 substituents\n" + ex1.getMessage(), ex1);
} // depends on control dependency: [catch], data = [none]
} else {
//sp3
try {
newPoints = get3DCoordinatesForSP3Ligands(refAtom, noCoords, withCoords, atomC, nwanted, length, angle); // depends on control dependency: [try], data = [none]
} catch (Exception ex1) {
// logger.debug("Get3DCoordinatesForLigandsERROR: Cannot place SP3 Ligands due to:" + ex1.toString());
throw new CDKException("Cannot place sp3 substituents\n" + ex1.getMessage(), ex1);
} // depends on control dependency: [catch], data = [none]
}
//logger.debug("...Ready "+newPoints.length+" "+newPoints[0].toString());
return newPoints;
} } |
public class class_name {
protected int RelationalExpr(int addPos) throws javax.xml.transform.TransformerException
{
int opPos = m_ops.getOp(OpMap.MAPINDEX_LENGTH);
if (-1 == addPos)
addPos = opPos;
AdditiveExpr(-1);
if (null != m_token)
{
if (tokenIs('<'))
{
nextToken();
if (tokenIs('='))
{
nextToken();
insertOp(addPos, 2, OpCodes.OP_LTE);
}
else
{
insertOp(addPos, 2, OpCodes.OP_LT);
}
int opPlusLeftHandLen = m_ops.getOp(OpMap.MAPINDEX_LENGTH) - addPos;
addPos = RelationalExpr(addPos);
m_ops.setOp(addPos + OpMap.MAPINDEX_LENGTH,
m_ops.getOp(addPos + opPlusLeftHandLen + 1) + opPlusLeftHandLen);
addPos += 2;
}
else if (tokenIs('>'))
{
nextToken();
if (tokenIs('='))
{
nextToken();
insertOp(addPos, 2, OpCodes.OP_GTE);
}
else
{
insertOp(addPos, 2, OpCodes.OP_GT);
}
int opPlusLeftHandLen = m_ops.getOp(OpMap.MAPINDEX_LENGTH) - addPos;
addPos = RelationalExpr(addPos);
m_ops.setOp(addPos + OpMap.MAPINDEX_LENGTH,
m_ops.getOp(addPos + opPlusLeftHandLen + 1) + opPlusLeftHandLen);
addPos += 2;
}
}
return addPos;
} } | public class class_name {
protected int RelationalExpr(int addPos) throws javax.xml.transform.TransformerException
{
int opPos = m_ops.getOp(OpMap.MAPINDEX_LENGTH);
if (-1 == addPos)
addPos = opPos;
AdditiveExpr(-1);
if (null != m_token)
{
if (tokenIs('<'))
{
nextToken(); // depends on control dependency: [if], data = [none]
if (tokenIs('='))
{
nextToken(); // depends on control dependency: [if], data = [none]
insertOp(addPos, 2, OpCodes.OP_LTE); // depends on control dependency: [if], data = [none]
}
else
{
insertOp(addPos, 2, OpCodes.OP_LT); // depends on control dependency: [if], data = [none]
}
int opPlusLeftHandLen = m_ops.getOp(OpMap.MAPINDEX_LENGTH) - addPos;
addPos = RelationalExpr(addPos); // depends on control dependency: [if], data = [none]
m_ops.setOp(addPos + OpMap.MAPINDEX_LENGTH,
m_ops.getOp(addPos + opPlusLeftHandLen + 1) + opPlusLeftHandLen); // depends on control dependency: [if], data = [none]
addPos += 2; // depends on control dependency: [if], data = [none]
}
else if (tokenIs('>'))
{
nextToken(); // depends on control dependency: [if], data = [none]
if (tokenIs('='))
{
nextToken(); // depends on control dependency: [if], data = [none]
insertOp(addPos, 2, OpCodes.OP_GTE); // depends on control dependency: [if], data = [none]
}
else
{
insertOp(addPos, 2, OpCodes.OP_GT); // depends on control dependency: [if], data = [none]
}
int opPlusLeftHandLen = m_ops.getOp(OpMap.MAPINDEX_LENGTH) - addPos;
addPos = RelationalExpr(addPos); // depends on control dependency: [if], data = [none]
m_ops.setOp(addPos + OpMap.MAPINDEX_LENGTH,
m_ops.getOp(addPos + opPlusLeftHandLen + 1) + opPlusLeftHandLen); // depends on control dependency: [if], data = [none]
addPos += 2; // depends on control dependency: [if], data = [none]
}
}
return addPos;
} } |
public class class_name {
void addDimensionsToNetcdfFile(NetcdfFile ncfile) {
if (isLatLon) {
ncfile.addDimension(g, new Dimension("lat", gds.getInt(GridDefRecord.NY), true));
ncfile.addDimension(g, new Dimension("lon", gds.getInt(GridDefRecord.NX), true));
} else {
ncfile.addDimension(g, new Dimension("y", gds.getInt(GridDefRecord.NY), true));
ncfile.addDimension(g, new Dimension("x", gds.getInt(GridDefRecord.NX), true));
}
} } | public class class_name {
void addDimensionsToNetcdfFile(NetcdfFile ncfile) {
if (isLatLon) {
ncfile.addDimension(g, new Dimension("lat", gds.getInt(GridDefRecord.NY), true)); // depends on control dependency: [if], data = [none]
ncfile.addDimension(g, new Dimension("lon", gds.getInt(GridDefRecord.NX), true)); // depends on control dependency: [if], data = [none]
} else {
ncfile.addDimension(g, new Dimension("y", gds.getInt(GridDefRecord.NY), true)); // depends on control dependency: [if], data = [none]
ncfile.addDimension(g, new Dimension("x", gds.getInt(GridDefRecord.NX), true)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public LaunchPermissionModifications withRemove(LaunchPermission... remove) {
if (this.remove == null) {
setRemove(new com.amazonaws.internal.SdkInternalList<LaunchPermission>(remove.length));
}
for (LaunchPermission ele : remove) {
this.remove.add(ele);
}
return this;
} } | public class class_name {
public LaunchPermissionModifications withRemove(LaunchPermission... remove) {
if (this.remove == null) {
setRemove(new com.amazonaws.internal.SdkInternalList<LaunchPermission>(remove.length)); // depends on control dependency: [if], data = [none]
}
for (LaunchPermission ele : remove) {
this.remove.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
protected void doAttributes(AttributedCharacterIterator iter) {
underline = false;
Set set = iter.getAttributes().keySet();
for(Iterator iterator = set.iterator(); iterator.hasNext();) {
AttributedCharacterIterator.Attribute attribute = (AttributedCharacterIterator.Attribute)iterator.next();
if (!(attribute instanceof TextAttribute)) {
continue;
}
TextAttribute textattribute = (TextAttribute)attribute;
if(textattribute.equals(TextAttribute.FONT)) {
Font font = (Font)iter.getAttributes().get(textattribute);
setFont(font);
}
else if(textattribute.equals(TextAttribute.UNDERLINE)) {
if(TextAttribute.UNDERLINE_ON.equals(iter.getAttributes().get(textattribute))) {
underline = true;
}
}
else if(textattribute.equals(TextAttribute.SIZE)) {
Object obj = iter.getAttributes().get(textattribute);
if(obj instanceof Integer) {
int i = ((Integer)obj).intValue();
setFont(getFont().deriveFont(getFont().getStyle(), i));
}
else if(obj instanceof Float) {
float f = ((Float)obj).floatValue();
setFont(getFont().deriveFont(getFont().getStyle(), f));
}
}
else if(textattribute.equals(TextAttribute.FOREGROUND)) {
setColor((Color) iter.getAttributes().get(textattribute));
}
else if(textattribute.equals(TextAttribute.FAMILY)) {
Font font = getFont();
Map fontAttributes = font.getAttributes();
fontAttributes.put(TextAttribute.FAMILY, iter.getAttributes().get(textattribute));
setFont(font.deriveFont(fontAttributes));
}
else if(textattribute.equals(TextAttribute.POSTURE)) {
Font font = getFont();
Map fontAttributes = font.getAttributes();
fontAttributes.put(TextAttribute.POSTURE, iter.getAttributes().get(textattribute));
setFont(font.deriveFont(fontAttributes));
}
else if(textattribute.equals(TextAttribute.WEIGHT)) {
Font font = getFont();
Map fontAttributes = font.getAttributes();
fontAttributes.put(TextAttribute.WEIGHT, iter.getAttributes().get(textattribute));
setFont(font.deriveFont(fontAttributes));
}
}
} } | public class class_name {
protected void doAttributes(AttributedCharacterIterator iter) {
underline = false;
Set set = iter.getAttributes().keySet();
for(Iterator iterator = set.iterator(); iterator.hasNext();) {
AttributedCharacterIterator.Attribute attribute = (AttributedCharacterIterator.Attribute)iterator.next();
if (!(attribute instanceof TextAttribute)) {
continue;
}
TextAttribute textattribute = (TextAttribute)attribute;
if(textattribute.equals(TextAttribute.FONT)) {
Font font = (Font)iter.getAttributes().get(textattribute);
setFont(font); // depends on control dependency: [if], data = [none]
}
else if(textattribute.equals(TextAttribute.UNDERLINE)) {
if(TextAttribute.UNDERLINE_ON.equals(iter.getAttributes().get(textattribute))) {
underline = true; // depends on control dependency: [if], data = [none]
}
}
else if(textattribute.equals(TextAttribute.SIZE)) {
Object obj = iter.getAttributes().get(textattribute);
if(obj instanceof Integer) {
int i = ((Integer)obj).intValue();
setFont(getFont().deriveFont(getFont().getStyle(), i)); // depends on control dependency: [if], data = [none]
}
else if(obj instanceof Float) {
float f = ((Float)obj).floatValue();
setFont(getFont().deriveFont(getFont().getStyle(), f)); // depends on control dependency: [if], data = [none]
}
}
else if(textattribute.equals(TextAttribute.FOREGROUND)) {
setColor((Color) iter.getAttributes().get(textattribute)); // depends on control dependency: [if], data = [none]
}
else if(textattribute.equals(TextAttribute.FAMILY)) {
Font font = getFont();
Map fontAttributes = font.getAttributes();
fontAttributes.put(TextAttribute.FAMILY, iter.getAttributes().get(textattribute)); // depends on control dependency: [if], data = [none]
setFont(font.deriveFont(fontAttributes)); // depends on control dependency: [if], data = [none]
}
else if(textattribute.equals(TextAttribute.POSTURE)) {
Font font = getFont();
Map fontAttributes = font.getAttributes();
fontAttributes.put(TextAttribute.POSTURE, iter.getAttributes().get(textattribute)); // depends on control dependency: [if], data = [none]
setFont(font.deriveFont(fontAttributes)); // depends on control dependency: [if], data = [none]
}
else if(textattribute.equals(TextAttribute.WEIGHT)) {
Font font = getFont();
Map fontAttributes = font.getAttributes();
fontAttributes.put(TextAttribute.WEIGHT, iter.getAttributes().get(textattribute)); // depends on control dependency: [if], data = [none]
setFont(font.deriveFont(fontAttributes)); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public StringBuffer appendMessage(StringBuffer toAppendTo) {
compare();
if (messages.length()==0) {
messages.append("[identical]");
}
// fix for JDK1.4 backwards incompatibility
return toAppendTo.append(messages.toString());
} } | public class class_name {
public StringBuffer appendMessage(StringBuffer toAppendTo) {
compare();
if (messages.length()==0) {
messages.append("[identical]"); // depends on control dependency: [if], data = [none]
}
// fix for JDK1.4 backwards incompatibility
return toAppendTo.append(messages.toString());
} } |
public class class_name {
private String createReportContent(String suiteName, List<TestResult> results, ReportTemplates templates) throws IOException {
final StringBuilder reportDetails = new StringBuilder();
for (TestResult result: results) {
Properties detailProps = new Properties();
detailProps.put("test.class", result.getClassName());
detailProps.put("test.name", StringEscapeUtils.escapeXml(result.getTestName()));
detailProps.put("test.duration", "0.0");
if (result.isFailed()) {
detailProps.put("test.error.cause", Optional.ofNullable(result.getCause()).map(Object::getClass).map(Class::getName).orElse(result.getFailureType()));
detailProps.put("test.error.msg", StringEscapeUtils.escapeXml(result.getErrorMessage()));
detailProps.put("test.error.stackTrace", Optional.ofNullable(result.getCause()).map(cause -> {
StringWriter writer = new StringWriter();
cause.printStackTrace(new PrintWriter(writer));
return writer.toString();
}).orElse(result.getFailureStack()));
reportDetails.append(PropertyUtils.replacePropertiesInString(templates.getFailedTemplate(), detailProps));
} else {
reportDetails.append(PropertyUtils.replacePropertiesInString(templates.getSuccessTemplate(), detailProps));
}
}
Properties reportProps = new Properties();
reportProps.put("test.suite", suiteName);
reportProps.put("test.cnt", Integer.toString(results.size()));
reportProps.put("test.skipped.cnt", Long.toString(results.stream().filter(TestResult::isSkipped).count()));
reportProps.put("test.failed.cnt", Long.toString(results.stream().filter(TestResult::isFailed).count()));
reportProps.put("test.success.cnt", Long.toString(results.stream().filter(TestResult::isSuccess).count()));
reportProps.put("test.error.cnt", "0");
reportProps.put("test.duration", "0.0");
reportProps.put("tests", reportDetails.toString());
return PropertyUtils.replacePropertiesInString(templates.getReportTemplate(), reportProps);
} } | public class class_name {
private String createReportContent(String suiteName, List<TestResult> results, ReportTemplates templates) throws IOException {
final StringBuilder reportDetails = new StringBuilder();
for (TestResult result: results) {
Properties detailProps = new Properties();
detailProps.put("test.class", result.getClassName());
detailProps.put("test.name", StringEscapeUtils.escapeXml(result.getTestName()));
detailProps.put("test.duration", "0.0");
if (result.isFailed()) {
detailProps.put("test.error.cause", Optional.ofNullable(result.getCause()).map(Object::getClass).map(Class::getName).orElse(result.getFailureType())); // depends on control dependency: [if], data = [none]
detailProps.put("test.error.msg", StringEscapeUtils.escapeXml(result.getErrorMessage())); // depends on control dependency: [if], data = [none]
detailProps.put("test.error.stackTrace", Optional.ofNullable(result.getCause()).map(cause -> {
StringWriter writer = new StringWriter();
cause.printStackTrace(new PrintWriter(writer));
return writer.toString();
}).orElse(result.getFailureStack())); // depends on control dependency: [if], data = [none]
reportDetails.append(PropertyUtils.replacePropertiesInString(templates.getFailedTemplate(), detailProps)); // depends on control dependency: [if], data = [none]
} else {
reportDetails.append(PropertyUtils.replacePropertiesInString(templates.getSuccessTemplate(), detailProps)); // depends on control dependency: [if], data = [none]
}
}
Properties reportProps = new Properties();
reportProps.put("test.suite", suiteName);
reportProps.put("test.cnt", Integer.toString(results.size()));
reportProps.put("test.skipped.cnt", Long.toString(results.stream().filter(TestResult::isSkipped).count()));
reportProps.put("test.failed.cnt", Long.toString(results.stream().filter(TestResult::isFailed).count()));
reportProps.put("test.success.cnt", Long.toString(results.stream().filter(TestResult::isSuccess).count()));
reportProps.put("test.error.cnt", "0");
reportProps.put("test.duration", "0.0");
reportProps.put("tests", reportDetails.toString());
return PropertyUtils.replacePropertiesInString(templates.getReportTemplate(), reportProps);
} } |
public class class_name {
public static EdgeScores tensorToEdgeScores(Tensor t) {
if (t.getDims().length != 2) {
throw new IllegalArgumentException("Tensor must be an nxn matrix.");
}
int n = t.getDims()[1];
EdgeScores es = new EdgeScores(n, 0);
for (int p = -1; p < n; p++) {
for (int c = 0; c < n; c++) {
if (p == c) { continue; }
int pp = getTensorParent(p, c);
es.setScore(p, c, t.get(pp, c));
}
}
return es;
} } | public class class_name {
public static EdgeScores tensorToEdgeScores(Tensor t) {
if (t.getDims().length != 2) {
throw new IllegalArgumentException("Tensor must be an nxn matrix.");
}
int n = t.getDims()[1];
EdgeScores es = new EdgeScores(n, 0);
for (int p = -1; p < n; p++) {
for (int c = 0; c < n; c++) {
if (p == c) { continue; }
int pp = getTensorParent(p, c);
es.setScore(p, c, t.get(pp, c)); // depends on control dependency: [for], data = [c]
}
}
return es;
} } |
public class class_name {
public DescribeTableRestoreStatusResult withTableRestoreStatusDetails(TableRestoreStatus... tableRestoreStatusDetails) {
if (this.tableRestoreStatusDetails == null) {
setTableRestoreStatusDetails(new com.amazonaws.internal.SdkInternalList<TableRestoreStatus>(tableRestoreStatusDetails.length));
}
for (TableRestoreStatus ele : tableRestoreStatusDetails) {
this.tableRestoreStatusDetails.add(ele);
}
return this;
} } | public class class_name {
public DescribeTableRestoreStatusResult withTableRestoreStatusDetails(TableRestoreStatus... tableRestoreStatusDetails) {
if (this.tableRestoreStatusDetails == null) {
setTableRestoreStatusDetails(new com.amazonaws.internal.SdkInternalList<TableRestoreStatus>(tableRestoreStatusDetails.length)); // depends on control dependency: [if], data = [none]
}
for (TableRestoreStatus ele : tableRestoreStatusDetails) {
this.tableRestoreStatusDetails.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public static PropertyEditor getInstance(Class<?> type) {
if (type == null) {
throw new NullPointerException("type");
}
if (type.isEnum()) {
return new EnumEditor(type);
}
if (type.isArray()) {
return new ArrayEditor(type.getComponentType());
}
if (Collection.class.isAssignableFrom(type)) {
if (Set.class.isAssignableFrom(type)) {
return new SetEditor(String.class);
}
if (List.class.isAssignableFrom(type)) {
return new ListEditor(String.class);
}
return new CollectionEditor(String.class);
}
if (Map.class.isAssignableFrom(type)) {
return new MapEditor(String.class, String.class);
}
if (Properties.class.isAssignableFrom(type)) {
return new PropertiesEditor();
}
type = filterPrimitiveType(type);
try {
return (PropertyEditor)
PropertyEditorFactory.class.getClassLoader().loadClass(
PropertyEditorFactory.class.getPackage().getName() +
'.' + type.getSimpleName() + "Editor").newInstance();
} catch (Exception e) {
return null;
}
} } | public class class_name {
public static PropertyEditor getInstance(Class<?> type) {
if (type == null) {
throw new NullPointerException("type");
}
if (type.isEnum()) {
return new EnumEditor(type); // depends on control dependency: [if], data = [none]
}
if (type.isArray()) {
return new ArrayEditor(type.getComponentType()); // depends on control dependency: [if], data = [none]
}
if (Collection.class.isAssignableFrom(type)) {
if (Set.class.isAssignableFrom(type)) {
return new SetEditor(String.class); // depends on control dependency: [if], data = [none]
}
if (List.class.isAssignableFrom(type)) {
return new ListEditor(String.class); // depends on control dependency: [if], data = [none]
}
return new CollectionEditor(String.class); // depends on control dependency: [if], data = [none]
}
if (Map.class.isAssignableFrom(type)) {
return new MapEditor(String.class, String.class); // depends on control dependency: [if], data = [none]
}
if (Properties.class.isAssignableFrom(type)) {
return new PropertiesEditor(); // depends on control dependency: [if], data = [none]
}
type = filterPrimitiveType(type);
try {
return (PropertyEditor)
PropertyEditorFactory.class.getClassLoader().loadClass(
PropertyEditorFactory.class.getPackage().getName() +
'.' + type.getSimpleName() + "Editor").newInstance(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void setNearClippingDistance(float near) {
if(leftCamera instanceof GVRCameraClippingDistanceInterface &&
centerCamera instanceof GVRCameraClippingDistanceInterface &&
rightCamera instanceof GVRCameraClippingDistanceInterface) {
((GVRCameraClippingDistanceInterface)leftCamera).setNearClippingDistance(near);
centerCamera.setNearClippingDistance(near);
((GVRCameraClippingDistanceInterface)rightCamera).setNearClippingDistance(near);
}
} } | public class class_name {
public void setNearClippingDistance(float near) {
if(leftCamera instanceof GVRCameraClippingDistanceInterface &&
centerCamera instanceof GVRCameraClippingDistanceInterface &&
rightCamera instanceof GVRCameraClippingDistanceInterface) {
((GVRCameraClippingDistanceInterface)leftCamera).setNearClippingDistance(near); // depends on control dependency: [if], data = [none]
centerCamera.setNearClippingDistance(near); // depends on control dependency: [if], data = [none]
((GVRCameraClippingDistanceInterface)rightCamera).setNearClippingDistance(near); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public synchronized void setBalance(float balance)
{
if (currentBalance != balance)
{
currentBalance = balance;
if (sourceLine!=null && sourceLine.isControlSupported(FloatControl.Type.BALANCE))
{
FloatControl balanceControl = (FloatControl)sourceLine.getControl(FloatControl.Type.BALANCE);
if (balance <= balanceControl.getMaximum() && balance >= balanceControl.getMinimum())
balanceControl.setValue(balance);
}
}
} } | public class class_name {
public synchronized void setBalance(float balance)
{
if (currentBalance != balance)
{
currentBalance = balance; // depends on control dependency: [if], data = [none]
if (sourceLine!=null && sourceLine.isControlSupported(FloatControl.Type.BALANCE))
{
FloatControl balanceControl = (FloatControl)sourceLine.getControl(FloatControl.Type.BALANCE);
if (balance <= balanceControl.getMaximum() && balance >= balanceControl.getMinimum())
balanceControl.setValue(balance);
}
}
} } |
public class class_name {
@Beta
@CanIgnoreReturnValue
@GwtIncompatible // concurrency
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static boolean shutdownAndAwaitTermination(
ExecutorService service, long timeout, TimeUnit unit) {
long halfTimeoutNanos = unit.toNanos(timeout) / 2;
// Disable new tasks from being submitted
service.shutdown();
try {
// Wait for half the duration of the timeout for existing tasks to terminate
if (!service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS)) {
// Cancel currently executing tasks
service.shutdownNow();
// Wait the other half of the timeout for tasks to respond to being cancelled
service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS);
}
} catch (InterruptedException ie) {
// Preserve interrupt status
Thread.currentThread().interrupt();
// (Re-)Cancel if current thread also interrupted
service.shutdownNow();
}
return service.isTerminated();
} } | public class class_name {
@Beta
@CanIgnoreReturnValue
@GwtIncompatible // concurrency
@SuppressWarnings("GoodTime") // should accept a java.time.Duration
public static boolean shutdownAndAwaitTermination(
ExecutorService service, long timeout, TimeUnit unit) {
long halfTimeoutNanos = unit.toNanos(timeout) / 2;
// Disable new tasks from being submitted
service.shutdown();
try {
// Wait for half the duration of the timeout for existing tasks to terminate
if (!service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS)) {
// Cancel currently executing tasks
service.shutdownNow(); // depends on control dependency: [if], data = [none]
// Wait the other half of the timeout for tasks to respond to being cancelled
service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS); // depends on control dependency: [if], data = [none]
}
} catch (InterruptedException ie) {
// Preserve interrupt status
Thread.currentThread().interrupt();
// (Re-)Cancel if current thread also interrupted
service.shutdownNow();
} // depends on control dependency: [catch], data = [none]
return service.isTerminated();
} } |
public class class_name {
public static JKType getType(int typeNumber) {
JKType sqlDataType = codeToJKTypeMapping.get(typeNumber);
if (sqlDataType == null) {
logger.debug("No mapping found for datatype , default mapping will return " + typeNumber);
return DEFAULT_MAPPING;
}
return sqlDataType;
} } | public class class_name {
public static JKType getType(int typeNumber) {
JKType sqlDataType = codeToJKTypeMapping.get(typeNumber);
if (sqlDataType == null) {
logger.debug("No mapping found for datatype , default mapping will return " + typeNumber);
// depends on control dependency: [if], data = [none]
return DEFAULT_MAPPING;
// depends on control dependency: [if], data = [none]
}
return sqlDataType;
} } |
public class class_name {
private InputSplitAssigner getAssignerByType(final Class<? extends InputSplit> inputSplitType,
final boolean allowLoading) {
synchronized (this.loadedAssigners) {
InputSplitAssigner assigner = this.loadedAssigners.get(inputSplitType);
if (assigner == null && allowLoading) {
assigner = loadInputSplitAssigner(inputSplitType);
if (assigner != null) {
this.loadedAssigners.put(inputSplitType, assigner);
}
}
if (assigner != null) {
return assigner;
}
}
LOG.warn("Unable to find specific input split provider for type " + inputSplitType.getName()
+ ", using default assigner");
return this.defaultAssigner;
} } | public class class_name {
private InputSplitAssigner getAssignerByType(final Class<? extends InputSplit> inputSplitType,
final boolean allowLoading) {
synchronized (this.loadedAssigners) {
InputSplitAssigner assigner = this.loadedAssigners.get(inputSplitType);
if (assigner == null && allowLoading) {
assigner = loadInputSplitAssigner(inputSplitType); // depends on control dependency: [if], data = [none]
if (assigner != null) {
this.loadedAssigners.put(inputSplitType, assigner); // depends on control dependency: [if], data = [none]
}
}
if (assigner != null) {
return assigner; // depends on control dependency: [if], data = [none]
}
}
LOG.warn("Unable to find specific input split provider for type " + inputSplitType.getName()
+ ", using default assigner");
return this.defaultAssigner;
} } |
public class class_name {
public void addAnnotation(/* @Nullable */ JvmAnnotationTarget target, /* @Nullable */ XAnnotation annotation) {
if(annotation == null || target == null)
return;
JvmAnnotationReference annotationReference = getJvmAnnotationReference(annotation);
if(annotationReference != null) {
target.getAnnotations().add(annotationReference);
}
} } | public class class_name {
public void addAnnotation(/* @Nullable */ JvmAnnotationTarget target, /* @Nullable */ XAnnotation annotation) {
if(annotation == null || target == null)
return;
JvmAnnotationReference annotationReference = getJvmAnnotationReference(annotation);
if(annotationReference != null) {
target.getAnnotations().add(annotationReference); // depends on control dependency: [if], data = [(annotationReference]
}
} } |
public class class_name {
private String tail(String moduleName) {
if (moduleName.indexOf(MODULE_NAME_SEPARATOR) > 0) {
return moduleName.substring(moduleName.indexOf(MODULE_NAME_SEPARATOR) + 1);
} else {
return "";
}
} } | public class class_name {
private String tail(String moduleName) {
if (moduleName.indexOf(MODULE_NAME_SEPARATOR) > 0) {
return moduleName.substring(moduleName.indexOf(MODULE_NAME_SEPARATOR) + 1); // depends on control dependency: [if], data = [(moduleName.indexOf(MODULE_NAME_SEPARATOR)]
} else {
return ""; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public List<SecondaryIndexSearcher> getIndexSearchersForQuery(List<IndexExpression> clause)
{
Map<String, Set<ByteBuffer>> groupByIndexType = new HashMap<>();
//Group columns by type
for (IndexExpression ix : clause)
{
SecondaryIndex index = getIndexForColumn(ix.column);
if (index == null || !index.supportsOperator(ix.operator))
continue;
Set<ByteBuffer> columns = groupByIndexType.get(index.indexTypeForGrouping());
if (columns == null)
{
columns = new HashSet<>();
groupByIndexType.put(index.indexTypeForGrouping(), columns);
}
columns.add(ix.column);
}
List<SecondaryIndexSearcher> indexSearchers = new ArrayList<>(groupByIndexType.size());
//create searcher per type
for (Set<ByteBuffer> column : groupByIndexType.values())
indexSearchers.add(getIndexForColumn(column.iterator().next()).createSecondaryIndexSearcher(column));
return indexSearchers;
} } | public class class_name {
public List<SecondaryIndexSearcher> getIndexSearchersForQuery(List<IndexExpression> clause)
{
Map<String, Set<ByteBuffer>> groupByIndexType = new HashMap<>();
//Group columns by type
for (IndexExpression ix : clause)
{
SecondaryIndex index = getIndexForColumn(ix.column);
if (index == null || !index.supportsOperator(ix.operator))
continue;
Set<ByteBuffer> columns = groupByIndexType.get(index.indexTypeForGrouping());
if (columns == null)
{
columns = new HashSet<>(); // depends on control dependency: [if], data = [none]
groupByIndexType.put(index.indexTypeForGrouping(), columns); // depends on control dependency: [if], data = [none]
}
columns.add(ix.column); // depends on control dependency: [for], data = [ix]
}
List<SecondaryIndexSearcher> indexSearchers = new ArrayList<>(groupByIndexType.size());
//create searcher per type
for (Set<ByteBuffer> column : groupByIndexType.values())
indexSearchers.add(getIndexForColumn(column.iterator().next()).createSecondaryIndexSearcher(column));
return indexSearchers;
} } |
public class class_name {
public static String getOperation(HttpString method) {
String operation = "";
if (Methods.POST.equals(method)) {
operation = WRITE;
} else if (Methods.PUT.equals(method)) {
operation = WRITE;
} else if (Methods.DELETE.equals(method)) {
operation = WRITE;
} else if (Methods.GET.equals(method)) {
operation = READ;
} else if (Methods.PATCH.equals(method)) {
operation = WRITE;
} else if (Methods.OPTIONS.equals(method)) {
operation = READ;
} else if (Methods.HEAD.equals(method)) {
operation = READ;
} else {
// ignore everything else
}
return operation;
} } | public class class_name {
public static String getOperation(HttpString method) {
String operation = "";
if (Methods.POST.equals(method)) {
operation = WRITE; // depends on control dependency: [if], data = [none]
} else if (Methods.PUT.equals(method)) {
operation = WRITE; // depends on control dependency: [if], data = [none]
} else if (Methods.DELETE.equals(method)) {
operation = WRITE; // depends on control dependency: [if], data = [none]
} else if (Methods.GET.equals(method)) {
operation = READ; // depends on control dependency: [if], data = [none]
} else if (Methods.PATCH.equals(method)) {
operation = WRITE; // depends on control dependency: [if], data = [none]
} else if (Methods.OPTIONS.equals(method)) {
operation = READ; // depends on control dependency: [if], data = [none]
} else if (Methods.HEAD.equals(method)) {
operation = READ; // depends on control dependency: [if], data = [none]
} else {
// ignore everything else
}
return operation;
} } |
public class class_name {
public static List<Action> createAllFor(Computer target) {
List<Action> result = new ArrayList<>();
for (TransientComputerActionFactory f: all()) {
result.addAll(f.createFor(target));
}
return result;
} } | public class class_name {
public static List<Action> createAllFor(Computer target) {
List<Action> result = new ArrayList<>();
for (TransientComputerActionFactory f: all()) {
result.addAll(f.createFor(target)); // depends on control dependency: [for], data = [f]
}
return result;
} } |
public class class_name {
public boolean exists(String path) throws InterruptedException, KeeperException {
int retries = 0;
while (true) {
try {
Stat stat = zk.exists(path, false);
if (stat == null) {
return false;
} else {
return true;
}
} catch (KeeperException.SessionExpiredException e) {
throw e;
} catch (KeeperException e) {
LOGGER.warn("exists connect lost... will retry " + retries + "\t" + e.toString());
if (retries++ == MAX_RETRIES) {
LOGGER.error("connect final failed");
throw e;
}
// sleep then retry
int sec = RETRY_PERIOD_SECONDS * retries;
LOGGER.warn("sleep " + sec);
TimeUnit.SECONDS.sleep(sec);
}
}
} } | public class class_name {
public boolean exists(String path) throws InterruptedException, KeeperException {
int retries = 0;
while (true) {
try {
Stat stat = zk.exists(path, false);
if (stat == null) {
return false; // depends on control dependency: [if], data = [none]
} else {
return true; // depends on control dependency: [if], data = [none]
}
} catch (KeeperException.SessionExpiredException e) {
throw e;
} catch (KeeperException e) { // depends on control dependency: [catch], data = [none]
LOGGER.warn("exists connect lost... will retry " + retries + "\t" + e.toString());
if (retries++ == MAX_RETRIES) {
LOGGER.error("connect final failed"); // depends on control dependency: [if], data = [none]
throw e;
}
// sleep then retry
int sec = RETRY_PERIOD_SECONDS * retries;
LOGGER.warn("sleep " + sec);
TimeUnit.SECONDS.sleep(sec);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
private String processVariableStatements(String control, String result, TestContext context) {
if (control.equals(Citrus.IGNORE_PLACEHOLDER)) {
return control;
}
Pattern whitespacePattern = Pattern.compile("[^a-zA-Z_0-9\\-\\.]");
Pattern variablePattern = Pattern.compile("@variable\\(?'?([a-zA-Z_0-9\\-\\.]*)'?\\)?@");
Matcher variableMatcher = variablePattern.matcher(control);
while (variableMatcher.find()) {
String actualValue = result.substring(variableMatcher.start());
Matcher whitespaceMatcher = whitespacePattern.matcher(actualValue);
if (whitespaceMatcher.find()) {
actualValue = actualValue.substring(0, whitespaceMatcher.start());
}
control = variableMatcher.replaceFirst(actualValue);
context.setVariable(variableMatcher.group(1), actualValue);
variableMatcher = variablePattern.matcher(control);
}
return control;
} } | public class class_name {
private String processVariableStatements(String control, String result, TestContext context) {
if (control.equals(Citrus.IGNORE_PLACEHOLDER)) {
return control; // depends on control dependency: [if], data = [none]
}
Pattern whitespacePattern = Pattern.compile("[^a-zA-Z_0-9\\-\\.]");
Pattern variablePattern = Pattern.compile("@variable\\(?'?([a-zA-Z_0-9\\-\\.]*)'?\\)?@");
Matcher variableMatcher = variablePattern.matcher(control);
while (variableMatcher.find()) {
String actualValue = result.substring(variableMatcher.start());
Matcher whitespaceMatcher = whitespacePattern.matcher(actualValue);
if (whitespaceMatcher.find()) {
actualValue = actualValue.substring(0, whitespaceMatcher.start());
}
control = variableMatcher.replaceFirst(actualValue);
context.setVariable(variableMatcher.group(1), actualValue);
variableMatcher = variablePattern.matcher(control);
}
return control;
} } |
public class class_name {
@Override
protected <T> void buildColumnMappingList(final BeanMapping<T> beanMapping, final Class<T> beanType, final Class<?>[] groups) {
final List<ColumnMapping> columnMappingList = new ArrayList<>();
for(Field field : beanType.getDeclaredFields()) {
final CsvColumn columnAnno = field.getAnnotation(CsvColumn.class);
if(columnAnno != null) {
columnMappingList.add(createColumnMapping(field, columnAnno, groups));
}
}
beanMapping.addAllColumns(columnMappingList);
} } | public class class_name {
@Override
protected <T> void buildColumnMappingList(final BeanMapping<T> beanMapping, final Class<T> beanType, final Class<?>[] groups) {
final List<ColumnMapping> columnMappingList = new ArrayList<>();
for(Field field : beanType.getDeclaredFields()) {
final CsvColumn columnAnno = field.getAnnotation(CsvColumn.class);
if(columnAnno != null) {
columnMappingList.add(createColumnMapping(field, columnAnno, groups));
// depends on control dependency: [if], data = [none]
}
}
beanMapping.addAllColumns(columnMappingList);
} } |
public class class_name {
@Nonnull
public static List<SCMDecisionHandler> listShouldPollVetos(@Nonnull Item item) {
List<SCMDecisionHandler> result = new ArrayList<>();
for (SCMDecisionHandler handler : all()) {
if (!handler.shouldPoll(item)) {
result.add(handler);
}
}
return result;
} } | public class class_name {
@Nonnull
public static List<SCMDecisionHandler> listShouldPollVetos(@Nonnull Item item) {
List<SCMDecisionHandler> result = new ArrayList<>();
for (SCMDecisionHandler handler : all()) {
if (!handler.shouldPoll(item)) {
result.add(handler); // depends on control dependency: [if], data = [none]
}
}
return result;
} } |
public class class_name {
public void select(int position, boolean fireEvent, boolean considerSelectableFlag) {
FastAdapter.RelativeInfo<Item> relativeInfo = mFastAdapter.getRelativeInfo(position);
if (relativeInfo == null || relativeInfo.item == null) {
return;
}
select(relativeInfo.adapter, relativeInfo.item, position, fireEvent, considerSelectableFlag);
} } | public class class_name {
public void select(int position, boolean fireEvent, boolean considerSelectableFlag) {
FastAdapter.RelativeInfo<Item> relativeInfo = mFastAdapter.getRelativeInfo(position);
if (relativeInfo == null || relativeInfo.item == null) {
return; // depends on control dependency: [if], data = [none]
}
select(relativeInfo.adapter, relativeInfo.item, position, fireEvent, considerSelectableFlag);
} } |
public class class_name {
public final Flux<T> log(Logger logger,
Level level,
boolean showOperatorLine,
SignalType... options) {
SignalLogger<T> log = new SignalLogger<>(this, "IGNORED", level,
showOperatorLine,
s -> logger,
options);
if (this instanceof Fuseable) {
return onAssembly(new FluxLogFuseable<>(this, log));
}
return onAssembly(new FluxLog<>(this, log));
} } | public class class_name {
public final Flux<T> log(Logger logger,
Level level,
boolean showOperatorLine,
SignalType... options) {
SignalLogger<T> log = new SignalLogger<>(this, "IGNORED", level,
showOperatorLine,
s -> logger,
options);
if (this instanceof Fuseable) {
return onAssembly(new FluxLogFuseable<>(this, log)); // depends on control dependency: [if], data = [none]
}
return onAssembly(new FluxLog<>(this, log));
} } |
public class class_name {
public String getStateName() {
CmsResourceState state = m_resource.getState();
String name;
if (m_request == null) {
name = org.opencms.workplace.explorer.Messages.get().getBundle().key(
org.opencms.workplace.explorer.Messages.getStateKey(state));
} else {
name = org.opencms.workplace.explorer.Messages.get().getBundle(m_request.getLocale()).key(
org.opencms.workplace.explorer.Messages.getStateKey(state));
}
return name;
} } | public class class_name {
public String getStateName() {
CmsResourceState state = m_resource.getState();
String name;
if (m_request == null) {
name = org.opencms.workplace.explorer.Messages.get().getBundle().key(
org.opencms.workplace.explorer.Messages.getStateKey(state)); // depends on control dependency: [if], data = [none]
} else {
name = org.opencms.workplace.explorer.Messages.get().getBundle(m_request.getLocale()).key(
org.opencms.workplace.explorer.Messages.getStateKey(state)); // depends on control dependency: [if], data = [none]
}
return name;
} } |
public class class_name {
public static void createAsync(final GWTVizPlotClient client) {
GWT.runAsync(new RunAsyncCallback() {
public void onFailure(Throwable err) {
client.onUnavailable();
}
public void onSuccess() {
if (instance == null) {
instance = new GWTVizPlot();
}
client.onSuccess(instance);
}
});
} } | public class class_name {
public static void createAsync(final GWTVizPlotClient client) {
GWT.runAsync(new RunAsyncCallback() {
public void onFailure(Throwable err) {
client.onUnavailable();
}
public void onSuccess() {
if (instance == null) {
instance = new GWTVizPlot(); // depends on control dependency: [if], data = [none]
}
client.onSuccess(instance);
}
});
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.