code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
---|---|
public class class_name {
private Map<String, Object> getMap(String mapString) {
Properties props = new Properties();
try {
props.load(new StringReader(mapString.substring(1, mapString.length() - 1).replaceAll(",\\s*", "\n")));
} catch (IOException e) {
throw new CitrusRuntimeException("Failed to reconstruct object of type map", e);
}
Map<String, Object> map = new LinkedHashMap<>();
for (Map.Entry<Object, Object> entry : props.entrySet()) {
String key;
Object value;
if (entry.getKey() instanceof String) {
key = VariableUtils.cutOffDoubleQuotes(entry.getKey().toString());
} else {
key = entry.getKey().toString();
}
if (entry.getValue() instanceof String) {
value = VariableUtils.cutOffDoubleQuotes(entry.getValue().toString()).trim();
} else {
value = entry.getValue();
}
map.put(key, value);
}
return map;
} } | public class class_name {
private Map<String, Object> getMap(String mapString) {
Properties props = new Properties();
try {
props.load(new StringReader(mapString.substring(1, mapString.length() - 1).replaceAll(",\\s*", "\n"))); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new CitrusRuntimeException("Failed to reconstruct object of type map", e);
} // depends on control dependency: [catch], data = [none]
Map<String, Object> map = new LinkedHashMap<>();
for (Map.Entry<Object, Object> entry : props.entrySet()) {
String key;
Object value;
if (entry.getKey() instanceof String) {
key = VariableUtils.cutOffDoubleQuotes(entry.getKey().toString()); // depends on control dependency: [if], data = [none]
} else {
key = entry.getKey().toString(); // depends on control dependency: [if], data = [none]
}
if (entry.getValue() instanceof String) {
value = VariableUtils.cutOffDoubleQuotes(entry.getValue().toString()).trim(); // depends on control dependency: [if], data = [none]
} else {
value = entry.getValue(); // depends on control dependency: [if], data = [none]
}
map.put(key, value); // depends on control dependency: [for], data = [none]
}
return map;
} } |
public class class_name {
private SearchResponse getSearchResponse(KunderaQuery kunderaQuery, FilteredQueryBuilder queryBuilder,
QueryBuilder filter, ESQuery query, EntityMetadata m, int firstResult, int maxResults,
KunderaMetadata kunderaMetadata)
{
SearchRequestBuilder builder = client.prepareSearch(m.getSchema().toLowerCase())
.setTypes(m.getEntityClazz().getSimpleName());
AggregationBuilder aggregation = query.buildAggregation(kunderaQuery, m, filter);
if (aggregation == null)
{
builder.setQuery(queryBuilder);
builder.setFrom(firstResult);
builder.setSize(maxResults);
addSortOrder(builder, kunderaQuery, m, kunderaMetadata);
}
else
{
log.debug("Aggregated query identified");
builder.addAggregation(aggregation);
if (kunderaQuery.getResult().length == 1 || (kunderaQuery.isSelectStatement()
&& KunderaQueryUtils.hasGroupBy(kunderaQuery.getJpqlExpression())))
{
builder.setSize(0);
}
}
SearchResponse response = null;
log.debug("Query generated: " + builder);
try
{
response = builder.execute().actionGet();
log.debug("Query execution response: " + response);
}
catch (ElasticsearchException e)
{
log.error("Exception occured while executing query on Elasticsearch.", e);
throw new KunderaException("Exception occured while executing query on Elasticsearch.", e);
}
return response;
} } | public class class_name {
private SearchResponse getSearchResponse(KunderaQuery kunderaQuery, FilteredQueryBuilder queryBuilder,
QueryBuilder filter, ESQuery query, EntityMetadata m, int firstResult, int maxResults,
KunderaMetadata kunderaMetadata)
{
SearchRequestBuilder builder = client.prepareSearch(m.getSchema().toLowerCase())
.setTypes(m.getEntityClazz().getSimpleName());
AggregationBuilder aggregation = query.buildAggregation(kunderaQuery, m, filter);
if (aggregation == null)
{
builder.setQuery(queryBuilder); // depends on control dependency: [if], data = [none]
builder.setFrom(firstResult); // depends on control dependency: [if], data = [none]
builder.setSize(maxResults); // depends on control dependency: [if], data = [none]
addSortOrder(builder, kunderaQuery, m, kunderaMetadata); // depends on control dependency: [if], data = [none]
}
else
{
log.debug("Aggregated query identified"); // depends on control dependency: [if], data = [none]
builder.addAggregation(aggregation); // depends on control dependency: [if], data = [(aggregation]
if (kunderaQuery.getResult().length == 1 || (kunderaQuery.isSelectStatement()
&& KunderaQueryUtils.hasGroupBy(kunderaQuery.getJpqlExpression())))
{
builder.setSize(0); // depends on control dependency: [if], data = [none]
}
}
SearchResponse response = null;
log.debug("Query generated: " + builder);
try
{
response = builder.execute().actionGet(); // depends on control dependency: [try], data = [none]
log.debug("Query execution response: " + response); // depends on control dependency: [try], data = [none]
}
catch (ElasticsearchException e)
{
log.error("Exception occured while executing query on Elasticsearch.", e);
throw new KunderaException("Exception occured while executing query on Elasticsearch.", e);
} // depends on control dependency: [catch], data = [none]
return response;
} } |
public class class_name {
@SuppressWarnings("deprecation")
public static <T> T toEntity(final Class<T> targetClass, final Document doc) {
checkTargetClass(targetClass);
if (Map.class.isAssignableFrom(targetClass)) {
// return (T) new LinkedHashMap<>(doc);
if (targetClass.isAssignableFrom(doc.getClass())) {
return (T) doc;
} else {
final Map<String, Object> map = (Map<String, Object>) N.newInstance(targetClass);
map.putAll(doc);
return (T) map;
}
}
final Method idSetMethod = getObjectIdSetMethod(targetClass);
final Class<?> parameterType = idSetMethod == null ? null : idSetMethod.getParameterTypes()[0];
final Object objectId = doc.getObjectId(_ID);
T entity = null;
doc.remove(_ID);
try {
entity = Maps.map2Entity(targetClass, doc);
if (objectId != null && parameterType != null) {
if (parameterType.isAssignableFrom(objectId.getClass())) {
ClassUtil.setPropValue(entity, idSetMethod, objectId);
} else if (parameterType.isAssignableFrom(String.class)) {
ClassUtil.setPropValue(entity, idSetMethod, objectId.toString());
} else {
ClassUtil.setPropValue(entity, idSetMethod, objectId);
}
}
} finally {
doc.put(_ID, objectId);
}
if (N.isDirtyMarker(entity.getClass())) {
((DirtyMarker) entity).markDirty(false);
}
return entity;
} } | public class class_name {
@SuppressWarnings("deprecation")
public static <T> T toEntity(final Class<T> targetClass, final Document doc) {
checkTargetClass(targetClass);
if (Map.class.isAssignableFrom(targetClass)) {
// return (T) new LinkedHashMap<>(doc);
if (targetClass.isAssignableFrom(doc.getClass())) {
return (T) doc;
// depends on control dependency: [if], data = [none]
} else {
final Map<String, Object> map = (Map<String, Object>) N.newInstance(targetClass);
map.putAll(doc);
// depends on control dependency: [if], data = [none]
return (T) map;
// depends on control dependency: [if], data = [none]
}
}
final Method idSetMethod = getObjectIdSetMethod(targetClass);
final Class<?> parameterType = idSetMethod == null ? null : idSetMethod.getParameterTypes()[0];
final Object objectId = doc.getObjectId(_ID);
T entity = null;
doc.remove(_ID);
try {
entity = Maps.map2Entity(targetClass, doc);
// depends on control dependency: [try], data = [none]
if (objectId != null && parameterType != null) {
if (parameterType.isAssignableFrom(objectId.getClass())) {
ClassUtil.setPropValue(entity, idSetMethod, objectId);
// depends on control dependency: [if], data = [none]
} else if (parameterType.isAssignableFrom(String.class)) {
ClassUtil.setPropValue(entity, idSetMethod, objectId.toString());
// depends on control dependency: [if], data = [none]
} else {
ClassUtil.setPropValue(entity, idSetMethod, objectId);
// depends on control dependency: [if], data = [none]
}
}
} finally {
doc.put(_ID, objectId);
}
if (N.isDirtyMarker(entity.getClass())) {
((DirtyMarker) entity).markDirty(false);
// depends on control dependency: [if], data = [none]
}
return entity;
} } |
public class class_name {
private static CouchbaseResponse handleSubdocumentMultiMutationResponseMessages(BinaryRequest request,
FullBinaryMemcacheResponse msg, ChannelHandlerContext ctx, ResponseStatus status, boolean seqOnMutation) {
if (!(request instanceof BinarySubdocMultiMutationRequest))
return null;
BinarySubdocMultiMutationRequest subdocRequest = (BinarySubdocMultiMutationRequest) request;
long cas = msg.getCAS();
short statusCode = msg.getStatus();
String bucket = request.bucket();
MutationToken mutationToken = null;
if (msg.getExtrasLength() > 0) {
mutationToken = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(), request.partition());
}
MultiMutationResponse response;
ByteBuf body = msg.content();
List<MultiResult<Mutation>> responses;
if (status.isSuccess()) {
List<MutationCommand> commands = subdocRequest.commands();
responses = new ArrayList<MultiResult<Mutation>>(commands.size());
//MB-17842: Mutations can have a value, so there could be individual results
//but only mutation commands that provide a value will have an explicit result in the binary response.
//However, we still want MutationResult for all of the commands
ListIterator<MutationCommand> it = commands.listIterator();
int explicitResultSize = 0;
//as long as there is an explicit response to read...
while(msg.content().readableBytes() >= 7) {
explicitResultSize++;
//...read the data
byte responseIndex = body.readByte();
short responseStatus = body.readShort(); //will this always be SUCCESS?
int responseLength = body.readInt();
ByteBuf responseValue;
if (responseLength > 0) {
responseValue = ctx.alloc().buffer(responseLength, responseLength);
responseValue.writeBytes(body, responseLength);
} else {
responseValue = Unpooled.EMPTY_BUFFER; //can an explicit response be 0-length (empty)?
}
//...sanity check response so subsequent loop don't run forever
if (it.nextIndex() > responseIndex) {
body.release();
throw new IllegalStateException("Unable to interpret multi mutation response, responseIndex = " +
responseIndex + " while next available command was #" + it.nextIndex());
}
///...catch up on all commands before current one that didn't get an explicit response
while(it.nextIndex() < responseIndex) {
MutationCommand noResultCommand = it.next();
responses.add(MultiResult.create(KeyValueStatus.SUCCESS.code(), ResponseStatus.SUCCESS,
noResultCommand.path(), noResultCommand.mutation(),
Unpooled.EMPTY_BUFFER));
}
//...then process the one that did get an explicit response
MutationCommand cmd = it.next();
responses.add(MultiResult.create(responseStatus, ResponseStatusConverter.fromBinary(responseStatus),
cmd.path(), cmd.mutation(), responseValue));
}
//...and finally the remainder of commands after the last one that got an explicit response:
while(it.hasNext()) {
MutationCommand noResultCommand = it.next();
responses.add(MultiResult.create(KeyValueStatus.SUCCESS.code(), ResponseStatus.SUCCESS,
noResultCommand.path(), noResultCommand.mutation(),
Unpooled.EMPTY_BUFFER));
}
if (responses.size() != commands.size()) {
body.release();
throw new IllegalStateException("Multi mutation spec size and result size differ: " + commands.size() +
" vs " + responses.size() + ", including " + explicitResultSize + " explicit results");
}
response = new MultiMutationResponse(bucket, subdocRequest, cas, mutationToken, responses);
} else if (ResponseStatus.SUBDOC_MULTI_PATH_FAILURE.equals(status)) {
//MB-17842: order of index and status has been swapped
byte firstErrorIndex = body.readByte();
short firstErrorCode = body.readShort();
response = new MultiMutationResponse(status, statusCode, bucket, firstErrorIndex, firstErrorCode,
subdocRequest, cas, mutationToken);
} else {
response = new MultiMutationResponse(status, statusCode, bucket, subdocRequest, cas, mutationToken);
}
body.release();
return response;
} } | public class class_name {
private static CouchbaseResponse handleSubdocumentMultiMutationResponseMessages(BinaryRequest request,
FullBinaryMemcacheResponse msg, ChannelHandlerContext ctx, ResponseStatus status, boolean seqOnMutation) {
if (!(request instanceof BinarySubdocMultiMutationRequest))
return null;
BinarySubdocMultiMutationRequest subdocRequest = (BinarySubdocMultiMutationRequest) request;
long cas = msg.getCAS();
short statusCode = msg.getStatus();
String bucket = request.bucket();
MutationToken mutationToken = null;
if (msg.getExtrasLength() > 0) {
mutationToken = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(), request.partition()); // depends on control dependency: [if], data = [none]
}
MultiMutationResponse response;
ByteBuf body = msg.content();
List<MultiResult<Mutation>> responses;
if (status.isSuccess()) {
List<MutationCommand> commands = subdocRequest.commands();
responses = new ArrayList<MultiResult<Mutation>>(commands.size()); // depends on control dependency: [if], data = [none]
//MB-17842: Mutations can have a value, so there could be individual results
//but only mutation commands that provide a value will have an explicit result in the binary response.
//However, we still want MutationResult for all of the commands
ListIterator<MutationCommand> it = commands.listIterator();
int explicitResultSize = 0;
//as long as there is an explicit response to read...
while(msg.content().readableBytes() >= 7) {
explicitResultSize++; // depends on control dependency: [while], data = [none]
//...read the data
byte responseIndex = body.readByte();
short responseStatus = body.readShort(); //will this always be SUCCESS?
int responseLength = body.readInt();
ByteBuf responseValue;
if (responseLength > 0) {
responseValue = ctx.alloc().buffer(responseLength, responseLength); // depends on control dependency: [if], data = [(responseLength]
responseValue.writeBytes(body, responseLength); // depends on control dependency: [if], data = [none]
} else {
responseValue = Unpooled.EMPTY_BUFFER; //can an explicit response be 0-length (empty)? // depends on control dependency: [if], data = [none]
}
//...sanity check response so subsequent loop don't run forever
if (it.nextIndex() > responseIndex) {
body.release(); // depends on control dependency: [if], data = [none]
throw new IllegalStateException("Unable to interpret multi mutation response, responseIndex = " +
responseIndex + " while next available command was #" + it.nextIndex());
}
///...catch up on all commands before current one that didn't get an explicit response
while(it.nextIndex() < responseIndex) {
MutationCommand noResultCommand = it.next();
responses.add(MultiResult.create(KeyValueStatus.SUCCESS.code(), ResponseStatus.SUCCESS,
noResultCommand.path(), noResultCommand.mutation(),
Unpooled.EMPTY_BUFFER)); // depends on control dependency: [while], data = [none]
}
//...then process the one that did get an explicit response
MutationCommand cmd = it.next();
responses.add(MultiResult.create(responseStatus, ResponseStatusConverter.fromBinary(responseStatus),
cmd.path(), cmd.mutation(), responseValue)); // depends on control dependency: [while], data = [none]
}
//...and finally the remainder of commands after the last one that got an explicit response:
while(it.hasNext()) {
MutationCommand noResultCommand = it.next();
responses.add(MultiResult.create(KeyValueStatus.SUCCESS.code(), ResponseStatus.SUCCESS,
noResultCommand.path(), noResultCommand.mutation(),
Unpooled.EMPTY_BUFFER)); // depends on control dependency: [while], data = [none]
}
if (responses.size() != commands.size()) {
body.release(); // depends on control dependency: [if], data = [none]
throw new IllegalStateException("Multi mutation spec size and result size differ: " + commands.size() +
" vs " + responses.size() + ", including " + explicitResultSize + " explicit results");
}
response = new MultiMutationResponse(bucket, subdocRequest, cas, mutationToken, responses); // depends on control dependency: [if], data = [none]
} else if (ResponseStatus.SUBDOC_MULTI_PATH_FAILURE.equals(status)) {
//MB-17842: order of index and status has been swapped
byte firstErrorIndex = body.readByte();
short firstErrorCode = body.readShort();
response = new MultiMutationResponse(status, statusCode, bucket, firstErrorIndex, firstErrorCode,
subdocRequest, cas, mutationToken); // depends on control dependency: [if], data = [none]
} else {
response = new MultiMutationResponse(status, statusCode, bucket, subdocRequest, cas, mutationToken); // depends on control dependency: [if], data = [none]
}
body.release();
return response;
} } |
public class class_name {
public boolean addObjectFactoryForClass(JDefinedClass clazz) {
JDefinedClass valueObjectFactoryClass = clazz._package()._getClass(FACTORY_CLASS_NAME);
if (objectFactoryClasses.containsKey(valueObjectFactoryClass.fullName())) {
return false;
}
objectFactoryClasses.put(valueObjectFactoryClass.fullName(), valueObjectFactoryClass);
JDefinedClass objectFactoryClass = null;
// If class has a non-hidden interface, then there is object factory in another package.
for (Iterator<JClass> iter = clazz._implements(); iter.hasNext();) {
JClass interfaceClass = iter.next();
if (!isHiddenClass(interfaceClass)) {
objectFactoryClass = interfaceClass._package()._getClass(FACTORY_CLASS_NAME);
if (objectFactoryClass != null) {
objectFactoryClasses.put(objectFactoryClass.fullName(), objectFactoryClass);
}
}
}
return objectFactoryClass != null;
} } | public class class_name {
public boolean addObjectFactoryForClass(JDefinedClass clazz) {
JDefinedClass valueObjectFactoryClass = clazz._package()._getClass(FACTORY_CLASS_NAME);
if (objectFactoryClasses.containsKey(valueObjectFactoryClass.fullName())) {
return false;
// depends on control dependency: [if], data = [none]
}
objectFactoryClasses.put(valueObjectFactoryClass.fullName(), valueObjectFactoryClass);
JDefinedClass objectFactoryClass = null;
// If class has a non-hidden interface, then there is object factory in another package.
for (Iterator<JClass> iter = clazz._implements(); iter.hasNext();) {
JClass interfaceClass = iter.next();
if (!isHiddenClass(interfaceClass)) {
objectFactoryClass = interfaceClass._package()._getClass(FACTORY_CLASS_NAME);
// depends on control dependency: [if], data = [none]
if (objectFactoryClass != null) {
objectFactoryClasses.put(objectFactoryClass.fullName(), objectFactoryClass);
// depends on control dependency: [if], data = [(objectFactoryClass]
}
}
}
return objectFactoryClass != null;
} } |
public class class_name {
public long getLastModified() throws GetLastModifiedException {
long result;
result = Long.MIN_VALUE;
for (Node node : nodes) {
if (node instanceof HttpNode) {
// skip getLastModified - it's not supported by Webservice Stub Servlet
} else {
result = Math.max(result, node.getLastModified());
}
}
return result == Long.MIN_VALUE ? -1 : result;
} } | public class class_name {
public long getLastModified() throws GetLastModifiedException {
long result;
result = Long.MIN_VALUE;
for (Node node : nodes) {
if (node instanceof HttpNode) {
// skip getLastModified - it's not supported by Webservice Stub Servlet
} else {
result = Math.max(result, node.getLastModified()); // depends on control dependency: [if], data = [none]
}
}
return result == Long.MIN_VALUE ? -1 : result;
} } |
public class class_name {
@Override
public void close() {
try {
xmlSerializer.close();
} catch (Exception e) {
e.printStackTrace();
throw new KriptonRuntimeException(e);
}
} } | public class class_name {
@Override
public void close() {
try {
xmlSerializer.close(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
e.printStackTrace();
throw new KriptonRuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private Model initModel() {
OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, ModelFactory.createDefaultModel());
try {
schemaReader.read(m);
} catch (RdfReaderException e) {
log.error("Cannot load ontology: {} ", getSchema(), e);
}
return m;
} } | public class class_name {
private Model initModel() {
OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, ModelFactory.createDefaultModel());
try {
schemaReader.read(m); // depends on control dependency: [try], data = [none]
} catch (RdfReaderException e) {
log.error("Cannot load ontology: {} ", getSchema(), e);
} // depends on control dependency: [catch], data = [none]
return m;
} } |
public class class_name {
public Collection<File> buildClasspathList( final MavenProject project, final String scope,
Set<Artifact> artifacts, boolean isGenerator )
throws ClasspathBuilderException
{
getLogger().debug( "establishing classpath list (scope = " + scope + ")" );
Set<File> items = new LinkedHashSet<File>();
// Note : Don't call addSourceWithActiveProject as a GWT dependency MUST be a valid GWT library module :
// * include java sources in the JAR as resources
// * define a gwt.xml module file to declare the required inherits
// addSourceWithActiveProject would make some java sources available to GWT compiler that should not be accessible in
// a non-reactor build, making the build less deterministic and encouraging bad design.
if ( !isGenerator ) {
items.add( new File( project.getBuild().getOutputDirectory() ) );
}
addSources( items, project.getCompileSourceRoots() );
if ( isGenerator ) {
addResources( items, project.getResources() );
}
// Use our own ClasspathElements fitering, as for RUNTIME we need to include PROVIDED artifacts,
// that is not the default Maven policy, as RUNTIME is used here to build the GWTShell execution classpath
if ( scope.equals( SCOPE_TEST ) )
{
addSources( items, project.getTestCompileSourceRoots() );
addResources( items, project.getTestResources() );
items.add( new File( project.getBuild().getTestOutputDirectory() ) );
// Add all project dependencies in classpath
for ( Artifact artifact : artifacts )
{
items.add( artifact.getFile() );
}
}
else if ( scope.equals( SCOPE_COMPILE ) )
{
// Add all project dependencies in classpath
getLogger().debug( "candidate artifacts : " + artifacts.size() );
for ( Artifact artifact : artifacts )
{
String artifactScope = artifact.getScope();
if ( SCOPE_COMPILE.equals( artifactScope ) || SCOPE_PROVIDED.equals( artifactScope )
|| SCOPE_SYSTEM.equals( artifactScope ) )
{
items.add( artifact.getFile() );
}
}
}
else if ( scope.equals( SCOPE_RUNTIME ) )
{
// Add all dependencies BUT "TEST" as we need PROVIDED ones to setup the execution
// GWTShell that is NOT a full JEE server
for ( Artifact artifact : artifacts )
{
getLogger().debug( "candidate artifact : " + artifact );
if ( !artifact.getScope().equals( SCOPE_TEST ) && artifact.getArtifactHandler().isAddedToClasspath() )
{
items.add( artifact.getFile() );
}
}
}
else
{
throw new ClasspathBuilderException( "unsupported scope " + scope );
}
return items;
} } | public class class_name {
public Collection<File> buildClasspathList( final MavenProject project, final String scope,
Set<Artifact> artifacts, boolean isGenerator )
throws ClasspathBuilderException
{
getLogger().debug( "establishing classpath list (scope = " + scope + ")" );
Set<File> items = new LinkedHashSet<File>();
// Note : Don't call addSourceWithActiveProject as a GWT dependency MUST be a valid GWT library module :
// * include java sources in the JAR as resources
// * define a gwt.xml module file to declare the required inherits
// addSourceWithActiveProject would make some java sources available to GWT compiler that should not be accessible in
// a non-reactor build, making the build less deterministic and encouraging bad design.
if ( !isGenerator ) {
items.add( new File( project.getBuild().getOutputDirectory() ) );
}
addSources( items, project.getCompileSourceRoots() );
if ( isGenerator ) {
addResources( items, project.getResources() );
}
// Use our own ClasspathElements fitering, as for RUNTIME we need to include PROVIDED artifacts,
// that is not the default Maven policy, as RUNTIME is used here to build the GWTShell execution classpath
if ( scope.equals( SCOPE_TEST ) )
{
addSources( items, project.getTestCompileSourceRoots() );
addResources( items, project.getTestResources() );
items.add( new File( project.getBuild().getTestOutputDirectory() ) );
// Add all project dependencies in classpath
for ( Artifact artifact : artifacts )
{
items.add( artifact.getFile() ); // depends on control dependency: [for], data = [artifact]
}
}
else if ( scope.equals( SCOPE_COMPILE ) )
{
// Add all project dependencies in classpath
getLogger().debug( "candidate artifacts : " + artifacts.size() );
for ( Artifact artifact : artifacts )
{
String artifactScope = artifact.getScope();
if ( SCOPE_COMPILE.equals( artifactScope ) || SCOPE_PROVIDED.equals( artifactScope )
|| SCOPE_SYSTEM.equals( artifactScope ) )
{
items.add( artifact.getFile() ); // depends on control dependency: [if], data = [none]
}
}
}
else if ( scope.equals( SCOPE_RUNTIME ) )
{
// Add all dependencies BUT "TEST" as we need PROVIDED ones to setup the execution
// GWTShell that is NOT a full JEE server
for ( Artifact artifact : artifacts )
{
getLogger().debug( "candidate artifact : " + artifact );
if ( !artifact.getScope().equals( SCOPE_TEST ) && artifact.getArtifactHandler().isAddedToClasspath() )
{
items.add( artifact.getFile() );
}
}
}
else
{
throw new ClasspathBuilderException( "unsupported scope " + scope );
}
return items;
} } |
public class class_name {
public boolean shouldDisplay() throws IOException, ServletException {
if (!Functions.hasPermission(Jenkins.ADMINISTER)) {
return false;
}
StaplerRequest req = Stapler.getCurrentRequest();
if (req == null) {
return false;
}
List<Ancestor> ancestors = req.getAncestors();
if (ancestors == null || ancestors.size() == 0) {
// ???
return false;
}
Ancestor a = ancestors.get(ancestors.size() - 1);
Object o = a.getObject();
// don't show while Jenkins is loading
if (o instanceof HudsonIsLoading) {
return false;
}
// … or restarting
if (o instanceof HudsonIsRestarting) {
return false;
}
// don't show for some URLs served directly by Jenkins
if (o instanceof Jenkins) {
String url = a.getRestOfUrl();
if (ignoredJenkinsRestOfUrls.contains(url)) {
return false;
}
}
if (getActiveAdministrativeMonitorsCount() == 0) {
return false;
}
return true;
} } | public class class_name {
public boolean shouldDisplay() throws IOException, ServletException {
if (!Functions.hasPermission(Jenkins.ADMINISTER)) {
return false;
}
StaplerRequest req = Stapler.getCurrentRequest();
if (req == null) {
return false;
}
List<Ancestor> ancestors = req.getAncestors();
if (ancestors == null || ancestors.size() == 0) {
// ???
return false;
}
Ancestor a = ancestors.get(ancestors.size() - 1);
Object o = a.getObject();
// don't show while Jenkins is loading
if (o instanceof HudsonIsLoading) {
return false;
}
// … or restarting
if (o instanceof HudsonIsRestarting) {
return false;
}
// don't show for some URLs served directly by Jenkins
if (o instanceof Jenkins) {
String url = a.getRestOfUrl();
if (ignoredJenkinsRestOfUrls.contains(url)) {
return false; // depends on control dependency: [if], data = [none]
}
}
if (getActiveAdministrativeMonitorsCount() == 0) {
return false;
}
return true;
} } |
public class class_name {
@FFDCIgnore({ ConfigEvaluatorException.class, ConfigRetrieverException.class })
Object evaluateMetaTypeAttribute(final String attributeName, final EvaluationContext context,
final ExtendedAttributeDefinition attributeDef, final String flatPrefix,
final boolean ignoreWarnings) throws ConfigEvaluatorException {
final ConfigElement config = context.getConfigElement();
context.setAttributeName(attributeName);
context.addProcessed(attributeName);
final String prefixedAttributeName = flatPrefix.length() == 0 ? attributeName : flatPrefix + attributeName;
Object rawValue = null;
if (attributeDef.getCopyOf() != null) {
AttributeValueCopy copy = new AttributeValueCopy(prefixedAttributeName, attributeDef.getCopyOf());
context.addAttributeValueCopy(copy);
}
if (attributeDef.isFlat()) {
//TODO check for not final, not PID??
RegistryEntry nestedRegistryEntry = getRegistryEntry(attributeDef.getReferencePid());
if (nestedRegistryEntry == null) {
return null;
}
//TODO rename + flat wont' work yet.
final Set<String> processedNames = new HashSet<String>();
final AtomicInteger i = new AtomicInteger();
String[] referenceAttributes = getReferenceAttributes(attributeName);
evaluateFlatReference(referenceAttributes, context, nestedRegistryEntry, flatPrefix, config, i, processedNames, ignoreWarnings, attributeDef);
ConfigEvaluatorException e = nestedRegistryEntry.traverseHierarchy(new EntryAction<ConfigEvaluatorException>() {
private ConfigEvaluatorException result;
@Override
public boolean entry(RegistryEntry registryEntry) {
String elementName = registryEntry.getEffectiveAD(attributeName);
if (elementName != null) {
context.addProcessed(elementName);
try {
evaluateFlatAttribute(attributeName, elementName, context, registryEntry, flatPrefix, config, i, processedNames, ignoreWarnings);
} catch (ConfigEvaluatorException e) {
result = e;
return false;
}
}
return true;
}
@Override
public ConfigEvaluatorException getResult() {
return result;
}
});
if (e != null) {
throw e;
}
evaluateFlatAttribute(attributeName, attributeName, context, nestedRegistryEntry, flatPrefix, config, i, processedNames, ignoreWarnings);
// if (hierarchy != null) {
// for (RegistryEntry entry : hierarchy) {
// //TODO both pid and alias? or just alias?
// i = evaluateFlatAttribute(attributeName, entry.getPid(), context, entry, flatPrefix, config, i, processedNames, ignoreWarnings);
// if (entry.getAlias() != null) {
// i = evaluateFlatAttribute(attributeName, entry.getAlias(), context, entry, flatPrefix, config, i, processedNames, ignoreWarnings);
// }
// //TODO extends alias, not childAlias
// if (entry.getChildAlias() != null) {
// i = evaluateFlatAttribute(attributeName, entry.getChildAlias(), context, entry, flatPrefix, config, i, processedNames, ignoreWarnings);
// }
// }
// }
// i = evaluateFlatAttribute(attributeName, attributeName, context, nestedRegistryEntry, flatPrefix, config, i, processedNames, ignoreWarnings);
//TODO no merging of flat stuff for cardinality 0.
int cardinality = attributeDef.getCardinality();
cardinality = cardinality == Integer.MIN_VALUE ? Integer.MAX_VALUE : cardinality < 0 ? -cardinality : cardinality == 0 ? 1 : cardinality;
if (i.get() > cardinality) {
throw new ConfigEvaluatorException("Attribute " + attributeDef.getID() + " exceeded maximum allowed size " + cardinality);
}
return i.get() == 0 ? null : i;
}
//Check the properties to pick up already evaluated attributes
Object actualValue = context.getProperties().get(attributeDef.getID());
if (actualValue != null) {
return actualValue;
}
if (!attributeDef.isFinal()) {
if (attributeDef.getType() == MetaTypeFactory.PID_TYPE) {
if (attributeDef.getReferencePid() != null) {
RegistryEntry registryEntry = getRegistryEntry(attributeDef.getReferencePid());
if (registryEntry != null) {
rawValue = registryEntry.traverseHierarchy(new EntryAction<Object>() {
private Object rawValue;
@Override
public boolean entry(RegistryEntry registryEntry) {
if (registryEntry.getEffectiveAD(attributeName) != null) {
rawValue = mergeReferenceAttributes(registryEntry.getEffectiveAD(attributeName), context, attributeDef, config, rawValue);
}
return true;
}
@Override
public Object getResult() {
return rawValue;
}
});
}
}
rawValue = mergeReferenceAttributes(attributeName, context, attributeDef, config, rawValue);
} else {
rawValue = config.getAttribute(attributeName);
}
} else if (isWildcardReference(attributeDef)) {
String factoryPid = attributeDef.getReferencePid();
WildcardReference ref = new WildcardReference(factoryPid, attributeDef, context.getConfigElement().getConfigID());
context.addUnresolvedReference(ref);
try {
ExtendedConfiguration[] configs = configRetriever.findAllConfigurationsByPid(factoryPid);
configs = configs == null ? new ExtendedConfiguration[0] : configs;
ArrayList<String> pids = new ArrayList<String>(configs.length);
for (ExtendedConfiguration extConfig : configs) {
pids.add(extConfig.getPid());
}
if (attributeDef.getCardinality() > 0) {
actualValue = pids.toArray(new String[0]);
} else {
actualValue = pids;
}
if (actualValue != null) {
context.setProperty(prefixedAttributeName, actualValue);
}
evaluateFinish(context);
return actualValue;
} catch (ConfigRetrieverException e) {
throw new ConfigEvaluatorException("problem looking up configurations with factoryPid " + factoryPid);
}
} else if (isWildcardService(attributeDef)) {
String service = attributeDef.getService();
WildcardService ref = new WildcardService(service, attributeDef, context.getConfigElement().getConfigID());
context.addUnresolvedReference(ref);
try {
ArrayList<String> pids = new ArrayList<String>();
List<RegistryEntry> entries = metatypeRegistry.getEntriesExposingService(service);
if (entries != null) {
for (RegistryEntry entry : entries) {
ExtendedConfiguration[] configs = configRetriever.findAllConfigurationsByPid(entry.getPid());
configs = configs == null ? new ExtendedConfiguration[0] : configs;
for (ExtendedConfiguration extConfig : configs) {
pids.add(extConfig.getPid());
}
}
}
if (attributeDef.getCardinality() > 0) {
actualValue = pids.toArray(new String[0]);
} else {
actualValue = pids;
}
if (actualValue != null) {
context.setProperty(prefixedAttributeName, actualValue);
}
evaluateFinish(context);
return actualValue;
} catch (ConfigRetrieverException e) {
throw new ConfigEvaluatorException("problem looking up configurations with service " + service);
}
}
if (rawValue == null) {
rawValue = getUnconfiguredAttributeValue(context, attributeDef);
}
// Process any list variables of the form ${list(variableName)}. We do this here separately from the other variable expression
// processing so that the values are available prior to cardinality checks.
if (rawValue != null) {
rawValue = variableEvaluator.processVariableLists(rawValue, attributeDef, context, ignoreWarnings);
}
if (rawValue != null) {
try {
actualValue = evaluateMetaType(rawValue, attributeDef, context, ignoreWarnings);
} catch (ConfigEvaluatorException iae) {
// try to fall-back to default value if validation of an option fails.
String validOptions[] = attributeDef.getOptionValues();
if (validOptions == null) {
// Fall back to variable registry or default value
Object badValue = rawValue;
rawValue = getUnconfiguredAttributeValue(context, attributeDef);
if (rawValue != null && !ignoreWarnings) {
Tr.warning(tc, "warn.config.validate.failed", iae.getMessage());
Tr.warning(tc, "warn.config.invalid.using.default.value", attributeDef.getID(), badValue, rawValue);
actualValue = evaluateMetaType(rawValue, attributeDef, context, ignoreWarnings);
} else {
throw iae;
}
} else {
if (tc.isWarningEnabled() && !ignoreWarnings) {
StringBuffer strBuffer = new StringBuffer();
// This formatter is consistent with the message in nlsprops
for (int i = 0; i < validOptions.length; i++) {
strBuffer.append("[");
strBuffer.append(validOptions[i]);
strBuffer.append("]");
}
Tr.warning(tc, "warn.config.invalid.value", attributeDef.getID(), rawValue, strBuffer.toString());
}
// Fall back to variable registry or default value
rawValue = getUnconfiguredAttributeValue(context, attributeDef);
if (rawValue != null) {
actualValue = evaluateMetaType(rawValue, attributeDef, context, ignoreWarnings);
}
}
}
if (actualValue != null) {
context.setProperty(prefixedAttributeName, actualValue);
}
evaluateFinish(context);
}
return actualValue;
} } | public class class_name {
@FFDCIgnore({ ConfigEvaluatorException.class, ConfigRetrieverException.class })
Object evaluateMetaTypeAttribute(final String attributeName, final EvaluationContext context,
final ExtendedAttributeDefinition attributeDef, final String flatPrefix,
final boolean ignoreWarnings) throws ConfigEvaluatorException {
final ConfigElement config = context.getConfigElement();
context.setAttributeName(attributeName);
context.addProcessed(attributeName);
final String prefixedAttributeName = flatPrefix.length() == 0 ? attributeName : flatPrefix + attributeName;
Object rawValue = null;
if (attributeDef.getCopyOf() != null) {
AttributeValueCopy copy = new AttributeValueCopy(prefixedAttributeName, attributeDef.getCopyOf());
context.addAttributeValueCopy(copy);
}
if (attributeDef.isFlat()) {
//TODO check for not final, not PID??
RegistryEntry nestedRegistryEntry = getRegistryEntry(attributeDef.getReferencePid());
if (nestedRegistryEntry == null) {
return null; // depends on control dependency: [if], data = [none]
}
//TODO rename + flat wont' work yet.
final Set<String> processedNames = new HashSet<String>();
final AtomicInteger i = new AtomicInteger();
String[] referenceAttributes = getReferenceAttributes(attributeName);
evaluateFlatReference(referenceAttributes, context, nestedRegistryEntry, flatPrefix, config, i, processedNames, ignoreWarnings, attributeDef);
ConfigEvaluatorException e = nestedRegistryEntry.traverseHierarchy(new EntryAction<ConfigEvaluatorException>() {
private ConfigEvaluatorException result;
@Override
public boolean entry(RegistryEntry registryEntry) {
String elementName = registryEntry.getEffectiveAD(attributeName);
if (elementName != null) {
context.addProcessed(elementName); // depends on control dependency: [if], data = [(elementName]
try {
evaluateFlatAttribute(attributeName, elementName, context, registryEntry, flatPrefix, config, i, processedNames, ignoreWarnings); // depends on control dependency: [try], data = [none]
} catch (ConfigEvaluatorException e) {
result = e;
return false;
} // depends on control dependency: [catch], data = [none]
}
return true;
}
@Override
public ConfigEvaluatorException getResult() {
return result;
}
});
if (e != null) {
throw e;
}
evaluateFlatAttribute(attributeName, attributeName, context, nestedRegistryEntry, flatPrefix, config, i, processedNames, ignoreWarnings);
// if (hierarchy != null) {
// for (RegistryEntry entry : hierarchy) {
// //TODO both pid and alias? or just alias?
// i = evaluateFlatAttribute(attributeName, entry.getPid(), context, entry, flatPrefix, config, i, processedNames, ignoreWarnings);
// if (entry.getAlias() != null) {
// i = evaluateFlatAttribute(attributeName, entry.getAlias(), context, entry, flatPrefix, config, i, processedNames, ignoreWarnings);
// }
// //TODO extends alias, not childAlias
// if (entry.getChildAlias() != null) {
// i = evaluateFlatAttribute(attributeName, entry.getChildAlias(), context, entry, flatPrefix, config, i, processedNames, ignoreWarnings);
// }
// }
// }
// i = evaluateFlatAttribute(attributeName, attributeName, context, nestedRegistryEntry, flatPrefix, config, i, processedNames, ignoreWarnings);
//TODO no merging of flat stuff for cardinality 0.
int cardinality = attributeDef.getCardinality();
cardinality = cardinality == Integer.MIN_VALUE ? Integer.MAX_VALUE : cardinality < 0 ? -cardinality : cardinality == 0 ? 1 : cardinality;
if (i.get() > cardinality) {
throw new ConfigEvaluatorException("Attribute " + attributeDef.getID() + " exceeded maximum allowed size " + cardinality);
}
return i.get() == 0 ? null : i;
}
//Check the properties to pick up already evaluated attributes
Object actualValue = context.getProperties().get(attributeDef.getID());
if (actualValue != null) {
return actualValue;
}
if (!attributeDef.isFinal()) {
if (attributeDef.getType() == MetaTypeFactory.PID_TYPE) {
if (attributeDef.getReferencePid() != null) {
RegistryEntry registryEntry = getRegistryEntry(attributeDef.getReferencePid());
if (registryEntry != null) {
rawValue = registryEntry.traverseHierarchy(new EntryAction<Object>() {
private Object rawValue;
@Override
public boolean entry(RegistryEntry registryEntry) {
if (registryEntry.getEffectiveAD(attributeName) != null) {
rawValue = mergeReferenceAttributes(registryEntry.getEffectiveAD(attributeName), context, attributeDef, config, rawValue); // depends on control dependency: [if], data = [(registryEntry.getEffectiveAD(attributeName)]
}
return true;
}
@Override
public Object getResult() {
return rawValue;
}
}); // depends on control dependency: [if], data = [none]
}
}
rawValue = mergeReferenceAttributes(attributeName, context, attributeDef, config, rawValue);
} else {
rawValue = config.getAttribute(attributeName);
}
} else if (isWildcardReference(attributeDef)) {
String factoryPid = attributeDef.getReferencePid();
WildcardReference ref = new WildcardReference(factoryPid, attributeDef, context.getConfigElement().getConfigID());
context.addUnresolvedReference(ref);
try {
ExtendedConfiguration[] configs = configRetriever.findAllConfigurationsByPid(factoryPid);
configs = configs == null ? new ExtendedConfiguration[0] : configs;
ArrayList<String> pids = new ArrayList<String>(configs.length);
for (ExtendedConfiguration extConfig : configs) {
pids.add(extConfig.getPid());
}
if (attributeDef.getCardinality() > 0) {
actualValue = pids.toArray(new String[0]);
} else {
actualValue = pids;
}
if (actualValue != null) {
context.setProperty(prefixedAttributeName, actualValue);
}
evaluateFinish(context);
return actualValue;
} catch (ConfigRetrieverException e) {
throw new ConfigEvaluatorException("problem looking up configurations with factoryPid " + factoryPid);
}
} else if (isWildcardService(attributeDef)) {
String service = attributeDef.getService();
WildcardService ref = new WildcardService(service, attributeDef, context.getConfigElement().getConfigID());
context.addUnresolvedReference(ref);
try {
ArrayList<String> pids = new ArrayList<String>();
List<RegistryEntry> entries = metatypeRegistry.getEntriesExposingService(service);
if (entries != null) {
for (RegistryEntry entry : entries) {
ExtendedConfiguration[] configs = configRetriever.findAllConfigurationsByPid(entry.getPid());
configs = configs == null ? new ExtendedConfiguration[0] : configs;
for (ExtendedConfiguration extConfig : configs) {
pids.add(extConfig.getPid());
}
}
}
if (attributeDef.getCardinality() > 0) {
actualValue = pids.toArray(new String[0]);
} else {
actualValue = pids;
}
if (actualValue != null) {
context.setProperty(prefixedAttributeName, actualValue);
}
evaluateFinish(context);
return actualValue;
} catch (ConfigRetrieverException e) {
throw new ConfigEvaluatorException("problem looking up configurations with service " + service);
}
}
if (rawValue == null) {
rawValue = getUnconfiguredAttributeValue(context, attributeDef);
}
// Process any list variables of the form ${list(variableName)}. We do this here separately from the other variable expression
// processing so that the values are available prior to cardinality checks.
if (rawValue != null) {
rawValue = variableEvaluator.processVariableLists(rawValue, attributeDef, context, ignoreWarnings);
}
if (rawValue != null) {
try {
actualValue = evaluateMetaType(rawValue, attributeDef, context, ignoreWarnings);
} catch (ConfigEvaluatorException iae) {
// try to fall-back to default value if validation of an option fails.
String validOptions[] = attributeDef.getOptionValues();
if (validOptions == null) {
// Fall back to variable registry or default value
Object badValue = rawValue;
rawValue = getUnconfiguredAttributeValue(context, attributeDef);
if (rawValue != null && !ignoreWarnings) {
Tr.warning(tc, "warn.config.validate.failed", iae.getMessage());
Tr.warning(tc, "warn.config.invalid.using.default.value", attributeDef.getID(), badValue, rawValue);
actualValue = evaluateMetaType(rawValue, attributeDef, context, ignoreWarnings);
} else {
throw iae;
}
} else {
if (tc.isWarningEnabled() && !ignoreWarnings) {
StringBuffer strBuffer = new StringBuffer();
// This formatter is consistent with the message in nlsprops
for (int i = 0; i < validOptions.length; i++) {
strBuffer.append("[");
strBuffer.append(validOptions[i]);
strBuffer.append("]");
}
Tr.warning(tc, "warn.config.invalid.value", attributeDef.getID(), rawValue, strBuffer.toString());
}
// Fall back to variable registry or default value
rawValue = getUnconfiguredAttributeValue(context, attributeDef);
if (rawValue != null) {
actualValue = evaluateMetaType(rawValue, attributeDef, context, ignoreWarnings);
}
}
}
if (actualValue != null) {
context.setProperty(prefixedAttributeName, actualValue);
}
evaluateFinish(context);
}
return actualValue;
} } |
public class class_name {
public java.util.List<RdsDbInstance> getRdsDbInstances() {
if (rdsDbInstances == null) {
rdsDbInstances = new com.amazonaws.internal.SdkInternalList<RdsDbInstance>();
}
return rdsDbInstances;
} } | public class class_name {
public java.util.List<RdsDbInstance> getRdsDbInstances() {
if (rdsDbInstances == null) {
rdsDbInstances = new com.amazonaws.internal.SdkInternalList<RdsDbInstance>(); // depends on control dependency: [if], data = [none]
}
return rdsDbInstances;
} } |
public class class_name {
public static String stripHost(final String uri)
{
if (!uri.startsWith("http"))
{
// It's likely a URI path, not the full URI (i.e. the host is
// already stripped).
return uri;
}
final String noHttpUri = StringUtils.substringAfter(uri, "://");
final int slashIndex = noHttpUri.indexOf("/");
if (slashIndex == -1)
{
return "/";
}
final String noHostUri = noHttpUri.substring(slashIndex);
return noHostUri;
} } | public class class_name {
public static String stripHost(final String uri)
{
if (!uri.startsWith("http"))
{
// It's likely a URI path, not the full URI (i.e. the host is
// already stripped).
return uri; // depends on control dependency: [if], data = [none]
}
final String noHttpUri = StringUtils.substringAfter(uri, "://");
final int slashIndex = noHttpUri.indexOf("/");
if (slashIndex == -1)
{
return "/"; // depends on control dependency: [if], data = [none]
}
final String noHostUri = noHttpUri.substring(slashIndex);
return noHostUri;
} } |
public class class_name {
public static void main(final String[] args)
throws IOException
{
System.out.println(Version.about());
System.out.println("ISO 6709 geographic point location tester. ");
System.out.println("For example, enter: +401213-0750015/");
System.out.println("Enter a blank line to quit.");
System.out.println("Starting. " + new Date());
final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String inputLine = "starter";
while (inputLine != null && inputLine.trim().length() > 0)
{
try
{
System.out.print("Enter an ISO 6709 geographic point location: ");
inputLine = in.readLine();
// Parse and print location point
final PointLocation pointLocation = PointLocationParser
.parsePointLocation(inputLine);
System.out.println(pointLocation);
System.out.println(PointLocationFormatter
.formatPointLocation(pointLocation, PointLocationFormatType.LONG));
}
catch (final ParserException e)
{
System.out.println(e.getMessage());
}
catch (final FormatterException e)
{
System.err.println(e.getMessage());
}
}
System.out.println("Done. " + new Date());
} } | public class class_name {
public static void main(final String[] args)
throws IOException
{
System.out.println(Version.about());
System.out.println("ISO 6709 geographic point location tester. ");
System.out.println("For example, enter: +401213-0750015/");
System.out.println("Enter a blank line to quit.");
System.out.println("Starting. " + new Date());
final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String inputLine = "starter";
while (inputLine != null && inputLine.trim().length() > 0)
{
try
{
System.out.print("Enter an ISO 6709 geographic point location: "); // depends on control dependency: [try], data = [none]
inputLine = in.readLine(); // depends on control dependency: [try], data = [none]
// Parse and print location point
final PointLocation pointLocation = PointLocationParser
.parsePointLocation(inputLine);
System.out.println(pointLocation); // depends on control dependency: [try], data = [none]
System.out.println(PointLocationFormatter
.formatPointLocation(pointLocation, PointLocationFormatType.LONG)); // depends on control dependency: [try], data = [none]
}
catch (final ParserException e)
{
System.out.println(e.getMessage());
} // depends on control dependency: [catch], data = [none]
catch (final FormatterException e)
{
System.err.println(e.getMessage());
} // depends on control dependency: [catch], data = [none]
}
System.out.println("Done. " + new Date());
} } |
public class class_name {
PdfCatalog getCatalog(PdfIndirectReference pages) {
PdfCatalog catalog = new PdfCatalog(pages, writer);
// [C1] outlines
if (rootOutline.getKids().size() > 0) {
catalog.put(PdfName.PAGEMODE, PdfName.USEOUTLINES);
catalog.put(PdfName.OUTLINES, rootOutline.indirectReference());
}
// [C2] version
writer.getPdfVersion().addToCatalog(catalog);
// [C3] preferences
viewerPreferences.addToCatalog(catalog);
// [C4] pagelabels
if (pageLabels != null) {
catalog.put(PdfName.PAGELABELS, pageLabels.getDictionary(writer));
}
// [C5] named objects
catalog.addNames(localDestinations, getDocumentLevelJS(), documentFileAttachment, writer);
// [C6] actions
if (openActionName != null) {
PdfAction action = getLocalGotoAction(openActionName);
catalog.setOpenAction(action);
}
else if (openActionAction != null)
catalog.setOpenAction(openActionAction);
if (additionalActions != null) {
catalog.setAdditionalActions(additionalActions);
}
// [C7] portable collections
if (collection != null) {
catalog.put(PdfName.COLLECTION, collection);
}
// [C8] AcroForm
if (annotationsImp.hasValidAcroForm()) {
try {
catalog.put(PdfName.ACROFORM, writer.addToBody(annotationsImp.getAcroForm()).getIndirectReference());
}
catch (IOException e) {
throw new ExceptionConverter(e);
}
}
return catalog;
} } | public class class_name {
PdfCatalog getCatalog(PdfIndirectReference pages) {
PdfCatalog catalog = new PdfCatalog(pages, writer);
// [C1] outlines
if (rootOutline.getKids().size() > 0) {
catalog.put(PdfName.PAGEMODE, PdfName.USEOUTLINES); // depends on control dependency: [if], data = [none]
catalog.put(PdfName.OUTLINES, rootOutline.indirectReference()); // depends on control dependency: [if], data = [none]
}
// [C2] version
writer.getPdfVersion().addToCatalog(catalog);
// [C3] preferences
viewerPreferences.addToCatalog(catalog);
// [C4] pagelabels
if (pageLabels != null) {
catalog.put(PdfName.PAGELABELS, pageLabels.getDictionary(writer)); // depends on control dependency: [if], data = [none]
}
// [C5] named objects
catalog.addNames(localDestinations, getDocumentLevelJS(), documentFileAttachment, writer);
// [C6] actions
if (openActionName != null) {
PdfAction action = getLocalGotoAction(openActionName);
catalog.setOpenAction(action); // depends on control dependency: [if], data = [none]
}
else if (openActionAction != null)
catalog.setOpenAction(openActionAction);
if (additionalActions != null) {
catalog.setAdditionalActions(additionalActions); // depends on control dependency: [if], data = [(additionalActions]
}
// [C7] portable collections
if (collection != null) {
catalog.put(PdfName.COLLECTION, collection); // depends on control dependency: [if], data = [none]
}
// [C8] AcroForm
if (annotationsImp.hasValidAcroForm()) {
try {
catalog.put(PdfName.ACROFORM, writer.addToBody(annotationsImp.getAcroForm()).getIndirectReference()); // depends on control dependency: [try], data = [none]
}
catch (IOException e) {
throw new ExceptionConverter(e);
} // depends on control dependency: [catch], data = [none]
}
return catalog;
} } |
public class class_name {
@Override
public List<Tuple> getTuples(EntityKey[] keys, TupleContext tupleContext) {
Objects.requireNonNull( keys );
if ( keys.length == 0 ) {
return Collections.emptyList();
}
else if ( keys.length == 1 ) {
return Collections.singletonList( getTuple( keys[0], tupleContext ) );
}
else {
final String cacheName = cacheName( keys[0] );
final ProtoStreamMappingAdapter mapper = provider.getDataMapperForCache( cacheName );
final Map<EntityKey,ProtostreamId> keyConversionMatch = new HashMap<>();
final Set<ProtostreamId> convertedKeys = new HashSet<>();
for ( EntityKey ek : keys ) {
if ( ek == null ) {
continue;
}
assert cacheName( ek ).equals( cacheName ) : "The javadoc comment promised batches would be loaded from the same table";
ProtostreamId idBuffer = mapper.createIdPayload( ek.getColumnNames(), ek.getColumnValues() );
keyConversionMatch.put( ek, idBuffer );
convertedKeys.add( idBuffer );
}
final Map<ProtostreamId, ProtostreamPayload> loadedBulk = mapper.withinCacheEncodingContext( c -> {
//TODO getAll doesn't support versioned entries ?!
return c.getAll( convertedKeys );
} );
final List<Tuple> results = new ArrayList<>( keys.length );
for ( int i = 0; i < keys.length; i++ ) {
EntityKey originalKey = keys[i];
if ( originalKey == null ) {
results.add( null );
continue;
}
ProtostreamId protostreamId = keyConversionMatch.get( originalKey );
ProtostreamPayload payload = loadedBulk.get( protostreamId );
if ( payload == null ) {
results.add( null );
continue;
}
results.add( payload.toTuple( SnapshotType.UNKNOWN ) );
}
return results;
}
} } | public class class_name {
@Override
public List<Tuple> getTuples(EntityKey[] keys, TupleContext tupleContext) {
Objects.requireNonNull( keys );
if ( keys.length == 0 ) {
return Collections.emptyList(); // depends on control dependency: [if], data = [none]
}
else if ( keys.length == 1 ) {
return Collections.singletonList( getTuple( keys[0], tupleContext ) ); // depends on control dependency: [if], data = [none]
}
else {
final String cacheName = cacheName( keys[0] );
final ProtoStreamMappingAdapter mapper = provider.getDataMapperForCache( cacheName );
final Map<EntityKey,ProtostreamId> keyConversionMatch = new HashMap<>();
final Set<ProtostreamId> convertedKeys = new HashSet<>();
for ( EntityKey ek : keys ) {
if ( ek == null ) {
continue;
}
assert cacheName( ek ).equals( cacheName ) : "The javadoc comment promised batches would be loaded from the same table";
ProtostreamId idBuffer = mapper.createIdPayload( ek.getColumnNames(), ek.getColumnValues() );
keyConversionMatch.put( ek, idBuffer ); // depends on control dependency: [for], data = [ek]
convertedKeys.add( idBuffer ); // depends on control dependency: [for], data = [none]
}
final Map<ProtostreamId, ProtostreamPayload> loadedBulk = mapper.withinCacheEncodingContext( c -> {
//TODO getAll doesn't support versioned entries ?!
return c.getAll( convertedKeys );
} );
final List<Tuple> results = new ArrayList<>( keys.length );
for ( int i = 0; i < keys.length; i++ ) {
EntityKey originalKey = keys[i];
if ( originalKey == null ) {
results.add( null ); // depends on control dependency: [if], data = [null )]
continue;
}
ProtostreamId protostreamId = keyConversionMatch.get( originalKey );
ProtostreamPayload payload = loadedBulk.get( protostreamId );
if ( payload == null ) {
results.add( null ); // depends on control dependency: [if], data = [null )]
continue;
}
results.add( payload.toTuple( SnapshotType.UNKNOWN ) ); // depends on control dependency: [for], data = [none]
}
return results;
}
} } |
public class class_name {
private void invokeMigrationOperation(ReplicaFragmentMigrationState migrationState, boolean firstFragment) {
boolean lastFragment = !fragmentedMigrationEnabled || !namespacesContext.hasNext();
Operation operation = new MigrationOperation(migrationInfo,
firstFragment ? completedMigrations : Collections.emptyList(),
partitionStateVersion, migrationState, firstFragment, lastFragment);
ILogger logger = getLogger();
if (logger.isFinestEnabled()) {
Set<ServiceNamespace> namespaces = migrationState != null
? migrationState.getNamespaceVersionMap().keySet() : Collections.emptySet();
logger.finest("Invoking MigrationOperation for namespaces " + namespaces + " and " + migrationInfo
+ ", lastFragment: " + lastFragment);
}
NodeEngine nodeEngine = getNodeEngine();
InternalPartitionServiceImpl partitionService = getService();
Address target = migrationInfo.getDestinationAddress();
nodeEngine.getOperationService()
.createInvocationBuilder(InternalPartitionService.SERVICE_NAME, operation, target)
.setExecutionCallback(new MigrationCallback())
.setResultDeserialized(true)
.setCallTimeout(partitionService.getPartitionMigrationTimeout())
.setTryCount(InternalPartitionService.MIGRATION_RETRY_COUNT)
.setTryPauseMillis(InternalPartitionService.MIGRATION_RETRY_PAUSE)
.invoke();
} } | public class class_name {
private void invokeMigrationOperation(ReplicaFragmentMigrationState migrationState, boolean firstFragment) {
boolean lastFragment = !fragmentedMigrationEnabled || !namespacesContext.hasNext();
Operation operation = new MigrationOperation(migrationInfo,
firstFragment ? completedMigrations : Collections.emptyList(),
partitionStateVersion, migrationState, firstFragment, lastFragment);
ILogger logger = getLogger();
if (logger.isFinestEnabled()) {
Set<ServiceNamespace> namespaces = migrationState != null
? migrationState.getNamespaceVersionMap().keySet() : Collections.emptySet();
logger.finest("Invoking MigrationOperation for namespaces " + namespaces + " and " + migrationInfo
+ ", lastFragment: " + lastFragment); // depends on control dependency: [if], data = [none]
}
NodeEngine nodeEngine = getNodeEngine();
InternalPartitionServiceImpl partitionService = getService();
Address target = migrationInfo.getDestinationAddress();
nodeEngine.getOperationService()
.createInvocationBuilder(InternalPartitionService.SERVICE_NAME, operation, target)
.setExecutionCallback(new MigrationCallback())
.setResultDeserialized(true)
.setCallTimeout(partitionService.getPartitionMigrationTimeout())
.setTryCount(InternalPartitionService.MIGRATION_RETRY_COUNT)
.setTryPauseMillis(InternalPartitionService.MIGRATION_RETRY_PAUSE)
.invoke();
} } |
public class class_name {
public String readUntil(final char... end)
{
final StringBuilder sb = new StringBuilder();
int pos = this.pos;
while (pos < this.value.length())
{
final char ch = this.value.charAt(pos);
if (ch == '\\' && pos + 1 < this.value.length())
{
final char c;
switch (c = this.value.charAt(pos + 1))
{
case '\\':
case '[':
case ']':
case '(':
case ')':
case '{':
case '}':
case '#':
case '"':
case '\'':
case '.':
case '>':
case '*':
case '+':
case '-':
case '_':
case '!':
case '`':
case '~':
sb.append(c);
pos++;
break;
default:
sb.append(ch);
break;
}
}
else
{
boolean endReached = false;
for (int n = 0; n < end.length; n++)
{
if (ch == end[n])
{
endReached = true;
break;
}
}
if (endReached)
{
break;
}
sb.append(ch);
}
pos++;
}
final char ch = pos < this.value.length() ? this.value.charAt(pos) : '\n';
for (int n = 0; n < end.length; n++)
{
if (ch == end[n])
{
this.pos = pos;
return sb.toString();
}
}
return null;
} } | public class class_name {
public String readUntil(final char... end)
{
final StringBuilder sb = new StringBuilder();
int pos = this.pos;
while (pos < this.value.length())
{
final char ch = this.value.charAt(pos);
if (ch == '\\' && pos + 1 < this.value.length())
{
final char c;
switch (c = this.value.charAt(pos + 1))
{
case '\\':
case '[':
case ']':
case '(':
case ')':
case '{':
case '}':
case '#':
case '"':
case '\'':
case '.':
case '>':
case '*':
case '+':
case '-':
case '_':
case '!':
case '`':
case '~':
sb.append(c);
pos++; // depends on control dependency: [if], data = [none]
break;
default:
sb.append(ch);
break;
}
}
else
{
boolean endReached = false;
for (int n = 0; n < end.length; n++)
{
if (ch == end[n])
{
endReached = true; // depends on control dependency: [if], data = [none]
break;
}
}
if (endReached)
{
break;
}
sb.append(ch);
}
pos++;
}
final char ch = pos < this.value.length() ? this.value.charAt(pos) : '\n';
for (int n = 0; n < end.length; n++)
{
if (ch == end[n])
{
this.pos = pos;
return sb.toString();
}
}
return null;
} } |
public class class_name {
private static String underscoreName(String name) {
StringBuilder result = new StringBuilder();
if (name != null && name.length() > 0) {
result.append(name.substring(0, 1).toLowerCase());
for (int i = 1; i < name.length(); i++) {
String s = name.substring(i, i + 1);
if (s.equals(s.toUpperCase())) {
result.append("_");
result.append(s.toLowerCase());
} else {
result.append(s);
}
}
}
return result.toString();
} } | public class class_name {
private static String underscoreName(String name) {
StringBuilder result = new StringBuilder();
if (name != null && name.length() > 0) {
result.append(name.substring(0, 1).toLowerCase()); // depends on control dependency: [if], data = [(name]
for (int i = 1; i < name.length(); i++) {
String s = name.substring(i, i + 1);
if (s.equals(s.toUpperCase())) {
result.append("_"); // depends on control dependency: [if], data = [none]
result.append(s.toLowerCase()); // depends on control dependency: [if], data = [none]
} else {
result.append(s); // depends on control dependency: [if], data = [none]
}
}
}
return result.toString();
} } |
public class class_name {
public Optional<ProjectHook> getOptionalHook(Object projectIdOrPath, Integer hookId) {
try {
return (Optional.ofNullable(getHook(projectIdOrPath, hookId)));
} catch (GitLabApiException glae) {
return (GitLabApi.createOptionalFromException(glae));
}
} } | public class class_name {
public Optional<ProjectHook> getOptionalHook(Object projectIdOrPath, Integer hookId) {
try {
return (Optional.ofNullable(getHook(projectIdOrPath, hookId))); // depends on control dependency: [try], data = [none]
} catch (GitLabApiException glae) {
return (GitLabApi.createOptionalFromException(glae));
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public void free(long idleStartTime)
{
if (_is == null) {
IllegalStateException exn = new IllegalStateException(L.l("{0} unexpected free of closed stream", this));
exn.fillInStackTrace();
log.log(Level.FINE, exn.toString(), exn);
return;
}
long requestStartTime = _requestStartTime;
_requestStartTime = 0;
if (requestStartTime > 0)
_requestTimeProbe.end(requestStartTime);
// #2369 - the load balancer might set its own view of the free
// time
if (idleStartTime <= 0) {
idleStartTime = _is.getReadTime();
if (idleStartTime <= 0) {
// for write-only, the read time is zero
idleStartTime = CurrentTime.currentTime();
}
}
_idleStartTime = idleStartTime;
_idleProbe.start();
_isIdle = true;
_pool.free(this);
} } | public class class_name {
@Override
public void free(long idleStartTime)
{
if (_is == null) {
IllegalStateException exn = new IllegalStateException(L.l("{0} unexpected free of closed stream", this));
exn.fillInStackTrace(); // depends on control dependency: [if], data = [none]
log.log(Level.FINE, exn.toString(), exn); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
long requestStartTime = _requestStartTime;
_requestStartTime = 0;
if (requestStartTime > 0)
_requestTimeProbe.end(requestStartTime);
// #2369 - the load balancer might set its own view of the free
// time
if (idleStartTime <= 0) {
idleStartTime = _is.getReadTime(); // depends on control dependency: [if], data = [none]
if (idleStartTime <= 0) {
// for write-only, the read time is zero
idleStartTime = CurrentTime.currentTime(); // depends on control dependency: [if], data = [none]
}
}
_idleStartTime = idleStartTime;
_idleProbe.start();
_isIdle = true;
_pool.free(this);
} } |
public class class_name {
public void printJobExecutionStatistics() {
/*
* Print Job Counters
*/
System.out.println("JOB COUNTERS *********************************************");
int size = this._job.size();
java.util.Iterator<Map.Entry<Enum, String>> kv = this._job.entrySet().iterator();
for (int i = 0; i < size; i++)
{
Map.Entry<Enum, String> entry = (Map.Entry<Enum, String>) kv.next();
Enum key = entry.getKey();
String value = entry.getValue();
System.out.println("Key:<" + key.name() + ">, value:<"+ value +">");
}
/*
*
*/
System.out.println("MAP COUNTERS *********************************************");
int size1 = this._mapTaskList.size();
for (int i = 0; i < size1; i++)
{
System.out.println("MAP TASK *********************************************");
this._mapTaskList.get(i).printKeys();
}
/*
*
*/
System.out.println("REDUCE COUNTERS *********************************************");
int size2 = this._mapTaskList.size();
for (int i = 0; i < size2; i++)
{
System.out.println("REDUCE TASK *********************************************");
this._reduceTaskList.get(i).printKeys();
}
} } | public class class_name {
public void printJobExecutionStatistics() {
/*
* Print Job Counters
*/
System.out.println("JOB COUNTERS *********************************************");
int size = this._job.size();
java.util.Iterator<Map.Entry<Enum, String>> kv = this._job.entrySet().iterator();
for (int i = 0; i < size; i++)
{
Map.Entry<Enum, String> entry = (Map.Entry<Enum, String>) kv.next();
Enum key = entry.getKey();
String value = entry.getValue();
System.out.println("Key:<" + key.name() + ">, value:<"+ value +">");
}
/*
*
*/
System.out.println("MAP COUNTERS *********************************************");
int size1 = this._mapTaskList.size();
for (int i = 0; i < size1; i++)
{
System.out.println("MAP TASK *********************************************"); // depends on control dependency: [for], data = [none]
this._mapTaskList.get(i).printKeys(); // depends on control dependency: [for], data = [i]
}
/*
*
*/
System.out.println("REDUCE COUNTERS *********************************************");
int size2 = this._mapTaskList.size();
for (int i = 0; i < size2; i++)
{
System.out.println("REDUCE TASK *********************************************"); // depends on control dependency: [for], data = [none]
this._reduceTaskList.get(i).printKeys(); // depends on control dependency: [for], data = [i]
}
} } |
public class class_name {
private void downloadMissingDependencies(String projectFolder) {
logger.debug("running pre-steps on folder {}", projectFolder);
String tempFolder = new FilesUtils().createTmpFolder(false, TempFolders.UNIQUE_GRADLE_TEMP_FOLDER);
File buildGradleTempDirectory = new File(tempFolder);
if (copyProjectFolder(projectFolder, buildGradleTempDirectory)) {
try {
Stream<Path> pathStream = Files.walk(Paths.get(buildGradleTempDirectory.getPath()), Integer.MAX_VALUE).filter(file -> file.getFileName().toString().equals(Constants.BUILD_GRADLE));
pathStream.forEach(path -> {
File buildGradleTmp = new File(path.toString());
if (buildGradleTmp.exists()) {
if (appendTaskToBomFile(buildGradleTmp)) {
runPreStepCommand(buildGradleTmp);
removeTaskFromBomFile(buildGradleTmp);
}
} else {
logger.warn("Could not find the path {}", buildGradleTmp.getPath());
}
});
} catch (IOException e) {
logger.warn("Couldn't list all 'build.gradle' files, error: {}", e.getMessage());
logger.debug("Error: {}", e.getStackTrace());
} finally {
new TempFolders().deleteTempFoldersHelper(Paths.get(System.getProperty("java.io.tmpdir"), TempFolders.UNIQUE_GRADLE_TEMP_FOLDER).toString());
}
}
} } | public class class_name {
private void downloadMissingDependencies(String projectFolder) {
logger.debug("running pre-steps on folder {}", projectFolder);
String tempFolder = new FilesUtils().createTmpFolder(false, TempFolders.UNIQUE_GRADLE_TEMP_FOLDER);
File buildGradleTempDirectory = new File(tempFolder);
if (copyProjectFolder(projectFolder, buildGradleTempDirectory)) {
try {
Stream<Path> pathStream = Files.walk(Paths.get(buildGradleTempDirectory.getPath()), Integer.MAX_VALUE).filter(file -> file.getFileName().toString().equals(Constants.BUILD_GRADLE));
pathStream.forEach(path -> {
File buildGradleTmp = new File(path.toString()); // depends on control dependency: [try], data = [none]
if (buildGradleTmp.exists()) {
if (appendTaskToBomFile(buildGradleTmp)) {
runPreStepCommand(buildGradleTmp); // depends on control dependency: [if], data = [none]
removeTaskFromBomFile(buildGradleTmp); // depends on control dependency: [if], data = [none]
}
} else {
logger.warn("Could not find the path {}", buildGradleTmp.getPath()); // depends on control dependency: [if], data = [none]
}
});
} catch (IOException e) {
logger.warn("Couldn't list all 'build.gradle' files, error: {}", e.getMessage());
logger.debug("Error: {}", e.getStackTrace());
} finally { // depends on control dependency: [catch], data = [none]
new TempFolders().deleteTempFoldersHelper(Paths.get(System.getProperty("java.io.tmpdir"), TempFolders.UNIQUE_GRADLE_TEMP_FOLDER).toString());
}
}
} } |
public class class_name {
TypeSerializer<?> getSubclassSerializer(Class<?> subclass) {
TypeSerializer<?> result = subclassSerializerCache.get(subclass);
if (result == null) {
result = createSubclassSerializer(subclass);
subclassSerializerCache.put(subclass, result);
}
return result;
} } | public class class_name {
TypeSerializer<?> getSubclassSerializer(Class<?> subclass) {
TypeSerializer<?> result = subclassSerializerCache.get(subclass);
if (result == null) {
result = createSubclassSerializer(subclass); // depends on control dependency: [if], data = [none]
subclassSerializerCache.put(subclass, result); // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
@Override
public int get(int index)
{
if (index < 0) {
throw new IndexOutOfBoundsException();
}
int count = 0;
final int[] localWords = words; // faster
for (int j = 0; j < firstEmptyWord; j++) {
int w = localWords[j];
int current = Integer.bitCount(w);
if (index < count + current) {
int bit = -1;
for (int skip = index - count; skip >= 0; skip--) {
bit = Integer.numberOfTrailingZeros(w & (ALL_ONES_WORD << (bit + 1)));
}
return multiplyByWordSize(j) + bit;
}
count += current;
}
throw new NoSuchElementException();
} } | public class class_name {
@Override
public int get(int index)
{
if (index < 0) {
throw new IndexOutOfBoundsException();
}
int count = 0;
final int[] localWords = words; // faster
for (int j = 0; j < firstEmptyWord; j++) {
int w = localWords[j];
int current = Integer.bitCount(w);
if (index < count + current) {
int bit = -1;
for (int skip = index - count; skip >= 0; skip--) {
bit = Integer.numberOfTrailingZeros(w & (ALL_ONES_WORD << (bit + 1)));
// depends on control dependency: [for], data = [none]
}
return multiplyByWordSize(j) + bit;
// depends on control dependency: [if], data = [none]
}
count += current;
// depends on control dependency: [for], data = [none]
}
throw new NoSuchElementException();
} } |
public class class_name {
public void writeUtf8(CharSequence string) {
for (int i = 0, len = string.length(); i < len; i++) {
char ch = string.charAt(i);
if (ch < 0x80) { // 7-bit ASCII character
writeByte(ch);
// This could be an ASCII run, or possibly entirely ASCII
while (i < len - 1) {
ch = string.charAt(i + 1);
if (ch >= 0x80) break;
i++;
writeByte(ch); // another 7-bit ASCII character
}
} else if (ch < 0x800) { // 11-bit character
writeByte(0xc0 | (ch >> 6));
writeByte(0x80 | (ch & 0x3f));
} else if (ch < 0xd800 || ch > 0xdfff) { // 16-bit character
writeByte(0xe0 | (ch >> 12));
writeByte(0x80 | ((ch >> 6) & 0x3f));
writeByte(0x80 | (ch & 0x3f));
} else { // Possibly a 21-bit character
if (!Character.isHighSurrogate(ch)) { // Malformed or not UTF-8
writeByte('?');
continue;
}
if (i == len - 1) { // Truncated or not UTF-8
writeByte('?');
break;
}
char low = string.charAt(++i);
if (!Character.isLowSurrogate(low)) { // Malformed or not UTF-8
writeByte('?');
writeByte(Character.isHighSurrogate(low) ? '?' : low);
continue;
}
// Write the 21-bit character using 4 bytes
// See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G2630
int codePoint = Character.toCodePoint(ch, low);
writeByte(0xf0 | (codePoint >> 18));
writeByte(0x80 | ((codePoint >> 12) & 0x3f));
writeByte(0x80 | ((codePoint >> 6) & 0x3f));
writeByte(0x80 | (codePoint & 0x3f));
}
}
} } | public class class_name {
public void writeUtf8(CharSequence string) {
for (int i = 0, len = string.length(); i < len; i++) {
char ch = string.charAt(i);
if (ch < 0x80) { // 7-bit ASCII character
writeByte(ch); // depends on control dependency: [if], data = [(ch]
// This could be an ASCII run, or possibly entirely ASCII
while (i < len - 1) {
ch = string.charAt(i + 1); // depends on control dependency: [while], data = [(i]
if (ch >= 0x80) break;
i++; // depends on control dependency: [while], data = [none]
writeByte(ch); // another 7-bit ASCII character // depends on control dependency: [while], data = [none]
}
} else if (ch < 0x800) { // 11-bit character
writeByte(0xc0 | (ch >> 6)); // depends on control dependency: [if], data = [(ch]
writeByte(0x80 | (ch & 0x3f)); // depends on control dependency: [if], data = [(ch]
} else if (ch < 0xd800 || ch > 0xdfff) { // 16-bit character
writeByte(0xe0 | (ch >> 12)); // depends on control dependency: [if], data = [none]
writeByte(0x80 | ((ch >> 6) & 0x3f)); // depends on control dependency: [if], data = [none]
writeByte(0x80 | (ch & 0x3f)); // depends on control dependency: [if], data = [none]
} else { // Possibly a 21-bit character
if (!Character.isHighSurrogate(ch)) { // Malformed or not UTF-8
writeByte('?'); // depends on control dependency: [if], data = [none]
continue;
}
if (i == len - 1) { // Truncated or not UTF-8
writeByte('?'); // depends on control dependency: [if], data = [none]
break;
}
char low = string.charAt(++i);
if (!Character.isLowSurrogate(low)) { // Malformed or not UTF-8
writeByte('?'); // depends on control dependency: [if], data = [none]
writeByte(Character.isHighSurrogate(low) ? '?' : low); // depends on control dependency: [if], data = [none]
continue;
}
// Write the 21-bit character using 4 bytes
// See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G2630
int codePoint = Character.toCodePoint(ch, low);
writeByte(0xf0 | (codePoint >> 18)); // depends on control dependency: [if], data = [none]
writeByte(0x80 | ((codePoint >> 12) & 0x3f)); // depends on control dependency: [if], data = [none]
writeByte(0x80 | ((codePoint >> 6) & 0x3f)); // depends on control dependency: [if], data = [none]
writeByte(0x80 | (codePoint & 0x3f)); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private boolean isEmptyAttribute(Attribute a) {
try {
return (a == null || a.size() == 0 || a.get() == null);
}
catch (NamingException e) {
return true;
}
} } | public class class_name {
private boolean isEmptyAttribute(Attribute a) {
try {
return (a == null || a.size() == 0 || a.get() == null); // depends on control dependency: [try], data = [none]
}
catch (NamingException e) {
return true;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected String normalizeRfsPrefix(String rfsPrefix) {
String result = insertContextStrings(rfsPrefix);
if (!isValidURL(result)) {
result = CmsFileUtil.normalizePath(result, '/');
}
if (CmsResource.isFolder(result)) {
// ensure prefix does NOT end with a folder '/'
result = result.substring(0, result.length() - 1);
}
return result;
} } | public class class_name {
protected String normalizeRfsPrefix(String rfsPrefix) {
String result = insertContextStrings(rfsPrefix);
if (!isValidURL(result)) {
result = CmsFileUtil.normalizePath(result, '/'); // depends on control dependency: [if], data = [none]
}
if (CmsResource.isFolder(result)) {
// ensure prefix does NOT end with a folder '/'
result = result.substring(0, result.length() - 1); // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
private Expression parseAtomList() {
Expression exp = parseAtom();
if (!tokenizer.current().isSymbol(",")) {
return exp;
}
ValueList atomList = new ValueList(true);
atomList.add(exp);
while (tokenizer.current().isSymbol(",")) {
tokenizer.consume();
atomList.add(parseAtom());
}
return atomList;
} } | public class class_name {
private Expression parseAtomList() {
Expression exp = parseAtom();
if (!tokenizer.current().isSymbol(",")) {
return exp; // depends on control dependency: [if], data = [none]
}
ValueList atomList = new ValueList(true);
atomList.add(exp);
while (tokenizer.current().isSymbol(",")) {
tokenizer.consume(); // depends on control dependency: [while], data = [none]
atomList.add(parseAtom()); // depends on control dependency: [while], data = [none]
}
return atomList;
} } |
public class class_name {
public void marshall(AssociateDomainRequest associateDomainRequest, ProtocolMarshaller protocolMarshaller) {
if (associateDomainRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(associateDomainRequest.getFleetArn(), FLEETARN_BINDING);
protocolMarshaller.marshall(associateDomainRequest.getDomainName(), DOMAINNAME_BINDING);
protocolMarshaller.marshall(associateDomainRequest.getAcmCertificateArn(), ACMCERTIFICATEARN_BINDING);
protocolMarshaller.marshall(associateDomainRequest.getDisplayName(), DISPLAYNAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(AssociateDomainRequest associateDomainRequest, ProtocolMarshaller protocolMarshaller) {
if (associateDomainRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(associateDomainRequest.getFleetArn(), FLEETARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(associateDomainRequest.getDomainName(), DOMAINNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(associateDomainRequest.getAcmCertificateArn(), ACMCERTIFICATEARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(associateDomainRequest.getDisplayName(), DISPLAYNAME_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 int getTileCount() {
if (tileCount == null) {
long count = 0;
boolean degrees = projection.isUnit(Units.DEGREES);
ProjectionTransform transformToWebMercator = null;
if (!degrees) {
transformToWebMercator = projection.getTransformation(ProjectionConstants.EPSG_WEB_MERCATOR);
}
for (int zoom = minZoom; zoom <= maxZoom; zoom++) {
BoundingBox expandedBoundingBox = getBoundingBox(zoom);
// Get the tile grid that includes the entire bounding box
TileGrid tileGrid = null;
if (degrees) {
tileGrid = TileBoundingBoxUtils.getTileGridWGS84(expandedBoundingBox, zoom);
} else {
tileGrid = TileBoundingBoxUtils.getTileGrid(expandedBoundingBox.transform(transformToWebMercator), zoom);
}
count += tileGrid.count();
tileGrids.put(zoom, tileGrid);
tileBounds.put(zoom, expandedBoundingBox);
}
tileCount = (int) Math.min(count, Integer.MAX_VALUE);
}
return tileCount;
} } | public class class_name {
public int getTileCount() {
if (tileCount == null) {
long count = 0;
boolean degrees = projection.isUnit(Units.DEGREES);
ProjectionTransform transformToWebMercator = null;
if (!degrees) {
transformToWebMercator = projection.getTransformation(ProjectionConstants.EPSG_WEB_MERCATOR); // depends on control dependency: [if], data = [none]
}
for (int zoom = minZoom; zoom <= maxZoom; zoom++) {
BoundingBox expandedBoundingBox = getBoundingBox(zoom);
// Get the tile grid that includes the entire bounding box
TileGrid tileGrid = null;
if (degrees) {
tileGrid = TileBoundingBoxUtils.getTileGridWGS84(expandedBoundingBox, zoom); // depends on control dependency: [if], data = [none]
} else {
tileGrid = TileBoundingBoxUtils.getTileGrid(expandedBoundingBox.transform(transformToWebMercator), zoom); // depends on control dependency: [if], data = [none]
}
count += tileGrid.count(); // depends on control dependency: [for], data = [none]
tileGrids.put(zoom, tileGrid); // depends on control dependency: [for], data = [zoom]
tileBounds.put(zoom, expandedBoundingBox); // depends on control dependency: [for], data = [zoom]
}
tileCount = (int) Math.min(count, Integer.MAX_VALUE); // depends on control dependency: [if], data = [none]
}
return tileCount;
} } |
public class class_name {
public boolean containsAll(final IntHashSet other) {
final IntIterator iterator = other.iterator();
while (iterator.hasNext()) {
if (!contains(iterator.nextValue())) {
return false;
}
}
return true;
} } | public class class_name {
public boolean containsAll(final IntHashSet other) {
final IntIterator iterator = other.iterator();
while (iterator.hasNext()) {
if (!contains(iterator.nextValue())) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
public SqlQuery groupBy(final String what) {
if (Strings.isNotEmpty(what)) {
groups.add(what);
}
return this;
} } | public class class_name {
public SqlQuery groupBy(final String what) {
if (Strings.isNotEmpty(what)) {
groups.add(what); // depends on control dependency: [if], data = [none]
}
return this;
} } |
public class class_name {
public static ObjectName createJavaMailObjectName(String serverName, String mailSessionID, int resourceCounter) {
Hashtable<String, String> props = new Hashtable<String, String>();
props.put(TYPE_SERVER, serverName);
props.put(MAIL_SESSION_ID, mailSessionID);
props.put(RESOURCE_ID, TYPE_JAVA_MAIL_RESOURCE + "-" + resourceCounter);
ObjectName objectName;
try {
objectName = createObjectName(TYPE_JAVA_MAIL_RESOURCE, NAME_JAVA_MAIL_RESOURCE, props);
} catch (IllegalArgumentException e) {
// mailSessionID contains illegal characters
props.remove(MAIL_SESSION_ID);
objectName = createObjectName(TYPE_JAVA_MAIL_RESOURCE, NAME_JAVA_MAIL_RESOURCE, props);
}
return objectName;
} } | public class class_name {
public static ObjectName createJavaMailObjectName(String serverName, String mailSessionID, int resourceCounter) {
Hashtable<String, String> props = new Hashtable<String, String>();
props.put(TYPE_SERVER, serverName);
props.put(MAIL_SESSION_ID, mailSessionID);
props.put(RESOURCE_ID, TYPE_JAVA_MAIL_RESOURCE + "-" + resourceCounter);
ObjectName objectName;
try {
objectName = createObjectName(TYPE_JAVA_MAIL_RESOURCE, NAME_JAVA_MAIL_RESOURCE, props); // depends on control dependency: [try], data = [none]
} catch (IllegalArgumentException e) {
// mailSessionID contains illegal characters
props.remove(MAIL_SESSION_ID);
objectName = createObjectName(TYPE_JAVA_MAIL_RESOURCE, NAME_JAVA_MAIL_RESOURCE, props);
} // depends on control dependency: [catch], data = [none]
return objectName;
} } |
public class class_name {
private void recomputeLoadSums() {
loadsHaveChanged.set(false);
for (int d = 0; d < nbDims; d++) {
int sli = 0;
int sls = 0;
for (int b = 0; b < nbBins; b++) {
sli += loads[d][b].getLB();
sls += loads[d][b].getUB();
}
this.sumLoadInf[d].set(sli);
this.sumLoadSup[d].set(sls);
}
} } | public class class_name {
private void recomputeLoadSums() {
loadsHaveChanged.set(false);
for (int d = 0; d < nbDims; d++) {
int sli = 0;
int sls = 0;
for (int b = 0; b < nbBins; b++) {
sli += loads[d][b].getLB();
// depends on control dependency: [for], data = [b]
sls += loads[d][b].getUB();
// depends on control dependency: [for], data = [b]
}
this.sumLoadInf[d].set(sli);
// depends on control dependency: [for], data = [d]
this.sumLoadSup[d].set(sls);
// depends on control dependency: [for], data = [d]
}
} } |
public class class_name {
@Override
public Object find(Class clazz, Object key)
{
s = getStatelessSession();
Object result = null;
try
{
result = s.get(clazz, (Serializable) key);
}
catch (ClassCastException ccex)
{
log.error("Class can not be serializable, Caused by {}.", ccex);
throw new KunderaException(ccex);
}
catch (Exception e)
{
log.error("Error while finding, Caused by {}. ", e);
throw new KunderaException(e);
}
return result;
} } | public class class_name {
@Override
public Object find(Class clazz, Object key)
{
s = getStatelessSession();
Object result = null;
try
{
result = s.get(clazz, (Serializable) key); // depends on control dependency: [try], data = [none]
}
catch (ClassCastException ccex)
{
log.error("Class can not be serializable, Caused by {}.", ccex);
throw new KunderaException(ccex);
} // depends on control dependency: [catch], data = [none]
catch (Exception e)
{
log.error("Error while finding, Caused by {}. ", e);
throw new KunderaException(e);
} // depends on control dependency: [catch], data = [none]
return result;
} } |
public class class_name {
public static DefaultConnectionFactory newLdaptiveConnectionFactory(final AbstractLdapProperties l) {
LOGGER.debug("Creating LDAP connection factory for [{}]", l.getLdapUrl());
val cc = newLdaptiveConnectionConfig(l);
val bindCf = new DefaultConnectionFactory(cc);
if (l.getProviderClass() != null) {
try {
val clazz = ClassUtils.getClass(l.getProviderClass());
bindCf.setProvider(Provider.class.cast(clazz.getDeclaredConstructor().newInstance()));
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
return bindCf;
} } | public class class_name {
public static DefaultConnectionFactory newLdaptiveConnectionFactory(final AbstractLdapProperties l) {
LOGGER.debug("Creating LDAP connection factory for [{}]", l.getLdapUrl());
val cc = newLdaptiveConnectionConfig(l);
val bindCf = new DefaultConnectionFactory(cc);
if (l.getProviderClass() != null) {
try {
val clazz = ClassUtils.getClass(l.getProviderClass());
bindCf.setProvider(Provider.class.cast(clazz.getDeclaredConstructor().newInstance())); // depends on control dependency: [try], data = [none]
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
}
return bindCf;
} } |
public class class_name {
public static void throwArgMismatchException( IllegalArgumentException exceptionToWrap, String featureName, Class[] actualParameters, Object[] args )
{
String argTypes = "(";
for( int i = 0; i < actualParameters.length; i++ )
{
Class aClass = actualParameters[i];
if( i > 0 )
{
argTypes += " ,";
}
argTypes += aClass.getName();
}
argTypes += ")";
String rttTypes = "(";
for( int i = 0; i < args.length; i++ )
{
if( i > 0 )
{
rttTypes += " ,";
}
if( args[i] != null )
{
rttTypes += args[i].getClass().getName();
}
else
{
rttTypes += "null";
}
}
rttTypes += ")";
throw new RuntimeException( "Tried to pass values of types: " + rttTypes + " into " + featureName + " that takes types " + argTypes, exceptionToWrap );
} } | public class class_name {
public static void throwArgMismatchException( IllegalArgumentException exceptionToWrap, String featureName, Class[] actualParameters, Object[] args )
{
String argTypes = "(";
for( int i = 0; i < actualParameters.length; i++ )
{
Class aClass = actualParameters[i];
if( i > 0 )
{
argTypes += " ,"; // depends on control dependency: [if], data = [none]
}
argTypes += aClass.getName(); // depends on control dependency: [for], data = [none]
}
argTypes += ")";
String rttTypes = "(";
for( int i = 0; i < args.length; i++ )
{
if( i > 0 )
{
rttTypes += " ,"; // depends on control dependency: [if], data = [none]
}
if( args[i] != null )
{
rttTypes += args[i].getClass().getName(); // depends on control dependency: [if], data = [none]
}
else
{
rttTypes += "null"; // depends on control dependency: [if], data = [none]
}
}
rttTypes += ")";
throw new RuntimeException( "Tried to pass values of types: " + rttTypes + " into " + featureName + " that takes types " + argTypes, exceptionToWrap );
} } |
public class class_name {
protected void releaseObjects() {
Log.d(TAG, "releaseObjects");
if (this.mediaPlayer != null) {
this.mediaPlayer.setSurface(null);
this.mediaPlayer.reset();
}
this.videoIsReady = false;
this.surfaceIsReady = false;
this.initialMovieHeight = -1;
this.initialMovieWidth = -1;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
if (this.textureView != null) {
this.textureView.setSurfaceTextureListener(null);
removeView(this.textureView);
this.textureView = null;
}
} else {
if (this.surfaceHolder != null) {
this.surfaceHolder.removeCallback(this);
this.surfaceHolder = null;
}
if (this.surfaceView != null) {
removeView(this.surfaceView);
this.surfaceView = null;
}
}
if (this.onProgressView != null) {
removeView(this.onProgressView);
}
} } | public class class_name {
protected void releaseObjects() {
Log.d(TAG, "releaseObjects");
if (this.mediaPlayer != null) {
this.mediaPlayer.setSurface(null); // depends on control dependency: [if], data = [null)]
this.mediaPlayer.reset(); // depends on control dependency: [if], data = [none]
}
this.videoIsReady = false;
this.surfaceIsReady = false;
this.initialMovieHeight = -1;
this.initialMovieWidth = -1;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
if (this.textureView != null) {
this.textureView.setSurfaceTextureListener(null); // depends on control dependency: [if], data = [null)]
removeView(this.textureView); // depends on control dependency: [if], data = [(this.textureView]
this.textureView = null; // depends on control dependency: [if], data = [none]
}
} else {
if (this.surfaceHolder != null) {
this.surfaceHolder.removeCallback(this); // depends on control dependency: [if], data = [none]
this.surfaceHolder = null; // depends on control dependency: [if], data = [none]
}
if (this.surfaceView != null) {
removeView(this.surfaceView); // depends on control dependency: [if], data = [(this.surfaceView]
this.surfaceView = null; // depends on control dependency: [if], data = [none]
}
}
if (this.onProgressView != null) {
removeView(this.onProgressView); // depends on control dependency: [if], data = [(this.onProgressView]
}
} } |
public class class_name {
protected DialectFactory createDialectFactory() {
DialectFactoryImpl factory = new DialectFactoryImpl();
factory.injectServices(new ServiceRegistryImplementor() {
@Override
public <R extends Service> R getService(Class<R> serviceRole) {
if (serviceRole == DialectResolver.class) {
return (R) new StandardDialectResolver();
} else if (serviceRole == StrategySelector.class) {
return (R) new StrategySelectorImpl(new ClassLoaderServiceImpl(Thread.currentThread().getContextClassLoader()));
}
return null;
}
@Override
public <R extends Service> ServiceBinding<R> locateServiceBinding(Class<R> serviceRole) {
return null;
}
@Override
public void destroy() {
}
@Override
public void registerChild(ServiceRegistryImplementor child) {
}
@Override
public void deRegisterChild(ServiceRegistryImplementor child) {
}
@Override
public ServiceRegistry getParentServiceRegistry() {
return null;
}
});
return factory;
} } | public class class_name {
protected DialectFactory createDialectFactory() {
DialectFactoryImpl factory = new DialectFactoryImpl();
factory.injectServices(new ServiceRegistryImplementor() {
@Override
public <R extends Service> R getService(Class<R> serviceRole) {
if (serviceRole == DialectResolver.class) {
return (R) new StandardDialectResolver(); // depends on control dependency: [if], data = [none]
} else if (serviceRole == StrategySelector.class) {
return (R) new StrategySelectorImpl(new ClassLoaderServiceImpl(Thread.currentThread().getContextClassLoader())); // depends on control dependency: [if], data = [none]
}
return null;
}
@Override
public <R extends Service> ServiceBinding<R> locateServiceBinding(Class<R> serviceRole) {
return null;
}
@Override
public void destroy() {
}
@Override
public void registerChild(ServiceRegistryImplementor child) {
}
@Override
public void deRegisterChild(ServiceRegistryImplementor child) {
}
@Override
public ServiceRegistry getParentServiceRegistry() {
return null;
}
});
return factory;
} } |
public class class_name {
public static String formatEntityKey(EntityDataModel entityDataModel, Object entity) throws ODataEdmException {
Key entityKey = getAndCheckEntityType(entityDataModel, entity.getClass()).getKey();
List<PropertyRef> keyPropertyRefs = entityKey.getPropertyRefs();
try {
if (keyPropertyRefs.size() == 1) {
return getKeyValueFromPropertyRef(entityDataModel, entity, keyPropertyRefs.get(0));
} else if (keyPropertyRefs.size() > 1) {
List<String> processedKeys = new ArrayList<>();
for (PropertyRef propertyRef : keyPropertyRefs) {
processedKeys.add(String.format("%s=%s", propertyRef.getPath(),
getKeyValueFromPropertyRef(entityDataModel, entity, propertyRef)));
}
return processedKeys.stream().map(Object::toString).collect(Collectors.joining(","));
} else {
LOG.error("Not possible to retrieve entity key for entity " + entity);
throw new ODataEdmException("Entity key is not found for " + entity);
}
} catch (IllegalAccessException e) {
LOG.error("Not possible to retrieve entity key for entity " + entity);
throw new ODataEdmException("Not possible to retrieve entity key for entity " + entity, e);
}
} } | public class class_name {
public static String formatEntityKey(EntityDataModel entityDataModel, Object entity) throws ODataEdmException {
Key entityKey = getAndCheckEntityType(entityDataModel, entity.getClass()).getKey();
List<PropertyRef> keyPropertyRefs = entityKey.getPropertyRefs();
try {
if (keyPropertyRefs.size() == 1) {
return getKeyValueFromPropertyRef(entityDataModel, entity, keyPropertyRefs.get(0)); // depends on control dependency: [if], data = [none]
} else if (keyPropertyRefs.size() > 1) {
List<String> processedKeys = new ArrayList<>();
for (PropertyRef propertyRef : keyPropertyRefs) {
processedKeys.add(String.format("%s=%s", propertyRef.getPath(),
getKeyValueFromPropertyRef(entityDataModel, entity, propertyRef))); // depends on control dependency: [for], data = [propertyRef]
}
return processedKeys.stream().map(Object::toString).collect(Collectors.joining(",")); // depends on control dependency: [if], data = [none]
} else {
LOG.error("Not possible to retrieve entity key for entity " + entity); // depends on control dependency: [if], data = [none]
throw new ODataEdmException("Entity key is not found for " + entity);
}
} catch (IllegalAccessException e) {
LOG.error("Not possible to retrieve entity key for entity " + entity);
throw new ODataEdmException("Not possible to retrieve entity key for entity " + entity, e);
}
} } |
public class class_name {
static OpenElementTag asEngineOpenElementTag(final IOpenElementTag openElementTag) {
if (openElementTag instanceof OpenElementTag) {
return (OpenElementTag) openElementTag;
}
final IAttribute[] originalAttributeArray = openElementTag.getAllAttributes();
final Attributes attributes;
if (originalAttributeArray == null || originalAttributeArray.length == 0) {
attributes = null;
} else {
// We will perform a deep cloning of the attributes into objects of the Attribute class, so that
// we make sure absolutely all Attributes in the new event are under the engine's control
final Attribute[] newAttributeArray = new Attribute[originalAttributeArray.length];
for (int i = 0; i < originalAttributeArray.length; i++) {
final IAttribute originalAttribute = originalAttributeArray[i];
newAttributeArray[i] =
new Attribute(
originalAttribute.getAttributeDefinition(), originalAttribute.getAttributeCompleteName(),
originalAttribute.getOperator(), originalAttribute.getValue(), originalAttribute.getValueQuotes(),
originalAttribute.getTemplateName(), originalAttribute.getLine(), originalAttribute.getCol());
}
final String[] newInnerWhiteSpaces;
if (newAttributeArray.length == 1) {
newInnerWhiteSpaces = Attributes.DEFAULT_WHITE_SPACE_ARRAY;
} else {
newInnerWhiteSpaces = new String[newAttributeArray.length];
Arrays.fill(newInnerWhiteSpaces, Attributes.DEFAULT_WHITE_SPACE);
}
attributes = new Attributes(newAttributeArray, newInnerWhiteSpaces);
}
return new OpenElementTag(
openElementTag.getTemplateMode(), openElementTag.getElementDefinition(), openElementTag.getElementCompleteName(),
attributes, openElementTag.isSynthetic(),
openElementTag.getTemplateName(), openElementTag.getLine(), openElementTag.getCol());
} } | public class class_name {
static OpenElementTag asEngineOpenElementTag(final IOpenElementTag openElementTag) {
if (openElementTag instanceof OpenElementTag) {
return (OpenElementTag) openElementTag; // depends on control dependency: [if], data = [none]
}
final IAttribute[] originalAttributeArray = openElementTag.getAllAttributes();
final Attributes attributes;
if (originalAttributeArray == null || originalAttributeArray.length == 0) {
attributes = null; // depends on control dependency: [if], data = [none]
} else {
// We will perform a deep cloning of the attributes into objects of the Attribute class, so that
// we make sure absolutely all Attributes in the new event are under the engine's control
final Attribute[] newAttributeArray = new Attribute[originalAttributeArray.length];
for (int i = 0; i < originalAttributeArray.length; i++) {
final IAttribute originalAttribute = originalAttributeArray[i];
newAttributeArray[i] =
new Attribute(
originalAttribute.getAttributeDefinition(), originalAttribute.getAttributeCompleteName(),
originalAttribute.getOperator(), originalAttribute.getValue(), originalAttribute.getValueQuotes(),
originalAttribute.getTemplateName(), originalAttribute.getLine(), originalAttribute.getCol()); // depends on control dependency: [for], data = [i]
}
final String[] newInnerWhiteSpaces;
if (newAttributeArray.length == 1) {
newInnerWhiteSpaces = Attributes.DEFAULT_WHITE_SPACE_ARRAY; // depends on control dependency: [if], data = [none]
} else {
newInnerWhiteSpaces = new String[newAttributeArray.length]; // depends on control dependency: [if], data = [none]
Arrays.fill(newInnerWhiteSpaces, Attributes.DEFAULT_WHITE_SPACE); // depends on control dependency: [if], data = [none]
}
attributes = new Attributes(newAttributeArray, newInnerWhiteSpaces); // depends on control dependency: [if], data = [none]
}
return new OpenElementTag(
openElementTag.getTemplateMode(), openElementTag.getElementDefinition(), openElementTag.getElementCompleteName(),
attributes, openElementTag.isSynthetic(),
openElementTag.getTemplateName(), openElementTag.getLine(), openElementTag.getCol());
} } |
public class class_name {
public double invertedGenerationalDistancePlus(Front front, Front referenceFront) {
double sum = 0.0;
for (int i = 0 ; i < referenceFront.getNumberOfPoints(); i++) {
sum += FrontUtils.distanceToClosestPoint(referenceFront.getPoint(i),
front, new DominanceDistance());
}
// STEP 4. Divide the sum by the maximum number of points of the reference Pareto front
return sum / referenceFront.getNumberOfPoints();
} } | public class class_name {
public double invertedGenerationalDistancePlus(Front front, Front referenceFront) {
double sum = 0.0;
for (int i = 0 ; i < referenceFront.getNumberOfPoints(); i++) {
sum += FrontUtils.distanceToClosestPoint(referenceFront.getPoint(i),
front, new DominanceDistance()); // depends on control dependency: [for], data = [none]
}
// STEP 4. Divide the sum by the maximum number of points of the reference Pareto front
return sum / referenceFront.getNumberOfPoints();
} } |
public class class_name {
public List<GoogleCalendar> getCalendars() throws IOException {
List<CalendarListEntry> calendarListEntries = dao.calendarList().list().execute().getItems();
List<GoogleCalendar> calendars = new ArrayList<>();
if (calendarListEntries != null && !calendarListEntries.isEmpty()) {
for (int i = 0; i < calendarListEntries.size(); i++) {
CalendarListEntry calendarListEntry = calendarListEntries.get(i);
GoogleCalendar calendar = converter.convert(calendarListEntry, GoogleCalendar.class);
calendar.setStyle(com.calendarfx.model.Calendar.Style.getStyle(i));
calendars.add(calendar);
}
}
return calendars;
} } | public class class_name {
public List<GoogleCalendar> getCalendars() throws IOException {
List<CalendarListEntry> calendarListEntries = dao.calendarList().list().execute().getItems();
List<GoogleCalendar> calendars = new ArrayList<>();
if (calendarListEntries != null && !calendarListEntries.isEmpty()) {
for (int i = 0; i < calendarListEntries.size(); i++) {
CalendarListEntry calendarListEntry = calendarListEntries.get(i);
GoogleCalendar calendar = converter.convert(calendarListEntry, GoogleCalendar.class);
calendar.setStyle(com.calendarfx.model.Calendar.Style.getStyle(i)); // depends on control dependency: [for], data = [i]
calendars.add(calendar); // depends on control dependency: [for], data = [none]
}
}
return calendars;
} } |
public class class_name {
private static String resolveName(Class<?> c, String name) {
if (name == null) {
return name;
}
if (!name.startsWith("/")) {
while (c.isArray()) {
c = c.getComponentType();
}
String baseName = c.getName();
int index = baseName.lastIndexOf('.');
if (index != -1) {
name = baseName.substring(0, index).replace('.', '/')
+"/"+name;
}
} else {
name = name.substring(1);
}
return name;
} } | public class class_name {
private static String resolveName(Class<?> c, String name) {
if (name == null) {
return name; // depends on control dependency: [if], data = [none]
}
if (!name.startsWith("/")) {
while (c.isArray()) {
c = c.getComponentType(); // depends on control dependency: [while], data = [none]
}
String baseName = c.getName();
int index = baseName.lastIndexOf('.');
if (index != -1) {
name = baseName.substring(0, index).replace('.', '/')
+"/"+name; // depends on control dependency: [if], data = [none]
}
} else {
name = name.substring(1); // depends on control dependency: [if], data = [none]
}
return name;
} } |
public class class_name {
public void auditPortableMediaCreate(
RFC3881EventOutcomeCodes eventOutcome,
String submissionSetUniqueId,
String patientId,
List<CodedValueType> purposesOfUse)
{
if (!isAuditorEnabled()) {
return;
}
ExportEvent exportEvent = new ExportEvent(true, eventOutcome, new IHETransactionEventTypeCodes.DistributeDocumentSetOnMedia(), purposesOfUse);
exportEvent.setAuditSourceId(getAuditSourceId(), getAuditEnterpriseSiteId());
exportEvent.addSourceActiveParticipant(getSystemUserId(), getSystemAltUserId(), getSystemUserName(), getSystemNetworkId(), true);
if (!EventUtils.isEmptyOrNull(patientId)) {
exportEvent.addPatientParticipantObject(patientId);
}
exportEvent.addSubmissionSetParticipantObject(submissionSetUniqueId);
audit(exportEvent);
} } | public class class_name {
public void auditPortableMediaCreate(
RFC3881EventOutcomeCodes eventOutcome,
String submissionSetUniqueId,
String patientId,
List<CodedValueType> purposesOfUse)
{
if (!isAuditorEnabled()) {
return; // depends on control dependency: [if], data = [none]
}
ExportEvent exportEvent = new ExportEvent(true, eventOutcome, new IHETransactionEventTypeCodes.DistributeDocumentSetOnMedia(), purposesOfUse);
exportEvent.setAuditSourceId(getAuditSourceId(), getAuditEnterpriseSiteId());
exportEvent.addSourceActiveParticipant(getSystemUserId(), getSystemAltUserId(), getSystemUserName(), getSystemNetworkId(), true);
if (!EventUtils.isEmptyOrNull(patientId)) {
exportEvent.addPatientParticipantObject(patientId); // depends on control dependency: [if], data = [none]
}
exportEvent.addSubmissionSetParticipantObject(submissionSetUniqueId);
audit(exportEvent);
} } |
public class class_name {
public MigrateArgs<K> auth(CharSequence password) {
LettuceAssert.notNull(password, "Password must not be null");
char[] chars = new char[password.length()];
for (int i = 0; i < password.length(); i++) {
chars[i] = password.charAt(i);
}
this.password = chars;
return this;
} } | public class class_name {
public MigrateArgs<K> auth(CharSequence password) {
LettuceAssert.notNull(password, "Password must not be null");
char[] chars = new char[password.length()];
for (int i = 0; i < password.length(); i++) {
chars[i] = password.charAt(i); // depends on control dependency: [for], data = [i]
}
this.password = chars;
return this;
} } |
public class class_name {
public final int getConstantIndex(long constant)
{
for (ConstantInfo ci : listConstantInfo(ConstantLong.class))
{
ConstantLong ic = (ConstantLong) ci;
if (constant == ic.getConstant())
{
return constantPoolIndexMap.get(ci);
}
}
return -1;
} } | public class class_name {
public final int getConstantIndex(long constant)
{
for (ConstantInfo ci : listConstantInfo(ConstantLong.class))
{
ConstantLong ic = (ConstantLong) ci;
if (constant == ic.getConstant())
{
return constantPoolIndexMap.get(ci); // depends on control dependency: [if], data = [none]
}
}
return -1;
} } |
public class class_name {
public QueryControllerQuery addQuery(String queryStr, String queryId) {
int position = getElementPosition(queryId);
QueryControllerQuery query = new QueryControllerQuery(queryId);
query.setQuery(queryStr);
if (position == -1) { // add to the collection for a new query.
entities.add(query);
fireElementAdded(query);
} else {
entities.set(position, query);
fireElementChanged(query);
}
return query;
} } | public class class_name {
public QueryControllerQuery addQuery(String queryStr, String queryId) {
int position = getElementPosition(queryId);
QueryControllerQuery query = new QueryControllerQuery(queryId);
query.setQuery(queryStr);
if (position == -1) { // add to the collection for a new query.
entities.add(query); // depends on control dependency: [if], data = [none]
fireElementAdded(query); // depends on control dependency: [if], data = [none]
} else {
entities.set(position, query); // depends on control dependency: [if], data = [(position]
fireElementChanged(query); // depends on control dependency: [if], data = [none]
}
return query;
} } |
public class class_name {
private void updateCountNoQuotaCheck(INode[] inodes, int startPos, int endPos,
long nsDelta, long dsDelta) {
try {
updateCount(inodes, startPos, endPos, nsDelta, dsDelta, false);
} catch (QuotaExceededException e) {
NameNode.LOG.warn("FSDirectory.updateCountNoQuotaCheck - unexpected ", e);
}
} } | public class class_name {
private void updateCountNoQuotaCheck(INode[] inodes, int startPos, int endPos,
long nsDelta, long dsDelta) {
try {
updateCount(inodes, startPos, endPos, nsDelta, dsDelta, false); // depends on control dependency: [try], data = [none]
} catch (QuotaExceededException e) {
NameNode.LOG.warn("FSDirectory.updateCountNoQuotaCheck - unexpected ", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void setJobDefinitions(java.util.Collection<JobDefinition> jobDefinitions) {
if (jobDefinitions == null) {
this.jobDefinitions = null;
return;
}
this.jobDefinitions = new java.util.ArrayList<JobDefinition>(jobDefinitions);
} } | public class class_name {
public void setJobDefinitions(java.util.Collection<JobDefinition> jobDefinitions) {
if (jobDefinitions == null) {
this.jobDefinitions = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.jobDefinitions = new java.util.ArrayList<JobDefinition>(jobDefinitions);
} } |
public class class_name {
@Override
protected void visitSoyFileNode(SoyFileNode node) {
StringBuilder file = new StringBuilder();
file.append("// This file was automatically generated from ")
.append(node.getFileName())
.append(".\n");
file.append("// Please don't edit this file by hand.\n");
// Output a section containing optionally-parsed compiler directives in comments. Since these
// are comments, they are not controlled by an option, and will be removed by minifiers that do
// not understand them.
file.append("\n");
String fileOverviewDescription = "Templates in namespace " + node.getNamespace() + ".";
JsDoc.Builder jsDocBuilder = JsDoc.builder();
jsDocBuilder.addAnnotation("fileoverview", fileOverviewDescription);
if (node.getDelPackageName() != null) {
jsDocBuilder.addParameterizedAnnotation("modName", node.getDelPackageName());
}
addJsDocToProvideDelTemplates(jsDocBuilder, node);
addJsDocToRequireDelTemplates(jsDocBuilder, node);
addCodeToRequireCss(jsDocBuilder, node);
jsDocBuilder.addAnnotation("public");
file.append(jsDocBuilder.build());
file.append("\n\n");
// Add code to define JS namespaces or add provide/require calls for Closure Library.
templateAliases = AliasUtils.IDENTITY_ALIASES;
jsCodeBuilder = createCodeBuilder();
if (jsSrcOptions.shouldGenerateGoogModules()) {
templateAliases = AliasUtils.createTemplateAliases(node);
addCodeToDeclareGoogModule(file, node);
addCodeToRequireGoogModules(node);
} else if (jsSrcOptions.shouldProvideRequireSoyNamespaces()) {
addCodeToProvideSoyNamespace(file, node);
file.append('\n');
addCodeToRequireSoyNamespaces(node);
} else {
throw new AssertionError("impossible");
}
// add declarations for the ijdata params
// This takes advantage of the way '@record' types in closure are 'open'.
// Unfortunately clutz doesn't understand this:
// https://github.com/angular/clutz/issues/832
// So TS users will not be able to see the property definitions.
// The most practical solution to that is for soy to generate its own .d.ts files.
Map<String, SoyType> ijData = getAllIjDataParams(node);
if (!ijData.isEmpty()) {
GoogRequire require = GoogRequire.create("soy");
jsCodeBuilder.appendLine();
for (Map.Entry<String, SoyType> entry : ijData.entrySet()) {
jsCodeBuilder.appendLine();
//
jsCodeBuilder.appendLine(
JsDoc.builder()
// Because every declaration can declare a type, we can get errors if they don't
// declare identical types. There isn't a good way to force identical declarations
// so we just suppress the duplicate error warning.
.addParameterizedAnnotation("suppress", "duplicate")
// declare every field as optional. This is because if a template is unused and
// declares an ij param we don't want to force people to supply a value.
.addParameterizedAnnotation(
"type",
getJsTypeForParamForDeclaration(entry.getValue()).typeExpr() + "|undefined")
.build()
.toString());
jsCodeBuilder.append(
require
.reference()
.dotAccess("IjData")
.dotAccess("prototype")
.dotAccess(entry.getKey())
.asStatement());
}
}
// Add code for each template.
for (TemplateNode template : node.getChildren()) {
jsCodeBuilder.appendLine().appendLine();
staticVarDeclarations = new ArrayList<>();
visit(template);
if (!staticVarDeclarations.isEmpty()) {
jsCodeBuilder.append(Statement.of(staticVarDeclarations));
}
}
jsCodeBuilder.appendGoogRequiresTo(file);
jsCodeBuilder.appendCodeTo(file);
jsFilesContents.add(file.toString());
jsCodeBuilder = null;
} } | public class class_name {
@Override
protected void visitSoyFileNode(SoyFileNode node) {
StringBuilder file = new StringBuilder();
file.append("// This file was automatically generated from ")
.append(node.getFileName())
.append(".\n");
file.append("// Please don't edit this file by hand.\n");
// Output a section containing optionally-parsed compiler directives in comments. Since these
// are comments, they are not controlled by an option, and will be removed by minifiers that do
// not understand them.
file.append("\n");
String fileOverviewDescription = "Templates in namespace " + node.getNamespace() + ".";
JsDoc.Builder jsDocBuilder = JsDoc.builder();
jsDocBuilder.addAnnotation("fileoverview", fileOverviewDescription);
if (node.getDelPackageName() != null) {
jsDocBuilder.addParameterizedAnnotation("modName", node.getDelPackageName()); // depends on control dependency: [if], data = [none]
}
addJsDocToProvideDelTemplates(jsDocBuilder, node);
addJsDocToRequireDelTemplates(jsDocBuilder, node);
addCodeToRequireCss(jsDocBuilder, node);
jsDocBuilder.addAnnotation("public");
file.append(jsDocBuilder.build());
file.append("\n\n");
// Add code to define JS namespaces or add provide/require calls for Closure Library.
templateAliases = AliasUtils.IDENTITY_ALIASES;
jsCodeBuilder = createCodeBuilder();
if (jsSrcOptions.shouldGenerateGoogModules()) {
templateAliases = AliasUtils.createTemplateAliases(node); // depends on control dependency: [if], data = [none]
addCodeToDeclareGoogModule(file, node); // depends on control dependency: [if], data = [none]
addCodeToRequireGoogModules(node); // depends on control dependency: [if], data = [none]
} else if (jsSrcOptions.shouldProvideRequireSoyNamespaces()) {
addCodeToProvideSoyNamespace(file, node); // depends on control dependency: [if], data = [none]
file.append('\n'); // depends on control dependency: [if], data = [none]
addCodeToRequireSoyNamespaces(node); // depends on control dependency: [if], data = [none]
} else {
throw new AssertionError("impossible");
}
// add declarations for the ijdata params
// This takes advantage of the way '@record' types in closure are 'open'.
// Unfortunately clutz doesn't understand this:
// https://github.com/angular/clutz/issues/832
// So TS users will not be able to see the property definitions.
// The most practical solution to that is for soy to generate its own .d.ts files.
Map<String, SoyType> ijData = getAllIjDataParams(node);
if (!ijData.isEmpty()) {
GoogRequire require = GoogRequire.create("soy");
jsCodeBuilder.appendLine(); // depends on control dependency: [if], data = [none]
for (Map.Entry<String, SoyType> entry : ijData.entrySet()) {
jsCodeBuilder.appendLine(); // depends on control dependency: [for], data = [none]
//
jsCodeBuilder.appendLine(
JsDoc.builder()
// Because every declaration can declare a type, we can get errors if they don't
// declare identical types. There isn't a good way to force identical declarations
// so we just suppress the duplicate error warning.
.addParameterizedAnnotation("suppress", "duplicate")
// declare every field as optional. This is because if a template is unused and
// declares an ij param we don't want to force people to supply a value.
.addParameterizedAnnotation(
"type",
getJsTypeForParamForDeclaration(entry.getValue()).typeExpr() + "|undefined")
.build()
.toString()); // depends on control dependency: [for], data = [none]
jsCodeBuilder.append(
require
.reference()
.dotAccess("IjData")
.dotAccess("prototype")
.dotAccess(entry.getKey())
.asStatement()); // depends on control dependency: [for], data = [none]
}
}
// Add code for each template.
for (TemplateNode template : node.getChildren()) {
jsCodeBuilder.appendLine().appendLine(); // depends on control dependency: [for], data = [none]
staticVarDeclarations = new ArrayList<>(); // depends on control dependency: [for], data = [none]
visit(template); // depends on control dependency: [for], data = [template]
if (!staticVarDeclarations.isEmpty()) {
jsCodeBuilder.append(Statement.of(staticVarDeclarations)); // depends on control dependency: [if], data = [none]
}
}
jsCodeBuilder.appendGoogRequiresTo(file);
jsCodeBuilder.appendCodeTo(file);
jsFilesContents.add(file.toString());
jsCodeBuilder = null;
} } |
public class class_name {
@Pure
public double[] toDoubleArray(Transform3D transform) {
double[] clone = new double[this.numCoords];
if (transform==null) {
for(int i=0; i<this.numCoords; ++i) {
clone[i] = this.coords[i];
}
}
else {
Point3f p = new Point3f();
for(int i=0; i<clone.length;) {
p.x = this.coords[i];
p.y = this.coords[i+1];
p.y = this.coords[i+2];
transform.transform(p);
clone[i++] = p.x;
clone[i++] = p.y;
clone[i++] = p.z;
}
}
return clone;
} } | public class class_name {
@Pure
public double[] toDoubleArray(Transform3D transform) {
double[] clone = new double[this.numCoords];
if (transform==null) {
for(int i=0; i<this.numCoords; ++i) {
clone[i] = this.coords[i]; // depends on control dependency: [for], data = [i]
}
}
else {
Point3f p = new Point3f();
for(int i=0; i<clone.length;) {
p.x = this.coords[i]; // depends on control dependency: [for], data = [i]
p.y = this.coords[i+1]; // depends on control dependency: [for], data = [i]
p.y = this.coords[i+2]; // depends on control dependency: [for], data = [i]
transform.transform(p); // depends on control dependency: [for], data = [none]
clone[i++] = p.x; // depends on control dependency: [for], data = [i]
clone[i++] = p.y; // depends on control dependency: [for], data = [i]
clone[i++] = p.z; // depends on control dependency: [for], data = [i]
}
}
return clone;
} } |
public class class_name {
public final void mMULTI_LINE_COMMENT() throws RecognitionException {
try {
int _type = MULTI_LINE_COMMENT;
int _channel = DEFAULT_TOKEN_CHANNEL;
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:324:5: ( '/*' ( options {greedy=false; } : . )* '*/' )
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:324:7: '/*' ( options {greedy=false; } : . )* '*/'
{
match("/*"); if (state.failed) return;
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:324:12: ( options {greedy=false; } : . )*
loop59:
while (true) {
int alt59=2;
int LA59_0 = input.LA(1);
if ( (LA59_0=='*') ) {
int LA59_1 = input.LA(2);
if ( (LA59_1=='/') ) {
alt59=2;
}
else if ( ((LA59_1 >= '\u0000' && LA59_1 <= '.')||(LA59_1 >= '0' && LA59_1 <= '\uFFFF')) ) {
alt59=1;
}
}
else if ( ((LA59_0 >= '\u0000' && LA59_0 <= ')')||(LA59_0 >= '+' && LA59_0 <= '\uFFFF')) ) {
alt59=1;
}
switch (alt59) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:324:38: .
{
matchAny(); if (state.failed) return;
}
break;
default :
break loop59;
}
}
match("*/"); if (state.failed) return;
if ( state.backtracking==0 ) { _channel=HIDDEN; }
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
} } | public class class_name {
public final void mMULTI_LINE_COMMENT() throws RecognitionException {
try {
int _type = MULTI_LINE_COMMENT;
int _channel = DEFAULT_TOKEN_CHANNEL;
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:324:5: ( '/*' ( options {greedy=false; } : . )* '*/' )
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:324:7: '/*' ( options {greedy=false; } : . )* '*/'
{
match("/*"); if (state.failed) return;
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:324:12: ( options {greedy=false; } : . )*
loop59:
while (true) {
int alt59=2;
int LA59_0 = input.LA(1);
if ( (LA59_0=='*') ) {
int LA59_1 = input.LA(2);
if ( (LA59_1=='/') ) {
alt59=2;
}
else if ( ((LA59_1 >= '\u0000' && LA59_1 <= '.')||(LA59_1 >= '0' && LA59_1 <= '\uFFFF')) ) {
alt59=1;
}
}
else if ( ((LA59_0 >= '\u0000' && LA59_0 <= ')')||(LA59_0 >= '+' && LA59_0 <= '\uFFFF')) ) {
alt59=1;
}
switch (alt59) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:324:38: .
{
matchAny(); if (state.failed) return;
}
break;
default :
break loop59;
}
}
match("*/"); if (state.failed) return;
if ( state.backtracking==0 ) { _channel=HIDDEN; } // depends on control dependency: [if], data = [none]
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
} } |
public class class_name {
public void marshall(Field field, ProtocolMarshaller protocolMarshaller) {
if (field == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(field.getKey(), KEY_BINDING);
protocolMarshaller.marshall(field.getStringValue(), STRINGVALUE_BINDING);
protocolMarshaller.marshall(field.getRefValue(), REFVALUE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(Field field, ProtocolMarshaller protocolMarshaller) {
if (field == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(field.getKey(), KEY_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(field.getStringValue(), STRINGVALUE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(field.getRefValue(), REFVALUE_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public String getFilePath(String resourcePath) {
String filePath = null;
String path = getCompletePath(resourcePath);
URL url = null;
try {
url = ClassLoaderResourceUtils.getResourceURL(path, this);
String strURL = url.toString();
if (strURL.startsWith(JawrConstant.FILE_URL_PREFIX)) {
filePath = new File(url.getFile()).getAbsolutePath();
} else if (strURL.startsWith(JawrConstant.JAR_URL_PREFIX + JawrConstant.FILE_URL_PREFIX)) {
String tmp = strURL.substring((JawrConstant.JAR_URL_PREFIX + JawrConstant.FILE_URL_PREFIX).length());
int idxJarContentSeparator = tmp.indexOf("!");
if (idxJarContentSeparator != -1) {
tmp = tmp.substring(0, idxJarContentSeparator);
}
filePath = new File(tmp).getAbsolutePath();
}
} catch (ResourceNotFoundException e) {
filePath = null;
}
return filePath;
} } | public class class_name {
@Override
public String getFilePath(String resourcePath) {
String filePath = null;
String path = getCompletePath(resourcePath);
URL url = null;
try {
url = ClassLoaderResourceUtils.getResourceURL(path, this); // depends on control dependency: [try], data = [none]
String strURL = url.toString();
if (strURL.startsWith(JawrConstant.FILE_URL_PREFIX)) {
filePath = new File(url.getFile()).getAbsolutePath(); // depends on control dependency: [if], data = [none]
} else if (strURL.startsWith(JawrConstant.JAR_URL_PREFIX + JawrConstant.FILE_URL_PREFIX)) {
String tmp = strURL.substring((JawrConstant.JAR_URL_PREFIX + JawrConstant.FILE_URL_PREFIX).length());
int idxJarContentSeparator = tmp.indexOf("!");
if (idxJarContentSeparator != -1) {
tmp = tmp.substring(0, idxJarContentSeparator); // depends on control dependency: [if], data = [none]
}
filePath = new File(tmp).getAbsolutePath(); // depends on control dependency: [if], data = [none]
}
} catch (ResourceNotFoundException e) {
filePath = null;
} // depends on control dependency: [catch], data = [none]
return filePath;
} } |
public class class_name {
private MobicentsSipSession retrieveSipSession(Dialog dialog) {
if(dialog != null) {
Iterator<SipContext> iterator = sipApplicationDispatcher.findSipApplications();
while(iterator.hasNext()) {
SipContext sipContext = iterator.next();
SipManager sipManager = sipContext.getSipManager();
Iterator<MobicentsSipSession> sipSessionsIt= sipManager.getAllSipSessions();
while (sipSessionsIt.hasNext()) {
MobicentsSipSession mobicentsSipSession = (MobicentsSipSession) sipSessionsIt
.next();
MobicentsSipSessionKey sessionKey = mobicentsSipSession.getKey();
if(sessionKey.getCallId().trim().equals(dialog.getCallId().getCallId())) {
if(logger.isDebugEnabled()) {
logger.debug("found session with the same Call Id " + sessionKey + ", to Tag " + sessionKey.getToTag());
logger.debug("dialog localParty = " + dialog.getLocalParty().getURI() + ", localTag " + dialog.getLocalTag());
logger.debug("dialog remoteParty = " + dialog.getRemoteParty().getURI() + ", remoteTag " + dialog.getRemoteTag());
}
if(sessionKey.getFromTag().equals(dialog.getLocalTag()) && sessionKey.getToTag().equals(dialog.getRemoteTag())) {
if(mobicentsSipSession.getProxy() == null) {
return mobicentsSipSession;
}
} else if (sessionKey.getFromTag().equals(dialog.getRemoteTag()) && sessionKey.getToTag().equals(dialog.getLocalTag())){
if(mobicentsSipSession.getProxy() == null) {
return mobicentsSipSession;
}
}
}
}
}
}
return null;
} } | public class class_name {
private MobicentsSipSession retrieveSipSession(Dialog dialog) {
if(dialog != null) {
Iterator<SipContext> iterator = sipApplicationDispatcher.findSipApplications();
while(iterator.hasNext()) {
SipContext sipContext = iterator.next();
SipManager sipManager = sipContext.getSipManager();
Iterator<MobicentsSipSession> sipSessionsIt= sipManager.getAllSipSessions();
while (sipSessionsIt.hasNext()) {
MobicentsSipSession mobicentsSipSession = (MobicentsSipSession) sipSessionsIt
.next();
MobicentsSipSessionKey sessionKey = mobicentsSipSession.getKey();
if(sessionKey.getCallId().trim().equals(dialog.getCallId().getCallId())) {
if(logger.isDebugEnabled()) {
logger.debug("found session with the same Call Id " + sessionKey + ", to Tag " + sessionKey.getToTag()); // depends on control dependency: [if], data = [none]
logger.debug("dialog localParty = " + dialog.getLocalParty().getURI() + ", localTag " + dialog.getLocalTag()); // depends on control dependency: [if], data = [none]
logger.debug("dialog remoteParty = " + dialog.getRemoteParty().getURI() + ", remoteTag " + dialog.getRemoteTag()); // depends on control dependency: [if], data = [none]
}
if(sessionKey.getFromTag().equals(dialog.getLocalTag()) && sessionKey.getToTag().equals(dialog.getRemoteTag())) {
if(mobicentsSipSession.getProxy() == null) {
return mobicentsSipSession; // depends on control dependency: [if], data = [none]
}
} else if (sessionKey.getFromTag().equals(dialog.getRemoteTag()) && sessionKey.getToTag().equals(dialog.getLocalTag())){
if(mobicentsSipSession.getProxy() == null) {
return mobicentsSipSession; // depends on control dependency: [if], data = [none]
}
}
}
}
}
}
return null;
} } |
public class class_name {
public static void put(String key, WidgetBuilder builder) {
if (null != key && null != builder) {
WIDGETBUILDERS.put(key, builder);
}
} } | public class class_name {
public static void put(String key, WidgetBuilder builder) {
if (null != key && null != builder) {
WIDGETBUILDERS.put(key, builder); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static <T> Collection<T> unique(Collection<T> self, boolean mutate, Comparator<T> comparator) {
List<T> answer = uniqueItems(self, comparator);
if (mutate) {
self.clear();
self.addAll(answer);
}
return mutate ? self : answer;
} } | public class class_name {
public static <T> Collection<T> unique(Collection<T> self, boolean mutate, Comparator<T> comparator) {
List<T> answer = uniqueItems(self, comparator);
if (mutate) {
self.clear(); // depends on control dependency: [if], data = [none]
self.addAll(answer); // depends on control dependency: [if], data = [none]
}
return mutate ? self : answer;
} } |
public class class_name {
private double[] computeResidualVector(double[] vector, int centroidIndex) {
double[] residualVector = new double[vectorLength];
for (int i = 0; i < vectorLength; i++) {
residualVector[i] = coarseQuantizer[centroidIndex][i] - vector[i];
}
return residualVector;
} } | public class class_name {
private double[] computeResidualVector(double[] vector, int centroidIndex) {
double[] residualVector = new double[vectorLength];
for (int i = 0; i < vectorLength; i++) {
residualVector[i] = coarseQuantizer[centroidIndex][i] - vector[i];
// depends on control dependency: [for], data = [i]
}
return residualVector;
} } |
public class class_name {
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
int iteratorIndex;
int iteratorBufferIndex;
int iteratorOffset;
@Override
public boolean hasNext() {
return iteratorIndex < size;
}
@Override
public E next() {
if (iteratorIndex >= size) {
throw new NoSuchElementException();
}
E[] buf = buffers[iteratorBufferIndex];
E result = buf[iteratorOffset];
// increment
iteratorIndex++;
iteratorOffset++;
if (iteratorOffset >= buf.length) {
iteratorOffset = 0;
iteratorBufferIndex++;
}
return result;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
} } | public class class_name {
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
int iteratorIndex;
int iteratorBufferIndex;
int iteratorOffset;
@Override
public boolean hasNext() {
return iteratorIndex < size;
}
@Override
public E next() {
if (iteratorIndex >= size) {
throw new NoSuchElementException();
}
E[] buf = buffers[iteratorBufferIndex];
E result = buf[iteratorOffset];
// increment
iteratorIndex++;
iteratorOffset++;
if (iteratorOffset >= buf.length) {
iteratorOffset = 0; // depends on control dependency: [if], data = [none]
iteratorBufferIndex++; // depends on control dependency: [if], data = [none]
}
return result;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
} } |
public class class_name {
private FinalApplicationStatus getYarnStatus(ApplicationStatus status) {
if (status == null) {
return FinalApplicationStatus.UNDEFINED;
}
else {
switch (status) {
case SUCCEEDED:
return FinalApplicationStatus.SUCCEEDED;
case FAILED:
return FinalApplicationStatus.FAILED;
case CANCELED:
return FinalApplicationStatus.KILLED;
default:
return FinalApplicationStatus.UNDEFINED;
}
}
} } | public class class_name {
private FinalApplicationStatus getYarnStatus(ApplicationStatus status) {
if (status == null) {
return FinalApplicationStatus.UNDEFINED; // depends on control dependency: [if], data = [none]
}
else {
switch (status) {
case SUCCEEDED:
return FinalApplicationStatus.SUCCEEDED;
case FAILED:
return FinalApplicationStatus.FAILED;
case CANCELED:
return FinalApplicationStatus.KILLED;
default:
return FinalApplicationStatus.UNDEFINED;
}
}
} } |
public class class_name {
public AgentFilter withAgentHealths(String... agentHealths) {
if (this.agentHealths == null) {
setAgentHealths(new java.util.ArrayList<String>(agentHealths.length));
}
for (String ele : agentHealths) {
this.agentHealths.add(ele);
}
return this;
} } | public class class_name {
public AgentFilter withAgentHealths(String... agentHealths) {
if (this.agentHealths == null) {
setAgentHealths(new java.util.ArrayList<String>(agentHealths.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : agentHealths) {
this.agentHealths.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public static Cell[] getColumn(final Sheet sheet, final int col) {
ArgUtils.notNull(sheet, "sheet");
int maxRow = getRows(sheet);
Cell[] cells = new Cell[maxRow];
for(int i=0; i < maxRow; i++) {
Row rows = sheet.getRow(i);
if(rows == null) {
rows = sheet.createRow(i);
}
Cell cell = rows.getCell(col);
if(cell == null) {
cell = rows.createCell(col, CellType.BLANK);
}
cells[i] = cell;
}
return cells;
} } | public class class_name {
public static Cell[] getColumn(final Sheet sheet, final int col) {
ArgUtils.notNull(sheet, "sheet");
int maxRow = getRows(sheet);
Cell[] cells = new Cell[maxRow];
for(int i=0; i < maxRow; i++) {
Row rows = sheet.getRow(i);
if(rows == null) {
rows = sheet.createRow(i);
// depends on control dependency: [if], data = [none]
}
Cell cell = rows.getCell(col);
if(cell == null) {
cell = rows.createCell(col, CellType.BLANK);
// depends on control dependency: [if], data = [none]
}
cells[i] = cell;
// depends on control dependency: [for], data = [i]
}
return cells;
} } |
public class class_name {
private boolean compileInternalToFile(
final String jarOutputPath,
final VoltCompilerReader cannonicalDDLIfAny,
final Catalog previousCatalogIfAny,
final List<VoltCompilerReader> ddlReaderList,
final InMemoryJarfile jarOutputRet)
{
if (jarOutputPath == null) {
addErr("The output jar path is null.");
return false;
}
InMemoryJarfile jarOutput = compileInternal(cannonicalDDLIfAny, previousCatalogIfAny, ddlReaderList, jarOutputRet);
if (jarOutput == null) {
return false;
}
try {
jarOutput.writeToFile(new File(jarOutputPath)).run();
}
catch (final Exception e) {
e.printStackTrace();
addErr("Error writing catalog jar to disk: " + e.getMessage());
return false;
}
return true;
} } | public class class_name {
private boolean compileInternalToFile(
final String jarOutputPath,
final VoltCompilerReader cannonicalDDLIfAny,
final Catalog previousCatalogIfAny,
final List<VoltCompilerReader> ddlReaderList,
final InMemoryJarfile jarOutputRet)
{
if (jarOutputPath == null) {
addErr("The output jar path is null."); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
InMemoryJarfile jarOutput = compileInternal(cannonicalDDLIfAny, previousCatalogIfAny, ddlReaderList, jarOutputRet);
if (jarOutput == null) {
return false; // depends on control dependency: [if], data = [none]
}
try {
jarOutput.writeToFile(new File(jarOutputPath)).run(); // depends on control dependency: [try], data = [none]
}
catch (final Exception e) {
e.printStackTrace();
addErr("Error writing catalog jar to disk: " + e.getMessage());
return false;
} // depends on control dependency: [catch], data = [none]
return true;
} } |
public class class_name {
public void marshall(ReplicationTaskAssessmentResult replicationTaskAssessmentResult, ProtocolMarshaller protocolMarshaller) {
if (replicationTaskAssessmentResult == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(replicationTaskAssessmentResult.getReplicationTaskIdentifier(), REPLICATIONTASKIDENTIFIER_BINDING);
protocolMarshaller.marshall(replicationTaskAssessmentResult.getReplicationTaskArn(), REPLICATIONTASKARN_BINDING);
protocolMarshaller.marshall(replicationTaskAssessmentResult.getReplicationTaskLastAssessmentDate(), REPLICATIONTASKLASTASSESSMENTDATE_BINDING);
protocolMarshaller.marshall(replicationTaskAssessmentResult.getAssessmentStatus(), ASSESSMENTSTATUS_BINDING);
protocolMarshaller.marshall(replicationTaskAssessmentResult.getAssessmentResultsFile(), ASSESSMENTRESULTSFILE_BINDING);
protocolMarshaller.marshall(replicationTaskAssessmentResult.getAssessmentResults(), ASSESSMENTRESULTS_BINDING);
protocolMarshaller.marshall(replicationTaskAssessmentResult.getS3ObjectUrl(), S3OBJECTURL_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ReplicationTaskAssessmentResult replicationTaskAssessmentResult, ProtocolMarshaller protocolMarshaller) {
if (replicationTaskAssessmentResult == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(replicationTaskAssessmentResult.getReplicationTaskIdentifier(), REPLICATIONTASKIDENTIFIER_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(replicationTaskAssessmentResult.getReplicationTaskArn(), REPLICATIONTASKARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(replicationTaskAssessmentResult.getReplicationTaskLastAssessmentDate(), REPLICATIONTASKLASTASSESSMENTDATE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(replicationTaskAssessmentResult.getAssessmentStatus(), ASSESSMENTSTATUS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(replicationTaskAssessmentResult.getAssessmentResultsFile(), ASSESSMENTRESULTSFILE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(replicationTaskAssessmentResult.getAssessmentResults(), ASSESSMENTRESULTS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(replicationTaskAssessmentResult.getS3ObjectUrl(), S3OBJECTURL_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 v(String tag, String formatString, Object... args) {
if (logger != null && isLoggingEnabled(tag, VERBOSE)) {
try {
logger.v(tag, String.format(Locale.ENGLISH, formatString, args));
} catch (Exception e) {
logger.v(tag, String.format(Locale.ENGLISH, "Unable to format log: %s", formatString), e);
}
}
} } | public class class_name {
public static void v(String tag, String formatString, Object... args) {
if (logger != null && isLoggingEnabled(tag, VERBOSE)) {
try {
logger.v(tag, String.format(Locale.ENGLISH, formatString, args)); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
logger.v(tag, String.format(Locale.ENGLISH, "Unable to format log: %s", formatString), e);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public void newCell(final int row,
final int column,
final String value,
final int mergedColStart) {
if ( emptyCellValue( value ) ) {
return;
}
final Integer rowInt = new Integer( row );
if ( this._rowProperties.containsKey( rowInt ) ) {
final String[] keyValue = (String[]) this._rowProperties.get( rowInt );
if ( PropertiesSheetListener.EMPTY_STRING.equals( keyValue[1] ) ) {
keyValue[1] = value;
keyValue[2] = RuleSheetParserUtil.rc2name(row, column);
}
} else {
final String trimmedValue = value.trim();
final String[] keyValue = {trimmedValue, PropertiesSheetListener.EMPTY_STRING, RuleSheetParserUtil.rc2name(row, column+1) };
this._rowProperties.put( rowInt, keyValue );
}
} } | public class class_name {
public void newCell(final int row,
final int column,
final String value,
final int mergedColStart) {
if ( emptyCellValue( value ) ) {
return; // depends on control dependency: [if], data = [none]
}
final Integer rowInt = new Integer( row );
if ( this._rowProperties.containsKey( rowInt ) ) {
final String[] keyValue = (String[]) this._rowProperties.get( rowInt );
if ( PropertiesSheetListener.EMPTY_STRING.equals( keyValue[1] ) ) {
keyValue[1] = value; // depends on control dependency: [if], data = [none]
keyValue[2] = RuleSheetParserUtil.rc2name(row, column); // depends on control dependency: [if], data = [none]
}
} else {
final String trimmedValue = value.trim();
final String[] keyValue = {trimmedValue, PropertiesSheetListener.EMPTY_STRING, RuleSheetParserUtil.rc2name(row, column+1) };
this._rowProperties.put( rowInt, keyValue ); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public Component getReadOnly(final String _wicketId,
final AbstractUIField _uiField)
throws EFapsException
{
Component ret = null;
if (applies(_uiField)) {
String icon = _uiField.getFieldConfiguration().getField().getIcon();
if (icon == null && _uiField.getInstance() != null
&& _uiField.getFieldConfiguration().getField().isShowTypeIcon()
&& _uiField.getInstance().getType() != null) {
final Image image = Image.getTypeIcon(_uiField.getInstance().getType());
if (image != null) {
icon = image.getName();
}
}
String content = null;
for (final IComponentFactory factory : _uiField.getFactories().values()) {
if (factory instanceof AbstractUIFactory) {
final AbstractUIFactory uiFactory = (AbstractUIFactory) factory;
if (uiFactory.applies(_uiField)) {
content = uiFactory.getReadOnlyValue(_uiField);
break;
}
}
}
if (StringUtils.isEmpty(content)) {
if (isCheckOut(_uiField) && icon != null) {
ret = new IconCheckOutLink(_wicketId, Model.of(_uiField), content, icon);
} else {
ret = new LabelField(_wicketId, Model.of(""), _uiField);
}
} else if (isCheckOut(_uiField)) {
if (icon == null) {
ret = new CheckOutLink(_wicketId, Model.of(_uiField), content);
} else {
ret = new IconCheckOutLink(_wicketId, Model.of(_uiField), content, icon);
}
} else {
// evaluate which kind of link must be done
IRequestablePage page = null;
IRequestablePage calledByPage = null;
if (RequestCycle.get().getActiveRequestHandler() instanceof IPageRequestHandler) {
page = ((IPageRequestHandler) RequestCycle.get().getActiveRequestHandler()).getPage();
if (page != null && page instanceof AbstractContentPage) {
final PageReference pageRef = ((AbstractContentPage) page).getCalledByPageReference();
if (pageRef != null) {
calledByPage = pageRef.getPage();
}
}
}
// first priority is the pagePosition than..
boolean ajax = page != null
&& ((Component) page).getDefaultModelObject() instanceof IPageObject
&& PagePosition.TREE.equals(((IPageObject) ((Component) page).getDefaultModelObject())
.getPagePosition());
if (!ajax) {
ajax = _uiField.getParent() != null
&& _uiField.getParent() instanceof IPageObject
&& PagePosition.TREE.equals(((IPageObject) _uiField.getParent()).getPagePosition());
}
if (!ajax) {
// ajax if the page or the reference is a ContentContainerPage,
// or the table was called as part of a WizardCall meaning connect is done
// or it was opened after a form in modal mode
ajax = page != null && (page instanceof ContentContainerPage
|| calledByPage instanceof ContentContainerPage)
|| page instanceof TablePage
&& ((AbstractUIPageObject) ((Component) page).getDefaultModelObject())
.isPartOfWizardCall()
// form opened modal over a form
|| page instanceof FormPage && calledByPage instanceof FormPage
&& Target.MODAL.equals(((UIForm) ((Component) page).getDefaultModelObject()).getTarget())
// form opened modal over a table that itself is part of a contentcontainer
|| page instanceof FormPage
&& Target.MODAL.equals(((UIForm) ((Component) page).getDefaultModelObject()).getTarget())
&& calledByPage instanceof TablePage
&& ((TablePage) calledByPage).getCalledByPageReference() != null
&& !(((TablePage) calledByPage).getCalledByPageReference().getPage() instanceof MainPage);
}
// verify ajax by checking if is not a recent link
if (ajax && RequestCycle.get().getActiveRequestHandler() instanceof IComponentRequestHandler) {
ajax = ajax && !(((IComponentRequestHandler) RequestCycle.get().getActiveRequestHandler())
.getComponent() instanceof RecentLink);
}
// check if for searchmode the page is in an pop up window
boolean isInPopUp = false;
if (_uiField.getParent().isSearchMode()) {
if (((IWizardElement) _uiField.getParent()).isWizardCall()) {
final IWizardElement pageObj = ((IWizardElement) _uiField
.getParent()).getUIWizardObject().getWizardElement().get(0);
if (pageObj instanceof IPageObject) {
isInPopUp = PagePosition.POPUP.equals(((IPageObject) pageObj).getPagePosition());
} else {
isInPopUp = Target.POPUP.equals(((ICmdUIObject) pageObj).getCommand().getTarget());
}
}
}
if (icon == null) {
if (ajax) {
// checking if is a link of a structurbrowser browserfield
if (page instanceof StructurBrowserPage
&& ((UIStructurBrowser) _uiField.getParent()).isBrowserField(_uiField)) {
ret = new LoadInTargetAjaxLink(_wicketId, Model.of(_uiField), content, ScriptTarget.TOP);
} else {
ret = new MenuContentLink(_wicketId, Model.of(_uiField), content);
}
} else if (isInPopUp) {
ret = new LoadInTargetAjaxLink(_wicketId, Model.of(_uiField), content, ScriptTarget.OPENER);
} else {
ret = new ContentContainerLink(_wicketId, Model.of(_uiField), content);
}
} else {
if (ajax) {
ret = new IconMenuContentLink(_wicketId, Model.of(_uiField), content, icon);
} else if (isInPopUp) {
ret = new IconLoadInTargetAjaxLink(_wicketId, Model.of(_uiField), content,
ScriptTarget.OPENER, icon);
} else {
ret = new IconContentContainerLink(_wicketId, Model.of(_uiField), content, icon);
}
}
}
}
return ret;
} } | public class class_name {
@Override
public Component getReadOnly(final String _wicketId,
final AbstractUIField _uiField)
throws EFapsException
{
Component ret = null;
if (applies(_uiField)) {
String icon = _uiField.getFieldConfiguration().getField().getIcon();
if (icon == null && _uiField.getInstance() != null
&& _uiField.getFieldConfiguration().getField().isShowTypeIcon()
&& _uiField.getInstance().getType() != null) {
final Image image = Image.getTypeIcon(_uiField.getInstance().getType());
if (image != null) {
icon = image.getName(); // depends on control dependency: [if], data = [none]
}
}
String content = null;
for (final IComponentFactory factory : _uiField.getFactories().values()) {
if (factory instanceof AbstractUIFactory) {
final AbstractUIFactory uiFactory = (AbstractUIFactory) factory;
if (uiFactory.applies(_uiField)) {
content = uiFactory.getReadOnlyValue(_uiField); // depends on control dependency: [if], data = [none]
break;
}
}
}
if (StringUtils.isEmpty(content)) {
if (isCheckOut(_uiField) && icon != null) {
ret = new IconCheckOutLink(_wicketId, Model.of(_uiField), content, icon); // depends on control dependency: [if], data = [none]
} else {
ret = new LabelField(_wicketId, Model.of(""), _uiField); // depends on control dependency: [if], data = [none]
}
} else if (isCheckOut(_uiField)) {
if (icon == null) {
ret = new CheckOutLink(_wicketId, Model.of(_uiField), content); // depends on control dependency: [if], data = [none]
} else {
ret = new IconCheckOutLink(_wicketId, Model.of(_uiField), content, icon); // depends on control dependency: [if], data = [none]
}
} else {
// evaluate which kind of link must be done
IRequestablePage page = null;
IRequestablePage calledByPage = null;
if (RequestCycle.get().getActiveRequestHandler() instanceof IPageRequestHandler) {
page = ((IPageRequestHandler) RequestCycle.get().getActiveRequestHandler()).getPage(); // depends on control dependency: [if], data = [none]
if (page != null && page instanceof AbstractContentPage) {
final PageReference pageRef = ((AbstractContentPage) page).getCalledByPageReference();
if (pageRef != null) {
calledByPage = pageRef.getPage(); // depends on control dependency: [if], data = [none]
}
}
}
// first priority is the pagePosition than..
boolean ajax = page != null
&& ((Component) page).getDefaultModelObject() instanceof IPageObject
&& PagePosition.TREE.equals(((IPageObject) ((Component) page).getDefaultModelObject())
.getPagePosition());
if (!ajax) {
ajax = _uiField.getParent() != null
&& _uiField.getParent() instanceof IPageObject
&& PagePosition.TREE.equals(((IPageObject) _uiField.getParent()).getPagePosition()); // depends on control dependency: [if], data = [none]
}
if (!ajax) {
// ajax if the page or the reference is a ContentContainerPage,
// or the table was called as part of a WizardCall meaning connect is done
// or it was opened after a form in modal mode
ajax = page != null && (page instanceof ContentContainerPage
|| calledByPage instanceof ContentContainerPage)
|| page instanceof TablePage
&& ((AbstractUIPageObject) ((Component) page).getDefaultModelObject())
.isPartOfWizardCall()
// form opened modal over a form
|| page instanceof FormPage && calledByPage instanceof FormPage
&& Target.MODAL.equals(((UIForm) ((Component) page).getDefaultModelObject()).getTarget())
// form opened modal over a table that itself is part of a contentcontainer
|| page instanceof FormPage
&& Target.MODAL.equals(((UIForm) ((Component) page).getDefaultModelObject()).getTarget())
&& calledByPage instanceof TablePage
&& ((TablePage) calledByPage).getCalledByPageReference() != null
&& !(((TablePage) calledByPage).getCalledByPageReference().getPage() instanceof MainPage); // depends on control dependency: [if], data = [none]
}
// verify ajax by checking if is not a recent link
if (ajax && RequestCycle.get().getActiveRequestHandler() instanceof IComponentRequestHandler) {
ajax = ajax && !(((IComponentRequestHandler) RequestCycle.get().getActiveRequestHandler())
.getComponent() instanceof RecentLink); // depends on control dependency: [if], data = [none]
}
// check if for searchmode the page is in an pop up window
boolean isInPopUp = false;
if (_uiField.getParent().isSearchMode()) {
if (((IWizardElement) _uiField.getParent()).isWizardCall()) {
final IWizardElement pageObj = ((IWizardElement) _uiField
.getParent()).getUIWizardObject().getWizardElement().get(0);
if (pageObj instanceof IPageObject) {
isInPopUp = PagePosition.POPUP.equals(((IPageObject) pageObj).getPagePosition()); // depends on control dependency: [if], data = [none]
} else {
isInPopUp = Target.POPUP.equals(((ICmdUIObject) pageObj).getCommand().getTarget()); // depends on control dependency: [if], data = [none]
}
}
}
if (icon == null) {
if (ajax) {
// checking if is a link of a structurbrowser browserfield
if (page instanceof StructurBrowserPage
&& ((UIStructurBrowser) _uiField.getParent()).isBrowserField(_uiField)) {
ret = new LoadInTargetAjaxLink(_wicketId, Model.of(_uiField), content, ScriptTarget.TOP); // depends on control dependency: [if], data = [none]
} else {
ret = new MenuContentLink(_wicketId, Model.of(_uiField), content); // depends on control dependency: [if], data = [none]
}
} else if (isInPopUp) {
ret = new LoadInTargetAjaxLink(_wicketId, Model.of(_uiField), content, ScriptTarget.OPENER); // depends on control dependency: [if], data = [none]
} else {
ret = new ContentContainerLink(_wicketId, Model.of(_uiField), content); // depends on control dependency: [if], data = [none]
}
} else {
if (ajax) {
ret = new IconMenuContentLink(_wicketId, Model.of(_uiField), content, icon); // depends on control dependency: [if], data = [none]
} else if (isInPopUp) {
ret = new IconLoadInTargetAjaxLink(_wicketId, Model.of(_uiField), content,
ScriptTarget.OPENER, icon); // depends on control dependency: [if], data = [none]
} else {
ret = new IconContentContainerLink(_wicketId, Model.of(_uiField), content, icon); // depends on control dependency: [if], data = [none]
}
}
}
}
return ret;
} } |
public class class_name {
protected void writeObjectHeader(List<Object> list) {
// action
list.add("{\"" + getOperation() + "\":{");
// flag indicating whether a comma needs to be added between fields
boolean commaMightBeNeeded = false;
commaMightBeNeeded = addExtractorOrDynamicValue(list, getMetadataExtractorOrFallback(Metadata.INDEX, indexExtractor), "", commaMightBeNeeded);
commaMightBeNeeded = addExtractorOrDynamicValue(list, getMetadataExtractorOrFallback(Metadata.TYPE, typeExtractor), "\"_type\":", commaMightBeNeeded);
commaMightBeNeeded = id(list, commaMightBeNeeded);
commaMightBeNeeded = addExtractorOrDynamicValue(list, getMetadataExtractorOrFallback(Metadata.PARENT, parentExtractor), requestParameterNames.parent, commaMightBeNeeded);
commaMightBeNeeded = addExtractorOrDynamicValueAsFieldWriter(list, getMetadataExtractorOrFallback(Metadata.ROUTING, routingExtractor), requestParameterNames.routing, commaMightBeNeeded);
commaMightBeNeeded = addExtractorOrDynamicValue(list, getMetadataExtractorOrFallback(Metadata.TTL, ttlExtractor), "\"_ttl\":", commaMightBeNeeded);
commaMightBeNeeded = addExtractorOrDynamicValue(list, getMetadataExtractorOrFallback(Metadata.TIMESTAMP, timestampExtractor), "\"_timestamp\":", commaMightBeNeeded);
// version & version_type fields
Object versionField = getMetadataExtractorOrFallback(Metadata.VERSION, versionExtractor);
if (versionField != null) {
if (commaMightBeNeeded) {
list.add(",");
commaMightBeNeeded = false;
}
commaMightBeNeeded = true;
list.add(requestParameterNames.version);
list.add(versionField);
// version_type - only needed when a version is specified
Object versionTypeField = getMetadataExtractorOrFallback(Metadata.VERSION_TYPE, versionTypeExtractor);
if (versionTypeField != null) {
if (commaMightBeNeeded) {
list.add(",");
commaMightBeNeeded = false;
}
commaMightBeNeeded = true;
list.add(requestParameterNames.versionType);
list.add(versionTypeField);
}
}
// useful for update command
otherHeader(list, commaMightBeNeeded);
list.add("}}\n");
} } | public class class_name {
protected void writeObjectHeader(List<Object> list) {
// action
list.add("{\"" + getOperation() + "\":{");
// flag indicating whether a comma needs to be added between fields
boolean commaMightBeNeeded = false;
commaMightBeNeeded = addExtractorOrDynamicValue(list, getMetadataExtractorOrFallback(Metadata.INDEX, indexExtractor), "", commaMightBeNeeded);
commaMightBeNeeded = addExtractorOrDynamicValue(list, getMetadataExtractorOrFallback(Metadata.TYPE, typeExtractor), "\"_type\":", commaMightBeNeeded);
commaMightBeNeeded = id(list, commaMightBeNeeded);
commaMightBeNeeded = addExtractorOrDynamicValue(list, getMetadataExtractorOrFallback(Metadata.PARENT, parentExtractor), requestParameterNames.parent, commaMightBeNeeded);
commaMightBeNeeded = addExtractorOrDynamicValueAsFieldWriter(list, getMetadataExtractorOrFallback(Metadata.ROUTING, routingExtractor), requestParameterNames.routing, commaMightBeNeeded);
commaMightBeNeeded = addExtractorOrDynamicValue(list, getMetadataExtractorOrFallback(Metadata.TTL, ttlExtractor), "\"_ttl\":", commaMightBeNeeded);
commaMightBeNeeded = addExtractorOrDynamicValue(list, getMetadataExtractorOrFallback(Metadata.TIMESTAMP, timestampExtractor), "\"_timestamp\":", commaMightBeNeeded);
// version & version_type fields
Object versionField = getMetadataExtractorOrFallback(Metadata.VERSION, versionExtractor);
if (versionField != null) {
if (commaMightBeNeeded) {
list.add(","); // depends on control dependency: [if], data = [none]
commaMightBeNeeded = false; // depends on control dependency: [if], data = [none]
}
commaMightBeNeeded = true; // depends on control dependency: [if], data = [none]
list.add(requestParameterNames.version); // depends on control dependency: [if], data = [none]
list.add(versionField); // depends on control dependency: [if], data = [(versionField]
// version_type - only needed when a version is specified
Object versionTypeField = getMetadataExtractorOrFallback(Metadata.VERSION_TYPE, versionTypeExtractor);
if (versionTypeField != null) {
if (commaMightBeNeeded) {
list.add(","); // depends on control dependency: [if], data = [none]
commaMightBeNeeded = false; // depends on control dependency: [if], data = [none]
}
commaMightBeNeeded = true; // depends on control dependency: [if], data = [none]
list.add(requestParameterNames.versionType); // depends on control dependency: [if], data = [none]
list.add(versionTypeField); // depends on control dependency: [if], data = [(versionTypeField]
}
}
// useful for update command
otherHeader(list, commaMightBeNeeded);
list.add("}}\n");
} } |
public class class_name {
public List<FieldRef> getFields() {
Map<String,FieldRef> fields = new LinkedHashMap<String,FieldRef>();
for (Klass<?> k = this; k!=null; k=k.getSuperClass()) {
for (FieldRef f : k.getDeclaredFields()) {
String name = f.getName();
if (!fields.containsKey(name) && f.isRoutable()) {
fields.put(name,f);
}
}
}
return new ArrayList<FieldRef>(fields.values());
} } | public class class_name {
public List<FieldRef> getFields() {
Map<String,FieldRef> fields = new LinkedHashMap<String,FieldRef>();
for (Klass<?> k = this; k!=null; k=k.getSuperClass()) {
for (FieldRef f : k.getDeclaredFields()) {
String name = f.getName();
if (!fields.containsKey(name) && f.isRoutable()) {
fields.put(name,f); // depends on control dependency: [if], data = [none]
}
}
}
return new ArrayList<FieldRef>(fields.values());
} } |
public class class_name {
public void setResultList(java.util.Collection<BatchDetectEntitiesItemResult> resultList) {
if (resultList == null) {
this.resultList = null;
return;
}
this.resultList = new java.util.ArrayList<BatchDetectEntitiesItemResult>(resultList);
} } | public class class_name {
public void setResultList(java.util.Collection<BatchDetectEntitiesItemResult> resultList) {
if (resultList == null) {
this.resultList = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.resultList = new java.util.ArrayList<BatchDetectEntitiesItemResult>(resultList);
} } |
public class class_name {
public List<CmpFieldType<EntityBeanType<T>>> getAllCmpField()
{
List<CmpFieldType<EntityBeanType<T>>> list = new ArrayList<CmpFieldType<EntityBeanType<T>>>();
List<Node> nodeList = childNode.get("cmp-field");
for(Node node: nodeList)
{
CmpFieldType<EntityBeanType<T>> type = new CmpFieldTypeImpl<EntityBeanType<T>>(this, "cmp-field", childNode, node);
list.add(type);
}
return list;
} } | public class class_name {
public List<CmpFieldType<EntityBeanType<T>>> getAllCmpField()
{
List<CmpFieldType<EntityBeanType<T>>> list = new ArrayList<CmpFieldType<EntityBeanType<T>>>();
List<Node> nodeList = childNode.get("cmp-field");
for(Node node: nodeList)
{
CmpFieldType<EntityBeanType<T>> type = new CmpFieldTypeImpl<EntityBeanType<T>>(this, "cmp-field", childNode, node);
list.add(type); // depends on control dependency: [for], data = [none]
}
return list;
} } |
public class class_name {
@Override
public List<Host> getSeedHosts() {
List<Host> hosts = new ArrayList<Host>();
if (seeds != null) {
for (String seed : seeds.split(",")) {
seed = seed.trim();
if (seed.length() > 0) {
hosts.add(new Host(seed, this.port));
}
}
}
return hosts;
} } | public class class_name {
@Override
public List<Host> getSeedHosts() {
List<Host> hosts = new ArrayList<Host>();
if (seeds != null) {
for (String seed : seeds.split(",")) {
seed = seed.trim(); // depends on control dependency: [for], data = [seed]
if (seed.length() > 0) {
hosts.add(new Host(seed, this.port)); // depends on control dependency: [if], data = [none]
}
}
}
return hosts;
} } |
public class class_name {
private void checkTable() {
// Documentation says that "0 xxx" means data-aging is disabled.
if (m_retentionAge.getValue() == 0) {
m_logger.info("Data aging disabled for table: {}", m_tableDef.getTableName());
return;
}
m_logger.info("Checking expired objects for: {}", m_tableDef.getTableName());
GregorianCalendar checkDate = new GregorianCalendar(Utils.UTC_TIMEZONE);
GregorianCalendar expireDate = m_retentionAge.getExpiredDate(checkDate);
int objsExpired = 0;
String fixedQuery = buildFixedQuery(expireDate);
String contToken = null;
StringBuilder uriParam = new StringBuilder();
do {
uriParam.setLength(0);
uriParam.append(fixedQuery);
if (!Utils.isEmpty(contToken)) {
uriParam.append("&g=");
uriParam.append(contToken);
}
ObjectQuery objQuery = new ObjectQuery(m_tableDef, uriParam.toString());
SearchResultList resultList =
SpiderService.instance().objectQuery(m_tableDef, objQuery);
List<String> objIDs = new ArrayList<>();
for (SearchResult result : resultList.results) {
objIDs.add(result.id());
}
if (deleteBatch(objIDs)) {
contToken = resultList.continuation_token;
} else {
contToken = null;
}
objsExpired += objIDs.size();
reportProgress("Expired " + objsExpired + " objects");
} while (!Utils.isEmpty(contToken));
m_logger.info("Deleted {} objects for {}", objsExpired, m_tableDef.getTableName());
} } | public class class_name {
private void checkTable() {
// Documentation says that "0 xxx" means data-aging is disabled.
if (m_retentionAge.getValue() == 0) {
m_logger.info("Data aging disabled for table: {}", m_tableDef.getTableName()); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
m_logger.info("Checking expired objects for: {}", m_tableDef.getTableName());
GregorianCalendar checkDate = new GregorianCalendar(Utils.UTC_TIMEZONE);
GregorianCalendar expireDate = m_retentionAge.getExpiredDate(checkDate);
int objsExpired = 0;
String fixedQuery = buildFixedQuery(expireDate);
String contToken = null;
StringBuilder uriParam = new StringBuilder();
do {
uriParam.setLength(0);
uriParam.append(fixedQuery);
if (!Utils.isEmpty(contToken)) {
uriParam.append("&g="); // depends on control dependency: [if], data = [none]
uriParam.append(contToken); // depends on control dependency: [if], data = [none]
}
ObjectQuery objQuery = new ObjectQuery(m_tableDef, uriParam.toString());
SearchResultList resultList =
SpiderService.instance().objectQuery(m_tableDef, objQuery);
List<String> objIDs = new ArrayList<>();
for (SearchResult result : resultList.results) {
objIDs.add(result.id()); // depends on control dependency: [for], data = [result]
}
if (deleteBatch(objIDs)) {
contToken = resultList.continuation_token; // depends on control dependency: [if], data = [none]
} else {
contToken = null; // depends on control dependency: [if], data = [none]
}
objsExpired += objIDs.size();
reportProgress("Expired " + objsExpired + " objects");
} while (!Utils.isEmpty(contToken));
m_logger.info("Deleted {} objects for {}", objsExpired, m_tableDef.getTableName());
} } |
public class class_name {
public Integer getZoomLevelMax(int zoomLevel) {
Integer zoomMax = zoomLevelMax.get(zoomLevel);
if (zoomMax == null) {
zoomMax = 0;
}
return zoomMax;
} } | public class class_name {
public Integer getZoomLevelMax(int zoomLevel) {
Integer zoomMax = zoomLevelMax.get(zoomLevel);
if (zoomMax == null) {
zoomMax = 0; // depends on control dependency: [if], data = [none]
}
return zoomMax;
} } |
public class class_name {
@Override
public void visitBeanDefinitionConstructor(AnnotationMetadata annotationMetadata,
boolean requiresReflection) {
if (constructorVisitor == null) {
// first build the constructor
visitBeanDefinitionConstructorInternal(annotationMetadata, requiresReflection, Collections.emptyMap(), null, null);
// now prepare the implementation of the build method. See BeanFactory interface
visitBuildMethodDefinition(annotationMetadata, Collections.emptyMap(), Collections.emptyMap());
// now override the injectBean method
visitInjectMethodDefinition();
}
} } | public class class_name {
@Override
public void visitBeanDefinitionConstructor(AnnotationMetadata annotationMetadata,
boolean requiresReflection) {
if (constructorVisitor == null) {
// first build the constructor
visitBeanDefinitionConstructorInternal(annotationMetadata, requiresReflection, Collections.emptyMap(), null, null); // depends on control dependency: [if], data = [null)]
// now prepare the implementation of the build method. See BeanFactory interface
visitBuildMethodDefinition(annotationMetadata, Collections.emptyMap(), Collections.emptyMap()); // depends on control dependency: [if], data = [none]
// now override the injectBean method
visitInjectMethodDefinition(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private int getQuoteToken( String content, int startOffset, int endOffset )
{
String quoteDelimiter = content.substring( startOffset, startOffset + 1 );
int index;
int endOfQuote = startOffset;
int endOfToken = startOffset + 1;
while( endOfToken <= endOffset )
{
if( isDelimiter( content.substring( endOfToken, endOfToken + 1 ) ) )
{
break;
}
endOfToken++;
}
index = content.indexOf( quoteDelimiter, endOfQuote + 1 );
if( (index < 0) || (index > endOffset) )
{
endOfQuote = endOffset;
}
else
{
endOfQuote = index;
}
if( isError( startOffset, endOfQuote - startOffset + 1 ) )
{
setCharacterAttributes( startOffset, endOfQuote - startOffset + 1, _error, true );
return endOfQuote + 1;
}
if( isWarning( startOffset, endOfQuote - startOffset + 1 ) )
{
setCharacterAttributes( startOffset, endOfQuote - startOffset + 1, _warning, true );
return endOfQuote + 1;
}
setCharacterAttributes( startOffset, endOfQuote - startOffset + 1, _stringLiteral, false );
return endOfQuote + 1;
} } | public class class_name {
private int getQuoteToken( String content, int startOffset, int endOffset )
{
String quoteDelimiter = content.substring( startOffset, startOffset + 1 );
int index;
int endOfQuote = startOffset;
int endOfToken = startOffset + 1;
while( endOfToken <= endOffset )
{
if( isDelimiter( content.substring( endOfToken, endOfToken + 1 ) ) )
{
break;
}
endOfToken++; // depends on control dependency: [while], data = [none]
}
index = content.indexOf( quoteDelimiter, endOfQuote + 1 );
if( (index < 0) || (index > endOffset) )
{
endOfQuote = endOffset; // depends on control dependency: [if], data = [none]
}
else
{
endOfQuote = index; // depends on control dependency: [if], data = [none]
}
if( isError( startOffset, endOfQuote - startOffset + 1 ) )
{
setCharacterAttributes( startOffset, endOfQuote - startOffset + 1, _error, true ); // depends on control dependency: [if], data = [none]
return endOfQuote + 1; // depends on control dependency: [if], data = [none]
}
if( isWarning( startOffset, endOfQuote - startOffset + 1 ) )
{
setCharacterAttributes( startOffset, endOfQuote - startOffset + 1, _warning, true ); // depends on control dependency: [if], data = [none]
return endOfQuote + 1; // depends on control dependency: [if], data = [none]
}
setCharacterAttributes( startOffset, endOfQuote - startOffset + 1, _stringLiteral, false );
return endOfQuote + 1;
} } |
public class class_name {
public static <T> List<T> randomEles(List<T> list, int count) {
final List<T> result = new ArrayList<T>(count);
int limit = list.size();
while (result.size() < count) {
result.add(randomEle(list, limit));
}
return result;
} } | public class class_name {
public static <T> List<T> randomEles(List<T> list, int count) {
final List<T> result = new ArrayList<T>(count);
int limit = list.size();
while (result.size() < count) {
result.add(randomEle(list, limit));
// depends on control dependency: [while], data = [none]
}
return result;
} } |
public class class_name {
protected static AgroalConnectionFactoryConfigurationSupplier connectionFactoryConfiguration(OperationContext context, ModelNode model) throws OperationFailedException {
AgroalConnectionFactoryConfigurationSupplier configuration = new AgroalConnectionFactoryConfigurationSupplier();
if (AbstractDataSourceDefinition.URL_ATTRIBUTE.resolveModelAttribute(context, model).isDefined()) {
configuration.jdbcUrl(AbstractDataSourceDefinition.URL_ATTRIBUTE.resolveModelAttribute(context, model).asString());
}
if (AbstractDataSourceDefinition.NEW_CONNECTION_SQL_ATTRIBUTE.resolveModelAttribute(context, model).isDefined()) {
configuration.initialSql(AbstractDataSourceDefinition.NEW_CONNECTION_SQL_ATTRIBUTE.resolveModelAttribute(context, model).asString());
}
if (AbstractDataSourceDefinition.TRANSACTION_ISOLATION_ATTRIBUTE.resolveModelAttribute(context, model).isDefined()) {
configuration.jdbcTransactionIsolation(TransactionIsolation.valueOf(AbstractDataSourceDefinition.TRANSACTION_ISOLATION_ATTRIBUTE.resolveModelAttribute(context, model).asString()));
}
if (AbstractDataSourceDefinition.CONNECTION_PROPERTIES_ATTRIBUTE.resolveModelAttribute(context, model).isDefined()) {
for (Property jdbcProperty : AbstractDataSourceDefinition.CONNECTION_PROPERTIES_ATTRIBUTE.resolveModelAttribute(context, model).asPropertyList()) {
configuration.jdbcProperty(jdbcProperty.getName(), jdbcProperty.getValue().asString());
}
}
if (AbstractDataSourceDefinition.USERNAME_ATTRIBUTE.resolveModelAttribute(context, model).isDefined()) {
configuration.principal(new NamePrincipal(AbstractDataSourceDefinition.USERNAME_ATTRIBUTE.resolveModelAttribute(context, model).asString()));
}
if (AbstractDataSourceDefinition.PASSWORD_ATTRIBUTE.resolveModelAttribute(context, model).isDefined()) {
configuration.credential(new SimplePassword(AbstractDataSourceDefinition.PASSWORD_ATTRIBUTE.resolveModelAttribute(context, model).asString()));
}
return configuration;
} } | public class class_name {
protected static AgroalConnectionFactoryConfigurationSupplier connectionFactoryConfiguration(OperationContext context, ModelNode model) throws OperationFailedException {
AgroalConnectionFactoryConfigurationSupplier configuration = new AgroalConnectionFactoryConfigurationSupplier();
if (AbstractDataSourceDefinition.URL_ATTRIBUTE.resolveModelAttribute(context, model).isDefined()) {
configuration.jdbcUrl(AbstractDataSourceDefinition.URL_ATTRIBUTE.resolveModelAttribute(context, model).asString());
}
if (AbstractDataSourceDefinition.NEW_CONNECTION_SQL_ATTRIBUTE.resolveModelAttribute(context, model).isDefined()) {
configuration.initialSql(AbstractDataSourceDefinition.NEW_CONNECTION_SQL_ATTRIBUTE.resolveModelAttribute(context, model).asString());
}
if (AbstractDataSourceDefinition.TRANSACTION_ISOLATION_ATTRIBUTE.resolveModelAttribute(context, model).isDefined()) {
configuration.jdbcTransactionIsolation(TransactionIsolation.valueOf(AbstractDataSourceDefinition.TRANSACTION_ISOLATION_ATTRIBUTE.resolveModelAttribute(context, model).asString()));
}
if (AbstractDataSourceDefinition.CONNECTION_PROPERTIES_ATTRIBUTE.resolveModelAttribute(context, model).isDefined()) {
for (Property jdbcProperty : AbstractDataSourceDefinition.CONNECTION_PROPERTIES_ATTRIBUTE.resolveModelAttribute(context, model).asPropertyList()) {
configuration.jdbcProperty(jdbcProperty.getName(), jdbcProperty.getValue().asString()); // depends on control dependency: [for], data = [jdbcProperty]
}
}
if (AbstractDataSourceDefinition.USERNAME_ATTRIBUTE.resolveModelAttribute(context, model).isDefined()) {
configuration.principal(new NamePrincipal(AbstractDataSourceDefinition.USERNAME_ATTRIBUTE.resolveModelAttribute(context, model).asString()));
}
if (AbstractDataSourceDefinition.PASSWORD_ATTRIBUTE.resolveModelAttribute(context, model).isDefined()) {
configuration.credential(new SimplePassword(AbstractDataSourceDefinition.PASSWORD_ATTRIBUTE.resolveModelAttribute(context, model).asString()));
}
return configuration;
} } |
public class class_name {
public void resetPageCount() {
pageN = 0;
DocListener listener;
for (Iterator iterator = listeners.iterator(); iterator.hasNext();) {
listener = (DocListener) iterator.next();
listener.resetPageCount();
}
} } | public class class_name {
public void resetPageCount() {
pageN = 0;
DocListener listener;
for (Iterator iterator = listeners.iterator(); iterator.hasNext();) {
listener = (DocListener) iterator.next(); // depends on control dependency: [for], data = [iterator]
listener.resetPageCount(); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
private void cleanupBackupDir(int keep) {
File[] backupDirFiles = getSortedBackupDirFiles();
if (backupDirFiles.length > keep) {
for (int i = keep; i < backupDirFiles.length; i++) {
backupDirFiles[i].delete();
}
}
} } | public class class_name {
private void cleanupBackupDir(int keep) {
File[] backupDirFiles = getSortedBackupDirFiles();
if (backupDirFiles.length > keep) {
for (int i = keep; i < backupDirFiles.length; i++) {
backupDirFiles[i].delete(); // depends on control dependency: [for], data = [i]
}
}
} } |
public class class_name {
@Nonnull
public static String getPathInWorkspace(@Nonnull final String absoluteFilePath, @Nonnull FilePath workspace) {
boolean windows = FileUtils.isWindows(workspace);
final String workspaceRemote = workspace.getRemote();
String sanitizedAbsoluteFilePath;
String sanitizedWorkspaceRemote;
if (windows) {
// sanitize to workaround JENKINS-44088
sanitizedWorkspaceRemote = workspaceRemote.replace('/', '\\');
sanitizedAbsoluteFilePath = absoluteFilePath.replace('/', '\\');
} else if (workspaceRemote.startsWith("/var/") && absoluteFilePath.startsWith("/private/var/")) {
// workaround MacOSX special folders path
// eg String workspace = "/var/folders/lq/50t8n2nx7l316pwm8gc_2rt40000gn/T/jenkinsTests.tmp/jenkins3845105900446934883test/workspace/build-on-master-with-tool-provided-maven";
// eg String absolutePath = "/private/var/folders/lq/50t8n2nx7l316pwm8gc_2rt40000gn/T/jenkinsTests.tmp/jenkins3845105900446934883test/workspace/build-on-master-with-tool-provided-maven/pom.xml";
sanitizedWorkspaceRemote = workspaceRemote;
sanitizedAbsoluteFilePath = absoluteFilePath.substring("/private".length());
} else {
sanitizedAbsoluteFilePath = absoluteFilePath;
sanitizedWorkspaceRemote = workspaceRemote;
}
if (StringUtils.startsWithIgnoreCase(sanitizedAbsoluteFilePath, sanitizedWorkspaceRemote)) {
// OK
} else if (sanitizedWorkspaceRemote.contains("/workspace/") && sanitizedAbsoluteFilePath.contains("/workspace/")) {
// workaround JENKINS-46084
// sanitizedAbsoluteFilePath = '/app/Jenkins/home/workspace/testjob/pom.xml'
// sanitizedWorkspaceRemote = '/var/lib/jenkins/workspace/testjob'
sanitizedAbsoluteFilePath = "/workspace/" + StringUtils.substringAfter(sanitizedAbsoluteFilePath, "/workspace/");
sanitizedWorkspaceRemote = "/workspace/" + StringUtils.substringAfter(sanitizedWorkspaceRemote, "/workspace/");
} else if (sanitizedWorkspaceRemote.endsWith("/workspace") && sanitizedAbsoluteFilePath.contains("/workspace/")) {
// workspace = "/var/lib/jenkins/jobs/Test-Pipeline/workspace";
// absolutePath = "/storage/jenkins/jobs/Test-Pipeline/workspace/pom.xml";
sanitizedAbsoluteFilePath = "workspace/" + StringUtils.substringAfter(sanitizedAbsoluteFilePath, "/workspace/");
sanitizedWorkspaceRemote = "workspace/";
} else {
throw new IllegalArgumentException("Cannot relativize '" + absoluteFilePath + "' relatively to '" + workspace.getRemote() + "'");
}
String relativePath = StringUtils.removeStartIgnoreCase(sanitizedAbsoluteFilePath, sanitizedWorkspaceRemote);
String fileSeparator = windows ? "\\" : "/";
if (relativePath.startsWith(fileSeparator)) {
relativePath = relativePath.substring(fileSeparator.length());
}
LOGGER.log(Level.FINEST, "getPathInWorkspace({0}, {1}: {2}", new Object[]{absoluteFilePath, workspaceRemote, relativePath});
return relativePath;
} } | public class class_name {
@Nonnull
public static String getPathInWorkspace(@Nonnull final String absoluteFilePath, @Nonnull FilePath workspace) {
boolean windows = FileUtils.isWindows(workspace);
final String workspaceRemote = workspace.getRemote();
String sanitizedAbsoluteFilePath;
String sanitizedWorkspaceRemote;
if (windows) {
// sanitize to workaround JENKINS-44088
sanitizedWorkspaceRemote = workspaceRemote.replace('/', '\\'); // depends on control dependency: [if], data = [none]
sanitizedAbsoluteFilePath = absoluteFilePath.replace('/', '\\'); // depends on control dependency: [if], data = [none]
} else if (workspaceRemote.startsWith("/var/") && absoluteFilePath.startsWith("/private/var/")) {
// workaround MacOSX special folders path
// eg String workspace = "/var/folders/lq/50t8n2nx7l316pwm8gc_2rt40000gn/T/jenkinsTests.tmp/jenkins3845105900446934883test/workspace/build-on-master-with-tool-provided-maven";
// eg String absolutePath = "/private/var/folders/lq/50t8n2nx7l316pwm8gc_2rt40000gn/T/jenkinsTests.tmp/jenkins3845105900446934883test/workspace/build-on-master-with-tool-provided-maven/pom.xml";
sanitizedWorkspaceRemote = workspaceRemote; // depends on control dependency: [if], data = [none]
sanitizedAbsoluteFilePath = absoluteFilePath.substring("/private".length()); // depends on control dependency: [if], data = [none]
} else {
sanitizedAbsoluteFilePath = absoluteFilePath; // depends on control dependency: [if], data = [none]
sanitizedWorkspaceRemote = workspaceRemote; // depends on control dependency: [if], data = [none]
}
if (StringUtils.startsWithIgnoreCase(sanitizedAbsoluteFilePath, sanitizedWorkspaceRemote)) {
// OK
} else if (sanitizedWorkspaceRemote.contains("/workspace/") && sanitizedAbsoluteFilePath.contains("/workspace/")) {
// workaround JENKINS-46084
// sanitizedAbsoluteFilePath = '/app/Jenkins/home/workspace/testjob/pom.xml'
// sanitizedWorkspaceRemote = '/var/lib/jenkins/workspace/testjob'
sanitizedAbsoluteFilePath = "/workspace/" + StringUtils.substringAfter(sanitizedAbsoluteFilePath, "/workspace/"); // depends on control dependency: [if], data = [none]
sanitizedWorkspaceRemote = "/workspace/" + StringUtils.substringAfter(sanitizedWorkspaceRemote, "/workspace/"); // depends on control dependency: [if], data = [none]
} else if (sanitizedWorkspaceRemote.endsWith("/workspace") && sanitizedAbsoluteFilePath.contains("/workspace/")) {
// workspace = "/var/lib/jenkins/jobs/Test-Pipeline/workspace";
// absolutePath = "/storage/jenkins/jobs/Test-Pipeline/workspace/pom.xml";
sanitizedAbsoluteFilePath = "workspace/" + StringUtils.substringAfter(sanitizedAbsoluteFilePath, "/workspace/"); // depends on control dependency: [if], data = [none]
sanitizedWorkspaceRemote = "workspace/"; // depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException("Cannot relativize '" + absoluteFilePath + "' relatively to '" + workspace.getRemote() + "'");
}
String relativePath = StringUtils.removeStartIgnoreCase(sanitizedAbsoluteFilePath, sanitizedWorkspaceRemote);
String fileSeparator = windows ? "\\" : "/";
if (relativePath.startsWith(fileSeparator)) {
relativePath = relativePath.substring(fileSeparator.length()); // depends on control dependency: [if], data = [none]
}
LOGGER.log(Level.FINEST, "getPathInWorkspace({0}, {1}: {2}", new Object[]{absoluteFilePath, workspaceRemote, relativePath});
return relativePath;
} } |
public class class_name {
private Stat getStat(String kind)
{
Stat stat = this.stats.get(kind);
if (stat == null)
{
stat = new Stat();
this.stats.put(kind, stat);
}
return stat;
} } | public class class_name {
private Stat getStat(String kind)
{
Stat stat = this.stats.get(kind);
if (stat == null)
{
stat = new Stat(); // depends on control dependency: [if], data = [none]
this.stats.put(kind, stat); // depends on control dependency: [if], data = [none]
}
return stat;
} } |
public class class_name {
private static double roundDown(final double n, final int p) {
double retval;
if (Double.isNaN(n) || Double.isInfinite(n)) {
retval = Double.NaN;
} else {
if (p != 0) {
final double temp = Math.pow(10, p);
retval = sign(n) * Math.round(Math.abs(n) * temp - ROUNDING_UP_FLOAT) / temp;
} else {
retval = (long) n;
}
}
return retval;
} } | public class class_name {
private static double roundDown(final double n, final int p) {
double retval;
if (Double.isNaN(n) || Double.isInfinite(n)) {
retval = Double.NaN;
// depends on control dependency: [if], data = [none]
} else {
if (p != 0) {
final double temp = Math.pow(10, p);
retval = sign(n) * Math.round(Math.abs(n) * temp - ROUNDING_UP_FLOAT) / temp;
// depends on control dependency: [if], data = [none]
} else {
retval = (long) n;
// depends on control dependency: [if], data = [none]
}
}
return retval;
} } |
public class class_name {
public void setIgnoreEMail(String serverName, String ignoreEMail) {
if (serverName != null) {
if (ignoreEMail != null) {
ignoreEMails.put(serverName, ignoreEMail);
} else {
ignoreEMails.remove(serverName);
}
}
} } | public class class_name {
public void setIgnoreEMail(String serverName, String ignoreEMail) {
if (serverName != null) {
if (ignoreEMail != null) {
ignoreEMails.put(serverName, ignoreEMail); // depends on control dependency: [if], data = [none]
} else {
ignoreEMails.remove(serverName); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private static Reader readerFromUrl(String resourceName) throws IOException {
URL resourceUrl = TemplateVars.class.getResource(resourceName);
InputStream in;
try {
if (resourceUrl.getProtocol().equalsIgnoreCase("file")) {
in = inputStreamFromFile(resourceUrl);
} else if (resourceUrl.getProtocol().equalsIgnoreCase("jar")) {
in = inputStreamFromJar(resourceUrl);
} else {
throw new AssertionError("Template fallback logic fails for: " + resourceUrl);
}
} catch (URISyntaxException e) {
throw new IOException(e);
}
return new InputStreamReader(in, StandardCharsets.UTF_8);
} } | public class class_name {
private static Reader readerFromUrl(String resourceName) throws IOException {
URL resourceUrl = TemplateVars.class.getResource(resourceName);
InputStream in;
try {
if (resourceUrl.getProtocol().equalsIgnoreCase("file")) {
in = inputStreamFromFile(resourceUrl); // depends on control dependency: [if], data = [none]
} else if (resourceUrl.getProtocol().equalsIgnoreCase("jar")) {
in = inputStreamFromJar(resourceUrl); // depends on control dependency: [if], data = [none]
} else {
throw new AssertionError("Template fallback logic fails for: " + resourceUrl);
}
} catch (URISyntaxException e) {
throw new IOException(e);
}
return new InputStreamReader(in, StandardCharsets.UTF_8);
} } |
public class class_name {
@Override
@SuppressWarnings("FutureReturnValueIgnored")
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
if (failCause != null) {
promise.setFailure(failCause);
ReferenceCountUtil.release(msg);
} else {
bufferedWrites.add(new ChannelWrite(msg, promise));
}
} } | public class class_name {
@Override
@SuppressWarnings("FutureReturnValueIgnored")
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
if (failCause != null) {
promise.setFailure(failCause); // depends on control dependency: [if], data = [(failCause]
ReferenceCountUtil.release(msg); // depends on control dependency: [if], data = [none]
} else {
bufferedWrites.add(new ChannelWrite(msg, promise)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private Document buildDocument(String location) {
try {
return documentBuilderFactory.newDocumentBuilder().parse(ClassPathResource.asInputStream(location));
} catch (ParserConfigurationException | SAXException | IOException | RuntimeException e) {
throw new XmlRuleSetException("Could not parse RuleSet from given location '" + location + "'.", e);
}
} } | public class class_name {
private Document buildDocument(String location) {
try {
return documentBuilderFactory.newDocumentBuilder().parse(ClassPathResource.asInputStream(location)); // depends on control dependency: [try], data = [none]
} catch (ParserConfigurationException | SAXException | IOException | RuntimeException e) {
throw new XmlRuleSetException("Could not parse RuleSet from given location '" + location + "'.", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public List<T> getMore() {
assert m_itemIndex < m_items.size();
List<T> result = new ArrayList<T>();
int totalSize = 0;
while ((m_itemIndex < m_items.size()) && (totalSize < m_batchSize)) {
T item = m_items.get(m_itemIndex);
result.add(item);
m_itemIndex += 1;
totalSize += item.getSize();
}
return result;
} } | public class class_name {
public List<T> getMore() {
assert m_itemIndex < m_items.size();
List<T> result = new ArrayList<T>();
int totalSize = 0;
while ((m_itemIndex < m_items.size()) && (totalSize < m_batchSize)) {
T item = m_items.get(m_itemIndex);
result.add(item); // depends on control dependency: [while], data = [none]
m_itemIndex += 1; // depends on control dependency: [while], data = [none]
totalSize += item.getSize(); // depends on control dependency: [while], data = [none]
}
return result;
} } |
public class class_name {
private static String formatServiceType(final CouchbaseRequest request) {
if (request instanceof BinaryRequest) {
return ThresholdLogReporter.SERVICE_KV;
} else if (request instanceof QueryRequest) {
return ThresholdLogReporter.SERVICE_N1QL;
} else if (request instanceof ViewRequest) {
return ThresholdLogReporter.SERVICE_VIEW;
} else if (request instanceof AnalyticsRequest) {
return ThresholdLogReporter.SERVICE_ANALYTICS;
} else if (request instanceof SearchRequest) {
return ThresholdLogReporter.SERVICE_FTS;
} else if (request instanceof ConfigRequest) {
// Shouldn't be user visible, but just for completeness sake.
return "config";
} else {
return "unknown";
}
} } | public class class_name {
private static String formatServiceType(final CouchbaseRequest request) {
if (request instanceof BinaryRequest) {
return ThresholdLogReporter.SERVICE_KV; // depends on control dependency: [if], data = [none]
} else if (request instanceof QueryRequest) {
return ThresholdLogReporter.SERVICE_N1QL; // depends on control dependency: [if], data = [none]
} else if (request instanceof ViewRequest) {
return ThresholdLogReporter.SERVICE_VIEW; // depends on control dependency: [if], data = [none]
} else if (request instanceof AnalyticsRequest) {
return ThresholdLogReporter.SERVICE_ANALYTICS; // depends on control dependency: [if], data = [none]
} else if (request instanceof SearchRequest) {
return ThresholdLogReporter.SERVICE_FTS; // depends on control dependency: [if], data = [none]
} else if (request instanceof ConfigRequest) {
// Shouldn't be user visible, but just for completeness sake.
return "config"; // depends on control dependency: [if], data = [none]
} else {
return "unknown"; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void marshall(AddTagsRequest addTagsRequest, ProtocolMarshaller protocolMarshaller) {
if (addTagsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(addTagsRequest.getResourceId(), RESOURCEID_BINDING);
protocolMarshaller.marshall(addTagsRequest.getTagsList(), TAGSLIST_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(AddTagsRequest addTagsRequest, ProtocolMarshaller protocolMarshaller) {
if (addTagsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(addTagsRequest.getResourceId(), RESOURCEID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(addTagsRequest.getTagsList(), TAGSLIST_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void deliver() {
// We can have reentrancy here when using a direct executor, triggered by calls to
// request more messages. This is safe as we simply loop until pendingDelivers = 0
if (inDelivery) {
return;
}
inDelivery = true;
try {
// Process the uncompressed bytes.
while (pendingDeliveries > 0 && hasRequiredBytes()) {
switch (state) {
case HEADER:
readHeader();
break;
case BODY:
// Read the body and deliver the message.
readBody();
// Since we've delivered a message, decrement the number of pending
// deliveries remaining.
pendingDeliveries--;
break;
default:
throw new IllegalStateException("Invalid state: " + state);
}
}
/*
* We are stalled when there are no more bytes to process. This allows delivering errors as
* soon as the buffered input has been consumed, independent of whether the application
* has requested another message. At this point in the function, either all frames have been
* delivered, or unprocessed is empty. If there is a partial message, it will be inside next
* frame and not in unprocessed. If there is extra data but no pending deliveries, it will
* be in unprocessed.
*/
if (closeWhenComplete && isStalled()) {
close();
}
} finally {
inDelivery = false;
}
} } | public class class_name {
private void deliver() {
// We can have reentrancy here when using a direct executor, triggered by calls to
// request more messages. This is safe as we simply loop until pendingDelivers = 0
if (inDelivery) {
return; // depends on control dependency: [if], data = [none]
}
inDelivery = true;
try {
// Process the uncompressed bytes.
while (pendingDeliveries > 0 && hasRequiredBytes()) {
switch (state) {
case HEADER:
readHeader();
break;
case BODY:
// Read the body and deliver the message.
readBody();
// Since we've delivered a message, decrement the number of pending
// deliveries remaining.
pendingDeliveries--;
break;
default:
throw new IllegalStateException("Invalid state: " + state);
}
}
/*
* We are stalled when there are no more bytes to process. This allows delivering errors as
* soon as the buffered input has been consumed, independent of whether the application
* has requested another message. At this point in the function, either all frames have been
* delivered, or unprocessed is empty. If there is a partial message, it will be inside next
* frame and not in unprocessed. If there is extra data but no pending deliveries, it will
* be in unprocessed.
*/
if (closeWhenComplete && isStalled()) {
close(); // depends on control dependency: [if], data = [none]
}
} finally {
inDelivery = false;
}
} } |
public class class_name {
public EClass getIfcPlaneAngleMeasure() {
if (ifcPlaneAngleMeasureEClass == null) {
ifcPlaneAngleMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(723);
}
return ifcPlaneAngleMeasureEClass;
} } | public class class_name {
public EClass getIfcPlaneAngleMeasure() {
if (ifcPlaneAngleMeasureEClass == null) {
ifcPlaneAngleMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(723);
// depends on control dependency: [if], data = [none]
}
return ifcPlaneAngleMeasureEClass;
} } |
public class class_name {
public static String substringAfter(String input, String substring) {
int index = input.indexOf(substring);
if (index == -1) {
return "";
} else {
return input.substring(index + substring.length());
}
} } | public class class_name {
public static String substringAfter(String input, String substring) {
int index = input.indexOf(substring);
if (index == -1) {
return ""; // depends on control dependency: [if], data = [none]
} else {
return input.substring(index + substring.length()); // depends on control dependency: [if], data = [(index]
}
} } |
public class class_name {
@Override
public void handleFailedDispatch(long clientId, long failedTime) {
ClientData clientData = core.getClientData(clientId);
if (failedTime == -1 || clientData == null)
return;
// We only add it and don't update it because we are interested in
// keeping track of the first moment it failed
if (clientData.markedAsFailedTime == -1) {
clientData.markedAsFailedTime = failedTime;
LOG.info("Marked client " + clientId + " as failed at " + failedTime);
}
clientData.lastSentTime = failedTime;
} } | public class class_name {
@Override
public void handleFailedDispatch(long clientId, long failedTime) {
ClientData clientData = core.getClientData(clientId);
if (failedTime == -1 || clientData == null)
return;
// We only add it and don't update it because we are interested in
// keeping track of the first moment it failed
if (clientData.markedAsFailedTime == -1) {
clientData.markedAsFailedTime = failedTime; // depends on control dependency: [if], data = [none]
LOG.info("Marked client " + clientId + " as failed at " + failedTime); // depends on control dependency: [if], data = [none]
}
clientData.lastSentTime = failedTime;
} } |
public class class_name {
public String translate(Coalesce c) {
final Expression[] alternative = c.getAlternative();
Expression exp = c.getExp();
inject(exp);
final String[] alts = new String[alternative.length];
int i = 0;
for (Expression e : alternative) {
inject(e);
alts[i] = e.translate();
i++;
}
return String.format("COALESCE(%s, " + Joiner.on(", ").join(alts) + ")", exp.translate());
} } | public class class_name {
public String translate(Coalesce c) {
final Expression[] alternative = c.getAlternative();
Expression exp = c.getExp();
inject(exp);
final String[] alts = new String[alternative.length];
int i = 0;
for (Expression e : alternative) {
inject(e); // depends on control dependency: [for], data = [e]
alts[i] = e.translate(); // depends on control dependency: [for], data = [e]
i++; // depends on control dependency: [for], data = [none]
}
return String.format("COALESCE(%s, " + Joiner.on(", ").join(alts) + ")", exp.translate());
} } |
public class class_name {
public float [] [] copyValues2D ()
{
final float v[][] = new float [m_nRows] [m_nCols];
for (int r = 0; r < m_nRows; ++r)
{
for (int c = 0; c < m_nCols; ++c)
{
v[r][c] = m_aValues[r][c];
}
}
return v;
} } | public class class_name {
public float [] [] copyValues2D ()
{
final float v[][] = new float [m_nRows] [m_nCols];
for (int r = 0; r < m_nRows; ++r)
{
for (int c = 0; c < m_nCols; ++c)
{
v[r][c] = m_aValues[r][c]; // depends on control dependency: [for], data = [c]
}
}
return v;
} } |
public class class_name {
public static Type resolveVariable(TypeVariable<?> variable, Class<?> implClass) {
Class<?> rawType = getRawType(implClass, null);
int index = ArrayUtils.indexOf(rawType.getTypeParameters(), variable);
if (index >= 0) {
return variable;
}
Class<?>[] interfaces = rawType.getInterfaces();
Type[] genericInterfaces = rawType.getGenericInterfaces();
for (int i = 0; i <= interfaces.length; i++) {
Class<?> rawInterface;
if (i < interfaces.length) {
rawInterface = interfaces[i];
} else {
rawInterface = rawType.getSuperclass();
if (rawInterface == null) {
continue;
}
}
Type resolved = resolveVariable(variable, rawInterface);
if (resolved instanceof Class || resolved instanceof ParameterizedType) {
return resolved;
}
if (resolved instanceof TypeVariable) {
TypeVariable<?> typeVariable = (TypeVariable<?>) resolved;
index = ArrayUtils.indexOf(rawInterface.getTypeParameters(), typeVariable);
if (index < 0) {
throw new IllegalArgumentException("Can't resolve type variable:" + typeVariable);
}
Type type = i < genericInterfaces.length ? genericInterfaces[i] : rawType.getGenericSuperclass();
if (type instanceof Class) {
return Object.class;
}
if (type instanceof ParameterizedType) {
return ((ParameterizedType) type).getActualTypeArguments()[index];
}
throw new IllegalArgumentException("Unsupported type: " + type);
}
}
return null;
} } | public class class_name {
public static Type resolveVariable(TypeVariable<?> variable, Class<?> implClass) {
Class<?> rawType = getRawType(implClass, null);
int index = ArrayUtils.indexOf(rawType.getTypeParameters(), variable);
if (index >= 0) {
return variable; // depends on control dependency: [if], data = [none]
}
Class<?>[] interfaces = rawType.getInterfaces();
Type[] genericInterfaces = rawType.getGenericInterfaces();
for (int i = 0; i <= interfaces.length; i++) {
Class<?> rawInterface;
if (i < interfaces.length) {
rawInterface = interfaces[i]; // depends on control dependency: [if], data = [none]
} else {
rawInterface = rawType.getSuperclass(); // depends on control dependency: [if], data = [none]
if (rawInterface == null) {
continue;
}
}
Type resolved = resolveVariable(variable, rawInterface);
if (resolved instanceof Class || resolved instanceof ParameterizedType) {
return resolved; // depends on control dependency: [if], data = [none]
}
if (resolved instanceof TypeVariable) {
TypeVariable<?> typeVariable = (TypeVariable<?>) resolved;
index = ArrayUtils.indexOf(rawInterface.getTypeParameters(), typeVariable); // depends on control dependency: [if], data = [none]
if (index < 0) {
throw new IllegalArgumentException("Can't resolve type variable:" + typeVariable);
}
Type type = i < genericInterfaces.length ? genericInterfaces[i] : rawType.getGenericSuperclass();
if (type instanceof Class) {
return Object.class; // depends on control dependency: [if], data = [none]
}
if (type instanceof ParameterizedType) {
return ((ParameterizedType) type).getActualTypeArguments()[index]; // depends on control dependency: [if], data = [none]
}
throw new IllegalArgumentException("Unsupported type: " + type);
}
}
return null;
} } |
public class class_name {
private void moveCursorToNextLine() {
cursorPosition = cursorPosition.withColumn(0).withRelativeRow(1);
if(cursorPosition.getRow() >= currentTextBuffer.getLineCount()) {
currentTextBuffer.newLine();
}
trimBufferBacklog();
correctCursor();
} } | public class class_name {
private void moveCursorToNextLine() {
cursorPosition = cursorPosition.withColumn(0).withRelativeRow(1);
if(cursorPosition.getRow() >= currentTextBuffer.getLineCount()) {
currentTextBuffer.newLine(); // depends on control dependency: [if], data = [none]
}
trimBufferBacklog();
correctCursor();
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.