code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
---|---|
public class class_name {
public void setSocket(Socket socket) {
if (socket != null)
{
m_remoteAddress = socket.getInetAddress();
this.port = socket.getPort();
m_controlThread = new DebugControlConnectionThread(socket, this);
m_controlThread.start();
executeStartupCommands();
m_controlThread.sendMessage("getsettings");
m_controlThread.sendMessage("[out-network");
//m_controlThread.sendMessage("[out-network-true");
String networkTracePortStr = m_controlThread.getMessage();
int networkTracePort = Integer.parseInt(networkTracePortStr);
if (LOG.isDebugEnabled()) LOG.debug("Received network trace port [" + networkTracePort + "]");
try
{
INetworkOutputConfig config = new INetworkOutputConfig()
{
@Override
public boolean isNetOutputEnabled()
{
return m_settingsData.netOutEnabled;
}
@Override
public boolean isGzipEnabled() {
return m_settingsData.gzipEnabled;
}
};
m_networkTraceThread2 = new NetworkDataReceiverThread2(
m_remoteAddress,
networkTracePort,
config
);
m_networkTraceThread2.start();
setConnectState(ConnectState.CONNECTED);
setConnectionStatusMsg(DefaultFactory.getFactory().getMessages().getConnected());
} catch (IOException ex)
{
m_traceEvents.add(
TraceFactory.createExceptionTraceEvent(
org.headlessintrace.rcp.ClientStrings.TRACE_CREATION_ERROR,
ex,
m_remoteAddress,
networkTracePortStr));
}
} else
{
setConnectState(ConnectState.DISCONNECTED_ERR);
}
} } | public class class_name {
public void setSocket(Socket socket) {
if (socket != null)
{
m_remoteAddress = socket.getInetAddress();
// depends on control dependency: [if], data = [none]
this.port = socket.getPort();
// depends on control dependency: [if], data = [none]
m_controlThread = new DebugControlConnectionThread(socket, this);
// depends on control dependency: [if], data = [(socket]
m_controlThread.start();
// depends on control dependency: [if], data = [none]
executeStartupCommands();
// depends on control dependency: [if], data = [none]
m_controlThread.sendMessage("getsettings");
// depends on control dependency: [if], data = [none]
m_controlThread.sendMessage("[out-network");
// depends on control dependency: [if], data = [none]
//m_controlThread.sendMessage("[out-network-true");
String networkTracePortStr = m_controlThread.getMessage();
int networkTracePort = Integer.parseInt(networkTracePortStr);
if (LOG.isDebugEnabled()) LOG.debug("Received network trace port [" + networkTracePort + "]");
try
{
INetworkOutputConfig config = new INetworkOutputConfig()
{
@Override
public boolean isNetOutputEnabled()
{
return m_settingsData.netOutEnabled;
}
@Override
public boolean isGzipEnabled() {
return m_settingsData.gzipEnabled;
}
};
m_networkTraceThread2 = new NetworkDataReceiverThread2(
m_remoteAddress,
networkTracePort,
config
);
// depends on control dependency: [try], data = [none]
m_networkTraceThread2.start();
// depends on control dependency: [try], data = [none]
setConnectState(ConnectState.CONNECTED);
// depends on control dependency: [try], data = [none]
setConnectionStatusMsg(DefaultFactory.getFactory().getMessages().getConnected());
// depends on control dependency: [try], data = [none]
} catch (IOException ex)
{
m_traceEvents.add(
TraceFactory.createExceptionTraceEvent(
org.headlessintrace.rcp.ClientStrings.TRACE_CREATION_ERROR,
ex,
m_remoteAddress,
networkTracePortStr));
}
// depends on control dependency: [catch], data = [none]
} else
{
setConnectState(ConnectState.DISCONNECTED_ERR);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setDiscreteMinutes(boolean DISCRETE) {
if (null == discreteMinutes) {
_discreteMinutes = DISCRETE;
stopTask(periodicTickTask);
if (isAnimated()) return;
scheduleTickTask();
} else {
discreteMinutes.set(DISCRETE);
}
} } | public class class_name {
public void setDiscreteMinutes(boolean DISCRETE) {
if (null == discreteMinutes) {
_discreteMinutes = DISCRETE; // depends on control dependency: [if], data = [none]
stopTask(periodicTickTask); // depends on control dependency: [if], data = [none]
if (isAnimated()) return;
scheduleTickTask(); // depends on control dependency: [if], data = [none]
} else {
discreteMinutes.set(DISCRETE); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@SuppressWarnings("unchecked")
public V put(final int keyPartA, final int keyPartB, final V value)
{
final long key = compoundKey(keyPartA, keyPartB);
V oldValue = null;
final int mask = values.length - 1;
int index = Hashing.hash(key, mask);
while (null != values[index])
{
if (key == keys[index])
{
oldValue = (V)values[index];
break;
}
index = ++index & mask;
}
if (null == oldValue)
{
++size;
keys[index] = key;
}
values[index] = value;
if (size > resizeThreshold)
{
increaseCapacity();
}
return oldValue;
} } | public class class_name {
@SuppressWarnings("unchecked")
public V put(final int keyPartA, final int keyPartB, final V value)
{
final long key = compoundKey(keyPartA, keyPartB);
V oldValue = null;
final int mask = values.length - 1;
int index = Hashing.hash(key, mask);
while (null != values[index])
{
if (key == keys[index])
{
oldValue = (V)values[index]; // depends on control dependency: [if], data = [none]
break;
}
index = ++index & mask; // depends on control dependency: [while], data = [none]
}
if (null == oldValue)
{
++size; // depends on control dependency: [if], data = [none]
keys[index] = key; // depends on control dependency: [if], data = [none]
}
values[index] = value;
if (size > resizeThreshold)
{
increaseCapacity(); // depends on control dependency: [if], data = [none]
}
return oldValue;
} } |
public class class_name {
public void add(char[] str, int idx) {
SAXRecord rr = records.get(String.valueOf(str));
if (null == rr) {
rr = new SAXRecord(str, idx);
this.records.put(String.valueOf(str), rr);
}
else {
rr.addIndex(idx);
}
this.realTSindex.put(idx, rr);
} } | public class class_name {
public void add(char[] str, int idx) {
SAXRecord rr = records.get(String.valueOf(str));
if (null == rr) {
rr = new SAXRecord(str, idx); // depends on control dependency: [if], data = [none]
this.records.put(String.valueOf(str), rr); // depends on control dependency: [if], data = [rr)]
}
else {
rr.addIndex(idx); // depends on control dependency: [if], data = [none]
}
this.realTSindex.put(idx, rr);
} } |
public class class_name {
public Socket createConnection(InetAddress peer) throws IOException
{
int attempts = 0;
while (true)
{
try
{
Socket socket = OutboundTcpConnectionPool.newSocket(peer);
socket.setSoTimeout(DatabaseDescriptor.getStreamingSocketTimeout());
socket.setKeepAlive(true);
return socket;
}
catch (IOException e)
{
if (++attempts >= MAX_CONNECT_ATTEMPTS)
throw e;
long waitms = DatabaseDescriptor.getRpcTimeout() * (long)Math.pow(2, attempts);
logger.warn("Failed attempt " + attempts + " to connect to " + peer + ". Retrying in " + waitms + " ms. (" + e + ")");
try
{
Thread.sleep(waitms);
}
catch (InterruptedException wtf)
{
throw new IOException("interrupted", wtf);
}
}
}
} } | public class class_name {
public Socket createConnection(InetAddress peer) throws IOException
{
int attempts = 0;
while (true)
{
try
{
Socket socket = OutboundTcpConnectionPool.newSocket(peer);
socket.setSoTimeout(DatabaseDescriptor.getStreamingSocketTimeout()); // depends on control dependency: [try], data = [none]
socket.setKeepAlive(true); // depends on control dependency: [try], data = [none]
return socket; // depends on control dependency: [try], data = [none]
}
catch (IOException e)
{
if (++attempts >= MAX_CONNECT_ATTEMPTS)
throw e;
long waitms = DatabaseDescriptor.getRpcTimeout() * (long)Math.pow(2, attempts);
logger.warn("Failed attempt " + attempts + " to connect to " + peer + ". Retrying in " + waitms + " ms. (" + e + ")");
try
{
Thread.sleep(waitms); // depends on control dependency: [try], data = [none]
}
catch (InterruptedException wtf)
{
throw new IOException("interrupted", wtf);
} // depends on control dependency: [catch], data = [none]
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public ListThreatIntelSetsResult withThreatIntelSetIds(String... threatIntelSetIds) {
if (this.threatIntelSetIds == null) {
setThreatIntelSetIds(new java.util.ArrayList<String>(threatIntelSetIds.length));
}
for (String ele : threatIntelSetIds) {
this.threatIntelSetIds.add(ele);
}
return this;
} } | public class class_name {
public ListThreatIntelSetsResult withThreatIntelSetIds(String... threatIntelSetIds) {
if (this.threatIntelSetIds == null) {
setThreatIntelSetIds(new java.util.ArrayList<String>(threatIntelSetIds.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : threatIntelSetIds) {
this.threatIntelSetIds.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public NioServer init(InetSocketAddress address) {
try {
// 打开服务器套接字通道
this.serverSocketChannel = ServerSocketChannel.open();
// 设置为非阻塞状态
serverSocketChannel.configureBlocking(false);
// 获取通道相关联的套接字
final ServerSocket serverSocket = serverSocketChannel.socket();
// 绑定端口号
serverSocket.bind(address);
// 打开一个选择器
selector = Selector.open();
// 服务器套接字注册到Selector中 并指定Selector监控连接事件
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (IOException e) {
throw new IORuntimeException(e);
}
return this;
} } | public class class_name {
public NioServer init(InetSocketAddress address) {
try {
// 打开服务器套接字通道
this.serverSocketChannel = ServerSocketChannel.open();
// depends on control dependency: [try], data = [none]
// 设置为非阻塞状态
serverSocketChannel.configureBlocking(false);
// depends on control dependency: [try], data = [none]
// 获取通道相关联的套接字
final ServerSocket serverSocket = serverSocketChannel.socket();
// 绑定端口号
serverSocket.bind(address);
// depends on control dependency: [try], data = [none]
// 打开一个选择器
selector = Selector.open();
// depends on control dependency: [try], data = [none]
// 服务器套接字注册到Selector中 并指定Selector监控连接事件
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
// depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new IORuntimeException(e);
}
// depends on control dependency: [catch], data = [none]
return this;
} } |
public class class_name {
static protected HTTPMethod makemethod(HTTPSession.Methods m, HTTPSession session, String url)
throws HTTPException
{
HTTPMethod meth = null;
if(MOCKMETHODCLASS == null) { // do the normal case
meth = new HTTPMethod(m, session, url);
} else {//(MOCKMETHODCLASS != null)
java.lang.Class methodcl = MOCKMETHODCLASS;
Constructor<HTTPMethod> cons = null;
try {
cons = methodcl.getConstructor(HTTPSession.Methods.class, HTTPSession.class, String.class);
} catch (Exception e) {
throw new HTTPException("HTTPFactory: no proper HTTPMethod constructor available", e);
}
try {
meth = cons.newInstance(m, session, url);
} catch (Exception e) {
throw new HTTPException("HTTPFactory: HTTPMethod constructor failed", e);
}
}
return meth;
} } | public class class_name {
static protected HTTPMethod makemethod(HTTPSession.Methods m, HTTPSession session, String url)
throws HTTPException
{
HTTPMethod meth = null;
if(MOCKMETHODCLASS == null) { // do the normal case
meth = new HTTPMethod(m, session, url);
} else {//(MOCKMETHODCLASS != null)
java.lang.Class methodcl = MOCKMETHODCLASS;
Constructor<HTTPMethod> cons = null;
try {
cons = methodcl.getConstructor(HTTPSession.Methods.class, HTTPSession.class, String.class); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new HTTPException("HTTPFactory: no proper HTTPMethod constructor available", e);
} // depends on control dependency: [catch], data = [none]
try {
meth = cons.newInstance(m, session, url); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new HTTPException("HTTPFactory: HTTPMethod constructor failed", e);
} // depends on control dependency: [catch], data = [none]
}
return meth;
} } |
public class class_name {
public void save() throws FileNotFoundException {
PrintStream p = new PrintStream(file);
p.println(COMMENT_PREFIX + "Saved ELKI settings. First line is title, remaining lines are parameters.");
for (Pair<String, ArrayList<String>> settings : store) {
p.println(settings.first);
for (String str : settings.second) {
p.println(str);
}
p.println();
}
p.close();
} } | public class class_name {
public void save() throws FileNotFoundException {
PrintStream p = new PrintStream(file);
p.println(COMMENT_PREFIX + "Saved ELKI settings. First line is title, remaining lines are parameters.");
for (Pair<String, ArrayList<String>> settings : store) {
p.println(settings.first);
for (String str : settings.second) {
p.println(str); // depends on control dependency: [for], data = [str]
}
p.println();
}
p.close();
} } |
public class class_name {
@SuppressWarnings("unchecked")
static <T> Class<T> forClass(final String clsName, final boolean cacheResult) throws IllegalArgumentException {
Class<?> cls = clsNamePool.get(clsName);
if (cls == null) {
cls = BUILT_IN_TYPE.get(clsName);
if (cls == null) {
try {
cls = Class.forName(clsName);
} catch (ClassNotFoundException e) {
String newClassName = clsName;
if (newClassName.indexOf(WD._PERIOD) < 0) {
int index = newClassName.indexOf("[]");
if (((index < 0) && !SYMBOL_OF_PRIMITIVE_ARRAY_CLASS_NAME.containsKey(newClassName))
|| ((index > 0) && !SYMBOL_OF_PRIMITIVE_ARRAY_CLASS_NAME.containsKey(newClassName.substring(0, index)))) {
newClassName = "java.lang." + newClassName;
try {
cls = Class.forName(newClassName);
BUILT_IN_TYPE.put(clsName, cls);
} catch (ClassNotFoundException e1) {
// ignore.
}
}
}
if (cls == null) {
newClassName = clsName;
int index = newClassName.indexOf("[]");
if (index > 0) {
String componentTypeName = newClassName.substring(0, index);
String temp = newClassName.replaceAll("\\[\\]", "");
if (componentTypeName.equals(temp)) {
int dimensions = (newClassName.length() - temp.length()) / 2;
String prefixOfArray = "";
while (dimensions-- > 0) {
prefixOfArray += "[";
}
String symbolOfPrimitiveArraryClassName = SYMBOL_OF_PRIMITIVE_ARRAY_CLASS_NAME.get(componentTypeName);
if (symbolOfPrimitiveArraryClassName != null) {
try {
cls = Class.forName(prefixOfArray + symbolOfPrimitiveArraryClassName);
BUILT_IN_TYPE.put(clsName, cls);
} catch (ClassNotFoundException e2) {
// ignore.
}
} else {
try {
final Type<?> componentType = N.typeOf(componentTypeName);
if (componentType.clazz().equals(Object.class) && !componentType.name().equals(ObjectType.OBJECT)) {
throw new IllegalArgumentException("No Class found by name: " + clsName);
}
cls = Class.forName(prefixOfArray + "L" + componentType.clazz().getCanonicalName() + ";");
} catch (ClassNotFoundException e3) {
// ignore.
}
}
}
}
if (cls == null) {
newClassName = clsName;
int lastIndex = -1;
while ((lastIndex = newClassName.lastIndexOf(WD._PERIOD)) > 0) {
newClassName = newClassName.substring(0, lastIndex) + "$" + newClassName.substring(lastIndex + 1);
try {
cls = Class.forName(newClassName);
break;
} catch (ClassNotFoundException e3) {
// ignore.
}
}
}
}
}
}
if (cls == null) {
throw new IllegalArgumentException("No class found by name: " + clsName);
}
if (cacheResult) {
clsNamePool.put(clsName, cls);
}
}
return (Class<T>) cls;
} } | public class class_name {
@SuppressWarnings("unchecked")
static <T> Class<T> forClass(final String clsName, final boolean cacheResult) throws IllegalArgumentException {
Class<?> cls = clsNamePool.get(clsName);
if (cls == null) {
cls = BUILT_IN_TYPE.get(clsName);
if (cls == null) {
try {
cls = Class.forName(clsName);
} catch (ClassNotFoundException e) {
String newClassName = clsName;
if (newClassName.indexOf(WD._PERIOD) < 0) {
int index = newClassName.indexOf("[]");
if (((index < 0) && !SYMBOL_OF_PRIMITIVE_ARRAY_CLASS_NAME.containsKey(newClassName))
|| ((index > 0) && !SYMBOL_OF_PRIMITIVE_ARRAY_CLASS_NAME.containsKey(newClassName.substring(0, index)))) {
newClassName = "java.lang." + newClassName;
// depends on control dependency: [if], data = [none]
try {
cls = Class.forName(newClassName);
// depends on control dependency: [try], data = [none]
BUILT_IN_TYPE.put(clsName, cls);
// depends on control dependency: [try], data = [none]
} catch (ClassNotFoundException e1) {
// ignore.
}
// depends on control dependency: [catch], data = [none]
}
}
if (cls == null) {
newClassName = clsName;
// depends on control dependency: [if], data = [none]
int index = newClassName.indexOf("[]");
if (index > 0) {
String componentTypeName = newClassName.substring(0, index);
String temp = newClassName.replaceAll("\\[\\]", "");
if (componentTypeName.equals(temp)) {
int dimensions = (newClassName.length() - temp.length()) / 2;
String prefixOfArray = "";
while (dimensions-- > 0) {
prefixOfArray += "[";
// depends on control dependency: [while], data = [none]
}
String symbolOfPrimitiveArraryClassName = SYMBOL_OF_PRIMITIVE_ARRAY_CLASS_NAME.get(componentTypeName);
if (symbolOfPrimitiveArraryClassName != null) {
try {
cls = Class.forName(prefixOfArray + symbolOfPrimitiveArraryClassName);
// depends on control dependency: [try], data = [none]
BUILT_IN_TYPE.put(clsName, cls);
// depends on control dependency: [try], data = [none]
} catch (ClassNotFoundException e2) {
// ignore.
}
// depends on control dependency: [catch], data = [none]
} else {
try {
final Type<?> componentType = N.typeOf(componentTypeName);
if (componentType.clazz().equals(Object.class) && !componentType.name().equals(ObjectType.OBJECT)) {
throw new IllegalArgumentException("No Class found by name: " + clsName);
}
cls = Class.forName(prefixOfArray + "L" + componentType.clazz().getCanonicalName() + ";");
// depends on control dependency: [try], data = [none]
} catch (ClassNotFoundException e3) {
// ignore.
}
// depends on control dependency: [catch], data = [none]
}
}
}
if (cls == null) {
newClassName = clsName;
// depends on control dependency: [if], data = [none]
int lastIndex = -1;
while ((lastIndex = newClassName.lastIndexOf(WD._PERIOD)) > 0) {
newClassName = newClassName.substring(0, lastIndex) + "$" + newClassName.substring(lastIndex + 1);
// depends on control dependency: [while], data = [none]
try {
cls = Class.forName(newClassName);
// depends on control dependency: [try], data = [none]
break;
} catch (ClassNotFoundException e3) {
// ignore.
}
// depends on control dependency: [catch], data = [none]
}
}
}
}
}
if (cls == null) {
throw new IllegalArgumentException("No class found by name: " + clsName);
}
if (cacheResult) {
clsNamePool.put(clsName, cls);
}
}
return (Class<T>) cls;
} } |
public class class_name {
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String PID = null;
String sDefPID = null;
String methodName = null;
String versDateTime = null;
StringBuffer methodParms = new StringBuffer();
response.setContentType(HTML_CONTENT_TYPE);
Hashtable<String,String> h_methodParms = new Hashtable<String,String>();
// Get parameters passed from web form.
@SuppressWarnings("unchecked")
Enumeration<String> parms = request.getParameterNames();
while (parms.hasMoreElements()) {
String name = parms.nextElement();
if (name.equals("PID")) {
PID = request.getParameter(name);
} else if (name.equals("sDefPID")) {
sDefPID = request.getParameter(name);
} else if (name.equals("methodName")) {
methodName = request.getParameter(name);
} else if (name.equals("asOfDateTime")) {
versDateTime = request.getParameter(name).trim();
if (versDateTime.equalsIgnoreCase("null")
|| versDateTime.equalsIgnoreCase("")) {
versDateTime = null;
}
} else if (name.equals("Submit")) {
// Submit parameter is ignored.
} else {
// Any remaining parameters are assumed to be method parameters
// so
// decode and place in hashtable.
h_methodParms.put(name, request.getParameter(name));
}
}
// Check that all required parameters are present.
if (PID == null || PID.equalsIgnoreCase("") || sDefPID == null
|| sDefPID.equalsIgnoreCase("") || methodName == null
|| methodName.equalsIgnoreCase("")) {
String message =
"[MethodParameterResolverServlet] Insufficient "
+ "information to construct dissemination request. Parameters "
+ "received from web form were: PID: " + PID
+ " -- sDefPID: " + sDefPID + " -- methodName: "
+ methodName + " -- methodParms: "
+ methodParms.toString() + "\". ";
logger.error(message);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
message);
} else {
// Translate web form parameters into dissemination request.
StringBuffer redirectURL = new StringBuffer();
redirectURL.append(request.getContextPath() + "/get/" + PID + "/"
+ sDefPID + "/" + methodName);
// Add method parameters.
int i = 0;
for (Enumeration<String> e = h_methodParms.keys(); e.hasMoreElements();) {
String name =
URLEncoder.encode(e.nextElement(), "UTF-8");
String value =
URLEncoder.encode(h_methodParms.get(name),
"UTF-8");
i++;
if (i == h_methodParms.size()) {
methodParms.append(name + "=" + value);
} else {
methodParms.append(name + "=" + value + "&");
}
}
if (h_methodParms.size() > 0) {
if (versDateTime == null || versDateTime.equalsIgnoreCase("")) {
redirectURL.append("?" + methodParms.toString());
} else {
redirectURL.append("/" + versDateTime + "?"
+ methodParms.toString());
}
} else {
if (versDateTime == null || versDateTime.equalsIgnoreCase("")) {
redirectURL.append("/");
} else {
redirectURL.append("/" + versDateTime + "/");
}
}
// Redirect request back to FedoraAccessServlet.
response.sendRedirect(redirectURL.toString());
}
} } | public class class_name {
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String PID = null;
String sDefPID = null;
String methodName = null;
String versDateTime = null;
StringBuffer methodParms = new StringBuffer();
response.setContentType(HTML_CONTENT_TYPE);
Hashtable<String,String> h_methodParms = new Hashtable<String,String>();
// Get parameters passed from web form.
@SuppressWarnings("unchecked")
Enumeration<String> parms = request.getParameterNames();
while (parms.hasMoreElements()) {
String name = parms.nextElement();
if (name.equals("PID")) {
PID = request.getParameter(name);
} else if (name.equals("sDefPID")) {
sDefPID = request.getParameter(name);
} else if (name.equals("methodName")) {
methodName = request.getParameter(name);
} else if (name.equals("asOfDateTime")) {
versDateTime = request.getParameter(name).trim();
if (versDateTime.equalsIgnoreCase("null")
|| versDateTime.equalsIgnoreCase("")) {
versDateTime = null; // depends on control dependency: [if], data = [none]
}
} else if (name.equals("Submit")) {
// Submit parameter is ignored.
} else {
// Any remaining parameters are assumed to be method parameters
// so
// decode and place in hashtable.
h_methodParms.put(name, request.getParameter(name));
}
}
// Check that all required parameters are present.
if (PID == null || PID.equalsIgnoreCase("") || sDefPID == null
|| sDefPID.equalsIgnoreCase("") || methodName == null
|| methodName.equalsIgnoreCase("")) {
String message =
"[MethodParameterResolverServlet] Insufficient "
+ "information to construct dissemination request. Parameters "
+ "received from web form were: PID: " + PID
+ " -- sDefPID: " + sDefPID + " -- methodName: "
+ methodName + " -- methodParms: "
+ methodParms.toString() + "\". ";
logger.error(message);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
message);
} else {
// Translate web form parameters into dissemination request.
StringBuffer redirectURL = new StringBuffer();
redirectURL.append(request.getContextPath() + "/get/" + PID + "/"
+ sDefPID + "/" + methodName);
// Add method parameters.
int i = 0;
for (Enumeration<String> e = h_methodParms.keys(); e.hasMoreElements();) {
String name =
URLEncoder.encode(e.nextElement(), "UTF-8");
String value =
URLEncoder.encode(h_methodParms.get(name),
"UTF-8");
i++;
if (i == h_methodParms.size()) {
methodParms.append(name + "=" + value);
} else {
methodParms.append(name + "=" + value + "&");
}
}
if (h_methodParms.size() > 0) {
if (versDateTime == null || versDateTime.equalsIgnoreCase("")) {
redirectURL.append("?" + methodParms.toString());
} else {
redirectURL.append("/" + versDateTime + "?"
+ methodParms.toString());
}
} else {
if (versDateTime == null || versDateTime.equalsIgnoreCase("")) {
redirectURL.append("/");
} else {
redirectURL.append("/" + versDateTime + "/");
}
}
// Redirect request back to FedoraAccessServlet.
response.sendRedirect(redirectURL.toString());
}
} } |
public class class_name {
public static String buildSummaryDetailsButtons(CmsDialog wp) {
StringBuffer result = new StringBuffer(512);
// create detail view selector
result.append("<table border=\"0\">\n<tr>\n\t<td>");
result.append(wp.key(Messages.GUI_PERMISSION_SELECT_VIEW_0));
result.append("</td>\n");
String selectedView = wp.getSettings().getPermissionDetailView();
result.append("\t<form action=\"").append(wp.getDialogUri()).append(
"\" method=\"post\" name=\"selectshortview\">\n");
result.append("\t<td>\n");
result.append("\t<input type=\"hidden\" name=\"");
result.append(PARAM_VIEW);
result.append("\" value=\"short\">\n");
// set parameters to show correct hidden input fields
wp.setParamAction(null);
result.append(wp.paramsAsHidden());
result.append("\t<input type=\"submit\" class=\"dialogbutton\" value=\"").append(
wp.key(Messages.GUI_LABEL_SUMMARY_0)).append("\"");
if (!"long".equals(selectedView)) {
result.append(" disabled=\"disabled\"");
}
result.append(">\n");
result.append("\t</td>\n");
result.append("\t</form>\n\t<form action=\"").append(wp.getDialogUri()).append(
"\" method=\"post\" name=\"selectlongview\">\n");
result.append("\t<td>\n");
result.append("\t<input type=\"hidden\" name=\"");
result.append(PARAM_VIEW);
result.append("\" value=\"long\">\n");
result.append(wp.paramsAsHidden());
result.append("\t<input type=\"submit\" class=\"dialogbutton\" value=\"").append(
wp.key(Messages.GUI_LABEL_DETAILS_0)).append("\"");
if ("long".equals(selectedView)) {
result.append(" disabled=\"disabled\"");
}
result.append(">\n");
result.append("\t</td>\n\t</form>\n");
result.append("</tr>\n</table>\n");
return result.toString();
} } | public class class_name {
public static String buildSummaryDetailsButtons(CmsDialog wp) {
StringBuffer result = new StringBuffer(512);
// create detail view selector
result.append("<table border=\"0\">\n<tr>\n\t<td>");
result.append(wp.key(Messages.GUI_PERMISSION_SELECT_VIEW_0));
result.append("</td>\n");
String selectedView = wp.getSettings().getPermissionDetailView();
result.append("\t<form action=\"").append(wp.getDialogUri()).append(
"\" method=\"post\" name=\"selectshortview\">\n");
result.append("\t<td>\n");
result.append("\t<input type=\"hidden\" name=\"");
result.append(PARAM_VIEW);
result.append("\" value=\"short\">\n");
// set parameters to show correct hidden input fields
wp.setParamAction(null);
result.append(wp.paramsAsHidden());
result.append("\t<input type=\"submit\" class=\"dialogbutton\" value=\"").append(
wp.key(Messages.GUI_LABEL_SUMMARY_0)).append("\"");
if (!"long".equals(selectedView)) {
result.append(" disabled=\"disabled\""); // depends on control dependency: [if], data = [none]
}
result.append(">\n");
result.append("\t</td>\n");
result.append("\t</form>\n\t<form action=\"").append(wp.getDialogUri()).append(
"\" method=\"post\" name=\"selectlongview\">\n");
result.append("\t<td>\n");
result.append("\t<input type=\"hidden\" name=\"");
result.append(PARAM_VIEW);
result.append("\" value=\"long\">\n");
result.append(wp.paramsAsHidden());
result.append("\t<input type=\"submit\" class=\"dialogbutton\" value=\"").append(
wp.key(Messages.GUI_LABEL_DETAILS_0)).append("\"");
if ("long".equals(selectedView)) {
result.append(" disabled=\"disabled\""); // depends on control dependency: [if], data = [none]
}
result.append(">\n");
result.append("\t</td>\n\t</form>\n");
result.append("</tr>\n</table>\n");
return result.toString();
} } |
public class class_name {
public static void streamPaired(final Readable firstReadable,
final Readable secondReadable,
final PairedEndListener listener) throws IOException {
checkNotNull(firstReadable);
checkNotNull(secondReadable);
checkNotNull(listener);
final ConcurrentMap<String, Fastq> keyedByPrefix = new ConcurrentHashMap<>();
final StreamListener streamListener = new StreamListener() {
@Override
public void fastq(final Fastq fastq) {
String prefix = prefix(fastq);
Fastq other = keyedByPrefix.putIfAbsent(prefix, fastq);
if ((other != null) && !fastq.equals(other)) {
if (isLeft(other) && isRight(fastq)) {
listener.paired(other, fastq);
}
else if (isRight(other) && isLeft(fastq)) {
listener.paired(fastq, other);
}
else {
throw new PairedEndFastqReaderException("fastq " + fastq + " other " + other);
}
keyedByPrefix.remove(prefix);
}
}
};
try {
ExecutorService executor = Executors.newFixedThreadPool(2);
Callable<Void> task1 = new Callable<Void>() {
@Override
public Void call() throws IOException {
new SangerFastqReader().stream(firstReadable, streamListener);
return null;
}
};
Callable<Void> task2 = new Callable<Void>() {
@Override
public Void call() throws IOException {
new SangerFastqReader().stream(secondReadable, streamListener);
return null;
}
};
for (Future<Void> future : executor.invokeAll(ImmutableList.of(task1, task2))) {
future.get();
}
executor.shutdown();
}
catch (ExecutionException e) {
throw new IOException(e.getCause());
}
catch (InterruptedException e) {
// ignore
}
catch (PairedEndFastqReaderException e) {
throw new IOException("could not read paired end FASTQ reads", e);
}
for (Fastq unpaired : keyedByPrefix.values()) {
listener.unpaired(unpaired);
}
} } | public class class_name {
public static void streamPaired(final Readable firstReadable,
final Readable secondReadable,
final PairedEndListener listener) throws IOException {
checkNotNull(firstReadable);
checkNotNull(secondReadable);
checkNotNull(listener);
final ConcurrentMap<String, Fastq> keyedByPrefix = new ConcurrentHashMap<>();
final StreamListener streamListener = new StreamListener() {
@Override
public void fastq(final Fastq fastq) {
String prefix = prefix(fastq);
Fastq other = keyedByPrefix.putIfAbsent(prefix, fastq);
if ((other != null) && !fastq.equals(other)) {
if (isLeft(other) && isRight(fastq)) {
listener.paired(other, fastq); // depends on control dependency: [if], data = [none]
}
else if (isRight(other) && isLeft(fastq)) {
listener.paired(fastq, other); // depends on control dependency: [if], data = [none]
}
else {
throw new PairedEndFastqReaderException("fastq " + fastq + " other " + other);
}
keyedByPrefix.remove(prefix); // depends on control dependency: [if], data = [none]
}
}
};
try {
ExecutorService executor = Executors.newFixedThreadPool(2);
Callable<Void> task1 = new Callable<Void>() {
@Override
public Void call() throws IOException {
new SangerFastqReader().stream(firstReadable, streamListener);
return null;
}
};
Callable<Void> task2 = new Callable<Void>() {
@Override
public Void call() throws IOException {
new SangerFastqReader().stream(secondReadable, streamListener);
return null;
}
};
for (Future<Void> future : executor.invokeAll(ImmutableList.of(task1, task2))) {
future.get(); // depends on control dependency: [for], data = [future]
}
executor.shutdown();
}
catch (ExecutionException e) {
throw new IOException(e.getCause());
}
catch (InterruptedException e) {
// ignore
}
catch (PairedEndFastqReaderException e) {
throw new IOException("could not read paired end FASTQ reads", e);
}
for (Fastq unpaired : keyedByPrefix.values()) {
listener.unpaired(unpaired);
}
} } |
public class class_name {
public InstanceID registerTaskManager(
TaskManagerGateway taskManagerGateway,
TaskManagerLocation taskManagerLocation,
HardwareDescription resources,
int numberOfSlots) {
synchronized (this.lock) {
if (this.isShutdown) {
throw new IllegalStateException("InstanceManager is shut down.");
}
Instance prior = registeredHostsByResource.get(taskManagerLocation.getResourceID());
if (prior != null) {
throw new IllegalStateException("Registration attempt from TaskManager at "
+ taskManagerLocation.addressString() +
". This connection is already registered under ID " + prior.getId());
}
boolean wasDead = this.deadHosts.remove(taskManagerLocation.getResourceID());
if (wasDead) {
LOG.info("Registering TaskManager at " + taskManagerLocation.addressString() +
" which was marked as dead earlier because of a heart-beat timeout.");
}
InstanceID instanceID = new InstanceID();
Instance host = new Instance(
taskManagerGateway,
taskManagerLocation,
instanceID,
resources,
numberOfSlots);
registeredHostsById.put(instanceID, host);
registeredHostsByResource.put(taskManagerLocation.getResourceID(), host);
totalNumberOfAliveTaskSlots += numberOfSlots;
if (LOG.isInfoEnabled()) {
LOG.info(String.format("Registered TaskManager at %s (%s) as %s. " +
"Current number of registered hosts is %d. " +
"Current number of alive task slots is %d.",
taskManagerLocation.getHostname(),
taskManagerGateway.getAddress(),
instanceID,
registeredHostsById.size(),
totalNumberOfAliveTaskSlots));
}
host.reportHeartBeat();
// notify all listeners (for example the scheduler)
notifyNewInstance(host);
return instanceID;
}
} } | public class class_name {
public InstanceID registerTaskManager(
TaskManagerGateway taskManagerGateway,
TaskManagerLocation taskManagerLocation,
HardwareDescription resources,
int numberOfSlots) {
synchronized (this.lock) {
if (this.isShutdown) {
throw new IllegalStateException("InstanceManager is shut down.");
}
Instance prior = registeredHostsByResource.get(taskManagerLocation.getResourceID());
if (prior != null) {
throw new IllegalStateException("Registration attempt from TaskManager at "
+ taskManagerLocation.addressString() +
". This connection is already registered under ID " + prior.getId());
}
boolean wasDead = this.deadHosts.remove(taskManagerLocation.getResourceID());
if (wasDead) {
LOG.info("Registering TaskManager at " + taskManagerLocation.addressString() +
" which was marked as dead earlier because of a heart-beat timeout."); // depends on control dependency: [if], data = [none]
}
InstanceID instanceID = new InstanceID();
Instance host = new Instance(
taskManagerGateway,
taskManagerLocation,
instanceID,
resources,
numberOfSlots);
registeredHostsById.put(instanceID, host);
registeredHostsByResource.put(taskManagerLocation.getResourceID(), host);
totalNumberOfAliveTaskSlots += numberOfSlots;
if (LOG.isInfoEnabled()) {
LOG.info(String.format("Registered TaskManager at %s (%s) as %s. " +
"Current number of registered hosts is %d. " +
"Current number of alive task slots is %d.",
taskManagerLocation.getHostname(),
taskManagerGateway.getAddress(),
instanceID,
registeredHostsById.size(),
totalNumberOfAliveTaskSlots)); // depends on control dependency: [if], data = [none]
}
host.reportHeartBeat();
// notify all listeners (for example the scheduler)
notifyNewInstance(host);
return instanceID;
}
} } |
public class class_name {
public static void addThreshold(String name, String producerName, String statName, String valueName, String intervalName,
ThresholdConditionGuard... guards) {
ThresholdDefinition definition = new ThresholdDefinition();
definition.setName(name);
definition.setProducerName(producerName);
definition.setStatName(statName);
definition.setValueName(valueName);
definition.setIntervalName(intervalName);
Threshold threshold = ThresholdRepository.getInstance().createThreshold(definition);
if (guards != null) {
for (ThresholdConditionGuard g: guards) {
threshold.addGuard(g);
}
}
} } | public class class_name {
public static void addThreshold(String name, String producerName, String statName, String valueName, String intervalName,
ThresholdConditionGuard... guards) {
ThresholdDefinition definition = new ThresholdDefinition();
definition.setName(name);
definition.setProducerName(producerName);
definition.setStatName(statName);
definition.setValueName(valueName);
definition.setIntervalName(intervalName);
Threshold threshold = ThresholdRepository.getInstance().createThreshold(definition);
if (guards != null) {
for (ThresholdConditionGuard g: guards) {
threshold.addGuard(g); // depends on control dependency: [for], data = [g]
}
}
} } |
public class class_name {
@Override
public INDArray createFromNpyPointer(Pointer pointer) {
Pointer dataPointer = nativeOps.dataPointForNumpy(pointer);
int dataBufferElementSize = nativeOps.elementSizeForNpyArray(pointer);
DataBuffer data = null;
Pointer shapeBufferPointer = nativeOps.shapeBufferForNumpy(pointer);
int length = nativeOps.lengthForShapeBufferPointer(shapeBufferPointer);
shapeBufferPointer.capacity(8 * length);
shapeBufferPointer.limit(8 * length);
shapeBufferPointer.position(0);
val intPointer = new LongPointer(shapeBufferPointer);
val newPointer = new LongPointer(length);
val perfD = PerformanceTracker.getInstance().helperStartTransaction();
Pointer.memcpy(newPointer, intPointer, shapeBufferPointer.limit());
PerformanceTracker.getInstance().helperRegisterTransaction(0, perfD, shapeBufferPointer.limit(), MemcpyDirection.HOST_TO_HOST);
DataBuffer shapeBuffer = Nd4j.createBuffer(
newPointer,
DataType.LONG,
length,
LongIndexer.create(newPointer));
dataPointer.position(0);
dataPointer.limit(dataBufferElementSize * Shape.length(shapeBuffer));
dataPointer.capacity(dataBufferElementSize * Shape.length(shapeBuffer));
if(dataBufferElementSize == (Float.SIZE / 8)) {
FloatPointer dPointer = new FloatPointer(dataPointer.limit() / dataBufferElementSize);
val perfX = PerformanceTracker.getInstance().helperStartTransaction();
Pointer.memcpy(dPointer, dataPointer, dataPointer.limit());
PerformanceTracker.getInstance().helperRegisterTransaction(0, perfX, dataPointer.limit(), MemcpyDirection.HOST_TO_HOST);
data = Nd4j.createBuffer(dPointer,
DataType.FLOAT,
Shape.length(shapeBuffer),
FloatIndexer.create(dPointer));
}
else if(dataBufferElementSize == (Double.SIZE / 8)) {
DoublePointer dPointer = new DoublePointer(dataPointer.limit() / dataBufferElementSize);
val perfX = PerformanceTracker.getInstance().helperStartTransaction();
Pointer.memcpy(dPointer, dataPointer, dataPointer.limit());
PerformanceTracker.getInstance().helperRegisterTransaction(0, perfX, dataPointer.limit(), MemcpyDirection.HOST_TO_HOST);
data = Nd4j.createBuffer(dPointer,
DataType.DOUBLE,
Shape.length(shapeBuffer),
DoubleIndexer.create(dPointer));
}
INDArray ret = Nd4j.create(data,
Shape.shape(shapeBuffer),
Shape.strideArr(shapeBuffer),
0,
Shape.order(shapeBuffer));
Nd4j.getAffinityManager().tagLocation(ret, AffinityManager.Location.DEVICE);
return ret;
} } | public class class_name {
@Override
public INDArray createFromNpyPointer(Pointer pointer) {
Pointer dataPointer = nativeOps.dataPointForNumpy(pointer);
int dataBufferElementSize = nativeOps.elementSizeForNpyArray(pointer);
DataBuffer data = null;
Pointer shapeBufferPointer = nativeOps.shapeBufferForNumpy(pointer);
int length = nativeOps.lengthForShapeBufferPointer(shapeBufferPointer);
shapeBufferPointer.capacity(8 * length);
shapeBufferPointer.limit(8 * length);
shapeBufferPointer.position(0);
val intPointer = new LongPointer(shapeBufferPointer);
val newPointer = new LongPointer(length);
val perfD = PerformanceTracker.getInstance().helperStartTransaction();
Pointer.memcpy(newPointer, intPointer, shapeBufferPointer.limit());
PerformanceTracker.getInstance().helperRegisterTransaction(0, perfD, shapeBufferPointer.limit(), MemcpyDirection.HOST_TO_HOST);
DataBuffer shapeBuffer = Nd4j.createBuffer(
newPointer,
DataType.LONG,
length,
LongIndexer.create(newPointer));
dataPointer.position(0);
dataPointer.limit(dataBufferElementSize * Shape.length(shapeBuffer));
dataPointer.capacity(dataBufferElementSize * Shape.length(shapeBuffer));
if(dataBufferElementSize == (Float.SIZE / 8)) {
FloatPointer dPointer = new FloatPointer(dataPointer.limit() / dataBufferElementSize);
val perfX = PerformanceTracker.getInstance().helperStartTransaction();
Pointer.memcpy(dPointer, dataPointer, dataPointer.limit()); // depends on control dependency: [if], data = [none]
PerformanceTracker.getInstance().helperRegisterTransaction(0, perfX, dataPointer.limit(), MemcpyDirection.HOST_TO_HOST); // depends on control dependency: [if], data = [none]
data = Nd4j.createBuffer(dPointer,
DataType.FLOAT,
Shape.length(shapeBuffer),
FloatIndexer.create(dPointer)); // depends on control dependency: [if], data = [none]
}
else if(dataBufferElementSize == (Double.SIZE / 8)) {
DoublePointer dPointer = new DoublePointer(dataPointer.limit() / dataBufferElementSize);
val perfX = PerformanceTracker.getInstance().helperStartTransaction();
Pointer.memcpy(dPointer, dataPointer, dataPointer.limit()); // depends on control dependency: [if], data = [none]
PerformanceTracker.getInstance().helperRegisterTransaction(0, perfX, dataPointer.limit(), MemcpyDirection.HOST_TO_HOST); // depends on control dependency: [if], data = [none]
data = Nd4j.createBuffer(dPointer,
DataType.DOUBLE,
Shape.length(shapeBuffer),
DoubleIndexer.create(dPointer)); // depends on control dependency: [if], data = [none]
}
INDArray ret = Nd4j.create(data,
Shape.shape(shapeBuffer),
Shape.strideArr(shapeBuffer),
0,
Shape.order(shapeBuffer));
Nd4j.getAffinityManager().tagLocation(ret, AffinityManager.Location.DEVICE);
return ret;
} } |
public class class_name {
@Deprecated
public static String encodePath(String path) {
try {
return URIUtil.encodePath(path, "UTF-8");
} catch (URIException ex) {
throw new EsHadoopIllegalArgumentException("Cannot encode path segment [" + path + "]", ex);
}
} } | public class class_name {
@Deprecated
public static String encodePath(String path) {
try {
return URIUtil.encodePath(path, "UTF-8"); // depends on control dependency: [try], data = [none]
} catch (URIException ex) {
throw new EsHadoopIllegalArgumentException("Cannot encode path segment [" + path + "]", ex);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public java.util.List<String> getScheduledInstanceIds() {
if (scheduledInstanceIds == null) {
scheduledInstanceIds = new com.amazonaws.internal.SdkInternalList<String>();
}
return scheduledInstanceIds;
} } | public class class_name {
public java.util.List<String> getScheduledInstanceIds() {
if (scheduledInstanceIds == null) {
scheduledInstanceIds = new com.amazonaws.internal.SdkInternalList<String>(); // depends on control dependency: [if], data = [none]
}
return scheduledInstanceIds;
} } |
public class class_name {
private void load(QueueItem item) throws Exception {
int bulkLoad = store.getBulkLoad();
bulkLoad = Math.min(getItemQueue().size(), bulkLoad);
if (bulkLoad == 1) {
item.setData(store.load(item.getItemId()));
} else if (bulkLoad > 1) {
long maxIdToLoad = -1;
Iterator<QueueItem> iterator = getItemQueue().iterator();
Set<Long> keySet = createHashSet(bulkLoad);
keySet.add(item.getItemId());
while (keySet.size() < bulkLoad && iterator.hasNext()) {
long itemId = iterator.next().getItemId();
if (itemId > lastIdLoaded) {
keySet.add(itemId);
maxIdToLoad = Math.max(itemId, maxIdToLoad);
}
}
Map<Long, Data> values = store.loadAll(keySet);
lastIdLoaded = maxIdToLoad;
dataMap.putAll(values);
item.setData(getDataFromMap(item.getItemId()));
}
} } | public class class_name {
private void load(QueueItem item) throws Exception {
int bulkLoad = store.getBulkLoad();
bulkLoad = Math.min(getItemQueue().size(), bulkLoad);
if (bulkLoad == 1) {
item.setData(store.load(item.getItemId()));
} else if (bulkLoad > 1) {
long maxIdToLoad = -1;
Iterator<QueueItem> iterator = getItemQueue().iterator();
Set<Long> keySet = createHashSet(bulkLoad);
keySet.add(item.getItemId());
while (keySet.size() < bulkLoad && iterator.hasNext()) {
long itemId = iterator.next().getItemId();
if (itemId > lastIdLoaded) {
keySet.add(itemId); // depends on control dependency: [if], data = [(itemId]
maxIdToLoad = Math.max(itemId, maxIdToLoad); // depends on control dependency: [if], data = [(itemId]
}
}
Map<Long, Data> values = store.loadAll(keySet);
lastIdLoaded = maxIdToLoad;
dataMap.putAll(values);
item.setData(getDataFromMap(item.getItemId()));
}
} } |
public class class_name {
private Link recursiveResolveLink(Page redirectPage, Link link) {
// set link reference to content resource of redirect page, keep other parameters
LinkRequest linkRequest = link.getLinkRequest();
LinkRequest redirectLinkRequest = new LinkRequest(
redirectPage.getContentResource(),
null,
linkRequest.getLinkArgs());
// check of maximum recursive calls via threadlocal to avoid endless loops, return invalid link if one is detected
LinkResolveCounter linkResolveCounter = LinkResolveCounter.get();
try {
linkResolveCounter.increaseCount();
if (linkResolveCounter.isMaximumReached()) {
// endless loop detected - set link to invalid link
link.setUrl(null);
return link;
}
// resolve link by recursive call to link handler, track recursion count
return linkHandler.get(redirectLinkRequest).build();
}
finally {
linkResolveCounter.decreaseCount();
}
} } | public class class_name {
private Link recursiveResolveLink(Page redirectPage, Link link) {
// set link reference to content resource of redirect page, keep other parameters
LinkRequest linkRequest = link.getLinkRequest();
LinkRequest redirectLinkRequest = new LinkRequest(
redirectPage.getContentResource(),
null,
linkRequest.getLinkArgs());
// check of maximum recursive calls via threadlocal to avoid endless loops, return invalid link if one is detected
LinkResolveCounter linkResolveCounter = LinkResolveCounter.get();
try {
linkResolveCounter.increaseCount(); // depends on control dependency: [try], data = [none]
if (linkResolveCounter.isMaximumReached()) {
// endless loop detected - set link to invalid link
link.setUrl(null); // depends on control dependency: [if], data = [none]
return link; // depends on control dependency: [if], data = [none]
}
// resolve link by recursive call to link handler, track recursion count
return linkHandler.get(redirectLinkRequest).build(); // depends on control dependency: [try], data = [none]
}
finally {
linkResolveCounter.decreaseCount();
}
} } |
public class class_name {
public static double[][] getImaginary(ComplexNumber[][] cn) {
double[][] n = new double[cn.length][cn[0].length];
for (int i = 0; i < n.length; i++) {
for (int j = 0; j < n[0].length; j++) {
n[i][j] = cn[i][j].imaginary;
}
}
return n;
} } | public class class_name {
public static double[][] getImaginary(ComplexNumber[][] cn) {
double[][] n = new double[cn.length][cn[0].length];
for (int i = 0; i < n.length; i++) {
for (int j = 0; j < n[0].length; j++) {
n[i][j] = cn[i][j].imaginary;
// depends on control dependency: [for], data = [j]
}
}
return n;
} } |
public class class_name {
public PutAction serialize(byte[] keyBytes, FieldMapping fieldMapping,
Object fieldValue) {
Put put = new Put(keyBytes);
PutAction putAction = new PutAction(put);
String fieldName = fieldMapping.getFieldName();
if (fieldMapping.getMappingType() == MappingType.COLUMN
|| fieldMapping.getMappingType() == MappingType.COUNTER) {
serializeColumn(fieldName, fieldMapping.getFamily(),
fieldMapping.getQualifier(), fieldValue, put);
} else if (fieldMapping.getMappingType() == MappingType.KEY_AS_COLUMN) {
serializeKeyAsColumn(fieldName, fieldMapping.getFamily(),
fieldMapping.getPrefix(), fieldValue, put);
} else if (fieldMapping.getMappingType() == MappingType.OCC_VERSION) {
serializeOCCColumn(fieldValue, putAction);
} else {
throw new ValidationException(
"Invalid field mapping for field with name: "
+ fieldMapping.getFieldName());
}
return putAction;
} } | public class class_name {
public PutAction serialize(byte[] keyBytes, FieldMapping fieldMapping,
Object fieldValue) {
Put put = new Put(keyBytes);
PutAction putAction = new PutAction(put);
String fieldName = fieldMapping.getFieldName();
if (fieldMapping.getMappingType() == MappingType.COLUMN
|| fieldMapping.getMappingType() == MappingType.COUNTER) {
serializeColumn(fieldName, fieldMapping.getFamily(),
fieldMapping.getQualifier(), fieldValue, put); // depends on control dependency: [if], data = [none]
} else if (fieldMapping.getMappingType() == MappingType.KEY_AS_COLUMN) {
serializeKeyAsColumn(fieldName, fieldMapping.getFamily(),
fieldMapping.getPrefix(), fieldValue, put); // depends on control dependency: [if], data = [none]
} else if (fieldMapping.getMappingType() == MappingType.OCC_VERSION) {
serializeOCCColumn(fieldValue, putAction); // depends on control dependency: [if], data = [none]
} else {
throw new ValidationException(
"Invalid field mapping for field with name: "
+ fieldMapping.getFieldName());
}
return putAction;
} } |
public class class_name {
public String getKeyByIndex(int index) {
Set<String> keySet = keyIndexs.keySet();
for (String key : keySet) {
int idx = keyIndexs.get(key);
if (index == idx) {
return key;
}
}
return null;
} } | public class class_name {
public String getKeyByIndex(int index) {
Set<String> keySet = keyIndexs.keySet();
for (String key : keySet) {
int idx = keyIndexs.get(key);
if (index == idx) {
return key;
// depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
@SuppressWarnings("nls")
protected JsonObject parseConfig(JdbcOptionsBean config) {
JsonObject jsonConfig = new JsonObject();
nullSafePut(jsonConfig, "provider_class", HikariCPDataSourceProvider.class.getCanonicalName()); // Vert.x thing
nullSafePut(jsonConfig, "jdbcUrl", config.getJdbcUrl());
nullSafePut(jsonConfig, "username", config.getUsername());
nullSafePut(jsonConfig, "password", config.getPassword());
nullSafePut(jsonConfig, "autoCommit", config.isAutoCommit());
nullSafePut(jsonConfig, "connectionTimeout", config.getConnectionTimeout());
nullSafePut(jsonConfig, "idleTimeout", config.getIdleTimeout());
nullSafePut(jsonConfig, "maxLifetime", config.getMaxLifetime());
nullSafePut(jsonConfig, "minimumIdle", config.getMinimumIdle());
nullSafePut(jsonConfig, "maximumPoolSize", config.getMaximumPoolSize());
nullSafePut(jsonConfig, "poolName", config.getPoolName());
JsonObject dsProperties = new JsonObject();
for (Entry<String, Object> entry : config.getDsProperties().entrySet()) {
dsProperties.put(entry.getKey(), entry.getValue());
}
jsonConfig.put("properties", dsProperties);
return jsonConfig;
} } | public class class_name {
@SuppressWarnings("nls")
protected JsonObject parseConfig(JdbcOptionsBean config) {
JsonObject jsonConfig = new JsonObject();
nullSafePut(jsonConfig, "provider_class", HikariCPDataSourceProvider.class.getCanonicalName()); // Vert.x thing
nullSafePut(jsonConfig, "jdbcUrl", config.getJdbcUrl());
nullSafePut(jsonConfig, "username", config.getUsername());
nullSafePut(jsonConfig, "password", config.getPassword());
nullSafePut(jsonConfig, "autoCommit", config.isAutoCommit());
nullSafePut(jsonConfig, "connectionTimeout", config.getConnectionTimeout());
nullSafePut(jsonConfig, "idleTimeout", config.getIdleTimeout());
nullSafePut(jsonConfig, "maxLifetime", config.getMaxLifetime());
nullSafePut(jsonConfig, "minimumIdle", config.getMinimumIdle());
nullSafePut(jsonConfig, "maximumPoolSize", config.getMaximumPoolSize());
nullSafePut(jsonConfig, "poolName", config.getPoolName());
JsonObject dsProperties = new JsonObject();
for (Entry<String, Object> entry : config.getDsProperties().entrySet()) {
dsProperties.put(entry.getKey(), entry.getValue()); // depends on control dependency: [for], data = [entry]
}
jsonConfig.put("properties", dsProperties);
return jsonConfig;
} } |
public class class_name {
public static String join(String[] strings, String delimiter)
{
if (strings == null)
{
return null;
}
if (strings.length == 0)
{
return "";
}
boolean useDelimiter = (delimiter != null && delimiter.length() != 0);
StringBuilder sb = new StringBuilder();
for (String string : strings)
{
sb.append(string);
if (useDelimiter);
{
sb.append(delimiter);
}
}
if (useDelimiter && sb.length() != 0)
{
// Remove the last delimiter.
sb.setLength(sb.length() - delimiter.length());
}
return sb.toString();
} } | public class class_name {
public static String join(String[] strings, String delimiter)
{
if (strings == null)
{
return null;
// depends on control dependency: [if], data = [none]
}
if (strings.length == 0)
{
return "";
// depends on control dependency: [if], data = [none]
}
boolean useDelimiter = (delimiter != null && delimiter.length() != 0);
StringBuilder sb = new StringBuilder();
for (String string : strings)
{
sb.append(string);
// depends on control dependency: [for], data = [string]
if (useDelimiter);
{
sb.append(delimiter);
}
}
if (useDelimiter && sb.length() != 0)
{
// Remove the last delimiter.
sb.setLength(sb.length() - delimiter.length());
// depends on control dependency: [if], data = [none]
}
return sb.toString();
} } |
public class class_name {
public Object store(String correlationId, String key, Object value, long timeout) {
synchronized (_lock) {
// Get the entry
CacheEntry entry = _cache.get(key);
timeout = timeout > 0 ? timeout : _timeout;
// Shortcut to remove entry from the cache
if (value == null) {
if (entry != null) {
_cache.remove(key);
_count--;
}
return null;
}
// Update the entry
if (entry != null) {
entry.setValue(value, timeout);
}
// Or create a new entry
else {
entry = new CacheEntry(key, value, timeout);
_cache.put(key, entry);
_count++;
}
// Clean up the cache
if (_maxSize > 0 && _count > _maxSize)
cleanup();
return value;
}
} } | public class class_name {
public Object store(String correlationId, String key, Object value, long timeout) {
synchronized (_lock) {
// Get the entry
CacheEntry entry = _cache.get(key);
timeout = timeout > 0 ? timeout : _timeout;
// Shortcut to remove entry from the cache
if (value == null) {
if (entry != null) {
_cache.remove(key); // depends on control dependency: [if], data = [none]
_count--; // depends on control dependency: [if], data = [none]
}
return null; // depends on control dependency: [if], data = [none]
}
// Update the entry
if (entry != null) {
entry.setValue(value, timeout); // depends on control dependency: [if], data = [none]
}
// Or create a new entry
else {
entry = new CacheEntry(key, value, timeout); // depends on control dependency: [if], data = [none]
_cache.put(key, entry); // depends on control dependency: [if], data = [none]
_count++; // depends on control dependency: [if], data = [none]
}
// Clean up the cache
if (_maxSize > 0 && _count > _maxSize)
cleanup();
return value;
}
} } |
public class class_name {
public BigRational multiply(BigInteger value) {
if (isZero() || value.signum() == 0) {
return ZERO;
}
if (equals(ONE)) {
return valueOf(value);
}
if (value.equals(BigInteger.ONE)) {
return this;
}
return multiply(new BigDecimal(value));
} } | public class class_name {
public BigRational multiply(BigInteger value) {
if (isZero() || value.signum() == 0) {
return ZERO;
// depends on control dependency: [if], data = [none]
}
if (equals(ONE)) {
return valueOf(value);
// depends on control dependency: [if], data = [none]
}
if (value.equals(BigInteger.ONE)) {
return this;
// depends on control dependency: [if], data = [none]
}
return multiply(new BigDecimal(value));
} } |
public class class_name {
public Node newOptionalParameterFromNode(Node n) {
Node newParam = newParameterFromNode(n);
if (!newParam.isVarArgs() && !newParam.isOptionalArg()) {
newParam.setOptionalArg(true);
}
return newParam;
} } | public class class_name {
public Node newOptionalParameterFromNode(Node n) {
Node newParam = newParameterFromNode(n);
if (!newParam.isVarArgs() && !newParam.isOptionalArg()) {
newParam.setOptionalArg(true); // depends on control dependency: [if], data = [none]
}
return newParam;
} } |
public class class_name {
@Override
public List<TextSpan> getSpans(String type) {
List<TextSpan> spans = new ArrayList<TextSpan>();
Map<Token, TextSpan> tokToSpan = connector.token2ItsTextSpans.get(type);
if (tokToSpan != null) {
spans.addAll(tokToSpan.values());
}
return spans;
} } | public class class_name {
@Override
public List<TextSpan> getSpans(String type) {
List<TextSpan> spans = new ArrayList<TextSpan>();
Map<Token, TextSpan> tokToSpan = connector.token2ItsTextSpans.get(type);
if (tokToSpan != null) {
spans.addAll(tokToSpan.values()); // depends on control dependency: [if], data = [(tokToSpan]
}
return spans;
} } |
public class class_name {
private ServiceReference checkService(ServiceReference serviceReference, String interfaceClassName)
{
if (serviceReference != null)
{
Object service = bundleContext.getService(serviceReference);
if (service != null)
{
try {
if (interfaceClassName != null)
if (!service.getClass().isAssignableFrom(Class.forName(interfaceClassName)))
serviceReference = null;
} catch (ClassNotFoundException e) {
// Ignore this error
}
}
}
return serviceReference;
} } | public class class_name {
private ServiceReference checkService(ServiceReference serviceReference, String interfaceClassName)
{
if (serviceReference != null)
{
Object service = bundleContext.getService(serviceReference);
if (service != null)
{
try {
if (interfaceClassName != null)
if (!service.getClass().isAssignableFrom(Class.forName(interfaceClassName)))
serviceReference = null;
} catch (ClassNotFoundException e) {
// Ignore this error
} // depends on control dependency: [catch], data = [none]
}
}
return serviceReference;
} } |
public class class_name {
private Attributes createAttributes(Map<String, String> parameters)
{
AttributesImpl attributes = new AttributesImpl();
if (parameters != null && !parameters.isEmpty()) {
for (Map.Entry<String, String> entry : parameters.entrySet()) {
String value = entry.getValue();
String key = entry.getKey();
if (key != null && value != null) {
attributes.addAttribute(null, null, key, null, value);
}
}
}
return attributes;
} } | public class class_name {
private Attributes createAttributes(Map<String, String> parameters)
{
AttributesImpl attributes = new AttributesImpl();
if (parameters != null && !parameters.isEmpty()) {
for (Map.Entry<String, String> entry : parameters.entrySet()) {
String value = entry.getValue();
String key = entry.getKey();
if (key != null && value != null) {
attributes.addAttribute(null, null, key, null, value); // depends on control dependency: [if], data = [none]
}
}
}
return attributes;
} } |
public class class_name {
public CoreActivity findActivity(String activityId) {
CoreActivity localActivity = getChildActivity(activityId);
if (localActivity!=null) {
return localActivity;
}
for (CoreActivity activity: getActivities()) {
CoreActivity nestedActivity = activity.findActivity(activityId);
if (nestedActivity!=null) {
return nestedActivity;
}
}
return null;
} } | public class class_name {
public CoreActivity findActivity(String activityId) {
CoreActivity localActivity = getChildActivity(activityId);
if (localActivity!=null) {
return localActivity; // depends on control dependency: [if], data = [none]
}
for (CoreActivity activity: getActivities()) {
CoreActivity nestedActivity = activity.findActivity(activityId);
if (nestedActivity!=null) {
return nestedActivity; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public static ModelNode addCurrentServerGroupsToHostInfoModel(boolean ignoreUnaffectedServerGroups, Resource hostModel, ModelNode model) {
if (!ignoreUnaffectedServerGroups) {
return model;
}
model.get(IGNORE_UNUSED_CONFIG).set(ignoreUnaffectedServerGroups);
addServerGroupsToModel(hostModel, model);
return model;
} } | public class class_name {
public static ModelNode addCurrentServerGroupsToHostInfoModel(boolean ignoreUnaffectedServerGroups, Resource hostModel, ModelNode model) {
if (!ignoreUnaffectedServerGroups) {
return model; // depends on control dependency: [if], data = [none]
}
model.get(IGNORE_UNUSED_CONFIG).set(ignoreUnaffectedServerGroups);
addServerGroupsToModel(hostModel, model);
return model;
} } |
public class class_name {
private static String getResponseMimeType(final HttpResponse httpHeadResponse) {
Header contentTypeHeader = httpHeadResponse.getFirstHeader("Content-Type");
if (contentTypeHeader != null) {
String contentType = contentTypeHeader.getValue();
if (contentType != null) {
try {
return ContentType.parse(contentType).getMimeType();
} catch (ParseException | UnsupportedCharsetException exception) {
return contentType.split(";")[0].trim();
}
}
}
return ContentType.DEFAULT_TEXT.getMimeType();
} } | public class class_name {
private static String getResponseMimeType(final HttpResponse httpHeadResponse) {
Header contentTypeHeader = httpHeadResponse.getFirstHeader("Content-Type");
if (contentTypeHeader != null) {
String contentType = contentTypeHeader.getValue();
if (contentType != null) {
try {
return ContentType.parse(contentType).getMimeType();
// depends on control dependency: [try], data = [none]
} catch (ParseException | UnsupportedCharsetException exception) {
return contentType.split(";")[0].trim();
}
// depends on control dependency: [catch], data = [none]
}
}
return ContentType.DEFAULT_TEXT.getMimeType();
} } |
public class class_name {
public PebbleEngine createPebbleEngine() {
PebbleEngine.Builder builder = new PebbleEngine.Builder();
builder.strictVariables(strictVariables);
if (defaultLocale != null) {
builder.defaultLocale(defaultLocale);
}
if (templateLoaders == null) {
if (templateLoaderPaths != null && templateLoaderPaths.length > 0) {
List<Loader<?>> templateLoaderList = new ArrayList<>();
for (String path : templateLoaderPaths) {
templateLoaderList.add(getTemplateLoaderForPath(path));
}
setTemplateLoader(templateLoaderList);
}
}
Loader<?> templateLoader = getAggregateTemplateLoader(templateLoaders);
builder.loader(templateLoader);
return builder.build();
} } | public class class_name {
public PebbleEngine createPebbleEngine() {
PebbleEngine.Builder builder = new PebbleEngine.Builder();
builder.strictVariables(strictVariables);
if (defaultLocale != null) {
builder.defaultLocale(defaultLocale); // depends on control dependency: [if], data = [(defaultLocale]
}
if (templateLoaders == null) {
if (templateLoaderPaths != null && templateLoaderPaths.length > 0) {
List<Loader<?>> templateLoaderList = new ArrayList<>(); // depends on control dependency: [if], data = [none]
for (String path : templateLoaderPaths) {
templateLoaderList.add(getTemplateLoaderForPath(path)); // depends on control dependency: [for], data = [path]
}
setTemplateLoader(templateLoaderList); // depends on control dependency: [if], data = [none]
}
}
Loader<?> templateLoader = getAggregateTemplateLoader(templateLoaders);
builder.loader(templateLoader);
return builder.build();
} } |
public class class_name {
public boolean execInsert(D6Model[] modelObjects, D6Inex includeExcludeColumnNames, boolean ignoreDuplicate) {
log("#execInsert");
boolean retVal = false;
if (modelObjects == null) {
return retVal;
}
final int numOfModelObjects = modelObjects.length;
if (numOfModelObjects == 0) {
return retVal;
}
final D6Model firstModelObject = modelObjects[0];
final D6CrudInsertHelper d6CrudInsertHelper = new D6CrudInsertHelper(firstModelObject.getClass());
final String insertSQL = d6CrudInsertHelper.createInsertPreparedSQLStatement(includeExcludeColumnNames, ignoreDuplicate);
Connection conn = null;
try {
PreparedStatement preparedStmt = null;
conn = createConnection();
// There is a possibility that the error occurs in one single insert
// statement.
// Therefore, turn the auto commit off.
conn.setAutoCommit(false);
preparedStmt = conn.prepareStatement(insertSQL);
for (int i = 0; i < modelObjects.length; i++) {
D6Model model = modelObjects[i];
d6CrudInsertHelper.map(model, preparedStmt, includeExcludeColumnNames);
// execute SQL
preparedStmt.executeUpdate();
}
// finally commit
conn.commit();
retVal = true;
} catch (SQLException e) {
loge("#execInsert", e);
retVal = false;
} catch (D6Exception e) {
// catch from helper
loge("#execInsert", e);
retVal = false;
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
loge("#execInsert", e);
retVal = false;
}
}
}
return retVal;
} } | public class class_name {
public boolean execInsert(D6Model[] modelObjects, D6Inex includeExcludeColumnNames, boolean ignoreDuplicate) {
log("#execInsert");
boolean retVal = false;
if (modelObjects == null) {
return retVal; // depends on control dependency: [if], data = [none]
}
final int numOfModelObjects = modelObjects.length;
if (numOfModelObjects == 0) {
return retVal; // depends on control dependency: [if], data = [none]
}
final D6Model firstModelObject = modelObjects[0];
final D6CrudInsertHelper d6CrudInsertHelper = new D6CrudInsertHelper(firstModelObject.getClass());
final String insertSQL = d6CrudInsertHelper.createInsertPreparedSQLStatement(includeExcludeColumnNames, ignoreDuplicate);
Connection conn = null;
try {
PreparedStatement preparedStmt = null;
conn = createConnection(); // depends on control dependency: [try], data = [none]
// There is a possibility that the error occurs in one single insert
// statement.
// Therefore, turn the auto commit off.
conn.setAutoCommit(false); // depends on control dependency: [try], data = [none]
preparedStmt = conn.prepareStatement(insertSQL); // depends on control dependency: [try], data = [none]
for (int i = 0; i < modelObjects.length; i++) {
D6Model model = modelObjects[i];
d6CrudInsertHelper.map(model, preparedStmt, includeExcludeColumnNames); // depends on control dependency: [for], data = [none]
// execute SQL
preparedStmt.executeUpdate(); // depends on control dependency: [for], data = [none]
}
// finally commit
conn.commit(); // depends on control dependency: [try], data = [none]
retVal = true; // depends on control dependency: [try], data = [none]
} catch (SQLException e) {
loge("#execInsert", e);
retVal = false;
} catch (D6Exception e) { // depends on control dependency: [catch], data = [none]
// catch from helper
loge("#execInsert", e);
retVal = false;
} finally { // depends on control dependency: [catch], data = [none]
if (conn != null) {
try {
conn.close(); // depends on control dependency: [try], data = [none]
} catch (SQLException e) {
loge("#execInsert", e);
retVal = false;
} // depends on control dependency: [catch], data = [none]
}
}
return retVal;
} } |
public class class_name {
private static String getFullPath(final ContextModel model, final String path) {
String fullPath = path.trim();
if (model.getContextName().length() > 0) {
fullPath = "/" + model.getContextName();
if (!"/".equals(path.trim())) {
if ((!(fullPath.endsWith("/"))) && (!(path.startsWith("/")))) {
fullPath += "/";
}
fullPath = fullPath + path;
}
}
return fullPath;
} } | public class class_name {
private static String getFullPath(final ContextModel model, final String path) {
String fullPath = path.trim();
if (model.getContextName().length() > 0) {
fullPath = "/" + model.getContextName();
// depends on control dependency: [if], data = [none]
if (!"/".equals(path.trim())) {
if ((!(fullPath.endsWith("/"))) && (!(path.startsWith("/")))) {
fullPath += "/";
// depends on control dependency: [if], data = [none]
}
fullPath = fullPath + path;
// depends on control dependency: [if], data = [none]
}
}
return fullPath;
} } |
public class class_name {
public static String getRegion(String id) {
String region = null;
// "Etc/Unknown" is not a system time zone ID,
// but in the zone data.
if (!id.equals(UNKNOWN_ZONE_ID)) {
region = ZoneMeta.getRegion(id);
}
if (region == null) {
// unknown id
throw new IllegalArgumentException("Unknown system zone id: " + id);
}
return region;
} } | public class class_name {
public static String getRegion(String id) {
String region = null;
// "Etc/Unknown" is not a system time zone ID,
// but in the zone data.
if (!id.equals(UNKNOWN_ZONE_ID)) {
region = ZoneMeta.getRegion(id); // depends on control dependency: [if], data = [none]
}
if (region == null) {
// unknown id
throw new IllegalArgumentException("Unknown system zone id: " + id);
}
return region;
} } |
public class class_name {
@Override
public EClass getIfcFlowMovingDevice() {
if (ifcFlowMovingDeviceEClass == null) {
ifcFlowMovingDeviceEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(284);
}
return ifcFlowMovingDeviceEClass;
} } | public class class_name {
@Override
public EClass getIfcFlowMovingDevice() {
if (ifcFlowMovingDeviceEClass == null) {
ifcFlowMovingDeviceEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(284);
// depends on control dependency: [if], data = [none]
}
return ifcFlowMovingDeviceEClass;
} } |
public class class_name {
public static InstanceFields allDeclaredFieldsOf(Object instance) {
List<InstanceField> instanceFields = new ArrayList<InstanceField>();
for (Class<?> clazz = instance.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
instanceFields.addAll(instanceFieldsIn(instance, clazz.getDeclaredFields()));
}
return new InstanceFields(instance, instanceFields);
} } | public class class_name {
public static InstanceFields allDeclaredFieldsOf(Object instance) {
List<InstanceField> instanceFields = new ArrayList<InstanceField>();
for (Class<?> clazz = instance.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
instanceFields.addAll(instanceFieldsIn(instance, clazz.getDeclaredFields())); // depends on control dependency: [for], data = [clazz]
}
return new InstanceFields(instance, instanceFields);
} } |
public class class_name {
public static void traceLeave(Logger log, String method, long traceEnterId, Object... args) {
if (!log.isTraceEnabled()) {
return;
}
if (args.length == 0) {
log.trace("LEAVE {}@{} (elapsed={}us).", method, traceEnterId, ELAPSED_MICRO.apply(traceEnterId));
} else {
log.trace("LEAVE {}@{} {} (elapsed={}us).", method, traceEnterId, args, ELAPSED_MICRO.apply(traceEnterId));
}
} } | public class class_name {
public static void traceLeave(Logger log, String method, long traceEnterId, Object... args) {
if (!log.isTraceEnabled()) {
return; // depends on control dependency: [if], data = [none]
}
if (args.length == 0) {
log.trace("LEAVE {}@{} (elapsed={}us).", method, traceEnterId, ELAPSED_MICRO.apply(traceEnterId)); // depends on control dependency: [if], data = [none]
} else {
log.trace("LEAVE {}@{} {} (elapsed={}us).", method, traceEnterId, args, ELAPSED_MICRO.apply(traceEnterId)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
static double getHipConfidenceUB(final int lgK, final long numCoupons, final double hipEstAccum,
final int kappa) {
if (numCoupons == 0) { return 0.0; }
assert lgK >= 4;
assert (kappa >= 1) && (kappa <= 3);
double x = hipErrorConstant;
if (lgK <= 14) { x = (hipLowSideData[(3 * (lgK - 4)) + (kappa - 1)]) / 10000.0; }
final double rel = x / sqrt(1 << lgK);
final double eps = kappa * rel;
final double est = hipEstAccum;
final double result = est / (1.0 - eps);
return ceil(result); // widening for coverage
} } | public class class_name {
static double getHipConfidenceUB(final int lgK, final long numCoupons, final double hipEstAccum,
final int kappa) {
if (numCoupons == 0) { return 0.0; } // depends on control dependency: [if], data = [none]
assert lgK >= 4;
assert (kappa >= 1) && (kappa <= 3);
double x = hipErrorConstant;
if (lgK <= 14) { x = (hipLowSideData[(3 * (lgK - 4)) + (kappa - 1)]) / 10000.0; } // depends on control dependency: [if], data = [(lgK]
final double rel = x / sqrt(1 << lgK);
final double eps = kappa * rel;
final double est = hipEstAccum;
final double result = est / (1.0 - eps);
return ceil(result); // widening for coverage
} } |
public class class_name {
static byte[] flattenClassName(String className) {
byte[] flattened;
try {
flattened = className.getBytes("UTF8");
}
catch (UnsupportedEncodingException e) {
FFDCFilter.processException(e, "com.ibm.ws.sib.mfp.impl.JsSdoMessageImpl.<clinit>", "50");
flattened = className.getBytes();
}
return flattened;
} } | public class class_name {
static byte[] flattenClassName(String className) {
byte[] flattened;
try {
flattened = className.getBytes("UTF8"); // depends on control dependency: [try], data = [none]
}
catch (UnsupportedEncodingException e) {
FFDCFilter.processException(e, "com.ibm.ws.sib.mfp.impl.JsSdoMessageImpl.<clinit>", "50");
flattened = className.getBytes();
} // depends on control dependency: [catch], data = [none]
return flattened;
} } |
public class class_name {
public ArrayList<String> getFeatures() {
if (isFinalState())
return null;
ArrayList<String> featurelist = new ArrayList<String>();
int rightFocus = leftFocus + 1;
// ISparseVector vec = new HashSparseVector();
//所有的联合feature
featurelist.add(combinedFeature("+0+1", POS, new int[]{0, 1}));
featurelist.add(combinedFeature("-1+0+1", POS, new int[]{-1, 0, 1}));
featurelist.add(combinedFeature("+0+1+2", POS, new int[]{0, 1, 2}));
featurelist.add(combinedFeature("+1+2+3", POS, new int[]{1, 2, 3}));
featurelist.add(combinedFeature("-2+3+4", POS, new int[]{2, 3, 4}));
featurelist.add(combinedFeature("+0+1", LEX, new int[]{0, 1}));
featurelist.add(combinedFeature("-1+0+1", LEX, new int[]{-1, 0, 1}));
featurelist.add(combinedFeature("+0+1+2", LEX, new int[]{0, 1, 2}));
// 设定上下文窗口大小
int l = 2;
int r = 4;
for (int i = 0; i <= l; i++) {
// 特征前缀
String posFeature = "-" + String.valueOf(i) + POS;
String lexFeature = "-" + String.valueOf(i) + LEX;
String lcLexFeature = "-" + String.valueOf(i)
+ CH_L_LEX;
String lcPosFeature = "-" + String.valueOf(i)
+ CH_L_POS;
String rcLexFeature = "-" + String.valueOf(i)
+ CH_R_LEX;
String rcPosFeature = "-" + String.valueOf(i)
+ CH_R_POS;
String lcDepFeature = "-" + String.valueOf(i)
+ CH_L_DEP;
String rcDepFeature = "-" + String.valueOf(i)
+ CH_R_DEP;
if (leftFocus - i < 0) {
featurelist.add(lexFeature + START + String.valueOf(i - leftFocus));
featurelist.add(posFeature + START + String.valueOf(i - leftFocus));
} else {
featurelist.add(lexFeature + sent.words[trees.get(leftFocus - i).id]);
featurelist.add(posFeature + sent.tags[trees.get(leftFocus - i).id]);
if (trees.get(leftFocus - i).leftChilds.size() != 0) {
for (int j = 0; j < trees.get(leftFocus - i).leftChilds
.size(); j++) {
int leftChildIndex = trees.get(leftFocus - i).leftChilds
.get(j).id;
featurelist.add(lcLexFeature
+ sent.words[leftChildIndex]);
featurelist.add(lcPosFeature
+ sent.tags[leftChildIndex]);
featurelist.add(lcDepFeature
+ sent.getDepClass(leftChildIndex));
}
}else{
featurelist.add(lcLexFeature + NULL);
featurelist.add(lcPosFeature + NULL);
}
if (trees.get(leftFocus - i).rightChilds.size() != 0) {
for (int j = 0; j < trees.get(leftFocus - i).rightChilds
.size(); j++) {
int rightChildIndex = trees.get(leftFocus - i).rightChilds
.get(j).id;
featurelist.add(rcLexFeature
+ sent.words[rightChildIndex]);
featurelist.add(rcPosFeature
+ sent.tags[rightChildIndex]);
featurelist.add(rcDepFeature
+ sent.getDepClass(rightChildIndex));
}
}else{
featurelist.add(rcLexFeature + NULL);
featurelist.add(rcPosFeature + NULL);
}
}
}
for (int i = 0; i <= r; i++) {
String posFeature = "+" + String.valueOf(i) + POS;
String lexFeature = "+" + String.valueOf(i) + LEX;
String lcLexFeature = "+" + String.valueOf(i)
+ CH_L_LEX;
String rcLexFeature = "+" + String.valueOf(i)
+ CH_R_LEX;
String lcPosFeature = "+" + String.valueOf(i)
+ CH_L_POS;
String rcPosFeature = "+" + String.valueOf(i)
+ CH_R_POS;
String lcDepFeature = "+" + String.valueOf(i)
+ CH_L_DEP;
String rcDepFeature = "+" + String.valueOf(i)
+ CH_R_DEP;
if (rightFocus + i >= trees.size()) {
featurelist.add(lexFeature+ END+ String.valueOf(rightFocus + i- trees.size() + 3));
featurelist.add(posFeature+ END+ String.valueOf(rightFocus + i- trees.size() + 3));
} else {
featurelist.add(lexFeature+ sent.words[trees.get(rightFocus + i).id]);
featurelist.add(posFeature+ sent.tags[trees.get(rightFocus + i).id]);
if (trees.get(rightFocus + i).leftChilds.size() != 0) {
for (int j = 0; j < trees.get(rightFocus + i).leftChilds
.size(); j++) {
int leftChildIndex = trees.get(rightFocus + i).leftChilds
.get(j).id;
featurelist.add(lcLexFeature+ sent.words[leftChildIndex]);
featurelist.add(lcPosFeature+ sent.tags[leftChildIndex]);
featurelist.add(lcDepFeature+ sent.getDepClass(leftChildIndex));
}
}else{
featurelist.add(lcLexFeature + NULL);
featurelist.add(lcPosFeature + NULL);
}
if (trees.get(rightFocus + i).rightChilds.size() != 0) {
for (int j = 0; j < trees.get(rightFocus + i).rightChilds
.size(); j++) {
int rightChildIndex = trees.get(rightFocus + i).rightChilds
.get(j).id;
featurelist.add(rcLexFeature+ sent.words[rightChildIndex]);
featurelist.add(rcPosFeature+ sent.tags[rightChildIndex]);
featurelist.add(rcDepFeature+ sent.getDepClass(rightChildIndex));
}
}else{
featurelist.add(rcLexFeature + NULL);
featurelist.add(rcPosFeature + NULL);
}
}
}
return featurelist;
} } | public class class_name {
public ArrayList<String> getFeatures() {
if (isFinalState())
return null;
ArrayList<String> featurelist = new ArrayList<String>();
int rightFocus = leftFocus + 1;
// ISparseVector vec = new HashSparseVector();
//所有的联合feature
featurelist.add(combinedFeature("+0+1", POS, new int[]{0, 1}));
featurelist.add(combinedFeature("-1+0+1", POS, new int[]{-1, 0, 1}));
featurelist.add(combinedFeature("+0+1+2", POS, new int[]{0, 1, 2}));
featurelist.add(combinedFeature("+1+2+3", POS, new int[]{1, 2, 3}));
featurelist.add(combinedFeature("-2+3+4", POS, new int[]{2, 3, 4}));
featurelist.add(combinedFeature("+0+1", LEX, new int[]{0, 1}));
featurelist.add(combinedFeature("-1+0+1", LEX, new int[]{-1, 0, 1}));
featurelist.add(combinedFeature("+0+1+2", LEX, new int[]{0, 1, 2}));
// 设定上下文窗口大小
int l = 2;
int r = 4;
for (int i = 0; i <= l; i++) {
// 特征前缀
String posFeature = "-" + String.valueOf(i) + POS;
String lexFeature = "-" + String.valueOf(i) + LEX;
String lcLexFeature = "-" + String.valueOf(i)
+ CH_L_LEX;
String lcPosFeature = "-" + String.valueOf(i)
+ CH_L_POS;
String rcLexFeature = "-" + String.valueOf(i)
+ CH_R_LEX;
String rcPosFeature = "-" + String.valueOf(i)
+ CH_R_POS;
String lcDepFeature = "-" + String.valueOf(i)
+ CH_L_DEP;
String rcDepFeature = "-" + String.valueOf(i)
+ CH_R_DEP;
if (leftFocus - i < 0) {
featurelist.add(lexFeature + START + String.valueOf(i - leftFocus));
// depends on control dependency: [if], data = [none]
featurelist.add(posFeature + START + String.valueOf(i - leftFocus));
// depends on control dependency: [if], data = [none]
} else {
featurelist.add(lexFeature + sent.words[trees.get(leftFocus - i).id]);
// depends on control dependency: [if], data = [(leftFocus - i]
featurelist.add(posFeature + sent.tags[trees.get(leftFocus - i).id]);
// depends on control dependency: [if], data = [(leftFocus - i]
if (trees.get(leftFocus - i).leftChilds.size() != 0) {
for (int j = 0; j < trees.get(leftFocus - i).leftChilds
.size(); j++) {
int leftChildIndex = trees.get(leftFocus - i).leftChilds
.get(j).id;
featurelist.add(lcLexFeature
+ sent.words[leftChildIndex]);
// depends on control dependency: [for], data = [none]
featurelist.add(lcPosFeature
+ sent.tags[leftChildIndex]); // depends on control dependency: [for], data = [none]
featurelist.add(lcDepFeature
+ sent.getDepClass(leftChildIndex));
// depends on control dependency: [for], data = [none]
}
}else{
featurelist.add(lcLexFeature + NULL);
// depends on control dependency: [if], data = [none]
featurelist.add(lcPosFeature + NULL);
// depends on control dependency: [if], data = [none]
}
if (trees.get(leftFocus - i).rightChilds.size() != 0) {
for (int j = 0; j < trees.get(leftFocus - i).rightChilds
.size(); j++) {
int rightChildIndex = trees.get(leftFocus - i).rightChilds
.get(j).id;
featurelist.add(rcLexFeature
+ sent.words[rightChildIndex]);
// depends on control dependency: [for], data = [none]
featurelist.add(rcPosFeature
+ sent.tags[rightChildIndex]); // depends on control dependency: [for], data = [none]
featurelist.add(rcDepFeature
+ sent.getDepClass(rightChildIndex));
// depends on control dependency: [for], data = [none]
}
}else{
featurelist.add(rcLexFeature + NULL);
// depends on control dependency: [if], data = [none]
featurelist.add(rcPosFeature + NULL);
// depends on control dependency: [if], data = [none]
}
}
}
for (int i = 0; i <= r; i++) {
String posFeature = "+" + String.valueOf(i) + POS;
String lexFeature = "+" + String.valueOf(i) + LEX;
String lcLexFeature = "+" + String.valueOf(i)
+ CH_L_LEX;
String rcLexFeature = "+" + String.valueOf(i)
+ CH_R_LEX;
String lcPosFeature = "+" + String.valueOf(i)
+ CH_L_POS;
String rcPosFeature = "+" + String.valueOf(i)
+ CH_R_POS;
String lcDepFeature = "+" + String.valueOf(i)
+ CH_L_DEP;
String rcDepFeature = "+" + String.valueOf(i)
+ CH_R_DEP;
if (rightFocus + i >= trees.size()) {
featurelist.add(lexFeature+ END+ String.valueOf(rightFocus + i- trees.size() + 3));
// depends on control dependency: [if], data = [(rightFocus + i]
featurelist.add(posFeature+ END+ String.valueOf(rightFocus + i- trees.size() + 3));
// depends on control dependency: [if], data = [(rightFocus + i]
} else {
featurelist.add(lexFeature+ sent.words[trees.get(rightFocus + i).id]);
// depends on control dependency: [if], data = [(rightFocus + i]
featurelist.add(posFeature+ sent.tags[trees.get(rightFocus + i).id]);
// depends on control dependency: [if], data = [(rightFocus + i]
if (trees.get(rightFocus + i).leftChilds.size() != 0) {
for (int j = 0; j < trees.get(rightFocus + i).leftChilds
.size(); j++) {
int leftChildIndex = trees.get(rightFocus + i).leftChilds
.get(j).id;
featurelist.add(lcLexFeature+ sent.words[leftChildIndex]);
// depends on control dependency: [for], data = [none]
featurelist.add(lcPosFeature+ sent.tags[leftChildIndex]);
// depends on control dependency: [for], data = [none]
featurelist.add(lcDepFeature+ sent.getDepClass(leftChildIndex));
// depends on control dependency: [for], data = [none]
}
}else{
featurelist.add(lcLexFeature + NULL);
// depends on control dependency: [if], data = [none]
featurelist.add(lcPosFeature + NULL);
// depends on control dependency: [if], data = [none]
}
if (trees.get(rightFocus + i).rightChilds.size() != 0) {
for (int j = 0; j < trees.get(rightFocus + i).rightChilds
.size(); j++) {
int rightChildIndex = trees.get(rightFocus + i).rightChilds
.get(j).id;
featurelist.add(rcLexFeature+ sent.words[rightChildIndex]);
// depends on control dependency: [for], data = [none]
featurelist.add(rcPosFeature+ sent.tags[rightChildIndex]);
// depends on control dependency: [for], data = [none]
featurelist.add(rcDepFeature+ sent.getDepClass(rightChildIndex));
// depends on control dependency: [for], data = [none]
}
}else{
featurelist.add(rcLexFeature + NULL);
// depends on control dependency: [if], data = [none]
featurelist.add(rcPosFeature + NULL);
// depends on control dependency: [if], data = [none]
}
}
}
return featurelist;
} } |
public class class_name {
public void rename(String src, String target) throws RolloverFailure {
if (src.equals(target)) {
addWarn("Source and target files are the same [" + src + "]. Skipping.");
return;
}
File srcFile = new File(src);
if (srcFile.exists()) {
File targetFile = new File(target);
createMissingTargetDirsIfNecessary(targetFile);
addInfo("Renaming file [" + srcFile + "] to [" + targetFile + "]");
boolean result = srcFile.renameTo(targetFile);
if (!result) {
addWarn("Failed to rename file [" + srcFile + "] as [" + targetFile + "].");
Boolean areOnDifferentVolumes = areOnDifferentVolumes(srcFile, targetFile);
if (Boolean.TRUE.equals(areOnDifferentVolumes)) {
addWarn("Detected different file systems for source [" + src + "] and target [" + target + "]. Attempting rename by copying.");
renameByCopying(src, target);
return;
} else {
addWarn("Please consider leaving the [file] option of " + RollingFileAppender.class.getSimpleName() + " empty.");
addWarn("See also " + RENAMING_ERROR_URL);
}
}
} else {
throw new RolloverFailure("File [" + src + "] does not exist.");
}
} } | public class class_name {
public void rename(String src, String target) throws RolloverFailure {
if (src.equals(target)) {
addWarn("Source and target files are the same [" + src + "]. Skipping.");
return;
}
File srcFile = new File(src);
if (srcFile.exists()) {
File targetFile = new File(target);
createMissingTargetDirsIfNecessary(targetFile);
addInfo("Renaming file [" + srcFile + "] to [" + targetFile + "]");
boolean result = srcFile.renameTo(targetFile);
if (!result) {
addWarn("Failed to rename file [" + srcFile + "] as [" + targetFile + "].");
Boolean areOnDifferentVolumes = areOnDifferentVolumes(srcFile, targetFile);
if (Boolean.TRUE.equals(areOnDifferentVolumes)) {
addWarn("Detected different file systems for source [" + src + "] and target [" + target + "]. Attempting rename by copying."); // depends on control dependency: [if], data = [none]
renameByCopying(src, target); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
} else {
addWarn("Please consider leaving the [file] option of " + RollingFileAppender.class.getSimpleName() + " empty."); // depends on control dependency: [if], data = [none]
addWarn("See also " + RENAMING_ERROR_URL); // depends on control dependency: [if], data = [none]
}
}
} else {
throw new RolloverFailure("File [" + src + "] does not exist.");
}
} } |
public class class_name {
private void generatedWithoutSelective(XmlElement xmlElement, IntrospectedTable introspectedTable, boolean hasPrefix) {
if (this.support()) {
List<Element> newEles = new ArrayList<>();
for (Element ele : xmlElement.getElements()) {
// 找到text节点且格式为 set xx = xx 或者 xx = xx
if (ele instanceof TextElement) {
String text = ((TextElement) ele).getContent().trim();
if (text.matches("(^set\\s)?\\S+\\s?=.*")) {
// 清理 set 操作
text = text.replaceFirst("^set\\s", "").trim();
String columnName = text.split("=")[0].trim();
IntrospectedColumn introspectedColumn = IntrospectedTableTools.safeGetColumn(introspectedTable, columnName);
// 查找判断是否需要进行节点替换
List<Element> incrementEles = PluginTools.getHook(IIncrementsPluginHook.class).incrementSetElementGenerated(introspectedColumn, hasPrefix ? "record." : null, text.endsWith(","));
if (!incrementEles.isEmpty()) {
newEles.addAll(incrementEles);
continue;
}
}
}
newEles.add(ele);
}
// 替换节点
xmlElement.getElements().clear();
xmlElement.getElements().addAll(newEles);
}
} } | public class class_name {
private void generatedWithoutSelective(XmlElement xmlElement, IntrospectedTable introspectedTable, boolean hasPrefix) {
if (this.support()) {
List<Element> newEles = new ArrayList<>();
for (Element ele : xmlElement.getElements()) {
// 找到text节点且格式为 set xx = xx 或者 xx = xx
if (ele instanceof TextElement) {
String text = ((TextElement) ele).getContent().trim();
if (text.matches("(^set\\s)?\\S+\\s?=.*")) {
// 清理 set 操作
text = text.replaceFirst("^set\\s", "").trim(); // depends on control dependency: [if], data = [none]
String columnName = text.split("=")[0].trim();
IntrospectedColumn introspectedColumn = IntrospectedTableTools.safeGetColumn(introspectedTable, columnName);
// 查找判断是否需要进行节点替换
List<Element> incrementEles = PluginTools.getHook(IIncrementsPluginHook.class).incrementSetElementGenerated(introspectedColumn, hasPrefix ? "record." : null, text.endsWith(","));
if (!incrementEles.isEmpty()) {
newEles.addAll(incrementEles); // depends on control dependency: [if], data = [none]
continue;
}
}
}
newEles.add(ele); // depends on control dependency: [for], data = [ele]
}
// 替换节点
xmlElement.getElements().clear(); // depends on control dependency: [if], data = [none]
xmlElement.getElements().addAll(newEles); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public String getVfsName(CmsObject cms, String rfsName) {
CmsStaticExportData data = getRfsExportData(cms, rfsName);
if (data != null) {
String result = data.getVfsName();
if ((result != null) && result.startsWith(cms.getRequestContext().getSiteRoot())) {
result = result.substring(cms.getRequestContext().getSiteRoot().length());
}
return result;
}
return null;
} } | public class class_name {
public String getVfsName(CmsObject cms, String rfsName) {
CmsStaticExportData data = getRfsExportData(cms, rfsName);
if (data != null) {
String result = data.getVfsName();
if ((result != null) && result.startsWith(cms.getRequestContext().getSiteRoot())) {
result = result.substring(cms.getRequestContext().getSiteRoot().length()); // depends on control dependency: [if], data = [none]
}
return result; // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public XMLGregorianCalendar buildXMLGregorianCalendarDate(XMLGregorianCalendar cal) {
XMLGregorianCalendar result = null;
if (cal != null) {
result = newXMLGregorianCalendar(cal.getDay(), cal.getMonth(), cal.getYear());
}
return result;
} } | public class class_name {
public XMLGregorianCalendar buildXMLGregorianCalendarDate(XMLGregorianCalendar cal) {
XMLGregorianCalendar result = null;
if (cal != null) {
result = newXMLGregorianCalendar(cal.getDay(), cal.getMonth(), cal.getYear()); // depends on control dependency: [if], data = [(cal]
}
return result;
} } |
public class class_name {
public ListApplicationSnapshotsResult withSnapshotSummaries(SnapshotDetails... snapshotSummaries) {
if (this.snapshotSummaries == null) {
setSnapshotSummaries(new java.util.ArrayList<SnapshotDetails>(snapshotSummaries.length));
}
for (SnapshotDetails ele : snapshotSummaries) {
this.snapshotSummaries.add(ele);
}
return this;
} } | public class class_name {
public ListApplicationSnapshotsResult withSnapshotSummaries(SnapshotDetails... snapshotSummaries) {
if (this.snapshotSummaries == null) {
setSnapshotSummaries(new java.util.ArrayList<SnapshotDetails>(snapshotSummaries.length)); // depends on control dependency: [if], data = [none]
}
for (SnapshotDetails ele : snapshotSummaries) {
this.snapshotSummaries.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
boolean trySetCipherSuite(CipherSuite suite) {
/*
* If we're resuming a session we know we can
* support this key exchange algorithm and in fact
* have already cached the result of it in
* the session state.
*/
if (resumingSession) {
return true;
}
if (suite.isNegotiable() == false) {
return false;
}
// must not negotiate the obsoleted weak cipher suites.
if (protocolVersion.v >= suite.obsoleted) {
return false;
}
// must not negotiate unsupported cipher suites.
if (protocolVersion.v < suite.supported) {
return false;
}
KeyExchange keyExchange = suite.keyExchange;
// null out any existing references
privateKey = null;
certs = null;
dh = null;
tempPrivateKey = null;
tempPublicKey = null;
Collection<SignatureAndHashAlgorithm> supportedSignAlgs = null;
if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
if (peerSupportedSignAlgs != null) {
supportedSignAlgs = peerSupportedSignAlgs;
} else {
SignatureAndHashAlgorithm algorithm = null;
// we may optimize the performance
switch (keyExchange) {
// If the negotiated key exchange algorithm is one of
// (RSA, DHE_RSA, DH_RSA, RSA_PSK, ECDH_RSA, ECDHE_RSA),
// behave as if client had sent the value {sha1,rsa}.
case K_RSA:
case K_DHE_RSA:
case K_DH_RSA:
// case K_RSA_PSK:
case K_ECDH_RSA:
case K_ECDHE_RSA:
algorithm = SignatureAndHashAlgorithm.valueOf(
HashAlgorithm.SHA1.value,
SignatureAlgorithm.RSA.value, 0);
break;
// If the negotiated key exchange algorithm is one of
// (DHE_DSS, DH_DSS), behave as if the client had
// sent the value {sha1,dsa}.
case K_DHE_DSS:
case K_DH_DSS:
algorithm = SignatureAndHashAlgorithm.valueOf(
HashAlgorithm.SHA1.value,
SignatureAlgorithm.DSA.value, 0);
break;
// If the negotiated key exchange algorithm is one of
// (ECDH_ECDSA, ECDHE_ECDSA), behave as if the client
// had sent value {sha1,ecdsa}.
case K_ECDH_ECDSA:
case K_ECDHE_ECDSA:
algorithm = SignatureAndHashAlgorithm.valueOf(
HashAlgorithm.SHA1.value,
SignatureAlgorithm.ECDSA.value, 0);
break;
default:
// no peer supported signature algorithms
}
if (algorithm == null) {
supportedSignAlgs =
Collections.<SignatureAndHashAlgorithm>emptySet();
} else {
supportedSignAlgs =
new ArrayList<SignatureAndHashAlgorithm>(1);
supportedSignAlgs.add(algorithm);
}
// Sets the peer supported signature algorithm to use in KM
// temporarily.
session.setPeerSupportedSignatureAlgorithms(supportedSignAlgs);
}
}
switch (keyExchange) {
case K_RSA:
// need RSA certs for authentication
if (setupPrivateKeyAndChain("RSA") == false) {
return false;
}
break;
case K_RSA_EXPORT:
// need RSA certs for authentication
if (setupPrivateKeyAndChain("RSA") == false) {
return false;
}
try {
if (JsseJce.getRSAKeyLength(certs[0].getPublicKey()) > 512) {
if (!setupEphemeralRSAKeys(suite.exportable)) {
return false;
}
}
} catch (RuntimeException e) {
// could not determine keylength, ignore key
return false;
}
break;
case K_DHE_RSA:
// need RSA certs for authentication
if (setupPrivateKeyAndChain("RSA") == false) {
return false;
}
// get preferable peer signature algorithm for server key exchange
if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
preferableSignatureAlgorithm =
SignatureAndHashAlgorithm.getPreferableAlgorithm(
supportedSignAlgs, "RSA", privateKey);
if (preferableSignatureAlgorithm == null) {
return false;
}
}
setupEphemeralDHKeys(suite.exportable);
break;
case K_ECDHE_RSA:
// need RSA certs for authentication
if (setupPrivateKeyAndChain("RSA") == false) {
return false;
}
// get preferable peer signature algorithm for server key exchange
if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
preferableSignatureAlgorithm =
SignatureAndHashAlgorithm.getPreferableAlgorithm(
supportedSignAlgs, "RSA", privateKey);
if (preferableSignatureAlgorithm == null) {
return false;
}
}
if (setupEphemeralECDHKeys() == false) {
return false;
}
break;
case K_DHE_DSS:
// get preferable peer signature algorithm for server key exchange
if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
preferableSignatureAlgorithm =
SignatureAndHashAlgorithm.getPreferableAlgorithm(
supportedSignAlgs, "DSA");
if (preferableSignatureAlgorithm == null) {
return false;
}
}
// need DSS certs for authentication
if (setupPrivateKeyAndChain("DSA") == false) {
return false;
}
setupEphemeralDHKeys(suite.exportable);
break;
case K_ECDHE_ECDSA:
// get preferable peer signature algorithm for server key exchange
if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
preferableSignatureAlgorithm =
SignatureAndHashAlgorithm.getPreferableAlgorithm(
supportedSignAlgs, "ECDSA");
if (preferableSignatureAlgorithm == null) {
return false;
}
}
// need EC cert signed using EC
if (setupPrivateKeyAndChain("EC_EC") == false) {
return false;
}
if (setupEphemeralECDHKeys() == false) {
return false;
}
break;
case K_ECDH_RSA:
// need EC cert signed using RSA
if (setupPrivateKeyAndChain("EC_RSA") == false) {
return false;
}
setupStaticECDHKeys();
break;
case K_ECDH_ECDSA:
// need EC cert signed using EC
if (setupPrivateKeyAndChain("EC_EC") == false) {
return false;
}
setupStaticECDHKeys();
break;
case K_KRB5:
case K_KRB5_EXPORT:
// need Kerberos Key
if (!setupKerberosKeys()) {
return false;
}
break;
case K_DH_ANON:
// no certs needed for anonymous
setupEphemeralDHKeys(suite.exportable);
break;
case K_ECDH_ANON:
// no certs needed for anonymous
if (setupEphemeralECDHKeys() == false) {
return false;
}
break;
default:
// internal error, unknown key exchange
throw new RuntimeException("Unrecognized cipherSuite: " + suite);
}
setCipherSuite(suite);
// set the peer implicit supported signature algorithms
if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
if (peerSupportedSignAlgs == null) {
setPeerSupportedSignAlgs(supportedSignAlgs);
// we had alreay update the session
}
}
return true;
} } | public class class_name {
boolean trySetCipherSuite(CipherSuite suite) {
/*
* If we're resuming a session we know we can
* support this key exchange algorithm and in fact
* have already cached the result of it in
* the session state.
*/
if (resumingSession) {
return true; // depends on control dependency: [if], data = [none]
}
if (suite.isNegotiable() == false) {
return false; // depends on control dependency: [if], data = [none]
}
// must not negotiate the obsoleted weak cipher suites.
if (protocolVersion.v >= suite.obsoleted) {
return false; // depends on control dependency: [if], data = [none]
}
// must not negotiate unsupported cipher suites.
if (protocolVersion.v < suite.supported) {
return false; // depends on control dependency: [if], data = [none]
}
KeyExchange keyExchange = suite.keyExchange;
// null out any existing references
privateKey = null;
certs = null;
dh = null;
tempPrivateKey = null;
tempPublicKey = null;
Collection<SignatureAndHashAlgorithm> supportedSignAlgs = null;
if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
if (peerSupportedSignAlgs != null) {
supportedSignAlgs = peerSupportedSignAlgs; // depends on control dependency: [if], data = [none]
} else {
SignatureAndHashAlgorithm algorithm = null;
// we may optimize the performance
switch (keyExchange) {
// If the negotiated key exchange algorithm is one of
// (RSA, DHE_RSA, DH_RSA, RSA_PSK, ECDH_RSA, ECDHE_RSA),
// behave as if client had sent the value {sha1,rsa}.
case K_RSA:
case K_DHE_RSA:
case K_DH_RSA:
// case K_RSA_PSK:
case K_ECDH_RSA:
case K_ECDHE_RSA:
algorithm = SignatureAndHashAlgorithm.valueOf(
HashAlgorithm.SHA1.value,
SignatureAlgorithm.RSA.value, 0);
break;
// If the negotiated key exchange algorithm is one of
// (DHE_DSS, DH_DSS), behave as if the client had
// sent the value {sha1,dsa}.
case K_DHE_DSS:
case K_DH_DSS:
algorithm = SignatureAndHashAlgorithm.valueOf(
HashAlgorithm.SHA1.value,
SignatureAlgorithm.DSA.value, 0);
break;
// If the negotiated key exchange algorithm is one of
// (ECDH_ECDSA, ECDHE_ECDSA), behave as if the client
// had sent value {sha1,ecdsa}.
case K_ECDH_ECDSA:
case K_ECDHE_ECDSA:
algorithm = SignatureAndHashAlgorithm.valueOf(
HashAlgorithm.SHA1.value,
SignatureAlgorithm.ECDSA.value, 0);
break;
default:
// no peer supported signature algorithms
}
if (algorithm == null) {
supportedSignAlgs =
Collections.<SignatureAndHashAlgorithm>emptySet(); // depends on control dependency: [if], data = [none]
} else {
supportedSignAlgs =
new ArrayList<SignatureAndHashAlgorithm>(1); // depends on control dependency: [if], data = [none]
supportedSignAlgs.add(algorithm); // depends on control dependency: [if], data = [(algorithm]
}
// Sets the peer supported signature algorithm to use in KM
// temporarily.
session.setPeerSupportedSignatureAlgorithms(supportedSignAlgs);
}
}
switch (keyExchange) {
case K_RSA:
// need RSA certs for authentication
if (setupPrivateKeyAndChain("RSA") == false) {
return false; // depends on control dependency: [if], data = [none]
}
break;
case K_RSA_EXPORT:
// need RSA certs for authentication
if (setupPrivateKeyAndChain("RSA") == false) {
return false; // depends on control dependency: [if], data = [none]
}
try {
if (JsseJce.getRSAKeyLength(certs[0].getPublicKey()) > 512) {
if (!setupEphemeralRSAKeys(suite.exportable)) {
return false; // depends on control dependency: [if], data = [none]
}
}
} catch (RuntimeException e) {
// could not determine keylength, ignore key
return false;
} // depends on control dependency: [catch], data = [none]
break;
case K_DHE_RSA:
// need RSA certs for authentication
if (setupPrivateKeyAndChain("RSA") == false) {
return false; // depends on control dependency: [if], data = [none]
}
// get preferable peer signature algorithm for server key exchange
if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
preferableSignatureAlgorithm =
SignatureAndHashAlgorithm.getPreferableAlgorithm(
supportedSignAlgs, "RSA", privateKey); // depends on control dependency: [if], data = [none]
if (preferableSignatureAlgorithm == null) {
return false; // depends on control dependency: [if], data = [none]
}
}
setupEphemeralDHKeys(suite.exportable);
break;
case K_ECDHE_RSA:
// need RSA certs for authentication
if (setupPrivateKeyAndChain("RSA") == false) {
return false; // depends on control dependency: [if], data = [none]
}
// get preferable peer signature algorithm for server key exchange
if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
preferableSignatureAlgorithm =
SignatureAndHashAlgorithm.getPreferableAlgorithm(
supportedSignAlgs, "RSA", privateKey); // depends on control dependency: [if], data = [none]
if (preferableSignatureAlgorithm == null) {
return false; // depends on control dependency: [if], data = [none]
}
}
if (setupEphemeralECDHKeys() == false) {
return false; // depends on control dependency: [if], data = [none]
}
break;
case K_DHE_DSS:
// get preferable peer signature algorithm for server key exchange
if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
preferableSignatureAlgorithm =
SignatureAndHashAlgorithm.getPreferableAlgorithm(
supportedSignAlgs, "DSA"); // depends on control dependency: [if], data = [none]
if (preferableSignatureAlgorithm == null) {
return false; // depends on control dependency: [if], data = [none]
}
}
// need DSS certs for authentication
if (setupPrivateKeyAndChain("DSA") == false) {
return false; // depends on control dependency: [if], data = [none]
}
setupEphemeralDHKeys(suite.exportable);
break;
case K_ECDHE_ECDSA:
// get preferable peer signature algorithm for server key exchange
if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
preferableSignatureAlgorithm =
SignatureAndHashAlgorithm.getPreferableAlgorithm(
supportedSignAlgs, "ECDSA"); // depends on control dependency: [if], data = [none]
if (preferableSignatureAlgorithm == null) {
return false; // depends on control dependency: [if], data = [none]
}
}
// need EC cert signed using EC
if (setupPrivateKeyAndChain("EC_EC") == false) {
return false; // depends on control dependency: [if], data = [none]
}
if (setupEphemeralECDHKeys() == false) {
return false; // depends on control dependency: [if], data = [none]
}
break;
case K_ECDH_RSA:
// need EC cert signed using RSA
if (setupPrivateKeyAndChain("EC_RSA") == false) {
return false; // depends on control dependency: [if], data = [none]
}
setupStaticECDHKeys();
break;
case K_ECDH_ECDSA:
// need EC cert signed using EC
if (setupPrivateKeyAndChain("EC_EC") == false) {
return false; // depends on control dependency: [if], data = [none]
}
setupStaticECDHKeys();
break;
case K_KRB5:
case K_KRB5_EXPORT:
// need Kerberos Key
if (!setupKerberosKeys()) {
return false; // depends on control dependency: [if], data = [none]
}
break;
case K_DH_ANON:
// no certs needed for anonymous
setupEphemeralDHKeys(suite.exportable);
break;
case K_ECDH_ANON:
// no certs needed for anonymous
if (setupEphemeralECDHKeys() == false) {
return false; // depends on control dependency: [if], data = [none]
}
break;
default:
// internal error, unknown key exchange
throw new RuntimeException("Unrecognized cipherSuite: " + suite);
}
setCipherSuite(suite); // depends on control dependency: [if], data = [none]
// set the peer implicit supported signature algorithms
if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
if (peerSupportedSignAlgs == null) {
setPeerSupportedSignAlgs(supportedSignAlgs); // depends on control dependency: [if], data = [none]
// we had alreay update the session
}
}
return true; // depends on control dependency: [if], data = [none]
} } |
public class class_name {
@Override
public <T> T asObject(String string, Class<T> valueType) throws BugError {
if ("null".equals(string)) {
return null;
}
Number number = string.isEmpty() ? 0 : parseNumber(string);
// hopefully int and double are most used numeric types and test them first
if (Types.equalsAny(valueType, int.class, Integer.class)) {
return (T) (Integer) number.intValue();
}
if (Types.equalsAny(valueType, double.class, Double.class)) {
return (T) (Double) number.doubleValue();
}
if (Types.equalsAny(valueType, byte.class, Byte.class)) {
return (T) (Byte) number.byteValue();
}
if (Types.equalsAny(valueType, short.class, Short.class)) {
return (T) (Short) number.shortValue();
}
if (Types.equalsAny(valueType, long.class, Long.class)) {
// because converting between doubles and longs may result in loss of precision we need
// special treatment for longs. @see ConverterUnitTest.testConversionPrecision
if (string.length() > 0 && string.indexOf('.') == -1) {
// handle hexadecimal notation
if (string.length() > 1 && string.charAt(0) == '0' && string.charAt(1) == 'x') {
return (T) (Long) Long.parseLong(string.substring(2), 16);
}
return (T) (Long) Long.parseLong(string);
}
return (T) (Long) number.longValue();
}
if (Types.equalsAny(valueType, float.class, Float.class)) {
return (T) (Float) number.floatValue();
}
// if(Classes.equalsAny(t,BigInteger.class) {
// return (T)new BigInteger(number.doubleValue());
// }
if (Types.equalsAny(valueType, BigDecimal.class)) {
return (T) new BigDecimal(number.doubleValue());
}
throw new BugError("Unsupported numeric value |%s|.", valueType);
} } | public class class_name {
@Override
public <T> T asObject(String string, Class<T> valueType) throws BugError {
if ("null".equals(string)) {
return null;
}
Number number = string.isEmpty() ? 0 : parseNumber(string);
// hopefully int and double are most used numeric types and test them first
if (Types.equalsAny(valueType, int.class, Integer.class)) {
return (T) (Integer) number.intValue();
}
if (Types.equalsAny(valueType, double.class, Double.class)) {
return (T) (Double) number.doubleValue();
}
if (Types.equalsAny(valueType, byte.class, Byte.class)) {
return (T) (Byte) number.byteValue();
}
if (Types.equalsAny(valueType, short.class, Short.class)) {
return (T) (Short) number.shortValue();
}
if (Types.equalsAny(valueType, long.class, Long.class)) {
// because converting between doubles and longs may result in loss of precision we need
// special treatment for longs. @see ConverterUnitTest.testConversionPrecision
if (string.length() > 0 && string.indexOf('.') == -1) {
// handle hexadecimal notation
if (string.length() > 1 && string.charAt(0) == '0' && string.charAt(1) == 'x') {
return (T) (Long) Long.parseLong(string.substring(2), 16);
// depends on control dependency: [if], data = [none]
}
return (T) (Long) Long.parseLong(string);
// depends on control dependency: [if], data = [none]
}
return (T) (Long) number.longValue();
}
if (Types.equalsAny(valueType, float.class, Float.class)) {
return (T) (Float) number.floatValue();
}
// if(Classes.equalsAny(t,BigInteger.class) {
// return (T)new BigInteger(number.doubleValue());
// }
if (Types.equalsAny(valueType, BigDecimal.class)) {
return (T) new BigDecimal(number.doubleValue());
}
throw new BugError("Unsupported numeric value |%s|.", valueType);
} } |
public class class_name {
public void addMasterListeners()
{
super.addMasterListeners();
this.addListener(new SetUserIDHandler(ProjectTask.ENTERED_BY_USER_ID, true));
this.addListener(new SetUserIDHandler(ProjectTask.CHANGED_BY_USER_ID, true));
this.addListener(new DateChangedHandler(ProjectTask.CHANGED_DATE));
FieldListener listener = null;
this.getField(ProjectTask.END_DATE_TIME).addListener(listener = new InitDateOffsetHandler(this.getField(ProjectTask.DURATION), (DateTimeField)this.getField(ProjectTask.START_DATE_TIME)));
listener.setRespondsToMode(DBConstants.READ_MOVE, true);
this.getField(ProjectTask.END_DATE_TIME).addListener(listener = new ReComputeTimeOffsetHandler(ProjectTask.DURATION, (DateTimeField)this.getField(ProjectTask.START_DATE_TIME)));
this.getField(ProjectTask.START_DATE_TIME).addListener(listener = new ReComputeEndDateHandler(ProjectTask.END_DATE_TIME, (NumberField)this.getField(ProjectTask.DURATION)));
this.getField(ProjectTask.DURATION).addListener(listener = new ChangeOnChangeHandler(this.getField(ProjectTask.START_DATE_TIME)));
listener.setRespondsToMode(DBConstants.INIT_MOVE, false);
this.getField(ProjectTask.START_DATE_TIME).addListener(new InitFieldHandler((BaseField)null)
{
public int fieldChanged(boolean bDisplayOption, int iMoveMode)
{
if (!getField(ProjectTask.PARENT_PROJECT_TASK_ID).isNull())
{
Record recParent = ((ReferenceField)getField(ProjectTask.PARENT_PROJECT_TASK_ID)).getReference();
if (recParent != null)
if ((recParent.getEditMode() == DBConstants.EDIT_IN_PROGRESS) || (recParent.getEditMode() == DBConstants.EDIT_CURRENT))
{
if (recParent.getField(ProjectTask.HAS_CHILDREN).getState() == true)
return this.getOwner().moveFieldToThis(recParent.getField(ProjectTask.END_DATE_TIME), bDisplayOption, iMoveMode);
else
return this.getOwner().moveFieldToThis(recParent.getField(ProjectTask.START_DATE_TIME), bDisplayOption, iMoveMode);
}
}
return super.fieldChanged(bDisplayOption, iMoveMode);
}
});
this.addListener(new UpdateChildrenHandler(null));
this.addListener(new UpdateDependenciesHandler(null));
this.addListener(new SurveyDatesHandler(null));
// todo (don) Move these to the server environment
this.addListener(new SubFileIntegrityHandler(ProjectTask.class.getName(), true));
this.addListener(new SubFileIntegrityHandler(ProjectTaskPredecessor.class.getName(), true));
this.addListener(new SubFileIntegrityHandler(ProjectTaskPredecessor.class.getName(), true)
{
public Record getSubRecord()
{
if (m_recDependent == null)
m_recDependent = this.createSubRecord();
if (m_recDependent != null)
{
if (m_recDependent.getListener(SubFileFilter.class.getName()) == null)
{
m_recDependent.addListener(new SubFileFilter(getField(ProjectTask.ID), ProjectTaskPredecessor.PROJECT_TASK_ID, null, null, null, null));
m_recDependent.setKeyArea(ProjectTaskPredecessor.PROJECT_TASK_ID_KEY);
}
}
return m_recDependent;
}
});
} } | public class class_name {
public void addMasterListeners()
{
super.addMasterListeners();
this.addListener(new SetUserIDHandler(ProjectTask.ENTERED_BY_USER_ID, true));
this.addListener(new SetUserIDHandler(ProjectTask.CHANGED_BY_USER_ID, true));
this.addListener(new DateChangedHandler(ProjectTask.CHANGED_DATE));
FieldListener listener = null;
this.getField(ProjectTask.END_DATE_TIME).addListener(listener = new InitDateOffsetHandler(this.getField(ProjectTask.DURATION), (DateTimeField)this.getField(ProjectTask.START_DATE_TIME)));
listener.setRespondsToMode(DBConstants.READ_MOVE, true);
this.getField(ProjectTask.END_DATE_TIME).addListener(listener = new ReComputeTimeOffsetHandler(ProjectTask.DURATION, (DateTimeField)this.getField(ProjectTask.START_DATE_TIME)));
this.getField(ProjectTask.START_DATE_TIME).addListener(listener = new ReComputeEndDateHandler(ProjectTask.END_DATE_TIME, (NumberField)this.getField(ProjectTask.DURATION)));
this.getField(ProjectTask.DURATION).addListener(listener = new ChangeOnChangeHandler(this.getField(ProjectTask.START_DATE_TIME)));
listener.setRespondsToMode(DBConstants.INIT_MOVE, false);
this.getField(ProjectTask.START_DATE_TIME).addListener(new InitFieldHandler((BaseField)null)
{
public int fieldChanged(boolean bDisplayOption, int iMoveMode)
{
if (!getField(ProjectTask.PARENT_PROJECT_TASK_ID).isNull())
{
Record recParent = ((ReferenceField)getField(ProjectTask.PARENT_PROJECT_TASK_ID)).getReference();
if (recParent != null)
if ((recParent.getEditMode() == DBConstants.EDIT_IN_PROGRESS) || (recParent.getEditMode() == DBConstants.EDIT_CURRENT))
{
if (recParent.getField(ProjectTask.HAS_CHILDREN).getState() == true)
return this.getOwner().moveFieldToThis(recParent.getField(ProjectTask.END_DATE_TIME), bDisplayOption, iMoveMode);
else
return this.getOwner().moveFieldToThis(recParent.getField(ProjectTask.START_DATE_TIME), bDisplayOption, iMoveMode);
}
}
return super.fieldChanged(bDisplayOption, iMoveMode);
}
});
this.addListener(new UpdateChildrenHandler(null));
this.addListener(new UpdateDependenciesHandler(null));
this.addListener(new SurveyDatesHandler(null));
// todo (don) Move these to the server environment
this.addListener(new SubFileIntegrityHandler(ProjectTask.class.getName(), true));
this.addListener(new SubFileIntegrityHandler(ProjectTaskPredecessor.class.getName(), true));
this.addListener(new SubFileIntegrityHandler(ProjectTaskPredecessor.class.getName(), true)
{
public Record getSubRecord()
{
if (m_recDependent == null)
m_recDependent = this.createSubRecord();
if (m_recDependent != null)
{
if (m_recDependent.getListener(SubFileFilter.class.getName()) == null)
{
m_recDependent.addListener(new SubFileFilter(getField(ProjectTask.ID), ProjectTaskPredecessor.PROJECT_TASK_ID, null, null, null, null)); // depends on control dependency: [if], data = [null)]
m_recDependent.setKeyArea(ProjectTaskPredecessor.PROJECT_TASK_ID_KEY); // depends on control dependency: [if], data = [none]
}
}
return m_recDependent;
}
});
} } |
public class class_name {
@Override
public void tick(long now) {
if (now - this.initiatedTime >= STOP_TIMER_TIMEOUT) {
if (this.aspFactoryImpl.association.isConnected()) {
logger.warn(String
.format("Asp=%s was stopped but underlying Association=%s was not stopped after TIMEOUT=%d ms. Forcing stop now",
this.aspFactoryImpl.getName(), this.aspFactoryImpl.association.getName(), STOP_TIMER_TIMEOUT));
try {
this.aspFactoryImpl.transportManagement.stopAssociation(this.aspFactoryImpl.association.getName());
} catch (Exception e) {
logger.error(String.format("Exception while trying to stop Association=%s",
this.aspFactoryImpl.association.getName()));
}
}
// Finally cancel
this.cancel();
}// if(now-this.initiatedTime >= STOP_TIMER_TIMEOUT)
} } | public class class_name {
@Override
public void tick(long now) {
if (now - this.initiatedTime >= STOP_TIMER_TIMEOUT) {
if (this.aspFactoryImpl.association.isConnected()) {
logger.warn(String
.format("Asp=%s was stopped but underlying Association=%s was not stopped after TIMEOUT=%d ms. Forcing stop now",
this.aspFactoryImpl.getName(), this.aspFactoryImpl.association.getName(), STOP_TIMER_TIMEOUT)); // depends on control dependency: [if], data = [none]
try {
this.aspFactoryImpl.transportManagement.stopAssociation(this.aspFactoryImpl.association.getName()); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
logger.error(String.format("Exception while trying to stop Association=%s",
this.aspFactoryImpl.association.getName()));
} // depends on control dependency: [catch], data = [none]
}
// Finally cancel
this.cancel(); // depends on control dependency: [if], data = [none]
}// if(now-this.initiatedTime >= STOP_TIMER_TIMEOUT)
} } |
public class class_name {
protected ReadOnlyListWrapper<Point2ifx> innerPointsProperty() {
if (this.coords == null) {
this.coords = new ReadOnlyListWrapper<>(this, MathFXAttributeNames.COORDINATES,
FXCollections.observableList(new ArrayList<>()));
}
return this.coords;
} } | public class class_name {
protected ReadOnlyListWrapper<Point2ifx> innerPointsProperty() {
if (this.coords == null) {
this.coords = new ReadOnlyListWrapper<>(this, MathFXAttributeNames.COORDINATES,
FXCollections.observableList(new ArrayList<>())); // depends on control dependency: [if], data = [none]
}
return this.coords;
} } |
public class class_name {
public LinkChangeListener getLinkChangeListener() {
if (TraceComponent.isAnyTracingEnabled()
&& tc.isEntryEnabled()) {
SibTr.entry(tc, "getLinkChangeListener");
SibTr.exit(tc, "getLinkChangeListener", _linkChangeListener);
}
return _linkChangeListener;
} } | public class class_name {
public LinkChangeListener getLinkChangeListener() {
if (TraceComponent.isAnyTracingEnabled()
&& tc.isEntryEnabled()) {
SibTr.entry(tc, "getLinkChangeListener"); // depends on control dependency: [if], data = [none]
SibTr.exit(tc, "getLinkChangeListener", _linkChangeListener); // depends on control dependency: [if], data = [none]
}
return _linkChangeListener;
} } |
public class class_name {
public UNode toDoc() {
// The root node is always a MAP whose name is the application's name. In case it
// is serialized to XML, we set this node's tag name to "application".
UNode appNode = UNode.createMapNode(m_appName, "application");
// Add the application's key.
if (!Utils.isEmpty(m_key)) {
appNode.addValueNode("key", m_key);
}
// Add options, if any, in a MAP node.
if (m_optionMap.size() > 0) {
UNode optsNode = appNode.addMapNode("options");
for (String optName : m_optionMap.keySet()) {
// Set each option's tag name to "option" for XML's sake.
optsNode.addValueNode(optName, m_optionMap.get(optName), "option");
}
}
// Add tables, if any, in a MAP node.
if (m_tableMap.size() > 0) {
UNode tablesNode = appNode.addMapNode("tables");
for (TableDefinition tableDef : m_tableMap.values()) {
tablesNode.addChildNode(tableDef.toDoc());
}
}
return appNode;
} } | public class class_name {
public UNode toDoc() {
// The root node is always a MAP whose name is the application's name. In case it
// is serialized to XML, we set this node's tag name to "application".
UNode appNode = UNode.createMapNode(m_appName, "application");
// Add the application's key.
if (!Utils.isEmpty(m_key)) {
appNode.addValueNode("key", m_key);
// depends on control dependency: [if], data = [none]
}
// Add options, if any, in a MAP node.
if (m_optionMap.size() > 0) {
UNode optsNode = appNode.addMapNode("options");
for (String optName : m_optionMap.keySet()) {
// Set each option's tag name to "option" for XML's sake.
optsNode.addValueNode(optName, m_optionMap.get(optName), "option");
// depends on control dependency: [for], data = [optName]
}
}
// Add tables, if any, in a MAP node.
if (m_tableMap.size() > 0) {
UNode tablesNode = appNode.addMapNode("tables");
for (TableDefinition tableDef : m_tableMap.values()) {
tablesNode.addChildNode(tableDef.toDoc());
// depends on control dependency: [for], data = [tableDef]
}
}
return appNode;
} } |
public class class_name {
public static Set<MediaType> set(MediaType... types) {
Set<MediaType> set = new HashSet<MediaType>();
for (MediaType type : types) {
if (type != null) {
set.add(type);
}
}
return Collections.unmodifiableSet(set);
} } | public class class_name {
public static Set<MediaType> set(MediaType... types) {
Set<MediaType> set = new HashSet<MediaType>();
for (MediaType type : types) {
if (type != null) {
set.add(type); // depends on control dependency: [if], data = [(type]
}
}
return Collections.unmodifiableSet(set);
} } |
public class class_name {
public int getMaxFieldLenth()
{
//get max field name
int maxLen = 0;
for ( String s : keys )
{
maxLen = s.length() > maxLen ? s.length() : maxLen;
}
return maxLen+1;
} } | public class class_name {
public int getMaxFieldLenth()
{
//get max field name
int maxLen = 0;
for ( String s : keys )
{
maxLen = s.length() > maxLen ? s.length() : maxLen; // depends on control dependency: [for], data = [s]
}
return maxLen+1;
} } |
public class class_name {
protected Collection<Artifact> getAllDependencies() throws Exception {
List<Artifact> artifacts = new ArrayList<Artifact>();
for (Iterator<?> dependencies = project.getDependencies().iterator(); dependencies.hasNext();) {
Dependency dependency = (Dependency)dependencies.next();
String groupId = dependency.getGroupId();
String artifactId = dependency.getArtifactId();
VersionRange versionRange;
try {
versionRange = VersionRange.createFromVersionSpec(dependency.getVersion());
} catch (InvalidVersionSpecificationException e) {
throw new MojoExecutionException("unable to parse version", e);
}
String type = dependency.getType();
if (type == null) {
type = "jar";
}
String classifier = dependency.getClassifier();
boolean optional = dependency.isOptional();
String scope = dependency.getScope();
if (scope == null) {
scope = Artifact.SCOPE_COMPILE;
}
Artifact art = this.artifactFactory.createDependencyArtifact(groupId, artifactId, versionRange,
type, classifier, scope, null, optional);
if (scope.equalsIgnoreCase(Artifact.SCOPE_SYSTEM)) {
art.setFile(new File(dependency.getSystemPath()));
}
List<String> exclusions = new ArrayList<String>();
for (Iterator<?> j = dependency.getExclusions().iterator(); j.hasNext();) {
Exclusion e = (Exclusion)j.next();
exclusions.add(e.getGroupId() + ":" + e.getArtifactId());
}
ArtifactFilter newFilter = new ExcludesArtifactFilter(exclusions);
art.setDependencyFilter(newFilter);
artifacts.add(art);
}
return artifacts;
} } | public class class_name {
protected Collection<Artifact> getAllDependencies() throws Exception {
List<Artifact> artifacts = new ArrayList<Artifact>();
for (Iterator<?> dependencies = project.getDependencies().iterator(); dependencies.hasNext();) {
Dependency dependency = (Dependency)dependencies.next();
String groupId = dependency.getGroupId();
String artifactId = dependency.getArtifactId();
VersionRange versionRange;
try {
versionRange = VersionRange.createFromVersionSpec(dependency.getVersion()); // depends on control dependency: [try], data = [none]
} catch (InvalidVersionSpecificationException e) {
throw new MojoExecutionException("unable to parse version", e);
} // depends on control dependency: [catch], data = [none]
String type = dependency.getType();
if (type == null) {
type = "jar"; // depends on control dependency: [if], data = [none]
}
String classifier = dependency.getClassifier();
boolean optional = dependency.isOptional();
String scope = dependency.getScope();
if (scope == null) {
scope = Artifact.SCOPE_COMPILE; // depends on control dependency: [if], data = [none]
}
Artifact art = this.artifactFactory.createDependencyArtifact(groupId, artifactId, versionRange,
type, classifier, scope, null, optional);
if (scope.equalsIgnoreCase(Artifact.SCOPE_SYSTEM)) {
art.setFile(new File(dependency.getSystemPath())); // depends on control dependency: [if], data = [none]
}
List<String> exclusions = new ArrayList<String>();
for (Iterator<?> j = dependency.getExclusions().iterator(); j.hasNext();) {
Exclusion e = (Exclusion)j.next();
exclusions.add(e.getGroupId() + ":" + e.getArtifactId()); // depends on control dependency: [for], data = [none]
}
ArtifactFilter newFilter = new ExcludesArtifactFilter(exclusions);
art.setDependencyFilter(newFilter);
artifacts.add(art);
}
return artifacts;
} } |
public class class_name {
private static String parseShortZoneID(String text, ParsePosition pos) {
String resolvedID = null;
if (SHORT_ZONE_ID_TRIE == null) {
synchronized (TimeZoneFormat.class) {
if (SHORT_ZONE_ID_TRIE == null) {
// Build short zone ID trie
TextTrieMap<String> trie = new TextTrieMap<String>(true);
Set<String> canonicalIDs = TimeZone.getAvailableIDs(SystemTimeZoneType.CANONICAL, null, null);
for (String id : canonicalIDs) {
String shortID = ZoneMeta.getShortID(id);
if (shortID != null) {
trie.put(shortID, id);
}
}
// Canonical list does not contain Etc/Unknown
trie.put(UNKNOWN_SHORT_ZONE_ID, UNKNOWN_ZONE_ID);
SHORT_ZONE_ID_TRIE = trie;
}
}
}
int[] matchLen = new int[] {0};
Iterator<String> itr = SHORT_ZONE_ID_TRIE.get(text, pos.getIndex(), matchLen);
if (itr != null) {
resolvedID = itr.next();
pos.setIndex(pos.getIndex() + matchLen[0]);
} else {
pos.setErrorIndex(pos.getIndex());
}
return resolvedID;
} } | public class class_name {
private static String parseShortZoneID(String text, ParsePosition pos) {
String resolvedID = null;
if (SHORT_ZONE_ID_TRIE == null) {
synchronized (TimeZoneFormat.class) { // depends on control dependency: [if], data = [none]
if (SHORT_ZONE_ID_TRIE == null) {
// Build short zone ID trie
TextTrieMap<String> trie = new TextTrieMap<String>(true);
Set<String> canonicalIDs = TimeZone.getAvailableIDs(SystemTimeZoneType.CANONICAL, null, null);
for (String id : canonicalIDs) {
String shortID = ZoneMeta.getShortID(id);
if (shortID != null) {
trie.put(shortID, id); // depends on control dependency: [if], data = [(shortID]
}
}
// Canonical list does not contain Etc/Unknown
trie.put(UNKNOWN_SHORT_ZONE_ID, UNKNOWN_ZONE_ID); // depends on control dependency: [if], data = [none]
SHORT_ZONE_ID_TRIE = trie; // depends on control dependency: [if], data = [none]
}
}
}
int[] matchLen = new int[] {0};
Iterator<String> itr = SHORT_ZONE_ID_TRIE.get(text, pos.getIndex(), matchLen);
if (itr != null) {
resolvedID = itr.next(); // depends on control dependency: [if], data = [none]
pos.setIndex(pos.getIndex() + matchLen[0]); // depends on control dependency: [if], data = [none]
} else {
pos.setErrorIndex(pos.getIndex()); // depends on control dependency: [if], data = [none]
}
return resolvedID;
} } |
public class class_name {
private static Method findMethod(
Object target,
String name,
Class<?> parameterType) {
for (Method method : target.getClass().getMethods()) {
if (!method.getName().equals(name)) {
continue;
}
Class<?>[] parameters = method.getParameterTypes();
if (parameters.length != 1) {
continue;
}
if (parameters[0].isAssignableFrom(parameterType)) {
return method;
}
}
throw new IllegalStateException(
"No method '" + name + "(" + parameterType + ") on type "
+ target.getClass());
} } | public class class_name {
private static Method findMethod(
Object target,
String name,
Class<?> parameterType) {
for (Method method : target.getClass().getMethods()) {
if (!method.getName().equals(name)) {
continue;
}
Class<?>[] parameters = method.getParameterTypes();
if (parameters.length != 1) {
continue;
}
if (parameters[0].isAssignableFrom(parameterType)) {
return method; // depends on control dependency: [if], data = [none]
}
}
throw new IllegalStateException(
"No method '" + name + "(" + parameterType + ") on type "
+ target.getClass());
} } |
public class class_name {
private boolean isObjectHasValue(Object targetObj) {
for (Map.Entry<String, String> entry : cellMapping.entrySet()) {
if (!StringUtils.equalsIgnoreCase(HEADER_KEY, entry.getKey())) {
if (StringUtils.isNotBlank(getPropertyValue(targetObj, entry.getValue()))) {
return true;
}
}
}
return false;
} } | public class class_name {
private boolean isObjectHasValue(Object targetObj) {
for (Map.Entry<String, String> entry : cellMapping.entrySet()) {
if (!StringUtils.equalsIgnoreCase(HEADER_KEY, entry.getKey())) {
if (StringUtils.isNotBlank(getPropertyValue(targetObj, entry.getValue()))) {
return true; // depends on control dependency: [if], data = [none]
}
}
}
return false;
} } |
public class class_name {
@SuppressWarnings("WeakerAccess")
public ByteBuffer getRawData() {
if (rawData != null) {
rawData.rewind();
return rawData.slice();
}
return null;
} } | public class class_name {
@SuppressWarnings("WeakerAccess")
public ByteBuffer getRawData() {
if (rawData != null) {
rawData.rewind(); // depends on control dependency: [if], data = [none]
return rawData.slice(); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
private static Integer[] castToInteger( int[] d )
{
Integer[] dest = new Integer[d.length];
for ( int i = 0; i < d.length; i++ )
{
dest[i] = d[i];
}
return dest;
} } | public class class_name {
private static Integer[] castToInteger( int[] d )
{
Integer[] dest = new Integer[d.length];
for ( int i = 0; i < d.length; i++ )
{
dest[i] = d[i]; // depends on control dependency: [for], data = [i]
}
return dest;
} } |
public class class_name {
public static int bytesToInt(byte[] bytes) {
assert bytes != null && bytes.length <= 4;
final int BYTE_SIZE = 8;
int value = 0;
for (int i = 0; i < bytes.length; i++) {
// shift byte i times, so it gets the correct significance
int shift = BYTE_SIZE * i;
// (b & 0xff) treats b as unsigned byte
// calculate the value to add by performing the shift
value += (bytes[i] & 0xff) << shift;
}
return value;
} } | public class class_name {
public static int bytesToInt(byte[] bytes) {
assert bytes != null && bytes.length <= 4;
final int BYTE_SIZE = 8;
int value = 0;
for (int i = 0; i < bytes.length; i++) {
// shift byte i times, so it gets the correct significance
int shift = BYTE_SIZE * i;
// (b & 0xff) treats b as unsigned byte
// calculate the value to add by performing the shift
value += (bytes[i] & 0xff) << shift; // depends on control dependency: [for], data = [i]
}
return value;
} } |
public class class_name {
@TargetApi(Build.VERSION_CODES.FROYO)
public static File getExternalCacheDir(Context context) {
if (Version.hasFroyo()) {
File path = context.getExternalCacheDir();
// In some case, even the sd card is mounted, getExternalCacheDir will return null, may be it is nearly full.
if (path != null) {
return path;
}
}
// Before Froyo or the path is null, we need to construct the external cache folder ourselves
final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
} } | public class class_name {
@TargetApi(Build.VERSION_CODES.FROYO)
public static File getExternalCacheDir(Context context) {
if (Version.hasFroyo()) {
File path = context.getExternalCacheDir();
// In some case, even the sd card is mounted, getExternalCacheDir will return null, may be it is nearly full.
if (path != null) {
return path; // depends on control dependency: [if], data = [none]
}
}
// Before Froyo or the path is null, we need to construct the external cache folder ourselves
final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
} } |
public class class_name {
public static long copyStream(InputStream input, OutputStream output, boolean closeStreams)
throws RuntimeException {
long numBytesCopied = 0;
int bufferSize = BUFFER_SIZE;
try {
// make sure we buffer the input
input = new BufferedInputStream(input, bufferSize);
byte[] buffer = new byte[bufferSize];
for (int bytesRead = input.read(buffer); bytesRead != -1; bytesRead = input.read(buffer)) {
output.write(buffer, 0, bytesRead);
numBytesCopied += bytesRead;
}
output.flush();
} catch (IOException ioe) {
throw new RuntimeException("Stream data cannot be copied", ioe);
} finally {
if (closeStreams) {
try {
output.close();
} catch (IOException ioe2) {
// what to do?
}
try {
input.close();
} catch (IOException ioe2) {
// what to do?
}
}
}
return numBytesCopied;
} } | public class class_name {
public static long copyStream(InputStream input, OutputStream output, boolean closeStreams)
throws RuntimeException {
long numBytesCopied = 0;
int bufferSize = BUFFER_SIZE;
try {
// make sure we buffer the input
input = new BufferedInputStream(input, bufferSize);
byte[] buffer = new byte[bufferSize];
for (int bytesRead = input.read(buffer); bytesRead != -1; bytesRead = input.read(buffer)) {
output.write(buffer, 0, bytesRead); // depends on control dependency: [for], data = [bytesRead]
numBytesCopied += bytesRead; // depends on control dependency: [for], data = [bytesRead]
}
output.flush();
} catch (IOException ioe) {
throw new RuntimeException("Stream data cannot be copied", ioe);
} finally {
if (closeStreams) {
try {
output.close(); // depends on control dependency: [try], data = [none]
} catch (IOException ioe2) {
// what to do?
} // depends on control dependency: [catch], data = [none]
try {
input.close(); // depends on control dependency: [try], data = [none]
} catch (IOException ioe2) {
// what to do?
} // depends on control dependency: [catch], data = [none]
}
}
return numBytesCopied;
} } |
public class class_name {
public boolean init(String modelDir) {
this.modelDir = modelDir;
Option taggerOpt = new Option(this.modelDir);
if (!taggerOpt.readOptions()) {
return false;
}
taggerMaps = new Maps();
taggerDict = new Dictionary();
taggerFGen = new FeatureGen(taggerMaps, taggerDict);
taggerVtb = new Viterbi();
taggerModel = new Model(taggerOpt, taggerMaps, taggerDict, taggerFGen,
taggerVtb);
if (!taggerModel.init()) {
System.out.println("Couldn't load the model");
System.out.println("Check the <model directory> and the <model file> again");
return false;
}
return true;
} } | public class class_name {
public boolean init(String modelDir) {
this.modelDir = modelDir;
Option taggerOpt = new Option(this.modelDir);
if (!taggerOpt.readOptions()) {
return false;
// depends on control dependency: [if], data = [none]
}
taggerMaps = new Maps();
taggerDict = new Dictionary();
taggerFGen = new FeatureGen(taggerMaps, taggerDict);
taggerVtb = new Viterbi();
taggerModel = new Model(taggerOpt, taggerMaps, taggerDict, taggerFGen,
taggerVtb);
if (!taggerModel.init()) {
System.out.println("Couldn't load the model");
// depends on control dependency: [if], data = [none]
System.out.println("Check the <model directory> and the <model file> again");
// depends on control dependency: [if], data = [none]
return false;
// depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
protected void handleConfigureResponse(MemberState member, ConfigureRequest request, ConfigureResponse response) {
if (response.status() == Response.Status.OK) {
handleConfigureResponseOk(member, request, response);
} else {
handleConfigureResponseError(member, request, response);
}
} } | public class class_name {
protected void handleConfigureResponse(MemberState member, ConfigureRequest request, ConfigureResponse response) {
if (response.status() == Response.Status.OK) {
handleConfigureResponseOk(member, request, response); // depends on control dependency: [if], data = [none]
} else {
handleConfigureResponseError(member, request, response); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public CPRuleUserSegmentRel fetchByCommerceUserSegmentEntryId_Last(
long commerceUserSegmentEntryId,
OrderByComparator<CPRuleUserSegmentRel> orderByComparator) {
int count = countByCommerceUserSegmentEntryId(commerceUserSegmentEntryId);
if (count == 0) {
return null;
}
List<CPRuleUserSegmentRel> list = findByCommerceUserSegmentEntryId(commerceUserSegmentEntryId,
count - 1, count, orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
} } | public class class_name {
@Override
public CPRuleUserSegmentRel fetchByCommerceUserSegmentEntryId_Last(
long commerceUserSegmentEntryId,
OrderByComparator<CPRuleUserSegmentRel> orderByComparator) {
int count = countByCommerceUserSegmentEntryId(commerceUserSegmentEntryId);
if (count == 0) {
return null; // depends on control dependency: [if], data = [none]
}
List<CPRuleUserSegmentRel> list = findByCommerceUserSegmentEntryId(commerceUserSegmentEntryId,
count - 1, count, orderByComparator);
if (!list.isEmpty()) {
return list.get(0); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
@Deprecated
public static <K, V> ImmutableMap<K, V> disjointUnion(Map<K, V> first, Map<K, V> second) {
checkNotNull(first);
checkNotNull(second);
final ImmutableMap.Builder<K, V> ret = ImmutableMap.builder();
// will throw an exception if there is any null mapping
ret.putAll(first);
for (final Entry<K, V> secondEntry : second.entrySet()) {
final V firstForKey = first.get(secondEntry.getKey());
if (firstForKey == null) {
// non-duplicate
// we know the first map doesn't actually map this key to null
// or ret.putAll(first) above would fail
ret.put(secondEntry.getKey(), secondEntry.getValue());
} else //noinspection StatementWithEmptyBody
if (firstForKey.equals(secondEntry.getValue())) {
// duplicate. This is okay. Do nothing.
} else {
throw new RuntimeException("When attempting a disjoint map union, " +
String.format("for key %s, first map had %s but second had %s", secondEntry.getKey(),
firstForKey, secondEntry.getValue()));
}
}
return ret.build();
} } | public class class_name {
@Deprecated
public static <K, V> ImmutableMap<K, V> disjointUnion(Map<K, V> first, Map<K, V> second) {
checkNotNull(first);
checkNotNull(second);
final ImmutableMap.Builder<K, V> ret = ImmutableMap.builder();
// will throw an exception if there is any null mapping
ret.putAll(first);
for (final Entry<K, V> secondEntry : second.entrySet()) {
final V firstForKey = first.get(secondEntry.getKey());
if (firstForKey == null) {
// non-duplicate
// we know the first map doesn't actually map this key to null
// or ret.putAll(first) above would fail
ret.put(secondEntry.getKey(), secondEntry.getValue()); // depends on control dependency: [if], data = [none]
} else //noinspection StatementWithEmptyBody
if (firstForKey.equals(secondEntry.getValue())) {
// duplicate. This is okay. Do nothing.
} else {
throw new RuntimeException("When attempting a disjoint map union, " +
String.format("for key %s, first map had %s but second had %s", secondEntry.getKey(),
firstForKey, secondEntry.getValue()));
}
}
return ret.build();
} } |
public class class_name {
public void onAuthentication(Authentication authentication,
HttpServletRequest request, HttpServletResponse response)
throws SessionAuthenticationException {
for (SessionAuthenticationStrategy delegate : this.delegateStrategies) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Delegating to " + delegate);
}
delegate.onAuthentication(authentication, request, response);
}
} } | public class class_name {
public void onAuthentication(Authentication authentication,
HttpServletRequest request, HttpServletResponse response)
throws SessionAuthenticationException {
for (SessionAuthenticationStrategy delegate : this.delegateStrategies) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Delegating to " + delegate); // depends on control dependency: [if], data = [none]
}
delegate.onAuthentication(authentication, request, response);
}
} } |
public class class_name {
public <A2 extends Annotation> AnnotationMetadata annotate(
AnnotationMetadata annotationMetadata,
AnnotationValue<A2> annotationValue) {
if (annotationMetadata instanceof DefaultAnnotationMetadata) {
final Optional<T> annotationMirror = getAnnotationMirror(annotationValue.getAnnotationName());
final DefaultAnnotationMetadata defaultMetadata = (DefaultAnnotationMetadata) annotationMetadata;
defaultMetadata.addDeclaredAnnotation(
annotationValue.getAnnotationName(),
annotationValue.getValues()
);
annotationMirror.ifPresent(annotationType ->
processAnnotationStereotypes(
defaultMetadata,
true,
annotationType,
annotationValue.getAnnotationName()
)
);
}
return annotationMetadata;
} } | public class class_name {
public <A2 extends Annotation> AnnotationMetadata annotate(
AnnotationMetadata annotationMetadata,
AnnotationValue<A2> annotationValue) {
if (annotationMetadata instanceof DefaultAnnotationMetadata) {
final Optional<T> annotationMirror = getAnnotationMirror(annotationValue.getAnnotationName());
final DefaultAnnotationMetadata defaultMetadata = (DefaultAnnotationMetadata) annotationMetadata;
defaultMetadata.addDeclaredAnnotation(
annotationValue.getAnnotationName(),
annotationValue.getValues()
); // depends on control dependency: [if], data = [none]
annotationMirror.ifPresent(annotationType ->
processAnnotationStereotypes(
defaultMetadata,
true,
annotationType,
annotationValue.getAnnotationName()
)
); // depends on control dependency: [if], data = [none]
}
return annotationMetadata;
} } |
public class class_name {
public void offerStatement(int stmtHash, int offset, ByteBuffer psetBuffer) {
m_inputCRC.update(stmtHash);
m_inputCRC.updateFromPosition(offset, psetBuffer);
if (m_hashCount < MAX_HASHES_COUNT) {
m_hashes[m_hashCount] = stmtHash;
m_hashes[m_hashCount + 1] = (int) m_inputCRC.getValue();
}
m_hashCount += 2;
} } | public class class_name {
public void offerStatement(int stmtHash, int offset, ByteBuffer psetBuffer) {
m_inputCRC.update(stmtHash);
m_inputCRC.updateFromPosition(offset, psetBuffer);
if (m_hashCount < MAX_HASHES_COUNT) {
m_hashes[m_hashCount] = stmtHash; // depends on control dependency: [if], data = [none]
m_hashes[m_hashCount + 1] = (int) m_inputCRC.getValue(); // depends on control dependency: [if], data = [none]
}
m_hashCount += 2;
} } |
public class class_name {
public boolean intersects(Range r) {
if ((length() == 0) || (r.length() == 0))
return false;
if (this == VLEN || r == VLEN)
return true;
int last = Math.min(this.last(), r.last());
int resultStride = stride * r.stride();
int useFirst;
if (resultStride == 1) { // both strides are 1
useFirst = Math.max(this.first(), r.first());
} else if (stride == 1) { // then r has a stride
if (r.first() >= first())
useFirst = r.first();
else {
int incr = (first() - r.first()) / resultStride;
useFirst = r.first() + incr * resultStride;
if (useFirst < first()) useFirst += resultStride;
}
} else if (r.stride() == 1) { // then this has a stride
if (first() >= r.first())
useFirst = first();
else {
int incr = (r.first() - first()) / resultStride;
useFirst = first() + incr * resultStride;
if (useFirst < r.first()) useFirst += resultStride;
}
} else {
throw new UnsupportedOperationException("Intersection when both ranges have a stride");
}
return (useFirst <= last);
} } | public class class_name {
public boolean intersects(Range r) {
if ((length() == 0) || (r.length() == 0))
return false;
if (this == VLEN || r == VLEN)
return true;
int last = Math.min(this.last(), r.last());
int resultStride = stride * r.stride();
int useFirst;
if (resultStride == 1) { // both strides are 1
useFirst = Math.max(this.first(), r.first()); // depends on control dependency: [if], data = [none]
} else if (stride == 1) { // then r has a stride
if (r.first() >= first())
useFirst = r.first();
else {
int incr = (first() - r.first()) / resultStride;
useFirst = r.first() + incr * resultStride; // depends on control dependency: [if], data = [none]
if (useFirst < first()) useFirst += resultStride;
}
} else if (r.stride() == 1) { // then this has a stride
if (first() >= r.first())
useFirst = first();
else {
int incr = (r.first() - first()) / resultStride;
useFirst = first() + incr * resultStride; // depends on control dependency: [if], data = [none]
if (useFirst < r.first()) useFirst += resultStride;
}
} else {
throw new UnsupportedOperationException("Intersection when both ranges have a stride");
}
return (useFirst <= last);
} } |
public class class_name {
private void addBackup() {
// move the current log file to the newly formatted backup name
String newname = this.fileinfo + this.myFormat.format(new Date(HttpDispatcher.getApproxTime())) + this.extensioninfo;
File newFile = new File(newname);
renameFile(this.myFile, newFile);
// now see if we need to delete an existing backup to make room
if (this.backups.size() == getMaximumBackupFiles()) {
File oldest = this.backups.removeLast();
if (null != oldest && oldest.exists()) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, getFileName() + ": Purging oldest backup-> " + oldest.getName());
}
oldest.delete();
}
}
this.backups.addFirst(newFile);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, getFileName() + ": number of backup files-> " + this.backups.size());
}
} } | public class class_name {
private void addBackup() {
// move the current log file to the newly formatted backup name
String newname = this.fileinfo + this.myFormat.format(new Date(HttpDispatcher.getApproxTime())) + this.extensioninfo;
File newFile = new File(newname);
renameFile(this.myFile, newFile);
// now see if we need to delete an existing backup to make room
if (this.backups.size() == getMaximumBackupFiles()) {
File oldest = this.backups.removeLast();
if (null != oldest && oldest.exists()) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, getFileName() + ": Purging oldest backup-> " + oldest.getName()); // depends on control dependency: [if], data = [none]
}
oldest.delete(); // depends on control dependency: [if], data = [none]
}
}
this.backups.addFirst(newFile);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, getFileName() + ": number of backup files-> " + this.backups.size()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static Element drawCosine(SVGPlot svgp, Projection2D proj, NumberVector mid, double angle) {
// Project origin
double[] pointOfOrigin = proj.fastProjectDataToRenderSpace(new double[proj.getInputDimensionality()]);
// direction of the selected Point
double[] selPoint = proj.fastProjectDataToRenderSpace(mid);
double[] range1, range2;
{
// Rotation plane:
double[] pm = mid.toArray();
// Compute relative vectors
double[] p1 = minusEquals(proj.fastProjectRenderToDataSpace(selPoint[0] + 10, selPoint[1]), pm);
double[] p2 = minusEquals(proj.fastProjectRenderToDataSpace(selPoint[0], selPoint[1] + 10), pm);
// Scale p1 and p2 to unit length:
timesEquals(p1, 1. / euclideanLength(p1));
timesEquals(p2, 1. / euclideanLength(p2));
if(Math.abs(scalarProduct(p1, p2)) > 1E-10) {
LoggingUtil.warning("Projection does not seem to be orthogonal?");
}
// Project onto p1, p2:
double l1 = scalarProduct(pm, p1), l2 = scalarProduct(pm, p2);
// Rotate projection by + and - angle
// Using sin(-x) = -sin(x) and cos(-x)=cos(x)
final DoubleWrapper tmp = new DoubleWrapper(); // To return cosine
final double sangle = FastMath.sinAndCos(angle, tmp), cangle = tmp.value;
double r11 = +cangle * l1 - sangle * l2, r12 = +sangle * l1 + cangle * l2;
double r21 = +cangle * l1 + sangle * l2, r22 = -sangle * l1 + cangle * l2;
// Build rotated vectors - remove projected component, add rotated
// component:
double[] r1 = plusTimesEquals(plusTimes(pm, p1, -l1 + r11), p2, -l2 + r12);
double[] r2 = plusTimesEquals(plusTimes(pm, p1, -l1 + r21), p2, -l2 + r22);
// Project to render space:
range1 = proj.fastProjectDataToRenderSpace(r1);
range2 = proj.fastProjectDataToRenderSpace(r2);
}
// Continue lines to viewport.
{
CanvasSize viewport = proj.estimateViewport();
minusEquals(range1, pointOfOrigin);
plusEquals(timesEquals(range1, viewport.continueToMargin(pointOfOrigin, range1)), pointOfOrigin);
minusEquals(range2, pointOfOrigin);
plusEquals(timesEquals(range2, viewport.continueToMargin(pointOfOrigin, range2)), pointOfOrigin);
// Go backwards into the other direction - the origin might not be in the
// viewport!
double[] start1 = minus(pointOfOrigin, range1);
plusEquals(timesEquals(start1, viewport.continueToMargin(range1, start1)), range1);
double[] start2 = minus(pointOfOrigin, range2);
plusEquals(timesEquals(start2, viewport.continueToMargin(range2, start2)), range2);
// TODO: add filled variant?
return new SVGPath().moveTo(start1).lineTo(range1).moveTo(start2).lineTo(range2).makeElement(svgp);
}
} } | public class class_name {
public static Element drawCosine(SVGPlot svgp, Projection2D proj, NumberVector mid, double angle) {
// Project origin
double[] pointOfOrigin = proj.fastProjectDataToRenderSpace(new double[proj.getInputDimensionality()]);
// direction of the selected Point
double[] selPoint = proj.fastProjectDataToRenderSpace(mid);
double[] range1, range2;
{
// Rotation plane:
double[] pm = mid.toArray();
// Compute relative vectors
double[] p1 = minusEquals(proj.fastProjectRenderToDataSpace(selPoint[0] + 10, selPoint[1]), pm);
double[] p2 = minusEquals(proj.fastProjectRenderToDataSpace(selPoint[0], selPoint[1] + 10), pm);
// Scale p1 and p2 to unit length:
timesEquals(p1, 1. / euclideanLength(p1));
timesEquals(p2, 1. / euclideanLength(p2));
if(Math.abs(scalarProduct(p1, p2)) > 1E-10) {
LoggingUtil.warning("Projection does not seem to be orthogonal?"); // depends on control dependency: [if], data = [none]
}
// Project onto p1, p2:
double l1 = scalarProduct(pm, p1), l2 = scalarProduct(pm, p2);
// Rotate projection by + and - angle
// Using sin(-x) = -sin(x) and cos(-x)=cos(x)
final DoubleWrapper tmp = new DoubleWrapper(); // To return cosine
final double sangle = FastMath.sinAndCos(angle, tmp), cangle = tmp.value;
double r11 = +cangle * l1 - sangle * l2, r12 = +sangle * l1 + cangle * l2;
double r21 = +cangle * l1 + sangle * l2, r22 = -sangle * l1 + cangle * l2;
// Build rotated vectors - remove projected component, add rotated
// component:
double[] r1 = plusTimesEquals(plusTimes(pm, p1, -l1 + r11), p2, -l2 + r12);
double[] r2 = plusTimesEquals(plusTimes(pm, p1, -l1 + r21), p2, -l2 + r22);
// Project to render space:
range1 = proj.fastProjectDataToRenderSpace(r1);
range2 = proj.fastProjectDataToRenderSpace(r2);
}
// Continue lines to viewport.
{
CanvasSize viewport = proj.estimateViewport();
minusEquals(range1, pointOfOrigin);
plusEquals(timesEquals(range1, viewport.continueToMargin(pointOfOrigin, range1)), pointOfOrigin);
minusEquals(range2, pointOfOrigin);
plusEquals(timesEquals(range2, viewport.continueToMargin(pointOfOrigin, range2)), pointOfOrigin);
// Go backwards into the other direction - the origin might not be in the
// viewport!
double[] start1 = minus(pointOfOrigin, range1);
plusEquals(timesEquals(start1, viewport.continueToMargin(range1, start1)), range1);
double[] start2 = minus(pointOfOrigin, range2);
plusEquals(timesEquals(start2, viewport.continueToMargin(range2, start2)), range2);
// TODO: add filled variant?
return new SVGPath().moveTo(start1).lineTo(range1).moveTo(start2).lineTo(range2).makeElement(svgp);
}
} } |
public class class_name {
public boolean addOnScaledListener(OnScaledListener listener) {
final boolean added = mOnScaledListeners.add(listener);
if (added) {
listener.onScaled(mSceneRootObject.getTransform().getScaleX());
}
return added;
} } | public class class_name {
public boolean addOnScaledListener(OnScaledListener listener) {
final boolean added = mOnScaledListeners.add(listener);
if (added) {
listener.onScaled(mSceneRootObject.getTransform().getScaleX()); // depends on control dependency: [if], data = [none]
}
return added;
} } |
public class class_name {
public void waitForJobToComplete(String jobId) {
while (true) {
List<Message> messages = sqs.receiveMessage(new ReceiveMessageRequest(queueUrl)).getMessages();
for (Message message : messages) {
String messageBody = message.getBody();
if (!messageBody.startsWith("{")) {
messageBody = new String(BinaryUtils.fromBase64(messageBody));
}
try {
JsonNode json = MAPPER.readTree(messageBody);
String jsonMessage = json.get("Message").asText().replace("\\\"", "\"");
json = MAPPER.readTree(jsonMessage);
String messageJobId = json.get("JobId").asText();
String messageStatus = json.get("StatusMessage").asText();
// Don't process this message if it wasn't the job we were looking for
if (!jobId.equals(messageJobId)) continue;
try {
if (StatusCode.Succeeded.toString().equals(messageStatus)) return;
if (StatusCode.Failed.toString().equals(messageStatus)) {
throw new AmazonClientException("Archive retrieval failed");
}
} finally {
deleteMessage(message);
}
} catch (IOException e) {
throw new AmazonClientException("Unable to parse status message: " + messageBody, e);
}
}
sleep(1000 * 30);
}
} } | public class class_name {
public void waitForJobToComplete(String jobId) {
while (true) {
List<Message> messages = sqs.receiveMessage(new ReceiveMessageRequest(queueUrl)).getMessages();
for (Message message : messages) {
String messageBody = message.getBody();
if (!messageBody.startsWith("{")) {
messageBody = new String(BinaryUtils.fromBase64(messageBody)); // depends on control dependency: [if], data = [none]
}
try {
JsonNode json = MAPPER.readTree(messageBody);
String jsonMessage = json.get("Message").asText().replace("\\\"", "\"");
json = MAPPER.readTree(jsonMessage);
String messageJobId = json.get("JobId").asText();
String messageStatus = json.get("StatusMessage").asText();
// Don't process this message if it wasn't the job we were looking for
if (!jobId.equals(messageJobId)) continue;
try {
if (StatusCode.Succeeded.toString().equals(messageStatus)) return;
if (StatusCode.Failed.toString().equals(messageStatus)) {
throw new AmazonClientException("Archive retrieval failed");
}
} finally {
deleteMessage(message);
}
} catch (IOException e) {
throw new AmazonClientException("Unable to parse status message: " + messageBody, e);
}
}
sleep(1000 * 30);
}
} } |
public class class_name {
static ArrayOfDoublesUnion heapifyUnion(final Memory mem, final long seed) {
final SerializerDeserializer.SketchType type = SerializerDeserializer.getSketchType(mem);
// compatibility with version 0.9.1 and lower
if (type == SerializerDeserializer.SketchType.ArrayOfDoublesQuickSelectSketch) {
final ArrayOfDoublesQuickSelectSketch sketch = new HeapArrayOfDoublesQuickSelectSketch(mem, seed);
return new HeapArrayOfDoublesUnion(sketch);
}
final byte version = mem.getByte(SERIAL_VERSION_BYTE);
if (version != serialVersionUID) {
throw new SketchesArgumentException("Serial version mismatch. Expected: "
+ serialVersionUID + ", actual: " + version);
}
SerializerDeserializer.validateFamily(mem.getByte(FAMILY_ID_BYTE), mem.getByte(PREAMBLE_LONGS_BYTE));
SerializerDeserializer.validateType(mem.getByte(SKETCH_TYPE_BYTE),
SerializerDeserializer.SketchType.ArrayOfDoublesUnion);
final long unionTheta = mem.getLong(THETA_LONG);
final Memory sketchMem = mem.region(PREAMBLE_SIZE_BYTES, mem.getCapacity() - PREAMBLE_SIZE_BYTES);
final ArrayOfDoublesQuickSelectSketch sketch = new HeapArrayOfDoublesQuickSelectSketch(sketchMem, seed);
final ArrayOfDoublesUnion union = new HeapArrayOfDoublesUnion(sketch);
union.theta_ = unionTheta;
return union;
} } | public class class_name {
static ArrayOfDoublesUnion heapifyUnion(final Memory mem, final long seed) {
final SerializerDeserializer.SketchType type = SerializerDeserializer.getSketchType(mem);
// compatibility with version 0.9.1 and lower
if (type == SerializerDeserializer.SketchType.ArrayOfDoublesQuickSelectSketch) {
final ArrayOfDoublesQuickSelectSketch sketch = new HeapArrayOfDoublesQuickSelectSketch(mem, seed);
return new HeapArrayOfDoublesUnion(sketch); // depends on control dependency: [if], data = [none]
}
final byte version = mem.getByte(SERIAL_VERSION_BYTE);
if (version != serialVersionUID) {
throw new SketchesArgumentException("Serial version mismatch. Expected: "
+ serialVersionUID + ", actual: " + version);
}
SerializerDeserializer.validateFamily(mem.getByte(FAMILY_ID_BYTE), mem.getByte(PREAMBLE_LONGS_BYTE));
SerializerDeserializer.validateType(mem.getByte(SKETCH_TYPE_BYTE),
SerializerDeserializer.SketchType.ArrayOfDoublesUnion);
final long unionTheta = mem.getLong(THETA_LONG);
final Memory sketchMem = mem.region(PREAMBLE_SIZE_BYTES, mem.getCapacity() - PREAMBLE_SIZE_BYTES);
final ArrayOfDoublesQuickSelectSketch sketch = new HeapArrayOfDoublesQuickSelectSketch(sketchMem, seed);
final ArrayOfDoublesUnion union = new HeapArrayOfDoublesUnion(sketch);
union.theta_ = unionTheta;
return union;
} } |
public class class_name {
public int getNextCode() {
// Attempt to get the next code. The exception is caught to make
// this robust to cases wherein the EndOfInformation code has been
// omitted from a strip. Examples of such cases have been observed
// in practice.
try {
nextData = (nextData << 8) | (data[bytePointer++] & 0xff);
nextBits += 8;
if (nextBits < bitsToGet) {
nextData = (nextData << 8) | (data[bytePointer++] & 0xff);
nextBits += 8;
}
int code =
(nextData >> (nextBits - bitsToGet)) & andTable[bitsToGet-9];
nextBits -= bitsToGet;
return code;
} catch(ArrayIndexOutOfBoundsException e) {
// Strip not terminated as expected: return EndOfInformation code.
return 257;
}
} } | public class class_name {
public int getNextCode() {
// Attempt to get the next code. The exception is caught to make
// this robust to cases wherein the EndOfInformation code has been
// omitted from a strip. Examples of such cases have been observed
// in practice.
try {
nextData = (nextData << 8) | (data[bytePointer++] & 0xff); // depends on control dependency: [try], data = [none]
nextBits += 8; // depends on control dependency: [try], data = [none]
if (nextBits < bitsToGet) {
nextData = (nextData << 8) | (data[bytePointer++] & 0xff); // depends on control dependency: [if], data = [none]
nextBits += 8; // depends on control dependency: [if], data = [none]
}
int code =
(nextData >> (nextBits - bitsToGet)) & andTable[bitsToGet-9];
nextBits -= bitsToGet; // depends on control dependency: [try], data = [none]
return code; // depends on control dependency: [try], data = [none]
} catch(ArrayIndexOutOfBoundsException e) {
// Strip not terminated as expected: return EndOfInformation code.
return 257;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected Map<String, AbstractServer> createServices(ServerSetup[] config, Managers mgr) {
Map<String, AbstractServer> srvc = new HashMap<>();
for (ServerSetup setup : config) {
if (srvc.containsKey(setup.getProtocol())) {
throw new IllegalArgumentException("Server '" + setup.getProtocol() + "' was found at least twice in the array");
}
final String protocol = setup.getProtocol();
if (protocol.startsWith(ServerSetup.PROTOCOL_SMTP)) {
srvc.put(protocol, new SmtpServer(setup, mgr));
} else if (protocol.startsWith(ServerSetup.PROTOCOL_POP3)) {
srvc.put(protocol, new Pop3Server(setup, mgr));
} else if (protocol.startsWith(ServerSetup.PROTOCOL_IMAP)) {
srvc.put(protocol, new ImapServer(setup, mgr));
}
}
return srvc;
} } | public class class_name {
protected Map<String, AbstractServer> createServices(ServerSetup[] config, Managers mgr) {
Map<String, AbstractServer> srvc = new HashMap<>();
for (ServerSetup setup : config) {
if (srvc.containsKey(setup.getProtocol())) {
throw new IllegalArgumentException("Server '" + setup.getProtocol() + "' was found at least twice in the array");
}
final String protocol = setup.getProtocol();
if (protocol.startsWith(ServerSetup.PROTOCOL_SMTP)) {
srvc.put(protocol, new SmtpServer(setup, mgr));
// depends on control dependency: [if], data = [none]
} else if (protocol.startsWith(ServerSetup.PROTOCOL_POP3)) {
srvc.put(protocol, new Pop3Server(setup, mgr));
// depends on control dependency: [if], data = [none]
} else if (protocol.startsWith(ServerSetup.PROTOCOL_IMAP)) {
srvc.put(protocol, new ImapServer(setup, mgr));
// depends on control dependency: [if], data = [none]
}
}
return srvc;
} } |
public class class_name {
static <T> T transform(Object value, Class<T> toClazz, Registry registry) {
try {
if (toClazz.isInstance(value)) {
return (T) value;
}
else if (value instanceof BindObject) {
T bean = newInstance(toClazz);
for(Map.Entry<String, Object> entry : (BindObject) value) {
Class<?> requiredType = PropertyUtils.getPropertyType(toClazz, entry.getKey());
Object propValue = transform(entry.getValue(), requiredType, registry);
if (propValue != null) {
PropertyUtils.writeProperty(bean, entry.getKey(), propValue);
}
}
return bean;
}
else if (value instanceof Optional) {
Optional<?> optional = (Optional) value;
if (toClazz == Optional.class) {
Class<?> targetType = PropertyUtils.getGenericParamTypes(toClazz)[0];
return (T) optional.map(v -> transform(v, targetType, registry));
} else {
return transform(optional.orElse(null), toClazz, registry);
}
}
else if (value instanceof Map) {
Map<?, ?> values = (Map) value;
if (Map.class.isAssignableFrom(toClazz)) {
Class<?> keyType = PropertyUtils.getGenericParamTypes(toClazz)[0];
Class<?> valueType = PropertyUtils.getGenericParamTypes(toClazz)[1];
values = values.entrySet().stream().map(e ->
entry(transform(e.getKey(), keyType, registry),
transform(e.getValue(), valueType, registry))
).collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue
));
return doTransform(values, toClazz, registry);
}
else throw new IllegalArgumentException(
"INCOMPATIBLE transform: " + value.getClass().getName() + " -> " + toClazz.getName());
}
else if (value instanceof Collection) {
Collection<?> values = (Collection) value;
if (Collection.class.isAssignableFrom(toClazz) || toClazz.isArray()) {
Class<?> elemType = toClazz.isArray() ? toClazz.getComponentType()
: PropertyUtils.getGenericParamTypes(toClazz)[0];
values = values.stream().map(v -> transform(v, elemType, registry))
.collect(Collectors.<Object>toList());
return doTransform(values, toClazz, registry);
}
else throw new IllegalArgumentException(
"INCOMPATIBLE transform: " + value.getClass().getName() + " -> " + toClazz.getName());
}
else {
return doTransform(value, toClazz, registry);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
} } | public class class_name {
static <T> T transform(Object value, Class<T> toClazz, Registry registry) {
try {
if (toClazz.isInstance(value)) {
return (T) value; // depends on control dependency: [if], data = [none]
}
else if (value instanceof BindObject) {
T bean = newInstance(toClazz);
for(Map.Entry<String, Object> entry : (BindObject) value) {
Class<?> requiredType = PropertyUtils.getPropertyType(toClazz, entry.getKey());
Object propValue = transform(entry.getValue(), requiredType, registry);
if (propValue != null) {
PropertyUtils.writeProperty(bean, entry.getKey(), propValue); // depends on control dependency: [if], data = [none]
}
}
return bean; // depends on control dependency: [if], data = [none]
}
else if (value instanceof Optional) {
Optional<?> optional = (Optional) value;
if (toClazz == Optional.class) {
Class<?> targetType = PropertyUtils.getGenericParamTypes(toClazz)[0];
return (T) optional.map(v -> transform(v, targetType, registry)); // depends on control dependency: [if], data = [none]
} else {
return transform(optional.orElse(null), toClazz, registry); // depends on control dependency: [if], data = [none]
}
}
else if (value instanceof Map) {
Map<?, ?> values = (Map) value; // depends on control dependency: [if], data = [none]
if (Map.class.isAssignableFrom(toClazz)) {
Class<?> keyType = PropertyUtils.getGenericParamTypes(toClazz)[0];
Class<?> valueType = PropertyUtils.getGenericParamTypes(toClazz)[1];
values = values.entrySet().stream().map(e ->
entry(transform(e.getKey(), keyType, registry),
transform(e.getValue(), valueType, registry))
).collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue
));
return doTransform(values, toClazz, registry);
}
else throw new IllegalArgumentException(
"INCOMPATIBLE transform: " + value.getClass().getName() + " -> " + toClazz.getName());
}
else if (value instanceof Collection) {
Collection<?> values = (Collection) value;
if (Collection.class.isAssignableFrom(toClazz) || toClazz.isArray()) {
Class<?> elemType = toClazz.isArray() ? toClazz.getComponentType()
: PropertyUtils.getGenericParamTypes(toClazz)[0];
values = values.stream().map(v -> transform(v, elemType, registry))
.collect(Collectors.<Object>toList());
return doTransform(values, toClazz, registry);
}
else throw new IllegalArgumentException(
"INCOMPATIBLE transform: " + value.getClass().getName() + " -> " + toClazz.getName()); // depends on control dependency: [if], data = [none]
}
else {
return doTransform(value, toClazz, registry); // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
throw new RuntimeException(e);
}
} } |
public class class_name {
@PostConstruct
public void initialize() {
final FwWebDirection direction = assistWebDirection();
final CsrfResourceProvider resourceProvider = direction.assistCsrfResourceProvider();
if (resourceProvider != null) {
final String providedHeaderName = resourceProvider.provideTokenHeaderName();
if (providedHeaderName != null) {
tokenHeaderName = providedHeaderName;
}
final String providedParameterName = resourceProvider.provideTokenParameterName();
if (providedParameterName != null) {
tokenParameterName = providedParameterName;
}
final CsrfTokenGenerator providedGenerator = resourceProvider.provideTokenGenerator();
if (providedGenerator != null) {
tokenGenerator = providedGenerator;
}
}
if (tokenGenerator == null) {
tokenGenerator = createDefaultTokenGenerator();
}
showBootLogging();
} } | public class class_name {
@PostConstruct
public void initialize() {
final FwWebDirection direction = assistWebDirection();
final CsrfResourceProvider resourceProvider = direction.assistCsrfResourceProvider();
if (resourceProvider != null) {
final String providedHeaderName = resourceProvider.provideTokenHeaderName();
if (providedHeaderName != null) {
tokenHeaderName = providedHeaderName; // depends on control dependency: [if], data = [none]
}
final String providedParameterName = resourceProvider.provideTokenParameterName();
if (providedParameterName != null) {
tokenParameterName = providedParameterName; // depends on control dependency: [if], data = [none]
}
final CsrfTokenGenerator providedGenerator = resourceProvider.provideTokenGenerator();
if (providedGenerator != null) {
tokenGenerator = providedGenerator; // depends on control dependency: [if], data = [none]
}
}
if (tokenGenerator == null) {
tokenGenerator = createDefaultTokenGenerator(); // depends on control dependency: [if], data = [none]
}
showBootLogging();
} } |
public class class_name {
void updateMembers(MembersView membersView) {
MemberMap currentMemberMap = memberMapRef.get();
Collection<MemberImpl> addedMembers = new LinkedList<>();
Collection<MemberImpl> removedMembers = new LinkedList<>();
ClusterHeartbeatManager clusterHeartbeatManager = clusterService.getClusterHeartbeatManager();
MemberImpl[] members = new MemberImpl[membersView.size()];
int memberIndex = 0;
for (MemberInfo memberInfo : membersView.getMembers()) {
Address address = memberInfo.getAddress();
MemberImpl member = currentMemberMap.getMember(address);
if (member != null && member.getUuid().equals(memberInfo.getUuid())) {
member = createNewMemberImplIfChanged(memberInfo, member);
members[memberIndex++] = member;
continue;
}
if (member != null) {
assert !(member.localMember() && member.equals(clusterService.getLocalMember()))
: "Local " + member + " cannot be replaced with " + memberInfo;
// UUID changed: means member has gone and come back with a new uuid
removedMembers.add(member);
}
member = createMember(memberInfo, memberInfo.getAttributes());
addedMembers.add(member);
long now = clusterService.getClusterTime();
clusterHeartbeatManager.onHeartbeat(member, now);
repairPartitionTableIfReturningMember(member);
members[memberIndex++] = member;
}
MemberMap newMemberMap = membersView.toMemberMap();
for (MemberImpl member : currentMemberMap.getMembers()) {
if (!newMemberMap.contains(member.getAddress())) {
removedMembers.add(member);
}
}
setMembers(MemberMap.createNew(membersView.getVersion(), members));
for (MemberImpl member : removedMembers) {
closeConnection(member.getAddress(), "Member left event received from master");
handleMemberRemove(memberMapRef.get(), member);
}
clusterService.getClusterJoinManager().insertIntoRecentlyJoinedMemberSet(addedMembers);
sendMembershipEvents(currentMemberMap.getMembers(), addedMembers);
removeFromMissingMembers(members);
clusterHeartbeatManager.heartbeat();
clusterService.printMemberList();
//async call
node.getNodeExtension().scheduleClusterVersionAutoUpgrade();
} } | public class class_name {
void updateMembers(MembersView membersView) {
MemberMap currentMemberMap = memberMapRef.get();
Collection<MemberImpl> addedMembers = new LinkedList<>();
Collection<MemberImpl> removedMembers = new LinkedList<>();
ClusterHeartbeatManager clusterHeartbeatManager = clusterService.getClusterHeartbeatManager();
MemberImpl[] members = new MemberImpl[membersView.size()];
int memberIndex = 0;
for (MemberInfo memberInfo : membersView.getMembers()) {
Address address = memberInfo.getAddress();
MemberImpl member = currentMemberMap.getMember(address);
if (member != null && member.getUuid().equals(memberInfo.getUuid())) {
member = createNewMemberImplIfChanged(memberInfo, member); // depends on control dependency: [if], data = [(member]
members[memberIndex++] = member; // depends on control dependency: [if], data = [none]
continue;
}
if (member != null) {
assert !(member.localMember() && member.equals(clusterService.getLocalMember()))
: "Local " + member + " cannot be replaced with " + memberInfo; // depends on control dependency: [if], data = [(member]
// UUID changed: means member has gone and come back with a new uuid
removedMembers.add(member); // depends on control dependency: [if], data = [(member]
}
member = createMember(memberInfo, memberInfo.getAttributes()); // depends on control dependency: [for], data = [memberInfo]
addedMembers.add(member); // depends on control dependency: [for], data = [none]
long now = clusterService.getClusterTime();
clusterHeartbeatManager.onHeartbeat(member, now); // depends on control dependency: [for], data = [none]
repairPartitionTableIfReturningMember(member); // depends on control dependency: [for], data = [none]
members[memberIndex++] = member; // depends on control dependency: [for], data = [none]
}
MemberMap newMemberMap = membersView.toMemberMap();
for (MemberImpl member : currentMemberMap.getMembers()) {
if (!newMemberMap.contains(member.getAddress())) {
removedMembers.add(member); // depends on control dependency: [if], data = [none]
}
}
setMembers(MemberMap.createNew(membersView.getVersion(), members));
for (MemberImpl member : removedMembers) {
closeConnection(member.getAddress(), "Member left event received from master"); // depends on control dependency: [for], data = [member]
handleMemberRemove(memberMapRef.get(), member); // depends on control dependency: [for], data = [member]
}
clusterService.getClusterJoinManager().insertIntoRecentlyJoinedMemberSet(addedMembers);
sendMembershipEvents(currentMemberMap.getMembers(), addedMembers);
removeFromMissingMembers(members);
clusterHeartbeatManager.heartbeat();
clusterService.printMemberList();
//async call
node.getNodeExtension().scheduleClusterVersionAutoUpgrade();
} } |
public class class_name {
public static Serializable getBeanFieldValue(IDeepType entity, Field deepField) {
try {
return (Serializable) PropertyUtils.getProperty(entity, deepField.getName());
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) {
throw new DeepIOException(e1);
}
} } | public class class_name {
public static Serializable getBeanFieldValue(IDeepType entity, Field deepField) {
try {
return (Serializable) PropertyUtils.getProperty(entity, deepField.getName()); // depends on control dependency: [try], data = [none]
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) {
throw new DeepIOException(e1);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void setIcon(IconRow iconRow, GeometryType geometryType) {
if (geometryType != null) {
if (iconRow != null) {
icons.put(geometryType, iconRow);
} else {
icons.remove(geometryType);
}
} else {
defaultIcon = iconRow;
}
} } | public class class_name {
public void setIcon(IconRow iconRow, GeometryType geometryType) {
if (geometryType != null) {
if (iconRow != null) {
icons.put(geometryType, iconRow); // depends on control dependency: [if], data = [none]
} else {
icons.remove(geometryType); // depends on control dependency: [if], data = [none]
}
} else {
defaultIcon = iconRow; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private Map<TemplateType, JSType> evaluateTypeTransformations(
ImmutableList<TemplateType> templateTypes,
Map<TemplateType, JSType> inferredTypes,
FlowScope scope) {
Map<String, JSType> typeVars = null;
Map<TemplateType, JSType> result = null;
TypeTransformation ttlObj = null;
for (TemplateType type : templateTypes) {
if (type.isTypeTransformation()) {
// Lazy initialization when the first type transformation is found
if (ttlObj == null) {
ttlObj = new TypeTransformation(compiler, scope.getDeclarationScope());
typeVars = buildTypeVariables(inferredTypes);
result = new LinkedHashMap<>();
}
// Evaluate the type transformation expression using the current
// known types for the template type variables
JSType transformedType = ttlObj.eval(
type.getTypeTransformation(),
ImmutableMap.copyOf(typeVars));
result.put(type, transformedType);
// Add the transformed type to the type variables
typeVars.put(type.getReferenceName(), transformedType);
}
}
return result;
} } | public class class_name {
private Map<TemplateType, JSType> evaluateTypeTransformations(
ImmutableList<TemplateType> templateTypes,
Map<TemplateType, JSType> inferredTypes,
FlowScope scope) {
Map<String, JSType> typeVars = null;
Map<TemplateType, JSType> result = null;
TypeTransformation ttlObj = null;
for (TemplateType type : templateTypes) {
if (type.isTypeTransformation()) {
// Lazy initialization when the first type transformation is found
if (ttlObj == null) {
ttlObj = new TypeTransformation(compiler, scope.getDeclarationScope()); // depends on control dependency: [if], data = [none]
typeVars = buildTypeVariables(inferredTypes); // depends on control dependency: [if], data = [none]
result = new LinkedHashMap<>(); // depends on control dependency: [if], data = [none]
}
// Evaluate the type transformation expression using the current
// known types for the template type variables
JSType transformedType = ttlObj.eval(
type.getTypeTransformation(),
ImmutableMap.copyOf(typeVars));
result.put(type, transformedType); // depends on control dependency: [if], data = [none]
// Add the transformed type to the type variables
typeVars.put(type.getReferenceName(), transformedType); // depends on control dependency: [if], data = [none]
}
}
return result;
} } |
public class class_name {
int computeMethodInfoSize() {
// If this method_info must be copied from an existing one, the size computation is trivial.
if (sourceOffset != 0) {
// sourceLength excludes the first 6 bytes for access_flags, name_index and descriptor_index.
return 6 + sourceLength;
}
// 2 bytes each for access_flags, name_index, descriptor_index and attributes_count.
int size = 8;
// For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS.
if (code.length > 0) {
if (code.length > 65535) {
throw new IndexOutOfBoundsException("Method code too large!");
}
symbolTable.addConstantUtf8(Constants.CODE);
// The Code attribute has 6 header bytes, plus 2, 2, 4 and 2 bytes respectively for max_stack,
// max_locals, code_length and attributes_count, plus the bytecode and the exception table.
size += 16 + code.length + Handler.getExceptionTableSize(firstHandler);
if (stackMapTableEntries != null) {
boolean useStackMapTable = symbolTable.getMajorVersion() >= Opcodes.V1_6;
symbolTable.addConstantUtf8(useStackMapTable ? Constants.STACK_MAP_TABLE : "StackMap");
// 6 header bytes and 2 bytes for number_of_entries.
size += 8 + stackMapTableEntries.length;
}
if (lineNumberTable != null) {
symbolTable.addConstantUtf8(Constants.LINE_NUMBER_TABLE);
// 6 header bytes and 2 bytes for line_number_table_length.
size += 8 + lineNumberTable.length;
}
if (localVariableTable != null) {
symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TABLE);
// 6 header bytes and 2 bytes for local_variable_table_length.
size += 8 + localVariableTable.length;
}
if (localVariableTypeTable != null) {
symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TYPE_TABLE);
// 6 header bytes and 2 bytes for local_variable_type_table_length.
size += 8 + localVariableTypeTable.length;
}
if (firstCodeAttribute != null) {
size +=
firstCodeAttribute.computeAttributesSize(
symbolTable, code.data, code.length, maxStack, maxLocals);
}
}
if (numberOfExceptions > 0) {
symbolTable.addConstantUtf8(Constants.EXCEPTIONS);
size += 8 + 2 * numberOfExceptions;
}
boolean useSyntheticAttribute = symbolTable.getMajorVersion() < Opcodes.V1_5;
if ((accessFlags & Opcodes.ACC_SYNTHETIC) != 0 && useSyntheticAttribute) {
symbolTable.addConstantUtf8(Constants.SYNTHETIC);
size += 6;
}
if (signatureIndex != 0) {
symbolTable.addConstantUtf8(Constants.SIGNATURE);
size += 8;
}
if ((accessFlags & Opcodes.ACC_DEPRECATED) != 0) {
symbolTable.addConstantUtf8(Constants.DEPRECATED);
size += 6;
}
if (defaultValue != null) {
symbolTable.addConstantUtf8(Constants.ANNOTATION_DEFAULT);
size += 6 + defaultValue.length;
}
if (parameters != null) {
symbolTable.addConstantUtf8(Constants.METHOD_PARAMETERS);
// 6 header bytes and 1 byte for parameters_count.
size += 7 + parameters.length;
}
if (firstAttribute != null) {
size += firstAttribute.computeAttributesSize(symbolTable);
}
return size;
} } | public class class_name {
int computeMethodInfoSize() {
// If this method_info must be copied from an existing one, the size computation is trivial.
if (sourceOffset != 0) {
// sourceLength excludes the first 6 bytes for access_flags, name_index and descriptor_index.
return 6 + sourceLength; // depends on control dependency: [if], data = [none]
}
// 2 bytes each for access_flags, name_index, descriptor_index and attributes_count.
int size = 8;
// For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS.
if (code.length > 0) {
if (code.length > 65535) {
throw new IndexOutOfBoundsException("Method code too large!");
}
symbolTable.addConstantUtf8(Constants.CODE); // depends on control dependency: [if], data = [none]
// The Code attribute has 6 header bytes, plus 2, 2, 4 and 2 bytes respectively for max_stack,
// max_locals, code_length and attributes_count, plus the bytecode and the exception table.
size += 16 + code.length + Handler.getExceptionTableSize(firstHandler); // depends on control dependency: [if], data = [none]
if (stackMapTableEntries != null) {
boolean useStackMapTable = symbolTable.getMajorVersion() >= Opcodes.V1_6;
symbolTable.addConstantUtf8(useStackMapTable ? Constants.STACK_MAP_TABLE : "StackMap"); // depends on control dependency: [if], data = [none]
// 6 header bytes and 2 bytes for number_of_entries.
size += 8 + stackMapTableEntries.length; // depends on control dependency: [if], data = [none]
}
if (lineNumberTable != null) {
symbolTable.addConstantUtf8(Constants.LINE_NUMBER_TABLE); // depends on control dependency: [if], data = [none]
// 6 header bytes and 2 bytes for line_number_table_length.
size += 8 + lineNumberTable.length; // depends on control dependency: [if], data = [none]
}
if (localVariableTable != null) {
symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TABLE); // depends on control dependency: [if], data = [none]
// 6 header bytes and 2 bytes for local_variable_table_length.
size += 8 + localVariableTable.length; // depends on control dependency: [if], data = [none]
}
if (localVariableTypeTable != null) {
symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TYPE_TABLE); // depends on control dependency: [if], data = [none]
// 6 header bytes and 2 bytes for local_variable_type_table_length.
size += 8 + localVariableTypeTable.length; // depends on control dependency: [if], data = [none]
}
if (firstCodeAttribute != null) {
size +=
firstCodeAttribute.computeAttributesSize(
symbolTable, code.data, code.length, maxStack, maxLocals); // depends on control dependency: [if], data = [none]
}
}
if (numberOfExceptions > 0) {
symbolTable.addConstantUtf8(Constants.EXCEPTIONS); // depends on control dependency: [if], data = [none]
size += 8 + 2 * numberOfExceptions; // depends on control dependency: [if], data = [none]
}
boolean useSyntheticAttribute = symbolTable.getMajorVersion() < Opcodes.V1_5;
if ((accessFlags & Opcodes.ACC_SYNTHETIC) != 0 && useSyntheticAttribute) {
symbolTable.addConstantUtf8(Constants.SYNTHETIC); // depends on control dependency: [if], data = [none]
size += 6; // depends on control dependency: [if], data = [none]
}
if (signatureIndex != 0) {
symbolTable.addConstantUtf8(Constants.SIGNATURE); // depends on control dependency: [if], data = [none]
size += 8; // depends on control dependency: [if], data = [none]
}
if ((accessFlags & Opcodes.ACC_DEPRECATED) != 0) {
symbolTable.addConstantUtf8(Constants.DEPRECATED); // depends on control dependency: [if], data = [none]
size += 6; // depends on control dependency: [if], data = [none]
}
if (defaultValue != null) {
symbolTable.addConstantUtf8(Constants.ANNOTATION_DEFAULT); // depends on control dependency: [if], data = [none]
size += 6 + defaultValue.length; // depends on control dependency: [if], data = [none]
}
if (parameters != null) {
symbolTable.addConstantUtf8(Constants.METHOD_PARAMETERS); // depends on control dependency: [if], data = [none]
// 6 header bytes and 1 byte for parameters_count.
size += 7 + parameters.length; // depends on control dependency: [if], data = [none]
}
if (firstAttribute != null) {
size += firstAttribute.computeAttributesSize(symbolTable); // depends on control dependency: [if], data = [none]
}
return size;
} } |
public class class_name {
@Override
public void onRefreshed(BoxAuthentication.BoxAuthenticationInfo info) {
if (sameUser(info)) {
BoxAuthentication.BoxAuthenticationInfo.cloneInfo(mAuthInfo, info);
if (sessionAuthListener != null) {
sessionAuthListener.onRefreshed(info);
}
}
} } | public class class_name {
@Override
public void onRefreshed(BoxAuthentication.BoxAuthenticationInfo info) {
if (sameUser(info)) {
BoxAuthentication.BoxAuthenticationInfo.cloneInfo(mAuthInfo, info); // depends on control dependency: [if], data = [none]
if (sessionAuthListener != null) {
sessionAuthListener.onRefreshed(info); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
protected <T> T instantiateClass(Class<T> clazz) throws Throwable {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "instantiateClass", clazz);
}
T object = null;
try {
object = clazz.newInstance();
} catch (Throwable e) {
Tr.error(tc, BVNLSConstants.BVKEY_CLASS_NOT_FOUND, new Object[] { ivBVContext.getPath(), clazz, e });
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Unable to create a ValidationFactory because of ", e);
}
throw e;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "instantiateClass", object);
}
return object;
} } | public class class_name {
protected <T> T instantiateClass(Class<T> clazz) throws Throwable {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "instantiateClass", clazz);
}
T object = null;
try {
object = clazz.newInstance();
} catch (Throwable e) {
Tr.error(tc, BVNLSConstants.BVKEY_CLASS_NOT_FOUND, new Object[] { ivBVContext.getPath(), clazz, e });
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Unable to create a ValidationFactory because of ", e); // depends on control dependency: [if], data = [none]
}
throw e;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "instantiateClass", object);
}
return object;
} } |
public class class_name {
public void marshall(BackupSelection backupSelection, ProtocolMarshaller protocolMarshaller) {
if (backupSelection == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(backupSelection.getSelectionName(), SELECTIONNAME_BINDING);
protocolMarshaller.marshall(backupSelection.getIamRoleArn(), IAMROLEARN_BINDING);
protocolMarshaller.marshall(backupSelection.getResources(), RESOURCES_BINDING);
protocolMarshaller.marshall(backupSelection.getListOfTags(), LISTOFTAGS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(BackupSelection backupSelection, ProtocolMarshaller protocolMarshaller) {
if (backupSelection == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(backupSelection.getSelectionName(), SELECTIONNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(backupSelection.getIamRoleArn(), IAMROLEARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(backupSelection.getResources(), RESOURCES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(backupSelection.getListOfTags(), LISTOFTAGS_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 SgClass create(final SgClassPool pool, final String className) {
if (pool == null) {
throw new IllegalArgumentException("The argument 'pool' cannot be null!");
}
if (className == null) {
throw new IllegalArgumentException("The argument 'className' cannot be null!");
}
final SgClass cached = pool.get(className);
if (cached != null) {
return cached;
}
try {
return create(pool, Class.forName(className));
} catch (final ClassNotFoundException e) {
throw new IllegalArgumentException("Cannot create '" + className + "'!", e);
}
} } | public class class_name {
public static SgClass create(final SgClassPool pool, final String className) {
if (pool == null) {
throw new IllegalArgumentException("The argument 'pool' cannot be null!");
}
if (className == null) {
throw new IllegalArgumentException("The argument 'className' cannot be null!");
}
final SgClass cached = pool.get(className);
if (cached != null) {
return cached;
// depends on control dependency: [if], data = [none]
}
try {
return create(pool, Class.forName(className));
// depends on control dependency: [try], data = [none]
} catch (final ClassNotFoundException e) {
throw new IllegalArgumentException("Cannot create '" + className + "'!", e);
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void remove(EJSHome home)
{
List<BeanO> removedBeans = new ArrayList<BeanO>();
// Clear out any entries eligible for garbage collection and then
// loop through the remaining entries, looking for values that belong
// to the specified home and remove them. This will hold the cache
// lock for longer than normal, but it is not expected that
// applications will be stopped very often.
synchronized (ivCache)
{
poll();
for (Iterator<Map.Entry<WeakReference<EJSWrapperBase>, BeanO>> it = ivCache.entrySet().iterator(); it.hasNext();)
{
BeanO bean = it.next().getValue();
if (bean.home == home)
{
it.remove(); // d730739
removedBeans.add(bean);
}
}
}
// Now that the cache lock has been dropped, go ahead and destroy
// all of the beans that were removed.
for (BeanO bean : removedBeans)
{
bean.destroy();
}
} } | public class class_name {
public void remove(EJSHome home)
{
List<BeanO> removedBeans = new ArrayList<BeanO>();
// Clear out any entries eligible for garbage collection and then
// loop through the remaining entries, looking for values that belong
// to the specified home and remove them. This will hold the cache
// lock for longer than normal, but it is not expected that
// applications will be stopped very often.
synchronized (ivCache)
{
poll();
for (Iterator<Map.Entry<WeakReference<EJSWrapperBase>, BeanO>> it = ivCache.entrySet().iterator(); it.hasNext();)
{
BeanO bean = it.next().getValue();
if (bean.home == home)
{
it.remove(); // d730739 // depends on control dependency: [if], data = [none]
removedBeans.add(bean); // depends on control dependency: [if], data = [none]
}
}
}
// Now that the cache lock has been dropped, go ahead and destroy
// all of the beans that were removed.
for (BeanO bean : removedBeans)
{
bean.destroy(); // depends on control dependency: [for], data = [bean]
}
} } |
public class class_name {
public ACE[] getSecurity(boolean resolveSids) throws IOException {
int f;
ACE[] aces;
f = open0( O_RDONLY, READ_CONTROL, 0, isDirectory() ? 1 : 0 );
/*
* NtTrans Query Security Desc Request / Response
*/
NtTransQuerySecurityDesc request = new NtTransQuerySecurityDesc( f, 0x04 );
NtTransQuerySecurityDescResponse response = new NtTransQuerySecurityDescResponse();
try {
send( request, response );
aces = response.securityDescriptor.aces;
if (aces != null)
processAces(aces, resolveSids);
} finally {
try {
close( f, 0L );
} catch(SmbException se) {
if (log.level >= 1)
se.printStackTrace(log);
}
}
return aces;
} } | public class class_name {
public ACE[] getSecurity(boolean resolveSids) throws IOException {
int f;
ACE[] aces;
f = open0( O_RDONLY, READ_CONTROL, 0, isDirectory() ? 1 : 0 );
/*
* NtTrans Query Security Desc Request / Response
*/
NtTransQuerySecurityDesc request = new NtTransQuerySecurityDesc( f, 0x04 );
NtTransQuerySecurityDescResponse response = new NtTransQuerySecurityDescResponse();
try {
send( request, response );
aces = response.securityDescriptor.aces;
if (aces != null)
processAces(aces, resolveSids);
} finally {
try {
close( f, 0L ); // depends on control dependency: [try], data = [none]
} catch(SmbException se) {
if (log.level >= 1)
se.printStackTrace(log);
} // depends on control dependency: [catch], data = [none]
}
return aces;
} } |
public class class_name {
public T validateScript(Resource scriptResource, Charset charset) {
try {
validateScript(FileUtils.readToString(scriptResource, charset));
} catch (IOException e) {
throw new CitrusRuntimeException("Failed to read script resource file", e);
}
return self;
} } | public class class_name {
public T validateScript(Resource scriptResource, Charset charset) {
try {
validateScript(FileUtils.readToString(scriptResource, charset)); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new CitrusRuntimeException("Failed to read script resource file", e);
} // depends on control dependency: [catch], data = [none]
return self;
} } |
public class class_name {
public static void checkJavaInternalAccess(ILogger logger) {
if (logger == null || !JavaVersion.isAtLeast(JavaVersion.JAVA_9)) {
// older Java versions are fine with the reflection
return;
}
Map<String, PackageAccessRequirement[]> requirements = new TreeMap<String, PackageAccessRequirement[]>();
requirements.put("java.base",
new PackageAccessRequirement[] {
createRequirement(false, "jdk.internal.ref"),
createRequirement(true, "java.lang"),
createRequirement(true, "java.nio"),
createRequirement(true, "sun.nio.ch")
});
requirements.put("jdk.management", getJdkManagementRequirements());
requirements.put("java.management", new PackageAccessRequirement[] { createRequirement(true, "sun.management") });
checkPackageRequirements(logger, requirements);
} } | public class class_name {
public static void checkJavaInternalAccess(ILogger logger) {
if (logger == null || !JavaVersion.isAtLeast(JavaVersion.JAVA_9)) {
// older Java versions are fine with the reflection
return; // depends on control dependency: [if], data = [none]
}
Map<String, PackageAccessRequirement[]> requirements = new TreeMap<String, PackageAccessRequirement[]>();
requirements.put("java.base",
new PackageAccessRequirement[] {
createRequirement(false, "jdk.internal.ref"),
createRequirement(true, "java.lang"),
createRequirement(true, "java.nio"),
createRequirement(true, "sun.nio.ch")
});
requirements.put("jdk.management", getJdkManagementRequirements());
requirements.put("java.management", new PackageAccessRequirement[] { createRequirement(true, "sun.management") });
checkPackageRequirements(logger, requirements);
} } |
public class class_name {
@PublicEvolving
public boolean shouldAutocastTo(BasicTypeInfo<?> to) {
for (Class<?> possibleTo: possibleCastTargetTypes) {
if (possibleTo.equals(to.getTypeClass())) {
return true;
}
}
return false;
} } | public class class_name {
@PublicEvolving
public boolean shouldAutocastTo(BasicTypeInfo<?> to) {
for (Class<?> possibleTo: possibleCastTargetTypes) {
if (possibleTo.equals(to.getTypeClass())) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
public static String getText(final Node root) {
if (root == null) {
return "";
} else {
final StringBuilder result = new StringBuilder(1024);
if (root.hasChildNodes()) {
final NodeList list = root.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
final Node childNode = list.item(i);
if (childNode.getNodeType() == Node.ELEMENT_NODE) {
final Element e = (Element) childNode;
final String value = e.getAttribute(ATTRIBUTE_NAME_CLASS);
if (!excludeList.contains(value)) {
final String s = getText(e);
result.append(s);
}
} else if (childNode.getNodeType() == Node.TEXT_NODE) {
result.append(childNode.getNodeValue());
}
}
} else if (root.getNodeType() == Node.TEXT_NODE) {
result.append(root.getNodeValue());
}
return result.toString();
}
} } | public class class_name {
public static String getText(final Node root) {
if (root == null) {
return ""; // depends on control dependency: [if], data = [none]
} else {
final StringBuilder result = new StringBuilder(1024);
if (root.hasChildNodes()) {
final NodeList list = root.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
final Node childNode = list.item(i);
if (childNode.getNodeType() == Node.ELEMENT_NODE) {
final Element e = (Element) childNode;
final String value = e.getAttribute(ATTRIBUTE_NAME_CLASS);
if (!excludeList.contains(value)) {
final String s = getText(e);
result.append(s); // depends on control dependency: [if], data = [none]
}
} else if (childNode.getNodeType() == Node.TEXT_NODE) {
result.append(childNode.getNodeValue()); // depends on control dependency: [if], data = [none]
}
}
} else if (root.getNodeType() == Node.TEXT_NODE) {
result.append(root.getNodeValue()); // depends on control dependency: [if], data = [none]
}
return result.toString(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public synchronized void close() {
if (isOpen()) {
clearCache();
closeStatements();
try {
connection.close();
} catch (SQLException ex) {
LOGGER.error("There was an error attempting to close the CveDB, see the log for more details.");
LOGGER.debug("", ex);
} catch (Throwable ex) {
LOGGER.error("There was an exception attempting to close the CveDB, see the log for more details.");
LOGGER.debug("", ex);
}
releaseResources();
connectionFactory.cleanup();
}
} } | public class class_name {
@Override
public synchronized void close() {
if (isOpen()) {
clearCache(); // depends on control dependency: [if], data = [none]
closeStatements(); // depends on control dependency: [if], data = [none]
try {
connection.close(); // depends on control dependency: [try], data = [none]
} catch (SQLException ex) {
LOGGER.error("There was an error attempting to close the CveDB, see the log for more details.");
LOGGER.debug("", ex);
} catch (Throwable ex) { // depends on control dependency: [catch], data = [none]
LOGGER.error("There was an exception attempting to close the CveDB, see the log for more details.");
LOGGER.debug("", ex);
} // depends on control dependency: [catch], data = [none]
releaseResources(); // depends on control dependency: [if], data = [none]
connectionFactory.cleanup(); // depends on control dependency: [if], data = [none]
}
} } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.