code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
static int sharedPrefixLength(ByteBuffer a, int aStart, ByteBuffer b, int bStart) {
int i = 0;
final int max = Math.min(a.remaining() - aStart, b.remaining() - bStart);
aStart += a.position();
bStart += b.position();
while (i < max && a.get(aStart++) == b.get(bStart++)) {
i++;
}
return i;
} } | public class class_name {
static int sharedPrefixLength(ByteBuffer a, int aStart, ByteBuffer b, int bStart) {
int i = 0;
final int max = Math.min(a.remaining() - aStart, b.remaining() - bStart);
aStart += a.position();
bStart += b.position();
while (i < max && a.get(aStart++) == b.get(bStart++)) {
i++;
// depends on control dependency: [while], data = [none]
}
return i;
} } |
public class class_name {
public static String slurpGBURLNoExceptions(URL u) {
try {
return slurpGBURL(u);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} } | public class class_name {
public static String slurpGBURLNoExceptions(URL u) {
try {
return slurpGBURL(u);
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
e.printStackTrace();
return null;
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void addPostParams(final Request request) {
if (publicKey != null) {
request.addPostParam("PublicKey", publicKey.toString());
}
if (friendlyName != null) {
request.addPostParam("FriendlyName", friendlyName);
}
if (accountSid != null) {
request.addPostParam("AccountSid", accountSid);
}
} } | public class class_name {
private void addPostParams(final Request request) {
if (publicKey != null) {
request.addPostParam("PublicKey", publicKey.toString()); // depends on control dependency: [if], data = [none]
}
if (friendlyName != null) {
request.addPostParam("FriendlyName", friendlyName); // depends on control dependency: [if], data = [none]
}
if (accountSid != null) {
request.addPostParam("AccountSid", accountSid); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void validateAttributeGeneralization(final Attributes atts) {
final QName[][] d = domains.peekFirst();
if (d != null) {
for (final QName[] spec: d) {
for (int i = spec.length - 1; i > -1; i--) {
if (atts.getValue(spec[i].getNamespaceURI(), spec[i].getLocalPart()) != null) {
for (int j = i - 1; j > -1; j--) {
if (atts.getValue(spec[j].getNamespaceURI(), spec[j].getLocalPart()) != null) {
logger.error(MessageUtils.getMessage("DOTJ058E",
spec[j].toString(), spec[i].toString()).toString());
}
}
}
}
}
}
} } | public class class_name {
private void validateAttributeGeneralization(final Attributes atts) {
final QName[][] d = domains.peekFirst();
if (d != null) {
for (final QName[] spec: d) {
for (int i = spec.length - 1; i > -1; i--) {
if (atts.getValue(spec[i].getNamespaceURI(), spec[i].getLocalPart()) != null) {
for (int j = i - 1; j > -1; j--) {
if (atts.getValue(spec[j].getNamespaceURI(), spec[j].getLocalPart()) != null) {
logger.error(MessageUtils.getMessage("DOTJ058E",
spec[j].toString(), spec[i].toString()).toString()); // depends on control dependency: [if], data = [none]
}
}
}
}
}
}
} } |
public class class_name {
public SearchExpression withSubExpressions(SearchExpression... subExpressions) {
if (this.subExpressions == null) {
setSubExpressions(new java.util.ArrayList<SearchExpression>(subExpressions.length));
}
for (SearchExpression ele : subExpressions) {
this.subExpressions.add(ele);
}
return this;
} } | public class class_name {
public SearchExpression withSubExpressions(SearchExpression... subExpressions) {
if (this.subExpressions == null) {
setSubExpressions(new java.util.ArrayList<SearchExpression>(subExpressions.length)); // depends on control dependency: [if], data = [none]
}
for (SearchExpression ele : subExpressions) {
this.subExpressions.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public static String dumpConstraints(final Constraint[] constraints) {
if ( constraints == null ) {
return null;
}
final StringBuffer buffer = new StringBuffer();
for ( int i = 0, length = constraints.length; i < length; i++ ) {
buffer.append( constraints[i].toString() + "<br>" );
}
return buffer.toString();
} } | public class class_name {
public static String dumpConstraints(final Constraint[] constraints) {
if ( constraints == null ) {
return null; // depends on control dependency: [if], data = [none]
}
final StringBuffer buffer = new StringBuffer();
for ( int i = 0, length = constraints.length; i < length; i++ ) {
buffer.append( constraints[i].toString() + "<br>" ); // depends on control dependency: [for], data = [i]
}
return buffer.toString();
} } |
public class class_name {
public boolean accept(File file) {
// extract this file's extension
String fileExt = FileUtil.parseFileExtension(file.getName());
// a file extension might not have existed
if (fileExt == null) {
// if no file extension extracted, this definitely is not a match
return false;
}
// does it match our list of acceptable file extensions?
for (String extension : extensions) {
if (caseSensitive) {
if (fileExt.equals(extension)) {
return true;
}
} else {
if (fileExt.equalsIgnoreCase(extension)) {
return true;
}
}
}
// if we got here, then no match was found
return false;
} } | public class class_name {
public boolean accept(File file) {
// extract this file's extension
String fileExt = FileUtil.parseFileExtension(file.getName());
// a file extension might not have existed
if (fileExt == null) {
// if no file extension extracted, this definitely is not a match
return false; // depends on control dependency: [if], data = [none]
}
// does it match our list of acceptable file extensions?
for (String extension : extensions) {
if (caseSensitive) {
if (fileExt.equals(extension)) {
return true; // depends on control dependency: [if], data = [none]
}
} else {
if (fileExt.equalsIgnoreCase(extension)) {
return true; // depends on control dependency: [if], data = [none]
}
}
}
// if we got here, then no match was found
return false;
} } |
public class class_name {
private void drawNextHalf(Canvas canvas) {
canvas.save();
canvas.clipRect(isFlippingVertically() ? mBottomRect : mRightRect);
final float degreesFlipped = getDegreesFlipped();
final Page p = degreesFlipped > 90 ? mCurrentPage : mNextPage;
// if the view does not exist, skip drawing it
if (p.valid) {
setDrawWithLayer(p.v, true);
drawChild(canvas, p.v, 0);
}
drawNextShadow(canvas);
canvas.restore();
} } | public class class_name {
private void drawNextHalf(Canvas canvas) {
canvas.save();
canvas.clipRect(isFlippingVertically() ? mBottomRect : mRightRect);
final float degreesFlipped = getDegreesFlipped();
final Page p = degreesFlipped > 90 ? mCurrentPage : mNextPage;
// if the view does not exist, skip drawing it
if (p.valid) {
setDrawWithLayer(p.v, true); // depends on control dependency: [if], data = [none]
drawChild(canvas, p.v, 0); // depends on control dependency: [if], data = [none]
}
drawNextShadow(canvas);
canvas.restore();
} } |
public class class_name {
public long getRateLimitReset()
{
if (retrofitError.getResponse() == null)
{
return -1;
}
for (Header header : retrofitError.getResponse().getHeaders())
{
if ("X-RateLimit-Reset".equals(header.getName()))
{
return Long.parseLong(header.getValue());
}
}
return -1;
} } | public class class_name {
public long getRateLimitReset()
{
if (retrofitError.getResponse() == null)
{
return -1; // depends on control dependency: [if], data = [none]
}
for (Header header : retrofitError.getResponse().getHeaders())
{
if ("X-RateLimit-Reset".equals(header.getName()))
{
return Long.parseLong(header.getValue()); // depends on control dependency: [if], data = [none]
}
}
return -1;
} } |
public class class_name {
public void add(Rec fieldList) throws DBException
{
Record record = (Record)fieldList;
boolean bRefreshed = true;
if ((this.getRecord().getOpenMode() & DBConstants.OPEN_REFRESH_AND_LOCK_ON_CHANGE_STRATEGY) == DBConstants.OPEN_REFRESH_AND_LOCK_ON_CHANGE_STRATEGY)
bRefreshed = record.isRefreshedRecord(); // Only do this on the second write
super.add(record);
if (bRefreshed)
{ // On second only
Iterator<BaseTable> iterator = this.getTables();
while (iterator.hasNext())
{
BaseTable table = iterator.next();
if ((table != null) && (table != this.getNextTable()))
{
if (table.getRecord().getEditMode() == Constants.EDIT_ADD)
{ // Should have been in sync, but it is now!
Record record2 = table.getRecord();
boolean bIsAutoSequence = record2.setAutoSequence(false);
this.copyRecord(record2, record);
try {
table.add(record2);
} catch (DBException ex) {
throw ex;
} finally {
record2.setAutoSequence(bIsAutoSequence);
}
}
}
}
}
} } | public class class_name {
public void add(Rec fieldList) throws DBException
{
Record record = (Record)fieldList;
boolean bRefreshed = true;
if ((this.getRecord().getOpenMode() & DBConstants.OPEN_REFRESH_AND_LOCK_ON_CHANGE_STRATEGY) == DBConstants.OPEN_REFRESH_AND_LOCK_ON_CHANGE_STRATEGY)
bRefreshed = record.isRefreshedRecord(); // Only do this on the second write
super.add(record);
if (bRefreshed)
{ // On second only
Iterator<BaseTable> iterator = this.getTables();
while (iterator.hasNext())
{
BaseTable table = iterator.next();
if ((table != null) && (table != this.getNextTable()))
{
if (table.getRecord().getEditMode() == Constants.EDIT_ADD)
{ // Should have been in sync, but it is now!
Record record2 = table.getRecord();
boolean bIsAutoSequence = record2.setAutoSequence(false);
this.copyRecord(record2, record); // depends on control dependency: [if], data = [none]
try {
table.add(record2); // depends on control dependency: [try], data = [none]
} catch (DBException ex) {
throw ex;
} finally { // depends on control dependency: [catch], data = [none]
record2.setAutoSequence(bIsAutoSequence);
}
}
}
}
}
} } |
public class class_name {
protected Tree processGossipRequest(Tree data) throws Exception {
// Debug
String sender = data.get("sender", (String) null);
if (debugHeartbeats) {
logger.info("Gossip request received from \"" + sender + "\" node:\r\n" + data);
}
// Add "online" and "offline" response blocks
LinkedList<NodeDescriptor> allNodes = new LinkedList<>(nodes.values());
NodeDescriptor descriptor = getDescriptor();
allNodes.add(descriptor);
int size = allNodes.size() + 1;
FastBuildTree onlineRsp = new FastBuildTree(size);
FastBuildTree offlineRsp = new FastBuildTree(size);
// Online / offline nodes in request
Tree onlineReq = data.get("online");
Tree offlineReq = data.get("offline");
// Loop in nodes
LinkedList<NodeDescriptor> disconnectedNodes = new LinkedList<>();
for (NodeDescriptor node : allNodes) {
node.writeLock.lock();
try {
Tree online = onlineReq == null ? null : onlineReq.get(node.nodeID);
Tree offline = offlineReq == null ? null : offlineReq.get(node.nodeID);
// Online or offline sequence number
long seq = 0;
// CPU data
long cpuSeq = 0;
int cpu = 0;
if (offline != null) {
if (!offline.isPrimitive()) {
logger.warn("Invalid \"offline\" block: " + offline.toString(false));
continue;
}
seq = offline.asLong();
} else if (online != null) {
if (!online.isEnumeration() || online.size() != 3) {
logger.warn("Invalid \"online\" block: " + online.toString(false));
continue;
}
seq = online.get(0).asLong();
cpuSeq = online.get(1).asLong();
cpu = online.get(2).asInteger();
}
if ((seq == 0 || seq < node.seq) && node.seq > 0) {
// We have newer info or requester doesn't know it
if (node.offlineSince == 0) {
if (!node.info.isEmpty()) {
if ((cpuSeq == 0 || cpuSeq < node.cpuSeq) && node.cpuSeq > 0) {
ArrayList<Object> array = new ArrayList<>(3);
array.add(node.info.asObject());
array.add(node.cpuSeq);
array.add(node.cpu);
onlineRsp.putUnsafe(node.nodeID, array);
} else {
onlineRsp.putUnsafe(node.nodeID, Collections.singletonList(node.info.asObject()));
}
}
} else {
offlineRsp.putUnsafe(node.nodeID, node.seq);
}
}
if (offline != null) {
// Requester said it is OFFLINE
if (node.offlineSince > 0) {
// We also knew it as offline
node.markAsOffline(seq);
continue;
}
if (!node.local) {
if (node.offlineSince == 0) {
// We know it is online, so we change it to offline
if (node.markAsOffline(seq)) {
// Remove remote actions and listeners
registry.removeActions(node.nodeID);
eventbus.removeListeners(node.nodeID);
writer.close(node.nodeID);
disconnectedNodes.add(node);
} else if (seq == node.seq) {
// We send back that this node is online
node.seq = seq + 1;
node.info.put("seq", node.seq);
if (cpuSeq < node.cpuSeq && node.cpuSeq > 0) {
ArrayList<Object> array = new ArrayList<>(3);
array.add(node.info.asObject());
array.add(node.cpuSeq);
array.add(node.cpu);
onlineRsp.putUnsafe(node.nodeID, array);
} else {
onlineRsp.putUnsafe(node.nodeID, Collections.singletonList(node.info.asObject()));
}
}
}
continue;
}
} else if (online != null) {
// Requester said it is ONLINE
if (node.offlineSince == 0) {
if (cpuSeq > node.cpuSeq) {
// We update our CPU info
node.updateCpu(cpuSeq, cpu);
} else if (cpuSeq < node.cpuSeq && node.cpuSeq > 0) {
// We have newer CPU value, send back
ArrayList<Object> array = new ArrayList<>(2);
array.add(node.cpuSeq);
array.add(node.cpu);
onlineRsp.putUnsafe(node.nodeID, array);
}
} else {
// We knew it as offline. We do nothing, because we'll
// request it and we'll receive its INFO
continue;
}
}
} finally {
node.writeLock.unlock();
}
}
// Create gossip response
FastBuildTree root = new FastBuildTree(4);
root.putUnsafe("ver", ServiceBroker.PROTOCOL_VERSION);
root.putUnsafe("sender", nodeID);
// Remove empty blocks
boolean emptyOnlineBlock = onlineRsp.isEmpty();
boolean emptyOfflineBlock = offlineRsp.isEmpty();
if (emptyOnlineBlock && emptyOfflineBlock) {
// Message is empty
return root;
}
if (!emptyOnlineBlock) {
root.putUnsafe("online", onlineRsp.asObject());
}
if (!emptyOfflineBlock) {
root.putUnsafe("offline", offlineRsp.asObject());
}
// Debug
if (debugHeartbeats) {
logger.info("Gossip response submitting to \"" + sender + "\" node:\r\n" + root);
}
// Serialize response
byte[] packet = serialize(PACKET_GOSSIP_RSP_ID, root);
// Send response
writer.send(sender, packet);
// Notify listeners (unexpected disconnection)
for (NodeDescriptor node : disconnectedNodes) {
logger.info("Node \"" + node.nodeID + "\" disconnected.");
broadcastNodeDisconnected(node.info, true);
}
// For unit testing
return root;
} } | public class class_name {
protected Tree processGossipRequest(Tree data) throws Exception {
// Debug
String sender = data.get("sender", (String) null);
if (debugHeartbeats) {
logger.info("Gossip request received from \"" + sender + "\" node:\r\n" + data);
}
// Add "online" and "offline" response blocks
LinkedList<NodeDescriptor> allNodes = new LinkedList<>(nodes.values());
NodeDescriptor descriptor = getDescriptor();
allNodes.add(descriptor);
int size = allNodes.size() + 1;
FastBuildTree onlineRsp = new FastBuildTree(size);
FastBuildTree offlineRsp = new FastBuildTree(size);
// Online / offline nodes in request
Tree onlineReq = data.get("online");
Tree offlineReq = data.get("offline");
// Loop in nodes
LinkedList<NodeDescriptor> disconnectedNodes = new LinkedList<>();
for (NodeDescriptor node : allNodes) {
node.writeLock.lock();
try {
Tree online = onlineReq == null ? null : onlineReq.get(node.nodeID);
Tree offline = offlineReq == null ? null : offlineReq.get(node.nodeID);
// Online or offline sequence number
long seq = 0;
// CPU data
long cpuSeq = 0;
int cpu = 0;
if (offline != null) {
if (!offline.isPrimitive()) {
logger.warn("Invalid \"offline\" block: " + offline.toString(false)); // depends on control dependency: [if], data = [none]
continue;
}
seq = offline.asLong(); // depends on control dependency: [if], data = [none]
} else if (online != null) {
if (!online.isEnumeration() || online.size() != 3) {
logger.warn("Invalid \"online\" block: " + online.toString(false)); // depends on control dependency: [if], data = [none]
continue;
}
seq = online.get(0).asLong(); // depends on control dependency: [if], data = [none]
cpuSeq = online.get(1).asLong(); // depends on control dependency: [if], data = [none]
cpu = online.get(2).asInteger(); // depends on control dependency: [if], data = [none]
}
if ((seq == 0 || seq < node.seq) && node.seq > 0) {
// We have newer info or requester doesn't know it
if (node.offlineSince == 0) {
if (!node.info.isEmpty()) {
if ((cpuSeq == 0 || cpuSeq < node.cpuSeq) && node.cpuSeq > 0) {
ArrayList<Object> array = new ArrayList<>(3);
array.add(node.info.asObject()); // depends on control dependency: [if], data = [none]
array.add(node.cpuSeq); // depends on control dependency: [if], data = [none]
array.add(node.cpu); // depends on control dependency: [if], data = [none]
onlineRsp.putUnsafe(node.nodeID, array); // depends on control dependency: [if], data = [none]
} else {
onlineRsp.putUnsafe(node.nodeID, Collections.singletonList(node.info.asObject())); // depends on control dependency: [if], data = [none]
}
}
} else {
offlineRsp.putUnsafe(node.nodeID, node.seq); // depends on control dependency: [if], data = [none]
}
}
if (offline != null) {
// Requester said it is OFFLINE
if (node.offlineSince > 0) {
// We also knew it as offline
node.markAsOffline(seq); // depends on control dependency: [if], data = [none]
continue;
}
if (!node.local) {
if (node.offlineSince == 0) {
// We know it is online, so we change it to offline
if (node.markAsOffline(seq)) {
// Remove remote actions and listeners
registry.removeActions(node.nodeID); // depends on control dependency: [if], data = [none]
eventbus.removeListeners(node.nodeID); // depends on control dependency: [if], data = [none]
writer.close(node.nodeID); // depends on control dependency: [if], data = [none]
disconnectedNodes.add(node); // depends on control dependency: [if], data = [none]
} else if (seq == node.seq) {
// We send back that this node is online
node.seq = seq + 1; // depends on control dependency: [if], data = [none]
node.info.put("seq", node.seq); // depends on control dependency: [if], data = [node.seq)]
if (cpuSeq < node.cpuSeq && node.cpuSeq > 0) {
ArrayList<Object> array = new ArrayList<>(3);
array.add(node.info.asObject()); // depends on control dependency: [if], data = [none]
array.add(node.cpuSeq); // depends on control dependency: [if], data = [none]
array.add(node.cpu); // depends on control dependency: [if], data = [none]
onlineRsp.putUnsafe(node.nodeID, array); // depends on control dependency: [if], data = [none]
} else {
onlineRsp.putUnsafe(node.nodeID, Collections.singletonList(node.info.asObject())); // depends on control dependency: [if], data = [none]
}
}
}
continue;
}
} else if (online != null) {
// Requester said it is ONLINE
if (node.offlineSince == 0) {
if (cpuSeq > node.cpuSeq) {
// We update our CPU info
node.updateCpu(cpuSeq, cpu); // depends on control dependency: [if], data = [(cpuSeq]
} else if (cpuSeq < node.cpuSeq && node.cpuSeq > 0) {
// We have newer CPU value, send back
ArrayList<Object> array = new ArrayList<>(2);
array.add(node.cpuSeq); // depends on control dependency: [if], data = [none]
array.add(node.cpu); // depends on control dependency: [if], data = [none]
onlineRsp.putUnsafe(node.nodeID, array); // depends on control dependency: [if], data = [none]
}
} else {
// We knew it as offline. We do nothing, because we'll
// request it and we'll receive its INFO
continue;
}
}
} finally {
node.writeLock.unlock();
}
}
// Create gossip response
FastBuildTree root = new FastBuildTree(4);
root.putUnsafe("ver", ServiceBroker.PROTOCOL_VERSION);
root.putUnsafe("sender", nodeID);
// Remove empty blocks
boolean emptyOnlineBlock = onlineRsp.isEmpty();
boolean emptyOfflineBlock = offlineRsp.isEmpty();
if (emptyOnlineBlock && emptyOfflineBlock) {
// Message is empty
return root;
}
if (!emptyOnlineBlock) {
root.putUnsafe("online", onlineRsp.asObject());
}
if (!emptyOfflineBlock) {
root.putUnsafe("offline", offlineRsp.asObject());
}
// Debug
if (debugHeartbeats) {
logger.info("Gossip response submitting to \"" + sender + "\" node:\r\n" + root);
}
// Serialize response
byte[] packet = serialize(PACKET_GOSSIP_RSP_ID, root);
// Send response
writer.send(sender, packet);
// Notify listeners (unexpected disconnection)
for (NodeDescriptor node : disconnectedNodes) {
logger.info("Node \"" + node.nodeID + "\" disconnected.");
broadcastNodeDisconnected(node.info, true);
}
// For unit testing
return root;
} } |
public class class_name {
public void onConnected() {
ConnectionState event = null;
synchronized (this) {
if (this.state != ConnectionState.CONNECTING) {
LOG.debug("Unable to set to connected, not in CONNECTING state: {}", this.state);
return;
}
this.state = ConnectionState.CONNECTED;
inputAvailable = false; // cannot read (yet)
outputAvailable = true; // write allowed
event = this.state;
}
notifyStateListeners(event);
} } | public class class_name {
public void onConnected() {
ConnectionState event = null;
synchronized (this) {
if (this.state != ConnectionState.CONNECTING) {
LOG.debug("Unable to set to connected, not in CONNECTING state: {}", this.state); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.state = ConnectionState.CONNECTED;
inputAvailable = false; // cannot read (yet)
outputAvailable = true; // write allowed
event = this.state;
}
notifyStateListeners(event);
} } |
public class class_name {
public ClassNode getClassNode() {
if (classNode == null && GroovyObject.class.isAssignableFrom(theClass)) {
// let's try load it from the classpath
String groovyFile = theClass.getName();
int idx = groovyFile.indexOf('$');
if (idx > 0) {
groovyFile = groovyFile.substring(0, idx);
}
groovyFile = groovyFile.replace('.', '/') + ".groovy";
//System.out.println("Attempting to load: " + groovyFile);
URL url = theClass.getClassLoader().getResource(groovyFile);
if (url == null) {
url = Thread.currentThread().getContextClassLoader().getResource(groovyFile);
}
if (url != null) {
try {
/*
* todo there is no CompileUnit in scope so class name
* checking won't work but that mostly affects the bytecode
* generation rather than viewing the AST
*/
CompilationUnit.ClassgenCallback search = new CompilationUnit.ClassgenCallback() {
public void call(ClassVisitor writer, ClassNode node) {
if (node.getName().equals(theClass.getName())) {
MetaClassImpl.this.classNode = node;
}
}
};
CompilationUnit unit = new CompilationUnit();
unit.setClassgenCallback(search);
unit.addSource(url);
unit.compile(Phases.CLASS_GENERATION);
}
catch (Exception e) {
throw new GroovyRuntimeException("Exception thrown parsing: " + groovyFile + ". Reason: " + e, e);
}
}
}
return classNode;
} } | public class class_name {
public ClassNode getClassNode() {
if (classNode == null && GroovyObject.class.isAssignableFrom(theClass)) {
// let's try load it from the classpath
String groovyFile = theClass.getName();
int idx = groovyFile.indexOf('$');
if (idx > 0) {
groovyFile = groovyFile.substring(0, idx); // depends on control dependency: [if], data = [none]
}
groovyFile = groovyFile.replace('.', '/') + ".groovy"; // depends on control dependency: [if], data = [none]
//System.out.println("Attempting to load: " + groovyFile);
URL url = theClass.getClassLoader().getResource(groovyFile);
if (url == null) {
url = Thread.currentThread().getContextClassLoader().getResource(groovyFile); // depends on control dependency: [if], data = [none]
}
if (url != null) {
try {
/*
* todo there is no CompileUnit in scope so class name
* checking won't work but that mostly affects the bytecode
* generation rather than viewing the AST
*/
CompilationUnit.ClassgenCallback search = new CompilationUnit.ClassgenCallback() {
public void call(ClassVisitor writer, ClassNode node) {
if (node.getName().equals(theClass.getName())) {
MetaClassImpl.this.classNode = node; // depends on control dependency: [if], data = [none]
}
}
};
CompilationUnit unit = new CompilationUnit();
unit.setClassgenCallback(search); // depends on control dependency: [try], data = [none]
unit.addSource(url); // depends on control dependency: [try], data = [none]
unit.compile(Phases.CLASS_GENERATION); // depends on control dependency: [try], data = [none]
}
catch (Exception e) {
throw new GroovyRuntimeException("Exception thrown parsing: " + groovyFile + ". Reason: " + e, e);
} // depends on control dependency: [catch], data = [none]
}
}
return classNode;
} } |
public class class_name {
private static void displayDocumentAttachements(final VerticalLayout panelContent,
final List<DocumentAttachment> documentAttachmentList) {
for (final DocumentAttachment documentAttachment : documentAttachmentList) {
if (PDF.equalsIgnoreCase(documentAttachment.getFileType())) {
final WTPdfViewer wtPdfViewer = new WTPdfViewer();
wtPdfViewer.setSizeFull();
wtPdfViewer.setResource(new StreamResource(new StreamSourceImplementation(documentAttachment.getFileUrl()), documentAttachment.getFileName()));
panelContent.addComponent(wtPdfViewer);
panelContent.setExpandRatio(wtPdfViewer, ContentRatio.LARGE);
} else {
final VerticalLayout verticalLayout = new VerticalLayout();
panelContent.addComponent(verticalLayout);
panelContent.setExpandRatio(verticalLayout, ContentRatio.SMALL);
final ExternalAttachmentDownloadLink link = new ExternalAttachmentDownloadLink(
documentAttachment.getFileName(), documentAttachment.getFileType(),
documentAttachment.getFileUrl());
verticalLayout.addComponent(link);
}
}
} } | public class class_name {
private static void displayDocumentAttachements(final VerticalLayout panelContent,
final List<DocumentAttachment> documentAttachmentList) {
for (final DocumentAttachment documentAttachment : documentAttachmentList) {
if (PDF.equalsIgnoreCase(documentAttachment.getFileType())) {
final WTPdfViewer wtPdfViewer = new WTPdfViewer();
wtPdfViewer.setSizeFull(); // depends on control dependency: [if], data = [none]
wtPdfViewer.setResource(new StreamResource(new StreamSourceImplementation(documentAttachment.getFileUrl()), documentAttachment.getFileName())); // depends on control dependency: [if], data = [none]
panelContent.addComponent(wtPdfViewer); // depends on control dependency: [if], data = [none]
panelContent.setExpandRatio(wtPdfViewer, ContentRatio.LARGE); // depends on control dependency: [if], data = [none]
} else {
final VerticalLayout verticalLayout = new VerticalLayout();
panelContent.addComponent(verticalLayout); // depends on control dependency: [if], data = [none]
panelContent.setExpandRatio(verticalLayout, ContentRatio.SMALL); // depends on control dependency: [if], data = [none]
final ExternalAttachmentDownloadLink link = new ExternalAttachmentDownloadLink(
documentAttachment.getFileName(), documentAttachment.getFileType(),
documentAttachment.getFileUrl());
verticalLayout.addComponent(link); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static base_responses update(nitro_service client, ntpserver resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
ntpserver updateresources[] = new ntpserver[resources.length];
for (int i=0;i<resources.length;i++){
updateresources[i] = new ntpserver();
updateresources[i].serverip = resources[i].serverip;
updateresources[i].servername = resources[i].servername;
updateresources[i].minpoll = resources[i].minpoll;
updateresources[i].maxpoll = resources[i].maxpoll;
updateresources[i].preferredntpserver = resources[i].preferredntpserver;
updateresources[i].autokey = resources[i].autokey;
updateresources[i].key = resources[i].key;
}
result = update_bulk_request(client, updateresources);
}
return result;
} } | public class class_name {
public static base_responses update(nitro_service client, ntpserver resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
ntpserver updateresources[] = new ntpserver[resources.length];
for (int i=0;i<resources.length;i++){
updateresources[i] = new ntpserver(); // depends on control dependency: [for], data = [i]
updateresources[i].serverip = resources[i].serverip; // depends on control dependency: [for], data = [i]
updateresources[i].servername = resources[i].servername; // depends on control dependency: [for], data = [i]
updateresources[i].minpoll = resources[i].minpoll; // depends on control dependency: [for], data = [i]
updateresources[i].maxpoll = resources[i].maxpoll; // depends on control dependency: [for], data = [i]
updateresources[i].preferredntpserver = resources[i].preferredntpserver; // depends on control dependency: [for], data = [i]
updateresources[i].autokey = resources[i].autokey; // depends on control dependency: [for], data = [i]
updateresources[i].key = resources[i].key; // depends on control dependency: [for], data = [i]
}
result = update_bulk_request(client, updateresources);
}
return result;
} } |
public class class_name {
@SuppressWarnings("unchecked")
/**
* 返回列表 key 中,下标为 index 的元素。
* 下标(index)参数 start 和 stop 都以 0 为底,也就是说,以 0 表示列表的第一个元素,
* 以 1 表示列表的第二个元素,以此类推。
* 你也可以使用负数下标,以 -1 表示列表的最后一个元素, -2 表示列表的倒数第二个元素,以此类推。
* 如果 key 不是列表类型,返回一个错误。
*/
public <T> T lindex(Object key, long index) {
Jedis jedis = getJedis();
try {
return (T)valueFromBytes(jedis.lindex(keyToBytes(key), index));
}
finally {close(jedis);}
} } | public class class_name {
@SuppressWarnings("unchecked")
/**
* 返回列表 key 中,下标为 index 的元素。
* 下标(index)参数 start 和 stop 都以 0 为底,也就是说,以 0 表示列表的第一个元素,
* 以 1 表示列表的第二个元素,以此类推。
* 你也可以使用负数下标,以 -1 表示列表的最后一个元素, -2 表示列表的倒数第二个元素,以此类推。
* 如果 key 不是列表类型,返回一个错误。
*/
public <T> T lindex(Object key, long index) {
Jedis jedis = getJedis();
try {
return (T)valueFromBytes(jedis.lindex(keyToBytes(key), index));
// depends on control dependency: [try], data = [none]
}
finally {close(jedis);}
} } |
public class class_name {
static String toValue(Cell cell, List<CellProcessor> cellProcessors) {
String value;
switch (cell.getCellTypeEnum()) {
case BLANK:
value = null;
break;
case STRING:
value = cell.getStringCellValue();
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
try {
// Excel dates are LocalDateTime, stored without timezone.
// Interpret them as UTC to prevent ambiguous DST overlaps which happen in other
// timezones.
LocaleUtil.setUserTimeZone(LocaleUtil.TIMEZONE_UTC);
Date dateCellValue = cell.getDateCellValue();
value = formatUTCDateAsLocalDateTime(dateCellValue);
} finally {
LocaleUtil.resetUserTimeZone();
}
} else {
// excel stores integer values as double values
// read an integer if the double value equals the
// integer value
double x = cell.getNumericCellValue();
if (x == Math.rint(x) && !Double.isNaN(x) && !Double.isInfinite(x))
value = String.valueOf((long) x);
else value = String.valueOf(x);
}
break;
case BOOLEAN:
value = String.valueOf(cell.getBooleanCellValue());
break;
case FORMULA:
// evaluate formula
FormulaEvaluator evaluator =
cell.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator();
CellValue cellValue;
try {
cellValue = evaluator.evaluate(cell);
} catch (StackOverflowError e) {
LOG.error("StackOverflowError evaluating formula", e);
throw new RuntimeException(
"Error evaluating formula, possibly due to deep formula nesting.");
}
switch (cellValue.getCellTypeEnum()) {
case BOOLEAN:
value = String.valueOf(cellValue.getBooleanValue());
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
try {
// Excel dates are LocalDateTime, stored without timezone.
// Interpret them as UTC to prevent ambiguous DST overlaps which happen in other
// timezones.
LocaleUtil.setUserTimeZone(LocaleUtil.TIMEZONE_UTC);
Date javaDate = DateUtil.getJavaDate(cellValue.getNumberValue(), false);
value = formatUTCDateAsLocalDateTime(javaDate);
} finally {
LocaleUtil.resetUserTimeZone();
}
} else {
// excel stores integer values as double values
// read an integer if the double value equals the
// integer value
double x = cellValue.getNumberValue();
if (x == Math.rint(x) && !Double.isNaN(x) && !Double.isInfinite(x))
value = String.valueOf((long) x);
else value = String.valueOf(x);
}
break;
case STRING:
value = cellValue.getStringValue();
break;
case BLANK:
value = null;
break;
default:
throw new MolgenisDataException(
"unsupported cell type: " + cellValue.getCellTypeEnum());
}
break;
default:
throw new MolgenisDataException("unsupported cell type: " + cell.getCellTypeEnum());
}
return AbstractCellProcessor.processCell(value, false, cellProcessors);
} } | public class class_name {
static String toValue(Cell cell, List<CellProcessor> cellProcessors) {
String value;
switch (cell.getCellTypeEnum()) {
case BLANK:
value = null;
break;
case STRING:
value = cell.getStringCellValue();
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
try {
// Excel dates are LocalDateTime, stored without timezone.
// Interpret them as UTC to prevent ambiguous DST overlaps which happen in other
// timezones.
LocaleUtil.setUserTimeZone(LocaleUtil.TIMEZONE_UTC); // depends on control dependency: [try], data = [none]
Date dateCellValue = cell.getDateCellValue();
value = formatUTCDateAsLocalDateTime(dateCellValue); // depends on control dependency: [try], data = [none]
} finally {
LocaleUtil.resetUserTimeZone();
}
} else {
// excel stores integer values as double values
// read an integer if the double value equals the
// integer value
double x = cell.getNumericCellValue();
if (x == Math.rint(x) && !Double.isNaN(x) && !Double.isInfinite(x))
value = String.valueOf((long) x);
else value = String.valueOf(x);
}
break;
case BOOLEAN:
value = String.valueOf(cell.getBooleanCellValue());
break;
case FORMULA:
// evaluate formula
FormulaEvaluator evaluator =
cell.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator();
CellValue cellValue;
try {
cellValue = evaluator.evaluate(cell); // depends on control dependency: [try], data = [none]
} catch (StackOverflowError e) {
LOG.error("StackOverflowError evaluating formula", e);
throw new RuntimeException(
"Error evaluating formula, possibly due to deep formula nesting.");
} // depends on control dependency: [catch], data = [none]
switch (cellValue.getCellTypeEnum()) {
case BOOLEAN:
value = String.valueOf(cellValue.getBooleanValue());
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
try {
// Excel dates are LocalDateTime, stored without timezone.
// Interpret them as UTC to prevent ambiguous DST overlaps which happen in other
// timezones.
LocaleUtil.setUserTimeZone(LocaleUtil.TIMEZONE_UTC); // depends on control dependency: [try], data = [none]
Date javaDate = DateUtil.getJavaDate(cellValue.getNumberValue(), false);
value = formatUTCDateAsLocalDateTime(javaDate); // depends on control dependency: [try], data = [none]
} finally {
LocaleUtil.resetUserTimeZone();
}
} else {
// excel stores integer values as double values
// read an integer if the double value equals the
// integer value
double x = cellValue.getNumberValue();
if (x == Math.rint(x) && !Double.isNaN(x) && !Double.isInfinite(x))
value = String.valueOf((long) x);
else value = String.valueOf(x);
}
break;
case STRING:
value = cellValue.getStringValue();
break;
case BLANK:
value = null;
break;
default:
throw new MolgenisDataException(
"unsupported cell type: " + cellValue.getCellTypeEnum());
}
break;
default:
throw new MolgenisDataException("unsupported cell type: " + cell.getCellTypeEnum());
}
return AbstractCellProcessor.processCell(value, false, cellProcessors);
} } |
public class class_name {
public static <Param> PathParamSerializer<Param> required(String name, Function<String, Param> deserialize,
Function<Param, String> serialize) {
return new NamedPathParamSerializer<Param>(name) {
@Override
public PSequence<String> serialize(Param parameter) {
return TreePVector.singleton(serialize.apply(parameter));
}
@Override
public Param deserialize(PSequence<String> parameters) {
if (parameters.isEmpty()) {
throw new IllegalArgumentException(name + " parameter is required");
} else {
return deserialize.apply(parameters.get(0));
}
}
};
} } | public class class_name {
public static <Param> PathParamSerializer<Param> required(String name, Function<String, Param> deserialize,
Function<Param, String> serialize) {
return new NamedPathParamSerializer<Param>(name) {
@Override
public PSequence<String> serialize(Param parameter) {
return TreePVector.singleton(serialize.apply(parameter));
}
@Override
public Param deserialize(PSequence<String> parameters) {
if (parameters.isEmpty()) {
throw new IllegalArgumentException(name + " parameter is required");
} else {
return deserialize.apply(parameters.get(0)); // depends on control dependency: [if], data = [none]
}
}
};
} } |
public class class_name {
protected void createPropertyControlDataObject(Root inputRootDataObject, String inputProperty) {
// use the root DataGraph to create a PropertyControl DataGraph
List<Control> propertyControls = inputRootDataObject.getControls();
PropertyControl propCtrl = null;
if (propertyControls != null) {
propCtrl = new PropertyControl();
propertyControls.add(propCtrl);
}
// add the requested property to the return list of properties
if (propCtrl != null) {
propCtrl.getProperties().add(inputProperty);
}
} } | public class class_name {
protected void createPropertyControlDataObject(Root inputRootDataObject, String inputProperty) {
// use the root DataGraph to create a PropertyControl DataGraph
List<Control> propertyControls = inputRootDataObject.getControls();
PropertyControl propCtrl = null;
if (propertyControls != null) {
propCtrl = new PropertyControl(); // depends on control dependency: [if], data = [none]
propertyControls.add(propCtrl); // depends on control dependency: [if], data = [none]
}
// add the requested property to the return list of properties
if (propCtrl != null) {
propCtrl.getProperties().add(inputProperty); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void close() {
try {
synchronized (lock) {
if (out == null)
return;
out.close();
out = null;
}
}
catch (IOException x) {
trouble = true;
}
} } | public class class_name {
public void close() {
try {
synchronized (lock) { // depends on control dependency: [try], data = [none]
if (out == null)
return;
out.close();
out = null;
}
}
catch (IOException x) {
trouble = true;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public boolean hasAnnotation(Element element, Class<? extends Annotation> ann) {
List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
for (AnnotationMirror annotationMirror : annotationMirrors) {
if (annotationMirror.getAnnotationType().toString().equals(ann.getName())) {
return true;
}
}
return false;
} } | public class class_name {
@Override
public boolean hasAnnotation(Element element, Class<? extends Annotation> ann) {
List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
for (AnnotationMirror annotationMirror : annotationMirrors) {
if (annotationMirror.getAnnotationType().toString().equals(ann.getName())) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
public void writeLE(final long n, final int b) {
long v = n;
for (int i = 0; i < b; i++) {
write((byte) (v & 0xff));
v >>= 8;
}
} } | public class class_name {
public void writeLE(final long n, final int b) {
long v = n;
for (int i = 0; i < b; i++) {
write((byte) (v & 0xff)); // depends on control dependency: [for], data = [none]
v >>= 8; // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
static
public Function getFunction(String name){
if(name == null){
return null;
} // End if
if(FunctionRegistry.functions.containsKey(name)){
Function function = FunctionRegistry.functions.get(name);
return function;
}
Class<?> functionClazz;
if(FunctionRegistry.functionClazzes.containsKey(name)){
functionClazz = FunctionRegistry.functionClazzes.get(name);
} else
{
functionClazz = loadFunctionClass(name);
FunctionRegistry.functionClazzes.put(name, functionClazz);
} // End if
if(functionClazz != null){
Function function;
try {
function = (Function)functionClazz.newInstance();
} catch(IllegalAccessException | InstantiationException | ExceptionInInitializerError e){
throw new EvaluationException("Function class " + PMMLException.formatKey(functionClazz.getName()) + " could not be instantiated")
.initCause(e);
}
return function;
}
return null;
} } | public class class_name {
static
public Function getFunction(String name){
if(name == null){
return null; // depends on control dependency: [if], data = [none]
} // End if
if(FunctionRegistry.functions.containsKey(name)){
Function function = FunctionRegistry.functions.get(name);
return function; // depends on control dependency: [if], data = [none]
}
Class<?> functionClazz;
if(FunctionRegistry.functionClazzes.containsKey(name)){
functionClazz = FunctionRegistry.functionClazzes.get(name); // depends on control dependency: [if], data = [none]
} else
{
functionClazz = loadFunctionClass(name); // depends on control dependency: [if], data = [none]
FunctionRegistry.functionClazzes.put(name, functionClazz); // depends on control dependency: [if], data = [none]
} // End if
if(functionClazz != null){
Function function;
try {
function = (Function)functionClazz.newInstance(); // depends on control dependency: [try], data = [none]
} catch(IllegalAccessException | InstantiationException | ExceptionInInitializerError e){
throw new EvaluationException("Function class " + PMMLException.formatKey(functionClazz.getName()) + " could not be instantiated")
.initCause(e);
} // depends on control dependency: [catch], data = [none]
return function; // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
@Override
public String getItemValue()
{
String ret = null;
try {
if (this.autoComplete != null && this.autoComplete.getParent().isEditMode()
&& !EditValue.NONE.equals(this.autoComplete.getAutoCompleteSetting().getValue4Edit())) {
final Instance instance = this.autoComplete.getInstance();
if (instance != null && instance.isValid()) {
switch (this.autoComplete.getAutoCompleteSetting().getValue4Edit()) {
case OID:
ret = instance.getOid();
break;
case ID:
ret = String.valueOf(instance.getId());
break;
default:
break;
}
}
} else if (this.autoComplete != null
&& (this.autoComplete.getParent().isEditMode()
|| this.autoComplete.getParent().isCreateMode())
&& !this.autoComplete.getAutoCompleteSetting().isRequired()) {
ret = this.autoComplete.getAutoCompleteValue();
}
} catch (final EFapsException e) {
AutoCompleteComboBox.LOG.error("Error in getItemValue()", e);
}
return ret;
} } | public class class_name {
@Override
public String getItemValue()
{
String ret = null;
try {
if (this.autoComplete != null && this.autoComplete.getParent().isEditMode()
&& !EditValue.NONE.equals(this.autoComplete.getAutoCompleteSetting().getValue4Edit())) {
final Instance instance = this.autoComplete.getInstance();
if (instance != null && instance.isValid()) {
switch (this.autoComplete.getAutoCompleteSetting().getValue4Edit()) {
case OID:
ret = instance.getOid();
break;
case ID:
ret = String.valueOf(instance.getId());
break;
default:
break;
}
}
} else if (this.autoComplete != null
&& (this.autoComplete.getParent().isEditMode()
|| this.autoComplete.getParent().isCreateMode())
&& !this.autoComplete.getAutoCompleteSetting().isRequired()) {
ret = this.autoComplete.getAutoCompleteValue(); // depends on control dependency: [if], data = [none]
}
} catch (final EFapsException e) {
AutoCompleteComboBox.LOG.error("Error in getItemValue()", e);
} // depends on control dependency: [catch], data = [none]
return ret;
} } |
public class class_name {
@Nullable
public String getString(String name) {
Attribute attribute = get(name);
if (attribute == null) {
return null;
}
return attribute.getValue();
} } | public class class_name {
@Nullable
public String getString(String name) {
Attribute attribute = get(name);
if (attribute == null) {
return null; // depends on control dependency: [if], data = [none]
}
return attribute.getValue();
} } |
public class class_name {
public void marshall(OnPremConfig onPremConfig, ProtocolMarshaller protocolMarshaller) {
if (onPremConfig == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(onPremConfig.getAgentArns(), AGENTARNS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(OnPremConfig onPremConfig, ProtocolMarshaller protocolMarshaller) {
if (onPremConfig == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(onPremConfig.getAgentArns(), AGENTARNS_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public String getVarTypeName(Class<?> type,Type ...actTypes)
{
String varType=getVarTypeName(type);
if(actTypes!=null)
{
List<String> acts=new ArrayList<>();
for(Type act:actTypes)
{
acts.add(act.getTypeName());
}
if(!acts.isEmpty())
{
if(acts.size()==1)
{
varType+="<"+acts.remove(0)+">";
}else
{
varType+="<"+String.join(",", acts)+">";
}
}
}
varType=varType.replace('$','.');
return varType;
} } | public class class_name {
public String getVarTypeName(Class<?> type,Type ...actTypes)
{
String varType=getVarTypeName(type);
if(actTypes!=null)
{
List<String> acts=new ArrayList<>();
for(Type act:actTypes)
{
acts.add(act.getTypeName());
// depends on control dependency: [for], data = [act]
}
if(!acts.isEmpty())
{
if(acts.size()==1)
{
varType+="<"+acts.remove(0)+">";
// depends on control dependency: [if], data = [none]
}else
{
varType+="<"+String.join(",", acts)+">";
// depends on control dependency: [if], data = [none]
}
}
}
varType=varType.replace('$','.');
return varType;
} } |
public class class_name {
void submit() {
CmsObject cms = A_CmsUI.getCmsObject();
try {
List<CmsUUID> changedIds = Lists.newArrayList();
CmsResourceDeleteMode mode = (CmsResourceDeleteMode)m_deleteSiblings.getValue();
for (CmsResource resource : m_context.getResources()) {
changedIds.add(resource.getStructureId());
CmsLockActionRecord lockRecord = CmsLockUtil.ensureLock(cms, resource);
try {
cms.deleteResource(cms.getSitePath(resource), mode);
} finally {
if (lockRecord.getChange().equals(LockChange.locked)) {
if (!resource.getState().isNew()) {
try {
cms.unlockResource(resource);
} catch (CmsVfsResourceNotFoundException e) {
LOG.warn(e.getLocalizedMessage(), e);
} catch (CmsLockException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
}
}
}
}
m_context.finish(changedIds);
} catch (Exception e) {
m_context.error(e);
}
} } | public class class_name {
void submit() {
CmsObject cms = A_CmsUI.getCmsObject();
try {
List<CmsUUID> changedIds = Lists.newArrayList();
CmsResourceDeleteMode mode = (CmsResourceDeleteMode)m_deleteSiblings.getValue();
for (CmsResource resource : m_context.getResources()) {
changedIds.add(resource.getStructureId()); // depends on control dependency: [for], data = [resource]
CmsLockActionRecord lockRecord = CmsLockUtil.ensureLock(cms, resource);
try {
cms.deleteResource(cms.getSitePath(resource), mode); // depends on control dependency: [try], data = [none]
} finally {
if (lockRecord.getChange().equals(LockChange.locked)) {
if (!resource.getState().isNew()) {
try {
cms.unlockResource(resource); // depends on control dependency: [try], data = [none]
} catch (CmsVfsResourceNotFoundException e) {
LOG.warn(e.getLocalizedMessage(), e);
} catch (CmsLockException e) { // depends on control dependency: [catch], data = [none]
LOG.warn(e.getLocalizedMessage(), e);
} // depends on control dependency: [catch], data = [none]
}
}
}
}
m_context.finish(changedIds); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
m_context.error(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public void registerListener(IServletContext isc) {
CDIWebRuntime cdiWebRuntime = getCDIWebRuntime();
if (cdiWebRuntime != null && cdiWebRuntime.isCdiEnabled(isc)) {
ModuleMetaData moduleMetaData = getModuleMetaData(isc);
BeanManager beanManager = cdiWebRuntime.getModuleBeanManager(moduleMetaData);
if (beanManager != null) {
// check to see if the ConversationFilter is mapped. If so we need to set a context init property
// to prevent WeldInitialListener from doing conversation activation
List<IFilterMapping> filterMappings = isc.getWebAppConfig().getFilterMappings();
for (IFilterMapping filterMapping : filterMappings) {
IFilterConfig filterConfig = filterMapping.getFilterConfig();
if (CDIWebConstants.CDI_CONVERSATION_FILTER.equals(filterConfig.getFilterName())) {
isc.setInitParameter(CONVERSATION_FILTER_REGISTERED, Boolean.TRUE.toString());
}
}
/*
* Workaround jira https://issues.jboss.org/browse/WELD-1874
* To make sure that the WeldInitialListener has the correct beanManager we
* have to pass a BeanManagerImpl into the constructor, however we do not
* know if we have a BeanManagerImpl or a BeanManagerProxy.
*/
BeanManagerImpl beanManagerImpl = null;
if (beanManager instanceof BeanManagerProxy) {
BeanManagerProxy proxy = (BeanManagerProxy) beanManager;
beanManagerImpl = proxy.delegate();
} else if (beanManager instanceof BeanManagerImpl) {
beanManagerImpl = (BeanManagerImpl) beanManager;
} else {
throw new RuntimeException("Unexpected beanManager instance.");
}
EventListener weldInitialListener = WeldListenerFactory.newWeldInitialListener(beanManagerImpl);
isc.addListener(weldInitialListener);
isc.setAttribute(WELD_INITIAL_LISTENER_ATTRIBUTE, weldInitialListener);
//End of workaround
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "added WeldInitialListener to the servlet context");
//Put bean manager on the servlet context
isc.setAttribute("javax.enterprise.inject.spi.BeanManager", beanManager);
}
}
} } | public class class_name {
@Override
public void registerListener(IServletContext isc) {
CDIWebRuntime cdiWebRuntime = getCDIWebRuntime();
if (cdiWebRuntime != null && cdiWebRuntime.isCdiEnabled(isc)) {
ModuleMetaData moduleMetaData = getModuleMetaData(isc);
BeanManager beanManager = cdiWebRuntime.getModuleBeanManager(moduleMetaData);
if (beanManager != null) {
// check to see if the ConversationFilter is mapped. If so we need to set a context init property
// to prevent WeldInitialListener from doing conversation activation
List<IFilterMapping> filterMappings = isc.getWebAppConfig().getFilterMappings();
for (IFilterMapping filterMapping : filterMappings) {
IFilterConfig filterConfig = filterMapping.getFilterConfig();
if (CDIWebConstants.CDI_CONVERSATION_FILTER.equals(filterConfig.getFilterName())) {
isc.setInitParameter(CONVERSATION_FILTER_REGISTERED, Boolean.TRUE.toString()); // depends on control dependency: [if], data = [none]
}
}
/*
* Workaround jira https://issues.jboss.org/browse/WELD-1874
* To make sure that the WeldInitialListener has the correct beanManager we
* have to pass a BeanManagerImpl into the constructor, however we do not
* know if we have a BeanManagerImpl or a BeanManagerProxy.
*/
BeanManagerImpl beanManagerImpl = null;
if (beanManager instanceof BeanManagerProxy) {
BeanManagerProxy proxy = (BeanManagerProxy) beanManager;
beanManagerImpl = proxy.delegate(); // depends on control dependency: [if], data = [none]
} else if (beanManager instanceof BeanManagerImpl) {
beanManagerImpl = (BeanManagerImpl) beanManager; // depends on control dependency: [if], data = [none]
} else {
throw new RuntimeException("Unexpected beanManager instance.");
}
EventListener weldInitialListener = WeldListenerFactory.newWeldInitialListener(beanManagerImpl);
isc.addListener(weldInitialListener); // depends on control dependency: [if], data = [none]
isc.setAttribute(WELD_INITIAL_LISTENER_ATTRIBUTE, weldInitialListener); // depends on control dependency: [if], data = [none]
//End of workaround
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "added WeldInitialListener to the servlet context");
//Put bean manager on the servlet context
isc.setAttribute("javax.enterprise.inject.spi.BeanManager", beanManager); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public byte[] getAsByteArray(String key) {
Object value = mValues.get(key);
if (value instanceof byte[]) {
return (byte[]) value;
} else {
return new byte[]{};
}
}
/**
* Returns a set of all of the keys and values
*
* @return a set of all of the keys and values
*/
public Set<Map.Entry<String, Object>> valueSet() {
return mValues.entrySet();
}
/**
* Returns a set of all of the keys
*
* @return a set of all of the keys
*/
public Set<String> keySet() {
return mValues.keySet();
}
public int describeContents() {
return 0;
}
/**
* Returns a string containing a concise, human-readable description of this object.
* @return a printable representation of this object.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (String name : mValues.keySet()) {
String value = getAsString(name);
if (sb.length() > 0) sb.append(" ");
sb.append(name + "=" + value);
}
return sb.toString();
} } | public class class_name {
public byte[] getAsByteArray(String key) {
Object value = mValues.get(key);
if (value instanceof byte[]) {
return (byte[]) value; // depends on control dependency: [if], data = [none]
} else {
return new byte[]{}; // depends on control dependency: [if], data = [none]
}
}
/**
* Returns a set of all of the keys and values
*
* @return a set of all of the keys and values
*/
public Set<Map.Entry<String, Object>> valueSet() {
return mValues.entrySet();
}
/**
* Returns a set of all of the keys
*
* @return a set of all of the keys
*/
public Set<String> keySet() {
return mValues.keySet();
}
public int describeContents() {
return 0;
}
/**
* Returns a string containing a concise, human-readable description of this object.
* @return a printable representation of this object.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (String name : mValues.keySet()) {
String value = getAsString(name);
if (sb.length() > 0) sb.append(" ");
sb.append(name + "=" + value); // depends on control dependency: [for], data = [name]
}
return sb.toString();
} } |
public class class_name {
public int getAvailableHeight(int fixedContentHeight) {
if (m_buttonPanel.isVisible()) {
fixedContentHeight += m_buttonPanel.getOffsetHeight();
}
return Window.getClientHeight() - 150 - fixedContentHeight;
} } | public class class_name {
public int getAvailableHeight(int fixedContentHeight) {
if (m_buttonPanel.isVisible()) {
fixedContentHeight += m_buttonPanel.getOffsetHeight(); // depends on control dependency: [if], data = [none]
}
return Window.getClientHeight() - 150 - fixedContentHeight;
} } |
public class class_name {
public ModifyReservedInstancesRequest withReservedInstancesIds(String... reservedInstancesIds) {
if (this.reservedInstancesIds == null) {
setReservedInstancesIds(new com.amazonaws.internal.SdkInternalList<String>(reservedInstancesIds.length));
}
for (String ele : reservedInstancesIds) {
this.reservedInstancesIds.add(ele);
}
return this;
} } | public class class_name {
public ModifyReservedInstancesRequest withReservedInstancesIds(String... reservedInstancesIds) {
if (this.reservedInstancesIds == null) {
setReservedInstancesIds(new com.amazonaws.internal.SdkInternalList<String>(reservedInstancesIds.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : reservedInstancesIds) {
this.reservedInstancesIds.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
private boolean itemInItemStateList(List<ItemState> list, String itemId, int state)
{
boolean retval = false;
for (ItemState itemState : list)
{
if (itemState.getState() == state && itemState.getData().getIdentifier().equals(itemId))
{
retval = true;
break;
}
}
return retval;
} } | public class class_name {
private boolean itemInItemStateList(List<ItemState> list, String itemId, int state)
{
boolean retval = false;
for (ItemState itemState : list)
{
if (itemState.getState() == state && itemState.getData().getIdentifier().equals(itemId))
{
retval = true; // depends on control dependency: [if], data = [none]
break;
}
}
return retval;
} } |
public class class_name {
public static List<String> getImageIds( String formString ) throws Exception {
List<String> imageIds = new ArrayList<String>();
if (formString != null && formString.length() > 0) {
JSONObject sectionObject = new JSONObject(formString);
List<String> formsNames = Utilities.getFormNames4Section(sectionObject);
for( String formName : formsNames ) {
JSONObject form4Name = Utilities.getForm4Name(formName, sectionObject);
JSONArray formItems = Utilities.getFormItems(form4Name);
for( int i = 0; i < formItems.length(); i++ ) {
JSONObject formItem = formItems.getJSONObject(i);
if (!formItem.has(Utilities.TAG_KEY)) {
continue;
}
String type = formItem.getString(Utilities.TAG_TYPE);
String value = "";
if (formItem.has(Utilities.TAG_VALUE))
value = formItem.getString(Utilities.TAG_VALUE);
if (type.equals(Utilities.TYPE_PICTURES)) {
if (value.trim().length() == 0) {
continue;
}
String[] imageSplit = value.split(";");
Collections.addAll(imageIds, imageSplit);
} else if (type.equals(Utilities.TYPE_MAP)) {
if (value.trim().length() == 0) {
continue;
}
String image = value.trim();
imageIds.add(image);
} else if (type.equals(Utilities.TYPE_SKETCH)) {
if (value.trim().length() == 0) {
continue;
}
String[] imageSplit = value.split(";");
Collections.addAll(imageIds, imageSplit);
}
}
}
}
return imageIds;
} } | public class class_name {
public static List<String> getImageIds( String formString ) throws Exception {
List<String> imageIds = new ArrayList<String>();
if (formString != null && formString.length() > 0) {
JSONObject sectionObject = new JSONObject(formString);
List<String> formsNames = Utilities.getFormNames4Section(sectionObject);
for( String formName : formsNames ) {
JSONObject form4Name = Utilities.getForm4Name(formName, sectionObject);
JSONArray formItems = Utilities.getFormItems(form4Name);
for( int i = 0; i < formItems.length(); i++ ) {
JSONObject formItem = formItems.getJSONObject(i);
if (!formItem.has(Utilities.TAG_KEY)) {
continue;
}
String type = formItem.getString(Utilities.TAG_TYPE);
String value = "";
if (formItem.has(Utilities.TAG_VALUE))
value = formItem.getString(Utilities.TAG_VALUE);
if (type.equals(Utilities.TYPE_PICTURES)) {
if (value.trim().length() == 0) {
continue;
}
String[] imageSplit = value.split(";");
Collections.addAll(imageIds, imageSplit); // depends on control dependency: [if], data = [none]
} else if (type.equals(Utilities.TYPE_MAP)) {
if (value.trim().length() == 0) {
continue;
}
String image = value.trim();
imageIds.add(image); // depends on control dependency: [if], data = [none]
} else if (type.equals(Utilities.TYPE_SKETCH)) {
if (value.trim().length() == 0) {
continue;
}
String[] imageSplit = value.split(";");
Collections.addAll(imageIds, imageSplit); // depends on control dependency: [if], data = [none]
}
}
}
}
return imageIds;
} } |
public class class_name {
public static byte[] loadBytesFromStream(InputStream stream) {
try {
BufferedInputStream bis = new BufferedInputStream(stream);
byte[] theData = new byte[10000000];
int dataReadSoFar = 0;
byte[] buffer = new byte[1024];
int read = 0;
while ((read = bis.read(buffer)) != -1) {
System.arraycopy(buffer, 0, theData, dataReadSoFar, read);
dataReadSoFar += read;
}
bis.close();
// Resize to actual data read
byte[] returnData = new byte[dataReadSoFar];
System.arraycopy(theData, 0, returnData, 0, dataReadSoFar);
return returnData;
}
catch (IOException e) {
throw new RuntimeException(e);
}
} } | public class class_name {
public static byte[] loadBytesFromStream(InputStream stream) {
try {
BufferedInputStream bis = new BufferedInputStream(stream);
byte[] theData = new byte[10000000];
int dataReadSoFar = 0;
byte[] buffer = new byte[1024];
int read = 0;
while ((read = bis.read(buffer)) != -1) {
System.arraycopy(buffer, 0, theData, dataReadSoFar, read); // depends on control dependency: [while], data = [none]
dataReadSoFar += read; // depends on control dependency: [while], data = [none]
}
bis.close(); // depends on control dependency: [try], data = [none]
// Resize to actual data read
byte[] returnData = new byte[dataReadSoFar];
System.arraycopy(theData, 0, returnData, 0, dataReadSoFar); // depends on control dependency: [try], data = [none]
return returnData; // depends on control dependency: [try], data = [none]
}
catch (IOException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
synchronized public static void loadAdapters(String configFile) {
InputStream is = CpoClassLoader.getResourceAsStream(configFile);
if (is == null) {
logger.info("Resource Not Found: " + configFile);
try {
is = new FileInputStream(configFile);
} catch (FileNotFoundException fnfe) {
logger.info("File Not Found: " + configFile);
is = null;
}
}
try {
CpoConfigDocument configDoc;
if (is == null) {
configDoc = CpoConfigDocument.Factory.parse(configFile);
} else {
configDoc = CpoConfigDocument.Factory.parse(is);
}
String errMsg = XmlBeansHelper.validateXml(configDoc);
if (errMsg != null) {
logger.error("Invalid CPO Config file: " + configFile + ":" + errMsg);
} else {
logger.info("Processing Config File: " + configFile);
// Moving the clear to here to make sure we get a good file before we just blow away all the adapters.
// We are doing a load clear all the caches first, in case the load gets called more than once.
CpoMetaDescriptor.clearAllInstances();
clearCpoAdapterFactoryCache();
CtCpoConfig cpoConfig = configDoc.getCpoConfig();
// Set the default context.
if (cpoConfig.isSetDefaultConfig()) {
defaultContext = cpoConfig.getDefaultConfig();
} else {
// make the first listed config the default.
defaultContext = cpoConfig.getDataConfigArray(0).getName();
}
for (CtMetaDescriptor metaDescriptor : cpoConfig.getMetaConfigArray()) {
boolean caseSensitive = true;
if (metaDescriptor.isSetCaseSensitive()) {
caseSensitive = metaDescriptor.getCaseSensitive();
}
// this will create and cache, so we don't need the return
CpoMetaDescriptor.getInstance(metaDescriptor.getName(), metaDescriptor.getMetaXmlArray(), caseSensitive);
}
// now lets loop through all the adapters and get them cached.
for (CtDataSourceConfig dataSourceConfig : cpoConfig.getDataConfigArray()) {
CpoAdapterFactory cpoAdapterFactory = makeCpoAdapterFactory(dataSourceConfig);
if (cpoAdapterFactory != null) {
addCpoAdapterFactory(dataSourceConfig.getName(), cpoAdapterFactory);
}
}
}
} catch (IOException ioe) {
logger.error("Error reading " + configFile + ": ", ioe);
} catch (XmlException xe) {
logger.error("Error processing " + configFile + ": Invalid XML");
} catch (CpoException ce) {
logger.error("Error processing " + configFile + ": ", ce);
}
} } | public class class_name {
synchronized public static void loadAdapters(String configFile) {
InputStream is = CpoClassLoader.getResourceAsStream(configFile);
if (is == null) {
logger.info("Resource Not Found: " + configFile); // depends on control dependency: [if], data = [none]
try {
is = new FileInputStream(configFile); // depends on control dependency: [try], data = [none]
} catch (FileNotFoundException fnfe) {
logger.info("File Not Found: " + configFile);
is = null;
} // depends on control dependency: [catch], data = [none]
}
try {
CpoConfigDocument configDoc;
if (is == null) {
configDoc = CpoConfigDocument.Factory.parse(configFile); // depends on control dependency: [if], data = [none]
} else {
configDoc = CpoConfigDocument.Factory.parse(is); // depends on control dependency: [if], data = [(is]
}
String errMsg = XmlBeansHelper.validateXml(configDoc);
if (errMsg != null) {
logger.error("Invalid CPO Config file: " + configFile + ":" + errMsg); // depends on control dependency: [if], data = [none]
} else {
logger.info("Processing Config File: " + configFile); // depends on control dependency: [if], data = [none]
// Moving the clear to here to make sure we get a good file before we just blow away all the adapters.
// We are doing a load clear all the caches first, in case the load gets called more than once.
CpoMetaDescriptor.clearAllInstances(); // depends on control dependency: [if], data = [none]
clearCpoAdapterFactoryCache(); // depends on control dependency: [if], data = [none]
CtCpoConfig cpoConfig = configDoc.getCpoConfig();
// Set the default context.
if (cpoConfig.isSetDefaultConfig()) {
defaultContext = cpoConfig.getDefaultConfig(); // depends on control dependency: [if], data = [none]
} else {
// make the first listed config the default.
defaultContext = cpoConfig.getDataConfigArray(0).getName(); // depends on control dependency: [if], data = [none]
}
for (CtMetaDescriptor metaDescriptor : cpoConfig.getMetaConfigArray()) {
boolean caseSensitive = true;
if (metaDescriptor.isSetCaseSensitive()) {
caseSensitive = metaDescriptor.getCaseSensitive(); // depends on control dependency: [if], data = [none]
}
// this will create and cache, so we don't need the return
CpoMetaDescriptor.getInstance(metaDescriptor.getName(), metaDescriptor.getMetaXmlArray(), caseSensitive); // depends on control dependency: [for], data = [metaDescriptor]
}
// now lets loop through all the adapters and get them cached.
for (CtDataSourceConfig dataSourceConfig : cpoConfig.getDataConfigArray()) {
CpoAdapterFactory cpoAdapterFactory = makeCpoAdapterFactory(dataSourceConfig);
if (cpoAdapterFactory != null) {
addCpoAdapterFactory(dataSourceConfig.getName(), cpoAdapterFactory); // depends on control dependency: [if], data = [none]
}
}
}
} catch (IOException ioe) {
logger.error("Error reading " + configFile + ": ", ioe);
} catch (XmlException xe) { // depends on control dependency: [catch], data = [none]
logger.error("Error processing " + configFile + ": Invalid XML");
} catch (CpoException ce) { // depends on control dependency: [catch], data = [none]
logger.error("Error processing " + configFile + ": ", ce);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private boolean isaConversionClass(JavaClass conversionCls) {
for (AnnotationEntry entry : conversionCls.getAnnotationEntries()) {
if (CONVERSION_ANNOTATIONS.contains(entry.getAnnotationType())) {
return true;
}
// this ignores the fact that this class might be a grand child, but meh
if (CONVERSION_SUPER_CLASSES.contains(conversionCls.getSuperclassName())) {
return true;
}
}
return false;
} } | public class class_name {
private boolean isaConversionClass(JavaClass conversionCls) {
for (AnnotationEntry entry : conversionCls.getAnnotationEntries()) {
if (CONVERSION_ANNOTATIONS.contains(entry.getAnnotationType())) {
return true; // depends on control dependency: [if], data = [none]
}
// this ignores the fact that this class might be a grand child, but meh
if (CONVERSION_SUPER_CLASSES.contains(conversionCls.getSuperclassName())) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
public byte[] lastData()
{
if (tc.isEntryEnabled()) Tr.entry(tc, "lastData",this);
byte[] lastData = null;
// Assuming that we have actually added data to this section, '_lastData' always
// references the last data item that was stored inside the recoverable unit
// section. Retireve any data content and return it.
if (_lastDataItem != null)
{
lastData = _lastDataItem.getData();
}
if (tc.isEntryEnabled()) Tr.exit(tc, "lastData",RLSUtils.toHexString(lastData,RLSUtils.MAX_DISPLAY_BYTES));
return lastData;
} } | public class class_name {
public byte[] lastData()
{
if (tc.isEntryEnabled()) Tr.entry(tc, "lastData",this);
byte[] lastData = null;
// Assuming that we have actually added data to this section, '_lastData' always
// references the last data item that was stored inside the recoverable unit
// section. Retireve any data content and return it.
if (_lastDataItem != null)
{
lastData = _lastDataItem.getData(); // depends on control dependency: [if], data = [none]
}
if (tc.isEntryEnabled()) Tr.exit(tc, "lastData",RLSUtils.toHexString(lastData,RLSUtils.MAX_DISPLAY_BYTES));
return lastData;
} } |
public class class_name {
private void handleFailedSlotRequest(SlotID slotId, AllocationID allocationId, Throwable cause) {
PendingSlotRequest pendingSlotRequest = pendingSlotRequests.get(allocationId);
LOG.debug("Slot request with allocation id {} failed for slot {}.", allocationId, slotId, cause);
if (null != pendingSlotRequest) {
pendingSlotRequest.setRequestFuture(null);
try {
internalRequestSlot(pendingSlotRequest);
} catch (ResourceManagerException e) {
pendingSlotRequests.remove(allocationId);
resourceActions.notifyAllocationFailure(
pendingSlotRequest.getJobId(),
allocationId,
e);
}
} else {
LOG.debug("There was not pending slot request with allocation id {}. Probably the request has been fulfilled or cancelled.", allocationId);
}
} } | public class class_name {
private void handleFailedSlotRequest(SlotID slotId, AllocationID allocationId, Throwable cause) {
PendingSlotRequest pendingSlotRequest = pendingSlotRequests.get(allocationId);
LOG.debug("Slot request with allocation id {} failed for slot {}.", allocationId, slotId, cause);
if (null != pendingSlotRequest) {
pendingSlotRequest.setRequestFuture(null); // depends on control dependency: [if], data = [(null]
try {
internalRequestSlot(pendingSlotRequest); // depends on control dependency: [try], data = [none]
} catch (ResourceManagerException e) {
pendingSlotRequests.remove(allocationId);
resourceActions.notifyAllocationFailure(
pendingSlotRequest.getJobId(),
allocationId,
e);
} // depends on control dependency: [catch], data = [none]
} else {
LOG.debug("There was not pending slot request with allocation id {}. Probably the request has been fulfilled or cancelled.", allocationId); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
static public remoteLocation extractLocationAndPath(String stageLocationPath)
{
String location = stageLocationPath;
String path = "";
// split stage location as location name and path
if (stageLocationPath.contains("/"))
{
location = stageLocationPath.substring(0, stageLocationPath.indexOf("/"));
path = stageLocationPath.substring(stageLocationPath.indexOf("/") + 1);
}
return new remoteLocation(location, path);
} } | public class class_name {
static public remoteLocation extractLocationAndPath(String stageLocationPath)
{
String location = stageLocationPath;
String path = "";
// split stage location as location name and path
if (stageLocationPath.contains("/"))
{
location = stageLocationPath.substring(0, stageLocationPath.indexOf("/")); // depends on control dependency: [if], data = [none]
path = stageLocationPath.substring(stageLocationPath.indexOf("/") + 1); // depends on control dependency: [if], data = [none]
}
return new remoteLocation(location, path);
} } |
public class class_name {
public static byte[] getBufferByteArray(BufferedImage image) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(image, "png", os);
} catch (IOException e) {
logger.error("getBufferByteArray error", e);
}
return os.toByteArray();
} } | public class class_name {
public static byte[] getBufferByteArray(BufferedImage image) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(image, "png", os); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
logger.error("getBufferByteArray error", e);
} // depends on control dependency: [catch], data = [none]
return os.toByteArray();
} } |
public class class_name {
private void restoreDefaults(@NonNull final PreferenceGroup preferenceGroup,
@NonNull final SharedPreferences sharedPreferences) {
for (int i = 0; i < preferenceGroup.getPreferenceCount(); i++) {
Preference preference = preferenceGroup.getPreference(i);
if (preference instanceof PreferenceGroup) {
restoreDefaults((PreferenceGroup) preference, sharedPreferences);
} else if (preference.getKey() != null && !preference.getKey().isEmpty()) {
Object oldValue = sharedPreferences.getAll().get(preference.getKey());
if (notifyOnRestoreDefaultValueRequested(preference, oldValue)) {
sharedPreferences.edit().remove(preference.getKey()).apply();
preferenceGroup.removePreference(preference);
preferenceGroup.addPreference(preference);
Object newValue = sharedPreferences.getAll().get(preference.getKey());
notifyOnRestoredDefaultValue(preference, oldValue, newValue);
} else {
preferenceGroup.removePreference(preference);
preferenceGroup.addPreference(preference);
}
}
}
} } | public class class_name {
private void restoreDefaults(@NonNull final PreferenceGroup preferenceGroup,
@NonNull final SharedPreferences sharedPreferences) {
for (int i = 0; i < preferenceGroup.getPreferenceCount(); i++) {
Preference preference = preferenceGroup.getPreference(i);
if (preference instanceof PreferenceGroup) {
restoreDefaults((PreferenceGroup) preference, sharedPreferences); // depends on control dependency: [if], data = [none]
} else if (preference.getKey() != null && !preference.getKey().isEmpty()) {
Object oldValue = sharedPreferences.getAll().get(preference.getKey());
if (notifyOnRestoreDefaultValueRequested(preference, oldValue)) {
sharedPreferences.edit().remove(preference.getKey()).apply(); // depends on control dependency: [if], data = [none]
preferenceGroup.removePreference(preference); // depends on control dependency: [if], data = [none]
preferenceGroup.addPreference(preference); // depends on control dependency: [if], data = [none]
Object newValue = sharedPreferences.getAll().get(preference.getKey());
notifyOnRestoredDefaultValue(preference, oldValue, newValue); // depends on control dependency: [if], data = [none]
} else {
preferenceGroup.removePreference(preference); // depends on control dependency: [if], data = [none]
preferenceGroup.addPreference(preference); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
public static boolean check(Map<String, Object> m, Map<String, Object> r) {
if (r.get(m.get("cmd")).equals("OK")) {
return true;
}
return false;
} } | public class class_name {
public static boolean check(Map<String, Object> m, Map<String, Object> r) {
if (r.get(m.get("cmd")).equals("OK")) {
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public void associate(CredentialsService credService, WSSecurityService securityService, UnauthenticatedSubjectService unauthSubjService, AuthenticationService authService,
WorkContext workCtx, String providerId)
throws WorkCompletedException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "associate", new Object[] { J2CSecurityHelper.objectId(workCtx), providerId });
}
// Check if application security is enabled and only in that case
// do the security context association.
if (WSSecurityHelper.isServerSecurityEnabled()) {
TraceNLS nls = J2CSecurityHelper.getNLS();
try {
UserRegistry registry = securityService.getUserRegistry(null);
final String appRealm = registry != null ? registry.getRealm() : null;
// The code below extracts the security work context and invokes
// setupSecurityContext on it passing in the callback handler and the
// execution and server subjects.
SecurityContext sc = (SecurityContext) workCtx;
final Subject executionSubject = new Subject();
J2CSecurityCallbackHandler handler = new J2CSecurityCallbackHandler(executionSubject, appRealm, credService.getUnauthenticatedUserid()); // Change from twas - jms - Setting to null for now - //cm.getUnauthenticatedString());
Subject serverSubject = null;
sc.setupSecurityContext(handler, executionSubject, serverSubject);
SubjectHelper subjectHelper = new SubjectHelper();
WSCredential credential = subjectHelper.getWSCredential(executionSubject);
// check if the Subject is already authenticated i.e it contains WebSphere credentials.
if (credential != null) {
if (handler.getInvocations()[0] == Invocation.CALLERPRINCIPALCALLBACK || // Begin 673415
handler.getInvocations()[1] == Invocation.GROUPPRINCIPALCALLBACK ||
handler.getInvocations()[2] == Invocation.PASSWORDVALIDATIONCALLBACK) {
String message = nls.getString("AUTHENTICATED_SUBJECT_AND_CALLBACK_NOT_SUPPORTED_J2CA0677",
"J2CA0677E: " +
"An authenticated JAAS Subject and one or more JASPIC callbacks were passed to the application server " +
"by the resource adapter."); // End 673415
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "associate");
}
throw new WSSecurityException(message);
} else if (appRealm.equals(credential.getRealmName()) || RegistryHelper.isRealmInboundTrusted(credential.getRealmName(), appRealm)) { // Begin 673415
J2CSecurityHelper.setRunAsSubject(executionSubject);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "associate");
}
return;
} else {
String message = nls.getFormattedMessage("REALM_IS_NOT_TRUSTED_J2CA0685", new Object[] { null }, "REALM_IS_NOT_TRUSTED_J2CA0685"); // Change from twas - jms - TODO check on this - credential.getRealmName() changed to null
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "associate");
}
throw new WSSecurityException(message);
}
}
// After the invocation of the setupSecurityContext the execution subject will be
// populated with the result of handling the callbacks that are passed in to the
// handle method of the callback handler. The result is a custom hashtable that can
// be used for security to do a hashtable login. The resource adapter can also modify
// the execution subject by adding a principal. The code below checks for the result and
// if the result is null or empty after the invocation of the callbacks throws an Exception
// See JCA 1.6 Spec 16.4.1.
Hashtable<String, Object> cred = J2CSecurityHelper.getCustomCredentials(executionSubject, handler.getCacheKey());
Set<Principal> principals = executionSubject.getPrincipals(); // 675546
if (handler.getInvocations()[0] == Invocation.CALLERPRINCIPALCALLBACK) {
if (cred == null || !cred.containsKey(AttributeNameConstants.WSCREDENTIAL_SECURITYNAME)) {
String message = nls.getString("CUSTOM_CREDENTIALS_MISSING_J2CA0668",
"J2CA0668E: The WorkManager was unable to "
+
"populate the execution subject with the caller principal or credentials necessary to establish the security "
+
"context for this Work instance.");
throw new WSSecurityException(message);
}
} else if ((handler.getInvocations()[1] == Invocation.GROUPPRINCIPALCALLBACK // Begin 673415
|| handler.getInvocations()[2] == Invocation.PASSWORDVALIDATIONCALLBACK)
&& principals.size() != 1) { //675546
// If CallerPrincipalCallback was not provided but other callbacks were provided then do not
// allow the security context to be setup. See next comment for the reason
String message = nls.getString("CALLERPRINCIPAL_NOT_PROVIDED_J2CA0669",
"J2CA0669E: The resource adapter " +
"did not provide a CallerPrincipalCallback, an execution subject containing a single principal, or an empty " +
"execution subject.");
throw new WSSecurityException(message);
} else { // End 673415
// As per the JCA 1.6 Spec(16.4.5) the CallerPrincipalCallback should always be called except if the
// Resource Adapter wants to establish the UNAUTHENTICATED Identity by passing in an empty
// subject or when it passes a single principal in the principal set of the subject in which
// case we handle it like a CallerPrincipalCallback is passed with that principal.
if (principals.isEmpty()) {
CallerPrincipalCallback cpCallback = new CallerPrincipalCallback(executionSubject, (String) null);
handler.handle(new Callback[] { cpCallback });
} else if (principals.size() == 1) {
CallerPrincipalCallback cpCallback = new CallerPrincipalCallback(executionSubject, principals.iterator().next());
executionSubject.getPrincipals().clear(); // 673415
handler.handle(new Callback[] { cpCallback });
} else {
String message = nls.getString("CALLERPRINCIPAL_NOT_PROVIDED_J2CA0669",
"J2CA0669E: The resource adapter "
+
"did not provide a CallerPrincipalCallback, an execution subject containing a single principal, or an empty "
+
"execution subject.");
throw new WSSecurityException(message);
}
// Refresh the cred variable since we are calling the handler here.
cred = J2CSecurityHelper.getCustomCredentials(executionSubject, handler.getCacheKey());
}
// Do a custom hashtable login to get the runAs subject and set it on a ThreadLocal
// so that we can retrieve it later in the WorkProxy to establish as the RunAs and Caller
// subject.
final String userName = (String) cred.get(AttributeNameConstants.WSCREDENTIAL_SECURITYNAME);
Subject runAsSubject = null;
if (userName.equals(credService.getUnauthenticatedUserid())) {
runAsSubject = unauthSubjService.getUnauthenticatedSubject();
} else {
final AuthenticationService authServ = authService;
PrivilegedExceptionAction<Subject> loginAction = new PrivilegedExceptionAction<Subject>() {
@Override
public Subject run() throws Exception {
return authServ.authenticate(JaasLoginConfigConstants.SYSTEM_DEFAULT, executionSubject);
}
};
runAsSubject = AccessController.doPrivileged(loginAction);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "The RunAs subject is created after a successful login.");
}
J2CSecurityHelper.setRunAsSubject(runAsSubject);
} catch (RuntimeException e) {
Tr.error(tc, "SECURITY_CONTEXT_NOT_ASSOCIATED_J2CA0671", e);
String message = nls.getString("SECURITY_CONTEXT_NOT_ASSOCIATED_J2CA0671",
"J2CA0671E: The WorkManager was unable to associate the inflown SecurityContext to the Work instance.");
WorkCompletedException workCompEx = new WorkCompletedException(
message, WorkException.INTERNAL);
workCompEx.initCause(e);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "associate");
}
throw workCompEx;
} catch (Exception e) {
Tr.error(tc, "SECURITY_CONTEXT_NOT_ASSOCIATED_J2CA0671", e);
String message = nls.getString("SECURITY_CONTEXT_NOT_ASSOCIATED_J2CA0671",
"J2CA0671E: The WorkManager was unable to associate the inflown SecurityContext to the Work instance.");
WorkCompletedException workCompEx = new WorkCompletedException(
message, WorkException.INTERNAL);
workCompEx.initCause(e);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "associate");
}
throw workCompEx;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "associate");
}
} else {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "associate", "Application security is not enabled for the application server.");
}
}
} } | public class class_name {
public void associate(CredentialsService credService, WSSecurityService securityService, UnauthenticatedSubjectService unauthSubjService, AuthenticationService authService,
WorkContext workCtx, String providerId)
throws WorkCompletedException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "associate", new Object[] { J2CSecurityHelper.objectId(workCtx), providerId });
}
// Check if application security is enabled and only in that case
// do the security context association.
if (WSSecurityHelper.isServerSecurityEnabled()) {
TraceNLS nls = J2CSecurityHelper.getNLS();
try {
UserRegistry registry = securityService.getUserRegistry(null);
final String appRealm = registry != null ? registry.getRealm() : null;
// The code below extracts the security work context and invokes
// setupSecurityContext on it passing in the callback handler and the
// execution and server subjects.
SecurityContext sc = (SecurityContext) workCtx;
final Subject executionSubject = new Subject();
J2CSecurityCallbackHandler handler = new J2CSecurityCallbackHandler(executionSubject, appRealm, credService.getUnauthenticatedUserid()); // Change from twas - jms - Setting to null for now - //cm.getUnauthenticatedString());
Subject serverSubject = null;
sc.setupSecurityContext(handler, executionSubject, serverSubject);
SubjectHelper subjectHelper = new SubjectHelper();
WSCredential credential = subjectHelper.getWSCredential(executionSubject);
// check if the Subject is already authenticated i.e it contains WebSphere credentials.
if (credential != null) {
if (handler.getInvocations()[0] == Invocation.CALLERPRINCIPALCALLBACK || // Begin 673415
handler.getInvocations()[1] == Invocation.GROUPPRINCIPALCALLBACK ||
handler.getInvocations()[2] == Invocation.PASSWORDVALIDATIONCALLBACK) {
String message = nls.getString("AUTHENTICATED_SUBJECT_AND_CALLBACK_NOT_SUPPORTED_J2CA0677",
"J2CA0677E: " +
"An authenticated JAAS Subject and one or more JASPIC callbacks were passed to the application server " +
"by the resource adapter."); // End 673415
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "associate"); // depends on control dependency: [if], data = [none]
}
throw new WSSecurityException(message);
} else if (appRealm.equals(credential.getRealmName()) || RegistryHelper.isRealmInboundTrusted(credential.getRealmName(), appRealm)) { // Begin 673415
J2CSecurityHelper.setRunAsSubject(executionSubject); // depends on control dependency: [if], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "associate"); // depends on control dependency: [if], data = [none]
}
return; // depends on control dependency: [if], data = [none]
} else {
String message = nls.getFormattedMessage("REALM_IS_NOT_TRUSTED_J2CA0685", new Object[] { null }, "REALM_IS_NOT_TRUSTED_J2CA0685"); // Change from twas - jms - TODO check on this - credential.getRealmName() changed to null
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "associate"); // depends on control dependency: [if], data = [none]
}
throw new WSSecurityException(message);
}
}
// After the invocation of the setupSecurityContext the execution subject will be
// populated with the result of handling the callbacks that are passed in to the
// handle method of the callback handler. The result is a custom hashtable that can
// be used for security to do a hashtable login. The resource adapter can also modify
// the execution subject by adding a principal. The code below checks for the result and
// if the result is null or empty after the invocation of the callbacks throws an Exception
// See JCA 1.6 Spec 16.4.1.
Hashtable<String, Object> cred = J2CSecurityHelper.getCustomCredentials(executionSubject, handler.getCacheKey());
Set<Principal> principals = executionSubject.getPrincipals(); // 675546
if (handler.getInvocations()[0] == Invocation.CALLERPRINCIPALCALLBACK) {
if (cred == null || !cred.containsKey(AttributeNameConstants.WSCREDENTIAL_SECURITYNAME)) {
String message = nls.getString("CUSTOM_CREDENTIALS_MISSING_J2CA0668",
"J2CA0668E: The WorkManager was unable to "
+
"populate the execution subject with the caller principal or credentials necessary to establish the security "
+
"context for this Work instance.");
throw new WSSecurityException(message);
}
} else if ((handler.getInvocations()[1] == Invocation.GROUPPRINCIPALCALLBACK // Begin 673415
|| handler.getInvocations()[2] == Invocation.PASSWORDVALIDATIONCALLBACK)
&& principals.size() != 1) { //675546
// If CallerPrincipalCallback was not provided but other callbacks were provided then do not
// allow the security context to be setup. See next comment for the reason
String message = nls.getString("CALLERPRINCIPAL_NOT_PROVIDED_J2CA0669",
"J2CA0669E: The resource adapter " +
"did not provide a CallerPrincipalCallback, an execution subject containing a single principal, or an empty " +
"execution subject.");
throw new WSSecurityException(message);
} else { // End 673415
// As per the JCA 1.6 Spec(16.4.5) the CallerPrincipalCallback should always be called except if the
// Resource Adapter wants to establish the UNAUTHENTICATED Identity by passing in an empty
// subject or when it passes a single principal in the principal set of the subject in which
// case we handle it like a CallerPrincipalCallback is passed with that principal.
if (principals.isEmpty()) {
CallerPrincipalCallback cpCallback = new CallerPrincipalCallback(executionSubject, (String) null);
handler.handle(new Callback[] { cpCallback }); // depends on control dependency: [if], data = [none]
} else if (principals.size() == 1) {
CallerPrincipalCallback cpCallback = new CallerPrincipalCallback(executionSubject, principals.iterator().next());
executionSubject.getPrincipals().clear(); // 673415 // depends on control dependency: [if], data = [none]
handler.handle(new Callback[] { cpCallback }); // depends on control dependency: [if], data = [none]
} else {
String message = nls.getString("CALLERPRINCIPAL_NOT_PROVIDED_J2CA0669",
"J2CA0669E: The resource adapter "
+
"did not provide a CallerPrincipalCallback, an execution subject containing a single principal, or an empty "
+
"execution subject.");
throw new WSSecurityException(message);
}
// Refresh the cred variable since we are calling the handler here.
cred = J2CSecurityHelper.getCustomCredentials(executionSubject, handler.getCacheKey()); // depends on control dependency: [if], data = [none]
}
// Do a custom hashtable login to get the runAs subject and set it on a ThreadLocal
// so that we can retrieve it later in the WorkProxy to establish as the RunAs and Caller
// subject.
final String userName = (String) cred.get(AttributeNameConstants.WSCREDENTIAL_SECURITYNAME);
Subject runAsSubject = null;
if (userName.equals(credService.getUnauthenticatedUserid())) {
runAsSubject = unauthSubjService.getUnauthenticatedSubject(); // depends on control dependency: [if], data = [none]
} else {
final AuthenticationService authServ = authService;
PrivilegedExceptionAction<Subject> loginAction = new PrivilegedExceptionAction<Subject>() {
@Override
public Subject run() throws Exception {
return authServ.authenticate(JaasLoginConfigConstants.SYSTEM_DEFAULT, executionSubject);
}
};
runAsSubject = AccessController.doPrivileged(loginAction); // depends on control dependency: [if], data = [none]
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "The RunAs subject is created after a successful login."); // depends on control dependency: [if], data = [none]
}
J2CSecurityHelper.setRunAsSubject(runAsSubject);
} catch (RuntimeException e) {
Tr.error(tc, "SECURITY_CONTEXT_NOT_ASSOCIATED_J2CA0671", e);
String message = nls.getString("SECURITY_CONTEXT_NOT_ASSOCIATED_J2CA0671",
"J2CA0671E: The WorkManager was unable to associate the inflown SecurityContext to the Work instance.");
WorkCompletedException workCompEx = new WorkCompletedException(
message, WorkException.INTERNAL);
workCompEx.initCause(e);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "associate"); // depends on control dependency: [if], data = [none]
}
throw workCompEx;
} catch (Exception e) {
Tr.error(tc, "SECURITY_CONTEXT_NOT_ASSOCIATED_J2CA0671", e);
String message = nls.getString("SECURITY_CONTEXT_NOT_ASSOCIATED_J2CA0671",
"J2CA0671E: The WorkManager was unable to associate the inflown SecurityContext to the Work instance.");
WorkCompletedException workCompEx = new WorkCompletedException(
message, WorkException.INTERNAL);
workCompEx.initCause(e);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "associate"); // depends on control dependency: [if], data = [none]
}
throw workCompEx;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "associate");
}
} else {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "associate", "Application security is not enabled for the application server.");
}
}
} } |
public class class_name {
@Override
public void connect() {
try {
// Create JMS client and session
disconnect();
if (factory == null) {
try {
Context ctx = new InitialContext();
factory = (TopicConnectionFactory) ctx.lookup(connectionFactoryJndiName);
} catch (Exception cause) {
logger.error("TopicConnectionFactory is undefined and \"" + connectionFactoryJndiName
+ "\" JNDI value isn't available!");
reconnect(cause);
return;
}
}
if ((username == null || username.isEmpty()) && (password == null || password.isEmpty())) {
client = factory.createTopicConnection();
} else {
client = factory.createTopicConnection(username, password);
}
client.setClientID(nodeID);
client.start();
session = client.createTopicSession(transacted, acknowledgeMode);
connected();
} catch (Exception cause) {
reconnect(cause);
}
} } | public class class_name {
@Override
public void connect() {
try {
// Create JMS client and session
disconnect();
// depends on control dependency: [try], data = [none]
if (factory == null) {
try {
Context ctx = new InitialContext();
factory = (TopicConnectionFactory) ctx.lookup(connectionFactoryJndiName);
// depends on control dependency: [try], data = [none]
} catch (Exception cause) {
logger.error("TopicConnectionFactory is undefined and \"" + connectionFactoryJndiName
+ "\" JNDI value isn't available!");
reconnect(cause);
return;
}
// depends on control dependency: [catch], data = [none]
}
if ((username == null || username.isEmpty()) && (password == null || password.isEmpty())) {
client = factory.createTopicConnection();
// depends on control dependency: [if], data = [none]
} else {
client = factory.createTopicConnection(username, password);
// depends on control dependency: [if], data = [none]
}
client.setClientID(nodeID);
// depends on control dependency: [try], data = [none]
client.start();
// depends on control dependency: [try], data = [none]
session = client.createTopicSession(transacted, acknowledgeMode);
// depends on control dependency: [try], data = [none]
connected();
// depends on control dependency: [try], data = [none]
} catch (Exception cause) {
reconnect(cause);
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static double Incomplete(double a, double b, double x) {
double aa, bb, t, xx, xc, w, y;
boolean flag;
if (a <= 0.0) {
try {
throw new IllegalArgumentException(" 'a' Lower limit must be greater than zero.");
} catch (Exception e) {
e.printStackTrace();
}
}
if (b <= 0.0) {
try {
throw new IllegalArgumentException(" 'b' Upper limit must be greater than zero.");
} catch (Exception e) {
e.printStackTrace();
}
}
if ((x <= 0.0) || (x >= 1.0)) {
if (x == 0.0) return 0.0;
if (x == 1.0) return 1.0;
try {
throw new IllegalArgumentException(" 'x' Value must be between 0 and 1.");
} catch (Exception e) {
e.printStackTrace();
}
}
flag = false;
if ((b * x) <= 1.0 && x <= 0.95) {
t = PowerSeries(a, b, x);
return t;
}
w = 1.0 - x;
if (x > (a / (a + b))) {
flag = true;
aa = b;
bb = a;
xc = x;
xx = w;
} else {
aa = a;
bb = b;
xc = w;
xx = x;
}
if (flag && (bb * xx) <= 1.0 && xx <= 0.95) {
t = PowerSeries(aa, bb, xx);
if (t <= Constants.DoubleEpsilon) t = 1.0 - Constants.DoubleEpsilon;
else t = 1.0 - t;
return t;
}
y = xx * (aa + bb - 2.0) - (aa - 1.0);
if (y < 0.0)
w = Incbcf(aa, bb, xx);
else
w = Incbd(aa, bb, xx) / xc;
y = aa * Math.log(xx);
t = bb * Math.log(xc);
if ((aa + bb) < Gamma.GammaMax && Math.abs(y) < Constants.LogMax && Math.abs(t) < Constants.LogMax) {
t = Math.pow(xc, bb);
t *= Math.pow(xx, aa);
t /= aa;
t *= w;
t *= Gamma.Function(aa + bb) / (Gamma.Function(aa) * Gamma.Function(bb));
if (flag) {
if (t <= Constants.DoubleEpsilon) t = 1.0 - Constants.DoubleEpsilon;
else t = 1.0 - t;
}
return t;
}
y += t + Gamma.Log(aa + bb) - Gamma.Log(aa) - Gamma.Log(bb);
y += Math.log(w / aa);
if (y < Constants.LogMin)
t = 0.0;
else
t = Math.exp(y);
if (flag) {
if (t <= Constants.DoubleEpsilon) t = 1.0 - Constants.DoubleEpsilon;
else t = 1.0 - t;
}
return t;
} } | public class class_name {
public static double Incomplete(double a, double b, double x) {
double aa, bb, t, xx, xc, w, y;
boolean flag;
if (a <= 0.0) {
try {
throw new IllegalArgumentException(" 'a' Lower limit must be greater than zero.");
} catch (Exception e) {
e.printStackTrace();
}
}
if (b <= 0.0) {
try {
throw new IllegalArgumentException(" 'b' Upper limit must be greater than zero.");
} catch (Exception e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
}
if ((x <= 0.0) || (x >= 1.0)) {
if (x == 0.0) return 0.0;
if (x == 1.0) return 1.0;
try {
throw new IllegalArgumentException(" 'x' Value must be between 0 and 1.");
} catch (Exception e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
}
flag = false;
if ((b * x) <= 1.0 && x <= 0.95) {
t = PowerSeries(a, b, x); // depends on control dependency: [if], data = [none]
return t; // depends on control dependency: [if], data = [none]
}
w = 1.0 - x;
if (x > (a / (a + b))) {
flag = true; // depends on control dependency: [if], data = [none]
aa = b; // depends on control dependency: [if], data = [none]
bb = a; // depends on control dependency: [if], data = [none]
xc = x; // depends on control dependency: [if], data = [none]
xx = w; // depends on control dependency: [if], data = [none]
} else {
aa = a; // depends on control dependency: [if], data = [none]
bb = b; // depends on control dependency: [if], data = [none]
xc = w; // depends on control dependency: [if], data = [none]
xx = x; // depends on control dependency: [if], data = [none]
}
if (flag && (bb * xx) <= 1.0 && xx <= 0.95) {
t = PowerSeries(aa, bb, xx); // depends on control dependency: [if], data = [none]
if (t <= Constants.DoubleEpsilon) t = 1.0 - Constants.DoubleEpsilon;
else t = 1.0 - t;
return t; // depends on control dependency: [if], data = [none]
}
y = xx * (aa + bb - 2.0) - (aa - 1.0);
if (y < 0.0)
w = Incbcf(aa, bb, xx);
else
w = Incbd(aa, bb, xx) / xc;
y = aa * Math.log(xx);
t = bb * Math.log(xc);
if ((aa + bb) < Gamma.GammaMax && Math.abs(y) < Constants.LogMax && Math.abs(t) < Constants.LogMax) {
t = Math.pow(xc, bb); // depends on control dependency: [if], data = [none]
t *= Math.pow(xx, aa); // depends on control dependency: [if], data = [none]
t /= aa; // depends on control dependency: [if], data = [none]
t *= w; // depends on control dependency: [if], data = [none]
t *= Gamma.Function(aa + bb) / (Gamma.Function(aa) * Gamma.Function(bb)); // depends on control dependency: [if], data = [none]
if (flag) {
if (t <= Constants.DoubleEpsilon) t = 1.0 - Constants.DoubleEpsilon;
else t = 1.0 - t;
}
return t; // depends on control dependency: [if], data = [none]
}
y += t + Gamma.Log(aa + bb) - Gamma.Log(aa) - Gamma.Log(bb);
y += Math.log(w / aa);
if (y < Constants.LogMin)
t = 0.0;
else
t = Math.exp(y);
if (flag) {
if (t <= Constants.DoubleEpsilon) t = 1.0 - Constants.DoubleEpsilon;
else t = 1.0 - t;
}
return t;
} } |
public class class_name {
public void marshall(RemoveIpRoutesRequest removeIpRoutesRequest, ProtocolMarshaller protocolMarshaller) {
if (removeIpRoutesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(removeIpRoutesRequest.getDirectoryId(), DIRECTORYID_BINDING);
protocolMarshaller.marshall(removeIpRoutesRequest.getCidrIps(), CIDRIPS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(RemoveIpRoutesRequest removeIpRoutesRequest, ProtocolMarshaller protocolMarshaller) {
if (removeIpRoutesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(removeIpRoutesRequest.getDirectoryId(), DIRECTORYID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(removeIpRoutesRequest.getCidrIps(), CIDRIPS_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private static void groupViewsByDirectoriesAndGetMeasures(
Set<View> views, TreeNode root, Map<String, Measure> measures, Set<View> cachedViews) {
for (View view : views) {
if (cachedViews.contains(view)) {
continue;
}
cachedViews.add(view);
List<String> dirs = PATH_SPLITTER.splitToList(view.getName().asString());
TreeNode node = root;
for (int i = 0; i < dirs.size(); i++) {
if (node == null) {
break; // Should never happen. Work around the nullness checker.
}
String dir = dirs.get(i);
if ("".equals(dir) && i == 0) {
continue; // In case view name starts with a '/'.
}
node.views++;
if (i != dirs.size() - 1) { // Non-leaf node (directory node)
node.children.putIfAbsent(dir, new TreeNode());
node = node.children.get(dir);
} else { // Leaf node (view node)
node.children.putIfAbsent(dir, new TreeNode(view.getName()));
}
}
Measure measure = view.getMeasure();
measures.putIfAbsent(measure.getName(), measure);
}
} } | public class class_name {
private static void groupViewsByDirectoriesAndGetMeasures(
Set<View> views, TreeNode root, Map<String, Measure> measures, Set<View> cachedViews) {
for (View view : views) {
if (cachedViews.contains(view)) {
continue;
}
cachedViews.add(view); // depends on control dependency: [for], data = [view]
List<String> dirs = PATH_SPLITTER.splitToList(view.getName().asString());
TreeNode node = root;
for (int i = 0; i < dirs.size(); i++) {
if (node == null) {
break; // Should never happen. Work around the nullness checker.
}
String dir = dirs.get(i);
if ("".equals(dir) && i == 0) {
continue; // In case view name starts with a '/'.
}
node.views++; // depends on control dependency: [for], data = [none]
if (i != dirs.size() - 1) { // Non-leaf node (directory node)
node.children.putIfAbsent(dir, new TreeNode()); // depends on control dependency: [if], data = [none]
node = node.children.get(dir); // depends on control dependency: [if], data = [none]
} else { // Leaf node (view node)
node.children.putIfAbsent(dir, new TreeNode(view.getName())); // depends on control dependency: [if], data = [none]
}
}
Measure measure = view.getMeasure();
measures.putIfAbsent(measure.getName(), measure); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
@Override
public void info( F0<String> msg )
{
if ( compilerLogger.isInfoEnabled() )
{
compilerLogger.info( msg.apply() );
}
} } | public class class_name {
@Override
public void info( F0<String> msg )
{
if ( compilerLogger.isInfoEnabled() )
{
compilerLogger.info( msg.apply() ); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@SuppressWarnings(UNUSED)
public FormValidation doCheckIvySettingsFile(@QueryParameter String value) {
String v = Util.fixEmpty(value);
if ((v == null) || (v.length() == 0)) {
// Null values are allowed.
return FormValidation.ok();
}
if (v.startsWith("/") || v.startsWith("\\") || v.matches("^\\w\\:\\\\.*")) {
return FormValidation.error("Ivy settings file must be a relative path.");
}
return FormValidation.ok();
} } | public class class_name {
@SuppressWarnings(UNUSED)
public FormValidation doCheckIvySettingsFile(@QueryParameter String value) {
String v = Util.fixEmpty(value);
if ((v == null) || (v.length() == 0)) {
// Null values are allowed.
return FormValidation.ok(); // depends on control dependency: [if], data = [none]
}
if (v.startsWith("/") || v.startsWith("\\") || v.matches("^\\w\\:\\\\.*")) {
return FormValidation.error("Ivy settings file must be a relative path."); // depends on control dependency: [if], data = [none]
}
return FormValidation.ok();
} } |
public class class_name {
public java.util.List<AggregateResourceIdentifier> getUnprocessedResourceIdentifiers() {
if (unprocessedResourceIdentifiers == null) {
unprocessedResourceIdentifiers = new com.amazonaws.internal.SdkInternalList<AggregateResourceIdentifier>();
}
return unprocessedResourceIdentifiers;
} } | public class class_name {
public java.util.List<AggregateResourceIdentifier> getUnprocessedResourceIdentifiers() {
if (unprocessedResourceIdentifiers == null) {
unprocessedResourceIdentifiers = new com.amazonaws.internal.SdkInternalList<AggregateResourceIdentifier>(); // depends on control dependency: [if], data = [none]
}
return unprocessedResourceIdentifiers;
} } |
public class class_name {
protected ConsumerSession createCoreConsumer(SICoreConnection _coreConn, ConsumerProperties _props) throws JMSException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "createCoreConsumer", new Object[] { _coreConn });
ConsumerSession cs = null;
JmsDestinationImpl dest = (JmsDestinationImpl) _props.getJmsDestination();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(this, tc, "destName: " + dest.getConsumerDestName() +
" type: " + _props.getDestinationType() +
" discrim: " + dest.getDestDiscrim() +
" selector: " + _props.getSelector() +
" reliability: " + _props.getReliability() +
" noLocal: " + _props.noLocal() +
" unrecovRel: " + _props.getUnrecovReliability() +
" gatherMsgs: " + _props.isGatherMessages());
try {
// Need to create a selection criteria object for create consumer call.
SelectionCriteria selectionCriteria = null;
SIDestinationAddress consumerSIDA = null;
try {
selectionCriteria = selectionCriteriaFactory.createSelectionCriteria(dest.getDestDiscrim(), // discriminator (topic)
_props.getSelector(), // selector string
SelectorDomain.JMS // selector domain
);
// The MessageProcessor resolves the bus field of the SIDA object that is passed
// in to createConsumerSession, which can lead to unusual behaviour since we have
// been passing this by reference rather than copying it. Taking a copy here
// avoids the 'back-door' populating of the object, and is still outside the mainline
// send path.
SIDestinationAddress originalConsumerProps = dest.getConsumerSIDestinationAddress();
consumerSIDA = JmsMessageImpl.destAddressFactory.createSIDestinationAddress(originalConsumerProps.getDestinationName(),
((JsDestinationAddress) originalConsumerProps).isLocalOnly(),
originalConsumerProps.getBusName());
} catch (SIErrorException sice) {
// No FFDC code needed
// d222942 review. SIErrorException are "should never happen" cases, so default message ok.
// d238447 FFDC review. Generate FFDC.
throw (JMSException) JmsErrorUtils.newThrowable(JMSException.class,
"EXCEPTION_RECEIVED_CWSIA0085",
new Object[] { sice, "JmsMsgConsumerImpl.createCoreConsumer" },
sice,
"JmsMsgConsumerImpl.createCoreConsumer#1",
this,
tc
);
}
if (_props.getSubName() != null) {
//Getting the final non durable subscription id by calling getCoreDurableSubName
// if subname is 'nondurSub1' and clientid is 'cid', the method getCoreDurableSubName
// returns subscriber id as 'nondurSub1##cid'
String subscriptionName = JmsInternalsFactory.getSharedUtils().getCoreDurableSubName(_props.getClientID(), _props.getSubName());
//createSharedConsumerSession is newly introduced SPI for non-durable shared subscriptions.
cs = _coreConn.createSharedConsumerSession(subscriptionName,
consumerSIDA,
_props.getDestinationType(),
selectionCriteria,
_props.getReliability(),
_props.readAhead(),
true,
_props.noLocal(),
_props.getUnrecovReliability(), /* recoverableExpress */
false, // bifurcatable
null, // alternateUserID
true, // ignoreInitialIndoubts
_props.isGatherMessages(),
null // msg control props
);
} else {
cs = _coreConn.createConsumerSession(consumerSIDA,
_props.getDestinationType(),
selectionCriteria,
_props.getReliability(),
_props.readAhead(),
_props.noLocal(),
_props.getUnrecovReliability(), /* recoverableExpress */
false, // bifurcatable
null, // alternateUserID
true, // ignoreInitialIndoubts
_props.isGatherMessages(),
null // msg control props
);
}
} catch (SISelectorSyntaxException e) {
// No FFDC code needed
// d238447 FFDC review. Bad selector is an app' error, so no FFDC.
throw (InvalidSelectorException) JmsErrorUtils.newThrowable(InvalidSelectorException.class,
"INVALID_SELECTOR_CWSIA0083",
null,
e,
null, // null probeId = no FFDC.
this,
tc
);
} catch (SINotAuthorizedException sidnfe) {
// No FFDC code needed
// d238447 FFDC review: Not auth is an app/config error, so no FFDC.
throw (JMSSecurityException) JmsErrorUtils.newThrowable(JMSSecurityException.class,
"CONSUMER_AUTH_ERROR_CWSIA0090",
new Object[] { dest.getDestName() },
sidnfe,
null, // null probeId = no FFDC
this,
tc
);
} catch (SINotPossibleInCurrentConfigurationException dwte) {
// No FFDC code needed
// This was SIDestinationWrongTypeException, now also gets DestNotFound
// d238447 FFDC review. Both are app/config errors, so no FFDC.
String msgKey = "MC_CREATE_FAILED_CWSIA0086";
throw (InvalidDestinationException) JmsErrorUtils.newThrowable(InvalidDestinationException.class,
msgKey,
new Object[] { dest },
dwte,
null, // null probeId = no FFDC
this,
tc
);
} catch (SITemporaryDestinationNotFoundException e) {
// No FFDC code needed
// d238447 FFDC reveiw. App error, no FFDC.
String msgKey = "MC_CREATE_FAILED_CWSIA0086";
throw (InvalidDestinationException) JmsErrorUtils.newThrowable(InvalidDestinationException.class,
msgKey,
new Object[] { dest },
e,
null, // null probeId = no FFDC
this,
tc
);
} catch (SIIncorrectCallException e) {
// No FFDC code needed
// d222942 review. Default message ok.
// d238447 FFDC review. Incorrect call would seem to be an internal error, so generate FFDC.
throw (JMSException) JmsErrorUtils.newThrowable(JMSException.class,
"EXCEPTION_RECEIVED_CWSIA0085",
new Object[] { e, "JmsMsgConsumerImpl.createCoreConsumer" },
e,
"JmsMsgConsumerImpl.createCoreConsumer#6",
this,
tc
);
} catch (SIException sice) {
// No FFDC code needed
// d222942 review.
// Exceptions thrown from createConsumerSession which can be handled with default message:
//SIConnectionUnavailableException, SIConnectionDroppedException,
//SIResourceException, SIConnectionLostException, SILimitExceededException.
// d238447 FFDC Review. These are either external errors, or should already have been FFDCd,
// so don't FFDC here.
throw (JMSException) JmsErrorUtils.newThrowable(JMSException.class,
"EXCEPTION_RECEIVED_CWSIA0085",
new Object[] { sice, "JmsMsgConsumerImpl.createCoreConsumer" },
sice,
null, // null probeId = no FFDC
this,
tc
);
} catch (SIErrorException sie) {
throw (JMSException) JmsErrorUtils.newThrowable(JMSException.class,
"EXCEPTION_RECEIVED_CWSIA0085",
new Object[] { sie, "JmsMsgConsumerImpl.createCoreConsumer" },
sie,
null, // null probeId = no FFDC
this,
tc
);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(this, tc, "createCoreConsumer", cs);
return cs;
} } | public class class_name {
protected ConsumerSession createCoreConsumer(SICoreConnection _coreConn, ConsumerProperties _props) throws JMSException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "createCoreConsumer", new Object[] { _coreConn });
ConsumerSession cs = null;
JmsDestinationImpl dest = (JmsDestinationImpl) _props.getJmsDestination();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(this, tc, "destName: " + dest.getConsumerDestName() +
" type: " + _props.getDestinationType() +
" discrim: " + dest.getDestDiscrim() +
" selector: " + _props.getSelector() +
" reliability: " + _props.getReliability() +
" noLocal: " + _props.noLocal() +
" unrecovRel: " + _props.getUnrecovReliability() +
" gatherMsgs: " + _props.isGatherMessages());
try {
// Need to create a selection criteria object for create consumer call.
SelectionCriteria selectionCriteria = null;
SIDestinationAddress consumerSIDA = null;
try {
selectionCriteria = selectionCriteriaFactory.createSelectionCriteria(dest.getDestDiscrim(), // discriminator (topic)
_props.getSelector(), // selector string
SelectorDomain.JMS // selector domain
); // depends on control dependency: [try], data = [none]
// The MessageProcessor resolves the bus field of the SIDA object that is passed
// in to createConsumerSession, which can lead to unusual behaviour since we have
// been passing this by reference rather than copying it. Taking a copy here
// avoids the 'back-door' populating of the object, and is still outside the mainline
// send path.
SIDestinationAddress originalConsumerProps = dest.getConsumerSIDestinationAddress();
consumerSIDA = JmsMessageImpl.destAddressFactory.createSIDestinationAddress(originalConsumerProps.getDestinationName(),
((JsDestinationAddress) originalConsumerProps).isLocalOnly(),
originalConsumerProps.getBusName()); // depends on control dependency: [try], data = [none]
} catch (SIErrorException sice) {
// No FFDC code needed
// d222942 review. SIErrorException are "should never happen" cases, so default message ok.
// d238447 FFDC review. Generate FFDC.
throw (JMSException) JmsErrorUtils.newThrowable(JMSException.class,
"EXCEPTION_RECEIVED_CWSIA0085",
new Object[] { sice, "JmsMsgConsumerImpl.createCoreConsumer" },
sice,
"JmsMsgConsumerImpl.createCoreConsumer#1",
this,
tc
);
} // depends on control dependency: [catch], data = [none]
if (_props.getSubName() != null) {
//Getting the final non durable subscription id by calling getCoreDurableSubName
// if subname is 'nondurSub1' and clientid is 'cid', the method getCoreDurableSubName
// returns subscriber id as 'nondurSub1##cid'
String subscriptionName = JmsInternalsFactory.getSharedUtils().getCoreDurableSubName(_props.getClientID(), _props.getSubName());
//createSharedConsumerSession is newly introduced SPI for non-durable shared subscriptions.
cs = _coreConn.createSharedConsumerSession(subscriptionName,
consumerSIDA,
_props.getDestinationType(),
selectionCriteria,
_props.getReliability(),
_props.readAhead(),
true,
_props.noLocal(),
_props.getUnrecovReliability(), /* recoverableExpress */
false, // bifurcatable
null, // alternateUserID
true, // ignoreInitialIndoubts
_props.isGatherMessages(),
null // msg control props
); // depends on control dependency: [if], data = [none]
} else {
cs = _coreConn.createConsumerSession(consumerSIDA,
_props.getDestinationType(),
selectionCriteria,
_props.getReliability(),
_props.readAhead(),
_props.noLocal(),
_props.getUnrecovReliability(), /* recoverableExpress */
false, // bifurcatable
null, // alternateUserID
true, // ignoreInitialIndoubts
_props.isGatherMessages(),
null // msg control props
); // depends on control dependency: [if], data = [none]
}
} catch (SISelectorSyntaxException e) {
// No FFDC code needed
// d238447 FFDC review. Bad selector is an app' error, so no FFDC.
throw (InvalidSelectorException) JmsErrorUtils.newThrowable(InvalidSelectorException.class,
"INVALID_SELECTOR_CWSIA0083",
null,
e,
null, // null probeId = no FFDC.
this,
tc
);
} catch (SINotAuthorizedException sidnfe) {
// No FFDC code needed
// d238447 FFDC review: Not auth is an app/config error, so no FFDC.
throw (JMSSecurityException) JmsErrorUtils.newThrowable(JMSSecurityException.class,
"CONSUMER_AUTH_ERROR_CWSIA0090",
new Object[] { dest.getDestName() },
sidnfe,
null, // null probeId = no FFDC
this,
tc
);
} catch (SINotPossibleInCurrentConfigurationException dwte) {
// No FFDC code needed
// This was SIDestinationWrongTypeException, now also gets DestNotFound
// d238447 FFDC review. Both are app/config errors, so no FFDC.
String msgKey = "MC_CREATE_FAILED_CWSIA0086";
throw (InvalidDestinationException) JmsErrorUtils.newThrowable(InvalidDestinationException.class,
msgKey,
new Object[] { dest },
dwte,
null, // null probeId = no FFDC
this,
tc
);
} catch (SITemporaryDestinationNotFoundException e) {
// No FFDC code needed
// d238447 FFDC reveiw. App error, no FFDC.
String msgKey = "MC_CREATE_FAILED_CWSIA0086";
throw (InvalidDestinationException) JmsErrorUtils.newThrowable(InvalidDestinationException.class,
msgKey,
new Object[] { dest },
e,
null, // null probeId = no FFDC
this,
tc
);
} catch (SIIncorrectCallException e) {
// No FFDC code needed
// d222942 review. Default message ok.
// d238447 FFDC review. Incorrect call would seem to be an internal error, so generate FFDC.
throw (JMSException) JmsErrorUtils.newThrowable(JMSException.class,
"EXCEPTION_RECEIVED_CWSIA0085",
new Object[] { e, "JmsMsgConsumerImpl.createCoreConsumer" },
e,
"JmsMsgConsumerImpl.createCoreConsumer#6",
this,
tc
);
} catch (SIException sice) {
// No FFDC code needed
// d222942 review.
// Exceptions thrown from createConsumerSession which can be handled with default message:
//SIConnectionUnavailableException, SIConnectionDroppedException,
//SIResourceException, SIConnectionLostException, SILimitExceededException.
// d238447 FFDC Review. These are either external errors, or should already have been FFDCd,
// so don't FFDC here.
throw (JMSException) JmsErrorUtils.newThrowable(JMSException.class,
"EXCEPTION_RECEIVED_CWSIA0085",
new Object[] { sice, "JmsMsgConsumerImpl.createCoreConsumer" },
sice,
null, // null probeId = no FFDC
this,
tc
);
} catch (SIErrorException sie) {
throw (JMSException) JmsErrorUtils.newThrowable(JMSException.class,
"EXCEPTION_RECEIVED_CWSIA0085",
new Object[] { sie, "JmsMsgConsumerImpl.createCoreConsumer" },
sie,
null, // null probeId = no FFDC
this,
tc
);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(this, tc, "createCoreConsumer", cs);
return cs;
} } |
public class class_name {
private String getSmallImageScaleParam(CmsResultItemBean infoBean) {
String result = null;
if (infoBean.getDimension() != null) {
String[] sizes = infoBean.getDimension().split("x");
try {
int width = Integer.parseInt(sizes[0].trim());
int height = Integer.parseInt(sizes[1].trim());
// only use the small image dimensions in case of dimensions smaller than the big thumbnail
if ((I_CmsLayoutBundle.INSTANCE.galleryResultItemCss().bigImageWidth() > width)
|| (I_CmsLayoutBundle.INSTANCE.galleryResultItemCss().bigImageHeight() > height)) {
result = IMAGE_SCALE_PARAM
+ ",w:"
+ I_CmsLayoutBundle.INSTANCE.galleryResultItemCss().smallImageWidth()
+ ",h:"
+ I_CmsLayoutBundle.INSTANCE.galleryResultItemCss().smallImageHeight();
}
} catch (Exception e) {
// failed parsing the dimensions, will use big image
}
}
if (result == null) {
result = getBigImageScaleParam();
}
return result;
} } | public class class_name {
private String getSmallImageScaleParam(CmsResultItemBean infoBean) {
String result = null;
if (infoBean.getDimension() != null) {
String[] sizes = infoBean.getDimension().split("x");
try {
int width = Integer.parseInt(sizes[0].trim());
int height = Integer.parseInt(sizes[1].trim());
// only use the small image dimensions in case of dimensions smaller than the big thumbnail
if ((I_CmsLayoutBundle.INSTANCE.galleryResultItemCss().bigImageWidth() > width)
|| (I_CmsLayoutBundle.INSTANCE.galleryResultItemCss().bigImageHeight() > height)) {
result = IMAGE_SCALE_PARAM
+ ",w:"
+ I_CmsLayoutBundle.INSTANCE.galleryResultItemCss().smallImageWidth()
+ ",h:"
+ I_CmsLayoutBundle.INSTANCE.galleryResultItemCss().smallImageHeight(); // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
// failed parsing the dimensions, will use big image
} // depends on control dependency: [catch], data = [none]
}
if (result == null) {
result = getBigImageScaleParam(); // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
public static byte[] fromBase64(String base64String) {
byte[] result = null;
if (base64String != null) {
result = Base64.decodeBase64(base64String);
}
return result;
} } | public class class_name {
public static byte[] fromBase64(String base64String) {
byte[] result = null;
if (base64String != null) {
result = Base64.decodeBase64(base64String); // depends on control dependency: [if], data = [(base64String]
}
return result;
} } |
public class class_name {
public void marshall(DatastoreStatistics datastoreStatistics, ProtocolMarshaller protocolMarshaller) {
if (datastoreStatistics == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(datastoreStatistics.getSize(), SIZE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DatastoreStatistics datastoreStatistics, ProtocolMarshaller protocolMarshaller) {
if (datastoreStatistics == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(datastoreStatistics.getSize(), SIZE_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static Configuration getConfiguration(JobContext context) {
try {
return (Configuration) GET_CONFIGURATION_METHOD.invoke(context);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException("Can't invoke method", e);
} catch (InvocationTargetException e) {
throw new IllegalArgumentException("Can't invoke method", e);
}
} } | public class class_name {
public static Configuration getConfiguration(JobContext context) {
try {
return (Configuration) GET_CONFIGURATION_METHOD.invoke(context); // depends on control dependency: [try], data = [none]
} catch (IllegalAccessException e) {
throw new IllegalArgumentException("Can't invoke method", e);
} catch (InvocationTargetException e) {
throw new IllegalArgumentException("Can't invoke method", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void runScript(Connection conn, Reader reader)
throws IOException, SQLException {
StringBuffer command = null;
try {
LineNumberReader lineReader = new LineNumberReader(reader);
String line = null;
while ((line = lineReader.readLine()) != null) {
if (command == null) {
command = new StringBuffer();
}
String trimmedLine = line.trim();
if (trimmedLine.startsWith("--")) {
log.info(trimmedLine);
} else if (trimmedLine.length() < 1 || trimmedLine.startsWith("//")) {
//Do nothing
} else if (trimmedLine.length() < 1 || trimmedLine.startsWith("--")) {
//Do nothing
} else if (trimmedLine.equals(getDelimiter()) || trimmedLine.endsWith(getDelimiter())) {
command.append(line.substring(0, line.lastIndexOf(getDelimiter())));
command.append(" ");
Statement statement = conn.createStatement();
log.info(command.toString());
try {
statement.execute(command.toString());
} catch (SQLException e) {
e.fillInStackTrace();
log.error("Error executing: " + command);
}
if (autoCommit && !conn.getAutoCommit()) {
conn.commit();
}
command = null;
try {
statement.close();
} catch (Exception e) {
//ignore
}
Thread.yield();
} else {
command.append(line);
command.append(" ");
}
}
if (!autoCommit) {
conn.commit();
}
} catch (SQLException e) {
e.fillInStackTrace();
throw e;
} catch (IOException e) {
e.fillInStackTrace();
throw e;
}
} } | public class class_name {
private void runScript(Connection conn, Reader reader)
throws IOException, SQLException {
StringBuffer command = null;
try {
LineNumberReader lineReader = new LineNumberReader(reader);
String line = null;
while ((line = lineReader.readLine()) != null) {
if (command == null) {
command = new StringBuffer(); // depends on control dependency: [if], data = [none]
}
String trimmedLine = line.trim();
if (trimmedLine.startsWith("--")) {
log.info(trimmedLine);
} else if (trimmedLine.length() < 1 || trimmedLine.startsWith("//")) {
//Do nothing
} else if (trimmedLine.length() < 1 || trimmedLine.startsWith("--")) {
//Do nothing
} else if (trimmedLine.equals(getDelimiter()) || trimmedLine.endsWith(getDelimiter())) {
command.append(line.substring(0, line.lastIndexOf(getDelimiter())));
command.append(" ");
Statement statement = conn.createStatement();
log.info(command.toString());
try {
statement.execute(command.toString());
} catch (SQLException e) {
e.fillInStackTrace();
log.error("Error executing: " + command);
}
if (autoCommit && !conn.getAutoCommit()) {
conn.commit();
}
command = null;
try {
statement.close();
} catch (Exception e) {
//ignore
}
Thread.yield();
} else {
command.append(line);
command.append(" ");
}
}
if (!autoCommit) {
conn.commit();
}
} catch (SQLException e) {
e.fillInStackTrace();
throw e;
} catch (IOException e) {
e.fillInStackTrace();
throw e;
}
} } |
public class class_name {
@InterfaceAudience.Public
public void waitForRows() throws CouchbaseLiteException {
start();
while (true) {
try {
queryFuture.get();
break;
} catch (InterruptedException e) {
continue;
} catch (Exception e) {
lastError = e;
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
}
}
} } | public class class_name {
@InterfaceAudience.Public
public void waitForRows() throws CouchbaseLiteException {
start();
while (true) {
try {
queryFuture.get(); // depends on control dependency: [try], data = [none]
break;
} catch (InterruptedException e) {
continue;
} catch (Exception e) { // depends on control dependency: [catch], data = [none]
lastError = e;
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public void setClassLoader (ClassLoader loader)
{
_loader = loader;
PresentsConnection conn = getConnection();
if (conn != null) {
conn.setClassLoader(loader);
}
} } | public class class_name {
public void setClassLoader (ClassLoader loader)
{
_loader = loader;
PresentsConnection conn = getConnection();
if (conn != null) {
conn.setClassLoader(loader); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
static Set<String> parsePathParameters(String path) {
Matcher m = PARAM_URL_REGEX.matcher(path);
Set<String> patterns = new LinkedHashSet<>();
while (m.find()) {
patterns.add(m.group(1));
}
return patterns;
} } | public class class_name {
static Set<String> parsePathParameters(String path) {
Matcher m = PARAM_URL_REGEX.matcher(path);
Set<String> patterns = new LinkedHashSet<>();
while (m.find()) {
patterns.add(m.group(1)); // depends on control dependency: [while], data = [none]
}
return patterns;
} } |
public class class_name {
@Override
public void removeByGroupId(long groupId) {
for (CPDefinitionSpecificationOptionValue cpDefinitionSpecificationOptionValue : findByGroupId(
groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(cpDefinitionSpecificationOptionValue);
}
} } | public class class_name {
@Override
public void removeByGroupId(long groupId) {
for (CPDefinitionSpecificationOptionValue cpDefinitionSpecificationOptionValue : findByGroupId(
groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(cpDefinitionSpecificationOptionValue); // depends on control dependency: [for], data = [cpDefinitionSpecificationOptionValue]
}
} } |
public class class_name {
private void setState(IState toState)
{
// We want to make sure state changes happen purely on the "home" thread,
// for the sake of sanity and avoiding many obscure race-condition bugs.
if (Thread.currentThread() == this.homeThread)
{
// We are on the home thread, so safe to proceed:
if (this.state != toState)
{
System.out.println(getName() + " enter state: " + toState);
TCPUtils.Log(Level.INFO, "======== " + getName() + " enter state: " + toState + " ========");
this.state = toState;
onPreStateChange(toState);
onStateChange();
}
}
else
{
// We are not on the home thread; queue this state transition
// so that the home thread can act on it.
queueStateChange(toState);
}
} } | public class class_name {
private void setState(IState toState)
{
// We want to make sure state changes happen purely on the "home" thread,
// for the sake of sanity and avoiding many obscure race-condition bugs.
if (Thread.currentThread() == this.homeThread)
{
// We are on the home thread, so safe to proceed:
if (this.state != toState)
{
System.out.println(getName() + " enter state: " + toState); // depends on control dependency: [if], data = [toState)]
TCPUtils.Log(Level.INFO, "======== " + getName() + " enter state: " + toState + " ========"); // depends on control dependency: [if], data = [none]
this.state = toState; // depends on control dependency: [if], data = [none]
onPreStateChange(toState); // depends on control dependency: [if], data = [toState)]
onStateChange(); // depends on control dependency: [if], data = [none]
}
}
else
{
// We are not on the home thread; queue this state transition
// so that the home thread can act on it.
queueStateChange(toState); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public synchronized void parseCatalog(URL aUrl) throws IOException {
catalogCwd = aUrl;
base = aUrl;
default_override = catalogManager.getPreferPublic();
catalogManager.debug.message(4, "Parse catalog: " + aUrl.toString());
DataInputStream inStream = null;
boolean parsed = false;
for (int count = 0; !parsed && count < readerArr.size(); count++) {
CatalogReader reader = (CatalogReader) readerArr.get(count);
try {
inStream = new DataInputStream(aUrl.openStream());
} catch (FileNotFoundException fnfe) {
// No catalog; give up!
break;
}
try {
reader.readCatalog(this, inStream);
parsed=true;
} catch (CatalogException ce) {
if (ce.getExceptionType() == CatalogException.PARSE_FAILED) {
// give up!
break;
} else {
// try again!
}
}
try {
inStream.close();
} catch (IOException e) {
//nop
}
}
if (parsed) parsePendingCatalogs();
} } | public class class_name {
public synchronized void parseCatalog(URL aUrl) throws IOException {
catalogCwd = aUrl;
base = aUrl;
default_override = catalogManager.getPreferPublic();
catalogManager.debug.message(4, "Parse catalog: " + aUrl.toString());
DataInputStream inStream = null;
boolean parsed = false;
for (int count = 0; !parsed && count < readerArr.size(); count++) {
CatalogReader reader = (CatalogReader) readerArr.get(count);
try {
inStream = new DataInputStream(aUrl.openStream()); // depends on control dependency: [try], data = [none]
} catch (FileNotFoundException fnfe) {
// No catalog; give up!
break;
} // depends on control dependency: [catch], data = [none]
try {
reader.readCatalog(this, inStream); // depends on control dependency: [try], data = [none]
parsed=true; // depends on control dependency: [try], data = [none]
} catch (CatalogException ce) {
if (ce.getExceptionType() == CatalogException.PARSE_FAILED) {
// give up!
break;
} else {
// try again!
}
} // depends on control dependency: [catch], data = [none]
try {
inStream.close(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
//nop
} // depends on control dependency: [catch], data = [none]
}
if (parsed) parsePendingCatalogs();
} } |
public class class_name {
public static void stop(){
//--Close logger
isClosed = true; // <- not a thread-safe boolean
Thread.yield(); //poor man's synchronization attempt (let everything else log that wants to)
Thread.yield();
//--Close Tracks
while(depth > 0){
depth -= 1;
//(send signal to handlers)
handlers.process(null, MessageType.END_TRACK, depth, System.currentTimeMillis());
}
//--Shutdown
handlers.process(null, MessageType.SHUTDOWN, 0, System.currentTimeMillis());
} } | public class class_name {
public static void stop(){
//--Close logger
isClosed = true; // <- not a thread-safe boolean
Thread.yield(); //poor man's synchronization attempt (let everything else log that wants to)
Thread.yield();
//--Close Tracks
while(depth > 0){
depth -= 1;
// depends on control dependency: [while], data = [none]
//(send signal to handlers)
handlers.process(null, MessageType.END_TRACK, depth, System.currentTimeMillis());
// depends on control dependency: [while], data = [none]
}
//--Shutdown
handlers.process(null, MessageType.SHUTDOWN, 0, System.currentTimeMillis());
} } |
public class class_name {
public GetComplianceSummaryByResourceTypeResult withComplianceSummariesByResourceType(ComplianceSummaryByResourceType... complianceSummariesByResourceType) {
if (this.complianceSummariesByResourceType == null) {
setComplianceSummariesByResourceType(new com.amazonaws.internal.SdkInternalList<ComplianceSummaryByResourceType>(
complianceSummariesByResourceType.length));
}
for (ComplianceSummaryByResourceType ele : complianceSummariesByResourceType) {
this.complianceSummariesByResourceType.add(ele);
}
return this;
} } | public class class_name {
public GetComplianceSummaryByResourceTypeResult withComplianceSummariesByResourceType(ComplianceSummaryByResourceType... complianceSummariesByResourceType) {
if (this.complianceSummariesByResourceType == null) {
setComplianceSummariesByResourceType(new com.amazonaws.internal.SdkInternalList<ComplianceSummaryByResourceType>(
complianceSummariesByResourceType.length)); // depends on control dependency: [if], data = [none]
}
for (ComplianceSummaryByResourceType ele : complianceSummariesByResourceType) {
this.complianceSummariesByResourceType.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
float parseNumber(String input, int startpos, int len)
{
boolean isNegative = false;
long significand = 0;
int numDigits = 0;
int numLeadingZeroes = 0;
int numTrailingZeroes = 0;
boolean decimalSeen = false;
int sigStart;
int decimalPos = 0;
int exponent;
long TOO_BIG = Long.MAX_VALUE / 10;
pos = startpos;
if (pos >= len)
return Float.NaN; // String is empty - no number found
char ch = input.charAt(pos);
switch (ch) {
case '-': isNegative = true;
// fall through
case '+': pos++;
}
sigStart = pos;
while (pos < len)
{
ch = input.charAt(pos);
if (ch == '0')
{
if (numDigits == 0) {
numLeadingZeroes++;
} else {
// We potentially skip trailing zeroes. Keep count for now.
numTrailingZeroes++;
}
}
else if (ch >= '1' && ch <= '9')
{
// Multiply any skipped zeroes into buffer
numDigits += numTrailingZeroes;
while (numTrailingZeroes > 0) {
if (significand > TOO_BIG) {
//Log.e("Number is too large");
return Float.NaN;
}
significand *= 10;
numTrailingZeroes--;
}
if (significand > TOO_BIG) {
// We will overflow if we continue...
//Log.e("Number is too large");
return Float.NaN;
}
significand = significand * 10 + ((int)ch - (int)'0');
numDigits++;
if (significand < 0)
return Float.NaN; // overflowed from +ve to -ve
}
else if (ch == '.')
{
if (decimalSeen) {
// Stop parsing here. We may be looking at a new number.
break;
}
decimalPos = pos - sigStart;
decimalSeen = true;
}
else
break;
pos++;
}
if (decimalSeen && pos == (decimalPos + 1)) {
// No digits following decimal point (eg. "1.")
//Log.e("Missing fraction part of number");
return Float.NaN;
}
// Have we seen anything number-ish at all so far?
if (numDigits == 0) {
if (numLeadingZeroes == 0) {
//Log.e("Number not found");
return Float.NaN;
}
// Leading zeroes have been seen though, so we
// treat that as a '0'.
numDigits = 1;
}
if (decimalSeen) {
exponent = decimalPos - numLeadingZeroes - numDigits;
} else {
exponent = numTrailingZeroes;
}
// Now look for exponent
if (pos < len)
{
ch = input.charAt(pos);
if (ch == 'E' || ch == 'e')
{
boolean expIsNegative = false;
int expVal = 0;
boolean abortExponent = false;
pos++;
if (pos == len) {
// Incomplete exponent.
//Log.e("Incomplete exponent of number");
return Float.NaN;
}
switch (input.charAt(pos)) {
case '-': expIsNegative = true;
// fall through
case '+': pos++;
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
break; // acceptable next char
default:
// any other character is a failure, ie no exponent.
// Could be something legal like "em" though.
abortExponent = true;
pos--; // reset pos to position of 'E'/'e'
}
if (!abortExponent)
{
int expStart = pos;
while (pos < len)
{
ch = input.charAt(pos);
if (ch >= '0' && ch <= '9')
{
if (expVal > TOO_BIG) {
// We will overflow if we continue...
//Log.e("Exponent of number is too large");
return Float.NaN;
}
expVal = expVal * 10 + ((int)ch - (int)'0');
pos++;
}
else
break;
}
// Check that at least some exponent digits were read
if (pos == expStart) {
//Log.e(""Incomplete exponent of number"");
return Float.NaN;
}
if (expIsNegative)
exponent -= expVal;
else
exponent += expVal;
}
}
}
// Quick check to eliminate huge exponents.
// Biggest float is (2 - 2^23) . 2^127 ~== 3.4e38
// Biggest negative float is 2^-149 ~== 1.4e-45
// Some numbers that will overflow will get through the scan
// and be returned as 'valid', yet fail when value() is called.
// However they will be very rare and not worth slowing down
// the parse for.
if ((exponent + numDigits) > 39 || (exponent + numDigits) < -44)
return Float.NaN;
float f = (float) significand;
if (significand != 0)
{
// Do exponents > 0
if (exponent > 0)
{
f *= positivePowersOf10[exponent];
}
else if (exponent < 0)
{
// Some valid numbers can have an exponent greater than the max (ie. < -38)
// for a float. For example, significand=123, exponent=-40
// If that's the case, we need to apply the exponent in two steps.
if (exponent < -38) {
// Long.MAX_VALUE is 19 digits, so taking 20 off the exponent should be enough.
f *= 1e-20;
exponent += 20;
}
// Do exponents < 0
f *= negativePowersOf10[-exponent];
}
}
return (isNegative) ? -f : f;
} } | public class class_name {
float parseNumber(String input, int startpos, int len)
{
boolean isNegative = false;
long significand = 0;
int numDigits = 0;
int numLeadingZeroes = 0;
int numTrailingZeroes = 0;
boolean decimalSeen = false;
int sigStart;
int decimalPos = 0;
int exponent;
long TOO_BIG = Long.MAX_VALUE / 10;
pos = startpos;
if (pos >= len)
return Float.NaN; // String is empty - no number found
char ch = input.charAt(pos);
switch (ch) {
case '-': isNegative = true;
// fall through
case '+': pos++;
}
sigStart = pos;
while (pos < len)
{
ch = input.charAt(pos);
// depends on control dependency: [while], data = [(pos]
if (ch == '0')
{
if (numDigits == 0) {
numLeadingZeroes++;
// depends on control dependency: [if], data = [none]
} else {
// We potentially skip trailing zeroes. Keep count for now.
numTrailingZeroes++;
// depends on control dependency: [if], data = [none]
}
}
else if (ch >= '1' && ch <= '9')
{
// Multiply any skipped zeroes into buffer
numDigits += numTrailingZeroes;
// depends on control dependency: [if], data = [none]
while (numTrailingZeroes > 0) {
if (significand > TOO_BIG) {
//Log.e("Number is too large");
return Float.NaN;
// depends on control dependency: [if], data = [none]
}
significand *= 10;
// depends on control dependency: [while], data = [none]
numTrailingZeroes--;
// depends on control dependency: [while], data = [none]
}
if (significand > TOO_BIG) {
// We will overflow if we continue...
//Log.e("Number is too large");
return Float.NaN;
// depends on control dependency: [if], data = [none]
}
significand = significand * 10 + ((int)ch - (int)'0');
// depends on control dependency: [if], data = [none]
numDigits++;
// depends on control dependency: [if], data = [none]
if (significand < 0)
return Float.NaN; // overflowed from +ve to -ve
}
else if (ch == '.')
{
if (decimalSeen) {
// Stop parsing here. We may be looking at a new number.
break;
}
decimalPos = pos - sigStart;
// depends on control dependency: [if], data = [none]
decimalSeen = true;
// depends on control dependency: [if], data = [none]
}
else
break;
pos++;
// depends on control dependency: [while], data = [none]
}
if (decimalSeen && pos == (decimalPos + 1)) {
// No digits following decimal point (eg. "1.")
//Log.e("Missing fraction part of number");
return Float.NaN;
// depends on control dependency: [if], data = [none]
}
// Have we seen anything number-ish at all so far?
if (numDigits == 0) {
if (numLeadingZeroes == 0) {
//Log.e("Number not found");
return Float.NaN;
// depends on control dependency: [if], data = [none]
}
// Leading zeroes have been seen though, so we
// treat that as a '0'.
numDigits = 1;
// depends on control dependency: [if], data = [none]
}
if (decimalSeen) {
exponent = decimalPos - numLeadingZeroes - numDigits;
// depends on control dependency: [if], data = [none]
} else {
exponent = numTrailingZeroes;
// depends on control dependency: [if], data = [none]
}
// Now look for exponent
if (pos < len)
{
ch = input.charAt(pos);
// depends on control dependency: [if], data = [(pos]
if (ch == 'E' || ch == 'e')
{
boolean expIsNegative = false;
int expVal = 0;
boolean abortExponent = false;
pos++;
// depends on control dependency: [if], data = [none]
if (pos == len) {
// Incomplete exponent.
//Log.e("Incomplete exponent of number");
return Float.NaN;
// depends on control dependency: [if], data = [none]
}
switch (input.charAt(pos)) {
case '-': expIsNegative = true;
// fall through
case '+': pos++;
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
break; // acceptable next char
default:
// any other character is a failure, ie no exponent.
// Could be something legal like "em" though.
abortExponent = true;
pos--; // reset pos to position of 'E'/'e'
// depends on control dependency: [if], data = [none]
}
if (!abortExponent)
{
int expStart = pos;
while (pos < len)
{
ch = input.charAt(pos);
// depends on control dependency: [while], data = [(pos]
if (ch >= '0' && ch <= '9')
{
if (expVal > TOO_BIG) {
// We will overflow if we continue...
//Log.e("Exponent of number is too large");
return Float.NaN;
// depends on control dependency: [if], data = [none]
}
expVal = expVal * 10 + ((int)ch - (int)'0');
// depends on control dependency: [if], data = [none]
pos++;
// depends on control dependency: [if], data = [none]
}
else
break;
}
// Check that at least some exponent digits were read
if (pos == expStart) {
//Log.e(""Incomplete exponent of number"");
return Float.NaN;
// depends on control dependency: [if], data = [none]
}
if (expIsNegative)
exponent -= expVal;
else
exponent += expVal;
}
}
}
// Quick check to eliminate huge exponents.
// Biggest float is (2 - 2^23) . 2^127 ~== 3.4e38
// Biggest negative float is 2^-149 ~== 1.4e-45
// Some numbers that will overflow will get through the scan
// and be returned as 'valid', yet fail when value() is called.
// However they will be very rare and not worth slowing down
// the parse for.
if ((exponent + numDigits) > 39 || (exponent + numDigits) < -44)
return Float.NaN;
float f = (float) significand;
if (significand != 0)
{
// Do exponents > 0
if (exponent > 0)
{
f *= positivePowersOf10[exponent];
}
else if (exponent < 0)
{
// Some valid numbers can have an exponent greater than the max (ie. < -38)
// for a float. For example, significand=123, exponent=-40
// If that's the case, we need to apply the exponent in two steps.
if (exponent < -38) {
// Long.MAX_VALUE is 19 digits, so taking 20 off the exponent should be enough.
f *= 1e-20;
// depends on control dependency: [if], data = [none]
exponent += 20;
// depends on control dependency: [if], data = [none]
}
// Do exponents < 0
f *= negativePowersOf10[-exponent];
}
}
return (isNegative) ? -f : f;
} } |
public class class_name {
public static void unRegisterMixPush() {
AVInstallation installation = AVInstallation.getCurrentInstallation();
String vendor = installation.getString(AVInstallation.VENDOR);
if (!StringUtil.isEmpty(vendor)) {
installation.put(AVInstallation.VENDOR, "lc");
installation.saveInBackground().subscribe(ObserverBuilder.buildSingleObserver(new SaveCallback() {
@Override
public void done(AVException e) {
if (null != e) {
printErrorLog("unRegisterMixPush error!");
} else {
LOGGER.d("Registration canceled successfully!");
}
}
}));
}
} } | public class class_name {
public static void unRegisterMixPush() {
AVInstallation installation = AVInstallation.getCurrentInstallation();
String vendor = installation.getString(AVInstallation.VENDOR);
if (!StringUtil.isEmpty(vendor)) {
installation.put(AVInstallation.VENDOR, "lc"); // depends on control dependency: [if], data = [none]
installation.saveInBackground().subscribe(ObserverBuilder.buildSingleObserver(new SaveCallback() {
@Override
public void done(AVException e) {
if (null != e) {
printErrorLog("unRegisterMixPush error!"); // depends on control dependency: [if], data = [none]
} else {
LOGGER.d("Registration canceled successfully!"); // depends on control dependency: [if], data = [none]
}
}
})); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static final String encode(String str, String charset)
{
if (charset.contains("8859"))
{
return encode(str, entityMapISO8859);
}
else
{
if (charset.toLowerCase().contains("utf"))
{
return encode(str, entityMapUTF8);
}
else
{
return encode(str, entityMapPlain);
}
}
} } | public class class_name {
public static final String encode(String str, String charset)
{
if (charset.contains("8859"))
{
return encode(str, entityMapISO8859);
// depends on control dependency: [if], data = [none]
}
else
{
if (charset.toLowerCase().contains("utf"))
{
return encode(str, entityMapUTF8);
// depends on control dependency: [if], data = [none]
}
else
{
return encode(str, entityMapPlain);
// depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
@Override
public void removeByGroupId(long groupId) {
for (CommerceShipmentItem commerceShipmentItem : findByGroupId(
groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commerceShipmentItem);
}
} } | public class class_name {
@Override
public void removeByGroupId(long groupId) {
for (CommerceShipmentItem commerceShipmentItem : findByGroupId(
groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commerceShipmentItem); // depends on control dependency: [for], data = [commerceShipmentItem]
}
} } |
public class class_name {
public void marshall(GetAssignmentRequest getAssignmentRequest, ProtocolMarshaller protocolMarshaller) {
if (getAssignmentRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getAssignmentRequest.getAssignmentId(), ASSIGNMENTID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(GetAssignmentRequest getAssignmentRequest, ProtocolMarshaller protocolMarshaller) {
if (getAssignmentRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getAssignmentRequest.getAssignmentId(), ASSIGNMENTID_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static List<MethodNode> chooseBestMethod(final ClassNode receiver, Collection<MethodNode> methods, ClassNode... args) {
if (methods.isEmpty()) return Collections.emptyList();
if (isUsingUncheckedGenerics(receiver)) {
ClassNode raw = makeRawType(receiver);
return chooseBestMethod(raw, methods, args);
}
List<MethodNode> bestChoices = new LinkedList<MethodNode>();
int bestDist = Integer.MAX_VALUE;
Collection<MethodNode> choicesLeft = removeCovariantsAndInterfaceEquivalents(methods);
for (MethodNode candidateNode : choicesLeft) {
ClassNode declaringClassForDistance = candidateNode.getDeclaringClass();
ClassNode actualReceiverForDistance = receiver != null ? receiver : candidateNode.getDeclaringClass();
MethodNode safeNode = candidateNode;
ClassNode[] safeArgs = args;
boolean isExtensionMethodNode = candidateNode instanceof ExtensionMethodNode;
if (isExtensionMethodNode) {
safeArgs = new ClassNode[args.length + 1];
System.arraycopy(args, 0, safeArgs, 1, args.length);
safeArgs[0] = receiver;
safeNode = ((ExtensionMethodNode) candidateNode).getExtensionMethodNode();
}
// todo : corner case
/*
class B extends A {}
Animal foo(A o) {...}
Person foo(B i){...}
B a = new B()
Person p = foo(b)
*/
Map<GenericsType, GenericsType> declaringAndActualGenericsTypeMap = GenericsUtils.makeDeclaringAndActualGenericsTypeMap(declaringClassForDistance, actualReceiverForDistance);
Parameter[] params = makeRawTypes(safeNode.getParameters(), declaringAndActualGenericsTypeMap);
int dist = measureParametersAndArgumentsDistance(params, safeArgs);
if (dist >= 0) {
dist += getClassDistance(declaringClassForDistance, actualReceiverForDistance);
dist += getExtensionDistance(isExtensionMethodNode);
if (dist < bestDist) {
bestChoices.clear();
bestChoices.add(candidateNode);
bestDist = dist;
} else if (dist == bestDist) {
bestChoices.add(candidateNode);
}
}
}
if (bestChoices.size() > 1) {
// GROOVY-6849: prefer extension methods in case of ambiguity
List<MethodNode> onlyExtensionMethods = new LinkedList<MethodNode>();
for (MethodNode choice : bestChoices) {
if (choice instanceof ExtensionMethodNode) {
onlyExtensionMethods.add(choice);
}
}
if (onlyExtensionMethods.size() == 1) {
return onlyExtensionMethods;
}
}
return bestChoices;
} } | public class class_name {
public static List<MethodNode> chooseBestMethod(final ClassNode receiver, Collection<MethodNode> methods, ClassNode... args) {
if (methods.isEmpty()) return Collections.emptyList();
if (isUsingUncheckedGenerics(receiver)) {
ClassNode raw = makeRawType(receiver);
return chooseBestMethod(raw, methods, args); // depends on control dependency: [if], data = [none]
}
List<MethodNode> bestChoices = new LinkedList<MethodNode>();
int bestDist = Integer.MAX_VALUE;
Collection<MethodNode> choicesLeft = removeCovariantsAndInterfaceEquivalents(methods);
for (MethodNode candidateNode : choicesLeft) {
ClassNode declaringClassForDistance = candidateNode.getDeclaringClass();
ClassNode actualReceiverForDistance = receiver != null ? receiver : candidateNode.getDeclaringClass();
MethodNode safeNode = candidateNode;
ClassNode[] safeArgs = args;
boolean isExtensionMethodNode = candidateNode instanceof ExtensionMethodNode;
if (isExtensionMethodNode) {
safeArgs = new ClassNode[args.length + 1]; // depends on control dependency: [if], data = [none]
System.arraycopy(args, 0, safeArgs, 1, args.length); // depends on control dependency: [if], data = [none]
safeArgs[0] = receiver; // depends on control dependency: [if], data = [none]
safeNode = ((ExtensionMethodNode) candidateNode).getExtensionMethodNode(); // depends on control dependency: [if], data = [none]
}
// todo : corner case
/*
class B extends A {}
Animal foo(A o) {...}
Person foo(B i){...}
B a = new B()
Person p = foo(b)
*/
Map<GenericsType, GenericsType> declaringAndActualGenericsTypeMap = GenericsUtils.makeDeclaringAndActualGenericsTypeMap(declaringClassForDistance, actualReceiverForDistance);
Parameter[] params = makeRawTypes(safeNode.getParameters(), declaringAndActualGenericsTypeMap);
int dist = measureParametersAndArgumentsDistance(params, safeArgs);
if (dist >= 0) {
dist += getClassDistance(declaringClassForDistance, actualReceiverForDistance); // depends on control dependency: [if], data = [none]
dist += getExtensionDistance(isExtensionMethodNode); // depends on control dependency: [if], data = [none]
if (dist < bestDist) {
bestChoices.clear(); // depends on control dependency: [if], data = [none]
bestChoices.add(candidateNode); // depends on control dependency: [if], data = [none]
bestDist = dist; // depends on control dependency: [if], data = [none]
} else if (dist == bestDist) {
bestChoices.add(candidateNode); // depends on control dependency: [if], data = [none]
}
}
}
if (bestChoices.size() > 1) {
// GROOVY-6849: prefer extension methods in case of ambiguity
List<MethodNode> onlyExtensionMethods = new LinkedList<MethodNode>();
for (MethodNode choice : bestChoices) {
if (choice instanceof ExtensionMethodNode) {
onlyExtensionMethods.add(choice); // depends on control dependency: [if], data = [none]
}
}
if (onlyExtensionMethods.size() == 1) {
return onlyExtensionMethods; // depends on control dependency: [if], data = [none]
}
}
return bestChoices;
} } |
public class class_name {
private String checkSuperClass(String classSegment) {
if (builder.isRemoveSuperClass() || builder.getSuperClass() != null) {
Matcher matcher = PATTERN_FIND_SUPER_CLASS.matcher(classSegment);
String superClassString = "";
if (builder.getSuperClass() != null) {
superClassString = "extends " + builder.getSuperClass() + " ";
}
if (matcher.find()) {
String replacement = matcher.group();
classSegment = StringHelper.replaceFirst(classSegment, replacement, superClassString);
} else {
Matcher classNameMatcher = PATTERN_FIND_CLASS_NAME.matcher(classSegment);
if (classNameMatcher.find()) {
String className = classNameMatcher.group();
String justClassName = findClassName(className);
if (justClassName != null && justClassName.equals(builder.getSuperClass())) {
return classSegment;
}
classSegment = StringHelper.replaceFirst(classSegment, className, className + superClassString);
}
}
}
return classSegment;
} } | public class class_name {
private String checkSuperClass(String classSegment) {
if (builder.isRemoveSuperClass() || builder.getSuperClass() != null) {
Matcher matcher = PATTERN_FIND_SUPER_CLASS.matcher(classSegment);
String superClassString = "";
if (builder.getSuperClass() != null) {
superClassString = "extends " + builder.getSuperClass() + " "; // depends on control dependency: [if], data = [none]
}
if (matcher.find()) {
String replacement = matcher.group();
classSegment = StringHelper.replaceFirst(classSegment, replacement, superClassString); // depends on control dependency: [if], data = [none]
} else {
Matcher classNameMatcher = PATTERN_FIND_CLASS_NAME.matcher(classSegment);
if (classNameMatcher.find()) {
String className = classNameMatcher.group();
String justClassName = findClassName(className);
if (justClassName != null && justClassName.equals(builder.getSuperClass())) {
return classSegment; // depends on control dependency: [if], data = [none]
}
classSegment = StringHelper.replaceFirst(classSegment, className, className + superClassString); // depends on control dependency: [if], data = [none]
}
}
}
return classSegment;
} } |
public class class_name {
@Trivial
public boolean isProviderResource(String resourceName) {
Collection<String> useResourceNames = getResourceNames();
if ( useResourceNames.contains(resourceName) ) {
return true;
}
// If the resource name already has a leading slash, there
// is no additional testing to do. Do NOT test again by
// removing a leading slash. Annotation processing will remove
// a leading slass, but will never add a leading slash.
// The resource name is expected to be the name of a class resource,
// which should never be empty. However, let's double check,
// and avoid any possible IndexOutOfBounds exception.
if ( resourceName.length() == 0) {
return false;
} else if ( resourceName.charAt(0) == '/' ) {
return false;
}
return useResourceNames.contains("/" + resourceName);
} } | public class class_name {
@Trivial
public boolean isProviderResource(String resourceName) {
Collection<String> useResourceNames = getResourceNames();
if ( useResourceNames.contains(resourceName) ) {
return true; // depends on control dependency: [if], data = [none]
}
// If the resource name already has a leading slash, there
// is no additional testing to do. Do NOT test again by
// removing a leading slash. Annotation processing will remove
// a leading slass, but will never add a leading slash.
// The resource name is expected to be the name of a class resource,
// which should never be empty. However, let's double check,
// and avoid any possible IndexOutOfBounds exception.
if ( resourceName.length() == 0) {
return false; // depends on control dependency: [if], data = [none]
} else if ( resourceName.charAt(0) == '/' ) {
return false; // depends on control dependency: [if], data = [none]
}
return useResourceNames.contains("/" + resourceName);
} } |
public class class_name {
void handleBoth(CoreSubscriber<? super R> s,
Publisher<? extends T>[] srcs,
@Nullable Object[] scalars,
int n,
int sc) {
if (sc != 0 && scalars != null) {
if (n != sc) {
ZipSingleCoordinator<T, R> coordinator =
new ZipSingleCoordinator<>(s, scalars, n, zipper);
s.onSubscribe(coordinator);
coordinator.subscribe(n, sc, srcs);
}
else {
Operators.MonoSubscriber<R, R> sds = new Operators.MonoSubscriber<>(s);
s.onSubscribe(sds);
R r;
try {
r = Objects.requireNonNull(zipper.apply(scalars),
"The zipper returned a null value");
}
catch (Throwable e) {
s.onError(Operators.onOperatorError(e, s.currentContext()));
return;
}
sds.complete(r);
}
}
else {
ZipCoordinator<T, R> coordinator =
new ZipCoordinator<>(s, zipper, n, queueSupplier, prefetch);
s.onSubscribe(coordinator);
coordinator.subscribe(srcs, n);
}
} } | public class class_name {
void handleBoth(CoreSubscriber<? super R> s,
Publisher<? extends T>[] srcs,
@Nullable Object[] scalars,
int n,
int sc) {
if (sc != 0 && scalars != null) {
if (n != sc) {
ZipSingleCoordinator<T, R> coordinator =
new ZipSingleCoordinator<>(s, scalars, n, zipper);
s.onSubscribe(coordinator); // depends on control dependency: [if], data = [none]
coordinator.subscribe(n, sc, srcs); // depends on control dependency: [if], data = [(n]
}
else {
Operators.MonoSubscriber<R, R> sds = new Operators.MonoSubscriber<>(s);
s.onSubscribe(sds); // depends on control dependency: [if], data = [none]
R r;
try {
r = Objects.requireNonNull(zipper.apply(scalars),
"The zipper returned a null value"); // depends on control dependency: [try], data = [none]
}
catch (Throwable e) {
s.onError(Operators.onOperatorError(e, s.currentContext()));
return;
} // depends on control dependency: [catch], data = [none]
sds.complete(r); // depends on control dependency: [if], data = [none]
}
}
else {
ZipCoordinator<T, R> coordinator =
new ZipCoordinator<>(s, zipper, n, queueSupplier, prefetch);
s.onSubscribe(coordinator); // depends on control dependency: [if], data = [none]
coordinator.subscribe(srcs, n); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private boolean canPasteFromClipboard() {
try {
return textComponent.getTransferHandler().canImport(
textComponent,
Toolkit.getDefaultToolkit().getSystemClipboard().getContents(textComponent)
.getTransferDataFlavors());
}
catch (IllegalStateException e) {
/*
* as the javadoc of Clipboard.getContents state: the
* IllegalStateException can be thrown when the clipboard is not
* available (i.e. in use by another application), so we return
* false.
*/
return false;
}
} } | public class class_name {
private boolean canPasteFromClipboard() {
try {
return textComponent.getTransferHandler().canImport(
textComponent,
Toolkit.getDefaultToolkit().getSystemClipboard().getContents(textComponent)
.getTransferDataFlavors()); // depends on control dependency: [try], data = [none]
}
catch (IllegalStateException e) {
/*
* as the javadoc of Clipboard.getContents state: the
* IllegalStateException can be thrown when the clipboard is not
* available (i.e. in use by another application), so we return
* false.
*/
return false;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static <T extends Enum<T>> T getEnumValue(Class<T> enumType,
String name) {
if (StringUtils.isEmpty(name)) {
return null;
}
try {
T v = Enum.valueOf(enumType, name);
return v;
} catch (IllegalArgumentException e) {
return null;
}
} } | public class class_name {
public static <T extends Enum<T>> T getEnumValue(Class<T> enumType,
String name) {
if (StringUtils.isEmpty(name)) {
return null; // depends on control dependency: [if], data = [none]
}
try {
T v = Enum.valueOf(enumType, name);
return v; // depends on control dependency: [try], data = [none]
} catch (IllegalArgumentException e) {
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static String encodeBytes(byte[] bytes)
{
String ret = null;
try
{
// Obfuscate the string
if(bytes != null)
ret = new String(Base64.encodeBase64(bytes));
}
catch(NoClassDefFoundError e)
{
ret = new String(bytes);
System.out.println("WARNING: unable to encode: "
+e.getClass().getName()+": "+e.getMessage());
}
return ret;
} } | public class class_name {
public static String encodeBytes(byte[] bytes)
{
String ret = null;
try
{
// Obfuscate the string
if(bytes != null)
ret = new String(Base64.encodeBase64(bytes));
}
catch(NoClassDefFoundError e)
{
ret = new String(bytes);
System.out.println("WARNING: unable to encode: "
+e.getClass().getName()+": "+e.getMessage());
} // depends on control dependency: [catch], data = [none]
return ret;
} } |
public class class_name {
public PdfNumber getAsNumber(PdfName key) {
PdfNumber number = null;
PdfObject orig = getDirectObject(key);
if (orig != null && orig.isNumber()) {
number = (PdfNumber) orig;
}
return number;
} } | public class class_name {
public PdfNumber getAsNumber(PdfName key) {
PdfNumber number = null;
PdfObject orig = getDirectObject(key);
if (orig != null && orig.isNumber()) {
number = (PdfNumber) orig; // depends on control dependency: [if], data = [none]
}
return number;
} } |
public class class_name {
public void marshall(ColorCorrector colorCorrector, ProtocolMarshaller protocolMarshaller) {
if (colorCorrector == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(colorCorrector.getBrightness(), BRIGHTNESS_BINDING);
protocolMarshaller.marshall(colorCorrector.getColorSpaceConversion(), COLORSPACECONVERSION_BINDING);
protocolMarshaller.marshall(colorCorrector.getContrast(), CONTRAST_BINDING);
protocolMarshaller.marshall(colorCorrector.getHdr10Metadata(), HDR10METADATA_BINDING);
protocolMarshaller.marshall(colorCorrector.getHue(), HUE_BINDING);
protocolMarshaller.marshall(colorCorrector.getSaturation(), SATURATION_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ColorCorrector colorCorrector, ProtocolMarshaller protocolMarshaller) {
if (colorCorrector == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(colorCorrector.getBrightness(), BRIGHTNESS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(colorCorrector.getColorSpaceConversion(), COLORSPACECONVERSION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(colorCorrector.getContrast(), CONTRAST_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(colorCorrector.getHdr10Metadata(), HDR10METADATA_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(colorCorrector.getHue(), HUE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(colorCorrector.getSaturation(), SATURATION_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void setTagValues(java.util.Collection<String> tagValues) {
if (tagValues == null) {
this.tagValues = null;
return;
}
this.tagValues = new java.util.ArrayList<String>(tagValues);
} } | public class class_name {
public void setTagValues(java.util.Collection<String> tagValues) {
if (tagValues == null) {
this.tagValues = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.tagValues = new java.util.ArrayList<String>(tagValues);
} } |
public class class_name {
public Observable<ServiceResponse<Page<IntegrationAccountSchemaInner>>> listByIntegrationAccountsNextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = String.format("%s", nextPageLink);
return service.listByIntegrationAccountsNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<IntegrationAccountSchemaInner>>>>() {
@Override
public Observable<ServiceResponse<Page<IntegrationAccountSchemaInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<IntegrationAccountSchemaInner>> result = listByIntegrationAccountsNextDelegate(response);
return Observable.just(new ServiceResponse<Page<IntegrationAccountSchemaInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} } | public class class_name {
public Observable<ServiceResponse<Page<IntegrationAccountSchemaInner>>> listByIntegrationAccountsNextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = String.format("%s", nextPageLink);
return service.listByIntegrationAccountsNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<IntegrationAccountSchemaInner>>>>() {
@Override
public Observable<ServiceResponse<Page<IntegrationAccountSchemaInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<IntegrationAccountSchemaInner>> result = listByIntegrationAccountsNextDelegate(response);
return Observable.just(new ServiceResponse<Page<IntegrationAccountSchemaInner>>(result.body(), result.response())); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
return Observable.error(t);
} // depends on control dependency: [catch], data = [none]
}
});
} } |
public class class_name {
protected Properties getJdbcProperties(JdbcConnectionDescriptor jcd,
String user, String password)
{
final Properties jdbcProperties;
jdbcProperties = jcd.getConnectionPoolDescriptor().getJdbcProperties();
if (user != null)
{
jdbcProperties.put("user", user);
jdbcProperties.put("password", password);
}
return jdbcProperties;
} } | public class class_name {
protected Properties getJdbcProperties(JdbcConnectionDescriptor jcd,
String user, String password)
{
final Properties jdbcProperties;
jdbcProperties = jcd.getConnectionPoolDescriptor().getJdbcProperties();
if (user != null)
{
jdbcProperties.put("user", user);
// depends on control dependency: [if], data = [none]
jdbcProperties.put("password", password);
// depends on control dependency: [if], data = [none]
}
return jdbcProperties;
} } |
public class class_name {
public void marshall(NamespaceFilter namespaceFilter, ProtocolMarshaller protocolMarshaller) {
if (namespaceFilter == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(namespaceFilter.getName(), NAME_BINDING);
protocolMarshaller.marshall(namespaceFilter.getValues(), VALUES_BINDING);
protocolMarshaller.marshall(namespaceFilter.getCondition(), CONDITION_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(NamespaceFilter namespaceFilter, ProtocolMarshaller protocolMarshaller) {
if (namespaceFilter == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(namespaceFilter.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(namespaceFilter.getValues(), VALUES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(namespaceFilter.getCondition(), CONDITION_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 ClassLoader getClassLoader(ComponentMetaData metaData) {
ModuleMetaData moduleMetaData = (metaData != null) ? metaData.getModuleMetaData() : null;
if (moduleMetaData instanceof WebModuleMetaData) {
WebAppConfiguration webAppConfiguration = (WebAppConfiguration) ((WebModuleMetaData)moduleMetaData).getConfiguration();
return webAppConfiguration.getWebApp().getClassLoader();
} else {
return null;
}
} } | public class class_name {
@Override
public ClassLoader getClassLoader(ComponentMetaData metaData) {
ModuleMetaData moduleMetaData = (metaData != null) ? metaData.getModuleMetaData() : null;
if (moduleMetaData instanceof WebModuleMetaData) {
WebAppConfiguration webAppConfiguration = (WebAppConfiguration) ((WebModuleMetaData)moduleMetaData).getConfiguration();
return webAppConfiguration.getWebApp().getClassLoader(); // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public FileDeleteFromComputeNodeOptions withOcpDate(DateTime ocpDate) {
if (ocpDate == null) {
this.ocpDate = null;
} else {
this.ocpDate = new DateTimeRfc1123(ocpDate);
}
return this;
} } | public class class_name {
public FileDeleteFromComputeNodeOptions withOcpDate(DateTime ocpDate) {
if (ocpDate == null) {
this.ocpDate = null; // depends on control dependency: [if], data = [none]
} else {
this.ocpDate = new DateTimeRfc1123(ocpDate); // depends on control dependency: [if], data = [(ocpDate]
}
return this;
} } |
public class class_name {
public static String prepareCompositeKey(final EntityMetadata m, final Object compositeKey)
{
Field[] fields = m.getIdAttribute().getBindableJavaType().getDeclaredFields();
StringBuilder stringBuilder = new StringBuilder();
for (Field f : fields)
{
if (!ReflectUtils.isTransientOrStatic(f))
{
try
{
String fieldValue = PropertyAccessorHelper.getString(compositeKey, f);
// what if field value is null????
stringBuilder.append(fieldValue);
stringBuilder.append(COMPOSITE_KEY_SEPERATOR);
}
catch (IllegalArgumentException e)
{
logger.error("Error during prepare composite key, Caused by {}.", e);
throw new PersistenceException(e);
}
}
}
if (stringBuilder.length() > 0)
{
stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(COMPOSITE_KEY_SEPERATOR));
}
return stringBuilder.toString();
} } | public class class_name {
public static String prepareCompositeKey(final EntityMetadata m, final Object compositeKey)
{
Field[] fields = m.getIdAttribute().getBindableJavaType().getDeclaredFields();
StringBuilder stringBuilder = new StringBuilder();
for (Field f : fields)
{
if (!ReflectUtils.isTransientOrStatic(f))
{
try
{
String fieldValue = PropertyAccessorHelper.getString(compositeKey, f);
// what if field value is null????
stringBuilder.append(fieldValue); // depends on control dependency: [try], data = [none]
stringBuilder.append(COMPOSITE_KEY_SEPERATOR); // depends on control dependency: [try], data = [none]
}
catch (IllegalArgumentException e)
{
logger.error("Error during prepare composite key, Caused by {}.", e);
throw new PersistenceException(e);
} // depends on control dependency: [catch], data = [none]
}
}
if (stringBuilder.length() > 0)
{
stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(COMPOSITE_KEY_SEPERATOR)); // depends on control dependency: [if], data = [none]
}
return stringBuilder.toString();
} } |
public class class_name {
public static final String format(String json) {
final int len = json.length();
if (len < 3) {
return json;
}
final StringTokenizer st = new StringTokenizer(json, ",{}[]", true);
final StringBuilder out = new StringBuilder(len * 2);
String token;
int indent = 0;
while (st.hasMoreTokens()) {
token = st.nextToken();
if ("{".equals(token) || "[".equals(token)) {
indent++;
out.append(token);
appendIndent(out, indent);
continue;
}
if ("}".equals(token) || "]".equals(token)) {
indent--;
appendIndent(out, indent);
out.append(token);
continue;
}
if (",".equals(token)) {
out.append(',');
appendIndent(out, indent);
continue;
}
out.append(token);
}
return out.toString();
} } | public class class_name {
public static final String format(String json) {
final int len = json.length();
if (len < 3) {
return json;
// depends on control dependency: [if], data = [none]
}
final StringTokenizer st = new StringTokenizer(json, ",{}[]", true);
final StringBuilder out = new StringBuilder(len * 2);
String token;
int indent = 0;
while (st.hasMoreTokens()) {
token = st.nextToken();
// depends on control dependency: [while], data = [none]
if ("{".equals(token) || "[".equals(token)) {
indent++;
// depends on control dependency: [if], data = [none]
out.append(token);
// depends on control dependency: [if], data = [none]
appendIndent(out, indent);
// depends on control dependency: [if], data = [none]
continue;
}
if ("}".equals(token) || "]".equals(token)) {
indent--;
// depends on control dependency: [if], data = [none]
appendIndent(out, indent);
// depends on control dependency: [if], data = [none]
out.append(token);
// depends on control dependency: [if], data = [none]
continue;
}
if (",".equals(token)) {
out.append(',');
// depends on control dependency: [if], data = [none]
appendIndent(out, indent);
// depends on control dependency: [if], data = [none]
continue;
}
out.append(token);
// depends on control dependency: [while], data = [none]
}
return out.toString();
} } |
public class class_name {
public static String read(InputStream input) {
try {
StringBuilder bld = new StringBuilder();
Reader reader = new InputStreamReader(input, "utf-8");
int ch;
while ((ch = reader.read()) >= 0)
bld.append((char)ch);
return bld.toString();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
} } | public class class_name {
public static String read(InputStream input) {
try {
StringBuilder bld = new StringBuilder();
Reader reader = new InputStreamReader(input, "utf-8");
int ch;
while ((ch = reader.read()) >= 0)
bld.append((char)ch);
return bld.toString();
// depends on control dependency: [try], data = [none]
} catch (IOException ex) {
throw new RuntimeException(ex);
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(LinkEvent event) {
final String fragmentTag = event.getFragmentTag();
mRTApi.removeFragment(fragmentTag);
if (!event.wasCancelled() && ID_01_LINK_FRAGMENT.equals(fragmentTag)) {
RTEditText editor = getActiveEditor();
if (editor != null) {
Link link = event.getLink();
String url = null;
if (link != null && link.isValid()) {
// the mLinkSelection.end() <= editor.length() check is necessary since
// the editor text can change when the link fragment is open
Selection selection = mLinkSelection != null && mLinkSelection.end() <= editor.length() ? mLinkSelection : new Selection(editor);
String linkText = link.getLinkText();
// if no text is selected this inserts the entered link text
// if text is selected we replace it by the link text
Editable str = editor.getText();
str.replace(selection.start(), selection.end(), linkText);
editor.setSelection(selection.start(), selection.start() + linkText.length());
url = link.getUrl();
}
editor.applyEffect(Effects.LINK, url); // if url == null -> remove the link
}
}
} } | public class class_name {
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(LinkEvent event) {
final String fragmentTag = event.getFragmentTag();
mRTApi.removeFragment(fragmentTag);
if (!event.wasCancelled() && ID_01_LINK_FRAGMENT.equals(fragmentTag)) {
RTEditText editor = getActiveEditor();
if (editor != null) {
Link link = event.getLink();
String url = null;
if (link != null && link.isValid()) {
// the mLinkSelection.end() <= editor.length() check is necessary since
// the editor text can change when the link fragment is open
Selection selection = mLinkSelection != null && mLinkSelection.end() <= editor.length() ? mLinkSelection : new Selection(editor);
String linkText = link.getLinkText();
// if no text is selected this inserts the entered link text
// if text is selected we replace it by the link text
Editable str = editor.getText();
str.replace(selection.start(), selection.end(), linkText); // depends on control dependency: [if], data = [none]
editor.setSelection(selection.start(), selection.start() + linkText.length()); // depends on control dependency: [if], data = [none]
url = link.getUrl(); // depends on control dependency: [if], data = [none]
}
editor.applyEffect(Effects.LINK, url); // if url == null -> remove the link // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
@Override
public String toJSONString() {
JSONStringer js = new JSONStringer();
try {
js.object();
// status code (1 byte)
js.keySymbolValuePair(JSON_STATUS_KEY, getStatusCode());
// column schema
js.key(JSON_SCHEMA_KEY).array();
for (int i = 0; i < getColumnCount(); i++) {
js.object();
js.keySymbolValuePair(JSON_NAME_KEY, getColumnName(i));
js.keySymbolValuePair(JSON_TYPE_KEY, getColumnType(i).getValue());
js.endObject();
}
js.endArray();
// row data
js.key(JSON_DATA_KEY).array();
VoltTableRow row = cloneRow();
row.resetRowPosition();
while (row.advanceRow()) {
js.array();
for (int i = 0; i < getColumnCount(); i++) {
row.putJSONRep(i, js);
}
js.endArray();
}
js.endArray();
js.endObject();
}
catch (JSONException e) {
e.printStackTrace();
throw new RuntimeException("Failed to serialized a table to JSON.", e);
}
return js.toString();
} } | public class class_name {
@Override
public String toJSONString() {
JSONStringer js = new JSONStringer();
try {
js.object(); // depends on control dependency: [try], data = [none]
// status code (1 byte)
js.keySymbolValuePair(JSON_STATUS_KEY, getStatusCode()); // depends on control dependency: [try], data = [none]
// column schema
js.key(JSON_SCHEMA_KEY).array(); // depends on control dependency: [try], data = [none]
for (int i = 0; i < getColumnCount(); i++) {
js.object(); // depends on control dependency: [for], data = [none]
js.keySymbolValuePair(JSON_NAME_KEY, getColumnName(i)); // depends on control dependency: [for], data = [i]
js.keySymbolValuePair(JSON_TYPE_KEY, getColumnType(i).getValue()); // depends on control dependency: [for], data = [i]
js.endObject(); // depends on control dependency: [for], data = [none]
}
js.endArray(); // depends on control dependency: [try], data = [none]
// row data
js.key(JSON_DATA_KEY).array(); // depends on control dependency: [try], data = [none]
VoltTableRow row = cloneRow();
row.resetRowPosition(); // depends on control dependency: [try], data = [none]
while (row.advanceRow()) {
js.array(); // depends on control dependency: [while], data = [none]
for (int i = 0; i < getColumnCount(); i++) {
row.putJSONRep(i, js); // depends on control dependency: [for], data = [i]
}
js.endArray(); // depends on control dependency: [while], data = [none]
}
js.endArray(); // depends on control dependency: [try], data = [none]
js.endObject(); // depends on control dependency: [try], data = [none]
}
catch (JSONException e) {
e.printStackTrace();
throw new RuntimeException("Failed to serialized a table to JSON.", e);
} // depends on control dependency: [catch], data = [none]
return js.toString();
} } |
public class class_name {
@SuppressWarnings({"Duplicates"})
public static BufferByteOutput<ByteBuffer> of(final int capacity, final WritableByteChannel channel) {
if (capacity <= 0) {
throw new IllegalArgumentException("capacity(" + capacity + ") <= 0");
}
if (channel == null) {
throw new NullPointerException("channel is null");
}
return new BufferByteOutput<ByteBuffer>(null) {
@Override
public void write(final int value) throws IOException {
if (target == null) {
target = ByteBuffer.allocate(capacity); // position: zero, limit: capacity
}
if (!target.hasRemaining()) { // no space to put
target.flip(); // limit -> position, position -> zero
do {
channel.write(target);
} while (target.position() == 0);
target.compact();
}
super.write(value);
}
@Override
public void setTarget(final ByteBuffer target) {
throw new UnsupportedOperationException();
}
};
} } | public class class_name {
@SuppressWarnings({"Duplicates"})
public static BufferByteOutput<ByteBuffer> of(final int capacity, final WritableByteChannel channel) {
if (capacity <= 0) {
throw new IllegalArgumentException("capacity(" + capacity + ") <= 0");
}
if (channel == null) {
throw new NullPointerException("channel is null");
}
return new BufferByteOutput<ByteBuffer>(null) {
@Override
public void write(final int value) throws IOException {
if (target == null) {
target = ByteBuffer.allocate(capacity); // position: zero, limit: capacity
}
if (!target.hasRemaining()) { // no space to put
target.flip(); // limit -> position, position -> zero // depends on control dependency: [if], data = [none]
do {
channel.write(target);
} while (target.position() == 0);
target.compact(); // depends on control dependency: [if], data = [none]
}
super.write(value);
}
@Override
public void setTarget(final ByteBuffer target) {
throw new UnsupportedOperationException();
}
};
} } |
public class class_name {
public String format(String key,
Object[] objects) {
if (traceNLS != null) {
return traceNLS.getFormattedMessage(key,
objects,
defaultMessage);
} else {
return objectsToString(key, objects);
}
} } | public class class_name {
public String format(String key,
Object[] objects) {
if (traceNLS != null) {
return traceNLS.getFormattedMessage(key,
objects,
defaultMessage); // depends on control dependency: [if], data = [none]
} else {
return objectsToString(key, objects); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void put(final String key, final String value) {
if (StringUtils.isBlank(value)) {
this.properties.remove(key);
} else {
this.properties.put(key, value);
}
} } | public class class_name {
public void put(final String key, final String value) {
if (StringUtils.isBlank(value)) {
this.properties.remove(key); // depends on control dependency: [if], data = [none]
} else {
this.properties.put(key, value); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected FeatureStyle getFeatureStyle(FeatureRow featureRow) {
FeatureStyle featureStyle = null;
if (featureTableStyles != null) {
featureStyle = featureTableStyles.getFeatureStyle(featureRow);
}
return featureStyle;
} } | public class class_name {
protected FeatureStyle getFeatureStyle(FeatureRow featureRow) {
FeatureStyle featureStyle = null;
if (featureTableStyles != null) {
featureStyle = featureTableStyles.getFeatureStyle(featureRow); // depends on control dependency: [if], data = [none]
}
return featureStyle;
} } |
public class class_name {
private synchronized long catchUp(long nextSequenceNumber) {
JournalReader journalReader = new UfsJournalReader(this, nextSequenceNumber, true);
try {
return catchUp(journalReader);
} finally {
try {
journalReader.close();
} catch (IOException e) {
LOG.warn("Failed to close journal reader: {}", e.toString());
}
}
} } | public class class_name {
private synchronized long catchUp(long nextSequenceNumber) {
JournalReader journalReader = new UfsJournalReader(this, nextSequenceNumber, true);
try {
return catchUp(journalReader); // depends on control dependency: [try], data = [none]
} finally {
try {
journalReader.close(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
LOG.warn("Failed to close journal reader: {}", e.toString());
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public void register(InternalIndex index) {
String[] components = index.getComponents();
String attribute = components == null ? index.getName() : components[0];
Record record = registry.get(attribute);
if (record == null) {
record = new Record();
registry.put(attribute, record);
}
if (index.isOrdered()) {
if (record.orderedWorseThan(index)) {
record.ordered = components == null ? index : new FirstComponentDecorator(index);
}
} else {
if (record.unorderedWorseThan(index)) {
record.unordered = index;
}
}
} } | public class class_name {
public void register(InternalIndex index) {
String[] components = index.getComponents();
String attribute = components == null ? index.getName() : components[0];
Record record = registry.get(attribute);
if (record == null) {
record = new Record(); // depends on control dependency: [if], data = [none]
registry.put(attribute, record); // depends on control dependency: [if], data = [none]
}
if (index.isOrdered()) {
if (record.orderedWorseThan(index)) {
record.ordered = components == null ? index : new FirstComponentDecorator(index); // depends on control dependency: [if], data = [none]
}
} else {
if (record.unorderedWorseThan(index)) {
record.unordered = index; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static String getVersion(String variant) {
Object data = getCalendarSystem(variant);
if (data instanceof AstronomicalHijriData) {
return AstronomicalHijriData.class.cast(data).getVersion();
}
return "";
} } | public class class_name {
public static String getVersion(String variant) {
Object data = getCalendarSystem(variant);
if (data instanceof AstronomicalHijriData) {
return AstronomicalHijriData.class.cast(data).getVersion(); // depends on control dependency: [if], data = [none]
}
return "";
} } |
public class class_name {
public TextCharacter withBackgroundColor(TextColor backgroundColor) {
if(this.backgroundColor == backgroundColor || this.backgroundColor.equals(backgroundColor)) {
return this;
}
return new TextCharacter(character, foregroundColor, backgroundColor, modifiers);
} } | public class class_name {
public TextCharacter withBackgroundColor(TextColor backgroundColor) {
if(this.backgroundColor == backgroundColor || this.backgroundColor.equals(backgroundColor)) {
return this; // depends on control dependency: [if], data = [none]
}
return new TextCharacter(character, foregroundColor, backgroundColor, modifiers);
} } |
public class class_name {
public final void abort()
{
int frameLength = buffer.capacity();
if (ByteOrder.nativeOrder() != LITTLE_ENDIAN)
{
frameLength = Integer.reverseBytes(frameLength);
}
buffer.putShort(TYPE_FIELD_OFFSET, (short)HDR_TYPE_PAD, LITTLE_ENDIAN);
buffer.putIntOrdered(FRAME_LENGTH_FIELD_OFFSET, frameLength);
} } | public class class_name {
public final void abort()
{
int frameLength = buffer.capacity();
if (ByteOrder.nativeOrder() != LITTLE_ENDIAN)
{
frameLength = Integer.reverseBytes(frameLength); // depends on control dependency: [if], data = [none]
}
buffer.putShort(TYPE_FIELD_OFFSET, (short)HDR_TYPE_PAD, LITTLE_ENDIAN);
buffer.putIntOrdered(FRAME_LENGTH_FIELD_OFFSET, frameLength);
} } |
public class class_name {
public void setSecurityControllerMap(Map map) {
for( Iterator i = map.entrySet().iterator(); i.hasNext(); ) {
Map.Entry entry = (Map.Entry) i.next();
registerSecurityControllerAlias( (String) entry.getKey(), (SecurityController) entry.getValue() );
}
} } | public class class_name {
public void setSecurityControllerMap(Map map) {
for( Iterator i = map.entrySet().iterator(); i.hasNext(); ) {
Map.Entry entry = (Map.Entry) i.next();
registerSecurityControllerAlias( (String) entry.getKey(), (SecurityController) entry.getValue() ); // depends on control dependency: [for], data = [none]
}
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.