code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
---|---|
public class class_name {
private static void delete(GeoPackageCore geoPackage, String table) {
ExtensionsDao extensionsDao = geoPackage.getExtensionsDao();
try {
if (extensionsDao.isTableExists()) {
extensionsDao.deleteByTableName(table);
}
} catch (SQLException e) {
throw new GeoPackageException(
"Failed to delete Table extensions. GeoPackage: "
+ geoPackage.getName() + ", Table: " + table, e);
}
} } | public class class_name {
private static void delete(GeoPackageCore geoPackage, String table) {
ExtensionsDao extensionsDao = geoPackage.getExtensionsDao();
try {
if (extensionsDao.isTableExists()) {
extensionsDao.deleteByTableName(table); // depends on control dependency: [if], data = [none]
}
} catch (SQLException e) {
throw new GeoPackageException(
"Failed to delete Table extensions. GeoPackage: "
+ geoPackage.getName() + ", Table: " + table, e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private Connection createConnection() {
if (mConnInfo != null) {
DBConnCreator dbConnCreator = new DBConnCreator(mConnInfo);
Connection conn = dbConnCreator.createDBConnection();
return conn;
} else if (mDbcpPropertyFile != null) {
Properties properties = new Properties();
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(mDbcpPropertyFile);
try {
properties.load(is);
DataSource ds;
ds = BasicDataSourceFactory.createDataSource(properties);
Connection conn = ds.getConnection();
return conn;
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
} } | public class class_name {
private Connection createConnection() {
if (mConnInfo != null) {
DBConnCreator dbConnCreator = new DBConnCreator(mConnInfo);
Connection conn = dbConnCreator.createDBConnection();
return conn; // depends on control dependency: [if], data = [none]
} else if (mDbcpPropertyFile != null) {
Properties properties = new Properties();
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(mDbcpPropertyFile);
try {
properties.load(is); // depends on control dependency: [try], data = [none]
DataSource ds;
ds = BasicDataSourceFactory.createDataSource(properties); // depends on control dependency: [try], data = [none]
Connection conn = ds.getConnection();
return conn; // depends on control dependency: [try], data = [none]
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) { // depends on control dependency: [catch], data = [none]
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
}
return null;
} } |
public class class_name {
public void answerReceived(JSONObject remoteSDP, String remoteConnection) {
if (isActive()) {
incomingSDP = remoteSDP;
toConnection = remoteConnection;
try {
JSONObject signalData = new JSONObject("{'signalType':'connected','version':'1.0'}");
signalData.put("target", directConnectionOnly ? "directConnection" : "call");
signalData.put("connectionId", toConnection);
signalData.put("sessionId", sessionID);
signalData.put("signalId", Respoke.makeGUID());
if (null != signalingChannel) {
signalingChannel.sendSignal(signalData, toEndpointId, toConnection, toType, false, new Respoke.TaskCompletionListener() {
@Override
public void onSuccess() {
if (isActive()) {
processRemoteSDP();
if (null != listenerReference) {
final Listener listener = listenerReference.get();
if (null != listener) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
if (isActive()) {
listener.onConnected(RespokeCall.this);
}
}
});
}
}
}
}
@Override
public void onError(final String errorMessage) {
postErrorToListener(errorMessage);
}
});
}
} catch (JSONException e) {
postErrorToListener("Error encoding answer signal");
}
}
} } | public class class_name {
public void answerReceived(JSONObject remoteSDP, String remoteConnection) {
if (isActive()) {
incomingSDP = remoteSDP; // depends on control dependency: [if], data = [none]
toConnection = remoteConnection; // depends on control dependency: [if], data = [none]
try {
JSONObject signalData = new JSONObject("{'signalType':'connected','version':'1.0'}");
signalData.put("target", directConnectionOnly ? "directConnection" : "call"); // depends on control dependency: [try], data = [none]
signalData.put("connectionId", toConnection); // depends on control dependency: [try], data = [none]
signalData.put("sessionId", sessionID); // depends on control dependency: [try], data = [none]
signalData.put("signalId", Respoke.makeGUID()); // depends on control dependency: [try], data = [none]
if (null != signalingChannel) {
signalingChannel.sendSignal(signalData, toEndpointId, toConnection, toType, false, new Respoke.TaskCompletionListener() {
@Override
public void onSuccess() {
if (isActive()) {
processRemoteSDP(); // depends on control dependency: [if], data = [none]
if (null != listenerReference) {
final Listener listener = listenerReference.get();
if (null != listener) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
if (isActive()) {
listener.onConnected(RespokeCall.this); // depends on control dependency: [if], data = [none]
}
}
}); // depends on control dependency: [if], data = [none]
}
}
}
}
@Override
public void onError(final String errorMessage) {
postErrorToListener(errorMessage);
}
}); // depends on control dependency: [if], data = [none]
}
} catch (JSONException e) {
postErrorToListener("Error encoding answer signal");
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
private static void renderX(Graphic g, CollisionFunction function, CollisionRange range, int th, int y)
{
if (UtilMath.isBetween(y, range.getMinY(), range.getMaxY()))
{
g.drawRect(function.getRenderX(y), th - y - 1, 0, 0, false);
}
} } | public class class_name {
private static void renderX(Graphic g, CollisionFunction function, CollisionRange range, int th, int y)
{
if (UtilMath.isBetween(y, range.getMinY(), range.getMaxY()))
{
g.drawRect(function.getRenderX(y), th - y - 1, 0, 0, false);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public boolean matches(Iterable<? extends T> target) {
if ((target instanceof Collection) && ((Collection<?>) target).size() != matchers.size()) {
return false;
}
Iterator<? extends ElementMatcher<? super T>> iterator = matchers.iterator();
for (T value : target) {
if (!iterator.hasNext() || !iterator.next().matches(value)) {
return false;
}
}
return true;
} } | public class class_name {
public boolean matches(Iterable<? extends T> target) {
if ((target instanceof Collection) && ((Collection<?>) target).size() != matchers.size()) {
return false; // depends on control dependency: [if], data = [none]
}
Iterator<? extends ElementMatcher<? super T>> iterator = matchers.iterator();
for (T value : target) {
if (!iterator.hasNext() || !iterator.next().matches(value)) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
public void addAll(SAXRecords records) {
for (SAXRecord record : records) {
char[] payload = record.getPayload();
for (Integer i : record.getIndexes()) {
this.add(payload, i);
}
}
} } | public class class_name {
public void addAll(SAXRecords records) {
for (SAXRecord record : records) {
char[] payload = record.getPayload();
for (Integer i : record.getIndexes()) {
this.add(payload, i); // depends on control dependency: [for], data = [i]
}
}
} } |
public class class_name {
public void setInitialAttributes(File file, FileAttribute<?>... attrs) {
// default values should already be sanitized by their providers
for (int i = 0; i < defaultValues.size(); i++) {
FileAttribute<?> attribute = defaultValues.get(i);
int separatorIndex = attribute.name().indexOf(':');
String view = attribute.name().substring(0, separatorIndex);
String attr = attribute.name().substring(separatorIndex + 1);
file.setAttribute(view, attr, attribute.value());
}
for (FileAttribute<?> attr : attrs) {
setAttribute(file, attr.name(), attr.value(), true);
}
} } | public class class_name {
public void setInitialAttributes(File file, FileAttribute<?>... attrs) {
// default values should already be sanitized by their providers
for (int i = 0; i < defaultValues.size(); i++) {
FileAttribute<?> attribute = defaultValues.get(i);
int separatorIndex = attribute.name().indexOf(':');
String view = attribute.name().substring(0, separatorIndex);
String attr = attribute.name().substring(separatorIndex + 1);
file.setAttribute(view, attr, attribute.value()); // depends on control dependency: [for], data = [none]
}
for (FileAttribute<?> attr : attrs) {
setAttribute(file, attr.name(), attr.value(), true); // depends on control dependency: [for], data = [attr]
}
} } |
public class class_name {
public void marshall(AssociationFilter associationFilter, ProtocolMarshaller protocolMarshaller) {
if (associationFilter == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(associationFilter.getKey(), KEY_BINDING);
protocolMarshaller.marshall(associationFilter.getValue(), VALUE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(AssociationFilter associationFilter, ProtocolMarshaller protocolMarshaller) {
if (associationFilter == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(associationFilter.getKey(), KEY_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(associationFilter.getValue(), VALUE_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 Locale[] getAvailableLocales() {
// TODO make this wrap getAvailableULocales later
if (shim == null) {
return ICUResourceBundle.getAvailableLocales(
ICUData.ICU_COLLATION_BASE_NAME, ICUResourceBundle.ICU_DATA_CLASS_LOADER);
}
return shim.getAvailableLocales();
} } | public class class_name {
public static Locale[] getAvailableLocales() {
// TODO make this wrap getAvailableULocales later
if (shim == null) {
return ICUResourceBundle.getAvailableLocales(
ICUData.ICU_COLLATION_BASE_NAME, ICUResourceBundle.ICU_DATA_CLASS_LOADER); // depends on control dependency: [if], data = [none]
}
return shim.getAvailableLocales();
} } |
public class class_name {
public static String urlEncode(final String text) {
try {
return URLEncoder.encode(text, StandardCharsets.UTF_8.name());
} catch (final UnsupportedEncodingException e) {
final String message = "Unable to encode text : " + text;
throw new TechnicalException(message, e);
}
} } | public class class_name {
public static String urlEncode(final String text) {
try {
return URLEncoder.encode(text, StandardCharsets.UTF_8.name()); // depends on control dependency: [try], data = [none]
} catch (final UnsupportedEncodingException e) {
final String message = "Unable to encode text : " + text;
throw new TechnicalException(message, e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void configure(ResourceResolver resolver, Configurer configurer, JBossWebservicesMetaData wsmd, Deployment dep)
{
if (configured)
{
throw Messages.MESSAGES.busAlreadyConfigured(bus);
}
bus.setProperty(org.jboss.wsf.stack.cxf.client.Constants.DEPLOYMENT_BUS, true);
busHolderListener = new BusHolderLifeCycleListener();
bus.getExtension(BusLifeCycleManager.class).registerLifeCycleListener(busHolderListener);
setWSDLManagerStreamWrapper(bus);
if (configurer != null)
{
bus.setExtension(configurer, Configurer.class);
}
Map<String, String> props = getProperties(wsmd);
setInterceptors(bus, dep, props);
dep.addAttachment(Bus.class, bus);
try
{
final JASPIAuthenticationProvider jaspiProvider = SPIProvider.getInstance().getSPI(
JASPIAuthenticationProvider.class,
ClassLoaderProvider.getDefaultProvider().getServerIntegrationClassLoader());
if (jaspiProvider != null && jaspiProvider.enableServerAuthentication(dep, wsmd))
{
bus.getInInterceptors().add(new AuthenticationMgrSubjectCreatingInterceptor());
}
}
catch (WSFException e)
{
Loggers.DEPLOYMENT_LOGGER.cannotFindJaspiClasses();
}
setResourceResolver(bus, resolver);
if (bus.getExtension(PolicyEngine.class) != null)
{
bus.getExtension(PolicyEngine.class).setAlternativeSelector(getAlternativeSelector(props));
}
setCXFManagement(bus, props); //*first* enabled cxf management if required, *then* add anything else which could be manageable (e.g. work queues)
setAdditionalWorkQueues(bus, props);
setWSDiscovery(bus, props);
AnnotationsInfo ai = dep.getAttachment(AnnotationsInfo.class);
if (ai == null || ai.hasAnnotatedClasses(PolicySets.class.getName())) {
policySetsListener = new PolicySetsAnnotationListener(dep.getClassLoader());
bus.getExtension(FactoryBeanListenerManager.class).addListener(policySetsListener);
}
//default to USE_ORIGINAL_THREAD = true; this can be overridden by simply setting the property in the endpoint or in the message using an interceptor
//this forces one way operation to use original thread, which is required for ejb webserivce endpoints to avoid authorization failures from ejb container
//and is a performance improvement in general when running in-container, as CXF needs to cache the message to free the thread, which is expensive
//(moreover the user can tune the web container thread pool instead of expecting cxf to fork new threads)
bus.setProperty(OneWayProcessorInterceptor.USE_ORIGINAL_THREAD, true);
//[JBWS-3135] enable decoupled faultTo. This is an optional feature in cxf and we need this to be default to make it same behavior with native stack
bus.setProperty("org.apache.cxf.ws.addressing.decoupled_fault_support", true);
FeatureUtils.addFeatures(bus, bus, props);
for (DDEndpoint dde : metadata.getEndpoints())
{
EndpointImpl endpoint = new EndpointImpl(bus, newInstance(dde.getImplementor(), dep));
if (dde.getInvoker() != null)
endpoint.setInvoker(newInvokerInstance(dde.getInvoker(), dep));
endpoint.setAddress(dde.getAddress());
endpoint.setEndpointName(dde.getPortName());
endpoint.setServiceName(dde.getServiceName());
endpoint.setWsdlLocation(dde.getWsdlLocation());
setHandlers(endpoint, dde, dep);
if (dde.getProperties() != null)
{
Map<String, Object> p = new HashMap<String, Object>();
p.putAll(dde.getProperties());
endpoint.setProperties(p);
}
if (dde.isAddressingEnabled())
{
WSAddressingFeature addressingFeature = new WSAddressingFeature();
addressingFeature.setAddressingRequired(dde.isAddressingRequired());
addressingFeature.setResponses(dde.getAddressingResponses());
endpoint.getFeatures().add(addressingFeature);
}
endpoint.setPublishedEndpointUrl(dde.getPublishedEndpointUrl());
endpoint.setSOAPAddressRewriteMetadata(dep.getAttachment(SOAPAddressRewriteMetadata.class));
endpoint.publish();
endpoints.add(endpoint);
if (dde.isMtomEnabled())
{
SOAPBinding binding = (SOAPBinding) endpoint.getBinding();
binding.setMTOMEnabled(true);
}
}
configured = true;
} } | public class class_name {
public void configure(ResourceResolver resolver, Configurer configurer, JBossWebservicesMetaData wsmd, Deployment dep)
{
if (configured)
{
throw Messages.MESSAGES.busAlreadyConfigured(bus);
}
bus.setProperty(org.jboss.wsf.stack.cxf.client.Constants.DEPLOYMENT_BUS, true);
busHolderListener = new BusHolderLifeCycleListener();
bus.getExtension(BusLifeCycleManager.class).registerLifeCycleListener(busHolderListener);
setWSDLManagerStreamWrapper(bus);
if (configurer != null)
{
bus.setExtension(configurer, Configurer.class); // depends on control dependency: [if], data = [(configurer]
}
Map<String, String> props = getProperties(wsmd);
setInterceptors(bus, dep, props);
dep.addAttachment(Bus.class, bus);
try
{
final JASPIAuthenticationProvider jaspiProvider = SPIProvider.getInstance().getSPI(
JASPIAuthenticationProvider.class,
ClassLoaderProvider.getDefaultProvider().getServerIntegrationClassLoader());
if (jaspiProvider != null && jaspiProvider.enableServerAuthentication(dep, wsmd))
{
bus.getInInterceptors().add(new AuthenticationMgrSubjectCreatingInterceptor()); // depends on control dependency: [if], data = [none]
}
}
catch (WSFException e)
{
Loggers.DEPLOYMENT_LOGGER.cannotFindJaspiClasses();
} // depends on control dependency: [catch], data = [none]
setResourceResolver(bus, resolver);
if (bus.getExtension(PolicyEngine.class) != null)
{
bus.getExtension(PolicyEngine.class).setAlternativeSelector(getAlternativeSelector(props)); // depends on control dependency: [if], data = [none]
}
setCXFManagement(bus, props); //*first* enabled cxf management if required, *then* add anything else which could be manageable (e.g. work queues)
setAdditionalWorkQueues(bus, props);
setWSDiscovery(bus, props);
AnnotationsInfo ai = dep.getAttachment(AnnotationsInfo.class);
if (ai == null || ai.hasAnnotatedClasses(PolicySets.class.getName())) {
policySetsListener = new PolicySetsAnnotationListener(dep.getClassLoader()); // depends on control dependency: [if], data = [none]
bus.getExtension(FactoryBeanListenerManager.class).addListener(policySetsListener); // depends on control dependency: [if], data = [none]
}
//default to USE_ORIGINAL_THREAD = true; this can be overridden by simply setting the property in the endpoint or in the message using an interceptor
//this forces one way operation to use original thread, which is required for ejb webserivce endpoints to avoid authorization failures from ejb container
//and is a performance improvement in general when running in-container, as CXF needs to cache the message to free the thread, which is expensive
//(moreover the user can tune the web container thread pool instead of expecting cxf to fork new threads)
bus.setProperty(OneWayProcessorInterceptor.USE_ORIGINAL_THREAD, true);
//[JBWS-3135] enable decoupled faultTo. This is an optional feature in cxf and we need this to be default to make it same behavior with native stack
bus.setProperty("org.apache.cxf.ws.addressing.decoupled_fault_support", true);
FeatureUtils.addFeatures(bus, bus, props);
for (DDEndpoint dde : metadata.getEndpoints())
{
EndpointImpl endpoint = new EndpointImpl(bus, newInstance(dde.getImplementor(), dep));
if (dde.getInvoker() != null)
endpoint.setInvoker(newInvokerInstance(dde.getInvoker(), dep));
endpoint.setAddress(dde.getAddress()); // depends on control dependency: [for], data = [dde]
endpoint.setEndpointName(dde.getPortName()); // depends on control dependency: [for], data = [dde]
endpoint.setServiceName(dde.getServiceName()); // depends on control dependency: [for], data = [dde]
endpoint.setWsdlLocation(dde.getWsdlLocation()); // depends on control dependency: [for], data = [dde]
setHandlers(endpoint, dde, dep); // depends on control dependency: [for], data = [dde]
if (dde.getProperties() != null)
{
Map<String, Object> p = new HashMap<String, Object>();
p.putAll(dde.getProperties()); // depends on control dependency: [if], data = [(dde.getProperties()]
endpoint.setProperties(p); // depends on control dependency: [if], data = [none]
}
if (dde.isAddressingEnabled())
{
WSAddressingFeature addressingFeature = new WSAddressingFeature();
addressingFeature.setAddressingRequired(dde.isAddressingRequired()); // depends on control dependency: [if], data = [none]
addressingFeature.setResponses(dde.getAddressingResponses()); // depends on control dependency: [if], data = [none]
endpoint.getFeatures().add(addressingFeature); // depends on control dependency: [if], data = [none]
}
endpoint.setPublishedEndpointUrl(dde.getPublishedEndpointUrl()); // depends on control dependency: [for], data = [dde]
endpoint.setSOAPAddressRewriteMetadata(dep.getAttachment(SOAPAddressRewriteMetadata.class)); // depends on control dependency: [for], data = [none]
endpoint.publish(); // depends on control dependency: [for], data = [none]
endpoints.add(endpoint); // depends on control dependency: [for], data = [none]
if (dde.isMtomEnabled())
{
SOAPBinding binding = (SOAPBinding) endpoint.getBinding();
binding.setMTOMEnabled(true); // depends on control dependency: [if], data = [none]
}
}
configured = true;
} } |
public class class_name {
private void checkForConnectionInFreePool(MCWrapper mcw) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(this, tc, "checkForConnectionInFreePool");
}
int hashMapBucket = mcw.getHashMapBucket();
/*
* Attempt to remove the mcw from the free pool
*/
if (freePool[hashMapBucket].removeMCWrapperFromList(mcw)) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(this, tc, "Managed connection wrapper was removed from the free pool wrapper list. mcw is " + mcw);
}
/*
* The connection was in the free pool, cleaup and destroy the mc.
*/
freePool[hashMapBucket].cleanupAndDestroyMCWrapper(mcw);
/*
* Finish the work needed in the free pool for this mcw.
*
* Parms on the removeMCWrapperFromList are:
* MCWrapper object = mcw
* removeFromFreePool = false (we alread removed the connection)
* synchronizationNeeded = true (we are not sync'ed, so the method will need to sync)
* skipWaiterNotify = false (if there are waiters, we should wake-up one of them)
* decrementTotalCounter = true (if we are going to wake-up a waiter, we need to allow
* the waiter to create a connection if total is at its max)
*/
freePool[hashMapBucket].removeMCWrapperFromList(mcw, false, true, false, true);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(this, tc, "checkForConnectionInFreePool");
}
} } | public class class_name {
private void checkForConnectionInFreePool(MCWrapper mcw) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(this, tc, "checkForConnectionInFreePool"); // depends on control dependency: [if], data = [none]
}
int hashMapBucket = mcw.getHashMapBucket();
/*
* Attempt to remove the mcw from the free pool
*/
if (freePool[hashMapBucket].removeMCWrapperFromList(mcw)) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(this, tc, "Managed connection wrapper was removed from the free pool wrapper list. mcw is " + mcw); // depends on control dependency: [if], data = [none]
}
/*
* The connection was in the free pool, cleaup and destroy the mc.
*/
freePool[hashMapBucket].cleanupAndDestroyMCWrapper(mcw); // depends on control dependency: [if], data = [none]
/*
* Finish the work needed in the free pool for this mcw.
*
* Parms on the removeMCWrapperFromList are:
* MCWrapper object = mcw
* removeFromFreePool = false (we alread removed the connection)
* synchronizationNeeded = true (we are not sync'ed, so the method will need to sync)
* skipWaiterNotify = false (if there are waiters, we should wake-up one of them)
* decrementTotalCounter = true (if we are going to wake-up a waiter, we need to allow
* the waiter to create a connection if total is at its max)
*/
freePool[hashMapBucket].removeMCWrapperFromList(mcw, false, true, false, true); // depends on control dependency: [if], data = [none]
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(this, tc, "checkForConnectionInFreePool"); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void addAll(final Iterable<String> strings) {
checkNotNull(strings);
for (String string : strings) {
add(string);
}
} } | public class class_name {
public void addAll(final Iterable<String> strings) {
checkNotNull(strings);
for (String string : strings) {
add(string); // depends on control dependency: [for], data = [string]
}
} } |
public class class_name {
private static void createLocales(TypeSpec.Builder type, List<LocaleID> defaultContent, Set<LocaleID> available) {
TypeSpec.Builder localeInterface = TypeSpec.interfaceBuilder("Locale")
.addModifiers(PUBLIC, STATIC)
.addMethod(MethodSpec.methodBuilder("language")
.addModifiers(PUBLIC, ABSTRACT)
.returns(String.class).build())
.addMethod(MethodSpec.methodBuilder("script")
.addModifiers(PUBLIC, ABSTRACT)
.returns(String.class).build())
.addMethod(MethodSpec.methodBuilder("territory")
.addModifiers(PUBLIC, ABSTRACT)
.returns(String.class).build())
.addMethod(MethodSpec.methodBuilder("variant")
.addModifiers(PUBLIC, ABSTRACT)
.returns(String.class).build())
.addMethod(MethodSpec.methodBuilder("compact")
.addModifiers(PUBLIC, ABSTRACT)
.returns(String.class).build())
.addMethod(MethodSpec.methodBuilder("expanded")
.addModifiers(PUBLIC, ABSTRACT)
.returns(String.class).build());
List<LocaleID> localeFields = new ArrayList<>();
List<String> allLocales = new ArrayList<>();
List<String> bundles = new ArrayList<>();
for (LocaleID locale : available) {
localeFields.add(locale);
allLocales.add(locale.safe);
bundles.add(locale.safe);
}
MethodSpec.Builder method = MethodSpec.methodBuilder("registerDefaultContent")
.addModifiers(PRIVATE, STATIC);
for (LocaleID locale : defaultContent) {
LocaleID dest = new LocaleID(locale.language, "", "", "");
if (available.contains(dest)) {
localeFields.add(locale);
allLocales.add(locale.safe);
method.addStatement("DEFAULT_CONTENT.put(Locale.$L, Locale.$L)",
locale.safe,
dest.safe);
}
}
type.addMethod(method.build());
Collections.sort(localeFields);
for (LocaleID locale : localeFields) {
addLocaleField(localeInterface, locale.safe, locale);
}
StringBuilder buf = new StringBuilder("$T.unmodifiableList($T.asList(\n");
for (int i = 0; i < allLocales.size(); i++) {
if (i > 0) {
buf.append(",\n");
}
buf.append(" Locale.$L");
}
buf.append("))");
Collections.sort(allLocales);
List<Object> arguments = new ArrayList<>();
arguments.add(Collections.class);
arguments.add(Arrays.class);
arguments.addAll(allLocales);
FieldSpec.Builder field = FieldSpec.builder(LIST_CLDR_LOCALE_IF, "AVAILABLE_LOCALES", PRIVATE, STATIC, FINAL);
field.initializer(buf.toString(), arguments.toArray());
type.addField(field.build());
buf = new StringBuilder("$T.unmodifiableList($T.asList(\n");
for (int i = 0; i < bundles.size(); i++) {
if (i > 0) {
buf.append(",\n");
}
buf.append(" Locale.$L");
}
buf.append("))");
Collections.sort(bundles);
arguments = new ArrayList<>();
arguments.add(Collections.class);
arguments.add(Arrays.class);
arguments.addAll(bundles);
field = FieldSpec.builder(LIST_CLDR_LOCALE_IF, "AVAILABLE_BUNDLES", PRIVATE, STATIC, FINAL);
field.initializer(buf.toString(), arguments.toArray());
type.addField(field.build());
method = MethodSpec.methodBuilder("availableLocales")
.addModifiers(PUBLIC, FINAL)
.returns(LIST_CLDR_LOCALE_IF)
.addStatement("return AVAILABLE_LOCALES");
type.addMethod(method.build());
method = MethodSpec.methodBuilder("availableBundles")
.addModifiers(PUBLIC, FINAL)
.returns(LIST_CLDR_LOCALE_IF)
.addStatement("return AVAILABLE_BUNDLES");
type.addMethod(method.build());
type.addType(localeInterface.build());
} } | public class class_name {
private static void createLocales(TypeSpec.Builder type, List<LocaleID> defaultContent, Set<LocaleID> available) {
TypeSpec.Builder localeInterface = TypeSpec.interfaceBuilder("Locale")
.addModifiers(PUBLIC, STATIC)
.addMethod(MethodSpec.methodBuilder("language")
.addModifiers(PUBLIC, ABSTRACT)
.returns(String.class).build())
.addMethod(MethodSpec.methodBuilder("script")
.addModifiers(PUBLIC, ABSTRACT)
.returns(String.class).build())
.addMethod(MethodSpec.methodBuilder("territory")
.addModifiers(PUBLIC, ABSTRACT)
.returns(String.class).build())
.addMethod(MethodSpec.methodBuilder("variant")
.addModifiers(PUBLIC, ABSTRACT)
.returns(String.class).build())
.addMethod(MethodSpec.methodBuilder("compact")
.addModifiers(PUBLIC, ABSTRACT)
.returns(String.class).build())
.addMethod(MethodSpec.methodBuilder("expanded")
.addModifiers(PUBLIC, ABSTRACT)
.returns(String.class).build());
List<LocaleID> localeFields = new ArrayList<>();
List<String> allLocales = new ArrayList<>();
List<String> bundles = new ArrayList<>();
for (LocaleID locale : available) {
localeFields.add(locale); // depends on control dependency: [for], data = [locale]
allLocales.add(locale.safe); // depends on control dependency: [for], data = [locale]
bundles.add(locale.safe); // depends on control dependency: [for], data = [locale]
}
MethodSpec.Builder method = MethodSpec.methodBuilder("registerDefaultContent")
.addModifiers(PRIVATE, STATIC);
for (LocaleID locale : defaultContent) {
LocaleID dest = new LocaleID(locale.language, "", "", "");
if (available.contains(dest)) {
localeFields.add(locale); // depends on control dependency: [if], data = [none]
allLocales.add(locale.safe); // depends on control dependency: [if], data = [none]
method.addStatement("DEFAULT_CONTENT.put(Locale.$L, Locale.$L)",
locale.safe,
dest.safe); // depends on control dependency: [if], data = [none]
}
}
type.addMethod(method.build());
Collections.sort(localeFields);
for (LocaleID locale : localeFields) {
addLocaleField(localeInterface, locale.safe, locale); // depends on control dependency: [for], data = [locale]
}
StringBuilder buf = new StringBuilder("$T.unmodifiableList($T.asList(\n");
for (int i = 0; i < allLocales.size(); i++) {
if (i > 0) {
buf.append(",\n");
}
buf.append(" Locale.$L");
}
buf.append("))");
Collections.sort(allLocales);
List<Object> arguments = new ArrayList<>();
arguments.add(Collections.class);
arguments.add(Arrays.class);
arguments.addAll(allLocales);
FieldSpec.Builder field = FieldSpec.builder(LIST_CLDR_LOCALE_IF, "AVAILABLE_LOCALES", PRIVATE, STATIC, FINAL);
field.initializer(buf.toString(), arguments.toArray());
type.addField(field.build());
buf = new StringBuilder("$T.unmodifiableList($T.asList(\n");
for (int i = 0; i < bundles.size(); i++) {
if (i > 0) {
buf.append(",\n");
}
buf.append(" Locale.$L");
}
buf.append("))");
Collections.sort(bundles);
arguments = new ArrayList<>();
arguments.add(Collections.class);
arguments.add(Arrays.class);
arguments.addAll(bundles);
field = FieldSpec.builder(LIST_CLDR_LOCALE_IF, "AVAILABLE_BUNDLES", PRIVATE, STATIC, FINAL);
field.initializer(buf.toString(), arguments.toArray());
type.addField(field.build());
method = MethodSpec.methodBuilder("availableLocales")
.addModifiers(PUBLIC, FINAL)
.returns(LIST_CLDR_LOCALE_IF)
.addStatement("return AVAILABLE_LOCALES");
type.addMethod(method.build());
method = MethodSpec.methodBuilder("availableBundles")
.addModifiers(PUBLIC, FINAL)
.returns(LIST_CLDR_LOCALE_IF)
.addStatement("return AVAILABLE_BUNDLES");
type.addMethod(method.build());
type.addType(localeInterface.build());
} } |
public class class_name {
private static final long trueMonthStart(long month)
{
long start = cache.get(month);
if (start == CalendarCache.EMPTY)
{
// Make a guess at when the month started, using the average length
long origin = HIJRA_MILLIS
+ (long)Math.floor(month * CalendarAstronomer.SYNODIC_MONTH) * ONE_DAY;
double age = moonAge(origin);
if (moonAge(origin) >= 0) {
// The month has already started
do {
origin -= ONE_DAY;
age = moonAge(origin);
} while (age >= 0);
}
else {
// Preceding month has not ended yet.
do {
origin += ONE_DAY;
age = moonAge(origin);
} while (age < 0);
}
start = (origin - HIJRA_MILLIS) / ONE_DAY + 1;
cache.put(month, start);
}
return start;
} } | public class class_name {
private static final long trueMonthStart(long month)
{
long start = cache.get(month);
if (start == CalendarCache.EMPTY)
{
// Make a guess at when the month started, using the average length
long origin = HIJRA_MILLIS
+ (long)Math.floor(month * CalendarAstronomer.SYNODIC_MONTH) * ONE_DAY;
double age = moonAge(origin);
if (moonAge(origin) >= 0) {
// The month has already started
do {
origin -= ONE_DAY;
age = moonAge(origin);
} while (age >= 0);
}
else {
// Preceding month has not ended yet.
do {
origin += ONE_DAY;
age = moonAge(origin);
} while (age < 0);
}
start = (origin - HIJRA_MILLIS) / ONE_DAY + 1; // depends on control dependency: [if], data = [none]
cache.put(month, start); // depends on control dependency: [if], data = [none]
}
return start;
} } |
public class class_name {
@Override
public <E> List<E> getColumnsById(String schemaName, String joinTableName, String joinColumnName,
String inverseJoinColumnName, Object parentId, Class columnJavaType)
{
List<Object> foreignKeys = new ArrayList<Object>();
if (getCqlVersion().equalsIgnoreCase(CassandraConstants.CQL_VERSION_3_0))
{
foreignKeys = getColumnsByIdUsingCql(schemaName, joinTableName, joinColumnName, inverseJoinColumnName,
parentId, columnJavaType);
}
else
{
Selector selector = clientFactory.getSelector(pool);
List<Column> columns = selector.getColumnsFromRow(joinTableName,
Bytes.fromByteArray(PropertyAccessorHelper.getBytes(parentId)),
Selector.newColumnsPredicateAll(true, 10), getConsistencyLevel());
foreignKeys = dataHandler.getForeignKeysFromJoinTable(inverseJoinColumnName, columns, columnJavaType);
if (log.isInfoEnabled())
{
log.info("Returning number of keys from join table", foreignKeys != null ? foreignKeys.size() : null);
}
}
return (List<E>) foreignKeys;
} } | public class class_name {
@Override
public <E> List<E> getColumnsById(String schemaName, String joinTableName, String joinColumnName,
String inverseJoinColumnName, Object parentId, Class columnJavaType)
{
List<Object> foreignKeys = new ArrayList<Object>();
if (getCqlVersion().equalsIgnoreCase(CassandraConstants.CQL_VERSION_3_0))
{
foreignKeys = getColumnsByIdUsingCql(schemaName, joinTableName, joinColumnName, inverseJoinColumnName,
parentId, columnJavaType); // depends on control dependency: [if], data = [none]
}
else
{
Selector selector = clientFactory.getSelector(pool);
List<Column> columns = selector.getColumnsFromRow(joinTableName,
Bytes.fromByteArray(PropertyAccessorHelper.getBytes(parentId)),
Selector.newColumnsPredicateAll(true, 10), getConsistencyLevel());
foreignKeys = dataHandler.getForeignKeysFromJoinTable(inverseJoinColumnName, columns, columnJavaType); // depends on control dependency: [if], data = [none]
if (log.isInfoEnabled())
{
log.info("Returning number of keys from join table", foreignKeys != null ? foreignKeys.size() : null); // depends on control dependency: [if], data = [none]
}
}
return (List<E>) foreignKeys;
} } |
public class class_name {
protected final boolean isValidBearerSubjectConfirmationData(final SubjectConfirmationData data,
final SAML2MessageContext context) {
if (data == null) {
logger.debug("SubjectConfirmationData cannot be null for Bearer confirmation");
return false;
}
// TODO Validate inResponseTo
if (data.getNotBefore() != null) {
logger.debug("SubjectConfirmationData notBefore must be null for Bearer confirmation");
return false;
}
if (data.getNotOnOrAfter() == null) {
logger.debug("SubjectConfirmationData notOnOrAfter cannot be null for Bearer confirmation");
return false;
}
if (data.getNotOnOrAfter().plusSeconds(acceptedSkew).isBeforeNow()) {
logger.debug("SubjectConfirmationData notOnOrAfter is too old");
return false;
}
try {
if (data.getRecipient() == null) {
logger.debug("SubjectConfirmationData recipient cannot be null for Bearer confirmation");
return false;
} else {
final Endpoint endpoint = context.getSAMLEndpointContext().getEndpoint();
if (endpoint == null) {
logger.warn("No endpoint was found in the SAML endpoint context");
return false;
}
final URI recipientUri = new URI(data.getRecipient());
final URI appEndpointUri = new URI(endpoint.getLocation());
if (!SAML2Utils.urisEqualAfterPortNormalization(recipientUri, appEndpointUri)) {
logger.debug("SubjectConfirmationData recipient {} does not match SP assertion consumer URL, found. "
+ "SP ACS URL from context: {}", recipientUri, appEndpointUri);
return false;
}
}
} catch (URISyntaxException use) {
logger.error("Unable to check SubjectConfirmationData recipient, a URI has invalid syntax.", use);
return false;
}
return true;
} } | public class class_name {
protected final boolean isValidBearerSubjectConfirmationData(final SubjectConfirmationData data,
final SAML2MessageContext context) {
if (data == null) {
logger.debug("SubjectConfirmationData cannot be null for Bearer confirmation"); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
// TODO Validate inResponseTo
if (data.getNotBefore() != null) {
logger.debug("SubjectConfirmationData notBefore must be null for Bearer confirmation"); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
if (data.getNotOnOrAfter() == null) {
logger.debug("SubjectConfirmationData notOnOrAfter cannot be null for Bearer confirmation"); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
if (data.getNotOnOrAfter().plusSeconds(acceptedSkew).isBeforeNow()) {
logger.debug("SubjectConfirmationData notOnOrAfter is too old"); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
try {
if (data.getRecipient() == null) {
logger.debug("SubjectConfirmationData recipient cannot be null for Bearer confirmation"); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
} else {
final Endpoint endpoint = context.getSAMLEndpointContext().getEndpoint();
if (endpoint == null) {
logger.warn("No endpoint was found in the SAML endpoint context"); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
final URI recipientUri = new URI(data.getRecipient());
final URI appEndpointUri = new URI(endpoint.getLocation());
if (!SAML2Utils.urisEqualAfterPortNormalization(recipientUri, appEndpointUri)) {
logger.debug("SubjectConfirmationData recipient {} does not match SP assertion consumer URL, found. "
+ "SP ACS URL from context: {}", recipientUri, appEndpointUri); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
}
} catch (URISyntaxException use) {
logger.error("Unable to check SubjectConfirmationData recipient, a URI has invalid syntax.", use);
return false;
} // depends on control dependency: [catch], data = [none]
return true;
} } |
public class class_name {
public Object get(Object key)
{
// Synchronize on the cache to ensure its integrity in a multi-threaded environment.
synchronized (cache)
{
// Try to extract the matching element as an ElementMonitor,
ElementMonitor monitor = (ElementMonitor) cache.get(key);
// If the element is not null then return its value, else null.
// Also upgrade the timestamp of the matching element to the present to show that it has been recently
// accessed.
if (monitor != null)
{
// Upgrade the timestamp.
long t = System.currentTimeMillis();
monitor.lastTouched = t;
// Return the element.
return monitor.element;
}
else
{
return null;
}
}
} } | public class class_name {
public Object get(Object key)
{
// Synchronize on the cache to ensure its integrity in a multi-threaded environment.
synchronized (cache)
{
// Try to extract the matching element as an ElementMonitor,
ElementMonitor monitor = (ElementMonitor) cache.get(key);
// If the element is not null then return its value, else null.
// Also upgrade the timestamp of the matching element to the present to show that it has been recently
// accessed.
if (monitor != null)
{
// Upgrade the timestamp.
long t = System.currentTimeMillis();
monitor.lastTouched = t; // depends on control dependency: [if], data = [none]
// Return the element.
return monitor.element; // depends on control dependency: [if], data = [none]
}
else
{
return null; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private List<Short> asShortList(Object value) {
short[] values = (short[]) value;
List<Short> list = new ArrayList<Short>(values.length);
for (short shortValue : values) {
list.add(shortValue);
}
return list;
} } | public class class_name {
private List<Short> asShortList(Object value) {
short[] values = (short[]) value;
List<Short> list = new ArrayList<Short>(values.length);
for (short shortValue : values) {
list.add(shortValue); // depends on control dependency: [for], data = [shortValue]
}
return list;
} } |
public class class_name {
private Object[] SetJavaScriptArguments(InteractiveObject interactiveObj,
Object argument0, Object argument1, Object argument2, Object argument3, boolean stateChanged) {
ArrayList<Object> scriptParameters = new ArrayList<Object>();
ScriptObject scriptObject = interactiveObj.getScriptObject();
// Get the parameters/values passed to the Script/JavaScript
for (ScriptObject.Field field : scriptObject.getFieldsArrayList()) {
if ((scriptObject.getFieldAccessType(field) == ScriptObject.AccessType.INPUT_OUTPUT) ||
(scriptObject.getFieldAccessType(field) == ScriptObject.AccessType.INPUT_ONLY)) {
String fieldType = scriptObject.getFieldType(field);
DefinedItem definedItem = scriptObject.getFromDefinedItem(field);
EventUtility eventUtility = scriptObject.getFromEventUtility(field);
TimeSensor timeSensor = scriptObject.getFromTimeSensor(field);
if (fieldType.equalsIgnoreCase("SFBool")) {
if (definedItem != null) {
if (definedItem.getGVRSceneObject() != null) {
GVRComponent gvrComponent = definedItem.getGVRSceneObject().getComponent(
GVRLight.getComponentType());
if (gvrComponent != null) {
scriptParameters.add(gvrComponent.isEnabled());
}
}
}
else if (eventUtility != null) {
scriptParameters.add( eventUtility.getToggle() );
}
else if (interactiveObj.getSensorFromField() != null) {
if (interactiveObj.getSensorFromField().equals(Sensor.IS_OVER)) {
scriptParameters.add(argument0);
}
else if (interactiveObj.getSensorFromField().equals(Sensor.IS_ACTIVE)) {
scriptParameters.add(!stateChanged);
}
}
else if ( interactiveObj.getEventUtility() != null) {
scriptParameters.add( interactiveObj.getEventUtility().getToggle() );
}
} // end if SFBool
else if ((fieldType.equalsIgnoreCase("SFVec2f")) && (definedItem == null)) {
// data from a Plane Sensor
if (interactiveObj.getSensorFromField() != null) {
if (interactiveObj.getSensor().getSensorType() == Sensor.Type.PLANE) {
scriptParameters.add( argument0 );
scriptParameters.add( argument1 );
}
}
}
else if ((fieldType.equalsIgnoreCase("SFFloat")) && (definedItem == null)) {
if (timeSensor != null) {
scriptParameters.add( timeSensor.getCycleInterval() );
}
else scriptParameters.add(argument0); // the time passed in from an SFTime node
}
else if ((fieldType.equalsIgnoreCase("SFRotation")) && (definedItem == null)) {
// data from a Cylinder or Sphere Sensor
if (interactiveObj.getSensorFromField() != null) {
if (interactiveObj.getSensor().getSensorType() == Sensor.Type.CYLINDER) {
scriptParameters.add(argument0);
scriptParameters.add(argument1);
scriptParameters.add(argument2);
scriptParameters.add(argument3);
}
else if (interactiveObj.getSensor().getSensorType() == Sensor.Type.SPHERE) {
scriptParameters.add(argument0);
scriptParameters.add(argument1);
scriptParameters.add(argument2);
scriptParameters.add(argument3);
}
}
}
else if (scriptObject.getFromDefinedItem(field) != null) {
if (fieldType.equalsIgnoreCase("SFColor")) {
float[] color = {0, 0, 0};
if (definedItem.getGVRMaterial() != null) {
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "diffuseColor") ) {
float[] diffuseColor = definedItem.getGVRMaterial().getVec4("diffuse_color");
for (int i = 0; i < 3; i++) {
color[i] = diffuseColor[i]; // only get the first 3 values, not the alpha value
}
} else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "emissiveColor") ) {
float[] emissiveColor = definedItem.getGVRMaterial().getVec4("emissive_color");
for (int i = 0; i < 3; i++) {
color[i] = emissiveColor[i]; // only get the first 3 values, not the alpha value
}
} else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "specularColor") ) {
float[] specularColor = definedItem.getGVRMaterial().getVec4("specular_color");
for (int i = 0; i < 3; i++) {
color[i] = specularColor[i]; // only get the first 3 values, not the alpha value
}
}
} else if (definedItem.getGVRSceneObject() != null) {
// likely a light object so get its properties
GVRComponent gvrComponent = definedItem.getGVRSceneObject().getComponent(
GVRLight.getComponentType());
if (gvrComponent != null) {
float[] lightColor = {0, 0, 0, 0};
if (gvrComponent instanceof GVRSpotLight) {
GVRSpotLight gvrSpotLightBase = (GVRSpotLight) gvrComponent;
lightColor = gvrSpotLightBase.getDiffuseIntensity();
} else if (gvrComponent instanceof GVRPointLight) {
GVRPointLight gvrPointLightBase = (GVRPointLight) gvrComponent;
lightColor = gvrPointLightBase.getDiffuseIntensity();
} else if (gvrComponent instanceof GVRDirectLight) {
GVRDirectLight gvrDirectLightBase = (GVRDirectLight) gvrComponent;
lightColor = gvrDirectLightBase.getDiffuseIntensity();
}
for (int i = 0; i < 3; i++) {
color[i] = lightColor[i]; // only get the first 3 values, not the alpha value
}
}
}
// append the parameters of the SFColor passed to the SCRIPT's javascript code
for (int i = 0; i < color.length; i++) {
scriptParameters.add(color[i]);
}
} // end if SFColor
else if (fieldType.equalsIgnoreCase("SFRotation")) {
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "rotation") ) {
if (definedItem.getGVRSceneObject() != null) {
// Likely the rotation in a Transform / GVRTransform
// GearVRf saves rotations as quaternions, but X3D scripting uses AxisAngle
// So, these values were saved as AxisAngle in the DefinedItem object
scriptParameters.add(definedItem.getAxisAngle().x);
scriptParameters.add(definedItem.getAxisAngle().y);
scriptParameters.add(definedItem.getAxisAngle().z);
scriptParameters.add(definedItem.getAxisAngle().angle);
}
} // rotation parameter
else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "orientation") ) {
if ( definedItem.getViewpoint() != null ) {
// have a Viewpoint which for the time-being means get the current direction of the camera
float[] lookAt = gvrContext.getMainScene().getMainCameraRig().getLookAt();
Vector3f cameraDir = new Vector3f(lookAt[0], lookAt[1], lookAt[2]);
Quaternionf q = ConvertDirectionalVectorToQuaternion(cameraDir);
AxisAngle4f cameraAxisAngle = new AxisAngle4f();
q.get(cameraAxisAngle);
scriptParameters.add( cameraAxisAngle.x );
scriptParameters.add( cameraAxisAngle.y );
scriptParameters.add( cameraAxisAngle.z );
scriptParameters.add( cameraAxisAngle.angle );
}
} // orientation parameter
} // end if SFRotation
else if (fieldType.equalsIgnoreCase("SFVec3f")) {
if (definedItem.getGVRSceneObject() != null) {
GVRComponent gvrComponent = definedItem.getGVRSceneObject().getComponent(
GVRLight.getComponentType());
if (gvrComponent != null) {
// it's a light
float[] parameter = {0, 0, 0};
if (gvrComponent instanceof GVRSpotLight) {
GVRSpotLight gvrSpotLightBase = (GVRSpotLight) gvrComponent;
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "attenuation") ) {
parameter[0] = gvrSpotLightBase.getAttenuationConstant();
parameter[1] = gvrSpotLightBase.getAttenuationLinear();
parameter[2] = gvrSpotLightBase.getAttenuationQuadratic();
} else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "location") ) {
parameter[0] = definedItem.getGVRSceneObject().getTransform().getPositionX();
parameter[1] = definedItem.getGVRSceneObject().getTransform().getPositionY();
parameter[2] = definedItem.getGVRSceneObject().getTransform().getPositionZ();
} else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "direction") ) {
parameter[0] = definedItem.getDirection().x;
parameter[1] = definedItem.getDirection().y;
parameter[2] = definedItem.getDirection().z;
}
} else if (gvrComponent instanceof GVRPointLight) {
GVRPointLight gvrPointLightBase = (GVRPointLight) gvrComponent;
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "attenuation") ) {
parameter[0] = gvrPointLightBase.getAttenuationConstant();
parameter[1] = gvrPointLightBase.getAttenuationLinear();
parameter[2] = gvrPointLightBase.getAttenuationQuadratic();
} else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "location") ) {
parameter[0] = definedItem.getGVRSceneObject().getTransform().getPositionX();
parameter[1] = definedItem.getGVRSceneObject().getTransform().getPositionY();
parameter[2] = definedItem.getGVRSceneObject().getTransform().getPositionZ();
}
} else if (gvrComponent instanceof GVRDirectLight) {
GVRDirectLight gvrDirectLightBase = (GVRDirectLight) gvrComponent;
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "direction") ) {
parameter[0] = definedItem.getDirection().x;
parameter[1] = definedItem.getDirection().y;
parameter[2] = definedItem.getDirection().z;
}
} // end GVRDirectLight
// append the parameters of the lights passed to the SCRIPT's javascript code
for (int i = 0; i < parameter.length; i++) {
scriptParameters.add(parameter[i]);
}
} // end gvrComponent != null. it's a light
else {
if (definedItem.getGVRSceneObject() != null) {
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "translation") ) {
GVRSceneObject gvrSceneObjectTranslation = root
.getSceneObjectByName((definedItem.getGVRSceneObject().getName() + x3dObject.TRANSFORM_TRANSLATION_));
scriptParameters.add(gvrSceneObjectTranslation.getTransform().getPositionX());
scriptParameters.add(gvrSceneObjectTranslation.getTransform().getPositionY());
scriptParameters.add(gvrSceneObjectTranslation.getTransform().getPositionZ());
} else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "scale") ) {
GVRSceneObject gvrSceneObjectScale = root
.getSceneObjectByName((definedItem.getGVRSceneObject().getName() + x3dObject.TRANSFORM_SCALE_));
scriptParameters.add(gvrSceneObjectScale.getTransform().getScaleX());
scriptParameters.add(gvrSceneObjectScale.getTransform().getScaleY());
scriptParameters.add(gvrSceneObjectScale.getTransform().getScaleZ());
}
}
}
} // end SFVec3f GVRSceneObject
} // end if SFVec3f
else if (fieldType.equalsIgnoreCase("SFVec2f")) {
float[] parameter = {0, 0};
if (definedItem.getGVRMaterial() != null) {
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "translation") ) {
parameter[0] = definedItem.getTextureTranslation().getX();
parameter[1] = -definedItem.getTextureTranslation().getY();
}
else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "scale") ) {
parameter[0] = definedItem.getTextureScale().getX();
parameter[1] = definedItem.getTextureScale().getY();
}
else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "center") ) {
parameter[0] = -definedItem.getTextureCenter().getX();
parameter[1] = definedItem.getTextureCenter().getY();
}
// append the parameters of the lights passed to the SCRIPT's javascript code
for (int i = 0; i < parameter.length; i++) {
scriptParameters.add(parameter[i]);
}
} // end SFVec3f GVRMaterial
} // end if SFVec2f
else if (fieldType.equalsIgnoreCase("SFFloat")) {
if (definedItem.getGVRMaterial() != null) {
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "shininess") ) {
scriptParameters.add(
definedItem.getGVRMaterial().getFloat("specular_exponent")
);
}
else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "transparency") ) {
scriptParameters.add(definedItem.getGVRMaterial().getOpacity());
}
else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "rotation") ) {
scriptParameters.add(definedItem.getTextureRotation().getValue());
}
} else if (definedItem.getGVRSceneObject() != null) {
// checking if it's a light
GVRComponent gvrComponent = definedItem.getGVRSceneObject().getComponent(
GVRLight.getComponentType());
if (gvrComponent != null) {
float parameter = 0;
if (gvrComponent instanceof GVRSpotLight) {
GVRSpotLight gvrSpotLightBase = (GVRSpotLight) gvrComponent;
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "beamWidth") ) {
parameter = gvrSpotLightBase.getInnerConeAngle() * (float) Math.PI / 180;
} else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "cutOffAngle") ) {
parameter = gvrSpotLightBase.getOuterConeAngle() * (float) Math.PI / 180;
}
} else if (gvrComponent instanceof GVRPointLight) {
GVRPointLight gvrPointLightBase = (GVRPointLight) gvrComponent;
} else if (gvrComponent instanceof GVRDirectLight) {
GVRDirectLight gvrDirectLightBase = (GVRDirectLight) gvrComponent;
}
scriptParameters.add(parameter);
}
}
else if (definedItem.getGVRVideoSceneObject() != null) {
GVRVideoSceneObjectPlayer gvrVideoSceneObjectPlayer = definedItem.getGVRVideoSceneObject().getMediaPlayer();
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field),"speed") ) {
if ( gvrVideoSceneObjectPlayer == null) {
// special case upon initialization of the movie texture, so the speed is init to 1
scriptParameters.add( 1 );
}
else if ( gvrVideoSceneObjectPlayer.getPlayer() == null) {
; // could occur prior to movie engine is setup
}
else {
ExoPlayer exoPlayer = (ExoPlayer) gvrVideoSceneObjectPlayer.getPlayer();
PlaybackParameters currPlaybackParamters = exoPlayer.getPlaybackParameters();
scriptParameters.add( currPlaybackParamters.speed );
}
} // end check for speed
} // end if SFFloat GVRVideoSceneObject
} // end if SFFloat
else if (fieldType.equalsIgnoreCase("SFTime")) {
if (definedItem.getGVRVideoSceneObject() != null) {
GVRVideoSceneObjectPlayer gvrVideoSceneObjectPlayer = definedItem.getGVRVideoSceneObject().getMediaPlayer();
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field),"duration") ) {
if ( gvrVideoSceneObjectPlayer == null) {
// special case upon initialization of the movie texture, so the speed is init to 1
scriptParameters.add( 1 );
}
else if ( gvrVideoSceneObjectPlayer.getPlayer() == null) {
; // could occur prior to movie engine is setup
}
else {
ExoPlayer exoPlayer = (ExoPlayer) gvrVideoSceneObjectPlayer.getPlayer();
scriptParameters.add( exoPlayer.getDuration() );
}
} // end check for duration
else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field),"elapsedTime") ) {
if ( gvrVideoSceneObjectPlayer == null) {
// special case upon initialization of the movie texture, so the elapsedTime is init to 0
scriptParameters.add( 0 );
}
else if ( gvrVideoSceneObjectPlayer.getPlayer() == null) {
; // could occur prior to movie engine is setup
}
else {
ExoPlayer exoPlayer = (ExoPlayer) gvrVideoSceneObjectPlayer.getPlayer();
// getContentPosition is for possible advertisements, and returns the same
// value as getCurrentPosition if no ads.
scriptParameters.add( exoPlayer.getContentPosition() );
}
} // end check for elapsedTime
} // end if SFTime GVRVideoSceneObject
} // end if SFTime
else if (fieldType.equalsIgnoreCase("SFInt32")) {
int parameter = 0;
if (definedItem.getGVRSceneObject() != null) {
GVRComponent gvrComponent = definedItem.getGVRSceneObject().getComponent(GVRSwitch.getComponentType());
if (gvrComponent != null) {
if (gvrComponent instanceof GVRSwitch) {
// We have a Switch node
GVRSwitch gvrSwitch = (GVRSwitch) gvrComponent;
parameter = gvrSwitch.getSwitchIndex();
}
}
}
scriptParameters.add(parameter);
}
else if (fieldType.equalsIgnoreCase("SFString")) {
if ( definedItem.getGVRTextViewSceneObject() != null) {
if (scriptObject.getFromDefinedItemField(field).equalsIgnoreCase("style")) {
GVRTextViewSceneObject.fontStyleTypes styleType =
definedItem.getGVRTextViewSceneObject().getStyleType();
String fontStyle = "";
if (styleType == GVRTextViewSceneObject.fontStyleTypes.PLAIN)
fontStyle = "PLAIN";
else if (styleType == GVRTextViewSceneObject.fontStyleTypes.BOLD)
fontStyle = "BOLD";
else if (styleType == GVRTextViewSceneObject.fontStyleTypes.BOLDITALIC)
fontStyle = "BOLDITALIC";
else if (styleType == GVRTextViewSceneObject.fontStyleTypes.ITALIC)
fontStyle = "ITALIC";
if (fontStyle != "") scriptParameters.add("\'" + fontStyle + "\'");
else Log.e(TAG, "style in ROUTE not recognized.");
}
}
} // end SFString
else if (fieldType.equalsIgnoreCase("MFString")) {
//TODO: will need to handle multiple strings particularly for Text node
GVRTexture gvrTexture = definedItem.getGVRTexture();
if (gvrTexture != null) {
// have a url containting a texture map
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "url") ) {
GVRImage gvrImage = gvrTexture.getImage();
if ( gvrImage != null ) {
if ( gvrImage.getFileName() != null) {
scriptParameters.add("\'" + gvrImage.getFileName() + "\'");
}
}
else Log.e(TAG, "ImageTexture name not DEFined");
}
else Log.e(TAG, "ImageTexture SCRIPT node url field not found");
}
else Log.e(TAG, "Unable to set MFString in SCRIPT node");
} // end MFString
} // end if definedItem != null
} // end INPUT_ONLY, INPUT_OUTPUT (only ways to pass parameters to JS parser
} // for loop checking for parameters passed to the JavaScript parser
// create the parameters array
if (scriptObject.getTimeStampParameter())
scriptParameters.add(1, 0); // insert the timeStamp parameter if it's used
Object[] parameters = new Object[scriptParameters.size()];
for (int i = 0; i < scriptParameters.size(); i++) {
parameters[i] = scriptParameters.get(i);
}
return parameters;
} } | public class class_name {
private Object[] SetJavaScriptArguments(InteractiveObject interactiveObj,
Object argument0, Object argument1, Object argument2, Object argument3, boolean stateChanged) {
ArrayList<Object> scriptParameters = new ArrayList<Object>();
ScriptObject scriptObject = interactiveObj.getScriptObject();
// Get the parameters/values passed to the Script/JavaScript
for (ScriptObject.Field field : scriptObject.getFieldsArrayList()) {
if ((scriptObject.getFieldAccessType(field) == ScriptObject.AccessType.INPUT_OUTPUT) ||
(scriptObject.getFieldAccessType(field) == ScriptObject.AccessType.INPUT_ONLY)) {
String fieldType = scriptObject.getFieldType(field);
DefinedItem definedItem = scriptObject.getFromDefinedItem(field);
EventUtility eventUtility = scriptObject.getFromEventUtility(field);
TimeSensor timeSensor = scriptObject.getFromTimeSensor(field);
if (fieldType.equalsIgnoreCase("SFBool")) {
if (definedItem != null) {
if (definedItem.getGVRSceneObject() != null) {
GVRComponent gvrComponent = definedItem.getGVRSceneObject().getComponent(
GVRLight.getComponentType());
if (gvrComponent != null) {
scriptParameters.add(gvrComponent.isEnabled()); // depends on control dependency: [if], data = [(gvrComponent]
}
}
}
else if (eventUtility != null) {
scriptParameters.add( eventUtility.getToggle() ); // depends on control dependency: [if], data = [none]
}
else if (interactiveObj.getSensorFromField() != null) {
if (interactiveObj.getSensorFromField().equals(Sensor.IS_OVER)) {
scriptParameters.add(argument0); // depends on control dependency: [if], data = [none]
}
else if (interactiveObj.getSensorFromField().equals(Sensor.IS_ACTIVE)) {
scriptParameters.add(!stateChanged); // depends on control dependency: [if], data = [none]
}
}
else if ( interactiveObj.getEventUtility() != null) {
scriptParameters.add( interactiveObj.getEventUtility().getToggle() ); // depends on control dependency: [if], data = [( interactiveObj.getEventUtility()]
}
} // end if SFBool
else if ((fieldType.equalsIgnoreCase("SFVec2f")) && (definedItem == null)) {
// data from a Plane Sensor
if (interactiveObj.getSensorFromField() != null) {
if (interactiveObj.getSensor().getSensorType() == Sensor.Type.PLANE) {
scriptParameters.add( argument0 ); // depends on control dependency: [if], data = [none]
scriptParameters.add( argument1 ); // depends on control dependency: [if], data = [none]
}
}
}
else if ((fieldType.equalsIgnoreCase("SFFloat")) && (definedItem == null)) {
if (timeSensor != null) {
scriptParameters.add( timeSensor.getCycleInterval() ); // depends on control dependency: [if], data = [none]
}
else scriptParameters.add(argument0); // the time passed in from an SFTime node
}
else if ((fieldType.equalsIgnoreCase("SFRotation")) && (definedItem == null)) {
// data from a Cylinder or Sphere Sensor
if (interactiveObj.getSensorFromField() != null) {
if (interactiveObj.getSensor().getSensorType() == Sensor.Type.CYLINDER) {
scriptParameters.add(argument0); // depends on control dependency: [if], data = [none]
scriptParameters.add(argument1); // depends on control dependency: [if], data = [none]
scriptParameters.add(argument2); // depends on control dependency: [if], data = [none]
scriptParameters.add(argument3); // depends on control dependency: [if], data = [none]
}
else if (interactiveObj.getSensor().getSensorType() == Sensor.Type.SPHERE) {
scriptParameters.add(argument0); // depends on control dependency: [if], data = [none]
scriptParameters.add(argument1); // depends on control dependency: [if], data = [none]
scriptParameters.add(argument2); // depends on control dependency: [if], data = [none]
scriptParameters.add(argument3); // depends on control dependency: [if], data = [none]
}
}
}
else if (scriptObject.getFromDefinedItem(field) != null) {
if (fieldType.equalsIgnoreCase("SFColor")) {
float[] color = {0, 0, 0};
if (definedItem.getGVRMaterial() != null) {
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "diffuseColor") ) {
float[] diffuseColor = definedItem.getGVRMaterial().getVec4("diffuse_color");
for (int i = 0; i < 3; i++) {
color[i] = diffuseColor[i]; // only get the first 3 values, not the alpha value // depends on control dependency: [for], data = [i]
}
} else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "emissiveColor") ) {
float[] emissiveColor = definedItem.getGVRMaterial().getVec4("emissive_color");
for (int i = 0; i < 3; i++) {
color[i] = emissiveColor[i]; // only get the first 3 values, not the alpha value // depends on control dependency: [for], data = [i]
}
} else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "specularColor") ) {
float[] specularColor = definedItem.getGVRMaterial().getVec4("specular_color");
for (int i = 0; i < 3; i++) {
color[i] = specularColor[i]; // only get the first 3 values, not the alpha value // depends on control dependency: [for], data = [i]
}
}
} else if (definedItem.getGVRSceneObject() != null) {
// likely a light object so get its properties
GVRComponent gvrComponent = definedItem.getGVRSceneObject().getComponent(
GVRLight.getComponentType());
if (gvrComponent != null) {
float[] lightColor = {0, 0, 0, 0};
if (gvrComponent instanceof GVRSpotLight) {
GVRSpotLight gvrSpotLightBase = (GVRSpotLight) gvrComponent;
lightColor = gvrSpotLightBase.getDiffuseIntensity(); // depends on control dependency: [if], data = [none]
} else if (gvrComponent instanceof GVRPointLight) {
GVRPointLight gvrPointLightBase = (GVRPointLight) gvrComponent;
lightColor = gvrPointLightBase.getDiffuseIntensity(); // depends on control dependency: [if], data = [none]
} else if (gvrComponent instanceof GVRDirectLight) {
GVRDirectLight gvrDirectLightBase = (GVRDirectLight) gvrComponent;
lightColor = gvrDirectLightBase.getDiffuseIntensity(); // depends on control dependency: [if], data = [none]
}
for (int i = 0; i < 3; i++) {
color[i] = lightColor[i]; // only get the first 3 values, not the alpha value // depends on control dependency: [for], data = [i]
}
}
}
// append the parameters of the SFColor passed to the SCRIPT's javascript code
for (int i = 0; i < color.length; i++) {
scriptParameters.add(color[i]); // depends on control dependency: [for], data = [i]
}
} // end if SFColor
else if (fieldType.equalsIgnoreCase("SFRotation")) {
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "rotation") ) {
if (definedItem.getGVRSceneObject() != null) {
// Likely the rotation in a Transform / GVRTransform
// GearVRf saves rotations as quaternions, but X3D scripting uses AxisAngle
// So, these values were saved as AxisAngle in the DefinedItem object
scriptParameters.add(definedItem.getAxisAngle().x); // depends on control dependency: [if], data = [none]
scriptParameters.add(definedItem.getAxisAngle().y); // depends on control dependency: [if], data = [none]
scriptParameters.add(definedItem.getAxisAngle().z); // depends on control dependency: [if], data = [none]
scriptParameters.add(definedItem.getAxisAngle().angle); // depends on control dependency: [if], data = [none]
}
} // rotation parameter
else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "orientation") ) {
if ( definedItem.getViewpoint() != null ) {
// have a Viewpoint which for the time-being means get the current direction of the camera
float[] lookAt = gvrContext.getMainScene().getMainCameraRig().getLookAt();
Vector3f cameraDir = new Vector3f(lookAt[0], lookAt[1], lookAt[2]);
Quaternionf q = ConvertDirectionalVectorToQuaternion(cameraDir);
AxisAngle4f cameraAxisAngle = new AxisAngle4f();
q.get(cameraAxisAngle); // depends on control dependency: [if], data = [none]
scriptParameters.add( cameraAxisAngle.x ); // depends on control dependency: [if], data = [none]
scriptParameters.add( cameraAxisAngle.y ); // depends on control dependency: [if], data = [none]
scriptParameters.add( cameraAxisAngle.z ); // depends on control dependency: [if], data = [none]
scriptParameters.add( cameraAxisAngle.angle ); // depends on control dependency: [if], data = [none]
}
} // orientation parameter
} // end if SFRotation
else if (fieldType.equalsIgnoreCase("SFVec3f")) {
if (definedItem.getGVRSceneObject() != null) {
GVRComponent gvrComponent = definedItem.getGVRSceneObject().getComponent(
GVRLight.getComponentType());
if (gvrComponent != null) {
// it's a light
float[] parameter = {0, 0, 0};
if (gvrComponent instanceof GVRSpotLight) {
GVRSpotLight gvrSpotLightBase = (GVRSpotLight) gvrComponent;
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "attenuation") ) {
parameter[0] = gvrSpotLightBase.getAttenuationConstant(); // depends on control dependency: [if], data = [none]
parameter[1] = gvrSpotLightBase.getAttenuationLinear(); // depends on control dependency: [if], data = [none]
parameter[2] = gvrSpotLightBase.getAttenuationQuadratic(); // depends on control dependency: [if], data = [none]
} else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "location") ) {
parameter[0] = definedItem.getGVRSceneObject().getTransform().getPositionX(); // depends on control dependency: [if], data = [none]
parameter[1] = definedItem.getGVRSceneObject().getTransform().getPositionY(); // depends on control dependency: [if], data = [none]
parameter[2] = definedItem.getGVRSceneObject().getTransform().getPositionZ(); // depends on control dependency: [if], data = [none]
} else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "direction") ) {
parameter[0] = definedItem.getDirection().x; // depends on control dependency: [if], data = [none]
parameter[1] = definedItem.getDirection().y; // depends on control dependency: [if], data = [none]
parameter[2] = definedItem.getDirection().z; // depends on control dependency: [if], data = [none]
}
} else if (gvrComponent instanceof GVRPointLight) {
GVRPointLight gvrPointLightBase = (GVRPointLight) gvrComponent;
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "attenuation") ) {
parameter[0] = gvrPointLightBase.getAttenuationConstant(); // depends on control dependency: [if], data = [none]
parameter[1] = gvrPointLightBase.getAttenuationLinear(); // depends on control dependency: [if], data = [none]
parameter[2] = gvrPointLightBase.getAttenuationQuadratic(); // depends on control dependency: [if], data = [none]
} else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "location") ) {
parameter[0] = definedItem.getGVRSceneObject().getTransform().getPositionX(); // depends on control dependency: [if], data = [none]
parameter[1] = definedItem.getGVRSceneObject().getTransform().getPositionY(); // depends on control dependency: [if], data = [none]
parameter[2] = definedItem.getGVRSceneObject().getTransform().getPositionZ(); // depends on control dependency: [if], data = [none]
}
} else if (gvrComponent instanceof GVRDirectLight) {
GVRDirectLight gvrDirectLightBase = (GVRDirectLight) gvrComponent;
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "direction") ) {
parameter[0] = definedItem.getDirection().x; // depends on control dependency: [if], data = [none]
parameter[1] = definedItem.getDirection().y; // depends on control dependency: [if], data = [none]
parameter[2] = definedItem.getDirection().z; // depends on control dependency: [if], data = [none]
}
} // end GVRDirectLight
// append the parameters of the lights passed to the SCRIPT's javascript code
for (int i = 0; i < parameter.length; i++) {
scriptParameters.add(parameter[i]); // depends on control dependency: [for], data = [i]
}
} // end gvrComponent != null. it's a light
else {
if (definedItem.getGVRSceneObject() != null) {
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "translation") ) {
GVRSceneObject gvrSceneObjectTranslation = root
.getSceneObjectByName((definedItem.getGVRSceneObject().getName() + x3dObject.TRANSFORM_TRANSLATION_));
scriptParameters.add(gvrSceneObjectTranslation.getTransform().getPositionX()); // depends on control dependency: [if], data = [none]
scriptParameters.add(gvrSceneObjectTranslation.getTransform().getPositionY()); // depends on control dependency: [if], data = [none]
scriptParameters.add(gvrSceneObjectTranslation.getTransform().getPositionZ()); // depends on control dependency: [if], data = [none]
} else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "scale") ) {
GVRSceneObject gvrSceneObjectScale = root
.getSceneObjectByName((definedItem.getGVRSceneObject().getName() + x3dObject.TRANSFORM_SCALE_));
scriptParameters.add(gvrSceneObjectScale.getTransform().getScaleX()); // depends on control dependency: [if], data = [none]
scriptParameters.add(gvrSceneObjectScale.getTransform().getScaleY()); // depends on control dependency: [if], data = [none]
scriptParameters.add(gvrSceneObjectScale.getTransform().getScaleZ()); // depends on control dependency: [if], data = [none]
}
}
}
} // end SFVec3f GVRSceneObject
} // end if SFVec3f
else if (fieldType.equalsIgnoreCase("SFVec2f")) {
float[] parameter = {0, 0};
if (definedItem.getGVRMaterial() != null) {
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "translation") ) {
parameter[0] = definedItem.getTextureTranslation().getX(); // depends on control dependency: [if], data = [none]
parameter[1] = -definedItem.getTextureTranslation().getY(); // depends on control dependency: [if], data = [none]
}
else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "scale") ) {
parameter[0] = definedItem.getTextureScale().getX(); // depends on control dependency: [if], data = [none]
parameter[1] = definedItem.getTextureScale().getY(); // depends on control dependency: [if], data = [none]
}
else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "center") ) {
parameter[0] = -definedItem.getTextureCenter().getX(); // depends on control dependency: [if], data = [none]
parameter[1] = definedItem.getTextureCenter().getY(); // depends on control dependency: [if], data = [none]
}
// append the parameters of the lights passed to the SCRIPT's javascript code
for (int i = 0; i < parameter.length; i++) {
scriptParameters.add(parameter[i]); // depends on control dependency: [for], data = [i]
}
} // end SFVec3f GVRMaterial
} // end if SFVec2f
else if (fieldType.equalsIgnoreCase("SFFloat")) {
if (definedItem.getGVRMaterial() != null) {
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "shininess") ) {
scriptParameters.add(
definedItem.getGVRMaterial().getFloat("specular_exponent")
); // depends on control dependency: [if], data = [none]
}
else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "transparency") ) {
scriptParameters.add(definedItem.getGVRMaterial().getOpacity()); // depends on control dependency: [if], data = [none]
}
else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "rotation") ) {
scriptParameters.add(definedItem.getTextureRotation().getValue()); // depends on control dependency: [if], data = [none]
}
} else if (definedItem.getGVRSceneObject() != null) {
// checking if it's a light
GVRComponent gvrComponent = definedItem.getGVRSceneObject().getComponent(
GVRLight.getComponentType());
if (gvrComponent != null) {
float parameter = 0;
if (gvrComponent instanceof GVRSpotLight) {
GVRSpotLight gvrSpotLightBase = (GVRSpotLight) gvrComponent;
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "beamWidth") ) {
parameter = gvrSpotLightBase.getInnerConeAngle() * (float) Math.PI / 180; // depends on control dependency: [if], data = [none]
} else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "cutOffAngle") ) {
parameter = gvrSpotLightBase.getOuterConeAngle() * (float) Math.PI / 180; // depends on control dependency: [if], data = [none]
}
} else if (gvrComponent instanceof GVRPointLight) {
GVRPointLight gvrPointLightBase = (GVRPointLight) gvrComponent;
} else if (gvrComponent instanceof GVRDirectLight) {
GVRDirectLight gvrDirectLightBase = (GVRDirectLight) gvrComponent;
}
scriptParameters.add(parameter); // depends on control dependency: [if], data = [none]
}
}
else if (definedItem.getGVRVideoSceneObject() != null) {
GVRVideoSceneObjectPlayer gvrVideoSceneObjectPlayer = definedItem.getGVRVideoSceneObject().getMediaPlayer();
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field),"speed") ) {
if ( gvrVideoSceneObjectPlayer == null) {
// special case upon initialization of the movie texture, so the speed is init to 1
scriptParameters.add( 1 ); // depends on control dependency: [if], data = [none]
}
else if ( gvrVideoSceneObjectPlayer.getPlayer() == null) {
; // could occur prior to movie engine is setup
}
else {
ExoPlayer exoPlayer = (ExoPlayer) gvrVideoSceneObjectPlayer.getPlayer();
PlaybackParameters currPlaybackParamters = exoPlayer.getPlaybackParameters();
scriptParameters.add( currPlaybackParamters.speed ); // depends on control dependency: [if], data = [none]
}
} // end check for speed
} // end if SFFloat GVRVideoSceneObject
} // end if SFFloat
else if (fieldType.equalsIgnoreCase("SFTime")) {
if (definedItem.getGVRVideoSceneObject() != null) {
GVRVideoSceneObjectPlayer gvrVideoSceneObjectPlayer = definedItem.getGVRVideoSceneObject().getMediaPlayer();
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field),"duration") ) {
if ( gvrVideoSceneObjectPlayer == null) {
// special case upon initialization of the movie texture, so the speed is init to 1
scriptParameters.add( 1 ); // depends on control dependency: [if], data = [none]
}
else if ( gvrVideoSceneObjectPlayer.getPlayer() == null) {
; // could occur prior to movie engine is setup
}
else {
ExoPlayer exoPlayer = (ExoPlayer) gvrVideoSceneObjectPlayer.getPlayer();
scriptParameters.add( exoPlayer.getDuration() ); // depends on control dependency: [if], data = [none]
}
} // end check for duration
else if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field),"elapsedTime") ) {
if ( gvrVideoSceneObjectPlayer == null) {
// special case upon initialization of the movie texture, so the elapsedTime is init to 0
scriptParameters.add( 0 ); // depends on control dependency: [if], data = [none]
}
else if ( gvrVideoSceneObjectPlayer.getPlayer() == null) {
; // could occur prior to movie engine is setup
}
else {
ExoPlayer exoPlayer = (ExoPlayer) gvrVideoSceneObjectPlayer.getPlayer();
// getContentPosition is for possible advertisements, and returns the same
// value as getCurrentPosition if no ads.
scriptParameters.add( exoPlayer.getContentPosition() ); // depends on control dependency: [if], data = [none]
}
} // end check for elapsedTime
} // end if SFTime GVRVideoSceneObject
} // end if SFTime
else if (fieldType.equalsIgnoreCase("SFInt32")) {
int parameter = 0;
if (definedItem.getGVRSceneObject() != null) {
GVRComponent gvrComponent = definedItem.getGVRSceneObject().getComponent(GVRSwitch.getComponentType());
if (gvrComponent != null) {
if (gvrComponent instanceof GVRSwitch) {
// We have a Switch node
GVRSwitch gvrSwitch = (GVRSwitch) gvrComponent;
parameter = gvrSwitch.getSwitchIndex(); // depends on control dependency: [if], data = [none]
}
}
}
scriptParameters.add(parameter);
}
else if (fieldType.equalsIgnoreCase("SFString")) {
if ( definedItem.getGVRTextViewSceneObject() != null) {
if (scriptObject.getFromDefinedItemField(field).equalsIgnoreCase("style")) {
GVRTextViewSceneObject.fontStyleTypes styleType =
definedItem.getGVRTextViewSceneObject().getStyleType();
String fontStyle = "";
if (styleType == GVRTextViewSceneObject.fontStyleTypes.PLAIN)
fontStyle = "PLAIN";
else if (styleType == GVRTextViewSceneObject.fontStyleTypes.BOLD)
fontStyle = "BOLD";
else if (styleType == GVRTextViewSceneObject.fontStyleTypes.BOLDITALIC)
fontStyle = "BOLDITALIC";
else if (styleType == GVRTextViewSceneObject.fontStyleTypes.ITALIC)
fontStyle = "ITALIC";
if (fontStyle != "") scriptParameters.add("\'" + fontStyle + "\'");
else Log.e(TAG, "style in ROUTE not recognized.");
}
}
} // end SFString
else if (fieldType.equalsIgnoreCase("MFString")) {
//TODO: will need to handle multiple strings particularly for Text node
GVRTexture gvrTexture = definedItem.getGVRTexture();
if (gvrTexture != null) {
// have a url containting a texture map
if ( StringFieldMatch( scriptObject.getFromDefinedItemField(field), "url") ) {
GVRImage gvrImage = gvrTexture.getImage();
if ( gvrImage != null ) {
if ( gvrImage.getFileName() != null) {
scriptParameters.add("\'" + gvrImage.getFileName() + "\'");
}
}
else Log.e(TAG, "ImageTexture name not DEFined");
}
else Log.e(TAG, "ImageTexture SCRIPT node url field not found");
}
else Log.e(TAG, "Unable to set MFString in SCRIPT node");
} // end MFString
} // end if definedItem != null
} // end INPUT_ONLY, INPUT_OUTPUT (only ways to pass parameters to JS parser
} // for loop checking for parameters passed to the JavaScript parser
// create the parameters array
if (scriptObject.getTimeStampParameter())
scriptParameters.add(1, 0); // insert the timeStamp parameter if it's used
Object[] parameters = new Object[scriptParameters.size()];
for (int i = 0; i < scriptParameters.size(); i++) {
parameters[i] = scriptParameters.get(i);
}
return parameters;
} } |
public class class_name {
protected void hookCurtainFinally(FwAssistantDirector assistantDirector) {
final FwCoreDirection coreDirection = assistantDirector.assistCoreDirection();
final CurtainFinallyHook hook = coreDirection.assistCurtainFinallyHook();
if (hook != null) {
hook.hook(assistantDirector);
}
} } | public class class_name {
protected void hookCurtainFinally(FwAssistantDirector assistantDirector) {
final FwCoreDirection coreDirection = assistantDirector.assistCoreDirection();
final CurtainFinallyHook hook = coreDirection.assistCurtainFinallyHook();
if (hook != null) {
hook.hook(assistantDirector); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static List<FileInfo> parseFileStatement(FileInfo parentContext, String statement)
{
Matcher fileMatcher = FileToken.matcher(statement);
if (! fileMatcher.lookingAt()) {
// This input does not start with FILE,
// so it's not a file command, it's something else.
// Return to caller a null and no errors.
return null;
}
String remainder = statement.substring(fileMatcher.end(), statement.length());
List<FileInfo> filesInfo = new ArrayList<>();
Matcher inlineBatchMatcher = DashInlineBatchToken.matcher(remainder);
if (inlineBatchMatcher.lookingAt()) {
remainder = remainder.substring(inlineBatchMatcher.end(), remainder.length());
Matcher delimiterMatcher = DelimiterToken.matcher(remainder);
// use matches here (not lookingAt) because we want to match
// all of the remainder, not just beginning
if (delimiterMatcher.matches()) {
String delimiter = delimiterMatcher.group(1);
filesInfo.add(new FileInfo(parentContext, FileOption.INLINEBATCH, delimiter));
return filesInfo;
}
throw new SQLParser.Exception(
"Did not find valid delimiter for \"file -inlinebatch\" command.");
}
// It is either a plain or a -batch file command.
FileOption option = FileOption.PLAIN;
Matcher batchMatcher = DashBatchToken.matcher(remainder);
if (batchMatcher.lookingAt()) {
option = FileOption.BATCH;
remainder = remainder.substring(batchMatcher.end(), remainder.length());
}
// remove spaces before and after filenames
remainder = remainder.trim();
// split filenames assuming they are separated by space ignoring spaces within quotes
// tests for parsing in TestSqlCmdInterface.java
List<String> filenames = new ArrayList<>();
Pattern regex = Pattern.compile("[^\\s\']+|'[^']*'");
Matcher regexMatcher = regex.matcher(remainder);
while (regexMatcher.find()) {
filenames.add(regexMatcher.group());
}
for (String filename : filenames) {
Matcher filenameMatcher = FilenameToken.matcher(filename);
// Use matches to match all input, not just beginning
if (filenameMatcher.matches()) {
filename = filenameMatcher.group(1);
// Trim whitespace from beginning and end of the file name.
// User may have wanted quoted whitespace at the beginning or end
// of the file name, but that seems very unlikely.
filename = filename.trim();
if (filename.startsWith("~")) {
filename = filename.replaceFirst("~", System.getProperty("user.home"));
}
filesInfo.add(new FileInfo(parentContext, option, filename));
}
}
// If no filename, or a filename of only spaces, then throw an error.
if ( filesInfo.size() == 0 ) {
String msg = String.format("Did not find valid file name in \"file%s\" command.",
option == FileOption.BATCH ? " -batch" : "");
throw new SQLParser.Exception(msg);
}
return filesInfo;
} } | public class class_name {
public static List<FileInfo> parseFileStatement(FileInfo parentContext, String statement)
{
Matcher fileMatcher = FileToken.matcher(statement);
if (! fileMatcher.lookingAt()) {
// This input does not start with FILE,
// so it's not a file command, it's something else.
// Return to caller a null and no errors.
return null; // depends on control dependency: [if], data = [none]
}
String remainder = statement.substring(fileMatcher.end(), statement.length());
List<FileInfo> filesInfo = new ArrayList<>();
Matcher inlineBatchMatcher = DashInlineBatchToken.matcher(remainder);
if (inlineBatchMatcher.lookingAt()) {
remainder = remainder.substring(inlineBatchMatcher.end(), remainder.length()); // depends on control dependency: [if], data = [none]
Matcher delimiterMatcher = DelimiterToken.matcher(remainder);
// use matches here (not lookingAt) because we want to match
// all of the remainder, not just beginning
if (delimiterMatcher.matches()) {
String delimiter = delimiterMatcher.group(1);
filesInfo.add(new FileInfo(parentContext, FileOption.INLINEBATCH, delimiter)); // depends on control dependency: [if], data = [none]
return filesInfo; // depends on control dependency: [if], data = [none]
}
throw new SQLParser.Exception(
"Did not find valid delimiter for \"file -inlinebatch\" command.");
}
// It is either a plain or a -batch file command.
FileOption option = FileOption.PLAIN;
Matcher batchMatcher = DashBatchToken.matcher(remainder);
if (batchMatcher.lookingAt()) {
option = FileOption.BATCH; // depends on control dependency: [if], data = [none]
remainder = remainder.substring(batchMatcher.end(), remainder.length()); // depends on control dependency: [if], data = [none]
}
// remove spaces before and after filenames
remainder = remainder.trim();
// split filenames assuming they are separated by space ignoring spaces within quotes
// tests for parsing in TestSqlCmdInterface.java
List<String> filenames = new ArrayList<>();
Pattern regex = Pattern.compile("[^\\s\']+|'[^']*'");
Matcher regexMatcher = regex.matcher(remainder);
while (regexMatcher.find()) {
filenames.add(regexMatcher.group()); // depends on control dependency: [while], data = [none]
}
for (String filename : filenames) {
Matcher filenameMatcher = FilenameToken.matcher(filename);
// Use matches to match all input, not just beginning
if (filenameMatcher.matches()) {
filename = filenameMatcher.group(1);
// Trim whitespace from beginning and end of the file name.
// User may have wanted quoted whitespace at the beginning or end
// of the file name, but that seems very unlikely.
filename = filename.trim();
if (filename.startsWith("~")) {
filename = filename.replaceFirst("~", System.getProperty("user.home"));
}
filesInfo.add(new FileInfo(parentContext, option, filename));
}
}
// If no filename, or a filename of only spaces, then throw an error.
if ( filesInfo.size() == 0 ) {
String msg = String.format("Did not find valid file name in \"file%s\" command.",
option == FileOption.BATCH ? " -batch" : "");
throw new SQLParser.Exception(msg);
}
return filesInfo;
} } |
public class class_name {
@CheckResult @WorkerThread
public Cursor query(@NonNull SupportSQLiteQuery query) {
Cursor cursor = getReadableDatabase().query(query);
if (logging) {
log("QUERY\n sql: %s", indentSql(query.getSql()));
}
return cursor;
} } | public class class_name {
@CheckResult @WorkerThread
public Cursor query(@NonNull SupportSQLiteQuery query) {
Cursor cursor = getReadableDatabase().query(query);
if (logging) {
log("QUERY\n sql: %s", indentSql(query.getSql())); // depends on control dependency: [if], data = [none]
}
return cursor;
} } |
public class class_name {
@Override
protected void loadDefaultProperties() {
for (P property : propertyClass.getEnumConstants()) {
try {
setProperty(property, property.getPropertyCharacteristics().getDefaultValue(), true);
} catch (PropertyException e) {
e.printStackTrace();
}
}
} } | public class class_name {
@Override
protected void loadDefaultProperties() {
for (P property : propertyClass.getEnumConstants()) {
try {
setProperty(property, property.getPropertyCharacteristics().getDefaultValue(), true);
// depends on control dependency: [try], data = [none]
} catch (PropertyException e) {
e.printStackTrace();
}
// depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public HString trimLeft(@NonNull Predicate<? super Annotation> toTrimPredicate) {
int start = 0;
while (start < tokenLength() && toTrimPredicate.test(tokenAt(start))) {
start++;
}
if (start < tokenLength()) {
return tokenAt(start).union(tokenAt(tokenLength() - 1));
}
return Fragments.empty(document());
} } | public class class_name {
public HString trimLeft(@NonNull Predicate<? super Annotation> toTrimPredicate) {
int start = 0;
while (start < tokenLength() && toTrimPredicate.test(tokenAt(start))) {
start++; // depends on control dependency: [while], data = [none]
}
if (start < tokenLength()) {
return tokenAt(start).union(tokenAt(tokenLength() - 1)); // depends on control dependency: [if], data = [(start]
}
return Fragments.empty(document());
} } |
public class class_name {
protected String convertMethodToMethodExp(Method method) {
if (method == null) {
return null;
}
final StringBuilder sb = new StringBuilder();
final Class<?> returnType = method.getReturnType();
sb.append(returnType != null ? returnType.getSimpleName() : "void"); // just in case
sb.append(" ").append(method.getName()).append("(");
final Class<?>[] parameterTypes = method.getParameterTypes();
int parameterIndex = 0;
for (Class<?> parameterType : parameterTypes) {
if (parameterIndex > 0) {
sb.append(", ");
}
sb.append(parameterType.getSimpleName());
++parameterIndex;
}
sb.append(")");
return sb.toString();
} } | public class class_name {
protected String convertMethodToMethodExp(Method method) {
if (method == null) {
return null; // depends on control dependency: [if], data = [none]
}
final StringBuilder sb = new StringBuilder();
final Class<?> returnType = method.getReturnType();
sb.append(returnType != null ? returnType.getSimpleName() : "void"); // just in case
sb.append(" ").append(method.getName()).append("(");
final Class<?>[] parameterTypes = method.getParameterTypes();
int parameterIndex = 0;
for (Class<?> parameterType : parameterTypes) {
if (parameterIndex > 0) {
sb.append(", ");
}
sb.append(parameterType.getSimpleName());
++parameterIndex;
}
sb.append(")");
return sb.toString();
} } |
public class class_name {
private VoltTable checkSnapshotFeasibility(String file_path, String file_nonce, JSONObject data, SnapshotFormat format)
{
VoltTable result = SnapshotUtil.constructNodeResultsTable();
SNAP_LOG.trace("Checking feasibility of save with path and nonce: " + file_path + ", " + file_nonce);
// Check if a snapshot is already in progress
if (SnapshotSiteProcessor.isSnapshotInProgress()) {
result.addRow(m_messenger.getHostId(), m_messenger.getHostname(), "", "FAILURE", "SNAPSHOT IN PROGRESS");
return result;
}
SnapshotRequestConfig config = null;
try {
config = new SnapshotRequestConfig(data, VoltDB.instance().getCatalogContext().database);
} catch (IllegalArgumentException e) {
// if we get exception here, it means table specified in snapshot doesn't exist in database.
result.addRow(m_messenger.getHostId(), m_messenger.getHostname(), "", "FAILURE", e.getMessage());
return result;
}
// Check if the snapshot file can be created successfully.
if (format.isFileBased()) {
// Check snapshot directory no matter table exists or not. If not, try to create the directory.
File parent = SnapshotUtil.constructFileForTable(new Table(), file_path, file_nonce, format, m_messenger.getHostId()).getParentFile();
if (!parent.exists() && !parent.mkdirs()) {
result.addRow(m_messenger.getHostId(), m_messenger.getHostname(), "", "FAILURE",
"FILE LOCATION UNWRITABLE: failed to create parent directory " + parent.getPath());
return result;
}
if (!parent.isDirectory() || !parent.canRead() || !parent.canWrite() || !parent.canExecute()) {
result.addRow(m_messenger.getHostId(), m_messenger.getHostname(), "", "FAILURE",
"FILE LOCATION UNWRITABLE: " + parent);
return result;
}
boolean sameNonceSnapshotExist = false;
Map<Table, String> tableToErrorMsg = new HashMap<>();
for (Table table : SnapshotUtil.getTablesToSave(VoltDB.instance().getCatalogContext().database)) {
String errMsg = null;
File saveFilePath =
SnapshotUtil.constructFileForTable(table, file_path, file_nonce, format, m_messenger.getHostId());
SNAP_LOG.trace("Host ID " + m_messenger.getHostId() +
" table: " + table.getTypeName() +
" to path: " + saveFilePath);
if (saveFilePath.exists()) {
sameNonceSnapshotExist = true;
//snapshot with same nonce exists, there is no need to check for other tables.
break;
}
try {
/*
* Sanity check that the file can be created
* and then delete it so empty files aren't
* orphaned if another part of the snapshot
* test fails.
*/
if (saveFilePath.createNewFile()) {
saveFilePath.delete();
}
} catch (IOException ex) {
errMsg = "FILE CREATION OF " + saveFilePath +
" RESULTED IN IOException: " + CoreUtils.throwableToString(ex);
}
if (errMsg != null) {
tableToErrorMsg.put(table, errMsg);
}
}
// Add error message only for tables included in current snapshot.
// If there exist any previous snapshot with same nonce, add sameNonceErrorMsg for each table,
// or add corresponding error message otherwise.
final String sameNonceErrorMsg = "SNAPSHOT FILE WITH SAME NONCE ALREADY EXISTS";
for (Table table : config.tables) {
if (sameNonceSnapshotExist) {
result.addRow(m_messenger.getHostId(), m_messenger.getHostname(), table.getTypeName(), "FAILURE", sameNonceErrorMsg);
} else if (tableToErrorMsg.containsKey(table)) {
result.addRow(m_messenger.getHostId(), m_messenger.getHostname(), table.getTypeName(), "FAILURE", tableToErrorMsg.get(table));
}
}
}
return result;
} } | public class class_name {
private VoltTable checkSnapshotFeasibility(String file_path, String file_nonce, JSONObject data, SnapshotFormat format)
{
VoltTable result = SnapshotUtil.constructNodeResultsTable();
SNAP_LOG.trace("Checking feasibility of save with path and nonce: " + file_path + ", " + file_nonce);
// Check if a snapshot is already in progress
if (SnapshotSiteProcessor.isSnapshotInProgress()) {
result.addRow(m_messenger.getHostId(), m_messenger.getHostname(), "", "FAILURE", "SNAPSHOT IN PROGRESS"); // depends on control dependency: [if], data = [none]
return result; // depends on control dependency: [if], data = [none]
}
SnapshotRequestConfig config = null;
try {
config = new SnapshotRequestConfig(data, VoltDB.instance().getCatalogContext().database); // depends on control dependency: [try], data = [none]
} catch (IllegalArgumentException e) {
// if we get exception here, it means table specified in snapshot doesn't exist in database.
result.addRow(m_messenger.getHostId(), m_messenger.getHostname(), "", "FAILURE", e.getMessage());
return result;
} // depends on control dependency: [catch], data = [none]
// Check if the snapshot file can be created successfully.
if (format.isFileBased()) {
// Check snapshot directory no matter table exists or not. If not, try to create the directory.
File parent = SnapshotUtil.constructFileForTable(new Table(), file_path, file_nonce, format, m_messenger.getHostId()).getParentFile();
if (!parent.exists() && !parent.mkdirs()) {
result.addRow(m_messenger.getHostId(), m_messenger.getHostname(), "", "FAILURE",
"FILE LOCATION UNWRITABLE: failed to create parent directory " + parent.getPath()); // depends on control dependency: [if], data = [none]
return result; // depends on control dependency: [if], data = [none]
}
if (!parent.isDirectory() || !parent.canRead() || !parent.canWrite() || !parent.canExecute()) {
result.addRow(m_messenger.getHostId(), m_messenger.getHostname(), "", "FAILURE",
"FILE LOCATION UNWRITABLE: " + parent); // depends on control dependency: [if], data = [none]
return result; // depends on control dependency: [if], data = [none]
}
boolean sameNonceSnapshotExist = false;
Map<Table, String> tableToErrorMsg = new HashMap<>();
for (Table table : SnapshotUtil.getTablesToSave(VoltDB.instance().getCatalogContext().database)) {
String errMsg = null;
File saveFilePath =
SnapshotUtil.constructFileForTable(table, file_path, file_nonce, format, m_messenger.getHostId());
SNAP_LOG.trace("Host ID " + m_messenger.getHostId() +
" table: " + table.getTypeName() +
" to path: " + saveFilePath); // depends on control dependency: [for], data = [none]
if (saveFilePath.exists()) {
sameNonceSnapshotExist = true; // depends on control dependency: [if], data = [none]
//snapshot with same nonce exists, there is no need to check for other tables.
break;
}
try {
/*
* Sanity check that the file can be created
* and then delete it so empty files aren't
* orphaned if another part of the snapshot
* test fails.
*/
if (saveFilePath.createNewFile()) {
saveFilePath.delete(); // depends on control dependency: [if], data = [none]
}
} catch (IOException ex) {
errMsg = "FILE CREATION OF " + saveFilePath +
" RESULTED IN IOException: " + CoreUtils.throwableToString(ex);
} // depends on control dependency: [catch], data = [none]
if (errMsg != null) {
tableToErrorMsg.put(table, errMsg); // depends on control dependency: [if], data = [none]
}
}
// Add error message only for tables included in current snapshot.
// If there exist any previous snapshot with same nonce, add sameNonceErrorMsg for each table,
// or add corresponding error message otherwise.
final String sameNonceErrorMsg = "SNAPSHOT FILE WITH SAME NONCE ALREADY EXISTS";
for (Table table : config.tables) {
if (sameNonceSnapshotExist) {
result.addRow(m_messenger.getHostId(), m_messenger.getHostname(), table.getTypeName(), "FAILURE", sameNonceErrorMsg); // depends on control dependency: [if], data = [none]
} else if (tableToErrorMsg.containsKey(table)) {
result.addRow(m_messenger.getHostId(), m_messenger.getHostname(), table.getTypeName(), "FAILURE", tableToErrorMsg.get(table)); // depends on control dependency: [if], data = [none]
}
}
}
return result;
} } |
public class class_name {
static TrileadVersionSupport getTrileadSupport() {
try {
if (isAfterTrilead8()) {
return createVersion9Instance();
}
} catch (Exception | LinkageError e) {
LOGGER.log(Level.WARNING, "Could not create Trilead support class. Using legacy Trilead features", e);
}
// We're on an old version of Triilead or couldn't create a new handler, fall back to legacy trilead handler
return new LegacyTrileadVersionSupport();
} } | public class class_name {
static TrileadVersionSupport getTrileadSupport() {
try {
if (isAfterTrilead8()) {
return createVersion9Instance(); // depends on control dependency: [if], data = [none]
}
} catch (Exception | LinkageError e) {
LOGGER.log(Level.WARNING, "Could not create Trilead support class. Using legacy Trilead features", e);
} // depends on control dependency: [catch], data = [none]
// We're on an old version of Triilead or couldn't create a new handler, fall back to legacy trilead handler
return new LegacyTrileadVersionSupport();
} } |
public class class_name {
public void init(TempCharBuffer head)
{
_top = head;
_head = head;
if (head != null) {
_buffer = head.buffer();
_length = head.getLength();
}
else
_length = 0;
_offset = 0;
} } | public class class_name {
public void init(TempCharBuffer head)
{
_top = head;
_head = head;
if (head != null) {
_buffer = head.buffer(); // depends on control dependency: [if], data = [none]
_length = head.getLength(); // depends on control dependency: [if], data = [none]
}
else
_length = 0;
_offset = 0;
} } |
public class class_name {
protected void startServingRPCServer() {
try {
stopRejectingRpcServer();
LOG.info("Starting gRPC server on address {}", mRpcBindAddress);
GrpcServerBuilder serverBuilder = GrpcServerBuilder.forAddress(
mRpcConnectAddress.getHostName(), mRpcBindAddress, ServerConfiguration.global());
registerServices(serverBuilder, mJobMaster.getServices());
mGrpcServer = serverBuilder.build().start();
LOG.info("Started gRPC server on address {}", mRpcConnectAddress);
// Wait until the server is shut down.
mGrpcServer.awaitTermination();
} catch (IOException e) {
throw new RuntimeException(e);
}
} } | public class class_name {
protected void startServingRPCServer() {
try {
stopRejectingRpcServer(); // depends on control dependency: [try], data = [none]
LOG.info("Starting gRPC server on address {}", mRpcBindAddress); // depends on control dependency: [try], data = [none]
GrpcServerBuilder serverBuilder = GrpcServerBuilder.forAddress(
mRpcConnectAddress.getHostName(), mRpcBindAddress, ServerConfiguration.global());
registerServices(serverBuilder, mJobMaster.getServices()); // depends on control dependency: [try], data = [none]
mGrpcServer = serverBuilder.build().start(); // depends on control dependency: [try], data = [none]
LOG.info("Started gRPC server on address {}", mRpcConnectAddress); // depends on control dependency: [try], data = [none]
// Wait until the server is shut down.
mGrpcServer.awaitTermination(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public EClass getIfcRelVoidsElement() {
if (ifcRelVoidsElementEClass == null) {
ifcRelVoidsElementEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(485);
}
return ifcRelVoidsElementEClass;
} } | public class class_name {
public EClass getIfcRelVoidsElement() {
if (ifcRelVoidsElementEClass == null) {
ifcRelVoidsElementEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(485);
// depends on control dependency: [if], data = [none]
}
return ifcRelVoidsElementEClass;
} } |
public class class_name {
public void visit(Visitor visitor) {
for (Map.Entry<String, NodeT> item : nodeTable.entrySet()) {
if (!visited.contains(item.getKey())) {
this.dfs(visitor, item.getValue());
}
}
visited.clear();
time = 0;
entryTime.clear();
exitTime.clear();
parent.clear();
processed.clear();
} } | public class class_name {
public void visit(Visitor visitor) {
for (Map.Entry<String, NodeT> item : nodeTable.entrySet()) {
if (!visited.contains(item.getKey())) {
this.dfs(visitor, item.getValue()); // depends on control dependency: [if], data = [none]
}
}
visited.clear();
time = 0;
entryTime.clear();
exitTime.clear();
parent.clear();
processed.clear();
} } |
public class class_name {
protected Resource getResourceByPath(String path)
{
String classPathPrefix = org.springframework.core.io.ResourceLoader.CLASSPATH_URL_PREFIX;
if(path.startsWith(classPathPrefix))
{
return super.getResourceByPath(path.substring(classPathPrefix.length()));
}
if (path != null && path.startsWith("/"))
{
path = path.substring(1);
}
return new FileSystemResource(path);
} } | public class class_name {
protected Resource getResourceByPath(String path)
{
String classPathPrefix = org.springframework.core.io.ResourceLoader.CLASSPATH_URL_PREFIX;
if(path.startsWith(classPathPrefix))
{
return super.getResourceByPath(path.substring(classPathPrefix.length())); // depends on control dependency: [if], data = [none]
}
if (path != null && path.startsWith("/"))
{
path = path.substring(1); // depends on control dependency: [if], data = [none]
}
return new FileSystemResource(path);
} } |
public class class_name {
public final EObject entryRuleOtherElement() throws RecognitionException {
EObject current = null;
EObject iv_ruleOtherElement = null;
try {
// InternalSimpleAntlr.g:737:2: (iv_ruleOtherElement= ruleOtherElement EOF )
// InternalSimpleAntlr.g:738:2: iv_ruleOtherElement= ruleOtherElement EOF
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getOtherElementRule());
}
pushFollow(FOLLOW_1);
iv_ruleOtherElement=ruleOtherElement();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current =iv_ruleOtherElement;
}
match(input,EOF,FOLLOW_2); if (state.failed) return current;
}
}
catch (RecognitionException re) {
recover(input,re);
appendSkippedTokens();
}
finally {
}
return current;
} } | public class class_name {
public final EObject entryRuleOtherElement() throws RecognitionException {
EObject current = null;
EObject iv_ruleOtherElement = null;
try {
// InternalSimpleAntlr.g:737:2: (iv_ruleOtherElement= ruleOtherElement EOF )
// InternalSimpleAntlr.g:738:2: iv_ruleOtherElement= ruleOtherElement EOF
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getOtherElementRule()); // depends on control dependency: [if], data = [none]
}
pushFollow(FOLLOW_1);
iv_ruleOtherElement=ruleOtherElement();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current =iv_ruleOtherElement; // depends on control dependency: [if], data = [none]
}
match(input,EOF,FOLLOW_2); if (state.failed) return current;
}
}
catch (RecognitionException re) {
recover(input,re);
appendSkippedTokens();
}
finally {
}
return current;
} } |
public class class_name {
public static ReplacedString replaceString(String s, String find, String replace) {
if (replace == null) replace = "-";
int index = -1;
int l = find.length();
boolean replaced = false;
do {
index = s.indexOf(find, index);
if (index >= 0) {
replaced = true;
s = s.substring(0, index) + replace + s.substring(index + l);
}
} while (index >= 0);
return new ReplacedString(s, replaced);
} } | public class class_name {
public static ReplacedString replaceString(String s, String find, String replace) {
if (replace == null) replace = "-";
int index = -1;
int l = find.length();
boolean replaced = false;
do {
index = s.indexOf(find, index);
if (index >= 0) {
replaced = true; // depends on control dependency: [if], data = [none]
s = s.substring(0, index) + replace + s.substring(index + l); // depends on control dependency: [if], data = [(index]
}
} while (index >= 0);
return new ReplacedString(s, replaced);
} } |
public class class_name {
public static void translate(Vector3d trans, Point3d[] x) {
for (Point3d p : x) {
p.add(trans);
}
} } | public class class_name {
public static void translate(Vector3d trans, Point3d[] x) {
for (Point3d p : x) {
p.add(trans); // depends on control dependency: [for], data = [p]
}
} } |
public class class_name {
public static void removeRowsInBody(
final SheetConfiguration sheetConfig,
final List<FacesRow> bodyRows, final int rowIndexStart,
final int rowIndexEnd) {
int top = sheetConfig.getBodyCellRange().getTopRow();
if ((rowIndexEnd < rowIndexStart) || (rowIndexStart < top)) {
return;
}
int irows = rowIndexEnd - rowIndexStart + 1;
for (int rowIndex = rowIndexEnd; rowIndex >= rowIndexStart; rowIndex--) {
bodyRows.remove(rowIndex - top);
}
for (int irow = rowIndexStart - top; irow < bodyRows
.size(); irow++) {
FacesRow facesrow = bodyRows.get(irow);
facesrow.setRowIndex(facesrow.getRowIndex() - irows);
}
} } | public class class_name {
public static void removeRowsInBody(
final SheetConfiguration sheetConfig,
final List<FacesRow> bodyRows, final int rowIndexStart,
final int rowIndexEnd) {
int top = sheetConfig.getBodyCellRange().getTopRow();
if ((rowIndexEnd < rowIndexStart) || (rowIndexStart < top)) {
return;
// depends on control dependency: [if], data = [none]
}
int irows = rowIndexEnd - rowIndexStart + 1;
for (int rowIndex = rowIndexEnd; rowIndex >= rowIndexStart; rowIndex--) {
bodyRows.remove(rowIndex - top);
// depends on control dependency: [for], data = [rowIndex]
}
for (int irow = rowIndexStart - top; irow < bodyRows
.size(); irow++) {
FacesRow facesrow = bodyRows.get(irow);
facesrow.setRowIndex(facesrow.getRowIndex() - irows);
// depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
public Object deserialise(final Node node)
{
if (node == null)
throw new IllegalArgumentException("Null argument passed to deserialise!");
final Unmarshaller unmarshaller = getUnmarshaller();
try
{
final Object obj = unmarshaller.unmarshal(node);
if (obj == null)
throw new RuntimeException("Error deserialising from " + node);
else
return obj;
}
catch (JAXBException e)
{
throw new JAXBRuntimeException("deserialisation", e);
}
} } | public class class_name {
public Object deserialise(final Node node)
{
if (node == null)
throw new IllegalArgumentException("Null argument passed to deserialise!");
final Unmarshaller unmarshaller = getUnmarshaller();
try
{
final Object obj = unmarshaller.unmarshal(node);
if (obj == null)
throw new RuntimeException("Error deserialising from " + node);
else
return obj;
}
catch (JAXBException e)
{
throw new JAXBRuntimeException("deserialisation", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void setPara(String text, byte paraLevel, byte[] embeddingLevels)
{
if (text == null) {
setPara(new char[0], paraLevel, embeddingLevels);
} else {
setPara(text.toCharArray(), paraLevel, embeddingLevels);
}
} } | public class class_name {
public void setPara(String text, byte paraLevel, byte[] embeddingLevels)
{
if (text == null) {
setPara(new char[0], paraLevel, embeddingLevels); // depends on control dependency: [if], data = [none]
} else {
setPara(text.toCharArray(), paraLevel, embeddingLevels); // depends on control dependency: [if], data = [(text]
}
} } |
public class class_name {
public static <T> String join(Iterator<T> iterator, CharSequence separator,
Functions.Function1<? super T, ? extends CharSequence> function) {
if (separator == null)
throw new NullPointerException("separator");
if (function == null)
throw new NullPointerException("function");
StringBuilder result = new StringBuilder();
while (iterator.hasNext()) {
T next = iterator.next();
CharSequence elementToString = function.apply(next);
result.append(elementToString);
if (iterator.hasNext())
result.append(separator);
}
return result.toString();
} } | public class class_name {
public static <T> String join(Iterator<T> iterator, CharSequence separator,
Functions.Function1<? super T, ? extends CharSequence> function) {
if (separator == null)
throw new NullPointerException("separator");
if (function == null)
throw new NullPointerException("function");
StringBuilder result = new StringBuilder();
while (iterator.hasNext()) {
T next = iterator.next();
CharSequence elementToString = function.apply(next);
result.append(elementToString); // depends on control dependency: [while], data = [none]
if (iterator.hasNext())
result.append(separator);
}
return result.toString();
} } |
public class class_name {
public AwsSecurityFindingFilters withSeverityLabel(StringFilter... severityLabel) {
if (this.severityLabel == null) {
setSeverityLabel(new java.util.ArrayList<StringFilter>(severityLabel.length));
}
for (StringFilter ele : severityLabel) {
this.severityLabel.add(ele);
}
return this;
} } | public class class_name {
public AwsSecurityFindingFilters withSeverityLabel(StringFilter... severityLabel) {
if (this.severityLabel == null) {
setSeverityLabel(new java.util.ArrayList<StringFilter>(severityLabel.length)); // depends on control dependency: [if], data = [none]
}
for (StringFilter ele : severityLabel) {
this.severityLabel.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public void marshall(LifecycleEventConfiguration lifecycleEventConfiguration, ProtocolMarshaller protocolMarshaller) {
if (lifecycleEventConfiguration == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(lifecycleEventConfiguration.getShutdown(), SHUTDOWN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(LifecycleEventConfiguration lifecycleEventConfiguration, ProtocolMarshaller protocolMarshaller) {
if (lifecycleEventConfiguration == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(lifecycleEventConfiguration.getShutdown(), SHUTDOWN_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
protected boolean prepare(final Context2D context, final Attributes attr, final double alpha)
{
final double w = attr.getWidth();
final double h = attr.getHeight();
final double r = attr.getCornerRadius();
if ((w > 0) && (h > 0))
{
context.beginPath();
if ((r > 0) && (r < (w / 2)) && (r < (h / 2)))
{
context.moveTo(r, 0);
context.lineTo(w - r, 0);
context.arc(w - r, r, r, (Math.PI * 3) / 2, 0, false);
context.lineTo(w, h - r);
context.arc(w - r, h - r, r, 0, Math.PI / 2, false);
context.lineTo(r, h);
context.arc(r, h - r, r, Math.PI / 2, Math.PI, false);
context.lineTo(0, r);
context.arc(r, r, r, Math.PI, (Math.PI * 3) / 2, false);
}
else
{
context.rect(0, 0, w, h);
}
context.closePath();
return true;
}
return false;
} } | public class class_name {
@Override
protected boolean prepare(final Context2D context, final Attributes attr, final double alpha)
{
final double w = attr.getWidth();
final double h = attr.getHeight();
final double r = attr.getCornerRadius();
if ((w > 0) && (h > 0))
{
context.beginPath(); // depends on control dependency: [if], data = [none]
if ((r > 0) && (r < (w / 2)) && (r < (h / 2)))
{
context.moveTo(r, 0); // depends on control dependency: [if], data = [none]
context.lineTo(w - r, 0); // depends on control dependency: [if], data = [none]
context.arc(w - r, r, r, (Math.PI * 3) / 2, 0, false); // depends on control dependency: [if], data = [none]
context.lineTo(w, h - r); // depends on control dependency: [if], data = [none]
context.arc(w - r, h - r, r, 0, Math.PI / 2, false); // depends on control dependency: [if], data = [none]
context.lineTo(r, h); // depends on control dependency: [if], data = [none]
context.arc(r, h - r, r, Math.PI / 2, Math.PI, false); // depends on control dependency: [if], data = [none]
context.lineTo(0, r); // depends on control dependency: [if], data = [none]
context.arc(r, r, r, Math.PI, (Math.PI * 3) / 2, false); // depends on control dependency: [if], data = [none]
}
else
{
context.rect(0, 0, w, h); // depends on control dependency: [if], data = [none]
}
context.closePath(); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
@Override public <G,B> Or<G,B> foldUntil(G accum,
Fn2<? super G,? super A,B> terminator,
Fn2<? super G,? super A,G> reducer) {
if (terminator == null) {
return Or.good(fold(accum, reducer));
}
if (reducer == null) {
throw new IllegalArgumentException("Can't fold with a null reduction function.");
}
// Yes, this is a cheap plastic imitation of what you'd hope for if you really need this
// method. The trouble is that when I implemented it correctly in _fold, I found
// it was going to be incredibly difficult, or more likely impossible to implement
// when the previous operation was flatMap, since you don't have the right result type to
// check against when you recurse in to the flat mapping function, and if you check the
// return from the recursion, it may have too many elements already.
// In XformTest.java, there's something marked "Early termination test" that illustrates
// this exact problem.
List<A> as = this.toMutableList();
for (A a : as) {
B term = terminator.apply(accum, a);
if (term != null) {
return Or.bad(term);
}
accum = reducer.apply(accum, a);
}
return Or.good(accum);
} } | public class class_name {
@Override public <G,B> Or<G,B> foldUntil(G accum,
Fn2<? super G,? super A,B> terminator,
Fn2<? super G,? super A,G> reducer) {
if (terminator == null) {
return Or.good(fold(accum, reducer)); // depends on control dependency: [if], data = [none]
}
if (reducer == null) {
throw new IllegalArgumentException("Can't fold with a null reduction function.");
}
// Yes, this is a cheap plastic imitation of what you'd hope for if you really need this
// method. The trouble is that when I implemented it correctly in _fold, I found
// it was going to be incredibly difficult, or more likely impossible to implement
// when the previous operation was flatMap, since you don't have the right result type to
// check against when you recurse in to the flat mapping function, and if you check the
// return from the recursion, it may have too many elements already.
// In XformTest.java, there's something marked "Early termination test" that illustrates
// this exact problem.
List<A> as = this.toMutableList();
for (A a : as) {
B term = terminator.apply(accum, a);
if (term != null) {
return Or.bad(term); // depends on control dependency: [if], data = [(term]
}
accum = reducer.apply(accum, a); // depends on control dependency: [for], data = [a]
}
return Or.good(accum); // depends on control dependency: [if], data = [none]
} } |
public class class_name {
@SuppressWarnings("unchecked")
@CheckReturnValue
@BackpressureSupport(BackpressureKind.FULL)
@SchedulerSupport(SchedulerSupport.NONE)
public final Flowable<T> startWithArray(T... items) {
Flowable<T> fromArray = fromArray(items);
if (fromArray == empty()) {
return RxJavaPlugins.onAssembly(this);
}
return concatArray(fromArray, this);
} } | public class class_name {
@SuppressWarnings("unchecked")
@CheckReturnValue
@BackpressureSupport(BackpressureKind.FULL)
@SchedulerSupport(SchedulerSupport.NONE)
public final Flowable<T> startWithArray(T... items) {
Flowable<T> fromArray = fromArray(items);
if (fromArray == empty()) {
return RxJavaPlugins.onAssembly(this); // depends on control dependency: [if], data = [none]
}
return concatArray(fromArray, this);
} } |
public class class_name {
public static void setBackgroundDrawable(View view, Drawable drawable) {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
view.setBackgroundDrawable(drawable);
} else {
view.setBackground(drawable);
}
} } | public class class_name {
public static void setBackgroundDrawable(View view, Drawable drawable) {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
view.setBackgroundDrawable(drawable); // depends on control dependency: [if], data = [none]
} else {
view.setBackground(drawable); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public int getAggregationDistinctColumnIndex(final int derivedSumIndex) {
for (Entry<Integer, Integer> entry : aggregationDistinctColumnIndexAndSumColumnIndexes.entrySet()) {
if (entry.getValue().equals(derivedSumIndex)) {
return entry.getKey();
}
}
throw new ShardingException("Can not get aggregation distinct column index.");
} } | public class class_name {
public int getAggregationDistinctColumnIndex(final int derivedSumIndex) {
for (Entry<Integer, Integer> entry : aggregationDistinctColumnIndexAndSumColumnIndexes.entrySet()) {
if (entry.getValue().equals(derivedSumIndex)) {
return entry.getKey(); // depends on control dependency: [if], data = [none]
}
}
throw new ShardingException("Can not get aggregation distinct column index.");
} } |
public class class_name {
public MappedField getMappedFieldByJavaField(final String name) {
for (final MappedField mf : persistenceFields) {
if (name.equals(mf.getJavaFieldName())) {
return mf;
}
}
return null;
} } | public class class_name {
public MappedField getMappedFieldByJavaField(final String name) {
for (final MappedField mf : persistenceFields) {
if (name.equals(mf.getJavaFieldName())) {
return mf; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
static public File computeAtlasDir(String name) {
File atlasDir = null;
if( null == name ) {
// Current dir
atlasDir = new File(".");
} else {
atlasDir = new File(name);
}
// Force absolute
if( false == atlasDir.isAbsolute() ){
atlasDir = atlasDir.getAbsoluteFile();
}
return atlasDir;
} } | public class class_name {
static public File computeAtlasDir(String name) {
File atlasDir = null;
if( null == name ) {
// Current dir
atlasDir = new File("."); // depends on control dependency: [if], data = [none]
} else {
atlasDir = new File(name); // depends on control dependency: [if], data = [none]
}
// Force absolute
if( false == atlasDir.isAbsolute() ){
atlasDir = atlasDir.getAbsoluteFile(); // depends on control dependency: [if], data = [none]
}
return atlasDir;
} } |
public class class_name {
protected String generateReport (String type, long now, boolean reset)
{
long sinceLast = now - _lastReportStamp;
long uptime = now - _serverStartTime;
StringBuilder report = new StringBuilder();
// add standard bits to the default report
if (DEFAULT_TYPE.equals(type)) {
report.append("- Uptime: ");
report.append(StringUtil.intervalToString(uptime)).append("\n");
report.append("- Report period: ");
report.append(StringUtil.intervalToString(sinceLast)).append("\n");
// report on the state of memory
Runtime rt = Runtime.getRuntime();
long total = rt.totalMemory(), max = rt.maxMemory();
long used = (total - rt.freeMemory());
report.append("- Memory: ").append(used/1024).append("k used, ");
report.append(total/1024).append("k total, ");
report.append(max/1024).append("k max\n");
}
for (Reporter rptr : _reporters.get(type)) {
try {
rptr.appendReport(report, now, sinceLast, reset);
} catch (Throwable t) {
log.warning("Reporter choked", "rptr", rptr, t);
}
}
/* The following Interval debug methods are no longer supported,
* but they could be added back easily if needed.
report.append("* samskivert.Interval:\n");
report.append("- Registered intervals: ");
report.append(Interval.registeredIntervalCount());
report.append("\n- Fired since last report: ");
report.append(Interval.getAndClearFiredIntervals());
report.append("\n");
*/
// strip off the final newline
int blen = report.length();
if (report.length() > 0 && report.charAt(blen-1) == '\n') {
report.delete(blen-1, blen);
}
// only reset the last report time if this is a periodic report
if (reset) {
_lastReportStamp = now;
}
return report.toString();
} } | public class class_name {
protected String generateReport (String type, long now, boolean reset)
{
long sinceLast = now - _lastReportStamp;
long uptime = now - _serverStartTime;
StringBuilder report = new StringBuilder();
// add standard bits to the default report
if (DEFAULT_TYPE.equals(type)) {
report.append("- Uptime: "); // depends on control dependency: [if], data = [none]
report.append(StringUtil.intervalToString(uptime)).append("\n"); // depends on control dependency: [if], data = [none]
report.append("- Report period: "); // depends on control dependency: [if], data = [none]
report.append(StringUtil.intervalToString(sinceLast)).append("\n"); // depends on control dependency: [if], data = [none]
// report on the state of memory
Runtime rt = Runtime.getRuntime();
long total = rt.totalMemory(), max = rt.maxMemory();
long used = (total - rt.freeMemory());
report.append("- Memory: ").append(used/1024).append("k used, "); // depends on control dependency: [if], data = [none]
report.append(total/1024).append("k total, "); // depends on control dependency: [if], data = [none]
report.append(max/1024).append("k max\n"); // depends on control dependency: [if], data = [none]
}
for (Reporter rptr : _reporters.get(type)) {
try {
rptr.appendReport(report, now, sinceLast, reset); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
log.warning("Reporter choked", "rptr", rptr, t);
} // depends on control dependency: [catch], data = [none]
}
/* The following Interval debug methods are no longer supported,
* but they could be added back easily if needed.
report.append("* samskivert.Interval:\n");
report.append("- Registered intervals: ");
report.append(Interval.registeredIntervalCount());
report.append("\n- Fired since last report: ");
report.append(Interval.getAndClearFiredIntervals());
report.append("\n");
*/
// strip off the final newline
int blen = report.length();
if (report.length() > 0 && report.charAt(blen-1) == '\n') {
report.delete(blen-1, blen); // depends on control dependency: [if], data = [none]
}
// only reset the last report time if this is a periodic report
if (reset) {
_lastReportStamp = now; // depends on control dependency: [if], data = [none]
}
return report.toString();
} } |
public class class_name {
@Override
public void emit(Sink sink, DataType dataType, String header) {
logger.fine("Generating data type " + dataType.name + ".");
sink.write(header);
sink.write(ASTPrinter.print(dataType));
sink.write("\n*/\n");
sink.write(ASTPrinter.printComments("", commentProcessor.leftAlign(dataType.comments)));
for (Annotation annotation : dataType.annotations) {
sink.write(ASTPrinter.print(annotation));
sink.write("\n");
}
if (dataType.constructors.size() == 1) {
emitSingleConstructor(sink, dataType, header);
} else {
emitMultipleConstructor(sink, dataType, header);
}
} } | public class class_name {
@Override
public void emit(Sink sink, DataType dataType, String header) {
logger.fine("Generating data type " + dataType.name + ".");
sink.write(header);
sink.write(ASTPrinter.print(dataType));
sink.write("\n*/\n");
sink.write(ASTPrinter.printComments("", commentProcessor.leftAlign(dataType.comments)));
for (Annotation annotation : dataType.annotations) {
sink.write(ASTPrinter.print(annotation)); // depends on control dependency: [for], data = [annotation]
sink.write("\n"); // depends on control dependency: [for], data = [none]
}
if (dataType.constructors.size() == 1) {
emitSingleConstructor(sink, dataType, header); // depends on control dependency: [if], data = [none]
} else {
emitMultipleConstructor(sink, dataType, header); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void inverse(double[] a) {
int n = a.length;
if (!Math.isPower2(n)) {
throw new IllegalArgumentException("The data vector size is not a power of 2.");
}
if (n < ncof) {
throw new IllegalArgumentException("The data vector size is less than wavelet coefficient size.");
}
int start = n >> (int) Math.floor(Math.log2(n/(ncof-1)));
for (int nn = start; nn <= n; nn <<= 1) {
backward(a, nn);
}
} } | public class class_name {
public void inverse(double[] a) {
int n = a.length;
if (!Math.isPower2(n)) {
throw new IllegalArgumentException("The data vector size is not a power of 2.");
}
if (n < ncof) {
throw new IllegalArgumentException("The data vector size is less than wavelet coefficient size.");
}
int start = n >> (int) Math.floor(Math.log2(n/(ncof-1)));
for (int nn = start; nn <= n; nn <<= 1) {
backward(a, nn); // depends on control dependency: [for], data = [nn]
}
} } |
public class class_name {
protected final RedisClusterConfiguration getClusterConfiguration() {
if (this.clusterConfiguration != null) {
return this.clusterConfiguration;
}
if (this.properties.getCluster() == null) {
return null;
}
RedisProperties.Cluster clusterProperties = this.properties.getCluster();
RedisClusterConfiguration config = new RedisClusterConfiguration(
clusterProperties.getNodes());
if (clusterProperties.getMaxRedirects() != null) {
config.setMaxRedirects(clusterProperties.getMaxRedirects());
}
if (this.properties.getPassword() != null) {
config.setPassword(RedisPassword.of(this.properties.getPassword()));
}
return config;
} } | public class class_name {
protected final RedisClusterConfiguration getClusterConfiguration() {
if (this.clusterConfiguration != null) {
return this.clusterConfiguration; // depends on control dependency: [if], data = [none]
}
if (this.properties.getCluster() == null) {
return null; // depends on control dependency: [if], data = [none]
}
RedisProperties.Cluster clusterProperties = this.properties.getCluster();
RedisClusterConfiguration config = new RedisClusterConfiguration(
clusterProperties.getNodes());
if (clusterProperties.getMaxRedirects() != null) {
config.setMaxRedirects(clusterProperties.getMaxRedirects()); // depends on control dependency: [if], data = [(clusterProperties.getMaxRedirects()]
}
if (this.properties.getPassword() != null) {
config.setPassword(RedisPassword.of(this.properties.getPassword())); // depends on control dependency: [if], data = [(this.properties.getPassword()]
}
return config;
} } |
public class class_name {
private void maybeUpdateExportObjectLiteral(NodeTraversal t, Node n) {
if (!currentScript.isModule) {
return;
}
Node parent = n.getParent();
Node rhs = parent.getLastChild();
if (rhs.isObjectLit()) {
for (Node c = rhs.getFirstChild(); c != null; c = c.getNext()) {
if (c.isComputedProp()) {
t.report(c, INVALID_EXPORT_COMPUTED_PROPERTY);
} else if (c.isStringKey()) {
if (!c.hasChildren()) {
c.addChildToBack(IR.name(c.getString()).useSourceInfoFrom(c));
}
Node value = c.getFirstChild();
maybeUpdateExportDeclToNode(t, c, value);
}
}
}
} } | public class class_name {
private void maybeUpdateExportObjectLiteral(NodeTraversal t, Node n) {
if (!currentScript.isModule) {
return; // depends on control dependency: [if], data = [none]
}
Node parent = n.getParent();
Node rhs = parent.getLastChild();
if (rhs.isObjectLit()) {
for (Node c = rhs.getFirstChild(); c != null; c = c.getNext()) {
if (c.isComputedProp()) {
t.report(c, INVALID_EXPORT_COMPUTED_PROPERTY); // depends on control dependency: [if], data = [none]
} else if (c.isStringKey()) {
if (!c.hasChildren()) {
c.addChildToBack(IR.name(c.getString()).useSourceInfoFrom(c)); // depends on control dependency: [if], data = [none]
}
Node value = c.getFirstChild();
maybeUpdateExportDeclToNode(t, c, value); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
private void maybeUpdateStats() {
// Update the free space if able to get the lock,
// with a frequency of once in RESTAT_INTERVAL_MS
if (lock.tryLock()) {
try {
if ((SystemClock.uptimeMillis() - mLastRestatTime) > RESTAT_INTERVAL_MS) {
updateStats();
}
} finally {
lock.unlock();
}
}
} } | public class class_name {
private void maybeUpdateStats() {
// Update the free space if able to get the lock,
// with a frequency of once in RESTAT_INTERVAL_MS
if (lock.tryLock()) {
try {
if ((SystemClock.uptimeMillis() - mLastRestatTime) > RESTAT_INTERVAL_MS) {
updateStats(); // depends on control dependency: [if], data = [none]
}
} finally {
lock.unlock();
}
}
} } |
public class class_name {
@Override
protected boolean isButtonEnabledForHistoryReference(HistoryReference historyReference) {
final SiteNode siteNode = getSiteNode(historyReference);
if (siteNode != null && !isButtonEnabledForSiteNode(siteNode)) {
return false;
}
return true;
} } | public class class_name {
@Override
protected boolean isButtonEnabledForHistoryReference(HistoryReference historyReference) {
final SiteNode siteNode = getSiteNode(historyReference);
if (siteNode != null && !isButtonEnabledForSiteNode(siteNode)) {
return false; // depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
private static <OriginObject, TargetObject> TargetObject setValue(OriginObject originObject, TargetObject targetObject, Class<TargetObject> targetClass) {
Field[] targetFields = ReflectUtil.getFieldArrayIncludeSupClassExcludeUID(targetClass);
Field originField = null; //目标字段类型
Object originValue = null; //原始对象属性值
Object targetValue = null; //目标对象属性值
//从目标对象中找原始对象的属性方式,
for (Field targetField : targetFields) {
originField = ReflectUtil.getField(originObject.getClass(), targetField.getName());
if (originField == null) { //目标对象有,但是原始对象中没有
continue;
}
if (Modifier.isStatic(originField.getModifiers())) {
continue;
}
targetField.setAccessible(true);
originField.setAccessible(true);
originValue = ReflectUtil.getFieldVal(originObject, targetField.getName());
if (originValue == null) { //从原始对象中获取的字段属性为null
continue;
}
targetValue = ValueCast.cast(targetField, targetObject, originValue);
if (targetValue != null) {
try {
targetField.set(targetObject, targetValue);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {//为目标属性赋值失败
e.printStackTrace();
}
}
}
return targetObject;
} } | public class class_name {
private static <OriginObject, TargetObject> TargetObject setValue(OriginObject originObject, TargetObject targetObject, Class<TargetObject> targetClass) {
Field[] targetFields = ReflectUtil.getFieldArrayIncludeSupClassExcludeUID(targetClass);
Field originField = null; //目标字段类型
Object originValue = null; //原始对象属性值
Object targetValue = null; //目标对象属性值
//从目标对象中找原始对象的属性方式,
for (Field targetField : targetFields) {
originField = ReflectUtil.getField(originObject.getClass(), targetField.getName()); // depends on control dependency: [for], data = [targetField]
if (originField == null) { //目标对象有,但是原始对象中没有
continue;
}
if (Modifier.isStatic(originField.getModifiers())) {
continue;
}
targetField.setAccessible(true); // depends on control dependency: [for], data = [targetField]
originField.setAccessible(true); // depends on control dependency: [for], data = [none]
originValue = ReflectUtil.getFieldVal(originObject, targetField.getName()); // depends on control dependency: [for], data = [targetField]
if (originValue == null) { //从原始对象中获取的字段属性为null
continue;
}
targetValue = ValueCast.cast(targetField, targetObject, originValue); // depends on control dependency: [for], data = [targetField]
if (targetValue != null) {
try {
targetField.set(targetObject, targetValue); // depends on control dependency: [try], data = [none]
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {//为目标属性赋值失败 // depends on control dependency: [catch], data = [none]
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
}
}
return targetObject;
} } |
public class class_name {
private long sumMatrix(int[][] mat) {
long ret = 0;
for(int i = 0; i < mat.length; i++) {
final int[] row = mat[i];
for(int j = 0; j < row.length; j++) {
ret += row[j];
}
}
return ret;
} } | public class class_name {
private long sumMatrix(int[][] mat) {
long ret = 0;
for(int i = 0; i < mat.length; i++) {
final int[] row = mat[i];
for(int j = 0; j < row.length; j++) {
ret += row[j]; // depends on control dependency: [for], data = [j]
}
}
return ret;
} } |
public class class_name {
public FloatBuffer getTexCoordBuffer(int coords) {
if (m_texcoords[coords] == null) {
return null;
}
return m_texcoords[coords].asFloatBuffer();
} } | public class class_name {
public FloatBuffer getTexCoordBuffer(int coords) {
if (m_texcoords[coords] == null) {
return null; // depends on control dependency: [if], data = [none]
}
return m_texcoords[coords].asFloatBuffer();
} } |
public class class_name {
public Bibliography makeBibliography(SelectionMode mode,
CSLItemData[] selection, CSLItemData[] quash) {
List<?> r;
try {
if ((selection == null || mode == null) && quash == null) {
r = runner.callMethod(engine, "makeBibliography", List.class);
} else {
Map<String, Object> args = new HashMap<>();
if (selection != null && mode != null) {
args.put(mode.toString(), selectionToList(selection));
}
if (quash != null) {
args.put("quash", selectionToList(quash));
}
r = runner.callMethod(engine, "makeBibliography",
List.class, args);
}
} catch (ScriptRunnerException e) {
throw new IllegalArgumentException("Could not make bibliography", e);
}
@SuppressWarnings("unchecked")
Map<String, Object> fpm = (Map<String, Object>)r.get(0);
List<CharSequence> entriesList = runner.convert(r.get(1), List.class);
String[] entries = new String[entriesList.size()];
for (int i = 0; i < entries.length; ++i) {
entries[i] = entriesList.get(i).toString();
}
int maxOffset = getFromMap(fpm, "maxoffset", 0);
int entrySpacing = getFromMap(fpm, "entryspacing", 0);
int lineSpacing = getFromMap(fpm, "linespacing", 0);
int hangingIndent = getFromMap(fpm, "hangingindent", 0);
boolean done = getFromMap(fpm, "done", false);
List<?> srcEntryIds = runner.convert(fpm.get("entry_ids"), List.class);
List<String> dstEntryIds = new ArrayList<>();
for (Object o : srcEntryIds) {
if (o instanceof Map) {
o = runner.convert(o, List.class);
}
if (o instanceof Collection) {
Collection<?> oc = (Collection<?>)o;
for (Object oco : oc) {
dstEntryIds.add(oco.toString());
}
} else {
dstEntryIds.add(o.toString());
}
}
String[] entryIds = dstEntryIds.toArray(new String[dstEntryIds.size()]);
SecondFieldAlign secondFieldAlign = SecondFieldAlign.FALSE;
Object sfa = fpm.get("second-field-align");
if (sfa != null) {
secondFieldAlign = SecondFieldAlign.fromString(sfa.toString());
}
String bibStart = getFromMap(fpm, "bibstart", "");
String bibEnd = getFromMap(fpm, "bibend", "");
//special treatment for some output formats
if (outputFormat.equals("fo")) {
//make reasonable margin for an average character width
String em = Math.max(2.5, maxOffset * 0.6) + "em";
for (int i = 0; i < entries.length; ++i) {
entries[i] = entries[i].replace("$$$__COLUMN_WIDTH_1__$$$", em);
}
}
return new Bibliography(entries, bibStart, bibEnd, entryIds,
maxOffset, entrySpacing, lineSpacing, hangingIndent,
done, secondFieldAlign);
} } | public class class_name {
public Bibliography makeBibliography(SelectionMode mode,
CSLItemData[] selection, CSLItemData[] quash) {
List<?> r;
try {
if ((selection == null || mode == null) && quash == null) {
r = runner.callMethod(engine, "makeBibliography", List.class); // depends on control dependency: [if], data = [none]
} else {
Map<String, Object> args = new HashMap<>();
if (selection != null && mode != null) {
args.put(mode.toString(), selectionToList(selection)); // depends on control dependency: [if], data = [(selection]
}
if (quash != null) {
args.put("quash", selectionToList(quash)); // depends on control dependency: [if], data = [(quash]
}
r = runner.callMethod(engine, "makeBibliography",
List.class, args); // depends on control dependency: [if], data = [none]
}
} catch (ScriptRunnerException e) {
throw new IllegalArgumentException("Could not make bibliography", e);
} // depends on control dependency: [catch], data = [none]
@SuppressWarnings("unchecked")
Map<String, Object> fpm = (Map<String, Object>)r.get(0);
List<CharSequence> entriesList = runner.convert(r.get(1), List.class);
String[] entries = new String[entriesList.size()];
for (int i = 0; i < entries.length; ++i) {
entries[i] = entriesList.get(i).toString(); // depends on control dependency: [for], data = [i]
}
int maxOffset = getFromMap(fpm, "maxoffset", 0);
int entrySpacing = getFromMap(fpm, "entryspacing", 0);
int lineSpacing = getFromMap(fpm, "linespacing", 0);
int hangingIndent = getFromMap(fpm, "hangingindent", 0);
boolean done = getFromMap(fpm, "done", false);
List<?> srcEntryIds = runner.convert(fpm.get("entry_ids"), List.class);
List<String> dstEntryIds = new ArrayList<>();
for (Object o : srcEntryIds) {
if (o instanceof Map) {
o = runner.convert(o, List.class); // depends on control dependency: [if], data = [none]
}
if (o instanceof Collection) {
Collection<?> oc = (Collection<?>)o;
for (Object oco : oc) {
dstEntryIds.add(oco.toString()); // depends on control dependency: [for], data = [oco]
}
} else {
dstEntryIds.add(o.toString()); // depends on control dependency: [if], data = [none]
}
}
String[] entryIds = dstEntryIds.toArray(new String[dstEntryIds.size()]);
SecondFieldAlign secondFieldAlign = SecondFieldAlign.FALSE;
Object sfa = fpm.get("second-field-align");
if (sfa != null) {
secondFieldAlign = SecondFieldAlign.fromString(sfa.toString()); // depends on control dependency: [if], data = [(sfa]
}
String bibStart = getFromMap(fpm, "bibstart", "");
String bibEnd = getFromMap(fpm, "bibend", "");
//special treatment for some output formats
if (outputFormat.equals("fo")) {
//make reasonable margin for an average character width
String em = Math.max(2.5, maxOffset * 0.6) + "em";
for (int i = 0; i < entries.length; ++i) {
entries[i] = entries[i].replace("$$$__COLUMN_WIDTH_1__$$$", em); // depends on control dependency: [for], data = [i]
}
}
return new Bibliography(entries, bibStart, bibEnd, entryIds,
maxOffset, entrySpacing, lineSpacing, hangingIndent,
done, secondFieldAlign);
} } |
public class class_name {
public static ZonedDateTime ofLocal(LocalDateTime localDateTime, ZoneId zone, ZoneOffset preferredOffset) {
Objects.requireNonNull(localDateTime, "localDateTime");
Objects.requireNonNull(zone, "zone");
if (zone instanceof ZoneOffset) {
return new ZonedDateTime(localDateTime, (ZoneOffset) zone, zone);
}
ZoneRules rules = zone.getRules();
List<ZoneOffset> validOffsets = rules.getValidOffsets(localDateTime);
ZoneOffset offset;
if (validOffsets.size() == 1) {
offset = validOffsets.get(0);
} else if (validOffsets.size() == 0) {
ZoneOffsetTransition trans = rules.getTransition(localDateTime);
localDateTime = localDateTime.plusSeconds(trans.getDuration().getSeconds());
offset = trans.getOffsetAfter();
} else {
if (preferredOffset != null && validOffsets.contains(preferredOffset)) {
offset = preferredOffset;
} else {
offset = Objects.requireNonNull(validOffsets.get(0), "offset"); // protect against bad ZoneRules
}
}
return new ZonedDateTime(localDateTime, offset, zone);
} } | public class class_name {
public static ZonedDateTime ofLocal(LocalDateTime localDateTime, ZoneId zone, ZoneOffset preferredOffset) {
Objects.requireNonNull(localDateTime, "localDateTime");
Objects.requireNonNull(zone, "zone");
if (zone instanceof ZoneOffset) {
return new ZonedDateTime(localDateTime, (ZoneOffset) zone, zone); // depends on control dependency: [if], data = [none]
}
ZoneRules rules = zone.getRules();
List<ZoneOffset> validOffsets = rules.getValidOffsets(localDateTime);
ZoneOffset offset;
if (validOffsets.size() == 1) {
offset = validOffsets.get(0); // depends on control dependency: [if], data = [none]
} else if (validOffsets.size() == 0) {
ZoneOffsetTransition trans = rules.getTransition(localDateTime);
localDateTime = localDateTime.plusSeconds(trans.getDuration().getSeconds()); // depends on control dependency: [if], data = [none]
offset = trans.getOffsetAfter(); // depends on control dependency: [if], data = [none]
} else {
if (preferredOffset != null && validOffsets.contains(preferredOffset)) {
offset = preferredOffset; // depends on control dependency: [if], data = [none]
} else {
offset = Objects.requireNonNull(validOffsets.get(0), "offset"); // protect against bad ZoneRules // depends on control dependency: [if], data = [none]
}
}
return new ZonedDateTime(localDateTime, offset, zone);
} } |
public class class_name {
public PolicyDetails withSchedules(Schedule... schedules) {
if (this.schedules == null) {
setSchedules(new java.util.ArrayList<Schedule>(schedules.length));
}
for (Schedule ele : schedules) {
this.schedules.add(ele);
}
return this;
} } | public class class_name {
public PolicyDetails withSchedules(Schedule... schedules) {
if (this.schedules == null) {
setSchedules(new java.util.ArrayList<Schedule>(schedules.length)); // depends on control dependency: [if], data = [none]
}
for (Schedule ele : schedules) {
this.schedules.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
private VolatileImage getImage(GraphicsConfiguration config, JComponent c, int w, int h, Object[] extendedCacheKeys) {
ImageCache imageCache = ImageCache.getInstance();
// get the buffer for this component
VolatileImage buffer = (VolatileImage) imageCache.getImage(config, w, h, this, extendedCacheKeys);
int renderCounter = 0; // to avoid any potential, though unlikely,
// infinite loop
do {
// validate the buffer so we can check for surface loss
int bufferStatus = VolatileImage.IMAGE_INCOMPATIBLE;
if (buffer != null) {
bufferStatus = buffer.validate(config);
}
// If the buffer status is incompatible or restored, then we need to
// re-render to the volatile image
if (bufferStatus == VolatileImage.IMAGE_INCOMPATIBLE || bufferStatus == VolatileImage.IMAGE_RESTORED) {
// if the buffer is null (hasn't been created), or isn't the
// right size, or has lost its contents,
// then recreate the buffer
if (buffer == null || buffer.getWidth() != w || buffer.getHeight() != h
|| bufferStatus == VolatileImage.IMAGE_INCOMPATIBLE) {
// clear any resources related to the old back buffer
if (buffer != null) {
buffer.flush();
buffer = null;
}
// recreate the buffer
buffer = config.createCompatibleVolatileImage(w, h, Transparency.TRANSLUCENT);
// put in cache for future
imageCache.setImage(buffer, config, w, h, this, extendedCacheKeys);
}
// create the graphics context with which to paint to the buffer
Graphics2D bg = buffer.createGraphics();
// clear the background before configuring the graphics
bg.setComposite(AlphaComposite.Clear);
bg.fillRect(0, 0, w, h);
bg.setComposite(AlphaComposite.SrcOver);
configureGraphics(bg);
// paint the painter into buffer
paintDirectly(bg, c, w, h, extendedCacheKeys);
// close buffer graphics
bg.dispose();
}
} while (buffer.contentsLost() && renderCounter++ < 3);
// check if we failed
if (renderCounter == 3)
return null;
// return image
return buffer;
} } | public class class_name {
private VolatileImage getImage(GraphicsConfiguration config, JComponent c, int w, int h, Object[] extendedCacheKeys) {
ImageCache imageCache = ImageCache.getInstance();
// get the buffer for this component
VolatileImage buffer = (VolatileImage) imageCache.getImage(config, w, h, this, extendedCacheKeys);
int renderCounter = 0; // to avoid any potential, though unlikely,
// infinite loop
do {
// validate the buffer so we can check for surface loss
int bufferStatus = VolatileImage.IMAGE_INCOMPATIBLE;
if (buffer != null) {
bufferStatus = buffer.validate(config); // depends on control dependency: [if], data = [none]
}
// If the buffer status is incompatible or restored, then we need to
// re-render to the volatile image
if (bufferStatus == VolatileImage.IMAGE_INCOMPATIBLE || bufferStatus == VolatileImage.IMAGE_RESTORED) {
// if the buffer is null (hasn't been created), or isn't the
// right size, or has lost its contents,
// then recreate the buffer
if (buffer == null || buffer.getWidth() != w || buffer.getHeight() != h
|| bufferStatus == VolatileImage.IMAGE_INCOMPATIBLE) {
// clear any resources related to the old back buffer
if (buffer != null) {
buffer.flush(); // depends on control dependency: [if], data = [none]
buffer = null; // depends on control dependency: [if], data = [none]
}
// recreate the buffer
buffer = config.createCompatibleVolatileImage(w, h, Transparency.TRANSLUCENT); // depends on control dependency: [if], data = [none]
// put in cache for future
imageCache.setImage(buffer, config, w, h, this, extendedCacheKeys); // depends on control dependency: [if], data = [(buffer]
}
// create the graphics context with which to paint to the buffer
Graphics2D bg = buffer.createGraphics();
// clear the background before configuring the graphics
bg.setComposite(AlphaComposite.Clear); // depends on control dependency: [if], data = [none]
bg.fillRect(0, 0, w, h); // depends on control dependency: [if], data = [none]
bg.setComposite(AlphaComposite.SrcOver); // depends on control dependency: [if], data = [none]
configureGraphics(bg); // depends on control dependency: [if], data = [none]
// paint the painter into buffer
paintDirectly(bg, c, w, h, extendedCacheKeys); // depends on control dependency: [if], data = [none]
// close buffer graphics
bg.dispose(); // depends on control dependency: [if], data = [none]
}
} while (buffer.contentsLost() && renderCounter++ < 3);
// check if we failed
if (renderCounter == 3)
return null;
// return image
return buffer;
} } |
public class class_name {
private String linesToCharsMunge(String text, List<String> lineArray,
Map<String, Integer> lineHash) {
int lineStart = 0;
int lineEnd = -1;
String line;
StringBuilder chars = new StringBuilder();
// Walk the text, pulling out a substring for each line.
// text.split('\n') would would temporarily double our memory footprint.
// Modifying text would create many large strings to garbage collect.
while (lineEnd < text.length() - 1) {
lineEnd = text.indexOf('\n', lineStart);
if (lineEnd == -1) {
lineEnd = text.length() - 1;
}
line = text.substring(lineStart, lineEnd + 1);
lineStart = lineEnd + 1;
if (lineHash.containsKey(line)) {
chars.append(String.valueOf((char) (int) lineHash.get(line)));
} else {
lineArray.add(line);
lineHash.put(line, lineArray.size() - 1);
chars.append(String.valueOf((char) (lineArray.size() - 1)));
}
}
return chars.toString();
} } | public class class_name {
private String linesToCharsMunge(String text, List<String> lineArray,
Map<String, Integer> lineHash) {
int lineStart = 0;
int lineEnd = -1;
String line;
StringBuilder chars = new StringBuilder();
// Walk the text, pulling out a substring for each line.
// text.split('\n') would would temporarily double our memory footprint.
// Modifying text would create many large strings to garbage collect.
while (lineEnd < text.length() - 1) {
lineEnd = text.indexOf('\n', lineStart); // depends on control dependency: [while], data = [none]
if (lineEnd == -1) {
lineEnd = text.length() - 1; // depends on control dependency: [if], data = [none]
}
line = text.substring(lineStart, lineEnd + 1); // depends on control dependency: [while], data = [none]
lineStart = lineEnd + 1; // depends on control dependency: [while], data = [none]
if (lineHash.containsKey(line)) {
chars.append(String.valueOf((char) (int) lineHash.get(line))); // depends on control dependency: [if], data = [none]
} else {
lineArray.add(line); // depends on control dependency: [if], data = [none]
lineHash.put(line, lineArray.size() - 1); // depends on control dependency: [if], data = [none]
chars.append(String.valueOf((char) (lineArray.size() - 1))); // depends on control dependency: [if], data = [none]
}
}
return chars.toString();
} } |
public class class_name {
protected void setErrorCodeVariableOnErrorEventDefinition(Element errorEventDefinition, ErrorEventDefinition definition) {
String errorCodeVar = errorEventDefinition.attributeNS(CAMUNDA_BPMN_EXTENSIONS_NS, "errorCodeVariable");
if (errorCodeVar != null) {
definition.setErrorCodeVariable(errorCodeVar);
}
} } | public class class_name {
protected void setErrorCodeVariableOnErrorEventDefinition(Element errorEventDefinition, ErrorEventDefinition definition) {
String errorCodeVar = errorEventDefinition.attributeNS(CAMUNDA_BPMN_EXTENSIONS_NS, "errorCodeVariable");
if (errorCodeVar != null) {
definition.setErrorCodeVariable(errorCodeVar); // depends on control dependency: [if], data = [(errorCodeVar]
}
} } |
public class class_name {
public void applyAttachedObject(FacesContext context, UIComponent parent)
{
// Retrieve the current FaceletContext from FacesContext object
FaceletContext faceletContext = (FaceletContext) context.getAttributes().get(
FaceletContext.FACELET_CONTEXT_KEY);
ValueExpression ve = null;
Behavior behavior = null;
if (_delegate.getBinding() != null)
{
ve = _delegate.getBinding().getValueExpression(faceletContext, Behavior.class);
behavior = (Behavior) ve.getValue(faceletContext);
}
if (behavior == null)
{
behavior = this.createBehavior(faceletContext);
if (ve != null)
{
ve.setValue(faceletContext, behavior);
}
}
if (behavior == null)
{
throw new TagException(_delegate.getTag(), "No Validator was created");
}
_delegate.setAttributes(faceletContext, behavior);
if (behavior instanceof ClientBehavior)
{
// cast to a ClientBehaviorHolder
ClientBehaviorHolder cvh = (ClientBehaviorHolder) parent;
// TODO: check if the behavior could be applied to the current parent
// For run tests it is not necessary, so we let this one pending.
// It is necessary to obtain a event name for add it, so we have to
// look first to the defined event name, otherwise take the default from
// the holder
String eventName = getEventName();
if (eventName == null)
{
eventName = cvh.getDefaultEventName();
}
if (eventName == null)
{
throw new TagAttributeException(_delegate.getEvent(),
"eventName could not be defined for client behavior "+ behavior.toString());
}
else if (!cvh.getEventNames().contains(eventName))
{
throw new TagAttributeException(_delegate.getEvent(),
"eventName "+eventName+" not found on component instance");
}
else
{
cvh.addClientBehavior(eventName, (ClientBehavior) behavior);
}
AjaxHandler.registerJsfAjaxDefaultResource(faceletContext, parent);
}
} } | public class class_name {
public void applyAttachedObject(FacesContext context, UIComponent parent)
{
// Retrieve the current FaceletContext from FacesContext object
FaceletContext faceletContext = (FaceletContext) context.getAttributes().get(
FaceletContext.FACELET_CONTEXT_KEY);
ValueExpression ve = null;
Behavior behavior = null;
if (_delegate.getBinding() != null)
{
ve = _delegate.getBinding().getValueExpression(faceletContext, Behavior.class); // depends on control dependency: [if], data = [none]
behavior = (Behavior) ve.getValue(faceletContext); // depends on control dependency: [if], data = [none]
}
if (behavior == null)
{
behavior = this.createBehavior(faceletContext); // depends on control dependency: [if], data = [none]
if (ve != null)
{
ve.setValue(faceletContext, behavior); // depends on control dependency: [if], data = [none]
}
}
if (behavior == null)
{
throw new TagException(_delegate.getTag(), "No Validator was created");
}
_delegate.setAttributes(faceletContext, behavior);
if (behavior instanceof ClientBehavior)
{
// cast to a ClientBehaviorHolder
ClientBehaviorHolder cvh = (ClientBehaviorHolder) parent;
// TODO: check if the behavior could be applied to the current parent
// For run tests it is not necessary, so we let this one pending.
// It is necessary to obtain a event name for add it, so we have to
// look first to the defined event name, otherwise take the default from
// the holder
String eventName = getEventName();
if (eventName == null)
{
eventName = cvh.getDefaultEventName(); // depends on control dependency: [if], data = [none]
}
if (eventName == null)
{
throw new TagAttributeException(_delegate.getEvent(),
"eventName could not be defined for client behavior "+ behavior.toString());
}
else if (!cvh.getEventNames().contains(eventName))
{
throw new TagAttributeException(_delegate.getEvent(),
"eventName "+eventName+" not found on component instance");
}
else
{
cvh.addClientBehavior(eventName, (ClientBehavior) behavior); // depends on control dependency: [if], data = [none]
}
AjaxHandler.registerJsfAjaxDefaultResource(faceletContext, parent); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void setActivityChooserPolicyIfNeeded() {
if (mOnShareTargetSelectedListener == null) {
return;
}
if (mOnChooseActivityListener == null) {
mOnChooseActivityListener = new ShareAcitivityChooserModelPolicy();
}
ActivityChooserModel dataModel = ActivityChooserModel.get(mContext, mShareHistoryFileName);
dataModel.setOnChooseActivityListener(mOnChooseActivityListener);
} } | public class class_name {
private void setActivityChooserPolicyIfNeeded() {
if (mOnShareTargetSelectedListener == null) {
return; // depends on control dependency: [if], data = [none]
}
if (mOnChooseActivityListener == null) {
mOnChooseActivityListener = new ShareAcitivityChooserModelPolicy(); // depends on control dependency: [if], data = [none]
}
ActivityChooserModel dataModel = ActivityChooserModel.get(mContext, mShareHistoryFileName);
dataModel.setOnChooseActivityListener(mOnChooseActivityListener);
} } |
public class class_name {
public final void addSubEntries(final Collection<NavigationEntryInterface> psubEntries) {
if (!CollectionUtils.isEmpty(psubEntries)) {
subEntries.addAll(psubEntries);
subEntries.forEach(subEntry -> subEntry.setParentEntry(this));
}
} } | public class class_name {
public final void addSubEntries(final Collection<NavigationEntryInterface> psubEntries) {
if (!CollectionUtils.isEmpty(psubEntries)) {
subEntries.addAll(psubEntries); // depends on control dependency: [if], data = [none]
subEntries.forEach(subEntry -> subEntry.setParentEntry(this)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void executePreparedQuery(boolean mustExecuteOnMaster,
ServerPrepareResult serverPrepareResult, Results results,
ParameterHolder[] parameters)
throws SQLException {
cmdPrologue();
try {
int parameterCount = serverPrepareResult.getParameters().length;
//send binary data in a separate stream
for (int i = 0; i < parameterCount; i++) {
if (parameters[i].isLongData()) {
writer.startPacket(0);
writer.write(COM_STMT_SEND_LONG_DATA);
writer.writeInt(serverPrepareResult.getStatementId());
writer.writeShort((short) i);
parameters[i].writeBinary(writer);
writer.flush();
}
}
//send execute query
ComStmtExecute.send(writer, serverPrepareResult.getStatementId(), parameters,
parameterCount, serverPrepareResult.getParameterTypeHeader(), CURSOR_TYPE_NO_CURSOR);
getResult(results);
} catch (SQLException qex) {
throw logQuery.exceptionWithQuery(parameters, qex, serverPrepareResult);
} catch (IOException e) {
throw handleIoException(e);
}
} } | public class class_name {
@Override
public void executePreparedQuery(boolean mustExecuteOnMaster,
ServerPrepareResult serverPrepareResult, Results results,
ParameterHolder[] parameters)
throws SQLException {
cmdPrologue();
try {
int parameterCount = serverPrepareResult.getParameters().length;
//send binary data in a separate stream
for (int i = 0; i < parameterCount; i++) {
if (parameters[i].isLongData()) {
writer.startPacket(0); // depends on control dependency: [if], data = [none]
writer.write(COM_STMT_SEND_LONG_DATA); // depends on control dependency: [if], data = [none]
writer.writeInt(serverPrepareResult.getStatementId()); // depends on control dependency: [if], data = [none]
writer.writeShort((short) i); // depends on control dependency: [if], data = [none]
parameters[i].writeBinary(writer); // depends on control dependency: [if], data = [none]
writer.flush(); // depends on control dependency: [if], data = [none]
}
}
//send execute query
ComStmtExecute.send(writer, serverPrepareResult.getStatementId(), parameters,
parameterCount, serverPrepareResult.getParameterTypeHeader(), CURSOR_TYPE_NO_CURSOR);
getResult(results);
} catch (SQLException qex) {
throw logQuery.exceptionWithQuery(parameters, qex, serverPrepareResult);
} catch (IOException e) {
throw handleIoException(e);
}
} } |
public class class_name {
CheckpointStatsHistory createSnapshot() {
if (readOnly) {
throw new UnsupportedOperationException("Can't create a snapshot of a read-only history.");
}
List<AbstractCheckpointStats> checkpointsHistory;
Map<Long, AbstractCheckpointStats> checkpointsById;
checkpointsById = new HashMap<>(checkpointsArray.length);
if (maxSize == 0) {
checkpointsHistory = Collections.emptyList();
} else {
AbstractCheckpointStats[] newCheckpointsArray = new AbstractCheckpointStats[checkpointsArray.length];
System.arraycopy(checkpointsArray, nextPos, newCheckpointsArray, 0, checkpointsArray.length - nextPos);
System.arraycopy(checkpointsArray, 0, newCheckpointsArray, checkpointsArray.length - nextPos, nextPos);
checkpointsHistory = Arrays.asList(newCheckpointsArray);
// reverse the order such that we start with the youngest checkpoint
Collections.reverse(checkpointsHistory);
for (AbstractCheckpointStats checkpoint : checkpointsHistory) {
checkpointsById.put(checkpoint.getCheckpointId(), checkpoint);
}
}
if (latestCompletedCheckpoint != null) {
checkpointsById.put(latestCompletedCheckpoint.getCheckpointId(), latestCompletedCheckpoint);
}
if (latestFailedCheckpoint != null) {
checkpointsById.put(latestFailedCheckpoint.getCheckpointId(), latestFailedCheckpoint);
}
if (latestSavepoint != null) {
checkpointsById.put(latestSavepoint.getCheckpointId(), latestSavepoint);
}
return new CheckpointStatsHistory(
true,
maxSize,
null,
checkpointsHistory,
checkpointsById,
latestCompletedCheckpoint,
latestFailedCheckpoint,
latestSavepoint);
} } | public class class_name {
CheckpointStatsHistory createSnapshot() {
if (readOnly) {
throw new UnsupportedOperationException("Can't create a snapshot of a read-only history.");
}
List<AbstractCheckpointStats> checkpointsHistory;
Map<Long, AbstractCheckpointStats> checkpointsById;
checkpointsById = new HashMap<>(checkpointsArray.length);
if (maxSize == 0) {
checkpointsHistory = Collections.emptyList(); // depends on control dependency: [if], data = [none]
} else {
AbstractCheckpointStats[] newCheckpointsArray = new AbstractCheckpointStats[checkpointsArray.length];
System.arraycopy(checkpointsArray, nextPos, newCheckpointsArray, 0, checkpointsArray.length - nextPos); // depends on control dependency: [if], data = [none]
System.arraycopy(checkpointsArray, 0, newCheckpointsArray, checkpointsArray.length - nextPos, nextPos); // depends on control dependency: [if], data = [none]
checkpointsHistory = Arrays.asList(newCheckpointsArray); // depends on control dependency: [if], data = [none]
// reverse the order such that we start with the youngest checkpoint
Collections.reverse(checkpointsHistory); // depends on control dependency: [if], data = [none]
for (AbstractCheckpointStats checkpoint : checkpointsHistory) {
checkpointsById.put(checkpoint.getCheckpointId(), checkpoint); // depends on control dependency: [for], data = [checkpoint]
}
}
if (latestCompletedCheckpoint != null) {
checkpointsById.put(latestCompletedCheckpoint.getCheckpointId(), latestCompletedCheckpoint); // depends on control dependency: [if], data = [(latestCompletedCheckpoint]
}
if (latestFailedCheckpoint != null) {
checkpointsById.put(latestFailedCheckpoint.getCheckpointId(), latestFailedCheckpoint); // depends on control dependency: [if], data = [(latestFailedCheckpoint]
}
if (latestSavepoint != null) {
checkpointsById.put(latestSavepoint.getCheckpointId(), latestSavepoint); // depends on control dependency: [if], data = [(latestSavepoint]
}
return new CheckpointStatsHistory(
true,
maxSize,
null,
checkpointsHistory,
checkpointsById,
latestCompletedCheckpoint,
latestFailedCheckpoint,
latestSavepoint);
} } |
public class class_name {
public Stream<TimestampInterval> streamPartitioned(DayPartitionRule rule) {
TimestampInterval interval = this.toCanonical();
PlainTimestamp start = interval.getStartAsTimestamp();
PlainTimestamp end = interval.getEndAsTimestamp();
if ((start == null) || (end == null)) {
throw new IllegalStateException("Streaming is not supported for infinite intervals.");
}
PlainDate d1 = start.getCalendarDate();
PlainDate d2 = end.getCalendarDate();
long days = CalendarUnit.DAYS.between(d1, d2);
if (days == 0) {
ClockInterval w = ClockInterval.between(start.getWallTime(), end.getWallTime());
return getPartitions(d1, w, rule).stream();
}
ClockInterval w1 = ClockInterval.between(start.getWallTime(), PlainTime.midnightAtEndOfDay());
ClockInterval w2 = ClockInterval.between(PlainTime.midnightAtStartOfDay(), end.getWallTime());
Stream<TimestampInterval> a = getPartitions(d1, w1, rule).stream();
Stream<TimestampInterval> c = getPartitions(d2, w2, rule).stream();
if (days > 1) {
Stream<TimestampInterval> b =
DateInterval.between(d1.plus(CalendarDays.ONE), d2.minus(CalendarDays.ONE)).streamPartitioned(rule);
a = Stream.concat(a, b);
}
return Stream.concat(a, c);
} } | public class class_name {
public Stream<TimestampInterval> streamPartitioned(DayPartitionRule rule) {
TimestampInterval interval = this.toCanonical();
PlainTimestamp start = interval.getStartAsTimestamp();
PlainTimestamp end = interval.getEndAsTimestamp();
if ((start == null) || (end == null)) {
throw new IllegalStateException("Streaming is not supported for infinite intervals.");
}
PlainDate d1 = start.getCalendarDate();
PlainDate d2 = end.getCalendarDate();
long days = CalendarUnit.DAYS.between(d1, d2);
if (days == 0) {
ClockInterval w = ClockInterval.between(start.getWallTime(), end.getWallTime());
return getPartitions(d1, w, rule).stream(); // depends on control dependency: [if], data = [none]
}
ClockInterval w1 = ClockInterval.between(start.getWallTime(), PlainTime.midnightAtEndOfDay());
ClockInterval w2 = ClockInterval.between(PlainTime.midnightAtStartOfDay(), end.getWallTime());
Stream<TimestampInterval> a = getPartitions(d1, w1, rule).stream();
Stream<TimestampInterval> c = getPartitions(d2, w2, rule).stream();
if (days > 1) {
Stream<TimestampInterval> b =
DateInterval.between(d1.plus(CalendarDays.ONE), d2.minus(CalendarDays.ONE)).streamPartitioned(rule);
a = Stream.concat(a, b); // depends on control dependency: [if], data = [none]
}
return Stream.concat(a, c);
} } |
public class class_name {
public int doCopyRecordsCommand(Script recScript, Map<String,Object> properties)
{
int iErrorCode = DBConstants.NORMAL_RETURN;
Record record = recScript.getTargetRecord(properties, DBParams.RECORD);
if (record == null)
return DBConstants.ERROR_RETURN;
if (properties.get(PARENT_RECORD) != null)
{
Record recParent = recScript.getTargetRecord(properties, PARENT_RECORD);
if (recParent != null)
record.addListener(new SubFileFilter(recParent));
}
Record recDestination = recScript.getTargetRecord(properties, Script.DESTINATION_RECORD);
try {
record.close();
while (record.hasNext())
{
record.next();
recDestination.addNew();
recDestination.setAutoSequence(false);
iErrorCode = this.doSubScriptCommands(recScript, properties);
if (iErrorCode != DBConstants.NORMAL_RETURN)
return iErrorCode;
if (recDestination.getCounterField().isNull())
recDestination.setAutoSequence(true);
try {
recDestination.add();
} catch (DBException ex) {
// Ignore duplicate records
}
}
} catch (DBException ex) {
ex.printStackTrace();
}
return DONT_READ_SUB_SCRIPT;
} } | public class class_name {
public int doCopyRecordsCommand(Script recScript, Map<String,Object> properties)
{
int iErrorCode = DBConstants.NORMAL_RETURN;
Record record = recScript.getTargetRecord(properties, DBParams.RECORD);
if (record == null)
return DBConstants.ERROR_RETURN;
if (properties.get(PARENT_RECORD) != null)
{
Record recParent = recScript.getTargetRecord(properties, PARENT_RECORD);
if (recParent != null)
record.addListener(new SubFileFilter(recParent));
}
Record recDestination = recScript.getTargetRecord(properties, Script.DESTINATION_RECORD);
try {
record.close(); // depends on control dependency: [try], data = [none]
while (record.hasNext())
{
record.next(); // depends on control dependency: [while], data = [none]
recDestination.addNew(); // depends on control dependency: [while], data = [none]
recDestination.setAutoSequence(false); // depends on control dependency: [while], data = [none]
iErrorCode = this.doSubScriptCommands(recScript, properties); // depends on control dependency: [while], data = [none]
if (iErrorCode != DBConstants.NORMAL_RETURN)
return iErrorCode;
if (recDestination.getCounterField().isNull())
recDestination.setAutoSequence(true);
try {
recDestination.add(); // depends on control dependency: [try], data = [none]
} catch (DBException ex) {
// Ignore duplicate records
} // depends on control dependency: [catch], data = [none]
}
} catch (DBException ex) {
ex.printStackTrace();
} // depends on control dependency: [catch], data = [none]
return DONT_READ_SUB_SCRIPT;
} } |
public class class_name {
public void onCancel() {
if (m_publishSelectPanel.m_model != null) {
final List<CmsUUID> toRemove = m_publishSelectPanel.m_model.getIdsOfAlreadyPublishedResources();
if (toRemove.isEmpty()) {
hide();
} else {
CmsRpcAction<CmsWorkflowResponse> action = new CmsRpcAction<CmsWorkflowResponse>() {
@Override
public void execute() {
start(0, true);
CmsWorkflowActionParams params = getWorkflowActionParams();
getService().executeAction(
new CmsWorkflowAction(CmsWorkflowAction.ACTION_CANCEL, "", true),
params,
this);
}
@Override
protected void onResponse(CmsWorkflowResponse result) {
stop(false);
hide();
}
};
action.execute();
}
} else {
hide();
}
} } | public class class_name {
public void onCancel() {
if (m_publishSelectPanel.m_model != null) {
final List<CmsUUID> toRemove = m_publishSelectPanel.m_model.getIdsOfAlreadyPublishedResources();
if (toRemove.isEmpty()) {
hide(); // depends on control dependency: [if], data = [none]
} else {
CmsRpcAction<CmsWorkflowResponse> action = new CmsRpcAction<CmsWorkflowResponse>() {
@Override
public void execute() {
start(0, true);
CmsWorkflowActionParams params = getWorkflowActionParams();
getService().executeAction(
new CmsWorkflowAction(CmsWorkflowAction.ACTION_CANCEL, "", true),
params,
this);
}
@Override
protected void onResponse(CmsWorkflowResponse result) {
stop(false);
hide();
}
};
action.execute(); // depends on control dependency: [if], data = [none]
}
} else {
hide(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void zip(final File zipFile) throws IOException {
File[] files = listFiles();
if (files.length == 0) {
return;
}
LOG.info("Creating zip file " + zipFile + " from directory " + this);
ZipOutputStream zipOut = null;
try {
zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
for (File file : files) {
zip("", file, zipOut);
}
} finally {
IOUtils.closeQuietly(zipOut);
}
} } | public class class_name {
public void zip(final File zipFile) throws IOException {
File[] files = listFiles();
if (files.length == 0) {
return;
}
LOG.info("Creating zip file " + zipFile + " from directory " + this);
ZipOutputStream zipOut = null;
try {
zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
for (File file : files) {
zip("", file, zipOut);
// depends on control dependency: [for], data = [file]
}
} finally {
IOUtils.closeQuietly(zipOut);
}
} } |
public class class_name {
public DeclaredType findSupertype(TypeMirror type, String qualifiedName) {
TypeElement element = asTypeElement(type);
if (element != null && element.getQualifiedName().toString().equals(qualifiedName)) {
return (DeclaredType) type;
}
for (TypeMirror t : directSupertypes(type)) {
DeclaredType result = findSupertype(t, qualifiedName);
if (result != null) {
return result;
}
}
return null;
} } | public class class_name {
public DeclaredType findSupertype(TypeMirror type, String qualifiedName) {
TypeElement element = asTypeElement(type);
if (element != null && element.getQualifiedName().toString().equals(qualifiedName)) {
return (DeclaredType) type; // depends on control dependency: [if], data = [none]
}
for (TypeMirror t : directSupertypes(type)) {
DeclaredType result = findSupertype(t, qualifiedName);
if (result != null) {
return result; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public static Basic2DMatrix fromBinary(byte[] array) {
ByteBuffer buffer = ByteBuffer.wrap(array);
if (buffer.get() != MATRIX_TAG) {
throw new IllegalArgumentException("Can not decode Basic2DMatrix from the given byte array.");
}
int rows = buffer.getInt();
int columns = buffer.getInt();
double[][] values = new double[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
values[i][j] = buffer.getDouble();
}
}
return new Basic2DMatrix(values);
} } | public class class_name {
public static Basic2DMatrix fromBinary(byte[] array) {
ByteBuffer buffer = ByteBuffer.wrap(array);
if (buffer.get() != MATRIX_TAG) {
throw new IllegalArgumentException("Can not decode Basic2DMatrix from the given byte array.");
}
int rows = buffer.getInt();
int columns = buffer.getInt();
double[][] values = new double[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
values[i][j] = buffer.getDouble(); // depends on control dependency: [for], data = [j]
}
}
return new Basic2DMatrix(values);
} } |
public class class_name {
private void readLinks2AccessTypes()
throws CacheReloadException
{
Connection con = null;
try {
final List<Long> values = new ArrayList<>();
con = Context.getConnection();
PreparedStatement stmt = null;
try {
stmt = con.prepareStatement(AccessSet.SQL_SET2TYPE);
stmt.setObject(1, getId());
final ResultSet rs = stmt.executeQuery();
while (rs.next()) {
values.add(rs.getLong(1));
}
rs.close();
} finally {
if (stmt != null) {
stmt.close();
}
}
con.commit();
for (final Long accessTypeId : values) {
final AccessType accessType = AccessType.getAccessType(accessTypeId);
if (accessType == null) {
AccessSet.LOG.error("could not found access type with id " + "'" + accessTypeId + "'");
} else {
AccessSet.LOG.debug(
"read link from AccessSet '{}' (id = {}, uuid = {}) to AccessType '{}' (id = {} uuid = {})",
getName(), getId(), getUUID(), accessType.getName(), accessType.getId(),
accessType.getUUID());
getAccessTypes().add(accessType);
}
}
} catch (final SQLException e) {
throw new CacheReloadException("could not read roles", e);
} catch (final EFapsException e) {
throw new CacheReloadException("could not read roles", e);
} finally {
try {
if (con != null && !con.isClosed()) {
con.close();
}
} catch (final SQLException e) {
throw new CacheReloadException("Cannot read a type for an attribute.", e);
}
}
} } | public class class_name {
private void readLinks2AccessTypes()
throws CacheReloadException
{
Connection con = null;
try {
final List<Long> values = new ArrayList<>();
con = Context.getConnection();
PreparedStatement stmt = null;
try {
stmt = con.prepareStatement(AccessSet.SQL_SET2TYPE); // depends on control dependency: [try], data = [none]
stmt.setObject(1, getId()); // depends on control dependency: [try], data = [none]
final ResultSet rs = stmt.executeQuery();
while (rs.next()) {
values.add(rs.getLong(1)); // depends on control dependency: [while], data = [none]
}
rs.close(); // depends on control dependency: [try], data = [none]
} finally {
if (stmt != null) {
stmt.close(); // depends on control dependency: [if], data = [none]
}
}
con.commit();
for (final Long accessTypeId : values) {
final AccessType accessType = AccessType.getAccessType(accessTypeId);
if (accessType == null) {
AccessSet.LOG.error("could not found access type with id " + "'" + accessTypeId + "'"); // depends on control dependency: [if], data = [none]
} else {
AccessSet.LOG.debug(
"read link from AccessSet '{}' (id = {}, uuid = {}) to AccessType '{}' (id = {} uuid = {})",
getName(), getId(), getUUID(), accessType.getName(), accessType.getId(),
accessType.getUUID());
getAccessTypes().add(accessType); // depends on control dependency: [if], data = [none]
}
}
} catch (final SQLException e) {
throw new CacheReloadException("could not read roles", e);
} catch (final EFapsException e) {
throw new CacheReloadException("could not read roles", e);
} finally {
try {
if (con != null && !con.isClosed()) {
con.close(); // depends on control dependency: [if], data = [none]
}
} catch (final SQLException e) {
throw new CacheReloadException("Cannot read a type for an attribute.", e);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public <T extends ManagedType> T getJaversManagedType(Class javaClass, Class<T> expectedType) {
JaversType mType = getJaversType(javaClass);
if (expectedType.isAssignableFrom(mType.getClass())) {
return (T) mType;
} else {
throw new JaversException(JaversExceptionCode.MANAGED_CLASS_MAPPING_ERROR,
javaClass,
mType.getClass().getSimpleName(),
expectedType.getSimpleName());
}
} } | public class class_name {
public <T extends ManagedType> T getJaversManagedType(Class javaClass, Class<T> expectedType) {
JaversType mType = getJaversType(javaClass);
if (expectedType.isAssignableFrom(mType.getClass())) {
return (T) mType; // depends on control dependency: [if], data = [none]
} else {
throw new JaversException(JaversExceptionCode.MANAGED_CLASS_MAPPING_ERROR,
javaClass,
mType.getClass().getSimpleName(),
expectedType.getSimpleName());
}
} } |
public class class_name {
public List<AddOn> getInstalledAddOns() {
List<AddOn> installedAddOns = new ArrayList<>(addOns.size());
for (AddOn addOn : addOns) {
if (AddOn.InstallationStatus.INSTALLED == addOn.getInstallationStatus()) {
installedAddOns.add(addOn);
}
}
return installedAddOns;
} } | public class class_name {
public List<AddOn> getInstalledAddOns() {
List<AddOn> installedAddOns = new ArrayList<>(addOns.size());
for (AddOn addOn : addOns) {
if (AddOn.InstallationStatus.INSTALLED == addOn.getInstallationStatus()) {
installedAddOns.add(addOn);
// depends on control dependency: [if], data = [none]
}
}
return installedAddOns;
} } |
public class class_name {
protected void handleCollectionTypeNotAvailable(XCollectionLiteral literal, ITypeComputationState state, Class<?> clazz) {
for(XExpression element: literal.getElements()) {
state.withNonVoidExpectation().computeTypes(element);
}
state.acceptActualType(state.getReferenceOwner().newUnknownTypeReference(clazz.getName()));
} } | public class class_name {
protected void handleCollectionTypeNotAvailable(XCollectionLiteral literal, ITypeComputationState state, Class<?> clazz) {
for(XExpression element: literal.getElements()) {
state.withNonVoidExpectation().computeTypes(element); // depends on control dependency: [for], data = [element]
}
state.acceptActualType(state.getReferenceOwner().newUnknownTypeReference(clazz.getName()));
} } |
public class class_name {
public AwsSecurityFindingFilters withNetworkDirection(StringFilter... networkDirection) {
if (this.networkDirection == null) {
setNetworkDirection(new java.util.ArrayList<StringFilter>(networkDirection.length));
}
for (StringFilter ele : networkDirection) {
this.networkDirection.add(ele);
}
return this;
} } | public class class_name {
public AwsSecurityFindingFilters withNetworkDirection(StringFilter... networkDirection) {
if (this.networkDirection == null) {
setNetworkDirection(new java.util.ArrayList<StringFilter>(networkDirection.length)); // depends on control dependency: [if], data = [none]
}
for (StringFilter ele : networkDirection) {
this.networkDirection.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
@Override
public boolean isCellEditable(int row, int column) {
// names are not editable
if (column == 0) {
return false;
}
PropertySheetTableModel.Item item = getSheetModel().getPropertySheetElement(row);
return item.isProperty() && item.getProperty().isEditable();
} } | public class class_name {
@Override
public boolean isCellEditable(int row, int column) {
// names are not editable
if (column == 0) {
return false;
// depends on control dependency: [if], data = [none]
}
PropertySheetTableModel.Item item = getSheetModel().getPropertySheetElement(row);
return item.isProperty() && item.getProperty().isEditable();
} } |
public class class_name {
ZoneInfo queryByToken(String token) {
try {
// http://developer.qiniu.com/article/developer/security/upload-token.html
// http://developer.qiniu.com/article/developer/security/put-policy.html
String[] strings = token.split(":");
String ak = strings[0];
String policy = new String(UrlSafeBase64.decode(strings[2]), Constants.UTF_8);
JSONObject obj = new JSONObject(policy);
String scope = obj.getString("scope");
String bkt = scope.split(":")[0];
return zoneInfo(ak, bkt);
} catch (Exception e) {
e.printStackTrace();
}
return null;
} } | public class class_name {
ZoneInfo queryByToken(String token) {
try {
// http://developer.qiniu.com/article/developer/security/upload-token.html
// http://developer.qiniu.com/article/developer/security/put-policy.html
String[] strings = token.split(":");
String ak = strings[0];
String policy = new String(UrlSafeBase64.decode(strings[2]), Constants.UTF_8);
JSONObject obj = new JSONObject(policy);
String scope = obj.getString("scope");
String bkt = scope.split(":")[0];
return zoneInfo(ak, bkt); // 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 {
@Override
public boolean compare(Object object) {
if (!(object instanceof Element)) {
return false;
}
if (!super.compare(object)) {
return false;
}
Element elem = (Element) object;
return Objects.equal(atomicNumber, elem.atomicNumber);
} } | public class class_name {
@Override
public boolean compare(Object object) {
if (!(object instanceof Element)) {
return false; // depends on control dependency: [if], data = [none]
}
if (!super.compare(object)) {
return false; // depends on control dependency: [if], data = [none]
}
Element elem = (Element) object;
return Objects.equal(atomicNumber, elem.atomicNumber);
} } |
public class class_name {
public void marshall(SetDefaultPolicyVersionRequest setDefaultPolicyVersionRequest, ProtocolMarshaller protocolMarshaller) {
if (setDefaultPolicyVersionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(setDefaultPolicyVersionRequest.getPolicyName(), POLICYNAME_BINDING);
protocolMarshaller.marshall(setDefaultPolicyVersionRequest.getPolicyVersionId(), POLICYVERSIONID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(SetDefaultPolicyVersionRequest setDefaultPolicyVersionRequest, ProtocolMarshaller protocolMarshaller) {
if (setDefaultPolicyVersionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(setDefaultPolicyVersionRequest.getPolicyName(), POLICYNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(setDefaultPolicyVersionRequest.getPolicyVersionId(), POLICYVERSIONID_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 void close(final Result result) throws IOException {
if (result != null && result instanceof StreamResult) {
final StreamResult r = (StreamResult) result;
final OutputStream o = r.getOutputStream();
if (o != null) {
o.close();
} else {
final Writer w = r.getWriter();
if (w != null) {
w.close();
}
}
}
} } | public class class_name {
public static void close(final Result result) throws IOException {
if (result != null && result instanceof StreamResult) {
final StreamResult r = (StreamResult) result;
final OutputStream o = r.getOutputStream();
if (o != null) {
o.close(); // depends on control dependency: [if], data = [none]
} else {
final Writer w = r.getWriter();
if (w != null) {
w.close(); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
public ZipEntry getEntry(String name) {
if (name == null) {
throw new NullPointerException("name");
}
long jzentry = 0;
synchronized (this) {
ensureOpen();
jzentry = getEntry(jzfile, zc.getBytes(name), true);
if (jzentry != 0) {
ZipEntry ze = getZipEntry(name, jzentry);
freeEntry(jzfile, jzentry);
return ze;
}
}
return null;
} } | public class class_name {
public ZipEntry getEntry(String name) {
if (name == null) {
throw new NullPointerException("name");
}
long jzentry = 0;
synchronized (this) {
ensureOpen();
jzentry = getEntry(jzfile, zc.getBytes(name), true);
if (jzentry != 0) {
ZipEntry ze = getZipEntry(name, jzentry);
freeEntry(jzfile, jzentry); // depends on control dependency: [if], data = [none]
return ze; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public static WorkQueue getWorkQueue() {
if (singleton == null) {
synchronized (WorkQueue.class) {
if (singleton == null)
// REMINDER: default number of threads?
singleton = new WorkQueue();
}
}
return singleton;
} } | public class class_name {
public static WorkQueue getWorkQueue() {
if (singleton == null) {
synchronized (WorkQueue.class) { // depends on control dependency: [if], data = [none]
if (singleton == null)
// REMINDER: default number of threads?
singleton = new WorkQueue();
}
}
return singleton;
} } |
public class class_name {
public void update(MatrixFunction function) {
MatrixIterator it = iterator();
while (it.hasNext()) {
double x = it.next();
int i = it.rowIndex();
int j = it.columnIndex();
it.set(function.evaluate(i, j, x));
}
} } | public class class_name {
public void update(MatrixFunction function) {
MatrixIterator it = iterator();
while (it.hasNext()) {
double x = it.next();
int i = it.rowIndex();
int j = it.columnIndex();
it.set(function.evaluate(i, j, x)); // depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
public static boolean avroSchemaTypesEqual(Schema schema1, Schema schema2) {
if (schema1.getType() != schema2.getType()) {
// if the types aren't equal, no need to go further. Return false
return false;
}
if (schema1.getType() == Schema.Type.ENUM
|| schema1.getType() == Schema.Type.FIXED) {
// Enum and Fixed types schemas should be equal using the Schema.equals
// method.
return schema1.equals(schema2);
}
if (schema1.getType() == Schema.Type.ARRAY) {
// Avro element schemas should be equal, which is tested by recursively
// calling this method.
return avroSchemaTypesEqual(schema1.getElementType(),
schema2.getElementType());
} else if (schema1.getType() == Schema.Type.MAP) {
// Map type values schemas should be equal, which is tested by recursively
// calling this method.
return avroSchemaTypesEqual(schema1.getValueType(),
schema2.getValueType());
} else if (schema1.getType() == Schema.Type.UNION) {
// Compare Union fields in the same position by comparing their schemas
// recursively calling this method.
if (schema1.getTypes().size() != schema2.getTypes().size()) {
return false;
}
for (int i = 0; i < schema1.getTypes().size(); i++) {
if (!avroSchemaTypesEqual(schema1.getTypes().get(i), schema2.getTypes()
.get(i))) {
return false;
}
}
return true;
} else if (schema1.getType() == Schema.Type.RECORD) {
// Compare record fields that match in name by comparing their schemas
// recursively calling this method.
if (schema1.getFields().size() != schema2.getFields().size()) {
return false;
}
for (Field field1 : schema1.getFields()) {
Field field2 = schema2.getField(field1.name());
if (field2 == null) {
return false;
}
if (!avroSchemaTypesEqual(field1.schema(), field2.schema())) {
return false;
}
}
return true;
} else {
// All other types are primitive, so them matching in type is enough.
return true;
}
} } | public class class_name {
public static boolean avroSchemaTypesEqual(Schema schema1, Schema schema2) {
if (schema1.getType() != schema2.getType()) {
// if the types aren't equal, no need to go further. Return false
return false; // depends on control dependency: [if], data = [none]
}
if (schema1.getType() == Schema.Type.ENUM
|| schema1.getType() == Schema.Type.FIXED) {
// Enum and Fixed types schemas should be equal using the Schema.equals
// method.
return schema1.equals(schema2); // depends on control dependency: [if], data = [none]
}
if (schema1.getType() == Schema.Type.ARRAY) {
// Avro element schemas should be equal, which is tested by recursively
// calling this method.
return avroSchemaTypesEqual(schema1.getElementType(),
schema2.getElementType()); // depends on control dependency: [if], data = [none]
} else if (schema1.getType() == Schema.Type.MAP) {
// Map type values schemas should be equal, which is tested by recursively
// calling this method.
return avroSchemaTypesEqual(schema1.getValueType(),
schema2.getValueType()); // depends on control dependency: [if], data = [none]
} else if (schema1.getType() == Schema.Type.UNION) {
// Compare Union fields in the same position by comparing their schemas
// recursively calling this method.
if (schema1.getTypes().size() != schema2.getTypes().size()) {
return false; // depends on control dependency: [if], data = [none]
}
for (int i = 0; i < schema1.getTypes().size(); i++) {
if (!avroSchemaTypesEqual(schema1.getTypes().get(i), schema2.getTypes()
.get(i))) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true; // depends on control dependency: [if], data = [none]
} else if (schema1.getType() == Schema.Type.RECORD) {
// Compare record fields that match in name by comparing their schemas
// recursively calling this method.
if (schema1.getFields().size() != schema2.getFields().size()) {
return false; // depends on control dependency: [if], data = [none]
}
for (Field field1 : schema1.getFields()) {
Field field2 = schema2.getField(field1.name());
if (field2 == null) {
return false; // depends on control dependency: [if], data = [none]
}
if (!avroSchemaTypesEqual(field1.schema(), field2.schema())) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true; // depends on control dependency: [if], data = [none]
} else {
// All other types are primitive, so them matching in type is enough.
return true; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private static boolean multiPointDisjointEnvelope_(MultiPoint multipoint_a,
Envelope envelope_b, double tolerance,
ProgressTracker progress_tracker) {
Envelope2D env_a = new Envelope2D(), env_b = new Envelope2D();
multipoint_a.queryEnvelope2D(env_a);
envelope_b.queryEnvelope2D(env_b);
if (envelopeInfContainsEnvelope_(env_b, env_a, tolerance))
return false;
Envelope2D env_b_inflated = new Envelope2D();
env_b_inflated.setCoords(env_b);
env_b_inflated.inflate(tolerance, tolerance);
Point2D pt_a = new Point2D();
for (int i = 0; i < multipoint_a.getPointCount(); i++) {
multipoint_a.getXY(i, pt_a);
if (!env_b_inflated.contains(pt_a))
continue;
return false;
}
return true;
} } | public class class_name {
private static boolean multiPointDisjointEnvelope_(MultiPoint multipoint_a,
Envelope envelope_b, double tolerance,
ProgressTracker progress_tracker) {
Envelope2D env_a = new Envelope2D(), env_b = new Envelope2D();
multipoint_a.queryEnvelope2D(env_a);
envelope_b.queryEnvelope2D(env_b);
if (envelopeInfContainsEnvelope_(env_b, env_a, tolerance))
return false;
Envelope2D env_b_inflated = new Envelope2D();
env_b_inflated.setCoords(env_b);
env_b_inflated.inflate(tolerance, tolerance);
Point2D pt_a = new Point2D();
for (int i = 0; i < multipoint_a.getPointCount(); i++) {
multipoint_a.getXY(i, pt_a); // depends on control dependency: [for], data = [i]
if (!env_b_inflated.contains(pt_a))
continue;
return false; // depends on control dependency: [for], data = [none]
}
return true;
} } |
public class class_name {
public static int byteArrayToInt(byte[] b, int offset) {
int value = 0;
for (int i = 0; i < 4; i++) {
int shift = (4 - 1 - i) * 8;
value += (b[i + offset] & 0x000000FF) << shift;
}
return value;
} } | public class class_name {
public static int byteArrayToInt(byte[] b, int offset) {
int value = 0;
for (int i = 0; i < 4; i++) {
int shift = (4 - 1 - i) * 8;
value += (b[i + offset] & 0x000000FF) << shift; // depends on control dependency: [for], data = [i]
}
return value;
} } |
public class class_name {
public static ClassOrInterfaceDeclaration mergeType(ClassOrInterfaceDeclaration one, ClassOrInterfaceDeclaration two) {
if (isAllNull(one, two)) return null;
ClassOrInterfaceDeclaration coid = null;
if (isAllNotNull(one, two)) {
coid = new ClassOrInterfaceDeclaration();
coid.setName(one.getName());
coid.setJavaDoc(mergeSelective(one.getJavaDoc(), two.getJavaDoc()));
coid.setComment(mergeSelective(one.getComment(), two.getComment()));
coid.setAnnotations(mergeListNoDuplicate(one.getAnnotations(), two.getAnnotations()));
coid.setModifiers(mergeModifiers(one.getModifiers(), two.getModifiers()));
coid.setExtends(mergeListNoDuplicate(one.getExtends(), two.getExtends()));
coid.setImplements(mergeListNoDuplicate(one.getImplements(), two.getImplements()));
coid.setTypeParameters(mergeSelective(one.getTypeParameters(), two.getTypeParameters()));
coid.setInterface(one.isInterface());
coid.setMembers(mergeBodies(one.getMembers(), two.getMembers()));
LOG.info("merge ClassOrInterfaceDeclaration --> {}", coid.getName());
} else {
coid = findFirstNotNull(one, two);
LOG.info("add ClassOrInterfaceDeclaration --> {}", coid.getName());
}
return coid;
} } | public class class_name {
public static ClassOrInterfaceDeclaration mergeType(ClassOrInterfaceDeclaration one, ClassOrInterfaceDeclaration two) {
if (isAllNull(one, two)) return null;
ClassOrInterfaceDeclaration coid = null;
if (isAllNotNull(one, two)) {
coid = new ClassOrInterfaceDeclaration(); // depends on control dependency: [if], data = [none]
coid.setName(one.getName()); // depends on control dependency: [if], data = [none]
coid.setJavaDoc(mergeSelective(one.getJavaDoc(), two.getJavaDoc())); // depends on control dependency: [if], data = [none]
coid.setComment(mergeSelective(one.getComment(), two.getComment())); // depends on control dependency: [if], data = [none]
coid.setAnnotations(mergeListNoDuplicate(one.getAnnotations(), two.getAnnotations())); // depends on control dependency: [if], data = [none]
coid.setModifiers(mergeModifiers(one.getModifiers(), two.getModifiers())); // depends on control dependency: [if], data = [none]
coid.setExtends(mergeListNoDuplicate(one.getExtends(), two.getExtends())); // depends on control dependency: [if], data = [none]
coid.setImplements(mergeListNoDuplicate(one.getImplements(), two.getImplements())); // depends on control dependency: [if], data = [none]
coid.setTypeParameters(mergeSelective(one.getTypeParameters(), two.getTypeParameters())); // depends on control dependency: [if], data = [none]
coid.setInterface(one.isInterface()); // depends on control dependency: [if], data = [none]
coid.setMembers(mergeBodies(one.getMembers(), two.getMembers())); // depends on control dependency: [if], data = [none]
LOG.info("merge ClassOrInterfaceDeclaration --> {}", coid.getName()); // depends on control dependency: [if], data = [none]
} else {
coid = findFirstNotNull(one, two); // depends on control dependency: [if], data = [none]
LOG.info("add ClassOrInterfaceDeclaration --> {}", coid.getName()); // depends on control dependency: [if], data = [none]
}
return coid;
} } |
public class class_name {
protected long getLastTriggersReleaseTime(T jedis){
final String lastReleaseTime = jedis.get(redisSchema.lastTriggerReleaseTime());
if(lastReleaseTime == null){
return 0;
}
return Long.parseLong(lastReleaseTime);
} } | public class class_name {
protected long getLastTriggersReleaseTime(T jedis){
final String lastReleaseTime = jedis.get(redisSchema.lastTriggerReleaseTime());
if(lastReleaseTime == null){
return 0; // depends on control dependency: [if], data = [none]
}
return Long.parseLong(lastReleaseTime);
} } |
public class class_name {
public void checked(double seconds) {
double end = System.currentTimeMillis() + (seconds * 1000);
try {
elementPresent(seconds);
while (!element.is().checked() && System.currentTimeMillis() < end) ;
double timeTook = Math.min((seconds * 1000) - (end - System.currentTimeMillis()), seconds * 1000) / 1000;
checkChecked(seconds, timeTook);
} catch (TimeoutException e) {
checkNotDisplayed(seconds, seconds);
}
} } | public class class_name {
public void checked(double seconds) {
double end = System.currentTimeMillis() + (seconds * 1000);
try {
elementPresent(seconds); // depends on control dependency: [try], data = [none]
while (!element.is().checked() && System.currentTimeMillis() < end) ;
double timeTook = Math.min((seconds * 1000) - (end - System.currentTimeMillis()), seconds * 1000) / 1000;
checkChecked(seconds, timeTook); // depends on control dependency: [try], data = [none]
} catch (TimeoutException e) {
checkNotDisplayed(seconds, seconds);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
static int getIndex(byte[] name) {
String nameString = new String(name, 0, name.length, ISO_8859_1);
Integer index = STATIC_INDEX_BY_NAME.get(nameString);
if (index == null) {
return -1;
}
return index;
} } | public class class_name {
static int getIndex(byte[] name) {
String nameString = new String(name, 0, name.length, ISO_8859_1);
Integer index = STATIC_INDEX_BY_NAME.get(nameString);
if (index == null) {
return -1; // depends on control dependency: [if], data = [none]
}
return index;
} } |
public class class_name {
public String rootUrlPrefix(PackageDoc doc) {
if ( doc == null || doc.name().isEmpty() ) {
return "";
}
else {
StringBuilder buf = new StringBuilder();
buf.append("../");
for ( int i = 0; i < doc.name().length(); i++ ) {
if ( doc.name().charAt(i) == '.' ) {
buf.append("../");
}
}
return buf.toString();
}
} } | public class class_name {
public String rootUrlPrefix(PackageDoc doc) {
if ( doc == null || doc.name().isEmpty() ) {
return ""; // depends on control dependency: [if], data = [none]
}
else {
StringBuilder buf = new StringBuilder();
buf.append("../"); // depends on control dependency: [if], data = [none]
for ( int i = 0; i < doc.name().length(); i++ ) {
if ( doc.name().charAt(i) == '.' ) {
buf.append("../"); // depends on control dependency: [if], data = [none]
}
}
return buf.toString(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static String getRealResourcePath(String path,
Map<String, String> pluginMsgPathMap) {
String realPath = path;
Matcher matcher = PLUGIN_RESOURCE_PATTERN.matcher(path);
StringBuffer sb = new StringBuffer();
if (matcher.find()) {
String pluginName = matcher.group(2);
String pluginPath = pluginMsgPathMap.get(pluginName);
if (pluginPath != null) {
matcher.appendReplacement(sb,
RegexUtil.adaptReplacementToMatcher(pluginPath + "/"));
matcher.appendTail(sb);
realPath = sb.toString();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Plugin path '" + path + "' mapped to '"
+ realPath + "'");
}
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("No Plugin path found for '" + pluginName);
}
}
}
return realPath;
} } | public class class_name {
public static String getRealResourcePath(String path,
Map<String, String> pluginMsgPathMap) {
String realPath = path;
Matcher matcher = PLUGIN_RESOURCE_PATTERN.matcher(path);
StringBuffer sb = new StringBuffer();
if (matcher.find()) {
String pluginName = matcher.group(2);
String pluginPath = pluginMsgPathMap.get(pluginName);
if (pluginPath != null) {
matcher.appendReplacement(sb,
RegexUtil.adaptReplacementToMatcher(pluginPath + "/")); // depends on control dependency: [if], data = [none]
matcher.appendTail(sb); // depends on control dependency: [if], data = [none]
realPath = sb.toString(); // depends on control dependency: [if], data = [none]
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Plugin path '" + path + "' mapped to '"
+ realPath + "'"); // depends on control dependency: [if], data = [none]
}
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("No Plugin path found for '" + pluginName); // depends on control dependency: [if], data = [none]
}
}
}
return realPath;
} } |
public class class_name {
public static boolean isAbsolutePath (final String path) {
if (path == null || path.trim().length() == 0) {
return false;
}
if (File.separator.equals(UNIX_SEPARATOR)) {
return path.startsWith(UNIX_SEPARATOR);
} else
if (File.separator.equals(WINDOWS_SEPARATOR) && path.length() > 2) {
return path.matches("([a-zA-Z]:|\\\\)\\\\.*");
}
return false;
} } | public class class_name {
public static boolean isAbsolutePath (final String path) {
if (path == null || path.trim().length() == 0) {
return false; // depends on control dependency: [if], data = [none]
}
if (File.separator.equals(UNIX_SEPARATOR)) {
return path.startsWith(UNIX_SEPARATOR); // depends on control dependency: [if], data = [none]
} else
if (File.separator.equals(WINDOWS_SEPARATOR) && path.length() > 2) {
return path.matches("([a-zA-Z]:|\\\\)\\\\.*"); // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
private CmsHistoryResourceBean createHistoryResourceBean(
CmsObject cms,
CmsResource historyRes,
boolean offline,
int maxVersion)
throws CmsException {
CmsHistoryResourceBean result = new CmsHistoryResourceBean();
Locale locale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms);
result.setStructureId(historyRes.getStructureId());
result.setRootPath(historyRes.getRootPath());
result.setDateLastModified(formatDate(historyRes.getDateLastModified(), locale));
CmsUUID userId = historyRes.getUserLastModified();
String userName = userId.toString();
try {
CmsUser user = cms.readUser(userId);
userName = user.getName();
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
result.setUserLastModified(userName);
result.setSize(historyRes.getLength());
if (historyRes instanceof I_CmsHistoryResource) {
int publishTag = ((I_CmsHistoryResource)historyRes).getPublishTag();
CmsHistoryProject project = cms.readHistoryProject(publishTag);
long publishDate = project.getPublishingDate();
result.setDatePublished(formatDate(publishDate, locale));
int version = ((I_CmsHistoryResource)historyRes).getVersion();
result.setVersion(
new CmsHistoryVersion(
Integer.valueOf(historyRes.getVersion()),
maxVersion == version ? OfflineOnline.online : null));
List<CmsProperty> historyProperties = cms.readHistoryPropertyObjects((I_CmsHistoryResource)historyRes);
Map<String, CmsProperty> historyPropertyMap = CmsProperty.toObjectMap(historyProperties);
CmsProperty titleProp = CmsProperty.wrapIfNull(
historyPropertyMap.get(CmsPropertyDefinition.PROPERTY_TITLE));
CmsProperty descProp = CmsProperty.wrapIfNull(
historyPropertyMap.get(CmsPropertyDefinition.PROPERTY_DESCRIPTION));
result.setTitle(titleProp.getValue());
result.setDescription(descProp.getValue());
} else {
if (offline) {
result.setVersion(new CmsHistoryVersion(null, OfflineOnline.offline));
} else {
result.setVersion(new CmsHistoryVersion(null, OfflineOnline.online));
}
}
return result;
} } | public class class_name {
private CmsHistoryResourceBean createHistoryResourceBean(
CmsObject cms,
CmsResource historyRes,
boolean offline,
int maxVersion)
throws CmsException {
CmsHistoryResourceBean result = new CmsHistoryResourceBean();
Locale locale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms);
result.setStructureId(historyRes.getStructureId());
result.setRootPath(historyRes.getRootPath());
result.setDateLastModified(formatDate(historyRes.getDateLastModified(), locale));
CmsUUID userId = historyRes.getUserLastModified();
String userName = userId.toString();
try {
CmsUser user = cms.readUser(userId);
userName = user.getName();
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
result.setUserLastModified(userName);
result.setSize(historyRes.getLength());
if (historyRes instanceof I_CmsHistoryResource) {
int publishTag = ((I_CmsHistoryResource)historyRes).getPublishTag();
CmsHistoryProject project = cms.readHistoryProject(publishTag);
long publishDate = project.getPublishingDate();
result.setDatePublished(formatDate(publishDate, locale));
int version = ((I_CmsHistoryResource)historyRes).getVersion();
result.setVersion(
new CmsHistoryVersion(
Integer.valueOf(historyRes.getVersion()),
maxVersion == version ? OfflineOnline.online : null));
List<CmsProperty> historyProperties = cms.readHistoryPropertyObjects((I_CmsHistoryResource)historyRes);
Map<String, CmsProperty> historyPropertyMap = CmsProperty.toObjectMap(historyProperties);
CmsProperty titleProp = CmsProperty.wrapIfNull(
historyPropertyMap.get(CmsPropertyDefinition.PROPERTY_TITLE));
CmsProperty descProp = CmsProperty.wrapIfNull(
historyPropertyMap.get(CmsPropertyDefinition.PROPERTY_DESCRIPTION));
result.setTitle(titleProp.getValue());
result.setDescription(descProp.getValue());
} else {
if (offline) {
result.setVersion(new CmsHistoryVersion(null, OfflineOnline.offline)); // depends on control dependency: [if], data = [none]
} else {
result.setVersion(new CmsHistoryVersion(null, OfflineOnline.online)); // depends on control dependency: [if], data = [none]
}
}
return result;
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.