code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
---|---|
public class class_name {
public String getInfix(String className) {
String postfix = getActionSuffix();
String simpleName = className.substring(className.lastIndexOf('.') + 1);
if (Strings.contains(simpleName, postfix)) {
simpleName = Strings.uncapitalize(simpleName.substring(0, simpleName.length() - postfix.length()));
} else {
simpleName = Strings.uncapitalize(simpleName);
}
MatchInfo match = getCtlMatchInfo(className);
StringBuilder infix = new StringBuilder(match.getReserved().toString());
if (infix.length() > 0) infix.append('.');
String remainder = Strings.substringBeforeLast(className, ".").substring(match.getStartIndex() + 1);
if (remainder.length() > 0) {
if ('.' == remainder.charAt(0)) remainder = remainder.substring(1);
infix.append(remainder).append('.');
}
if (infix.length() == 0) return simpleName;
infix.append(simpleName);
// 将.替换成/
for (int i = 0; i < infix.length(); i++) {
if (infix.charAt(i) == '.') infix.setCharAt(i, '/');
}
return infix.toString();
} } | public class class_name {
public String getInfix(String className) {
String postfix = getActionSuffix();
String simpleName = className.substring(className.lastIndexOf('.') + 1);
if (Strings.contains(simpleName, postfix)) {
simpleName = Strings.uncapitalize(simpleName.substring(0, simpleName.length() - postfix.length())); // depends on control dependency: [if], data = [none]
} else {
simpleName = Strings.uncapitalize(simpleName); // depends on control dependency: [if], data = [none]
}
MatchInfo match = getCtlMatchInfo(className);
StringBuilder infix = new StringBuilder(match.getReserved().toString());
if (infix.length() > 0) infix.append('.');
String remainder = Strings.substringBeforeLast(className, ".").substring(match.getStartIndex() + 1);
if (remainder.length() > 0) {
if ('.' == remainder.charAt(0)) remainder = remainder.substring(1);
infix.append(remainder).append('.'); // depends on control dependency: [if], data = [none]
}
if (infix.length() == 0) return simpleName;
infix.append(simpleName);
// 将.替换成/
for (int i = 0; i < infix.length(); i++) {
if (infix.charAt(i) == '.') infix.setCharAt(i, '/');
}
return infix.toString();
} } |
public class class_name {
public void marshall(UserPendingChanges userPendingChanges, ProtocolMarshaller protocolMarshaller) {
if (userPendingChanges == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(userPendingChanges.getConsoleAccess(), CONSOLEACCESS_BINDING);
protocolMarshaller.marshall(userPendingChanges.getGroups(), GROUPS_BINDING);
protocolMarshaller.marshall(userPendingChanges.getPendingChange(), PENDINGCHANGE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(UserPendingChanges userPendingChanges, ProtocolMarshaller protocolMarshaller) {
if (userPendingChanges == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(userPendingChanges.getConsoleAccess(), CONSOLEACCESS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(userPendingChanges.getGroups(), GROUPS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(userPendingChanges.getPendingChange(), PENDINGCHANGE_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private Object convertByteArrayToNumber(byte[] mass) {
double resultDouble = bytesToDouble(mass);
if (Double.isNaN(resultDouble) || (resultDouble < NAN_EPSILON && resultDouble > 0)) {
return null;
}
long resultLong = Math.round(resultDouble);
if (Math.abs(resultDouble - resultLong) >= EPSILON) {
return resultDouble;
} else {
return resultLong;
}
} } | public class class_name {
private Object convertByteArrayToNumber(byte[] mass) {
double resultDouble = bytesToDouble(mass);
if (Double.isNaN(resultDouble) || (resultDouble < NAN_EPSILON && resultDouble > 0)) {
return null; // depends on control dependency: [if], data = [none]
}
long resultLong = Math.round(resultDouble);
if (Math.abs(resultDouble - resultLong) >= EPSILON) {
return resultDouble; // depends on control dependency: [if], data = [none]
} else {
return resultLong; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static void shiftUp( Polygon2D_F64 a ) {
final int N = a.size();
Point2D_F64 first = a.get(0);
for (int i = 0; i < N-1; i++ ) {
a.vertexes.data[i] = a.vertexes.data[i+1];
}
a.vertexes.data[N-1] = first;
} } | public class class_name {
public static void shiftUp( Polygon2D_F64 a ) {
final int N = a.size();
Point2D_F64 first = a.get(0);
for (int i = 0; i < N-1; i++ ) {
a.vertexes.data[i] = a.vertexes.data[i+1]; // depends on control dependency: [for], data = [i]
}
a.vertexes.data[N-1] = first;
} } |
public class class_name {
public void build() throws SAXException {
// reorganize qualifying components by their namespaces to
// generate the list nicely
final Map<XSSchema, PerSchemaOutlineAdaptors> perSchema = new LinkedHashMap<>();
boolean hasComponentInNoNamespace = false;
for (final OutlineAdaptor oa : this.outlines) {
final XSComponent sc = oa.schemaComponent;
if (sc != null && (sc instanceof XSDeclaration)) {
final XSDeclaration decl = (XSDeclaration) sc;
if (!decl.isLocal()) { // local components cannot be referenced from outside, so no need to list.
PerSchemaOutlineAdaptors list = perSchema.get(decl.getOwnerSchema());
if (list == null) {
list = new PerSchemaOutlineAdaptors();
perSchema.put(decl.getOwnerSchema(), list);
}
list.add(oa);
if ("".equals(decl.getTargetNamespace()))
hasComponentInNoNamespace = true;
}
}
}
//final File episodeFile = new File(opt.targetDir, this.episodePackageName.replaceAll("\\.", "/") + "/" + this.episodeFileName);
try (final StringWriter stringWriter = new StringWriter()) {
final Bindings bindings = TXW.create(Bindings.class, new StreamSerializer(stringWriter));
if (hasComponentInNoNamespace) // otherwise jaxb binding NS should be the default namespace
bindings._namespace(Const.JAXB_NSURI, "jaxb");
else
bindings._namespace(Const.JAXB_NSURI, "");
bindings._namespace(Namespaces.KSCS_BINDINGS_NS, "kscs");
bindings.version("2.1");
bindings._comment("\n\n" + this.pluginContext.opt.getPrologComment() + "\n ");
// generate listing per schema
for (final Map.Entry<XSSchema, PerSchemaOutlineAdaptors> e : perSchema.entrySet()) {
final PerSchemaOutlineAdaptors ps = e.getValue();
final Bindings group = bindings.bindings();
final String tns = e.getKey().getTargetNamespace();
if (Namespaces.XML_NS.equals(tns)) {
group._namespace(tns, "xml");
} else if (!"".equals(tns)) {
group._namespace(tns, "tns");
}
group.scd("x-schema::" + ("".equals(tns) ? "" : (Namespaces.XML_NS.equals(tns) ? "xml" : "tns")));
group._attribute("if-exists", "true");
final SchemaBindings schemaBindings = group.schemaBindings();
schemaBindings.map(false);
if (ps.packageNames.size() == 1) {
final String packageName = ps.packageNames.iterator().next();
if (packageName != null && packageName.length() > 0) {
schemaBindings._package().name(packageName);
}
}
for (final OutlineAdaptor oa : ps.outlineAdaptors) {
final Bindings child = group.bindings();
oa.buildBindings(child);
}
group.commit(true);
}
bindings.commit();
final JTextFile jTextFile = new JTextFile(this.episodeFileName);
jTextFile.setContents(stringWriter.toString());
this.pluginContext.codeModel.rootPackage().addResourceFile(jTextFile);
} catch (final IOException e) {
this.pluginContext.errorHandler.error(new SAXParseException("Failed to write to " + this.episodeFileName, null, e));
}
} } | public class class_name {
public void build() throws SAXException {
// reorganize qualifying components by their namespaces to
// generate the list nicely
final Map<XSSchema, PerSchemaOutlineAdaptors> perSchema = new LinkedHashMap<>();
boolean hasComponentInNoNamespace = false;
for (final OutlineAdaptor oa : this.outlines) {
final XSComponent sc = oa.schemaComponent;
if (sc != null && (sc instanceof XSDeclaration)) {
final XSDeclaration decl = (XSDeclaration) sc;
if (!decl.isLocal()) { // local components cannot be referenced from outside, so no need to list.
PerSchemaOutlineAdaptors list = perSchema.get(decl.getOwnerSchema());
if (list == null) {
list = new PerSchemaOutlineAdaptors(); // depends on control dependency: [if], data = [none]
perSchema.put(decl.getOwnerSchema(), list); // depends on control dependency: [if], data = [none]
}
list.add(oa); // depends on control dependency: [if], data = [none]
if ("".equals(decl.getTargetNamespace()))
hasComponentInNoNamespace = true;
}
}
}
//final File episodeFile = new File(opt.targetDir, this.episodePackageName.replaceAll("\\.", "/") + "/" + this.episodeFileName);
try (final StringWriter stringWriter = new StringWriter()) {
final Bindings bindings = TXW.create(Bindings.class, new StreamSerializer(stringWriter));
if (hasComponentInNoNamespace) // otherwise jaxb binding NS should be the default namespace
bindings._namespace(Const.JAXB_NSURI, "jaxb");
else
bindings._namespace(Const.JAXB_NSURI, "");
bindings._namespace(Namespaces.KSCS_BINDINGS_NS, "kscs");
bindings.version("2.1");
bindings._comment("\n\n" + this.pluginContext.opt.getPrologComment() + "\n ");
// generate listing per schema
for (final Map.Entry<XSSchema, PerSchemaOutlineAdaptors> e : perSchema.entrySet()) {
final PerSchemaOutlineAdaptors ps = e.getValue();
final Bindings group = bindings.bindings();
final String tns = e.getKey().getTargetNamespace();
if (Namespaces.XML_NS.equals(tns)) {
group._namespace(tns, "xml"); // depends on control dependency: [if], data = [none]
} else if (!"".equals(tns)) {
group._namespace(tns, "tns"); // depends on control dependency: [if], data = [none]
}
group.scd("x-schema::" + ("".equals(tns) ? "" : (Namespaces.XML_NS.equals(tns) ? "xml" : "tns"))); // depends on control dependency: [for], data = [e]
group._attribute("if-exists", "true"); // depends on control dependency: [for], data = [e]
final SchemaBindings schemaBindings = group.schemaBindings();
schemaBindings.map(false); // depends on control dependency: [for], data = [e]
if (ps.packageNames.size() == 1) {
final String packageName = ps.packageNames.iterator().next();
if (packageName != null && packageName.length() > 0) {
schemaBindings._package().name(packageName); // depends on control dependency: [if], data = [(packageName]
}
}
for (final OutlineAdaptor oa : ps.outlineAdaptors) {
final Bindings child = group.bindings();
oa.buildBindings(child); // depends on control dependency: [for], data = [oa]
}
group.commit(true); // depends on control dependency: [for], data = [e]
}
bindings.commit();
final JTextFile jTextFile = new JTextFile(this.episodeFileName);
jTextFile.setContents(stringWriter.toString());
this.pluginContext.codeModel.rootPackage().addResourceFile(jTextFile);
} catch (final IOException e) {
this.pluginContext.errorHandler.error(new SAXParseException("Failed to write to " + this.episodeFileName, null, e));
}
} } |
public class class_name {
@Override
public EEnum getIfcRoleEnum() {
if (ifcRoleEnumEEnum == null) {
ifcRoleEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers()
.get(1054);
}
return ifcRoleEnumEEnum;
} } | public class class_name {
@Override
public EEnum getIfcRoleEnum() {
if (ifcRoleEnumEEnum == null) {
ifcRoleEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers()
.get(1054);
// depends on control dependency: [if], data = [none]
}
return ifcRoleEnumEEnum;
} } |
public class class_name {
public ChannelFuture removeAndWriteAll() {
assert ctx.executor().inEventLoop();
if (isEmpty()) {
return null;
}
ChannelPromise p = ctx.newPromise();
PromiseCombiner combiner = new PromiseCombiner(ctx.executor());
try {
// It is possible for some of the written promises to trigger more writes. The new writes
// will "revive" the queue, so we need to write them up until the queue is empty.
for (PendingWrite write = head; write != null; write = head) {
head = tail = null;
size = 0;
bytes = 0;
while (write != null) {
PendingWrite next = write.next;
Object msg = write.msg;
ChannelPromise promise = write.promise;
recycle(write, false);
if (!(promise instanceof VoidChannelPromise)) {
combiner.add(promise);
}
ctx.write(msg, promise);
write = next;
}
}
combiner.finish(p);
} catch (Throwable cause) {
p.setFailure(cause);
}
assertEmpty();
return p;
} } | public class class_name {
public ChannelFuture removeAndWriteAll() {
assert ctx.executor().inEventLoop();
if (isEmpty()) {
return null; // depends on control dependency: [if], data = [none]
}
ChannelPromise p = ctx.newPromise();
PromiseCombiner combiner = new PromiseCombiner(ctx.executor());
try {
// It is possible for some of the written promises to trigger more writes. The new writes
// will "revive" the queue, so we need to write them up until the queue is empty.
for (PendingWrite write = head; write != null; write = head) {
head = tail = null; // depends on control dependency: [for], data = [none]
size = 0; // depends on control dependency: [for], data = [none]
bytes = 0; // depends on control dependency: [for], data = [none]
while (write != null) {
PendingWrite next = write.next;
Object msg = write.msg;
ChannelPromise promise = write.promise;
recycle(write, false); // depends on control dependency: [while], data = [(write]
if (!(promise instanceof VoidChannelPromise)) {
combiner.add(promise); // depends on control dependency: [if], data = [none]
}
ctx.write(msg, promise); // depends on control dependency: [while], data = [none]
write = next; // depends on control dependency: [while], data = [none]
}
}
combiner.finish(p); // depends on control dependency: [try], data = [none]
} catch (Throwable cause) {
p.setFailure(cause);
} // depends on control dependency: [catch], data = [none]
assertEmpty();
return p;
} } |
public class class_name {
private static AspectranWebService create(ServletContext servletContext, String aspectranConfigParam) {
AspectranConfig aspectranConfig;
if (aspectranConfigParam != null) {
try {
aspectranConfig = new AspectranConfig(aspectranConfigParam);
} catch (AponParseException e) {
throw new AspectranServiceException("Error parsing '" + ASPECTRAN_CONFIG_PARAM +
"' initialization parameter for Aspectran Configuration", e);
}
} else {
aspectranConfig = new AspectranConfig();
}
ContextConfig contextConfig = aspectranConfig.touchContextConfig();
String rootFile = contextConfig.getRootFile();
if (!StringUtils.hasText(rootFile) && !contextConfig.hasAspectranParameters()) {
contextConfig.setRootFile(DEFAULT_APP_CONFIG_ROOT_FILE);
}
AspectranWebService service = new AspectranWebService(servletContext);
service.prepare(aspectranConfig);
service.setDefaultServletHttpRequestHandler(servletContext);
WebConfig webConfig = aspectranConfig.getWebConfig();
if (webConfig != null) {
applyWebConfig(service, webConfig);
}
setServiceStateListener(service);
return service;
} } | public class class_name {
private static AspectranWebService create(ServletContext servletContext, String aspectranConfigParam) {
AspectranConfig aspectranConfig;
if (aspectranConfigParam != null) {
try {
aspectranConfig = new AspectranConfig(aspectranConfigParam); // depends on control dependency: [try], data = [none]
} catch (AponParseException e) {
throw new AspectranServiceException("Error parsing '" + ASPECTRAN_CONFIG_PARAM +
"' initialization parameter for Aspectran Configuration", e);
} // depends on control dependency: [catch], data = [none]
} else {
aspectranConfig = new AspectranConfig(); // depends on control dependency: [if], data = [none]
}
ContextConfig contextConfig = aspectranConfig.touchContextConfig();
String rootFile = contextConfig.getRootFile();
if (!StringUtils.hasText(rootFile) && !contextConfig.hasAspectranParameters()) {
contextConfig.setRootFile(DEFAULT_APP_CONFIG_ROOT_FILE); // depends on control dependency: [if], data = [none]
}
AspectranWebService service = new AspectranWebService(servletContext);
service.prepare(aspectranConfig);
service.setDefaultServletHttpRequestHandler(servletContext);
WebConfig webConfig = aspectranConfig.getWebConfig();
if (webConfig != null) {
applyWebConfig(service, webConfig); // depends on control dependency: [if], data = [none]
}
setServiceStateListener(service);
return service;
} } |
public class class_name {
public final void release(TotalOrderRemoteTransactionState state) {
TotalOrderLatch synchronizedBlock = state.getTransactionSynchronizedBlock();
if (synchronizedBlock == null) {
//already released!
return;
}
Collection<Object> lockedKeys = state.getLockedKeys();
synchronizedBlock.unBlock();
for (Object key : lockedKeys) {
keysLocked.remove(key, synchronizedBlock);
}
if (trace) {
log.tracef("Release %s and locked keys %s. Checking pending tasks!", synchronizedBlock, lockedKeys);
}
state.reset();
} } | public class class_name {
public final void release(TotalOrderRemoteTransactionState state) {
TotalOrderLatch synchronizedBlock = state.getTransactionSynchronizedBlock();
if (synchronizedBlock == null) {
//already released!
return; // depends on control dependency: [if], data = [none]
}
Collection<Object> lockedKeys = state.getLockedKeys();
synchronizedBlock.unBlock();
for (Object key : lockedKeys) {
keysLocked.remove(key, synchronizedBlock); // depends on control dependency: [for], data = [key]
}
if (trace) {
log.tracef("Release %s and locked keys %s. Checking pending tasks!", synchronizedBlock, lockedKeys); // depends on control dependency: [if], data = [none]
}
state.reset();
} } |
public class class_name {
public void addTypeListener(String typeName, HollowTypeStateListener listener) {
List<HollowTypeStateListener> list = listeners.get(typeName);
if(list == null) {
list = new ArrayList<HollowTypeStateListener>();
listeners.put(typeName, list);
}
list.add(listener);
HollowTypeReadState typeState = typeStates.get(typeName);
if(typeState != null)
typeState.addListener(listener);
} } | public class class_name {
public void addTypeListener(String typeName, HollowTypeStateListener listener) {
List<HollowTypeStateListener> list = listeners.get(typeName);
if(list == null) {
list = new ArrayList<HollowTypeStateListener>(); // depends on control dependency: [if], data = [none]
listeners.put(typeName, list); // depends on control dependency: [if], data = [none]
}
list.add(listener);
HollowTypeReadState typeState = typeStates.get(typeName);
if(typeState != null)
typeState.addListener(listener);
} } |
public class class_name {
public void registerJavaPropertyNameProcessor( Class target, PropertyNameProcessor propertyNameProcessor ) {
if( target != null && propertyNameProcessor != null ) {
javaPropertyNameProcessorMap.put( target, propertyNameProcessor );
}
} } | public class class_name {
public void registerJavaPropertyNameProcessor( Class target, PropertyNameProcessor propertyNameProcessor ) {
if( target != null && propertyNameProcessor != null ) {
javaPropertyNameProcessorMap.put( target, propertyNameProcessor ); // depends on control dependency: [if], data = [( target]
}
} } |
public class class_name {
public static Method getSetter(Class<?> clazz, String fieldName) {
StringBuilder sb = new StringBuilder("set").append(
Character.toUpperCase(fieldName.charAt(0))).append(fieldName,
1, fieldName.length());
final String internedName = sb.toString().intern();
return traverseHierarchy(clazz, new TraverseTask<Method>() {
@Override
public Method run(Class<?> clazz) {
Method[] methods = clazz.getDeclaredMethods();
Method res = null;
for (int i = 0; i < methods.length; i++) {
Method m = methods[i];
if (isSetterSignature(m)) {
if (m.getName() == internedName
&& (res == null
|| res.getParameterTypes()[0].isAssignableFrom(m.getParameterTypes()[0]))) {
res = m;
}
}
}
return res;
}
});
} } | public class class_name {
public static Method getSetter(Class<?> clazz, String fieldName) {
StringBuilder sb = new StringBuilder("set").append(
Character.toUpperCase(fieldName.charAt(0))).append(fieldName,
1, fieldName.length());
final String internedName = sb.toString().intern();
return traverseHierarchy(clazz, new TraverseTask<Method>() {
@Override
public Method run(Class<?> clazz) {
Method[] methods = clazz.getDeclaredMethods();
Method res = null;
for (int i = 0; i < methods.length; i++) {
Method m = methods[i];
if (isSetterSignature(m)) {
if (m.getName() == internedName
&& (res == null
|| res.getParameterTypes()[0].isAssignableFrom(m.getParameterTypes()[0]))) {
res = m; // depends on control dependency: [if], data = [none]
}
}
}
return res;
}
});
} } |
public class class_name {
public java.util.List<String> getCommandIds() {
if (commandIds == null) {
commandIds = new com.amazonaws.internal.SdkInternalList<String>();
}
return commandIds;
} } | public class class_name {
public java.util.List<String> getCommandIds() {
if (commandIds == null) {
commandIds = new com.amazonaws.internal.SdkInternalList<String>(); // depends on control dependency: [if], data = [none]
}
return commandIds;
} } |
public class class_name {
private boolean verifyHostName(String hostName, String pattern) {
// Basic sanity checks
// Check length == 0 instead of .isEmpty() to support Java 5.
if ((hostName == null) || (hostName.length() == 0) || (hostName.startsWith("."))
|| (hostName.endsWith(".."))) {
// Invalid domain name
return false;
}
if ((pattern == null) || (pattern.length() == 0) || (pattern.startsWith("."))
|| (pattern.endsWith(".."))) {
// Invalid pattern/domain name
return false;
}
// Normalize hostName and pattern by turning them into absolute domain names if they are not
// yet absolute. This is needed because server certificates do not normally contain absolute
// names or patterns, but they should be treated as absolute. At the same time, any hostName
// presented to this method should also be treated as absolute for the purposes of matching
// to the server certificate.
// www.android.com matches www.android.com
// www.android.com matches www.android.com.
// www.android.com. matches www.android.com.
// www.android.com. matches www.android.com
if (!hostName.endsWith(".")) {
hostName += '.';
}
if (!pattern.endsWith(".")) {
pattern += '.';
}
// hostName and pattern are now absolute domain names.
pattern = pattern.toLowerCase(Locale.US);
// hostName and pattern are now in lower case -- domain names are case-insensitive.
if (!pattern.contains("*")) {
// Not a wildcard pattern -- hostName and pattern must match exactly.
return hostName.equals(pattern);
}
// Wildcard pattern
// WILDCARD PATTERN RULES:
// 1. Asterisk (*) is only permitted in the left-most domain name label and must be the
// only character in that label (i.e., must match the whole left-most label).
// For example, *.example.com is permitted, while *a.example.com, a*.example.com,
// a*b.example.com, a.*.example.com are not permitted.
// 2. Asterisk (*) cannot match across domain name labels.
// For example, *.example.com matches test.example.com but does not match
// sub.test.example.com.
// 3. Wildcard patterns for single-label domain names are not permitted.
if ((!pattern.startsWith("*.")) || (pattern.indexOf('*', 1) != -1)) {
// Asterisk (*) is only permitted in the left-most domain name label and must be the only
// character in that label
return false;
}
// Optimization: check whether hostName is too short to match the pattern. hostName must be at
// least as long as the pattern because asterisk must match the whole left-most label and
// hostName starts with a non-empty label. Thus, asterisk has to match one or more characters.
if (hostName.length() < pattern.length()) {
// hostName too short to match the pattern.
return false;
}
if ("*.".equals(pattern)) {
// Wildcard pattern for single-label domain name -- not permitted.
return false;
}
// hostName must end with the region of pattern following the asterisk.
String suffix = pattern.substring(1);
if (!hostName.endsWith(suffix)) {
// hostName does not end with the suffix
return false;
}
// Check that asterisk did not match across domain name labels.
int suffixStartIndexInHostName = hostName.length() - suffix.length();
if ((suffixStartIndexInHostName > 0)
&& (hostName.lastIndexOf('.', suffixStartIndexInHostName - 1) != -1)) {
// Asterisk is matching across domain name labels -- not permitted.
return false;
}
// hostName matches pattern
return true;
} } | public class class_name {
private boolean verifyHostName(String hostName, String pattern) {
// Basic sanity checks
// Check length == 0 instead of .isEmpty() to support Java 5.
if ((hostName == null) || (hostName.length() == 0) || (hostName.startsWith("."))
|| (hostName.endsWith(".."))) {
// Invalid domain name
return false; // depends on control dependency: [if], data = [none]
}
if ((pattern == null) || (pattern.length() == 0) || (pattern.startsWith("."))
|| (pattern.endsWith(".."))) {
// Invalid pattern/domain name
return false; // depends on control dependency: [if], data = [none]
}
// Normalize hostName and pattern by turning them into absolute domain names if they are not
// yet absolute. This is needed because server certificates do not normally contain absolute
// names or patterns, but they should be treated as absolute. At the same time, any hostName
// presented to this method should also be treated as absolute for the purposes of matching
// to the server certificate.
// www.android.com matches www.android.com
// www.android.com matches www.android.com.
// www.android.com. matches www.android.com.
// www.android.com. matches www.android.com
if (!hostName.endsWith(".")) {
hostName += '.'; // depends on control dependency: [if], data = [none]
}
if (!pattern.endsWith(".")) {
pattern += '.'; // depends on control dependency: [if], data = [none]
}
// hostName and pattern are now absolute domain names.
pattern = pattern.toLowerCase(Locale.US);
// hostName and pattern are now in lower case -- domain names are case-insensitive.
if (!pattern.contains("*")) {
// Not a wildcard pattern -- hostName and pattern must match exactly.
return hostName.equals(pattern); // depends on control dependency: [if], data = [none]
}
// Wildcard pattern
// WILDCARD PATTERN RULES:
// 1. Asterisk (*) is only permitted in the left-most domain name label and must be the
// only character in that label (i.e., must match the whole left-most label).
// For example, *.example.com is permitted, while *a.example.com, a*.example.com,
// a*b.example.com, a.*.example.com are not permitted.
// 2. Asterisk (*) cannot match across domain name labels.
// For example, *.example.com matches test.example.com but does not match
// sub.test.example.com.
// 3. Wildcard patterns for single-label domain names are not permitted.
if ((!pattern.startsWith("*.")) || (pattern.indexOf('*', 1) != -1)) {
// Asterisk (*) is only permitted in the left-most domain name label and must be the only
// character in that label
return false; // depends on control dependency: [if], data = [none]
}
// Optimization: check whether hostName is too short to match the pattern. hostName must be at
// least as long as the pattern because asterisk must match the whole left-most label and
// hostName starts with a non-empty label. Thus, asterisk has to match one or more characters.
if (hostName.length() < pattern.length()) {
// hostName too short to match the pattern.
return false; // depends on control dependency: [if], data = [none]
}
if ("*.".equals(pattern)) {
// Wildcard pattern for single-label domain name -- not permitted.
return false; // depends on control dependency: [if], data = [none]
}
// hostName must end with the region of pattern following the asterisk.
String suffix = pattern.substring(1);
if (!hostName.endsWith(suffix)) {
// hostName does not end with the suffix
return false; // depends on control dependency: [if], data = [none]
}
// Check that asterisk did not match across domain name labels.
int suffixStartIndexInHostName = hostName.length() - suffix.length();
if ((suffixStartIndexInHostName > 0)
&& (hostName.lastIndexOf('.', suffixStartIndexInHostName - 1) != -1)) {
// Asterisk is matching across domain name labels -- not permitted.
return false; // depends on control dependency: [if], data = [none]
}
// hostName matches pattern
return true;
} } |
public class class_name {
@Override protected void handleEvents(final String EVENT_TYPE) {
super.handleEvents(EVENT_TYPE);
if ("RECALC".equals(EVENT_TYPE)) {
range = gauge.getRange();
angleStep = ANGLE_RANGE / range;
minValue = gauge.getMinValue();
sections = gauge.getSections();
resize();
redraw();
setBar(gauge.getCurrentValue());
} else if ("VISIBILITY".equals(EVENT_TYPE)) {
Helper.enableNode(valueText, gauge.isValueVisible());
Helper.enableNode(titleText, !gauge.getTitle().isEmpty());
Helper.enableNode(unitText, !gauge.getUnit().isEmpty());
boolean tickLabelsVisible = gauge.getTickLabelsVisible();
Helper.enableNode(minText, tickLabelsVisible);
Helper.enableNode(maxText, tickLabelsVisible);
boolean thresholdVisible = gauge.isThresholdVisible();
Helper.enableNode(threshold, thresholdVisible);
Helper.enableNode(thresholdText, thresholdVisible);
resize();
redraw();
}
} } | public class class_name {
@Override protected void handleEvents(final String EVENT_TYPE) {
super.handleEvents(EVENT_TYPE);
if ("RECALC".equals(EVENT_TYPE)) {
range = gauge.getRange(); // depends on control dependency: [if], data = [none]
angleStep = ANGLE_RANGE / range; // depends on control dependency: [if], data = [none]
minValue = gauge.getMinValue(); // depends on control dependency: [if], data = [none]
sections = gauge.getSections(); // depends on control dependency: [if], data = [none]
resize(); // depends on control dependency: [if], data = [none]
redraw(); // depends on control dependency: [if], data = [none]
setBar(gauge.getCurrentValue()); // depends on control dependency: [if], data = [none]
} else if ("VISIBILITY".equals(EVENT_TYPE)) {
Helper.enableNode(valueText, gauge.isValueVisible()); // depends on control dependency: [if], data = [none]
Helper.enableNode(titleText, !gauge.getTitle().isEmpty()); // depends on control dependency: [if], data = [none]
Helper.enableNode(unitText, !gauge.getUnit().isEmpty()); // depends on control dependency: [if], data = [none]
boolean tickLabelsVisible = gauge.getTickLabelsVisible();
Helper.enableNode(minText, tickLabelsVisible); // depends on control dependency: [if], data = [none]
Helper.enableNode(maxText, tickLabelsVisible); // depends on control dependency: [if], data = [none]
boolean thresholdVisible = gauge.isThresholdVisible();
Helper.enableNode(threshold, thresholdVisible); // depends on control dependency: [if], data = [none]
Helper.enableNode(thresholdText, thresholdVisible); // depends on control dependency: [if], data = [none]
resize(); // depends on control dependency: [if], data = [none]
redraw(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void marshall(ActivityTaskCanceledEventAttributes activityTaskCanceledEventAttributes, ProtocolMarshaller protocolMarshaller) {
if (activityTaskCanceledEventAttributes == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(activityTaskCanceledEventAttributes.getDetails(), DETAILS_BINDING);
protocolMarshaller.marshall(activityTaskCanceledEventAttributes.getScheduledEventId(), SCHEDULEDEVENTID_BINDING);
protocolMarshaller.marshall(activityTaskCanceledEventAttributes.getStartedEventId(), STARTEDEVENTID_BINDING);
protocolMarshaller.marshall(activityTaskCanceledEventAttributes.getLatestCancelRequestedEventId(), LATESTCANCELREQUESTEDEVENTID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ActivityTaskCanceledEventAttributes activityTaskCanceledEventAttributes, ProtocolMarshaller protocolMarshaller) {
if (activityTaskCanceledEventAttributes == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(activityTaskCanceledEventAttributes.getDetails(), DETAILS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(activityTaskCanceledEventAttributes.getScheduledEventId(), SCHEDULEDEVENTID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(activityTaskCanceledEventAttributes.getStartedEventId(), STARTEDEVENTID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(activityTaskCanceledEventAttributes.getLatestCancelRequestedEventId(), LATESTCANCELREQUESTEDEVENTID_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void waitForMemberStart(String member, JMX jmx)
{
boolean isRunning = false;
boolean printedStartMember = false;
int count = 0;
while(!isRunning)
{
try{ isRunning = GemFireInspector.checkMemberStatus(member,jmx); }
catch(Exception e) {Debugger.printWarn(e);}
if(!printedStartMember )
{
Debugger.println("Waiting for member:"+member+". Starting member to continue. "+
" You can perform a gfsh status command to confirm whether the member is running");
printedStartMember = true;
}
try{ delay();}catch(Exception e){}
if(count > retryCount)
{
throw new RuntimeException("member:"+member+" did not start after "
+retryCount+" checks with a delay of "+sleepDelay+" milliseconds");
}
count++;
}
} } | public class class_name {
public void waitForMemberStart(String member, JMX jmx)
{
boolean isRunning = false;
boolean printedStartMember = false;
int count = 0;
while(!isRunning)
{
try{ isRunning = GemFireInspector.checkMemberStatus(member,jmx); } // depends on control dependency: [try], data = [none]
catch(Exception e) {Debugger.printWarn(e);} // depends on control dependency: [catch], data = [none]
if(!printedStartMember )
{
Debugger.println("Waiting for member:"+member+". Starting member to continue. "+
" You can perform a gfsh status command to confirm whether the member is running"); // depends on control dependency: [if], data = [none]
printedStartMember = true; // depends on control dependency: [if], data = [none]
}
try{ delay();}catch(Exception e){} // depends on control dependency: [try], data = [none] // depends on control dependency: [catch], data = [none]
if(count > retryCount)
{
throw new RuntimeException("member:"+member+" did not start after "
+retryCount+" checks with a delay of "+sleepDelay+" milliseconds");
}
count++; // depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
public void addResult(CmsResourceTypeStatResult result) {
if (!m_results.contains(result)) {
m_results.add(result);
m_updated = false;
} else {
m_results.remove(result);
m_results.add(result);
m_updated = true;
}
} } | public class class_name {
public void addResult(CmsResourceTypeStatResult result) {
if (!m_results.contains(result)) {
m_results.add(result); // depends on control dependency: [if], data = [none]
m_updated = false; // depends on control dependency: [if], data = [none]
} else {
m_results.remove(result); // depends on control dependency: [if], data = [none]
m_results.add(result); // depends on control dependency: [if], data = [none]
m_updated = true; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public BodyContent push() {
if (current.after == null) {
current.after = new Entry(current, new BodyContentImpl(current.body == null ? (JspWriter) base : current.body));
}
else {
current.after.doDevNull = false;
current.after.body.init(current.body == null ? (JspWriter) base : current.body);
}
current = current.after;
return current.body;
} } | public class class_name {
public BodyContent push() {
if (current.after == null) {
current.after = new Entry(current, new BodyContentImpl(current.body == null ? (JspWriter) base : current.body)); // depends on control dependency: [if], data = [none]
}
else {
current.after.doDevNull = false; // depends on control dependency: [if], data = [none]
current.after.body.init(current.body == null ? (JspWriter) base : current.body); // depends on control dependency: [if], data = [none]
}
current = current.after;
return current.body;
} } |
public class class_name {
@Override
public org.fcrepo.server.types.gen.MIMETypedStream getDatastreamDissemination(String pid,
String dsID,
String asOfDateTime) {
MessageContext ctx = context.getMessageContext();
Context context = ReadOnlyContext.getSoapContext(ctx);
assertInitialized();
try {
org.fcrepo.server.storage.types.MIMETypedStream mimeTypedStream =
m_access.getDatastreamDissemination(context,
pid,
dsID,
DateUtility
.parseDateOrNull(asOfDateTime));
org.fcrepo.server.types.gen.MIMETypedStream genMIMETypedStream =
TypeUtility
.convertMIMETypedStreamToGenMIMETypedStream(mimeTypedStream);
return genMIMETypedStream;
} catch (OutOfMemoryError oome) {
LOG.error("Out of memory error getting " + dsID
+ " datastream dissemination for " + pid);
String exceptionText =
"The datastream you are attempting to retrieve is too large "
+ "to transfer via getDatastreamDissemination (as determined "
+ "by the server memory allocation.) Consider retrieving this "
+ "datastream via REST at: ";
String restURL =
describeRepository().getRepositoryBaseURL() + "/get/" + pid
+ "/" + dsID;
throw CXFUtility.getFault(new Exception(exceptionText + restURL));
} catch (Throwable th) {
LOG.error("Error getting datastream dissemination", th);
throw CXFUtility.getFault(th);
}
} } | public class class_name {
@Override
public org.fcrepo.server.types.gen.MIMETypedStream getDatastreamDissemination(String pid,
String dsID,
String asOfDateTime) {
MessageContext ctx = context.getMessageContext();
Context context = ReadOnlyContext.getSoapContext(ctx);
assertInitialized();
try {
org.fcrepo.server.storage.types.MIMETypedStream mimeTypedStream =
m_access.getDatastreamDissemination(context,
pid,
dsID,
DateUtility
.parseDateOrNull(asOfDateTime));
org.fcrepo.server.types.gen.MIMETypedStream genMIMETypedStream =
TypeUtility
.convertMIMETypedStreamToGenMIMETypedStream(mimeTypedStream);
return genMIMETypedStream; // depends on control dependency: [try], data = [none]
} catch (OutOfMemoryError oome) {
LOG.error("Out of memory error getting " + dsID
+ " datastream dissemination for " + pid);
String exceptionText =
"The datastream you are attempting to retrieve is too large "
+ "to transfer via getDatastreamDissemination (as determined "
+ "by the server memory allocation.) Consider retrieving this "
+ "datastream via REST at: ";
String restURL =
describeRepository().getRepositoryBaseURL() + "/get/" + pid
+ "/" + dsID;
throw CXFUtility.getFault(new Exception(exceptionText + restURL));
} catch (Throwable th) { // depends on control dependency: [catch], data = [none]
LOG.error("Error getting datastream dissemination", th);
throw CXFUtility.getFault(th);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
boolean deleteEntity(@NotNull final PersistentStoreTransaction txn, @NotNull final PersistentEntity entity) {
clearProperties(txn, entity);
clearBlobs(txn, entity);
deleteLinks(txn, entity);
final PersistentEntityId id = entity.getId();
final int entityTypeId = id.getTypeId();
final long entityLocalId = id.getLocalId();
final ByteIterable key = LongBinding.longToCompressedEntry(entityLocalId);
if (config.isDebugSearchForIncomingLinksOnDelete()) {
// search for incoming links
final List<String> allLinkNames = getAllLinkNames(txn);
for (final String entityType : txn.getEntityTypes()) {
for (final String linkName : allLinkNames) {
//noinspection LoopStatementThatDoesntLoop
for (final Entity referrer : txn.findLinks(entityType, entity, linkName)) {
throw new EntityStoreException(entity +
" is about to be deleted, but it is referenced by " + referrer + ", link name: " + linkName);
}
}
}
}
if (getEntitiesTable(txn, entityTypeId).delete(txn.getEnvironmentTransaction(), key)) {
txn.entityDeleted(id);
return true;
}
return false;
} } | public class class_name {
boolean deleteEntity(@NotNull final PersistentStoreTransaction txn, @NotNull final PersistentEntity entity) {
clearProperties(txn, entity);
clearBlobs(txn, entity);
deleteLinks(txn, entity);
final PersistentEntityId id = entity.getId();
final int entityTypeId = id.getTypeId();
final long entityLocalId = id.getLocalId();
final ByteIterable key = LongBinding.longToCompressedEntry(entityLocalId);
if (config.isDebugSearchForIncomingLinksOnDelete()) {
// search for incoming links
final List<String> allLinkNames = getAllLinkNames(txn);
for (final String entityType : txn.getEntityTypes()) {
for (final String linkName : allLinkNames) {
//noinspection LoopStatementThatDoesntLoop
for (final Entity referrer : txn.findLinks(entityType, entity, linkName)) {
throw new EntityStoreException(entity +
" is about to be deleted, but it is referenced by " + referrer + ", link name: " + linkName);
}
}
}
}
if (getEntitiesTable(txn, entityTypeId).delete(txn.getEnvironmentTransaction(), key)) {
txn.entityDeleted(id); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public AwsSecurityFindingFilters withResourceType(StringFilter... resourceType) {
if (this.resourceType == null) {
setResourceType(new java.util.ArrayList<StringFilter>(resourceType.length));
}
for (StringFilter ele : resourceType) {
this.resourceType.add(ele);
}
return this;
} } | public class class_name {
public AwsSecurityFindingFilters withResourceType(StringFilter... resourceType) {
if (this.resourceType == null) {
setResourceType(new java.util.ArrayList<StringFilter>(resourceType.length)); // depends on control dependency: [if], data = [none]
}
for (StringFilter ele : resourceType) {
this.resourceType.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public final EObject ruleWildcard() throws RecognitionException {
EObject current = null;
Token otherlv_1=null;
enterRule();
try {
// InternalSimpleAntlr.g:1707:28: ( ( () otherlv_1= '.' ) )
// InternalSimpleAntlr.g:1708:1: ( () otherlv_1= '.' )
{
// InternalSimpleAntlr.g:1708:1: ( () otherlv_1= '.' )
// InternalSimpleAntlr.g:1708:2: () otherlv_1= '.'
{
// InternalSimpleAntlr.g:1708:2: ()
// InternalSimpleAntlr.g:1709:2:
{
if ( state.backtracking==0 ) {
/* */
}
if ( state.backtracking==0 ) {
current = forceCreateModelElement(
grammarAccess.getWildcardAccess().getWildcardAction_0(),
current);
}
}
otherlv_1=(Token)match(input,36,FOLLOW_2); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(otherlv_1, grammarAccess.getWildcardAccess().getFullStopKeyword_1());
}
}
}
if ( state.backtracking==0 ) {
leaveRule();
}
}
catch (RecognitionException re) {
recover(input,re);
appendSkippedTokens();
}
finally {
}
return current;
} } | public class class_name {
public final EObject ruleWildcard() throws RecognitionException {
EObject current = null;
Token otherlv_1=null;
enterRule();
try {
// InternalSimpleAntlr.g:1707:28: ( ( () otherlv_1= '.' ) )
// InternalSimpleAntlr.g:1708:1: ( () otherlv_1= '.' )
{
// InternalSimpleAntlr.g:1708:1: ( () otherlv_1= '.' )
// InternalSimpleAntlr.g:1708:2: () otherlv_1= '.'
{
// InternalSimpleAntlr.g:1708:2: ()
// InternalSimpleAntlr.g:1709:2:
{
if ( state.backtracking==0 ) {
/* */
}
if ( state.backtracking==0 ) {
current = forceCreateModelElement(
grammarAccess.getWildcardAccess().getWildcardAction_0(),
current); // depends on control dependency: [if], data = [none]
}
}
otherlv_1=(Token)match(input,36,FOLLOW_2); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(otherlv_1, grammarAccess.getWildcardAccess().getFullStopKeyword_1()); // depends on control dependency: [if], data = [none]
}
}
}
if ( state.backtracking==0 ) {
leaveRule(); // depends on control dependency: [if], data = [none]
}
}
catch (RecognitionException re) {
recover(input,re);
appendSkippedTokens();
}
finally {
}
return current;
} } |
public class class_name {
public InputStream openFileStream(String pathHint, String[] extensions)
{
if (fos == null)
{
try {
fos = (FileOpenService)ServiceManager.lookup("javax.jnlp.FileOpenService");
} catch (UnavailableServiceException e) {
fos = null;
}
}
if (fos != null) {
try {
// ask user to select a file through this service
FileContents fc = fos.openFileDialog(pathHint, extensions);
return fc.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
} } | public class class_name {
public InputStream openFileStream(String pathHint, String[] extensions)
{
if (fos == null)
{
try {
fos = (FileOpenService)ServiceManager.lookup("javax.jnlp.FileOpenService"); // depends on control dependency: [try], data = [none]
} catch (UnavailableServiceException e) {
fos = null;
} // depends on control dependency: [catch], data = [none]
}
if (fos != null) {
try {
// ask user to select a file through this service
FileContents fc = fos.openFileDialog(pathHint, extensions);
return fc.getInputStream(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
}
return null;
} } |
public class class_name {
public Violation checkInstantiation(
Collection<TypeVariableSymbol> typeParameters, Collection<Type> typeArguments) {
return Streams.zip(
typeParameters.stream(),
typeArguments.stream(),
(sym, type) -> {
if (!hasThreadSafeTypeParameterAnnotation(sym)) {
return Violation.absent();
}
Violation info =
isThreadSafeType(
/* allowContainerTypeParameters= */ true,
/* containerTypeParameters= */ ImmutableSet.of(),
type);
if (!info.isPresent()) {
return Violation.absent();
}
return info.plus(
String.format(
"instantiation of '%s' is %s", sym, purpose.mutableOrNotThreadSafe()));
})
.filter(Violation::isPresent)
.findFirst()
.orElse(Violation.absent());
} } | public class class_name {
public Violation checkInstantiation(
Collection<TypeVariableSymbol> typeParameters, Collection<Type> typeArguments) {
return Streams.zip(
typeParameters.stream(),
typeArguments.stream(),
(sym, type) -> {
if (!hasThreadSafeTypeParameterAnnotation(sym)) {
return Violation.absent();
}
Violation info =
isThreadSafeType(
/* allowContainerTypeParameters= */ true,
/* containerTypeParameters= */ ImmutableSet.of(),
type);
if (!info.isPresent()) {
return Violation.absent(); // depends on control dependency: [if], data = [none]
}
return info.plus(
String.format(
"instantiation of '%s' is %s", sym, purpose.mutableOrNotThreadSafe()));
})
.filter(Violation::isPresent)
.findFirst()
.orElse(Violation.absent());
} } |
public class class_name {
private static synchronized void proxyInit() {
if (PROXY_HOST != null && customRouterPlanner == null) {
HttpHost proxy = new HttpHost(PROXY_HOST, PROXY_PORT);
customRouterPlanner = new DefaultProxyRoutePlanner(proxy);
}
} } | public class class_name {
private static synchronized void proxyInit() {
if (PROXY_HOST != null && customRouterPlanner == null) {
HttpHost proxy = new HttpHost(PROXY_HOST, PROXY_PORT);
customRouterPlanner = new DefaultProxyRoutePlanner(proxy); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setLogStreams(java.util.Collection<LogStream> logStreams) {
if (logStreams == null) {
this.logStreams = null;
return;
}
this.logStreams = new com.amazonaws.internal.SdkInternalList<LogStream>(logStreams);
} } | public class class_name {
public void setLogStreams(java.util.Collection<LogStream> logStreams) {
if (logStreams == null) {
this.logStreams = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.logStreams = new com.amazonaws.internal.SdkInternalList<LogStream>(logStreams);
} } |
public class class_name {
protected String getCssPath(String resourceName) {
String path = resourceName;
if (jawrConfig.getGeneratorRegistry().isPathGenerated(path)) {
path = path.replace(':', '/');
path = JawrConstant.SPRITE_GENERATED_CSS_DIR + path;
}
return path;
} } | public class class_name {
protected String getCssPath(String resourceName) {
String path = resourceName;
if (jawrConfig.getGeneratorRegistry().isPathGenerated(path)) {
path = path.replace(':', '/'); // depends on control dependency: [if], data = [none]
path = JawrConstant.SPRITE_GENERATED_CSS_DIR + path; // depends on control dependency: [if], data = [none]
}
return path;
} } |
public class class_name {
public boolean covers(String uri) {
// any namspace covers only the any namespace uri
// no wildcard ("") requires equality between namespaces.
if (ANY_NAMESPACE.equals(ns) || "".equals(wildcard)) {
return ns.equals(uri);
}
String[] parts = split(ns, wildcard);
// no wildcard
if (parts.length == 1) {
return ns.equals(uri);
}
// at least one wildcard, we need to check that the start and end are the same
// then we get to match a string against a pattern like *p1*...*pn*
if (!uri.startsWith(parts[0])) {
return false;
}
if (!uri.endsWith(parts[parts.length - 1])) {
return false;
}
// Check that all remaining parts match the remaining URI.
int start = parts[0].length();
int end = uri.length() - parts[parts.length - 1].length();
for (int i = 1; i < parts.length - 1; i++) {
if (start > end) {
return false;
}
int match = uri.indexOf(parts[i], start);
if (match == -1 || match + parts[i].length() > end) {
return false;
}
start = match + parts[i].length();
}
return true;
} } | public class class_name {
public boolean covers(String uri) {
// any namspace covers only the any namespace uri
// no wildcard ("") requires equality between namespaces.
if (ANY_NAMESPACE.equals(ns) || "".equals(wildcard)) {
return ns.equals(uri); // depends on control dependency: [if], data = [none]
}
String[] parts = split(ns, wildcard);
// no wildcard
if (parts.length == 1) {
return ns.equals(uri); // depends on control dependency: [if], data = [none]
}
// at least one wildcard, we need to check that the start and end are the same
// then we get to match a string against a pattern like *p1*...*pn*
if (!uri.startsWith(parts[0])) {
return false; // depends on control dependency: [if], data = [none]
}
if (!uri.endsWith(parts[parts.length - 1])) {
return false; // depends on control dependency: [if], data = [none]
}
// Check that all remaining parts match the remaining URI.
int start = parts[0].length();
int end = uri.length() - parts[parts.length - 1].length();
for (int i = 1; i < parts.length - 1; i++) {
if (start > end) {
return false; // depends on control dependency: [if], data = [none]
}
int match = uri.indexOf(parts[i], start);
if (match == -1 || match + parts[i].length() > end) {
return false; // depends on control dependency: [if], data = [none]
}
start = match + parts[i].length(); // depends on control dependency: [for], data = [i]
}
return true;
} } |
public class class_name {
protected void processCollectionRequest(HyperionContext hyperionContext)
{
EndpointRequest request = hyperionContext.getEndpointRequest();
EndpointResponse response = hyperionContext.getEndpointResponse();
ApiVersionPlugin<ApiObject<Serializable>,PersistentObject<Serializable>,Serializable> apiVersionPlugin = hyperionContext.getVersionPlugin();
EntityPlugin plugin = hyperionContext.getEntityPlugin();
List<ApiObject<Serializable>> clientObjects = null;
try
{
clientObjects = marshaller.unmarshallCollection(request.getInputStream(), apiVersionPlugin.getApiClass());
}
catch (WriteLimitException e)
{
throw new BadRequestException(messageSource.getErrorMessage(ERROR_WRITE_LIMIT,hyperionContext.getLocale(),e.getWriteLimit()),e);
}
catch (MarshallingException e)
{
throw new BadRequestException(messageSource.getErrorMessage(ERROR_READING_REQUEST,hyperionContext.getLocale(),e.getMessage()),e);
}
PersistenceContext persistenceContext = buildPersistenceContext(hyperionContext);
Set<String> fieldSet = persistenceContext.getRequestedFields();
if(fieldSet != null)
fieldSet.add("id");
List<ApiObject> saved = plugin.getPersistenceOperations().createOrUpdateItems(clientObjects, persistenceContext);
processChangeEvents(hyperionContext,persistenceContext);
response.setResponseCode(200);
EntityList<ApiObject> entityResponse = new EntityList<>();
entityResponse.setEntries(saved);
hyperionContext.setResult(entityResponse);
} } | public class class_name {
protected void processCollectionRequest(HyperionContext hyperionContext)
{
EndpointRequest request = hyperionContext.getEndpointRequest();
EndpointResponse response = hyperionContext.getEndpointResponse();
ApiVersionPlugin<ApiObject<Serializable>,PersistentObject<Serializable>,Serializable> apiVersionPlugin = hyperionContext.getVersionPlugin();
EntityPlugin plugin = hyperionContext.getEntityPlugin();
List<ApiObject<Serializable>> clientObjects = null;
try
{
clientObjects = marshaller.unmarshallCollection(request.getInputStream(), apiVersionPlugin.getApiClass()); // depends on control dependency: [try], data = [none]
}
catch (WriteLimitException e)
{
throw new BadRequestException(messageSource.getErrorMessage(ERROR_WRITE_LIMIT,hyperionContext.getLocale(),e.getWriteLimit()),e);
} // depends on control dependency: [catch], data = [none]
catch (MarshallingException e)
{
throw new BadRequestException(messageSource.getErrorMessage(ERROR_READING_REQUEST,hyperionContext.getLocale(),e.getMessage()),e);
} // depends on control dependency: [catch], data = [none]
PersistenceContext persistenceContext = buildPersistenceContext(hyperionContext);
Set<String> fieldSet = persistenceContext.getRequestedFields();
if(fieldSet != null)
fieldSet.add("id");
List<ApiObject> saved = plugin.getPersistenceOperations().createOrUpdateItems(clientObjects, persistenceContext);
processChangeEvents(hyperionContext,persistenceContext);
response.setResponseCode(200);
EntityList<ApiObject> entityResponse = new EntityList<>();
entityResponse.setEntries(saved);
hyperionContext.setResult(entityResponse);
} } |
public class class_name {
public void setMask(String mask) {
if (mask != null && !mask.isEmpty()) {
AddResourcesListener.addResourceToHeadButAfterJQuery(C.BSF_LIBRARY, "js/jquery.inputmask.bundle.min.js");
}
getStateHelper().put(PropertyKeys.mask, mask);
} } | public class class_name {
public void setMask(String mask) {
if (mask != null && !mask.isEmpty()) {
AddResourcesListener.addResourceToHeadButAfterJQuery(C.BSF_LIBRARY, "js/jquery.inputmask.bundle.min.js"); // depends on control dependency: [if], data = [none]
}
getStateHelper().put(PropertyKeys.mask, mask);
} } |
public class class_name {
private static int hashCodeAsciiCompute(CharSequence value, int offset, int hash) {
if (BIG_ENDIAN_NATIVE_ORDER) {
return hash * HASH_CODE_C1 +
// Low order int
hashCodeAsciiSanitizeInt(value, offset + 4) * HASH_CODE_C2 +
// High order int
hashCodeAsciiSanitizeInt(value, offset);
}
return hash * HASH_CODE_C1 +
// Low order int
hashCodeAsciiSanitizeInt(value, offset) * HASH_CODE_C2 +
// High order int
hashCodeAsciiSanitizeInt(value, offset + 4);
} } | public class class_name {
private static int hashCodeAsciiCompute(CharSequence value, int offset, int hash) {
if (BIG_ENDIAN_NATIVE_ORDER) {
return hash * HASH_CODE_C1 +
// Low order int
hashCodeAsciiSanitizeInt(value, offset + 4) * HASH_CODE_C2 +
// High order int
hashCodeAsciiSanitizeInt(value, offset); // depends on control dependency: [if], data = [none]
}
return hash * HASH_CODE_C1 +
// Low order int
hashCodeAsciiSanitizeInt(value, offset) * HASH_CODE_C2 +
// High order int
hashCodeAsciiSanitizeInt(value, offset + 4);
} } |
public class class_name {
public static Module loadModulesFromProperties(final Module jFunkModule, final String propertiesFile)
throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
final List<Module> modules = Lists.newArrayList();
LOG.debug("Using jfunk.props.file=" + propertiesFile);
Properties props = loadProperties(propertiesFile);
for (final Enumeration<?> en = props.propertyNames(); en.hasMoreElements();) {
String name = (String) en.nextElement();
if (name.startsWith("module.")) {
String className = props.getProperty(name);
LOG.info("Loading " + name + "=" + className);
Class<? extends Module> moduleClass = Class.forName(className).asSubclass(Module.class);
Module module = moduleClass.newInstance();
modules.add(module);
}
}
return Modules.override(jFunkModule).with(modules);
} } | public class class_name {
public static Module loadModulesFromProperties(final Module jFunkModule, final String propertiesFile)
throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
final List<Module> modules = Lists.newArrayList();
LOG.debug("Using jfunk.props.file=" + propertiesFile);
Properties props = loadProperties(propertiesFile);
for (final Enumeration<?> en = props.propertyNames(); en.hasMoreElements();) {
String name = (String) en.nextElement();
if (name.startsWith("module.")) {
String className = props.getProperty(name);
LOG.info("Loading " + name + "=" + className); // depends on control dependency: [if], data = [none]
Class<? extends Module> moduleClass = Class.forName(className).asSubclass(Module.class);
Module module = moduleClass.newInstance();
modules.add(module);
}
}
return Modules.override(jFunkModule).with(modules);
} } |
public class class_name {
public void setDividerDrawable(Drawable divider) {
if (divider == mDivider) {
return;
}
//Fix for issue #379
if (divider instanceof ColorDrawable && Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
divider = new IcsColorDrawable((ColorDrawable) divider);
}
mDivider = divider;
if (divider != null) {
mDividerWidth = divider.getIntrinsicWidth();
mDividerHeight = divider.getIntrinsicHeight();
} else {
mDividerWidth = 0;
mDividerHeight = 0;
}
setWillNotDraw(divider == null);
requestLayout();
} } | public class class_name {
public void setDividerDrawable(Drawable divider) {
if (divider == mDivider) {
return; // depends on control dependency: [if], data = [none]
}
//Fix for issue #379
if (divider instanceof ColorDrawable && Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
divider = new IcsColorDrawable((ColorDrawable) divider); // depends on control dependency: [if], data = [none]
}
mDivider = divider;
if (divider != null) {
mDividerWidth = divider.getIntrinsicWidth(); // depends on control dependency: [if], data = [none]
mDividerHeight = divider.getIntrinsicHeight(); // depends on control dependency: [if], data = [none]
} else {
mDividerWidth = 0; // depends on control dependency: [if], data = [none]
mDividerHeight = 0; // depends on control dependency: [if], data = [none]
}
setWillNotDraw(divider == null);
requestLayout();
} } |
public class class_name {
public static Set<BioPAXElement> runNeighborhood(
Set<BioPAXElement> sourceSet,
Model model,
int limit,
Direction direction,
Filter... filters)
{
Graph graph;
if (model.getLevel() == BioPAXLevel.L3)
{
if (direction == Direction.UNDIRECTED)
{
graph = new GraphL3Undirected(model, filters);
direction = Direction.BOTHSTREAM;
}
else
{
graph = new GraphL3(model, filters);
}
}
else return Collections.emptySet();
Set<Node> source = prepareSingleNodeSet(sourceSet, graph);
if (sourceSet.isEmpty()) return Collections.emptySet();
NeighborhoodQuery query = new NeighborhoodQuery(source, direction, limit);
Set<GraphObject> resultWrappers = query.run();
return convertQueryResult(resultWrappers, graph, true);
} } | public class class_name {
public static Set<BioPAXElement> runNeighborhood(
Set<BioPAXElement> sourceSet,
Model model,
int limit,
Direction direction,
Filter... filters)
{
Graph graph;
if (model.getLevel() == BioPAXLevel.L3)
{
if (direction == Direction.UNDIRECTED)
{
graph = new GraphL3Undirected(model, filters); // depends on control dependency: [if], data = [none]
direction = Direction.BOTHSTREAM; // depends on control dependency: [if], data = [none]
}
else
{
graph = new GraphL3(model, filters); // depends on control dependency: [if], data = [none]
}
}
else return Collections.emptySet();
Set<Node> source = prepareSingleNodeSet(sourceSet, graph);
if (sourceSet.isEmpty()) return Collections.emptySet();
NeighborhoodQuery query = new NeighborhoodQuery(source, direction, limit);
Set<GraphObject> resultWrappers = query.run();
return convertQueryResult(resultWrappers, graph, true);
} } |
public class class_name {
public boolean close(){
if(super.close()){
dockableHolder.dispose();
dockableHolder.removeWindowFocusListener(this);
WindowListener[] listeners = dockableHolder.getWindowListeners();
for (WindowListener listener : listeners) {
dockableHolder.removeWindowListener(listener);
}
Lm.setParent(null);
dockableHolder.removeAll();
dockableHolder.getRootPane().removeAll();
dockableHolder = null;
return true;
}
else{
return false;
}
} } | public class class_name {
public boolean close(){
if(super.close()){
dockableHolder.dispose(); // depends on control dependency: [if], data = [none]
dockableHolder.removeWindowFocusListener(this); // depends on control dependency: [if], data = [none]
WindowListener[] listeners = dockableHolder.getWindowListeners();
for (WindowListener listener : listeners) {
dockableHolder.removeWindowListener(listener); // depends on control dependency: [for], data = [listener]
}
Lm.setParent(null); // depends on control dependency: [if], data = [none]
dockableHolder.removeAll(); // depends on control dependency: [if], data = [none]
dockableHolder.getRootPane().removeAll(); // depends on control dependency: [if], data = [none]
dockableHolder = null; // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
else{
return false; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Provides
List<? extends DataSource> provideContainerChildDataSources(final Configuration configuration, final Map<String, DataSource> availableDataSources) {
List<DataSource> dataSources = newArrayListWithExpectedSize(3);
String key = "dataSource.container.dsref";
for (int i = 1;; ++i) {
String dsKey = key + i;
String dsName = configuration.get(dsKey);
if (dsName == null) {
break;
}
DataSource ds = availableDataSources.get(dsName);
if (ds == null) {
throw new ProvisionException("DataSource with name '" + dsName + "' not available. Check your configuration.");
}
dataSources.add(ds);
}
return dataSources;
} } | public class class_name {
@Provides
List<? extends DataSource> provideContainerChildDataSources(final Configuration configuration, final Map<String, DataSource> availableDataSources) {
List<DataSource> dataSources = newArrayListWithExpectedSize(3);
String key = "dataSource.container.dsref";
for (int i = 1;; ++i) {
String dsKey = key + i;
String dsName = configuration.get(dsKey);
if (dsName == null) {
break;
}
DataSource ds = availableDataSources.get(dsName);
if (ds == null) {
throw new ProvisionException("DataSource with name '" + dsName + "' not available. Check your configuration.");
}
dataSources.add(ds); // depends on control dependency: [for], data = [none]
}
return dataSources;
} } |
public class class_name {
static String checkDefaultJson(JsonNode defaultJson, Schema schema) {
Schema.Type fieldType = schema.getType();
String expectedVal = null;
switch(fieldType) {
case NULL:
if(!defaultJson.isNull()) {
expectedVal = "null";
}
break;
case BOOLEAN:
if(!defaultJson.isBoolean()) {
expectedVal = "boolean";
}
break;
case INT:
if(!defaultJson.isInt()) {
expectedVal = "int";
}
break;
case LONG:
if(!defaultJson.isInt() && !defaultJson.isLong()) {
expectedVal = "long";
}
break;
case FLOAT:
case DOUBLE:
if(!defaultJson.isNumber()) {
expectedVal = "number";
}
break;
case BYTES:
if(defaultJson.isTextual()) {
break;
}
expectedVal = "bytes (ex. \"\\u00FF\")";
break;
case STRING:
if(!defaultJson.isTextual()) {
expectedVal = "string";
}
break;
case ENUM:
if(defaultJson.isTextual()) {
if(schema.hasEnumSymbol(defaultJson.getTextValue())) {
break;
}
}
expectedVal = "valid enum";
break;
case FIXED:
if(defaultJson.isTextual()) {
byte[] fixed = defaultJson.getValueAsText().getBytes();
if(fixed.length == schema.getFixedSize()) {
break;
}
expectedVal = "fixed size incorrect. Expected size: " + schema.getFixedSize()
+ " got size " + fixed.length;
break;
}
expectedVal = "fixed (ex. \"\\u00FF\")";
break;
case ARRAY:
if(defaultJson.isArray()) {
// Check all array variables
boolean isGood = true;
for(JsonNode node: defaultJson) {
String val = checkDefaultJson(node, schema.getElementType());
if(val == null) {
continue;
} else {
isGood = false;
break;
}
}
if(isGood) {
break;
}
}
expectedVal = "array of type " + schema.getElementType().toString();
break;
case MAP:
if(defaultJson.isObject()) {
boolean isGood = true;
for(JsonNode node: defaultJson) {
String val = checkDefaultJson(node, schema.getValueType());
if(val == null) {
continue;
} else {
isGood = false;
break;
}
}
if(isGood) {
break;
}
}
expectedVal = "map of type " + schema.getValueType().toString();
break;
case RECORD:
if(defaultJson.isObject()) {
boolean isGood = true;
for(Field field: schema.getFields()) {
JsonNode jsonNode = defaultJson.get(field.name());
if(jsonNode == null) {
jsonNode = field.defaultValue();
if(jsonNode == null) {
isGood = false;
break;
}
}
String val = checkDefaultJson(jsonNode, field.schema());
if(val != null) {
isGood = false;
break;
}
}
if(isGood) {
break;
}
}
expectedVal = "record of type " + schema.toString();
break;
case UNION:
// Avro spec states we only need to match with the first item
expectedVal = checkDefaultJson(defaultJson, schema.getTypes().get(0));
break;
}
return expectedVal;
} } | public class class_name {
static String checkDefaultJson(JsonNode defaultJson, Schema schema) {
Schema.Type fieldType = schema.getType();
String expectedVal = null;
switch(fieldType) {
case NULL:
if(!defaultJson.isNull()) {
expectedVal = "null"; // depends on control dependency: [if], data = [none]
}
break;
case BOOLEAN:
if(!defaultJson.isBoolean()) {
expectedVal = "boolean"; // depends on control dependency: [if], data = [none]
}
break;
case INT:
if(!defaultJson.isInt()) {
expectedVal = "int"; // depends on control dependency: [if], data = [none]
}
break;
case LONG:
if(!defaultJson.isInt() && !defaultJson.isLong()) {
expectedVal = "long"; // depends on control dependency: [if], data = [none]
}
break;
case FLOAT:
case DOUBLE:
if(!defaultJson.isNumber()) {
expectedVal = "number"; // depends on control dependency: [if], data = [none]
}
break;
case BYTES:
if(defaultJson.isTextual()) {
break;
}
expectedVal = "bytes (ex. \"\\u00FF\")";
break;
case STRING:
if(!defaultJson.isTextual()) {
expectedVal = "string"; // depends on control dependency: [if], data = [none]
}
break;
case ENUM:
if(defaultJson.isTextual()) {
if(schema.hasEnumSymbol(defaultJson.getTextValue())) {
break;
}
}
expectedVal = "valid enum";
break;
case FIXED:
if(defaultJson.isTextual()) {
byte[] fixed = defaultJson.getValueAsText().getBytes();
if(fixed.length == schema.getFixedSize()) {
break;
}
expectedVal = "fixed size incorrect. Expected size: " + schema.getFixedSize() // depends on control dependency: [if], data = [none]
+ " got size " + fixed.length; // depends on control dependency: [if], data = [none]
break;
}
expectedVal = "fixed (ex. \"\\u00FF\")";
break;
case ARRAY:
if(defaultJson.isArray()) {
// Check all array variables
boolean isGood = true;
for(JsonNode node: defaultJson) {
String val = checkDefaultJson(node, schema.getElementType());
if(val == null) {
continue;
} else {
isGood = false; // depends on control dependency: [if], data = [none]
break;
}
}
if(isGood) {
break;
}
}
expectedVal = "array of type " + schema.getElementType().toString();
break;
case MAP:
if(defaultJson.isObject()) {
boolean isGood = true;
for(JsonNode node: defaultJson) {
String val = checkDefaultJson(node, schema.getValueType());
if(val == null) {
continue;
} else {
isGood = false; // depends on control dependency: [if], data = [none]
break;
}
}
if(isGood) {
break;
}
}
expectedVal = "map of type " + schema.getValueType().toString();
break;
case RECORD:
if(defaultJson.isObject()) {
boolean isGood = true;
for(Field field: schema.getFields()) {
JsonNode jsonNode = defaultJson.get(field.name());
if(jsonNode == null) {
jsonNode = field.defaultValue(); // depends on control dependency: [if], data = [none]
if(jsonNode == null) {
isGood = false; // depends on control dependency: [if], data = [none]
break;
}
}
String val = checkDefaultJson(jsonNode, field.schema());
if(val != null) {
isGood = false; // depends on control dependency: [if], data = [none]
break;
}
}
if(isGood) {
break;
}
}
expectedVal = "record of type " + schema.toString();
break;
case UNION:
// Avro spec states we only need to match with the first item
expectedVal = checkDefaultJson(defaultJson, schema.getTypes().get(0));
break;
}
return expectedVal;
} } |
public class class_name {
private static LocaleStore createLocaleStore(Map<TextStyle, Map<Long, String>> valueTextMap) {
valueTextMap.put(TextStyle.FULL_STANDALONE, valueTextMap.get(TextStyle.FULL));
valueTextMap.put(TextStyle.SHORT_STANDALONE, valueTextMap.get(TextStyle.SHORT));
if (valueTextMap.containsKey(TextStyle.NARROW) && valueTextMap.containsKey(TextStyle.NARROW_STANDALONE) == false) {
valueTextMap.put(TextStyle.NARROW_STANDALONE, valueTextMap.get(TextStyle.NARROW));
}
return new LocaleStore(valueTextMap);
} } | public class class_name {
private static LocaleStore createLocaleStore(Map<TextStyle, Map<Long, String>> valueTextMap) {
valueTextMap.put(TextStyle.FULL_STANDALONE, valueTextMap.get(TextStyle.FULL));
valueTextMap.put(TextStyle.SHORT_STANDALONE, valueTextMap.get(TextStyle.SHORT));
if (valueTextMap.containsKey(TextStyle.NARROW) && valueTextMap.containsKey(TextStyle.NARROW_STANDALONE) == false) {
valueTextMap.put(TextStyle.NARROW_STANDALONE, valueTextMap.get(TextStyle.NARROW)); // depends on control dependency: [if], data = [none]
}
return new LocaleStore(valueTextMap);
} } |
public class class_name {
public List<Column> getInsertColumnList() {
List<Column> result = new ArrayList<>();
List<Column> tempColumnList = new ArrayList<>();
for (Column currentColumn:this.columns) {
if (currentColumn.referenceTable != null) {
tempColumnList = currentColumn.referenceTable.getFindColumnList();
for (Column tempColumn : tempColumnList) {
Column column = new Column();
column.name = currentColumn.name.replace("_ID", "_").replace("_id", "_") + tempColumn.name;
column.dataType = tempColumn.dataType;
column.nullable = currentColumn.nullable;
result.add(column);
}
} else {
Column column = new Column();
column.name = currentColumn.name;
column.dataType = currentColumn.dataType;
column.nullable = currentColumn.nullable;
result.add(column);
}
}
return result;
} } | public class class_name {
public List<Column> getInsertColumnList() {
List<Column> result = new ArrayList<>();
List<Column> tempColumnList = new ArrayList<>();
for (Column currentColumn:this.columns) {
if (currentColumn.referenceTable != null) {
tempColumnList = currentColumn.referenceTable.getFindColumnList();
// depends on control dependency: [if], data = [none]
for (Column tempColumn : tempColumnList) {
Column column = new Column();
column.name = currentColumn.name.replace("_ID", "_").replace("_id", "_") + tempColumn.name;
// depends on control dependency: [for], data = [tempColumn]
column.dataType = tempColumn.dataType;
// depends on control dependency: [for], data = [tempColumn]
column.nullable = currentColumn.nullable;
// depends on control dependency: [for], data = [none]
result.add(column);
// depends on control dependency: [for], data = [none]
}
} else {
Column column = new Column();
column.name = currentColumn.name;
// depends on control dependency: [if], data = [none]
column.dataType = currentColumn.dataType;
// depends on control dependency: [if], data = [none]
column.nullable = currentColumn.nullable;
// depends on control dependency: [if], data = [none]
result.add(column);
// depends on control dependency: [if], data = [none]
}
}
return result;
} } |
public class class_name {
public void marshall(CreateEntityRecognizerRequest createEntityRecognizerRequest, ProtocolMarshaller protocolMarshaller) {
if (createEntityRecognizerRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createEntityRecognizerRequest.getRecognizerName(), RECOGNIZERNAME_BINDING);
protocolMarshaller.marshall(createEntityRecognizerRequest.getDataAccessRoleArn(), DATAACCESSROLEARN_BINDING);
protocolMarshaller.marshall(createEntityRecognizerRequest.getTags(), TAGS_BINDING);
protocolMarshaller.marshall(createEntityRecognizerRequest.getInputDataConfig(), INPUTDATACONFIG_BINDING);
protocolMarshaller.marshall(createEntityRecognizerRequest.getClientRequestToken(), CLIENTREQUESTTOKEN_BINDING);
protocolMarshaller.marshall(createEntityRecognizerRequest.getLanguageCode(), LANGUAGECODE_BINDING);
protocolMarshaller.marshall(createEntityRecognizerRequest.getVolumeKmsKeyId(), VOLUMEKMSKEYID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(CreateEntityRecognizerRequest createEntityRecognizerRequest, ProtocolMarshaller protocolMarshaller) {
if (createEntityRecognizerRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createEntityRecognizerRequest.getRecognizerName(), RECOGNIZERNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createEntityRecognizerRequest.getDataAccessRoleArn(), DATAACCESSROLEARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createEntityRecognizerRequest.getTags(), TAGS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createEntityRecognizerRequest.getInputDataConfig(), INPUTDATACONFIG_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createEntityRecognizerRequest.getClientRequestToken(), CLIENTREQUESTTOKEN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createEntityRecognizerRequest.getLanguageCode(), LANGUAGECODE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createEntityRecognizerRequest.getVolumeKmsKeyId(), VOLUMEKMSKEYID_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 String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader(WebConstants.HEADER_FROWARDED_FOR);
if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
if (ip.equals(LOCAL_BACK_IP)) {
/** 根据网卡取本机配置的IP */
ip = getLocalIpAddr();
}
}
/**
* 对于通过多个代理的情况, 第一个IP为客户端真实IP,多个IP按照','分割
* x-forwarded-for=192.168.2.22, 192.168.1.92
*/
if (ip != null && ip.length() > 15) {
String[] ips = StringUtils.split(ip, ",");
for (String _ip : ips) {
ip = StringUtils.trimToNull(_ip);
if(!UNKNOWN.equalsIgnoreCase(ip)){
return ip;
}
}
}
return ip;
} } | public class class_name {
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader(WebConstants.HEADER_FROWARDED_FOR);
if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP"); // depends on control dependency: [if], data = [none]
}
if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP"); // depends on control dependency: [if], data = [none]
}
if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr(); // depends on control dependency: [if], data = [none]
if (ip.equals(LOCAL_BACK_IP)) {
/** 根据网卡取本机配置的IP */
ip = getLocalIpAddr(); // depends on control dependency: [if], data = [none]
}
}
/**
* 对于通过多个代理的情况, 第一个IP为客户端真实IP,多个IP按照','分割
* x-forwarded-for=192.168.2.22, 192.168.1.92
*/
if (ip != null && ip.length() > 15) {
String[] ips = StringUtils.split(ip, ",");
for (String _ip : ips) {
ip = StringUtils.trimToNull(_ip); // depends on control dependency: [for], data = [_ip]
if(!UNKNOWN.equalsIgnoreCase(ip)){
return ip; // depends on control dependency: [if], data = [none]
}
}
}
return ip;
} } |
public class class_name {
public void marshall(LoadBalancer loadBalancer, ProtocolMarshaller protocolMarshaller) {
if (loadBalancer == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(loadBalancer.getName(), NAME_BINDING);
protocolMarshaller.marshall(loadBalancer.getArn(), ARN_BINDING);
protocolMarshaller.marshall(loadBalancer.getSupportCode(), SUPPORTCODE_BINDING);
protocolMarshaller.marshall(loadBalancer.getCreatedAt(), CREATEDAT_BINDING);
protocolMarshaller.marshall(loadBalancer.getLocation(), LOCATION_BINDING);
protocolMarshaller.marshall(loadBalancer.getResourceType(), RESOURCETYPE_BINDING);
protocolMarshaller.marshall(loadBalancer.getTags(), TAGS_BINDING);
protocolMarshaller.marshall(loadBalancer.getDnsName(), DNSNAME_BINDING);
protocolMarshaller.marshall(loadBalancer.getState(), STATE_BINDING);
protocolMarshaller.marshall(loadBalancer.getProtocol(), PROTOCOL_BINDING);
protocolMarshaller.marshall(loadBalancer.getPublicPorts(), PUBLICPORTS_BINDING);
protocolMarshaller.marshall(loadBalancer.getHealthCheckPath(), HEALTHCHECKPATH_BINDING);
protocolMarshaller.marshall(loadBalancer.getInstancePort(), INSTANCEPORT_BINDING);
protocolMarshaller.marshall(loadBalancer.getInstanceHealthSummary(), INSTANCEHEALTHSUMMARY_BINDING);
protocolMarshaller.marshall(loadBalancer.getTlsCertificateSummaries(), TLSCERTIFICATESUMMARIES_BINDING);
protocolMarshaller.marshall(loadBalancer.getConfigurationOptions(), CONFIGURATIONOPTIONS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(LoadBalancer loadBalancer, ProtocolMarshaller protocolMarshaller) {
if (loadBalancer == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(loadBalancer.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(loadBalancer.getArn(), ARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(loadBalancer.getSupportCode(), SUPPORTCODE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(loadBalancer.getCreatedAt(), CREATEDAT_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(loadBalancer.getLocation(), LOCATION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(loadBalancer.getResourceType(), RESOURCETYPE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(loadBalancer.getTags(), TAGS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(loadBalancer.getDnsName(), DNSNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(loadBalancer.getState(), STATE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(loadBalancer.getProtocol(), PROTOCOL_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(loadBalancer.getPublicPorts(), PUBLICPORTS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(loadBalancer.getHealthCheckPath(), HEALTHCHECKPATH_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(loadBalancer.getInstancePort(), INSTANCEPORT_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(loadBalancer.getInstanceHealthSummary(), INSTANCEHEALTHSUMMARY_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(loadBalancer.getTlsCertificateSummaries(), TLSCERTIFICATESUMMARIES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(loadBalancer.getConfigurationOptions(), CONFIGURATIONOPTIONS_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private PoolingOptions getPoolingOptions(Properties connectionProperties)
{
// minSimultaneousRequests, maxSimultaneousRequests, coreConnections,
// maxConnections
PoolingOptions options = new PoolingOptions();
String hostDistance = connectionProperties.getProperty("hostDistance");
String maxConnectionsPerHost = connectionProperties.getProperty("maxConnectionsPerHost");
String maxRequestsPerConnection = connectionProperties.getProperty("maxRequestsPerConnection");
String coreConnections = connectionProperties.getProperty("coreConnections");
if (!StringUtils.isBlank(hostDistance))
{
HostDistance hostDist = HostDistance.valueOf(hostDistance.toUpperCase());
if (!StringUtils.isBlank(coreConnections))
{
options.setCoreConnectionsPerHost(HostDistance.LOCAL, new Integer(coreConnections));
}
if (!StringUtils.isBlank(maxConnectionsPerHost))
{
options.setMaxConnectionsPerHost(hostDist, new Integer(maxConnectionsPerHost));
}
if (!StringUtils.isBlank(maxRequestsPerConnection))
{
options.setMaxRequestsPerConnection(hostDist, new Integer(maxRequestsPerConnection));
}
}
return options;
} } | public class class_name {
private PoolingOptions getPoolingOptions(Properties connectionProperties)
{
// minSimultaneousRequests, maxSimultaneousRequests, coreConnections,
// maxConnections
PoolingOptions options = new PoolingOptions();
String hostDistance = connectionProperties.getProperty("hostDistance");
String maxConnectionsPerHost = connectionProperties.getProperty("maxConnectionsPerHost");
String maxRequestsPerConnection = connectionProperties.getProperty("maxRequestsPerConnection");
String coreConnections = connectionProperties.getProperty("coreConnections");
if (!StringUtils.isBlank(hostDistance))
{
HostDistance hostDist = HostDistance.valueOf(hostDistance.toUpperCase());
if (!StringUtils.isBlank(coreConnections))
{
options.setCoreConnectionsPerHost(HostDistance.LOCAL, new Integer(coreConnections)); // depends on control dependency: [if], data = [none]
}
if (!StringUtils.isBlank(maxConnectionsPerHost))
{
options.setMaxConnectionsPerHost(hostDist, new Integer(maxConnectionsPerHost)); // depends on control dependency: [if], data = [none]
}
if (!StringUtils.isBlank(maxRequestsPerConnection))
{
options.setMaxRequestsPerConnection(hostDist, new Integer(maxRequestsPerConnection)); // depends on control dependency: [if], data = [none]
}
}
return options;
} } |
public class class_name {
Token nextToken(Token tkn) throws IOException {
wsBuf.clear(); // resuse
// get the last read char (required for empty line detection)
int lastChar = in.readAgain();
// read the next char and set eol
/* note: unfourtunately isEndOfLine may consumes a character silently.
* this has no effect outside of the method. so a simple workaround
* is to call 'readAgain' on the stream...
* uh: might using objects instead of base-types (jdk1.5 autoboxing!)
*/
int c = in.read();
boolean eol = isEndOfLine(c);
c = in.readAgain();
// empty line detection: eol AND (last char was EOL or beginning)
while (strategy.getIgnoreEmptyLines() && eol && (lastChar == '\n' || lastChar == ExtendedBufferedReader.UNDEFINED) && !isEndOfFile(lastChar)) {
// go on char ahead ...
lastChar = c;
c = in.read();
eol = isEndOfLine(c);
c = in.readAgain();
// reached end of file without any content (empty line at the end)
if (isEndOfFile(c)) {
tkn.type = TT_EOF;
return tkn;
}
}
// did we reached eof during the last iteration already ? TT_EOF
if (isEndOfFile(lastChar) || (lastChar != strategy.getDelimiter() && isEndOfFile(c))) {
tkn.type = TT_EOF;
return tkn;
}
// important: make sure a new char gets consumed in each iteration
while (!tkn.isReady) {
// ignore whitespaces at beginning of a token
while (isWhitespace(c) && !eol) {
wsBuf.append((char) c);
c = in.read();
eol = isEndOfLine(c);
}
// ok, start of token reached: comment, encapsulated, or token
if (c == strategy.getCommentStart()) {
// ignore everything till end of line and continue (incr linecount)
in.readLine();
tkn = nextToken(tkn.reset());
} else if (c == strategy.getDelimiter()) {
// empty token return TT_TOKEN("")
tkn.type = TT_TOKEN;
tkn.isReady = true;
} else if (eol) {
// empty token return TT_EORECORD("")
//noop: tkn.content.append("");
tkn.type = TT_EORECORD;
tkn.isReady = true;
} else if (c == strategy.getEncapsulator()) {
// consume encapsulated token
encapsulatedTokenLexer(tkn, c);
} else if (isEndOfFile(c)) {
// end of file return TT_EOF()
//noop: tkn.content.append("");
tkn.type = TT_EOF;
tkn.isReady = true;
} else {
// next token must be a simple token
// add removed blanks when not ignoring whitespace chars...
if (!strategy.getIgnoreLeadingWhitespaces()) {
tkn.content.append(wsBuf);
}
simpleTokenLexer(tkn, c);
}
}
return tkn;
} } | public class class_name {
Token nextToken(Token tkn) throws IOException {
wsBuf.clear(); // resuse
// get the last read char (required for empty line detection)
int lastChar = in.readAgain();
// read the next char and set eol
/* note: unfourtunately isEndOfLine may consumes a character silently.
* this has no effect outside of the method. so a simple workaround
* is to call 'readAgain' on the stream...
* uh: might using objects instead of base-types (jdk1.5 autoboxing!)
*/
int c = in.read();
boolean eol = isEndOfLine(c);
c = in.readAgain();
// empty line detection: eol AND (last char was EOL or beginning)
while (strategy.getIgnoreEmptyLines() && eol && (lastChar == '\n' || lastChar == ExtendedBufferedReader.UNDEFINED) && !isEndOfFile(lastChar)) {
// go on char ahead ...
lastChar = c;
c = in.read();
eol = isEndOfLine(c);
c = in.readAgain();
// reached end of file without any content (empty line at the end)
if (isEndOfFile(c)) {
tkn.type = TT_EOF; // depends on control dependency: [if], data = [none]
return tkn; // depends on control dependency: [if], data = [none]
}
}
// did we reached eof during the last iteration already ? TT_EOF
if (isEndOfFile(lastChar) || (lastChar != strategy.getDelimiter() && isEndOfFile(c))) {
tkn.type = TT_EOF;
return tkn;
}
// important: make sure a new char gets consumed in each iteration
while (!tkn.isReady) {
// ignore whitespaces at beginning of a token
while (isWhitespace(c) && !eol) {
wsBuf.append((char) c); // depends on control dependency: [while], data = [none]
c = in.read(); // depends on control dependency: [while], data = [none]
eol = isEndOfLine(c); // depends on control dependency: [while], data = [none]
}
// ok, start of token reached: comment, encapsulated, or token
if (c == strategy.getCommentStart()) {
// ignore everything till end of line and continue (incr linecount)
in.readLine(); // depends on control dependency: [if], data = [none]
tkn = nextToken(tkn.reset()); // depends on control dependency: [if], data = [none]
} else if (c == strategy.getDelimiter()) {
// empty token return TT_TOKEN("")
tkn.type = TT_TOKEN; // depends on control dependency: [if], data = [none]
tkn.isReady = true; // depends on control dependency: [if], data = [none]
} else if (eol) {
// empty token return TT_EORECORD("")
//noop: tkn.content.append("");
tkn.type = TT_EORECORD; // depends on control dependency: [if], data = [none]
tkn.isReady = true; // depends on control dependency: [if], data = [none]
} else if (c == strategy.getEncapsulator()) {
// consume encapsulated token
encapsulatedTokenLexer(tkn, c); // depends on control dependency: [if], data = [none]
} else if (isEndOfFile(c)) {
// end of file return TT_EOF()
//noop: tkn.content.append("");
tkn.type = TT_EOF; // depends on control dependency: [if], data = [none]
tkn.isReady = true; // depends on control dependency: [if], data = [none]
} else {
// next token must be a simple token
// add removed blanks when not ignoring whitespace chars...
if (!strategy.getIgnoreLeadingWhitespaces()) {
tkn.content.append(wsBuf); // depends on control dependency: [if], data = [none]
}
simpleTokenLexer(tkn, c); // depends on control dependency: [if], data = [none]
}
}
return tkn;
} } |
public class class_name {
protected ObjectData collectObjectData(
CmsCmisCallContext context,
CmsObject cms,
CmsResource resource,
Set<String> filter,
String renditionFilter,
boolean includeAllowableActions,
boolean includeAcl,
IncludeRelationships includeRelationships)
throws CmsException {
ObjectDataImpl result = new ObjectDataImpl();
ObjectInfoImpl objectInfo = new ObjectInfoImpl();
result.setProperties(collectProperties(cms, resource, filter, objectInfo));
if (includeAllowableActions) {
result.setAllowableActions(collectAllowableActions(cms, resource));
}
if (includeAcl) {
result.setAcl(collectAcl(cms, resource, true));
result.setIsExactAcl(Boolean.FALSE);
}
if ((includeRelationships != null) && (includeRelationships != IncludeRelationships.NONE)) {
RelationshipDirection direction;
if (includeRelationships == IncludeRelationships.SOURCE) {
direction = RelationshipDirection.SOURCE;
} else if (includeRelationships == IncludeRelationships.TARGET) {
direction = RelationshipDirection.TARGET;
} else {
direction = RelationshipDirection.EITHER;
}
List<ObjectData> relationData = m_repository.getRelationshipObjectData(
context,
cms,
resource,
direction,
CmsCmisUtil.splitFilter("*"),
false);
result.setRelationships(relationData);
}
result.setRenditions(collectRenditions(cms, resource, renditionFilter, objectInfo));
if (context.isObjectInfoRequired()) {
objectInfo.setObject(result);
context.getObjectInfoHandler().addObjectInfo(objectInfo);
}
return result;
} } | public class class_name {
protected ObjectData collectObjectData(
CmsCmisCallContext context,
CmsObject cms,
CmsResource resource,
Set<String> filter,
String renditionFilter,
boolean includeAllowableActions,
boolean includeAcl,
IncludeRelationships includeRelationships)
throws CmsException {
ObjectDataImpl result = new ObjectDataImpl();
ObjectInfoImpl objectInfo = new ObjectInfoImpl();
result.setProperties(collectProperties(cms, resource, filter, objectInfo));
if (includeAllowableActions) {
result.setAllowableActions(collectAllowableActions(cms, resource));
}
if (includeAcl) {
result.setAcl(collectAcl(cms, resource, true));
result.setIsExactAcl(Boolean.FALSE);
}
if ((includeRelationships != null) && (includeRelationships != IncludeRelationships.NONE)) {
RelationshipDirection direction;
if (includeRelationships == IncludeRelationships.SOURCE) {
direction = RelationshipDirection.SOURCE;
// depends on control dependency: [if], data = [none]
} else if (includeRelationships == IncludeRelationships.TARGET) {
direction = RelationshipDirection.TARGET;
// depends on control dependency: [if], data = [none]
} else {
direction = RelationshipDirection.EITHER;
// depends on control dependency: [if], data = [none]
}
List<ObjectData> relationData = m_repository.getRelationshipObjectData(
context,
cms,
resource,
direction,
CmsCmisUtil.splitFilter("*"),
false);
result.setRelationships(relationData);
}
result.setRenditions(collectRenditions(cms, resource, renditionFilter, objectInfo));
if (context.isObjectInfoRequired()) {
objectInfo.setObject(result);
context.getObjectInfoHandler().addObjectInfo(objectInfo);
}
return result;
} } |
public class class_name {
public Set<Class<?>> findAndAddClassesInPackageByFile(String packageName, String packagePath,
final boolean recursive) {
LOGGER.debug("扫描包{}下、目录{}下的所有class", packageName, packagePath);
Set<Class<?>> classes = new LinkedHashSet<>();
// 获取此包的目录 建立一个File
File dir = new File(packagePath);
// 如果不存在或者 也不是目录就直接返回
if (!dir.exists() || !dir.isDirectory()) {
LOGGER.debug("用户定义包名 " + packageName + " 下没有任何文件");
return Collections.emptySet();
}
// 如果存在 就获取包下的所有文件 包括目录
File[] dirfiles = dir.listFiles(file -> (recursive && file.isDirectory())
|| (file.getName().endsWith("" + "" + ".class")));
if (dirfiles == null || dirfiles.length == 0) {
return Collections.emptySet();
}
// 循环所有文件
for (File file : dirfiles) {
// 如果是目录 则继续扫描
if (file.isDirectory()) {
classes.addAll(findAndAddClassesInPackageByFile(packageName + "/" + file.getName(),
file.getAbsolutePath(), recursive));
} else {
// 如果是java类文件 去掉后面的.class 只留下类名
String className = file.getName().substring(0, file.getName().length() - 6);
try {
packageName = packageName.replaceAll("/", ".");
className = packageName + '.' + className;
classes.add(classLoader.loadClass(className));
} catch (Throwable e) {
LOGGER.error("添加用户自定义视图类错误 找不到此类的.class文件", e);
}
}
}
return classes;
} } | public class class_name {
public Set<Class<?>> findAndAddClassesInPackageByFile(String packageName, String packagePath,
final boolean recursive) {
LOGGER.debug("扫描包{}下、目录{}下的所有class", packageName, packagePath);
Set<Class<?>> classes = new LinkedHashSet<>();
// 获取此包的目录 建立一个File
File dir = new File(packagePath);
// 如果不存在或者 也不是目录就直接返回
if (!dir.exists() || !dir.isDirectory()) {
LOGGER.debug("用户定义包名 " + packageName + " 下没有任何文件"); // depends on control dependency: [if], data = [none]
return Collections.emptySet(); // depends on control dependency: [if], data = [none]
}
// 如果存在 就获取包下的所有文件 包括目录
File[] dirfiles = dir.listFiles(file -> (recursive && file.isDirectory())
|| (file.getName().endsWith("" + "" + ".class")));
if (dirfiles == null || dirfiles.length == 0) {
return Collections.emptySet(); // depends on control dependency: [if], data = [none]
}
// 循环所有文件
for (File file : dirfiles) {
// 如果是目录 则继续扫描
if (file.isDirectory()) {
classes.addAll(findAndAddClassesInPackageByFile(packageName + "/" + file.getName(),
file.getAbsolutePath(), recursive)); // depends on control dependency: [if], data = [none]
} else {
// 如果是java类文件 去掉后面的.class 只留下类名
String className = file.getName().substring(0, file.getName().length() - 6);
try {
packageName = packageName.replaceAll("/", "."); // depends on control dependency: [try], data = [none]
className = packageName + '.' + className; // depends on control dependency: [try], data = [none]
classes.add(classLoader.loadClass(className)); // depends on control dependency: [try], data = [none]
} catch (Throwable e) {
LOGGER.error("添加用户自定义视图类错误 找不到此类的.class文件", e);
} // depends on control dependency: [catch], data = [none]
}
}
return classes;
} } |
public class class_name {
public ResultSet withRows(Row... rows) {
if (this.rows == null) {
setRows(new java.util.ArrayList<Row>(rows.length));
}
for (Row ele : rows) {
this.rows.add(ele);
}
return this;
} } | public class class_name {
public ResultSet withRows(Row... rows) {
if (this.rows == null) {
setRows(new java.util.ArrayList<Row>(rows.length)); // depends on control dependency: [if], data = [none]
}
for (Row ele : rows) {
this.rows.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
long getSupplementaryFlags(ClassSymbol c) {
if (jrtIndex == null || !jrtIndex.isInJRT(c.classfile) || c.name == names.module_info) {
return 0;
}
if (supplementaryFlags == null) {
supplementaryFlags = new HashMap<>();
}
Long flags = supplementaryFlags.get(c.packge());
if (flags == null) {
long newFlags = 0;
try {
JRTIndex.CtSym ctSym = jrtIndex.getCtSym(c.packge().flatName());
Profile minProfile = Profile.DEFAULT;
if (ctSym.proprietary)
newFlags |= PROPRIETARY;
if (ctSym.minProfile != null)
minProfile = Profile.lookup(ctSym.minProfile);
if (profile != Profile.DEFAULT && minProfile.value > profile.value) {
newFlags |= NOT_IN_PROFILE;
}
} catch (IOException ignore) {
}
supplementaryFlags.put(c.packge(), flags = newFlags);
}
return flags;
} } | public class class_name {
long getSupplementaryFlags(ClassSymbol c) {
if (jrtIndex == null || !jrtIndex.isInJRT(c.classfile) || c.name == names.module_info) {
return 0; // depends on control dependency: [if], data = [none]
}
if (supplementaryFlags == null) {
supplementaryFlags = new HashMap<>(); // depends on control dependency: [if], data = [none]
}
Long flags = supplementaryFlags.get(c.packge());
if (flags == null) {
long newFlags = 0;
try {
JRTIndex.CtSym ctSym = jrtIndex.getCtSym(c.packge().flatName());
Profile minProfile = Profile.DEFAULT;
if (ctSym.proprietary)
newFlags |= PROPRIETARY;
if (ctSym.minProfile != null)
minProfile = Profile.lookup(ctSym.minProfile);
if (profile != Profile.DEFAULT && minProfile.value > profile.value) {
newFlags |= NOT_IN_PROFILE; // depends on control dependency: [if], data = [none]
}
} catch (IOException ignore) {
} // depends on control dependency: [catch], data = [none]
supplementaryFlags.put(c.packge(), flags = newFlags); // depends on control dependency: [if], data = [none]
}
return flags;
} } |
public class class_name {
private void changeReferenceDataValuesInComponents(final ReferenceData oldReferenceData,
final ReferenceData newReferenceData, final Class<?> referenceDataClass) {
final Collection<ComponentBuilder> componentBuilders = _analysisJobBuilder.getComponentBuilders();
for (final ComponentBuilder componentBuilder : componentBuilders) {
final Map<ConfiguredPropertyDescriptor, Object> configuredProperties =
componentBuilder.getConfiguredProperties();
for (final Map.Entry<ConfiguredPropertyDescriptor, Object> entry : configuredProperties.entrySet()) {
final ConfiguredPropertyDescriptor propertyDescriptor = entry.getKey();
if (referenceDataClass.isAssignableFrom(propertyDescriptor.getBaseType())) {
final Object valueObject = entry.getValue();
// In some cases the configured property is an array
if (valueObject.getClass().isArray()) {
final Object[] values = (Object[]) valueObject;
for (int i = 0; i < values.length; i++) {
if (oldReferenceData.equals(values[i])) {
// change the old value of the pattern in the
// array with the new value
values[i] = newReferenceData;
}
}
} else {
if (oldReferenceData.equals(valueObject)) {
componentBuilder.setConfiguredProperty(propertyDescriptor, newReferenceData);
}
}
}
}
}
} } | public class class_name {
private void changeReferenceDataValuesInComponents(final ReferenceData oldReferenceData,
final ReferenceData newReferenceData, final Class<?> referenceDataClass) {
final Collection<ComponentBuilder> componentBuilders = _analysisJobBuilder.getComponentBuilders();
for (final ComponentBuilder componentBuilder : componentBuilders) {
final Map<ConfiguredPropertyDescriptor, Object> configuredProperties =
componentBuilder.getConfiguredProperties();
for (final Map.Entry<ConfiguredPropertyDescriptor, Object> entry : configuredProperties.entrySet()) {
final ConfiguredPropertyDescriptor propertyDescriptor = entry.getKey();
if (referenceDataClass.isAssignableFrom(propertyDescriptor.getBaseType())) {
final Object valueObject = entry.getValue();
// In some cases the configured property is an array
if (valueObject.getClass().isArray()) {
final Object[] values = (Object[]) valueObject;
for (int i = 0; i < values.length; i++) {
if (oldReferenceData.equals(values[i])) {
// change the old value of the pattern in the
// array with the new value
values[i] = newReferenceData; // depends on control dependency: [if], data = [none]
}
}
} else {
if (oldReferenceData.equals(valueObject)) {
componentBuilder.setConfiguredProperty(propertyDescriptor, newReferenceData); // depends on control dependency: [if], data = [none]
}
}
}
}
}
} } |
public class class_name {
public void setConvertToXmlPage(boolean convertToXmlPage) {
if (LOG.isDebugEnabled()) {
LOG.debug(
Messages.get().getBundle().key(
Messages.LOG_IMPORTEXPORT_SET_CONVERT_PARAMETER_1,
Boolean.toString(convertToXmlPage)));
}
m_convertToXmlPage = convertToXmlPage;
} } | public class class_name {
public void setConvertToXmlPage(boolean convertToXmlPage) {
if (LOG.isDebugEnabled()) {
LOG.debug(
Messages.get().getBundle().key(
Messages.LOG_IMPORTEXPORT_SET_CONVERT_PARAMETER_1,
Boolean.toString(convertToXmlPage))); // depends on control dependency: [if], data = [none]
}
m_convertToXmlPage = convertToXmlPage;
} } |
public class class_name {
public I_CmsXmlDocument getRawContent() {
if (m_content == null) {
// content has not been provided, must unmarshal XML first
CmsFile file;
try {
file = m_cms.readFile(m_resource);
if (CmsResourceTypeXmlPage.isXmlPage(file)) {
// this is an XML page
m_content = CmsXmlPageFactory.unmarshal(m_cms, file);
} else {
// this is an XML content
m_content = CmsXmlContentFactory.unmarshal(m_cms, file);
}
} catch (CmsException e) {
// this usually should not happen, as the resource already has been read by the current user
// and we just upgrade it to a File
throw new CmsRuntimeException(
Messages.get().container(Messages.ERR_XML_CONTENT_UNMARSHAL_1, m_resource.getRootPath()),
e);
}
}
// make sure a valid locale is used
if (m_locale == null) {
m_locale = OpenCms.getLocaleManager().getBestMatchingLocale(
m_requestedLocale,
OpenCms.getLocaleManager().getDefaultLocales(m_cms, m_cms.getRequestContext().getUri()),
m_content.getLocales());
}
return m_content;
} } | public class class_name {
public I_CmsXmlDocument getRawContent() {
if (m_content == null) {
// content has not been provided, must unmarshal XML first
CmsFile file;
try {
file = m_cms.readFile(m_resource); // depends on control dependency: [try], data = [none]
if (CmsResourceTypeXmlPage.isXmlPage(file)) {
// this is an XML page
m_content = CmsXmlPageFactory.unmarshal(m_cms, file); // depends on control dependency: [if], data = [none]
} else {
// this is an XML content
m_content = CmsXmlContentFactory.unmarshal(m_cms, file); // depends on control dependency: [if], data = [none]
}
} catch (CmsException e) {
// this usually should not happen, as the resource already has been read by the current user
// and we just upgrade it to a File
throw new CmsRuntimeException(
Messages.get().container(Messages.ERR_XML_CONTENT_UNMARSHAL_1, m_resource.getRootPath()),
e);
} // depends on control dependency: [catch], data = [none]
}
// make sure a valid locale is used
if (m_locale == null) {
m_locale = OpenCms.getLocaleManager().getBestMatchingLocale(
m_requestedLocale,
OpenCms.getLocaleManager().getDefaultLocales(m_cms, m_cms.getRequestContext().getUri()),
m_content.getLocales()); // depends on control dependency: [if], data = [none]
}
return m_content;
} } |
public class class_name {
public static Object newInstanceForClassName(final String className) {
try {
return newInstance(Class.forName(className));
} catch (Exception ex) {
throw new Error(String.format("Can't create instance of %s for error %s", className, ex.getMessage()), ex);
}
} } | public class class_name {
public static Object newInstanceForClassName(final String className) {
try {
return newInstance(Class.forName(className)); // depends on control dependency: [try], data = [none]
} catch (Exception ex) {
throw new Error(String.format("Can't create instance of %s for error %s", className, ex.getMessage()), ex);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private int filterNondominatedSet(double[][] front, int noPoints, int noObjectives) {
int i, j;
int n;
n = noPoints;
i = 0;
while (i < n) {
j = i + 1;
while (j < n) {
if (dominates(front[i], front[j], noObjectives)) {
/* remove point 'j' */
n--;
swap(front, j, n);
} else if (dominates(front[j], front[i], noObjectives)) {
/* remove point 'i'; ensure that the point copied to index 'i'
is considered in the next outer loop (thus, decrement i) */
n--;
swap(front, i, n);
i--;
break;
} else {
j++;
}
}
i++;
}
return n;
} } | public class class_name {
private int filterNondominatedSet(double[][] front, int noPoints, int noObjectives) {
int i, j;
int n;
n = noPoints;
i = 0;
while (i < n) {
j = i + 1; // depends on control dependency: [while], data = [none]
while (j < n) {
if (dominates(front[i], front[j], noObjectives)) {
/* remove point 'j' */
n--; // depends on control dependency: [if], data = [none]
swap(front, j, n); // depends on control dependency: [if], data = [none]
} else if (dominates(front[j], front[i], noObjectives)) {
/* remove point 'i'; ensure that the point copied to index 'i'
is considered in the next outer loop (thus, decrement i) */
n--; // depends on control dependency: [if], data = [none]
swap(front, i, n); // depends on control dependency: [if], data = [none]
i--; // depends on control dependency: [if], data = [none]
break;
} else {
j++; // depends on control dependency: [if], data = [none]
}
}
i++; // depends on control dependency: [while], data = [none]
}
return n;
} } |
public class class_name {
@Override
public void start() {
synchronized (this) {
if (result != TimeoutResult.NEW) {
throw new IllegalStateException("Start called twice on the same timeout");
}
startTime = System.nanoTime();
result = TimeoutResult.STARTED;
if (!policy.getTimeout().isZero()) {
timeoutFuture = executorService.schedule(this::timeout, asClampedNanos(policy.getTimeout()), TimeUnit.NANOSECONDS);
}
}
} } | public class class_name {
@Override
public void start() {
synchronized (this) {
if (result != TimeoutResult.NEW) {
throw new IllegalStateException("Start called twice on the same timeout");
}
startTime = System.nanoTime();
result = TimeoutResult.STARTED;
if (!policy.getTimeout().isZero()) {
timeoutFuture = executorService.schedule(this::timeout, asClampedNanos(policy.getTimeout()), TimeUnit.NANOSECONDS); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public <T extends ViewHandler<R>> T processing(boolean flag) {
lock.lock();
try {
setProcessing(flag);
return (T)this;
}
finally {
lock.unlock();
}
} } | public class class_name {
public <T extends ViewHandler<R>> T processing(boolean flag) {
lock.lock();
try {
setProcessing(flag); // depends on control dependency: [try], data = [none]
return (T)this; // depends on control dependency: [try], data = [none]
}
finally {
lock.unlock();
}
} } |
public class class_name {
@SuppressWarnings("unchecked")
protected CaseFileInstance internalGetCaseFileInstance(String caseId, String deploymentId) {
logger.debug("Retrieving case file from working memory for case " + caseId);
Collection<CaseFileInstance> caseFiles = (Collection<CaseFileInstance>) processService.execute(deploymentId, CaseContext.get(caseId), commandsFactory.newGetObjects(new ClassObjectFilter(CaseFileInstance.class)));
if (caseFiles.size() == 0) {
throw new CaseNotFoundException("Case with id " + caseId + " was not found");
} else if (caseFiles.size() == 1) {
CaseFileInstance caseFile = caseFiles.iterator().next();
logger.debug("Single case file {} found in working memory", caseFile);
// apply authorization
Map<String, Object> filteredData = authorizationManager.filterByDataAuthorization(caseId, caseFile, caseFile.getData());
((CaseFileInstanceImpl)caseFile).setData(filteredData);
for (Object variable : caseFile.getData().values()) {
if (variable instanceof LazyLoaded<?>) {
((LazyLoaded<?>) variable).load();
}
}
return caseFile;
}
logger.warn("Multiple case files found in working memory (most likely not using PER_CASE strategy), trying to filter out...");
CaseFileInstance caseFile = caseFiles.stream()
.filter(cf -> cf.getCaseId().equals(caseId))
.findFirst()
.orElse(null);
logger.warn("Case file {} after filtering {}", caseFile, (caseFile == null?"not found" : "found"));
if (caseFile != null) {
// apply authorization
Map<String, Object> filteredData = authorizationManager.filterByDataAuthorization(caseId, caseFile, caseFile.getData());
((CaseFileInstanceImpl)caseFile).setData(filteredData);
for (Object variable : caseFile.getData().values()) {
if (variable instanceof LazyLoaded<?>) {
((LazyLoaded<?>) variable).load();
}
}
}
return caseFile;
} } | public class class_name {
@SuppressWarnings("unchecked")
protected CaseFileInstance internalGetCaseFileInstance(String caseId, String deploymentId) {
logger.debug("Retrieving case file from working memory for case " + caseId);
Collection<CaseFileInstance> caseFiles = (Collection<CaseFileInstance>) processService.execute(deploymentId, CaseContext.get(caseId), commandsFactory.newGetObjects(new ClassObjectFilter(CaseFileInstance.class)));
if (caseFiles.size() == 0) {
throw new CaseNotFoundException("Case with id " + caseId + " was not found");
} else if (caseFiles.size() == 1) {
CaseFileInstance caseFile = caseFiles.iterator().next();
logger.debug("Single case file {} found in working memory", caseFile); // depends on control dependency: [if], data = [none]
// apply authorization
Map<String, Object> filteredData = authorizationManager.filterByDataAuthorization(caseId, caseFile, caseFile.getData());
((CaseFileInstanceImpl)caseFile).setData(filteredData); // depends on control dependency: [if], data = [none]
for (Object variable : caseFile.getData().values()) {
if (variable instanceof LazyLoaded<?>) {
((LazyLoaded<?>) variable).load(); // depends on control dependency: [if], data = [)]
}
}
return caseFile; // depends on control dependency: [if], data = [none]
}
logger.warn("Multiple case files found in working memory (most likely not using PER_CASE strategy), trying to filter out...");
CaseFileInstance caseFile = caseFiles.stream()
.filter(cf -> cf.getCaseId().equals(caseId))
.findFirst()
.orElse(null);
logger.warn("Case file {} after filtering {}", caseFile, (caseFile == null?"not found" : "found"));
if (caseFile != null) {
// apply authorization
Map<String, Object> filteredData = authorizationManager.filterByDataAuthorization(caseId, caseFile, caseFile.getData());
((CaseFileInstanceImpl)caseFile).setData(filteredData); // depends on control dependency: [if], data = [none]
for (Object variable : caseFile.getData().values()) {
if (variable instanceof LazyLoaded<?>) {
((LazyLoaded<?>) variable).load(); // depends on control dependency: [if], data = [)]
}
}
}
return caseFile;
} } |
public class class_name {
public void renameNodesInTree(String oldName, String newName) {
List<Node> nodes = getNodesFromTreeByName(oldName);
Iterator i = nodes.iterator();
while (i.hasNext()) {
Node n = (Node) i.next();
n.setName(newName);
}
} } | public class class_name {
public void renameNodesInTree(String oldName, String newName) {
List<Node> nodes = getNodesFromTreeByName(oldName);
Iterator i = nodes.iterator();
while (i.hasNext()) {
Node n = (Node) i.next();
n.setName(newName);
// depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
public static boolean nonDitaContext(final Deque<DitaClass> classes) {
final Iterator<DitaClass> it = classes.iterator();
it.next(); // Skip first, because we're checking if current element is inside non-DITA context
while (it.hasNext()) {
final DitaClass cls = it.next();
if (cls != null && cls.isValid() &&
(TOPIC_FOREIGN.matches(cls) || TOPIC_UNKNOWN.matches(cls))) {
return true;
} else if (cls != null && cls.isValid()) {
return false;
}
}
return false;
} } | public class class_name {
public static boolean nonDitaContext(final Deque<DitaClass> classes) {
final Iterator<DitaClass> it = classes.iterator();
it.next(); // Skip first, because we're checking if current element is inside non-DITA context
while (it.hasNext()) {
final DitaClass cls = it.next();
if (cls != null && cls.isValid() &&
(TOPIC_FOREIGN.matches(cls) || TOPIC_UNKNOWN.matches(cls))) {
return true; // depends on control dependency: [if], data = [none]
} else if (cls != null && cls.isValid()) {
return false; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
scope_ifname = null;
scope_ifname_set = false;
if (getClass().getClassLoader() != Class.class.getClassLoader()) {
throw new SecurityException ("invalid address type");
}
s.defaultReadObject();
if (ifname != null && !"".equals (ifname)) {
try {
scope_ifname = NetworkInterface.getByName(ifname);
if (scope_ifname == null) {
/* the interface does not exist on this system, so we clear
* the scope information completely */
scope_id_set = false;
scope_ifname_set = false;
scope_id = 0;
} else {
try {
scope_id = deriveNumericScope (scope_ifname);
} catch (UnknownHostException e) {
// typically should not happen, but it may be that
// the machine being used for deserialization has
// the same interface name but without IPv6 configured.
}
}
} catch (SocketException e) {}
}
/* if ifname was not supplied, then the numeric info is used */
ipaddress = ipaddress.clone();
// Check that our invariants are satisfied
if (ipaddress.length != INADDRSZ) {
throw new InvalidObjectException("invalid address length: "+
ipaddress.length);
}
if (holder().getFamily() != AF_INET6) {
throw new InvalidObjectException("invalid address family type");
}
} } | public class class_name {
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
scope_ifname = null;
scope_ifname_set = false;
if (getClass().getClassLoader() != Class.class.getClassLoader()) {
throw new SecurityException ("invalid address type");
}
s.defaultReadObject();
if (ifname != null && !"".equals (ifname)) {
try {
scope_ifname = NetworkInterface.getByName(ifname); // depends on control dependency: [try], data = [none]
if (scope_ifname == null) {
/* the interface does not exist on this system, so we clear
* the scope information completely */
scope_id_set = false; // depends on control dependency: [if], data = [none]
scope_ifname_set = false; // depends on control dependency: [if], data = [none]
scope_id = 0; // depends on control dependency: [if], data = [none]
} else {
try {
scope_id = deriveNumericScope (scope_ifname); // depends on control dependency: [try], data = [none]
} catch (UnknownHostException e) {
// typically should not happen, but it may be that
// the machine being used for deserialization has
// the same interface name but without IPv6 configured.
} // depends on control dependency: [catch], data = [none]
}
} catch (SocketException e) {} // depends on control dependency: [catch], data = [none]
}
/* if ifname was not supplied, then the numeric info is used */
ipaddress = ipaddress.clone();
// Check that our invariants are satisfied
if (ipaddress.length != INADDRSZ) {
throw new InvalidObjectException("invalid address length: "+
ipaddress.length);
}
if (holder().getFamily() != AF_INET6) {
throw new InvalidObjectException("invalid address family type");
}
} } |
public class class_name {
public static JavadocHelper create(JavacTask mainTask, Collection<? extends Path> sourceLocations) {
StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
try {
fm.setLocationFromPaths(StandardLocation.SOURCE_PATH, sourceLocations);
return new OnDemandJavadocHelper(mainTask, fm);
} catch (IOException ex) {
try {
fm.close();
} catch (IOException closeEx) {
}
return new JavadocHelper() {
@Override
public String getResolvedDocComment(Element forElement) throws IOException {
return null;
}
@Override
public Element getSourceElement(Element forElement) throws IOException {
return forElement;
}
@Override
public void close() throws IOException {}
};
}
} } | public class class_name {
public static JavadocHelper create(JavacTask mainTask, Collection<? extends Path> sourceLocations) {
StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
try {
fm.setLocationFromPaths(StandardLocation.SOURCE_PATH, sourceLocations); // depends on control dependency: [try], data = [none]
return new OnDemandJavadocHelper(mainTask, fm); // depends on control dependency: [try], data = [none]
} catch (IOException ex) {
try {
fm.close(); // depends on control dependency: [try], data = [none]
} catch (IOException closeEx) {
} // depends on control dependency: [catch], data = [none]
return new JavadocHelper() {
@Override
public String getResolvedDocComment(Element forElement) throws IOException {
return null;
}
@Override
public Element getSourceElement(Element forElement) throws IOException {
return forElement;
} // depends on control dependency: [catch], data = [none]
@Override
public void close() throws IOException {}
};
}
} } |
public class class_name {
public String getScreenURL()
{
String strURL = super.getScreenURL();
try {
if ((this.getHeaderRecord() != null)
&& (this.getHeaderRecord() != this.getMainRecord())
&& ((this.getHeaderRecord().getEditMode() == Constants.EDIT_IN_PROGRESS) || (this.getHeaderRecord().getEditMode() == Constants.EDIT_CURRENT)))
strURL = this.addURLParam(strURL, DBParams.HEADER_OBJECT_ID, this.getHeaderRecord().getHandle(DBConstants.BOOKMARK_HANDLE).toString());
//x else if (this.getProperty(DBParams.HEADEROBJECTID) != null)
//x strURL = this.addURLParam(strURL, DBParams.HEADER_OBJECT_ID, this.getProperty(DBParams.HEADER_OBJECT_ID));
} catch (DBException ex) {
ex.printStackTrace();
}
Map<String,Object> properties = this.getTask().getApplication().getProperties();
if (properties != null)
{ // Add any database properties to the url, so the created tables use this alternate db.
for (String key : properties.keySet())
{
if (key.endsWith(BaseDatabase.DBSHARED_PARAM_SUFFIX))
if (strURL.indexOf(key) == -1)
strURL = Utility.addURLParam(strURL, key, properties.get(key).toString());
if (key.endsWith(BaseDatabase.DBUSER_PARAM_SUFFIX))
if (strURL.indexOf(key) == -1)
strURL = Utility.addURLParam(strURL, key, properties.get(key).toString());
}
}
return strURL;
} } | public class class_name {
public String getScreenURL()
{
String strURL = super.getScreenURL();
try {
if ((this.getHeaderRecord() != null)
&& (this.getHeaderRecord() != this.getMainRecord())
&& ((this.getHeaderRecord().getEditMode() == Constants.EDIT_IN_PROGRESS) || (this.getHeaderRecord().getEditMode() == Constants.EDIT_CURRENT)))
strURL = this.addURLParam(strURL, DBParams.HEADER_OBJECT_ID, this.getHeaderRecord().getHandle(DBConstants.BOOKMARK_HANDLE).toString());
//x else if (this.getProperty(DBParams.HEADEROBJECTID) != null)
//x strURL = this.addURLParam(strURL, DBParams.HEADER_OBJECT_ID, this.getProperty(DBParams.HEADER_OBJECT_ID));
} catch (DBException ex) {
ex.printStackTrace();
} // depends on control dependency: [catch], data = [none]
Map<String,Object> properties = this.getTask().getApplication().getProperties();
if (properties != null)
{ // Add any database properties to the url, so the created tables use this alternate db.
for (String key : properties.keySet())
{
if (key.endsWith(BaseDatabase.DBSHARED_PARAM_SUFFIX))
if (strURL.indexOf(key) == -1)
strURL = Utility.addURLParam(strURL, key, properties.get(key).toString());
if (key.endsWith(BaseDatabase.DBUSER_PARAM_SUFFIX))
if (strURL.indexOf(key) == -1)
strURL = Utility.addURLParam(strURL, key, properties.get(key).toString());
}
}
return strURL;
} } |
public class class_name {
private void outputMemberInjections(GinjectorBindings bindings, FragmentMap fragments,
SourceWriteUtil sourceWriteUtil) {
NameGenerator nameGenerator = bindings.getNameGenerator();
for (TypeLiteral<?> type : bindings.getMemberInjectRequests()) {
if (!reachabilityAnalyzer.isReachableMemberInject(bindings, type)) {
continue;
}
List<InjectorMethod> memberInjectionHelpers = new ArrayList<InjectorMethod>();
try {
sourceWriteUtil.createMemberInjection(type, nameGenerator, memberInjectionHelpers);
outputMethods(memberInjectionHelpers, fragments);
} catch (NoSourceNameException e) {
errorManager.logError(e.getMessage(), e);
}
}
} } | public class class_name {
private void outputMemberInjections(GinjectorBindings bindings, FragmentMap fragments,
SourceWriteUtil sourceWriteUtil) {
NameGenerator nameGenerator = bindings.getNameGenerator();
for (TypeLiteral<?> type : bindings.getMemberInjectRequests()) {
if (!reachabilityAnalyzer.isReachableMemberInject(bindings, type)) {
continue;
}
List<InjectorMethod> memberInjectionHelpers = new ArrayList<InjectorMethod>();
try {
sourceWriteUtil.createMemberInjection(type, nameGenerator, memberInjectionHelpers); // depends on control dependency: [try], data = [none]
outputMethods(memberInjectionHelpers, fragments); // depends on control dependency: [try], data = [none]
} catch (NoSourceNameException e) {
errorManager.logError(e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public CompleteLayerUploadRequest withLayerDigests(String... layerDigests) {
if (this.layerDigests == null) {
setLayerDigests(new java.util.ArrayList<String>(layerDigests.length));
}
for (String ele : layerDigests) {
this.layerDigests.add(ele);
}
return this;
} } | public class class_name {
public CompleteLayerUploadRequest withLayerDigests(String... layerDigests) {
if (this.layerDigests == null) {
setLayerDigests(new java.util.ArrayList<String>(layerDigests.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : layerDigests) {
this.layerDigests.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public static String encodeString(String s)
{
if (s != null && s.length() != 0)
{
try
{
final byte[] encode = Base64.encode(s.getBytes(DATA_ENCODING));
return new String(encode, BYTE_ENCODING);
} catch (UnsupportedEncodingException e)
{
VdmDebugPlugin.log(e);
}
}
return EMPTY;
} } | public class class_name {
public static String encodeString(String s)
{
if (s != null && s.length() != 0)
{
try
{
final byte[] encode = Base64.encode(s.getBytes(DATA_ENCODING));
return new String(encode, BYTE_ENCODING); // depends on control dependency: [try], data = [none]
} catch (UnsupportedEncodingException e)
{
VdmDebugPlugin.log(e);
} // depends on control dependency: [catch], data = [none]
}
return EMPTY;
} } |
public class class_name {
private void processScript() {
ScriptReaderBase scr = null;
try {
if (database.isFilesInJar()
|| fa.isStreamElement(scriptFileName)) {
scr = ScriptReaderBase.newScriptReader(database,
scriptFileName,
scriptFormat);
Session session =
database.sessionManager.getSysSessionForScript(database);
scr.readAll(session);
scr.close();
}
} catch (Throwable e) {
if (scr != null) {
scr.close();
if (cache != null) {
cache.close(false);
}
closeAllTextCaches(false);
}
database.logger.appLog.logContext(e, null);
if (e instanceof HsqlException) {
throw (HsqlException) e;
} else if (e instanceof IOException) {
throw Error.error(ErrorCode.FILE_IO_ERROR, e.toString());
} else if (e instanceof OutOfMemoryError) {
throw Error.error(ErrorCode.OUT_OF_MEMORY);
} else {
throw Error.error(ErrorCode.GENERAL_ERROR, e.toString());
}
}
} } | public class class_name {
private void processScript() {
ScriptReaderBase scr = null;
try {
if (database.isFilesInJar()
|| fa.isStreamElement(scriptFileName)) {
scr = ScriptReaderBase.newScriptReader(database,
scriptFileName,
scriptFormat); // depends on control dependency: [if], data = [none]
Session session =
database.sessionManager.getSysSessionForScript(database);
scr.readAll(session); // depends on control dependency: [if], data = [none]
scr.close(); // depends on control dependency: [if], data = [none]
}
} catch (Throwable e) {
if (scr != null) {
scr.close(); // depends on control dependency: [if], data = [none]
if (cache != null) {
cache.close(false); // depends on control dependency: [if], data = [none]
}
closeAllTextCaches(false); // depends on control dependency: [if], data = [none]
}
database.logger.appLog.logContext(e, null);
if (e instanceof HsqlException) {
throw (HsqlException) e;
} else if (e instanceof IOException) {
throw Error.error(ErrorCode.FILE_IO_ERROR, e.toString());
} else if (e instanceof OutOfMemoryError) {
throw Error.error(ErrorCode.OUT_OF_MEMORY);
} else {
throw Error.error(ErrorCode.GENERAL_ERROR, e.toString());
}
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public Method getJavaMethod(Class<?> clazz, String methodName, Class... parameterTypes) {
String clazzName = clazz.getName();
String methodKey = buildMethodKey(clazzName, methodName, parameterTypes);
Method method = methodCache.get(methodKey);
if (null == method) {
getFastClass(clazz);// 分析一次clazz,这时会跟新methodCache
return methodCache.get(methodKey);
} else {
return method;
}
} } | public class class_name {
public Method getJavaMethod(Class<?> clazz, String methodName, Class... parameterTypes) {
String clazzName = clazz.getName();
String methodKey = buildMethodKey(clazzName, methodName, parameterTypes);
Method method = methodCache.get(methodKey);
if (null == method) {
getFastClass(clazz);// 分析一次clazz,这时会跟新methodCache // depends on control dependency: [if], data = [none]
return methodCache.get(methodKey); // depends on control dependency: [if], data = [none]
} else {
return method; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected byte[] parseJsp(
byte[] byteContent,
String encoding,
CmsFlexController controller,
Set<String> updatedFiles,
boolean isHardInclude) {
String content;
// make sure encoding is set correctly
try {
content = new String(byteContent, encoding);
} catch (UnsupportedEncodingException e) {
// encoding property is not set correctly
LOG.error(
Messages.get().getBundle().key(
Messages.LOG_UNSUPPORTED_ENC_1,
controller.getCurrentRequest().getElementUri()),
e);
try {
encoding = OpenCms.getSystemInfo().getDefaultEncoding();
content = new String(byteContent, encoding);
} catch (UnsupportedEncodingException e2) {
// should not happen since default encoding is always a valid encoding (checked during system startup)
content = new String(byteContent);
}
}
// parse for special %(link:...) macros
content = parseJspLinkMacros(content, controller);
// parse for special <%@cms file="..." %> tag
content = parseJspCmsTag(content, controller, updatedFiles);
// parse for included files in tags
content = parseJspIncludes(content, controller, updatedFiles);
// parse for <%@page pageEncoding="..." %> tag
content = parseJspEncoding(content, encoding, isHardInclude);
// Processes magic taglib attributes in page directives
content = processTaglibAttributes(content);
// convert the result to bytes and return it
try {
return content.getBytes(encoding);
} catch (UnsupportedEncodingException e) {
// should not happen since encoding was already checked
return content.getBytes();
}
} } | public class class_name {
protected byte[] parseJsp(
byte[] byteContent,
String encoding,
CmsFlexController controller,
Set<String> updatedFiles,
boolean isHardInclude) {
String content;
// make sure encoding is set correctly
try {
content = new String(byteContent, encoding); // depends on control dependency: [try], data = [none]
} catch (UnsupportedEncodingException e) {
// encoding property is not set correctly
LOG.error(
Messages.get().getBundle().key(
Messages.LOG_UNSUPPORTED_ENC_1,
controller.getCurrentRequest().getElementUri()),
e);
try {
encoding = OpenCms.getSystemInfo().getDefaultEncoding(); // depends on control dependency: [try], data = [none]
content = new String(byteContent, encoding); // depends on control dependency: [try], data = [none]
} catch (UnsupportedEncodingException e2) {
// should not happen since default encoding is always a valid encoding (checked during system startup)
content = new String(byteContent);
} // depends on control dependency: [catch], data = [none]
} // depends on control dependency: [catch], data = [none]
// parse for special %(link:...) macros
content = parseJspLinkMacros(content, controller);
// parse for special <%@cms file="..." %> tag
content = parseJspCmsTag(content, controller, updatedFiles);
// parse for included files in tags
content = parseJspIncludes(content, controller, updatedFiles);
// parse for <%@page pageEncoding="..." %> tag
content = parseJspEncoding(content, encoding, isHardInclude);
// Processes magic taglib attributes in page directives
content = processTaglibAttributes(content);
// convert the result to bytes and return it
try {
return content.getBytes(encoding); // depends on control dependency: [try], data = [none]
} catch (UnsupportedEncodingException e) {
// should not happen since encoding was already checked
return content.getBytes();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public List<Product> searchFor(final Optional<String> searchTerm) {
if (searchTerm.isPresent()) {
return products
.stream()
.filter(matchingProductsFor(searchTerm.get()))
.collect(toList());
} else {
return products;
}
} } | public class class_name {
public List<Product> searchFor(final Optional<String> searchTerm) {
if (searchTerm.isPresent()) {
return products
.stream()
.filter(matchingProductsFor(searchTerm.get()))
.collect(toList()); // depends on control dependency: [if], data = [none]
} else {
return products; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static Map<String, String> parseQueryString(String query) {
Map<String, String> queryMap = new HashMap<>();
if (query == null || query.isEmpty()) {
return queryMap;
}
// The query string should escape '&'.
String[] entries = query.split(String.valueOf(QUERY_SEPARATOR));
try {
for (String entry : entries) {
// There should be at most 2 parts, since key and value both should escape '='.
String[] parts = entry.split(String.valueOf(QUERY_KEY_VALUE_SEPARATOR));
if (parts.length == 0) {
// Skip this empty entry.
} else if (parts.length == 1) {
// There is no value part. Just use empty string as the value.
String key = URLDecoder.decode(parts[0], "UTF-8");
queryMap.put(key, "");
} else {
// Save the key and value.
String key = URLDecoder.decode(parts[0], "UTF-8");
String value = URLDecoder.decode(parts[1], "UTF-8");
queryMap.put(key, value);
}
}
} catch (UnsupportedEncodingException e) {
// This is unexpected.
throw new RuntimeException(e);
}
return queryMap;
} } | public class class_name {
public static Map<String, String> parseQueryString(String query) {
Map<String, String> queryMap = new HashMap<>();
if (query == null || query.isEmpty()) {
return queryMap; // depends on control dependency: [if], data = [none]
}
// The query string should escape '&'.
String[] entries = query.split(String.valueOf(QUERY_SEPARATOR));
try {
for (String entry : entries) {
// There should be at most 2 parts, since key and value both should escape '='.
String[] parts = entry.split(String.valueOf(QUERY_KEY_VALUE_SEPARATOR));
if (parts.length == 0) {
// Skip this empty entry.
} else if (parts.length == 1) {
// There is no value part. Just use empty string as the value.
String key = URLDecoder.decode(parts[0], "UTF-8");
queryMap.put(key, ""); // depends on control dependency: [if], data = [none]
} else {
// Save the key and value.
String key = URLDecoder.decode(parts[0], "UTF-8");
String value = URLDecoder.decode(parts[1], "UTF-8");
queryMap.put(key, value); // depends on control dependency: [if], data = [none]
}
}
} catch (UnsupportedEncodingException e) {
// This is unexpected.
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
return queryMap;
} } |
public class class_name {
public JBBPOut Long(final long... value) throws IOException {
assertNotEnded();
assertArrayNotNull(value);
if (this.processCommands) {
for (final long l : value) {
_writeLong(l);
}
}
return this;
} } | public class class_name {
public JBBPOut Long(final long... value) throws IOException {
assertNotEnded();
assertArrayNotNull(value);
if (this.processCommands) {
for (final long l : value) {
_writeLong(l); // depends on control dependency: [for], data = [l]
}
}
return this;
} } |
public class class_name {
public static byte[] messageDigest(String value) {
MessageDigest md5;
try {
md5 = MessageDigest.getInstance("MD5");
md5.update(value.getBytes("UTF-8"));
return md5.digest();
} catch (NoSuchAlgorithmException e) {
throw new SofaRpcRuntimeException("No such algorithm named md5", e);
} catch (UnsupportedEncodingException e) {
throw new SofaRpcRuntimeException("Unsupported encoding of" + value, e);
}
} } | public class class_name {
public static byte[] messageDigest(String value) {
MessageDigest md5;
try {
md5 = MessageDigest.getInstance("MD5"); // depends on control dependency: [try], data = [none]
md5.update(value.getBytes("UTF-8")); // depends on control dependency: [try], data = [none]
return md5.digest(); // depends on control dependency: [try], data = [none]
} catch (NoSuchAlgorithmException e) {
throw new SofaRpcRuntimeException("No such algorithm named md5", e);
} catch (UnsupportedEncodingException e) { // depends on control dependency: [catch], data = [none]
throw new SofaRpcRuntimeException("Unsupported encoding of" + value, e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void add(final Binding b) {
if (!disposedInd) {
if (bindings == null) {
bindings = new HashSet<>(4);
}
bindings.add(b);
return;
}
b.dispose();
} } | public class class_name {
public void add(final Binding b) {
if (!disposedInd) {
if (bindings == null) {
bindings = new HashSet<>(4); // depends on control dependency: [if], data = [none]
}
bindings.add(b); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
b.dispose();
} } |
public class class_name {
@Override
public LoadBalancerHealthCheck getLoadBalancerHealthCheck( @Nonnull String providerLBHealthCheckId, @Nullable String providerLoadBalancerId ) throws CloudException, InternalException {
APITrace.begin(provider, "LB.getLoadBalancerHealthCheck");
try {
Map<String, String> parameters = getELBParameters(getContext(), ELBMethod.DESCRIBE_LOAD_BALANCERS);
ELBMethod method;
NodeList blocks;
Document doc;
if( providerLoadBalancerId != null && providerLoadBalancerId.length() > 32 ) {
return null;
}
parameters.put("LoadBalancerNames.member.1", providerLoadBalancerId);
method = new ELBMethod(provider, getContext(), parameters);
try {
doc = method.invoke();
} catch( EC2Exception e ) {
String code = e.getCode();
if( code != null && code.equals("LoadBalancerNotFound") ) {
return null;
}
logger.error(e.getSummary());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("HealthCheck");
if( blocks.getLength() > 0 ) {
LoadBalancerHealthCheck lbhc = toLBHealthCheck(providerLoadBalancerId, blocks.item(0));
return lbhc;
}
return null;
} finally {
APITrace.end();
}
} } | public class class_name {
@Override
public LoadBalancerHealthCheck getLoadBalancerHealthCheck( @Nonnull String providerLBHealthCheckId, @Nullable String providerLoadBalancerId ) throws CloudException, InternalException {
APITrace.begin(provider, "LB.getLoadBalancerHealthCheck");
try {
Map<String, String> parameters = getELBParameters(getContext(), ELBMethod.DESCRIBE_LOAD_BALANCERS);
ELBMethod method;
NodeList blocks;
Document doc;
if( providerLoadBalancerId != null && providerLoadBalancerId.length() > 32 ) {
return null; // depends on control dependency: [if], data = [none]
}
parameters.put("LoadBalancerNames.member.1", providerLoadBalancerId);
method = new ELBMethod(provider, getContext(), parameters);
try {
doc = method.invoke(); // depends on control dependency: [try], data = [none]
} catch( EC2Exception e ) {
String code = e.getCode();
if( code != null && code.equals("LoadBalancerNotFound") ) {
return null; // depends on control dependency: [if], data = [none]
}
logger.error(e.getSummary());
throw new CloudException(e);
} // depends on control dependency: [catch], data = [none]
blocks = doc.getElementsByTagName("HealthCheck");
if( blocks.getLength() > 0 ) {
LoadBalancerHealthCheck lbhc = toLBHealthCheck(providerLoadBalancerId, blocks.item(0));
return lbhc; // depends on control dependency: [if], data = [none]
}
return null;
} finally {
APITrace.end();
}
} } |
public class class_name {
public void processRequest(RequestContext context, RequestSecurityProcessorChain processorChain) throws Exception {
Map<String, Expression> urlRestrictions = getUrlRestrictions();
if (MapUtils.isNotEmpty(urlRestrictions)) {
HttpServletRequest request = context.getRequest();
String requestUrl = getRequestUrl(context.getRequest());
logger.debug("Checking access restrictions for URL {}", requestUrl);
for (Map.Entry<String, Expression> entry : urlRestrictions.entrySet()) {
String urlPattern = entry.getKey();
Expression expression = entry.getValue();
if (pathMatcher.match(urlPattern, requestUrl)) {
logger.debug("Checking restriction [{} => {}]", requestUrl, expression.getExpressionString());
if (isAccessAllowed(request, expression)) {
logger.debug("Restriction [{}' => {}] evaluated to true for user: access allowed", requestUrl,
expression.getExpressionString());
break;
} else {
throw new AccessDeniedException("Restriction ['" + requestUrl + "' => " +
expression.getExpressionString() + "] evaluated to false " +
"for user: access denied");
}
}
}
}
processorChain.processRequest(context);
} } | public class class_name {
public void processRequest(RequestContext context, RequestSecurityProcessorChain processorChain) throws Exception {
Map<String, Expression> urlRestrictions = getUrlRestrictions();
if (MapUtils.isNotEmpty(urlRestrictions)) {
HttpServletRequest request = context.getRequest();
String requestUrl = getRequestUrl(context.getRequest());
logger.debug("Checking access restrictions for URL {}", requestUrl);
for (Map.Entry<String, Expression> entry : urlRestrictions.entrySet()) {
String urlPattern = entry.getKey();
Expression expression = entry.getValue();
if (pathMatcher.match(urlPattern, requestUrl)) {
logger.debug("Checking restriction [{} => {}]", requestUrl, expression.getExpressionString()); // depends on control dependency: [if], data = [none]
if (isAccessAllowed(request, expression)) {
logger.debug("Restriction [{}' => {}] evaluated to true for user: access allowed", requestUrl,
expression.getExpressionString()); // depends on control dependency: [if], data = [none]
break;
} else {
throw new AccessDeniedException("Restriction ['" + requestUrl + "' => " +
expression.getExpressionString() + "] evaluated to false " +
"for user: access denied");
}
}
}
}
processorChain.processRequest(context);
} } |
public class class_name {
public static Method[] getMethods(Class<?> componentInterface,
Class<?>[] businessInterfaces)
{
int numMethods = 0;
Method[] methods = null;
int numBusinessInterfaces = 0;
HashMap<String, Method> methodNameTable = new HashMap<String, Method>();
if (componentInterface != null)
{
methods = componentInterface.getMethods();
numMethods = methods.length;
}
if (businessInterfaces != null)
{
numBusinessInterfaces = businessInterfaces.length;
}
ArrayList<Method> result = new ArrayList<Method>(numMethods + (numBusinessInterfaces * 10));
//------------------------------------------------------------------------
// First, iterate over the component interface methods (i.e. list
// returned by "getMethods") and filter out methods belonging to the
// EJBObject and EJBLocalObject interface, static methods, and
// method synonyms.
//
// Method synonyms correspond to overrides. For all synonyms,
// keep the method instance declared on the most specific class.
// How do you determine the most specific class? Don't know.
// For now, if the method is declared on the interface class
// it always overrides others.
//------------------------------------------------------------------------
for (int i = 0; i < numMethods; i++)
{
Method m = methods[i];
// Filter out static methods
if (Modifier.isStatic(m.getModifiers())) {
continue;
}
String mKey = methodKey(m);
String interfaceName = m.getDeclaringClass().getName();
if (!interfaceName.equals("javax.ejb.EJBObject") && // f111627.1
!interfaceName.equals("javax.ejb.EJBLocalObject")) // f111627.1
{
Method synonym = methodNameTable.get(mKey);
if (synonym == null)
{
methodNameTable.put(mKey, m);
result.add(m);
}
else
{
// Method declared on most specific class wins
Class<?> mClass = m.getDeclaringClass();
Class<?> sClass = synonym.getDeclaringClass();
if (sClass.isAssignableFrom(mClass))
{
methodNameTable.put(mKey, m);
result.set(result.indexOf(synonym), m);
}
}
}
}
//------------------------------------------------------------------------
// Second, iterate over the business interface methods (i.e. list
// returned by "getMethods") and filter out static methods, and
// method synonyms. d366807.3
//
// Note: Business interfaces do NOT implement EJBObject or EJBLocalObject.
//------------------------------------------------------------------------
for (int i = 0; i < numBusinessInterfaces; ++i)
{
methods = businessInterfaces[i].getMethods();
numMethods = methods.length;
result.ensureCapacity(result.size() + numMethods);
for (int j = 0; j < numMethods; j++)
{
Method m = methods[j];
// Filter out static and bridge methods
if (Modifier.isStatic(m.getModifiers()) || m.isBridge()) {
continue;
}
// Filter out Object methods for No-Interface view F743-1756
Class<?> declaring = m.getDeclaringClass();
if (declaring == Object.class) {
continue;
}
String mKey = methodKey(m);
// d583041 - The container is responsible for implementing these
// methods, so do not include them in business interfaces.
if ((mKey.equals("equals(java.lang.Object,)") && m.getReturnType() == Boolean.TYPE) ||
(mKey.equals("hashCode()") && m.getReturnType() == Integer.TYPE))
{
continue;
}
Method synonym = methodNameTable.get(mKey);
if (synonym == null)
{
methodNameTable.put(mKey, m);
result.add(m);
}
else
{
// Method declared on most specific class wins
Class<?> mClass = m.getDeclaringClass();
Class<?> sClass = synonym.getDeclaringClass();
if (sClass.isAssignableFrom(mClass))
{
methodNameTable.put(mKey, m);
result.set(result.indexOf(synonym), m);
}
}
}
}
//------------------------------------------------------------------------
// Finally, return the methods sorted alphabetically.
//------------------------------------------------------------------------
return sortMethods(result);
} } | public class class_name {
public static Method[] getMethods(Class<?> componentInterface,
Class<?>[] businessInterfaces)
{
int numMethods = 0;
Method[] methods = null;
int numBusinessInterfaces = 0;
HashMap<String, Method> methodNameTable = new HashMap<String, Method>();
if (componentInterface != null)
{
methods = componentInterface.getMethods(); // depends on control dependency: [if], data = [none]
numMethods = methods.length; // depends on control dependency: [if], data = [none]
}
if (businessInterfaces != null)
{
numBusinessInterfaces = businessInterfaces.length; // depends on control dependency: [if], data = [none]
}
ArrayList<Method> result = new ArrayList<Method>(numMethods + (numBusinessInterfaces * 10));
//------------------------------------------------------------------------
// First, iterate over the component interface methods (i.e. list
// returned by "getMethods") and filter out methods belonging to the
// EJBObject and EJBLocalObject interface, static methods, and
// method synonyms.
//
// Method synonyms correspond to overrides. For all synonyms,
// keep the method instance declared on the most specific class.
// How do you determine the most specific class? Don't know.
// For now, if the method is declared on the interface class
// it always overrides others.
//------------------------------------------------------------------------
for (int i = 0; i < numMethods; i++)
{
Method m = methods[i];
// Filter out static methods
if (Modifier.isStatic(m.getModifiers())) {
continue;
}
String mKey = methodKey(m);
String interfaceName = m.getDeclaringClass().getName();
if (!interfaceName.equals("javax.ejb.EJBObject") && // f111627.1
!interfaceName.equals("javax.ejb.EJBLocalObject")) // f111627.1
{
Method synonym = methodNameTable.get(mKey);
if (synonym == null)
{
methodNameTable.put(mKey, m);
result.add(m);
}
else
{
// Method declared on most specific class wins
Class<?> mClass = m.getDeclaringClass();
Class<?> sClass = synonym.getDeclaringClass();
if (sClass.isAssignableFrom(mClass))
{
methodNameTable.put(mKey, m);
result.set(result.indexOf(synonym), m);
}
}
}
}
//------------------------------------------------------------------------
// Second, iterate over the business interface methods (i.e. list
// returned by "getMethods") and filter out static methods, and
// method synonyms. d366807.3
//
// Note: Business interfaces do NOT implement EJBObject or EJBLocalObject.
//------------------------------------------------------------------------
for (int i = 0; i < numBusinessInterfaces; ++i)
{
methods = businessInterfaces[i].getMethods();
numMethods = methods.length;
result.ensureCapacity(result.size() + numMethods);
for (int j = 0; j < numMethods; j++)
{
Method m = methods[j];
// Filter out static and bridge methods
if (Modifier.isStatic(m.getModifiers()) || m.isBridge()) {
continue;
}
// Filter out Object methods for No-Interface view F743-1756
Class<?> declaring = m.getDeclaringClass();
if (declaring == Object.class) {
continue;
}
String mKey = methodKey(m);
// d583041 - The container is responsible for implementing these
// methods, so do not include them in business interfaces.
if ((mKey.equals("equals(java.lang.Object,)") && m.getReturnType() == Boolean.TYPE) ||
(mKey.equals("hashCode()") && m.getReturnType() == Integer.TYPE))
{
continue;
}
Method synonym = methodNameTable.get(mKey);
if (synonym == null)
{
methodNameTable.put(mKey, m);
result.add(m);
}
else
{
// Method declared on most specific class wins
Class<?> mClass = m.getDeclaringClass();
Class<?> sClass = synonym.getDeclaringClass();
if (sClass.isAssignableFrom(mClass))
{
methodNameTable.put(mKey, m);
result.set(result.indexOf(synonym), m);
}
}
}
}
//------------------------------------------------------------------------
// Finally, return the methods sorted alphabetically.
//------------------------------------------------------------------------
return sortMethods(result);
} } |
public class class_name {
@Nonnull
@ReturnsMutableCopy
public ICommonsList <String> cancelUploadedFiles (@Nullable final String... aFieldNames)
{
final ICommonsList <String> ret = new CommonsArrayList <> ();
if (ArrayHelper.isNotEmpty (aFieldNames))
{
m_aRWLock.writeLocked ( () -> {
for (final String sFieldName : aFieldNames)
{
final TemporaryUserDataObject aUDO = m_aMap.remove (sFieldName);
if (aUDO != null)
{
_deleteUDO (aUDO);
ret.add (sFieldName);
}
}
});
}
return ret;
} } | public class class_name {
@Nonnull
@ReturnsMutableCopy
public ICommonsList <String> cancelUploadedFiles (@Nullable final String... aFieldNames)
{
final ICommonsList <String> ret = new CommonsArrayList <> ();
if (ArrayHelper.isNotEmpty (aFieldNames))
{
m_aRWLock.writeLocked ( () -> {
for (final String sFieldName : aFieldNames)
{
final TemporaryUserDataObject aUDO = m_aMap.remove (sFieldName);
if (aUDO != null)
{
_deleteUDO (aUDO); // depends on control dependency: [if], data = [(aUDO]
ret.add (sFieldName); // depends on control dependency: [if], data = [none]
}
}
});
}
return ret;
} } |
public class class_name {
public Object eval(Selector sel)
{
try
{
return eval(sel, MatchSpaceKey.DUMMY, EvalCache.DUMMY, null, false);
}
catch (BadMessageFormatMatchingException e)
{
// No FFDC Code Needed.
// FFDC driven by wrapper class.
FFDC.processException(this,
cclass,
"com.ibm.ws.sib.matchspace.selector.impl.Evaluator.eval",
e,
"1:145:1.28");
//TODO: Pass "sel" in FFDC or merely trace?
// This truly does not happen (see MatchSpaceKey.DUMMY)
throw new IllegalStateException(); // );
}
} } | public class class_name {
public Object eval(Selector sel)
{
try
{
return eval(sel, MatchSpaceKey.DUMMY, EvalCache.DUMMY, null, false); // depends on control dependency: [try], data = [none]
}
catch (BadMessageFormatMatchingException e)
{
// No FFDC Code Needed.
// FFDC driven by wrapper class.
FFDC.processException(this,
cclass,
"com.ibm.ws.sib.matchspace.selector.impl.Evaluator.eval",
e,
"1:145:1.28");
//TODO: Pass "sel" in FFDC or merely trace?
// This truly does not happen (see MatchSpaceKey.DUMMY)
throw new IllegalStateException(); // );
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private static void setParam(final SqlContext ctx, final String key, final String val) {
if (val.startsWith("[") && val.endsWith("]") && !(val.equals("[NULL]") || val.equals("[EMPTY]"))) {
// [] で囲まれた値は配列に変換する。ex) [1, 2] => {"1", "2"}
String[] parts = val.substring(1, val.length() - 1).split("\\s*,\\s*");
Object[] vals = new Object[parts.length];
for (int i = 0; i < parts.length; i++) {
vals[i] = convertSingleValue(parts[i]);
}
ctx.paramList(key, vals);
} else {
ctx.param(key, convertSingleValue(val));
}
} } | public class class_name {
private static void setParam(final SqlContext ctx, final String key, final String val) {
if (val.startsWith("[") && val.endsWith("]") && !(val.equals("[NULL]") || val.equals("[EMPTY]"))) {
// [] で囲まれた値は配列に変換する。ex) [1, 2] => {"1", "2"}
String[] parts = val.substring(1, val.length() - 1).split("\\s*,\\s*");
Object[] vals = new Object[parts.length];
for (int i = 0; i < parts.length; i++) {
vals[i] = convertSingleValue(parts[i]); // depends on control dependency: [for], data = [i]
}
ctx.paramList(key, vals); // depends on control dependency: [if], data = [none]
} else {
ctx.param(key, convertSingleValue(val)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected synchronized void compareReply(List<Long> processIds) {
Object[] replyIds = replyProcessIds.toArray();
for (Object replyId : replyIds) {
if (processIds.contains((Long) replyId) == false) { // 判断reply id是否在当前processId列表中
// 因为存在并发问题,如在执行Listener事件的同时,可能触发了process的创建,这时新建的processId会进入到reply队列中
// 此时接受到的processIds变量为上一个版本的内容,所以会删除新建的process,导致整个通道被挂住
if (CollectionUtils.isEmpty(processIds) == false) {
Long processId = processIds.get(0);
if (processId > (Long) replyId) { // 如果当前最小的processId都大于replyId, processId都是递增创建的
logger.info("## {} remove reply id [{}]", ClassUtils.getShortClassName(this.getClass()),
(Long) replyId);
replyProcessIds.remove((Long) replyId);
}
}
}
}
} } | public class class_name {
protected synchronized void compareReply(List<Long> processIds) {
Object[] replyIds = replyProcessIds.toArray();
for (Object replyId : replyIds) {
if (processIds.contains((Long) replyId) == false) { // 判断reply id是否在当前processId列表中
// 因为存在并发问题,如在执行Listener事件的同时,可能触发了process的创建,这时新建的processId会进入到reply队列中
// 此时接受到的processIds变量为上一个版本的内容,所以会删除新建的process,导致整个通道被挂住
if (CollectionUtils.isEmpty(processIds) == false) {
Long processId = processIds.get(0);
if (processId > (Long) replyId) { // 如果当前最小的processId都大于replyId, processId都是递增创建的
logger.info("## {} remove reply id [{}]", ClassUtils.getShortClassName(this.getClass()),
(Long) replyId); // depends on control dependency: [if], data = [none]
replyProcessIds.remove((Long) replyId); // depends on control dependency: [if], data = [(Long) replyId)]
}
}
}
}
} } |
public class class_name {
@Deprecated
private static DiscordRecord findBestDiscordWithHash(double[] series, int windowSize,
HashMap<String, ArrayList<Integer>> hash, VisitRegistry globalRegistry, double nThreshold)
throws Exception {
// we extract all seen words from the trie and sort them by the frequency decrease
ArrayList<FrequencyTableEntry> frequencies = hashToFreqEntries(hash);
Collections.sort(frequencies);
// init tracking variables
int bestSoFarPosition = -1;
double bestSoFarDistance = 0.0D;
String bestSoFarWord = "";
// discord search stats
int iterationCounter = 0;
int distanceCalls = 0;
// System.err.println(frequencies.size() + " left to iterate over");
while (!frequencies.isEmpty()) {
iterationCounter++;
// the head of this array has the rarest word
FrequencyTableEntry currentEntry = frequencies.remove(0);
// if (frequencies.size() % 10000 == 0) {
// System.err.println(frequencies.size() + " left to iterate over");
// }
String currentWord = String.valueOf(currentEntry.getStr());
int currentPos = currentEntry.getPosition();
// make sure it is not previously found discord passed through the parameters array
if (globalRegistry.isVisited(currentPos)) {
continue;
}
// all the candidates we are going to try
VisitRegistry randomRegistry = new VisitRegistry(series.length);
randomRegistry.markVisited(series.length - windowSize, series.length);
int markStart = currentPos - windowSize;
if (markStart < 0) {
markStart = 0;
}
int markEnd = currentPos + windowSize;
if (markEnd > series.length) {
markEnd = series.length;
}
randomRegistry.markVisited(markStart, markEnd);
LOGGER.trace("conducting search for {} at {}, iteration {}, to go: {}", currentWord,
currentPos, iterationCounter, frequencies.size());
// fix the current subsequence trace
double[] currentCandidateSeq = tp
.znorm(tp.subseriesByCopy(series, currentPos, currentPos + windowSize), nThreshold);
// let the search begin ..
double nearestNeighborDist = Double.MAX_VALUE;
boolean doRandomSearch = true;
// WE ARE GOING TO ITERATE OVER THE CURRENT WORD OCCURRENCES HERE FIRST
List<Integer> currentWordOccurrences = hash.get(currentWord);
for (Integer nextOccurrence : currentWordOccurrences) {
// just in case there is an overlap
if (randomRegistry.isVisited(nextOccurrence.intValue())) {
continue;
}
else {
randomRegistry.markVisited(nextOccurrence.intValue());
}
// get the subsequence and the distance
double[] occurrenceSubsequence = tp.znorm(
tp.subseriesByCopy(series, nextOccurrence, nextOccurrence + windowSize), nThreshold);
double dist = ed.distance(currentCandidateSeq, occurrenceSubsequence);
distanceCalls++;
// keep track of best so far distance
if (dist < nearestNeighborDist) {
nearestNeighborDist = dist;
LOGGER.trace(" ** current NN at {}, distance: {}, pos {}" + nextOccurrence,
nearestNeighborDist, currentPos);
}
if (dist < bestSoFarDistance) {
LOGGER.trace(" ** abandoning random visits loop, seen distance {} at iteration {}", dist,
bestSoFarDistance);
doRandomSearch = false;
break;
}
}
// check if we must continue with random neighbors
if (doRandomSearch) {
LOGGER.trace("starting random search");
int visitCounter = 0;
// while there are unvisited locations
int randomPos = -1;
while (-1 != (randomPos = randomRegistry.getNextRandomUnvisitedPosition())) {
randomRegistry.markVisited(randomPos);
double[] randomSubsequence = tp
.znorm(tp.subseriesByCopy(series, randomPos, randomPos + windowSize), nThreshold);
double dist = ed.distance(currentCandidateSeq, randomSubsequence);
distanceCalls++;
// early abandoning of the search:
// the current word is not discord, we have seen better
if (dist < bestSoFarDistance) {
nearestNeighborDist = dist;
LOGGER.trace(" ** abandoning random visits loop, seen distance {} at iteration {}",
nearestNeighborDist, visitCounter);
break;
}
// keep track
if (dist < nearestNeighborDist) {
LOGGER.trace(" ** current NN at {}, distance: {}, pos {}" + randomPos, dist,
currentPos);
nearestNeighborDist = dist;
}
visitCounter = visitCounter + 1;
} // while inner loop
} // end of random search loop
if (nearestNeighborDist > bestSoFarDistance) {
LOGGER.debug("discord updated: pos {}, dist {}", currentPos, bestSoFarDistance);
bestSoFarDistance = nearestNeighborDist;
bestSoFarPosition = currentPos;
bestSoFarWord = currentWord;
}
LOGGER.trace(" . . iterated {} times, best distance: {} for a string {} at {}",
iterationCounter, bestSoFarDistance, bestSoFarWord, bestSoFarPosition);
} // outer loop
LOGGER.trace("Distance calls: {}", distanceCalls);
DiscordRecord res = new DiscordRecord(bestSoFarPosition, bestSoFarDistance, bestSoFarWord);
res.setLength(windowSize);
res.setInfo("distance calls: " + distanceCalls);
return res;
} } | public class class_name {
@Deprecated
private static DiscordRecord findBestDiscordWithHash(double[] series, int windowSize,
HashMap<String, ArrayList<Integer>> hash, VisitRegistry globalRegistry, double nThreshold)
throws Exception {
// we extract all seen words from the trie and sort them by the frequency decrease
ArrayList<FrequencyTableEntry> frequencies = hashToFreqEntries(hash);
Collections.sort(frequencies);
// init tracking variables
int bestSoFarPosition = -1;
double bestSoFarDistance = 0.0D;
String bestSoFarWord = "";
// discord search stats
int iterationCounter = 0;
int distanceCalls = 0;
// System.err.println(frequencies.size() + " left to iterate over");
while (!frequencies.isEmpty()) {
iterationCounter++;
// the head of this array has the rarest word
FrequencyTableEntry currentEntry = frequencies.remove(0);
// if (frequencies.size() % 10000 == 0) {
// System.err.println(frequencies.size() + " left to iterate over");
// }
String currentWord = String.valueOf(currentEntry.getStr());
int currentPos = currentEntry.getPosition();
// make sure it is not previously found discord passed through the parameters array
if (globalRegistry.isVisited(currentPos)) {
continue;
}
// all the candidates we are going to try
VisitRegistry randomRegistry = new VisitRegistry(series.length);
randomRegistry.markVisited(series.length - windowSize, series.length);
int markStart = currentPos - windowSize;
if (markStart < 0) {
markStart = 0;
}
int markEnd = currentPos + windowSize;
if (markEnd > series.length) {
markEnd = series.length;
}
randomRegistry.markVisited(markStart, markEnd);
LOGGER.trace("conducting search for {} at {}, iteration {}, to go: {}", currentWord,
currentPos, iterationCounter, frequencies.size());
// fix the current subsequence trace
double[] currentCandidateSeq = tp
.znorm(tp.subseriesByCopy(series, currentPos, currentPos + windowSize), nThreshold);
// let the search begin ..
double nearestNeighborDist = Double.MAX_VALUE;
boolean doRandomSearch = true;
// WE ARE GOING TO ITERATE OVER THE CURRENT WORD OCCURRENCES HERE FIRST
List<Integer> currentWordOccurrences = hash.get(currentWord);
for (Integer nextOccurrence : currentWordOccurrences) {
// just in case there is an overlap
if (randomRegistry.isVisited(nextOccurrence.intValue())) {
continue;
}
else {
randomRegistry.markVisited(nextOccurrence.intValue()); // depends on control dependency: [if], data = [none]
}
// get the subsequence and the distance
double[] occurrenceSubsequence = tp.znorm(
tp.subseriesByCopy(series, nextOccurrence, nextOccurrence + windowSize), nThreshold);
double dist = ed.distance(currentCandidateSeq, occurrenceSubsequence);
distanceCalls++;
// keep track of best so far distance
if (dist < nearestNeighborDist) {
nearestNeighborDist = dist; // depends on control dependency: [if], data = [none]
LOGGER.trace(" ** current NN at {}, distance: {}, pos {}" + nextOccurrence, // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
nearestNeighborDist, currentPos);
}
if (dist < bestSoFarDistance) {
LOGGER.trace(" ** abandoning random visits loop, seen distance {} at iteration {}", dist, // depends on control dependency: [if], data = [none]
bestSoFarDistance);
doRandomSearch = false; // depends on control dependency: [if], data = [none]
break;
}
}
// check if we must continue with random neighbors
if (doRandomSearch) {
LOGGER.trace("starting random search");
int visitCounter = 0;
// while there are unvisited locations
int randomPos = -1;
while (-1 != (randomPos = randomRegistry.getNextRandomUnvisitedPosition())) {
randomRegistry.markVisited(randomPos); // depends on control dependency: [while], data = [none]
double[] randomSubsequence = tp
.znorm(tp.subseriesByCopy(series, randomPos, randomPos + windowSize), nThreshold);
double dist = ed.distance(currentCandidateSeq, randomSubsequence);
distanceCalls++; // depends on control dependency: [while], data = [none]
// early abandoning of the search:
// the current word is not discord, we have seen better
if (dist < bestSoFarDistance) {
nearestNeighborDist = dist; // depends on control dependency: [if], data = [none]
LOGGER.trace(" ** abandoning random visits loop, seen distance {} at iteration {}", // depends on control dependency: [if], data = [none]
nearestNeighborDist, visitCounter);
break;
}
// keep track
if (dist < nearestNeighborDist) {
LOGGER.trace(" ** current NN at {}, distance: {}, pos {}" + randomPos, dist, // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
currentPos);
nearestNeighborDist = dist; // depends on control dependency: [if], data = [none]
}
visitCounter = visitCounter + 1; // depends on control dependency: [while], data = [none]
} // while inner loop
} // end of random search loop
if (nearestNeighborDist > bestSoFarDistance) {
LOGGER.debug("discord updated: pos {}, dist {}", currentPos, bestSoFarDistance);
bestSoFarDistance = nearestNeighborDist;
bestSoFarPosition = currentPos;
bestSoFarWord = currentWord;
}
LOGGER.trace(" . . iterated {} times, best distance: {} for a string {} at {}",
iterationCounter, bestSoFarDistance, bestSoFarWord, bestSoFarPosition);
} // outer loop
LOGGER.trace("Distance calls: {}", distanceCalls);
DiscordRecord res = new DiscordRecord(bestSoFarPosition, bestSoFarDistance, bestSoFarWord);
res.setLength(windowSize);
res.setInfo("distance calls: " + distanceCalls);
return res;
} } |
public class class_name {
private void checkInvariants() {
for (int i = 0; i < tokens.size(); i++) {
Token token = tokens.get(i);
Preconditions.checkArgument(token.getID() == i + 1,
String.format("Tokens should be numbered consecutively, starting at 1: %s", token));
checkHead(token, token.getHead());
checkHead(token, token.getPHead());
}
} } | public class class_name {
private void checkInvariants() {
for (int i = 0; i < tokens.size(); i++) {
Token token = tokens.get(i);
Preconditions.checkArgument(token.getID() == i + 1,
String.format("Tokens should be numbered consecutively, starting at 1: %s", token)); // depends on control dependency: [for], data = [i]
checkHead(token, token.getHead()); // depends on control dependency: [for], data = [none]
checkHead(token, token.getPHead()); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
public static Predicates<Object> notIn(Iterable<?> iterable)
{
if (iterable instanceof SetIterable<?>)
{
return new NotInSetIterablePredicate((SetIterable<?>) iterable);
}
if (iterable instanceof Set<?>)
{
return new NotInSetPredicate((Set<?>) iterable);
}
if (iterable instanceof Collection<?> && ((Collection<?>) iterable).size() <= SMALL_COLLECTION_THRESHOLD)
{
return new NotInCollectionPredicate((Collection<?>) iterable);
}
return new NotInSetIterablePredicate(UnifiedSet.newSet(iterable));
} } | public class class_name {
public static Predicates<Object> notIn(Iterable<?> iterable)
{
if (iterable instanceof SetIterable<?>)
{
return new NotInSetIterablePredicate((SetIterable<?>) iterable); // depends on control dependency: [if], data = [)]
}
if (iterable instanceof Set<?>)
{
return new NotInSetPredicate((Set<?>) iterable); // depends on control dependency: [if], data = [)]
}
if (iterable instanceof Collection<?> && ((Collection<?>) iterable).size() <= SMALL_COLLECTION_THRESHOLD)
{
return new NotInCollectionPredicate((Collection<?>) iterable); // depends on control dependency: [if], data = [none]
}
return new NotInSetIterablePredicate(UnifiedSet.newSet(iterable));
} } |
public class class_name {
public static Media add_material(String access_token,MediaType mediaType,URI uri,Description description){
HttpPost httpPost = new HttpPost(BASE_URI+"/cgi-bin/material/add_material");
CloseableHttpClient tempHttpClient = HttpClients.createDefault();
try {
HttpEntity entity = tempHttpClient.execute(RequestBuilder.get().setUri(uri).build()).getEntity();
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
.addBinaryBody("media",EntityUtils.toByteArray(entity),ContentType.get(entity),"temp."+mediaType.fileSuffix());
if(description != null){
multipartEntityBuilder.addTextBody("description", JsonUtil.toJSONString(description),ContentType.create("text/plain",Charset.forName("utf-8")));
}
HttpEntity reqEntity = multipartEntityBuilder.addTextBody(PARAM_ACCESS_TOKEN, API.accessToken(access_token))
.addTextBody("type",mediaType.uploadType())
.build();
httpPost.setEntity(reqEntity);
return LocalHttpClient.executeJsonResult(httpPost,Media.class);
} catch (UnsupportedCharsetException e) {
logger.error("", e);
} catch (ClientProtocolException e) {
logger.error("", e);
} catch (ParseException e) {
logger.error("", e);
} catch (IOException e) {
logger.error("", e);
} finally{
try {
tempHttpClient.close();
} catch (IOException e) {
logger.error("", e);
}
}
return null;
} } | public class class_name {
public static Media add_material(String access_token,MediaType mediaType,URI uri,Description description){
HttpPost httpPost = new HttpPost(BASE_URI+"/cgi-bin/material/add_material");
CloseableHttpClient tempHttpClient = HttpClients.createDefault();
try {
HttpEntity entity = tempHttpClient.execute(RequestBuilder.get().setUri(uri).build()).getEntity();
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
.addBinaryBody("media",EntityUtils.toByteArray(entity),ContentType.get(entity),"temp."+mediaType.fileSuffix());
if(description != null){
multipartEntityBuilder.addTextBody("description", JsonUtil.toJSONString(description),ContentType.create("text/plain",Charset.forName("utf-8")));
// depends on control dependency: [if], data = [(description]
}
HttpEntity reqEntity = multipartEntityBuilder.addTextBody(PARAM_ACCESS_TOKEN, API.accessToken(access_token))
.addTextBody("type",mediaType.uploadType())
.build();
httpPost.setEntity(reqEntity);
// depends on control dependency: [try], data = [none]
return LocalHttpClient.executeJsonResult(httpPost,Media.class);
// depends on control dependency: [try], data = [none]
} catch (UnsupportedCharsetException e) {
logger.error("", e);
} catch (ClientProtocolException e) {
// depends on control dependency: [catch], data = [none]
logger.error("", e);
} catch (ParseException e) {
// depends on control dependency: [catch], data = [none]
logger.error("", e);
} catch (IOException e) {
// depends on control dependency: [catch], data = [none]
logger.error("", e);
} finally{
// depends on control dependency: [catch], data = [none]
try {
tempHttpClient.close();
// depends on control dependency: [try], data = [none]
} catch (IOException e) {
logger.error("", e);
}
// depends on control dependency: [catch], data = [none]
}
return null;
} } |
public class class_name {
private static String sanitizeSqlServerUrl(String jdbcUrl) {
StringBuilder result = new StringBuilder();
result.append(SQLSERVER_PREFIX);
String host;
if (jdbcUrl.contains(";")) {
host = StringUtils.substringBetween(jdbcUrl, SQLSERVER_PREFIX, ";");
} else {
host = StringUtils.substringAfter(jdbcUrl, SQLSERVER_PREFIX);
}
String queryString = StringUtils.substringAfter(jdbcUrl, ";");
Map<String, String> parameters = KeyValueFormat.parse(queryString);
Optional<String> server = firstValue(parameters, "serverName", "servername", "server");
if (server.isPresent()) {
result.append(server.get());
} else {
result.append(StringUtils.substringBefore(host, ":"));
}
Optional<String> port = firstValue(parameters, "portNumber", "port");
if (port.isPresent()) {
result.append(':').append(port.get());
} else if (host.contains(":")) {
result.append(':').append(StringUtils.substringAfter(host, ":"));
}
Optional<String> database = firstValue(parameters, "databaseName", "database");
database.ifPresent(s -> result.append('/').append(s));
return result.toString();
} } | public class class_name {
private static String sanitizeSqlServerUrl(String jdbcUrl) {
StringBuilder result = new StringBuilder();
result.append(SQLSERVER_PREFIX);
String host;
if (jdbcUrl.contains(";")) {
host = StringUtils.substringBetween(jdbcUrl, SQLSERVER_PREFIX, ";"); // depends on control dependency: [if], data = [none]
} else {
host = StringUtils.substringAfter(jdbcUrl, SQLSERVER_PREFIX); // depends on control dependency: [if], data = [none]
}
String queryString = StringUtils.substringAfter(jdbcUrl, ";");
Map<String, String> parameters = KeyValueFormat.parse(queryString);
Optional<String> server = firstValue(parameters, "serverName", "servername", "server");
if (server.isPresent()) {
result.append(server.get()); // depends on control dependency: [if], data = [none]
} else {
result.append(StringUtils.substringBefore(host, ":")); // depends on control dependency: [if], data = [none]
}
Optional<String> port = firstValue(parameters, "portNumber", "port");
if (port.isPresent()) {
result.append(':').append(port.get()); // depends on control dependency: [if], data = [none]
} else if (host.contains(":")) {
result.append(':').append(StringUtils.substringAfter(host, ":")); // depends on control dependency: [if], data = [none]
}
Optional<String> database = firstValue(parameters, "databaseName", "database");
database.ifPresent(s -> result.append('/').append(s));
return result.toString();
} } |
public class class_name {
public final void removeServer(String hostList) {
List<InetSocketAddress> addresses = AddrUtil.getAddresses(hostList);
if (addresses != null && addresses.size() > 0) {
for (InetSocketAddress address : addresses) {
removeAddr(address);
}
}
} } | public class class_name {
public final void removeServer(String hostList) {
List<InetSocketAddress> addresses = AddrUtil.getAddresses(hostList);
if (addresses != null && addresses.size() > 0) {
for (InetSocketAddress address : addresses) {
removeAddr(address); // depends on control dependency: [for], data = [address]
}
}
} } |
public class class_name {
public AtomContactSet getAtomContacts() {
AtomContactSet contacts = new AtomContactSet(cutoff);
List<Contact> list = getIndicesContacts();
if (jAtomObjects == null) {
for (Contact cont : list) {
contacts.add(new AtomContact(new Pair<Atom>(iAtomObjects[cont.getI()],iAtomObjects[cont.getJ()]),cont.getDistance()));
}
} else {
for (Contact cont : list) {
contacts.add(new AtomContact(new Pair<Atom>(iAtomObjects[cont.getI()],jAtomObjects[cont.getJ()]),cont.getDistance()));
}
}
return contacts;
} } | public class class_name {
public AtomContactSet getAtomContacts() {
AtomContactSet contacts = new AtomContactSet(cutoff);
List<Contact> list = getIndicesContacts();
if (jAtomObjects == null) {
for (Contact cont : list) {
contacts.add(new AtomContact(new Pair<Atom>(iAtomObjects[cont.getI()],iAtomObjects[cont.getJ()]),cont.getDistance())); // depends on control dependency: [for], data = [cont]
}
} else {
for (Contact cont : list) {
contacts.add(new AtomContact(new Pair<Atom>(iAtomObjects[cont.getI()],jAtomObjects[cont.getJ()]),cont.getDistance())); // depends on control dependency: [for], data = [cont]
}
}
return contacts;
} } |
public class class_name {
private void generateBuilderBasedConstructor(EclipseNode typeNode, TypeParameter[] typeParams, List<BuilderFieldData> builderFields,
EclipseNode sourceNode, String builderClassName, boolean callBuilderBasedSuperConstructor) {
ASTNode source = sourceNode.get();
TypeDeclaration typeDeclaration = ((TypeDeclaration) typeNode.get());
long p = (long) source.sourceStart << 32 | source.sourceEnd;
ConstructorDeclaration constructor = new ConstructorDeclaration(((CompilationUnitDeclaration) typeNode.top().get()).compilationResult);
constructor.modifiers = toEclipseModifier(AccessLevel.PROTECTED);
constructor.selector = typeDeclaration.name;
if (callBuilderBasedSuperConstructor) {
constructor.constructorCall = new ExplicitConstructorCall(ExplicitConstructorCall.Super);
constructor.constructorCall.arguments = new Expression[] {new SingleNameReference(BUILDER_VARIABLE_NAME, p)};
} else {
constructor.constructorCall = new ExplicitConstructorCall(ExplicitConstructorCall.ImplicitSuper);
}
constructor.constructorCall.sourceStart = source.sourceStart;
constructor.constructorCall.sourceEnd = source.sourceEnd;
constructor.thrownExceptions = null;
constructor.typeParameters = null;
constructor.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
constructor.bodyStart = constructor.declarationSourceStart = constructor.sourceStart = source.sourceStart;
constructor.bodyEnd = constructor.declarationSourceEnd = constructor.sourceEnd = source.sourceEnd;
TypeReference[] wildcards = new TypeReference[] {new Wildcard(Wildcard.UNBOUND), new Wildcard(Wildcard.UNBOUND)};
TypeReference builderType = new ParameterizedSingleTypeReference(builderClassName.toCharArray(), mergeToTypeReferences(typeParams, wildcards), 0, p);
constructor.arguments = new Argument[] {new Argument(BUILDER_VARIABLE_NAME, p, builderType, Modifier.FINAL)};
List<Statement> statements = new ArrayList<Statement>();
for (BuilderFieldData fieldNode : builderFields) {
char[] fieldName = removePrefixFromField(fieldNode.originalFieldNode);
FieldReference fieldInThis = new FieldReference(fieldNode.rawName, p);
int s = (int) (p >> 32);
int e = (int) p;
fieldInThis.receiver = new ThisReference(s, e);
Expression assignmentExpr;
if (fieldNode.singularData != null && fieldNode.singularData.getSingularizer() != null) {
fieldNode.singularData.getSingularizer().appendBuildCode(fieldNode.singularData, typeNode, statements, fieldNode.name, BUILDER_VARIABLE_NAME_STRING);
assignmentExpr = new SingleNameReference(fieldNode.name, p);
} else {
char[][] variableInBuilder = new char[][] {BUILDER_VARIABLE_NAME, fieldName};
long[] positions = new long[] {p, p};
assignmentExpr = new QualifiedNameReference(variableInBuilder, positions, s, e);
}
Statement assignment = new Assignment(fieldInThis, assignmentExpr, (int) p);
// In case of @Builder.Default, set the value to the default if it was NOT set in the builder.
if (fieldNode.nameOfSetFlag != null) {
char[][] setVariableInBuilder = new char[][] {BUILDER_VARIABLE_NAME, fieldNode.nameOfSetFlag};
long[] positions = new long[] {p, p};
QualifiedNameReference setVariableInBuilderRef = new QualifiedNameReference(setVariableInBuilder, positions, s, e);
MessageSend defaultMethodCall = new MessageSend();
defaultMethodCall.sourceStart = source.sourceStart;
defaultMethodCall.sourceEnd = source.sourceEnd;
defaultMethodCall.receiver = new SingleNameReference(((TypeDeclaration) typeNode.get()).name, 0L);
defaultMethodCall.selector = fieldNode.nameOfDefaultProvider;
defaultMethodCall.typeArguments = typeParameterNames(((TypeDeclaration) typeNode.get()).typeParameters);
Statement defaultAssignment = new Assignment(fieldInThis, defaultMethodCall, (int) p);
IfStatement ifBlockForDefault = new IfStatement(setVariableInBuilderRef, assignment, defaultAssignment, s, e);
statements.add(ifBlockForDefault);
} else {
statements.add(assignment);
}
if (hasNonNullAnnotations(fieldNode.originalFieldNode)) {
Statement nullCheck = generateNullCheck((FieldDeclaration) fieldNode.originalFieldNode.get(), sourceNode);
if (nullCheck != null) statements.add(nullCheck);
}
}
constructor.statements = statements.isEmpty() ? null : statements.toArray(new Statement[0]);
constructor.traverse(new SetGeneratedByVisitor(source), typeDeclaration.scope);
injectMethod(typeNode, constructor);
} } | public class class_name {
private void generateBuilderBasedConstructor(EclipseNode typeNode, TypeParameter[] typeParams, List<BuilderFieldData> builderFields,
EclipseNode sourceNode, String builderClassName, boolean callBuilderBasedSuperConstructor) {
ASTNode source = sourceNode.get();
TypeDeclaration typeDeclaration = ((TypeDeclaration) typeNode.get());
long p = (long) source.sourceStart << 32 | source.sourceEnd;
ConstructorDeclaration constructor = new ConstructorDeclaration(((CompilationUnitDeclaration) typeNode.top().get()).compilationResult);
constructor.modifiers = toEclipseModifier(AccessLevel.PROTECTED);
constructor.selector = typeDeclaration.name;
if (callBuilderBasedSuperConstructor) {
constructor.constructorCall = new ExplicitConstructorCall(ExplicitConstructorCall.Super); // depends on control dependency: [if], data = [none]
constructor.constructorCall.arguments = new Expression[] {new SingleNameReference(BUILDER_VARIABLE_NAME, p)}; // depends on control dependency: [if], data = [none]
} else {
constructor.constructorCall = new ExplicitConstructorCall(ExplicitConstructorCall.ImplicitSuper); // depends on control dependency: [if], data = [none]
}
constructor.constructorCall.sourceStart = source.sourceStart;
constructor.constructorCall.sourceEnd = source.sourceEnd;
constructor.thrownExceptions = null;
constructor.typeParameters = null;
constructor.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
constructor.bodyStart = constructor.declarationSourceStart = constructor.sourceStart = source.sourceStart;
constructor.bodyEnd = constructor.declarationSourceEnd = constructor.sourceEnd = source.sourceEnd;
TypeReference[] wildcards = new TypeReference[] {new Wildcard(Wildcard.UNBOUND), new Wildcard(Wildcard.UNBOUND)};
TypeReference builderType = new ParameterizedSingleTypeReference(builderClassName.toCharArray(), mergeToTypeReferences(typeParams, wildcards), 0, p);
constructor.arguments = new Argument[] {new Argument(BUILDER_VARIABLE_NAME, p, builderType, Modifier.FINAL)};
List<Statement> statements = new ArrayList<Statement>();
for (BuilderFieldData fieldNode : builderFields) {
char[] fieldName = removePrefixFromField(fieldNode.originalFieldNode);
FieldReference fieldInThis = new FieldReference(fieldNode.rawName, p);
int s = (int) (p >> 32);
int e = (int) p;
fieldInThis.receiver = new ThisReference(s, e); // depends on control dependency: [for], data = [none]
Expression assignmentExpr;
if (fieldNode.singularData != null && fieldNode.singularData.getSingularizer() != null) {
fieldNode.singularData.getSingularizer().appendBuildCode(fieldNode.singularData, typeNode, statements, fieldNode.name, BUILDER_VARIABLE_NAME_STRING); // depends on control dependency: [if], data = [(fieldNode.singularData]
assignmentExpr = new SingleNameReference(fieldNode.name, p); // depends on control dependency: [if], data = [none]
} else {
char[][] variableInBuilder = new char[][] {BUILDER_VARIABLE_NAME, fieldName};
long[] positions = new long[] {p, p};
assignmentExpr = new QualifiedNameReference(variableInBuilder, positions, s, e); // depends on control dependency: [if], data = [none]
}
Statement assignment = new Assignment(fieldInThis, assignmentExpr, (int) p);
// In case of @Builder.Default, set the value to the default if it was NOT set in the builder.
if (fieldNode.nameOfSetFlag != null) {
char[][] setVariableInBuilder = new char[][] {BUILDER_VARIABLE_NAME, fieldNode.nameOfSetFlag};
long[] positions = new long[] {p, p};
QualifiedNameReference setVariableInBuilderRef = new QualifiedNameReference(setVariableInBuilder, positions, s, e);
MessageSend defaultMethodCall = new MessageSend();
defaultMethodCall.sourceStart = source.sourceStart; // depends on control dependency: [if], data = [none]
defaultMethodCall.sourceEnd = source.sourceEnd; // depends on control dependency: [if], data = [none]
defaultMethodCall.receiver = new SingleNameReference(((TypeDeclaration) typeNode.get()).name, 0L); // depends on control dependency: [if], data = [none]
defaultMethodCall.selector = fieldNode.nameOfDefaultProvider; // depends on control dependency: [if], data = [none]
defaultMethodCall.typeArguments = typeParameterNames(((TypeDeclaration) typeNode.get()).typeParameters); // depends on control dependency: [if], data = [none]
Statement defaultAssignment = new Assignment(fieldInThis, defaultMethodCall, (int) p);
IfStatement ifBlockForDefault = new IfStatement(setVariableInBuilderRef, assignment, defaultAssignment, s, e);
statements.add(ifBlockForDefault); // depends on control dependency: [if], data = [none]
} else {
statements.add(assignment); // depends on control dependency: [if], data = [none]
}
if (hasNonNullAnnotations(fieldNode.originalFieldNode)) {
Statement nullCheck = generateNullCheck((FieldDeclaration) fieldNode.originalFieldNode.get(), sourceNode);
if (nullCheck != null) statements.add(nullCheck);
}
}
constructor.statements = statements.isEmpty() ? null : statements.toArray(new Statement[0]);
constructor.traverse(new SetGeneratedByVisitor(source), typeDeclaration.scope);
injectMethod(typeNode, constructor);
} } |
public class class_name {
@Override
public void writeVectorNumber(Vector<Double> vector) {
log.debug("writeVectorNumber: {}", vector);
buf.put(AMF3.TYPE_VECTOR_NUMBER);
if (hasReference(vector)) {
putInteger(getReferenceId(vector) << 1);
return;
}
storeReference(vector);
putInteger(vector.size() << 1 | 1);
putInteger(0);
buf.put((byte) 0x00);
for (Double v : vector) {
buf.putDouble(v);
}
} } | public class class_name {
@Override
public void writeVectorNumber(Vector<Double> vector) {
log.debug("writeVectorNumber: {}", vector);
buf.put(AMF3.TYPE_VECTOR_NUMBER);
if (hasReference(vector)) {
putInteger(getReferenceId(vector) << 1);
// depends on control dependency: [if], data = [none]
return;
// depends on control dependency: [if], data = [none]
}
storeReference(vector);
putInteger(vector.size() << 1 | 1);
putInteger(0);
buf.put((byte) 0x00);
for (Double v : vector) {
buf.putDouble(v);
// depends on control dependency: [for], data = [v]
}
} } |
public class class_name {
private Set<Class<?>> getClasses() {
HashSet<Class<?>> result = new HashSet<Class<?>>();
// in case of override only the last global configuration must be analyzed
JGlobalMap jGlobalMap = null;
for (Class<?> clazz : getAllsuperClasses(configuredClass)) {
// only if global configuration is null will be searched global configuration on super classes
if(isNull(jGlobalMap)){
jGlobalMap = clazz.getAnnotation(JGlobalMap.class);
//if the field configuration is defined in the global map
if(!isNull(jGlobalMap)){
addClasses(jGlobalMap.classes(),result);
if(!isNull(jGlobalMap.excluded()))
for (Field field : getListOfFields(configuredClass)){
JMap jMap = field.getAnnotation(JMap.class);
if(!isNull(jMap))
for (String fieldName : jGlobalMap.excluded())
if(field.getName().equals(fieldName))
addClasses(jMap.classes(),result,field.getName());
}
return result;
}
}
}
for (Field field : getListOfFields(configuredClass)){
JMap jMap = field.getAnnotation(JMap.class);
if(!isNull(jMap)) addClasses(jMap.classes(),result,field.getName());
}
return result;
} } | public class class_name {
private Set<Class<?>> getClasses() {
HashSet<Class<?>> result = new HashSet<Class<?>>();
// in case of override only the last global configuration must be analyzed
JGlobalMap jGlobalMap = null;
for (Class<?> clazz : getAllsuperClasses(configuredClass)) {
// only if global configuration is null will be searched global configuration on super classes
if(isNull(jGlobalMap)){
jGlobalMap = clazz.getAnnotation(JGlobalMap.class);
// depends on control dependency: [if], data = [none]
//if the field configuration is defined in the global map
if(!isNull(jGlobalMap)){
addClasses(jGlobalMap.classes(),result);
// depends on control dependency: [if], data = [none]
if(!isNull(jGlobalMap.excluded()))
for (Field field : getListOfFields(configuredClass)){
JMap jMap = field.getAnnotation(JMap.class);
if(!isNull(jMap))
for (String fieldName : jGlobalMap.excluded())
if(field.getName().equals(fieldName))
addClasses(jMap.classes(),result,field.getName());
}
return result;
// depends on control dependency: [if], data = [none]
}
}
}
for (Field field : getListOfFields(configuredClass)){
JMap jMap = field.getAnnotation(JMap.class);
if(!isNull(jMap)) addClasses(jMap.classes(),result,field.getName());
}
return result;
} } |
public class class_name {
private static String getVersion(final Class<?> clazz) {
CodeSource source = clazz.getProtectionDomain().getCodeSource();
URL location = source.getLocation();
try {
Path path = Paths.get(location.toURI());
return Files.isRegularFile(path) ? getVersionFromJar(path) : getVersionFromPom(path);
} catch (URISyntaxException ex) {
Logger.error(ex, "Unknown location: \"{}\"", location);
return null;
}
} } | public class class_name {
private static String getVersion(final Class<?> clazz) {
CodeSource source = clazz.getProtectionDomain().getCodeSource();
URL location = source.getLocation();
try {
Path path = Paths.get(location.toURI());
return Files.isRegularFile(path) ? getVersionFromJar(path) : getVersionFromPom(path); // depends on control dependency: [try], data = [none]
} catch (URISyntaxException ex) {
Logger.error(ex, "Unknown location: \"{}\"", location);
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public PropertyChangeListener[] getPropertyChangeListeners(String propertyName) {
List returnList = new ArrayList();
if (children != null) {
PropertyChangeSupport support = (PropertyChangeSupport) children.get(propertyName);
if (support != null) {
returnList.addAll(Arrays.asList(support.getPropertyChangeListeners()));
}
}
return (PropertyChangeListener[]) (returnList.toArray(new PropertyChangeListener[0]));
} } | public class class_name {
public PropertyChangeListener[] getPropertyChangeListeners(String propertyName) {
List returnList = new ArrayList();
if (children != null) {
PropertyChangeSupport support = (PropertyChangeSupport) children.get(propertyName);
if (support != null) {
returnList.addAll(Arrays.asList(support.getPropertyChangeListeners())); // depends on control dependency: [if], data = [(support]
}
}
return (PropertyChangeListener[]) (returnList.toArray(new PropertyChangeListener[0]));
} } |
public class class_name {
@Cmd
public String prompt(final String configKey, final String message) {
System.out.print(resolveProperty(message) + " "); //NOSONAR
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
String value = StringUtils.trim(in.readLine());
config.put(configKey, value);
return value;
// Stream nicht schliessen
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
} } | public class class_name {
@Cmd
public String prompt(final String configKey, final String message) {
System.out.print(resolveProperty(message) + " "); //NOSONAR
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
String value = StringUtils.trim(in.readLine());
config.put(configKey, value); // depends on control dependency: [try], data = [none]
return value; // depends on control dependency: [try], data = [none]
// Stream nicht schliessen
} catch (IOException ex) {
throw new IllegalStateException(ex);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static int subtract(int index0, int index1, int size) {
int distance = distanceP(index0, index1, size);
if( distance >= size/2+size%2 ) {
return distance-size;
} else {
return distance;
}
} } | public class class_name {
public static int subtract(int index0, int index1, int size) {
int distance = distanceP(index0, index1, size);
if( distance >= size/2+size%2 ) {
return distance-size; // depends on control dependency: [if], data = [none]
} else {
return distance; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void initializeChannels(GateDeploymentDescriptor descriptor) {
int numChannels = descriptor.getNumberOfChannelDescriptors();
this.channels = new OutputChannel[numChannels];
setChannelType(descriptor.getChannelType());
for (int i = 0; i < numChannels; i++) {
ChannelDeploymentDescriptor channelDescriptor = descriptor.getChannelDescriptor(i);
ChannelID id = channelDescriptor.getOutputChannelID();
ChannelID connectedId = channelDescriptor.getInputChannelID();
this.channels[i] = new OutputChannel(this, i, id, connectedId, getChannelType());
}
} } | public class class_name {
public void initializeChannels(GateDeploymentDescriptor descriptor) {
int numChannels = descriptor.getNumberOfChannelDescriptors();
this.channels = new OutputChannel[numChannels];
setChannelType(descriptor.getChannelType());
for (int i = 0; i < numChannels; i++) {
ChannelDeploymentDescriptor channelDescriptor = descriptor.getChannelDescriptor(i);
ChannelID id = channelDescriptor.getOutputChannelID();
ChannelID connectedId = channelDescriptor.getInputChannelID();
this.channels[i] = new OutputChannel(this, i, id, connectedId, getChannelType()); // depends on control dependency: [for], data = [i]
}
} } |
public class class_name {
public Reflect invoke(String methodName, Object... args) throws ReflectionException {
Class[] types = ReflectionUtils.getTypes(args);
try {
return on(clazz.getMethod(methodName, types), object, accessAll, args);
} catch (NoSuchMethodException e) {
Method method = ReflectionUtils.bestMatchingMethod(getMethods(), methodName, types);
if (method != null) {
return on(method, object, accessAll, args);
}
throw new ReflectionException(e);
}
} } | public class class_name {
public Reflect invoke(String methodName, Object... args) throws ReflectionException {
Class[] types = ReflectionUtils.getTypes(args);
try {
return on(clazz.getMethod(methodName, types), object, accessAll, args); // depends on control dependency: [try], data = [none]
} catch (NoSuchMethodException e) {
Method method = ReflectionUtils.bestMatchingMethod(getMethods(), methodName, types);
if (method != null) {
return on(method, object, accessAll, args); // depends on control dependency: [if], data = [(method]
}
throw new ReflectionException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private MediaTracker getTracker() {
// Opt: Only synchronize if trackerObj comes back null?
// If null, synchronize, re-check for null, and put new tracker
synchronized(this) {
if (tracker == null) {
@SuppressWarnings("serial")
Component comp = new Component() {};
tracker = new MediaTracker(comp);
}
}
return (MediaTracker) tracker;
} } | public class class_name {
private MediaTracker getTracker() {
// Opt: Only synchronize if trackerObj comes back null?
// If null, synchronize, re-check for null, and put new tracker
synchronized(this) {
if (tracker == null) {
@SuppressWarnings("serial")
Component comp = new Component() {};
tracker = new MediaTracker(comp); // depends on control dependency: [if], data = [none]
}
}
return (MediaTracker) tracker;
} } |
public class class_name {
public void postProcessMatches(DestinationHandler topicSpace,
String topic,
Object[] results,
int index)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "postProcessMatches","results: "+Arrays.toString(results)+";index: "+index + ";topic"+topic);
Set subRes = (Set) results[index];
Iterator itr = subRes.iterator();
if(authorization != null)
{
// If security is enabled then we'll do the permissions check
if(authorization.isBusSecure())
{
if(topicSpace != null &&
topicSpace.isTopicAccessCheckRequired()) // Bypass security checks
{
while (itr.hasNext())
{
MatchingConsumerDispatcher mcd = (MatchingConsumerDispatcher) itr.next();
ConsumerDispatcher cd = mcd.getConsumerDispatcher();
String userid = cd.getConsumerDispatcherState().getUser();
// We test whether the user is privileged only driving the full
// permission check if not.
if(!cd.getConsumerDispatcherState().isSIBServerSubject())
{
try
{
if(!authorization.
checkPermissionToSubscribe(topicSpace,
topic,
userid,
(TopicAclTraversalResults)results[MessageProcessorMatchTarget.ACL_TYPE]))
{
// Not authorized to subscribe to topic, need to remove from results
itr.remove();
}
}
catch (Exception e)
{
// No FFDC code needed
}
}
}
}
}
}
else
{
// Its a glitch and I need to feed this back.
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "postProcessMatches");
} } | public class class_name {
public void postProcessMatches(DestinationHandler topicSpace,
String topic,
Object[] results,
int index)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "postProcessMatches","results: "+Arrays.toString(results)+";index: "+index + ";topic"+topic);
Set subRes = (Set) results[index];
Iterator itr = subRes.iterator();
if(authorization != null)
{
// If security is enabled then we'll do the permissions check
if(authorization.isBusSecure())
{
if(topicSpace != null &&
topicSpace.isTopicAccessCheckRequired()) // Bypass security checks
{
while (itr.hasNext())
{
MatchingConsumerDispatcher mcd = (MatchingConsumerDispatcher) itr.next();
ConsumerDispatcher cd = mcd.getConsumerDispatcher();
String userid = cd.getConsumerDispatcherState().getUser();
// We test whether the user is privileged only driving the full
// permission check if not.
if(!cd.getConsumerDispatcherState().isSIBServerSubject())
{
try
{
if(!authorization.
checkPermissionToSubscribe(topicSpace,
topic,
userid,
(TopicAclTraversalResults)results[MessageProcessorMatchTarget.ACL_TYPE]))
{
// Not authorized to subscribe to topic, need to remove from results
itr.remove(); // depends on control dependency: [if], data = [none]
}
}
catch (Exception e)
{
// No FFDC code needed
} // depends on control dependency: [catch], data = [none]
}
}
}
}
}
else
{
// Its a glitch and I need to feed this back.
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "postProcessMatches");
} } |
public class class_name {
public void objectAvailable (T object)
{
// make sure life is not too cruel
if (_object != null) {
log.warning("Madre de dios! Our object came available but " +
"we've already got one!? " + this);
// go ahead and pitch the old one, God knows what's going on
_object = null;
}
if (!_pending) {
log.warning("J.C. on a pogo stick! Our object came available " +
"but we're not pending!? " + this);
// go with our badselves, it's the only way
}
// we're no longer pending
_pending = false;
// if we are no longer active, we don't want this damned thing
if (!_active) {
DObjectManager omgr = object.getManager();
// if the object's manager is null, that means the object is
// already destroyed and we need not trouble ourselves with
// unsubscription as it has already been pitched to the dogs
if (omgr != null) {
omgr.unsubscribeFromObject(_oid, this);
}
return;
}
// otherwise the air is fresh and clean and we can do our job
_object = object;
_subscriber.objectAvailable(object);
for (ChangeListener listener : _listeners) {
_object.addListener(listener);
}
} } | public class class_name {
public void objectAvailable (T object)
{
// make sure life is not too cruel
if (_object != null) {
log.warning("Madre de dios! Our object came available but " +
"we've already got one!? " + this);
// go ahead and pitch the old one, God knows what's going on
_object = null; // depends on control dependency: [if], data = [none]
}
if (!_pending) {
log.warning("J.C. on a pogo stick! Our object came available " +
"but we're not pending!? " + this); // depends on control dependency: [if], data = [none]
// go with our badselves, it's the only way
}
// we're no longer pending
_pending = false;
// if we are no longer active, we don't want this damned thing
if (!_active) {
DObjectManager omgr = object.getManager();
// if the object's manager is null, that means the object is
// already destroyed and we need not trouble ourselves with
// unsubscription as it has already been pitched to the dogs
if (omgr != null) {
omgr.unsubscribeFromObject(_oid, this); // depends on control dependency: [if], data = [none]
}
return; // depends on control dependency: [if], data = [none]
}
// otherwise the air is fresh and clean and we can do our job
_object = object;
_subscriber.objectAvailable(object);
for (ChangeListener listener : _listeners) {
_object.addListener(listener); // depends on control dependency: [for], data = [listener]
}
} } |
public class class_name {
public static <T> T findAncestor( Component start, Class<T> aClass )
{
if( start == null )
{
return null;
}
return findAtOrAbove( start.getParent(), aClass );
} } | public class class_name {
public static <T> T findAncestor( Component start, Class<T> aClass )
{
if( start == null )
{
return null; // depends on control dependency: [if], data = [none]
}
return findAtOrAbove( start.getParent(), aClass );
} } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.