code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
---|---|
public class class_name {
@Override
protected final int serializeBytes1to3 () {
int line = 0;
line |= taskAttributes.value() << Constants.TWO_BYTES_SHIFT;
if (writeExpectedFlag) {
line |= WRITE_EXPECTED_FLAG_MASK;
}
if (readExpectedFlag) {
line |= READ_EXPECTED_FLAG_MASK;
}
return line;
} } | public class class_name {
@Override
protected final int serializeBytes1to3 () {
int line = 0;
line |= taskAttributes.value() << Constants.TWO_BYTES_SHIFT;
if (writeExpectedFlag) {
line |= WRITE_EXPECTED_FLAG_MASK; // depends on control dependency: [if], data = [none]
}
if (readExpectedFlag) {
line |= READ_EXPECTED_FLAG_MASK; // depends on control dependency: [if], data = [none]
}
return line;
} } |
public class class_name {
public static String slurpURLNoExceptions(URL u) {
try {
return slurpURL(u);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} } | public class class_name {
public static String slurpURLNoExceptions(URL u) {
try {
return slurpURL(u);
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
e.printStackTrace();
return null;
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public float getStringWidth(String string, float tj) {
DocumentFont font = gs().font;
char[] chars = string.toCharArray();
float totalWidth = 0;
for (int i = 0; i < chars.length; i++) {
float w = font.getWidth(chars[i]) / 1000.0f;
float wordSpacing = chars[i] == 32 ? gs().wordSpacing : 0f;
totalWidth += ((w - tj / 1000f) * gs().fontSize + gs().characterSpacing + wordSpacing)
* gs().horizontalScaling;
}
return totalWidth;
} } | public class class_name {
public float getStringWidth(String string, float tj) {
DocumentFont font = gs().font;
char[] chars = string.toCharArray();
float totalWidth = 0;
for (int i = 0; i < chars.length; i++) {
float w = font.getWidth(chars[i]) / 1000.0f;
float wordSpacing = chars[i] == 32 ? gs().wordSpacing : 0f;
totalWidth += ((w - tj / 1000f) * gs().fontSize + gs().characterSpacing + wordSpacing)
* gs().horizontalScaling;
// depends on control dependency: [for], data = [none]
}
return totalWidth;
} } |
public class class_name {
protected Map<String, List<Object>> retrievePersonAttributesFromAttributeRepository(final String id) {
synchronized (lock) {
val repository = getAttributeRepository();
if (repository == null) {
LOGGER.warn("No attribute repositories could be fetched from application context");
return new HashMap<>(0);
}
return CoreAuthenticationUtils.retrieveAttributesFromAttributeRepository(repository, id, this.attributeRepositoryIds);
}
} } | public class class_name {
protected Map<String, List<Object>> retrievePersonAttributesFromAttributeRepository(final String id) {
synchronized (lock) {
val repository = getAttributeRepository();
if (repository == null) {
LOGGER.warn("No attribute repositories could be fetched from application context"); // depends on control dependency: [if], data = [none]
return new HashMap<>(0); // depends on control dependency: [if], data = [none]
}
return CoreAuthenticationUtils.retrieveAttributesFromAttributeRepository(repository, id, this.attributeRepositoryIds);
}
} } |
public class class_name {
public int getPluginRequestCount(int pluginId) {
PluginStats pluginStats = mapPluginStats.get(pluginId);
if (pluginStats != null) {
return pluginStats.getMessageCount();
}
return 0;
} } | public class class_name {
public int getPluginRequestCount(int pluginId) {
PluginStats pluginStats = mapPluginStats.get(pluginId);
if (pluginStats != null) {
return pluginStats.getMessageCount();
// depends on control dependency: [if], data = [none]
}
return 0;
} } |
public class class_name {
public Map getMap(String name, boolean create) {
if (name == null)
throw new IllegalStateException("name must not be null");
if (_nameMap == null)
return null;
TrackingObject to = (TrackingObject) _nameMap.get(name);
// The object wasn't found
if (to == null)
return null;
// If the object has been reclaimed, then we remove the named object from the map.
WeakReference wr = to.getWeakINameable();
INameable o = (INameable) wr.get();
if (o == null) {
synchronized (_nameMap) { _nameMap.remove(name); }
return null;
}
if (create)
return to;
return to.isMapCreated() ? to : null;
} } | public class class_name {
public Map getMap(String name, boolean create) {
if (name == null)
throw new IllegalStateException("name must not be null");
if (_nameMap == null)
return null;
TrackingObject to = (TrackingObject) _nameMap.get(name);
// The object wasn't found
if (to == null)
return null;
// If the object has been reclaimed, then we remove the named object from the map.
WeakReference wr = to.getWeakINameable();
INameable o = (INameable) wr.get();
if (o == null) {
synchronized (_nameMap) { _nameMap.remove(name); } // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
}
if (create)
return to;
return to.isMapCreated() ? to : null;
} } |
public class class_name {
public void marshall(ViolationEvent violationEvent, ProtocolMarshaller protocolMarshaller) {
if (violationEvent == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(violationEvent.getViolationId(), VIOLATIONID_BINDING);
protocolMarshaller.marshall(violationEvent.getThingName(), THINGNAME_BINDING);
protocolMarshaller.marshall(violationEvent.getSecurityProfileName(), SECURITYPROFILENAME_BINDING);
protocolMarshaller.marshall(violationEvent.getBehavior(), BEHAVIOR_BINDING);
protocolMarshaller.marshall(violationEvent.getMetricValue(), METRICVALUE_BINDING);
protocolMarshaller.marshall(violationEvent.getViolationEventType(), VIOLATIONEVENTTYPE_BINDING);
protocolMarshaller.marshall(violationEvent.getViolationEventTime(), VIOLATIONEVENTTIME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ViolationEvent violationEvent, ProtocolMarshaller protocolMarshaller) {
if (violationEvent == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(violationEvent.getViolationId(), VIOLATIONID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(violationEvent.getThingName(), THINGNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(violationEvent.getSecurityProfileName(), SECURITYPROFILENAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(violationEvent.getBehavior(), BEHAVIOR_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(violationEvent.getMetricValue(), METRICVALUE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(violationEvent.getViolationEventType(), VIOLATIONEVENTTYPE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(violationEvent.getViolationEventTime(), VIOLATIONEVENTTIME_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static List<Instant> instantsInRange(Instant firstInstant, Instant lastInstant,
Schedule schedule) {
Preconditions.checkArgument(
isAligned(firstInstant, schedule) && isAligned(lastInstant, schedule),
"unaligned instant");
Preconditions.checkArgument(!lastInstant.isBefore(firstInstant),
"last instant should not be before first instant");
final ExecutionTime executionTime = ExecutionTime.forCron(cron(schedule));
final List<Instant> instants = new ArrayList<>();
Instant currentInstant = firstInstant;
while (currentInstant.isBefore(lastInstant)) {
instants.add(currentInstant);
final ZonedDateTime utcDateTime = currentInstant.atZone(UTC);
currentInstant = executionTime.nextExecution(utcDateTime)
.orElseThrow(IllegalArgumentException::new) // with unix cron, this should not happen
.toInstant();
}
return instants;
} } | public class class_name {
public static List<Instant> instantsInRange(Instant firstInstant, Instant lastInstant,
Schedule schedule) {
Preconditions.checkArgument(
isAligned(firstInstant, schedule) && isAligned(lastInstant, schedule),
"unaligned instant");
Preconditions.checkArgument(!lastInstant.isBefore(firstInstant),
"last instant should not be before first instant");
final ExecutionTime executionTime = ExecutionTime.forCron(cron(schedule));
final List<Instant> instants = new ArrayList<>();
Instant currentInstant = firstInstant;
while (currentInstant.isBefore(lastInstant)) {
instants.add(currentInstant); // depends on control dependency: [while], data = [none]
final ZonedDateTime utcDateTime = currentInstant.atZone(UTC);
currentInstant = executionTime.nextExecution(utcDateTime)
.orElseThrow(IllegalArgumentException::new) // with unix cron, this should not happen
.toInstant(); // depends on control dependency: [while], data = [none]
}
return instants;
} } |
public class class_name {
public CharSequence getJavaScriptOptions()
{
StringBuilder sb = new StringBuilder();
this.optionsRenderer.renderBefore(sb);
int count = 0;
for (Entry<String, Object> entry : options.entrySet())
{
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof IModelOption< ? >)
value = ((IModelOption< ? >) value).wrapOnAssignment(owner);
boolean isLast = !(count < options.size() - 1);
if (value instanceof JsScope)
{
// Case of a JsScope
sb.append(this.optionsRenderer.renderOption(key, ((JsScope) value).render(), isLast));
}
else if (value instanceof ICollectionItemOptions)
{
// Case of an ICollectionItemOptions
sb.append(this.optionsRenderer.renderOption(key,
((ICollectionItemOptions) value).getJavascriptOption(), isLast));
}
else if (value instanceof IComplexOption)
{
// Case of an IComplexOption
sb.append(this.optionsRenderer.renderOption(key,
((IComplexOption) value).getJavascriptOption(), isLast));
}
else if (value instanceof ITypedOption< ? >)
{
// Case of an ITypedOption
sb.append(this.optionsRenderer.renderOption(key,
((ITypedOption< ? >) value).getJavascriptOption(), isLast));
}
else
{
// Other cases
sb.append(this.optionsRenderer.renderOption(key, value, isLast));
}
count++;
}
this.optionsRenderer.renderAfter(sb);
return sb;
} } | public class class_name {
public CharSequence getJavaScriptOptions()
{
StringBuilder sb = new StringBuilder();
this.optionsRenderer.renderBefore(sb);
int count = 0;
for (Entry<String, Object> entry : options.entrySet())
{
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof IModelOption< ? >)
value = ((IModelOption< ? >) value).wrapOnAssignment(owner);
boolean isLast = !(count < options.size() - 1);
if (value instanceof JsScope)
{
// Case of a JsScope
sb.append(this.optionsRenderer.renderOption(key, ((JsScope) value).render(), isLast)); // depends on control dependency: [if], data = [none]
}
else if (value instanceof ICollectionItemOptions)
{
// Case of an ICollectionItemOptions
sb.append(this.optionsRenderer.renderOption(key,
((ICollectionItemOptions) value).getJavascriptOption(), isLast)); // depends on control dependency: [if], data = [none]
}
else if (value instanceof IComplexOption)
{
// Case of an IComplexOption
sb.append(this.optionsRenderer.renderOption(key,
((IComplexOption) value).getJavascriptOption(), isLast)); // depends on control dependency: [if], data = [none]
}
else if (value instanceof ITypedOption< ? >)
{
// Case of an ITypedOption
sb.append(this.optionsRenderer.renderOption(key,
((ITypedOption< ? >) value).getJavascriptOption(), isLast)); // depends on control dependency: [if], data = [none]
}
else
{
// Other cases
sb.append(this.optionsRenderer.renderOption(key, value, isLast)); // depends on control dependency: [if], data = [)]
}
count++; // depends on control dependency: [for], data = [none]
}
this.optionsRenderer.renderAfter(sb);
return sb;
} } |
public class class_name {
private void handleBaseUriLink(EntityBuilder builder, String baseUri) {
if (StringUtils.isBlank(baseUri)) {
return;
}
Link link = LinkBuilder.newInstance().setRelationship(Link.RELATIONSHIP_BASEURI).setHref(baseUri).build();
builder.addLink(link);
} } | public class class_name {
private void handleBaseUriLink(EntityBuilder builder, String baseUri) {
if (StringUtils.isBlank(baseUri)) {
return;
// depends on control dependency: [if], data = [none]
}
Link link = LinkBuilder.newInstance().setRelationship(Link.RELATIONSHIP_BASEURI).setHref(baseUri).build();
builder.addLink(link);
} } |
public class class_name {
public String getMimeType(String filename, String defaultMimeType) {
Matcher matcher = extPattern.matcher(filename.toLowerCase());
String ext = "";
if (matcher.matches()) {
ext = matcher.group(1);
}
if (ext.length() > 0) {
String mimeType = mimetypes.getProperty(ext);
if (mimeType == null) {
return defaultMimeType;
}
return mimeType;
}
return defaultMimeType;
} } | public class class_name {
public String getMimeType(String filename, String defaultMimeType) {
Matcher matcher = extPattern.matcher(filename.toLowerCase());
String ext = "";
if (matcher.matches()) {
ext = matcher.group(1); // depends on control dependency: [if], data = [none]
}
if (ext.length() > 0) {
String mimeType = mimetypes.getProperty(ext);
if (mimeType == null) {
return defaultMimeType; // depends on control dependency: [if], data = [none]
}
return mimeType; // depends on control dependency: [if], data = [none]
}
return defaultMimeType;
} } |
public class class_name {
public boolean getBooleanResult(final CharSequence equation) {
final Element result = new ValueElement(getResult(equation), null, null);
if (result.isBoolean()) {
return result.getBoolean();
} else if (result.isInt()) {
return result.getInt() > 0;
} else if (result.isFloat()) {
return result.getFloat() > 0f;
}
return !isNullOrFalse(result.getString());
} } | public class class_name {
public boolean getBooleanResult(final CharSequence equation) {
final Element result = new ValueElement(getResult(equation), null, null);
if (result.isBoolean()) {
return result.getBoolean(); // depends on control dependency: [if], data = [none]
} else if (result.isInt()) {
return result.getInt() > 0; // depends on control dependency: [if], data = [none]
} else if (result.isFloat()) {
return result.getFloat() > 0f; // depends on control dependency: [if], data = [none]
}
return !isNullOrFalse(result.getString());
} } |
public class class_name {
public void syncTopologyMetaForFollower() {
// sys meta, use remote only
syncSysMetaFromRemote();
// normal topology meta, local + remote
for (Entry<String, TopologyMetricContext> entry : context.getTopologyMetricContexts().entrySet()) {
String topology = entry.getKey();
TopologyMetricContext metricContext = entry.getValue();
if (!JStormMetrics.SYS_TOPOLOGY_SET.contains(topology)) {
try {
syncMetaFromCache(topology, metricContext);
syncNonSysMetaFromRemote(topology, metricContext);
} catch (Exception e1) {
LOG.warn("failed to sync meta for topology:{}", topology);
}
}
}
} } | public class class_name {
public void syncTopologyMetaForFollower() {
// sys meta, use remote only
syncSysMetaFromRemote();
// normal topology meta, local + remote
for (Entry<String, TopologyMetricContext> entry : context.getTopologyMetricContexts().entrySet()) {
String topology = entry.getKey();
TopologyMetricContext metricContext = entry.getValue();
if (!JStormMetrics.SYS_TOPOLOGY_SET.contains(topology)) {
try {
syncMetaFromCache(topology, metricContext); // depends on control dependency: [try], data = [none]
syncNonSysMetaFromRemote(topology, metricContext); // depends on control dependency: [try], data = [none]
} catch (Exception e1) {
LOG.warn("failed to sync meta for topology:{}", topology);
} // depends on control dependency: [catch], data = [none]
}
}
} } |
public class class_name {
public NumberExpression<T> negate() {
if (negation == null) {
negation = Expressions.numberOperation(getType(), Ops.NEGATE, mixin);
}
return negation;
} } | public class class_name {
public NumberExpression<T> negate() {
if (negation == null) {
negation = Expressions.numberOperation(getType(), Ops.NEGATE, mixin); // depends on control dependency: [if], data = [none]
}
return negation;
} } |
public class class_name {
public Logger getLogger(String name)
{
PaxLogger paxLogger;
if (m_paxLogging == null)
{
paxLogger = FallbackLogFactory.createFallbackLog(null, name);
}
else
{
paxLogger = m_paxLogging.getLogger(name, Slf4jLogger.SLF4J_FQCN);
}
Slf4jLogger logger = new Slf4jLogger(name, paxLogger);
if (m_paxLogging == null) {
// just add the logger which PaxLoggingManager need to be replaced.
synchronized (m_loggers) {
m_loggers.put(name, logger);
}
}
return logger;
} } | public class class_name {
public Logger getLogger(String name)
{
PaxLogger paxLogger;
if (m_paxLogging == null)
{
paxLogger = FallbackLogFactory.createFallbackLog(null, name); // depends on control dependency: [if], data = [none]
}
else
{
paxLogger = m_paxLogging.getLogger(name, Slf4jLogger.SLF4J_FQCN); // depends on control dependency: [if], data = [none]
}
Slf4jLogger logger = new Slf4jLogger(name, paxLogger);
if (m_paxLogging == null) {
// just add the logger which PaxLoggingManager need to be replaced.
synchronized (m_loggers) { // depends on control dependency: [if], data = [none]
m_loggers.put(name, logger);
}
}
return logger;
} } |
public class class_name {
public static void removeAppNameSubContext(Context envCtx, String appName) {
if(envCtx != null) {
try {
javax.naming.Context sipContext = (javax.naming.Context)envCtx.lookup(SIP_SUBCONTEXT);
sipContext.destroySubcontext(appName);
} catch (NamingException e) {
logger.error(sm.getString("naming.unbindFailed", e));
}
}
} } | public class class_name {
public static void removeAppNameSubContext(Context envCtx, String appName) {
if(envCtx != null) {
try {
javax.naming.Context sipContext = (javax.naming.Context)envCtx.lookup(SIP_SUBCONTEXT);
sipContext.destroySubcontext(appName);
// depends on control dependency: [try], data = [none]
} catch (NamingException e) {
logger.error(sm.getString("naming.unbindFailed", e));
}
// depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public long hash64( final byte[] data, int length, int seed) {
final long m = 0xc6a4a7935bd1e995L;
final int r = 47;
long h = (seed&0xffffffffl)^(length*m);
int length8 = length/8;
for (int i=0; i<length8; i++) {
final int i8 = i*8;
long k = ((long)data[i8+0]&0xff) +(((long)data[i8+1]&0xff)<<8)
+(((long)data[i8+2]&0xff)<<16) +(((long)data[i8+3]&0xff)<<24)
+(((long)data[i8+4]&0xff)<<32) +(((long)data[i8+5]&0xff)<<40)
+(((long)data[i8+6]&0xff)<<48) +(((long)data[i8+7]&0xff)<<56);
k *= m;
k ^= k >>> r;
k *= m;
h ^= k;
h *= m;
}
switch (length%8) {
case 7: h ^= (long)(data[(length&~7)+6]&0xff) << 48;
case 6: h ^= (long)(data[(length&~7)+5]&0xff) << 40;
case 5: h ^= (long)(data[(length&~7)+4]&0xff) << 32;
case 4: h ^= (long)(data[(length&~7)+3]&0xff) << 24;
case 3: h ^= (long)(data[(length&~7)+2]&0xff) << 16;
case 2: h ^= (long)(data[(length&~7)+1]&0xff) << 8;
case 1: h ^= (long)(data[length&~7]&0xff);
h *= m;
};
h ^= h >>> r;
h *= m;
h ^= h >>> r;
return h;
} } | public class class_name {
public long hash64( final byte[] data, int length, int seed) {
final long m = 0xc6a4a7935bd1e995L;
final int r = 47;
long h = (seed&0xffffffffl)^(length*m);
int length8 = length/8;
for (int i=0; i<length8; i++) {
final int i8 = i*8;
long k = ((long)data[i8+0]&0xff) +(((long)data[i8+1]&0xff)<<8)
+(((long)data[i8+2]&0xff)<<16) +(((long)data[i8+3]&0xff)<<24)
+(((long)data[i8+4]&0xff)<<32) +(((long)data[i8+5]&0xff)<<40)
+(((long)data[i8+6]&0xff)<<48) +(((long)data[i8+7]&0xff)<<56);
k *= m; // depends on control dependency: [for], data = [none]
k ^= k >>> r; // depends on control dependency: [for], data = [none]
k *= m; // depends on control dependency: [for], data = [none]
h ^= k; // depends on control dependency: [for], data = [none]
h *= m; // depends on control dependency: [for], data = [none]
}
switch (length%8) {
case 7: h ^= (long)(data[(length&~7)+6]&0xff) << 48;
case 6: h ^= (long)(data[(length&~7)+5]&0xff) << 40;
case 5: h ^= (long)(data[(length&~7)+4]&0xff) << 32;
case 4: h ^= (long)(data[(length&~7)+3]&0xff) << 24;
case 3: h ^= (long)(data[(length&~7)+2]&0xff) << 16;
case 2: h ^= (long)(data[(length&~7)+1]&0xff) << 8;
case 1: h ^= (long)(data[length&~7]&0xff);
h *= m;
};
h ^= h >>> r;
h *= m;
h ^= h >>> r;
return h;
} } |
public class class_name {
private long processPauseRequest(
final AbstractBody req) {
assertLocked();
if (cmParams != null && cmParams.getMaxPause() != null) {
try {
AttrPause pause = AttrPause.createFromString(
req.getAttribute(Attributes.PAUSE));
if (pause != null) {
long delay = pause.getInMilliseconds() - PAUSE_MARGIN;
if (delay < 0) {
delay = EMPTY_REQUEST_DELAY;
}
return delay;
}
} catch (BOSHException boshx) {
LOG.log(Level.FINEST, "Could not extract", boshx);
}
}
return getDefaultEmptyRequestDelay();
} } | public class class_name {
private long processPauseRequest(
final AbstractBody req) {
assertLocked();
if (cmParams != null && cmParams.getMaxPause() != null) {
try {
AttrPause pause = AttrPause.createFromString(
req.getAttribute(Attributes.PAUSE));
if (pause != null) {
long delay = pause.getInMilliseconds() - PAUSE_MARGIN;
if (delay < 0) {
delay = EMPTY_REQUEST_DELAY; // depends on control dependency: [if], data = [none]
}
return delay; // depends on control dependency: [if], data = [none]
}
} catch (BOSHException boshx) {
LOG.log(Level.FINEST, "Could not extract", boshx);
} // depends on control dependency: [catch], data = [none]
}
return getDefaultEmptyRequestDelay();
} } |
public class class_name {
private KeyPersonCompensationDataType getCompensation(KeyPersonDto keyPerson) {
KeyPersonCompensationDataType keyPersonCompensation = KeyPersonCompensationDataType.Factory.newInstance();
if (keyPerson != null) {
if (keyPerson.getAcademicMonths() != null) {
keyPersonCompensation.setAcademicMonths(keyPerson.getAcademicMonths().bigDecimalValue());
}
if (keyPerson.getCalendarMonths() != null) {
keyPersonCompensation.setCalendarMonths(keyPerson.getCalendarMonths().bigDecimalValue());
}
if (keyPerson.getFringe() != null) {
keyPersonCompensation.setFringeBenefits(keyPerson.getFringe().add(keyPerson.getFringeCostSharing() != null ? keyPerson.getFringeCostSharing() : ScaleTwoDecimal.ZERO).bigDecimalValue());
}
if (keyPerson.getSummerMonths() != null) {
keyPersonCompensation.setSummerMonths(keyPerson.getSummerMonths().bigDecimalValue());
}
if (keyPerson.getRequestedSalary() != null) {
keyPersonCompensation.setRequestedSalary(keyPerson.getRequestedSalary().add(keyPerson.getCostSharingAmount() != null ? keyPerson.getCostSharingAmount() : ScaleTwoDecimal.ZERO).bigDecimalValue());
}
TotalDataType total = TotalDataType.Factory.newInstance();
if (keyPerson.getFundsRequested() != null) {
total.setFederal(keyPerson.getFundsRequested().bigDecimalValue());
}
if (keyPerson.getNonFundsRequested() != null) {
total.setNonFederal(keyPerson.getNonFundsRequested().bigDecimalValue());
}
if (keyPerson.getFundsRequested() != null && keyPerson.getNonFundsRequested() != null) {
total.setTotalFedNonFed(keyPerson.getFundsRequested().add(keyPerson.getNonFundsRequested()).bigDecimalValue());
}
keyPersonCompensation.setTotal(total);
if (keyPerson.getBaseSalary() != null) {
keyPersonCompensation.setBaseSalary(keyPerson.getBaseSalary().bigDecimalValue());
}
}
return keyPersonCompensation;
} } | public class class_name {
private KeyPersonCompensationDataType getCompensation(KeyPersonDto keyPerson) {
KeyPersonCompensationDataType keyPersonCompensation = KeyPersonCompensationDataType.Factory.newInstance();
if (keyPerson != null) {
if (keyPerson.getAcademicMonths() != null) {
keyPersonCompensation.setAcademicMonths(keyPerson.getAcademicMonths().bigDecimalValue()); // depends on control dependency: [if], data = [(keyPerson.getAcademicMonths()]
}
if (keyPerson.getCalendarMonths() != null) {
keyPersonCompensation.setCalendarMonths(keyPerson.getCalendarMonths().bigDecimalValue()); // depends on control dependency: [if], data = [(keyPerson.getCalendarMonths()]
}
if (keyPerson.getFringe() != null) {
keyPersonCompensation.setFringeBenefits(keyPerson.getFringe().add(keyPerson.getFringeCostSharing() != null ? keyPerson.getFringeCostSharing() : ScaleTwoDecimal.ZERO).bigDecimalValue()); // depends on control dependency: [if], data = [(keyPerson.getFringe()]
}
if (keyPerson.getSummerMonths() != null) {
keyPersonCompensation.setSummerMonths(keyPerson.getSummerMonths().bigDecimalValue()); // depends on control dependency: [if], data = [(keyPerson.getSummerMonths()]
}
if (keyPerson.getRequestedSalary() != null) {
keyPersonCompensation.setRequestedSalary(keyPerson.getRequestedSalary().add(keyPerson.getCostSharingAmount() != null ? keyPerson.getCostSharingAmount() : ScaleTwoDecimal.ZERO).bigDecimalValue()); // depends on control dependency: [if], data = [(keyPerson.getRequestedSalary()]
}
TotalDataType total = TotalDataType.Factory.newInstance();
if (keyPerson.getFundsRequested() != null) {
total.setFederal(keyPerson.getFundsRequested().bigDecimalValue()); // depends on control dependency: [if], data = [(keyPerson.getFundsRequested()]
}
if (keyPerson.getNonFundsRequested() != null) {
total.setNonFederal(keyPerson.getNonFundsRequested().bigDecimalValue()); // depends on control dependency: [if], data = [(keyPerson.getNonFundsRequested()]
}
if (keyPerson.getFundsRequested() != null && keyPerson.getNonFundsRequested() != null) {
total.setTotalFedNonFed(keyPerson.getFundsRequested().add(keyPerson.getNonFundsRequested()).bigDecimalValue()); // depends on control dependency: [if], data = [(keyPerson.getFundsRequested()]
}
keyPersonCompensation.setTotal(total); // depends on control dependency: [if], data = [none]
if (keyPerson.getBaseSalary() != null) {
keyPersonCompensation.setBaseSalary(keyPerson.getBaseSalary().bigDecimalValue()); // depends on control dependency: [if], data = [(keyPerson.getBaseSalary()]
}
}
return keyPersonCompensation;
} } |
public class class_name {
public String getSchema(Class<?> clazz)
{
if (clazz == Integer.class || clazz == Integer.TYPE)
{
return "integer [" + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE + "]";
}
else if (clazz == Long.class || clazz == Long.TYPE)
{
return "long [" + Long.MIN_VALUE + " to " + Long.MAX_VALUE + "]";
}
else if (clazz == Double.class || clazz == Double.TYPE)
{
return "double [" + Double.MIN_VALUE + " to " + Double.MAX_VALUE + "]";
}
else if (clazz == Boolean.class || clazz == Boolean.TYPE)
{
return "boolean [true, false]";
}
else if (clazz == Void.class)
{
return "void";
}
else if (clazz == Byte[].class || clazz == byte[].class)
{
return "binary stream";
}
else if (clazz.isEnum())
{
return "enum " + Arrays.asList(clazz.getEnumConstants());
}
else if (clazz.isAnnotationPresent(XmlRootElement.class))
{
try
{
final JAXBSerialiser serialiser = JAXBSerialiser.getMoxy(clazz);
return generate(serialiser);
}
catch (Exception e)
{
// Ignore
return "error generating schema for " + clazz + ": " + e.getMessage();
}
}
else if (clazz.isAnnotationPresent(XmlType.class) || clazz.isAnnotationPresent(XmlEnum.class))
{
// Class generated by JAXB XSD To Java (as a result we have to emit the entire schema rather than being able to provide a specific sub-schema for the type in question because XmlRootElement is not specified)
try
{
final JAXBSerialiser serialiser = JAXBSerialiser.getMoxy(clazz.getPackage().getName());
return generate(serialiser);
}
catch (Exception e)
{
// Ignore
return "error generating schema for XSD-To-Java package schema for class " + clazz + ": " + e.getMessage();
}
}
else
{
return clazz.toString();
}
} } | public class class_name {
public String getSchema(Class<?> clazz)
{
if (clazz == Integer.class || clazz == Integer.TYPE)
{
return "integer [" + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE + "]"; // depends on control dependency: [if], data = [none]
}
else if (clazz == Long.class || clazz == Long.TYPE)
{
return "long [" + Long.MIN_VALUE + " to " + Long.MAX_VALUE + "]"; // depends on control dependency: [if], data = [none]
}
else if (clazz == Double.class || clazz == Double.TYPE)
{
return "double [" + Double.MIN_VALUE + " to " + Double.MAX_VALUE + "]"; // depends on control dependency: [if], data = [none]
}
else if (clazz == Boolean.class || clazz == Boolean.TYPE)
{
return "boolean [true, false]"; // depends on control dependency: [if], data = [none]
}
else if (clazz == Void.class)
{
return "void"; // depends on control dependency: [if], data = [none]
}
else if (clazz == Byte[].class || clazz == byte[].class)
{
return "binary stream"; // depends on control dependency: [if], data = [none]
}
else if (clazz.isEnum())
{
return "enum " + Arrays.asList(clazz.getEnumConstants()); // depends on control dependency: [if], data = [none]
}
else if (clazz.isAnnotationPresent(XmlRootElement.class))
{
try
{
final JAXBSerialiser serialiser = JAXBSerialiser.getMoxy(clazz);
return generate(serialiser); // depends on control dependency: [try], data = [none]
}
catch (Exception e)
{
// Ignore
return "error generating schema for " + clazz + ": " + e.getMessage();
} // depends on control dependency: [catch], data = [none]
}
else if (clazz.isAnnotationPresent(XmlType.class) || clazz.isAnnotationPresent(XmlEnum.class))
{
// Class generated by JAXB XSD To Java (as a result we have to emit the entire schema rather than being able to provide a specific sub-schema for the type in question because XmlRootElement is not specified)
try
{
final JAXBSerialiser serialiser = JAXBSerialiser.getMoxy(clazz.getPackage().getName());
return generate(serialiser); // depends on control dependency: [try], data = [none]
}
catch (Exception e)
{
// Ignore
return "error generating schema for XSD-To-Java package schema for class " + clazz + ": " + e.getMessage();
} // depends on control dependency: [catch], data = [none]
}
else
{
return clazz.toString(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected List<Integer> getAllAcceptedStates(CharSequence text, int startIndex){
List<Integer> states = new ArrayList<Integer>();
int lastAcceptedState = -1;
int p = runAutomaton.getInitialState();
int l = text.length();
for (int i = startIndex; i < l; i++) {
p = runAutomaton.step(p, text.charAt(i));
if (p == -1) {
if (lastAcceptedState == -1){
return null;
}else{
break;
}
}
if (runAutomaton.isAccept(p)){
states.add(p);
lastAcceptedState = p;
}
}
if (states.size() == 0){// this does happen, but why?
return null;
}
return states;
} } | public class class_name {
protected List<Integer> getAllAcceptedStates(CharSequence text, int startIndex){
List<Integer> states = new ArrayList<Integer>();
int lastAcceptedState = -1;
int p = runAutomaton.getInitialState();
int l = text.length();
for (int i = startIndex; i < l; i++) {
p = runAutomaton.step(p, text.charAt(i));
// depends on control dependency: [for], data = [i]
if (p == -1) {
if (lastAcceptedState == -1){
return null;
// depends on control dependency: [if], data = [none]
}else{
break;
}
}
if (runAutomaton.isAccept(p)){
states.add(p);
// depends on control dependency: [if], data = [none]
lastAcceptedState = p;
// depends on control dependency: [if], data = [none]
}
}
if (states.size() == 0){// this does happen, but why?
return null;
// depends on control dependency: [if], data = [none]
}
return states;
} } |
public class class_name {
@Override
public PipelineEventReader<XMLEventReader, XMLEvent> getEventReader(
HttpServletRequest request, HttpServletResponse response) {
final PipelineEventReader<XMLEventReader, XMLEvent> pipelineEventReader =
this.wrappedComponent.getEventReader(request, response);
final XMLEventReader eventReader = pipelineEventReader.getEventReader();
final IStylesheetDescriptor stylesheetDescriptor =
stylesheetAttributeSource.getStylesheetDescriptor(request);
final IPortalRequestInfo portalRequestInfo =
this.urlSyntaxProvider.getPortalRequestInfo(request);
final XMLEventReader filteredEventReader;
if (portalRequestInfo.getTargetedPortletWindowId() == null) {
final IStylesheetParameterDescriptor defaultWindowStateParam =
stylesheetDescriptor.getStylesheetParameterDescriptor(
"dashboardForcedWindowState");
if (defaultWindowStateParam != null) {
// Set all window states to the specified default
final WindowState windowState =
PortletUtils.getWindowState(defaultWindowStateParam.getDefaultValue());
filteredEventReader =
new SinglePortletWindowStateSettingXMLEventReader(
request, eventReader, windowState);
} else {
// Make sure there aren't any portlets in a "targeted" window state
filteredEventReader =
new NonTargetedPortletWindowStateSettingXMLEventReader(
request, eventReader);
}
} else {
// Not mobile, don't bother filtering
filteredEventReader = eventReader;
}
final Map<String, String> outputProperties = pipelineEventReader.getOutputProperties();
return new PipelineEventReaderImpl<XMLEventReader, XMLEvent>(
filteredEventReader, outputProperties);
} } | public class class_name {
@Override
public PipelineEventReader<XMLEventReader, XMLEvent> getEventReader(
HttpServletRequest request, HttpServletResponse response) {
final PipelineEventReader<XMLEventReader, XMLEvent> pipelineEventReader =
this.wrappedComponent.getEventReader(request, response);
final XMLEventReader eventReader = pipelineEventReader.getEventReader();
final IStylesheetDescriptor stylesheetDescriptor =
stylesheetAttributeSource.getStylesheetDescriptor(request);
final IPortalRequestInfo portalRequestInfo =
this.urlSyntaxProvider.getPortalRequestInfo(request);
final XMLEventReader filteredEventReader;
if (portalRequestInfo.getTargetedPortletWindowId() == null) {
final IStylesheetParameterDescriptor defaultWindowStateParam =
stylesheetDescriptor.getStylesheetParameterDescriptor(
"dashboardForcedWindowState");
if (defaultWindowStateParam != null) {
// Set all window states to the specified default
final WindowState windowState =
PortletUtils.getWindowState(defaultWindowStateParam.getDefaultValue());
filteredEventReader =
new SinglePortletWindowStateSettingXMLEventReader(
request, eventReader, windowState); // depends on control dependency: [if], data = [none]
} else {
// Make sure there aren't any portlets in a "targeted" window state
filteredEventReader =
new NonTargetedPortletWindowStateSettingXMLEventReader(
request, eventReader); // depends on control dependency: [if], data = [none]
}
} else {
// Not mobile, don't bother filtering
filteredEventReader = eventReader; // depends on control dependency: [if], data = [none]
}
final Map<String, String> outputProperties = pipelineEventReader.getOutputProperties();
return new PipelineEventReaderImpl<XMLEventReader, XMLEvent>(
filteredEventReader, outputProperties);
} } |
public class class_name {
public static Optional<Boolean> isTarget(EventModel eventModel, Identifiable identifiable) {
if (eventModel.getListResourceContainer()
.providesResource(Collections.singletonList(SelectorResource.RESOURCE_ID))) {
return Optional.of(eventModel.getListResourceContainer()
.provideResource(SelectorResource.RESOURCE_ID)
.stream()
.map(ResourceModel::getResource)
.filter(resource -> resource instanceof Identification)
.map(object -> (Identification) object)
.anyMatch(identifiable::isOwner));
} else {
return Optional.empty();
}
} } | public class class_name {
public static Optional<Boolean> isTarget(EventModel eventModel, Identifiable identifiable) {
if (eventModel.getListResourceContainer()
.providesResource(Collections.singletonList(SelectorResource.RESOURCE_ID))) {
return Optional.of(eventModel.getListResourceContainer()
.provideResource(SelectorResource.RESOURCE_ID)
.stream()
.map(ResourceModel::getResource)
.filter(resource -> resource instanceof Identification)
.map(object -> (Identification) object)
.anyMatch(identifiable::isOwner)); // depends on control dependency: [if], data = [none]
} else {
return Optional.empty(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static <E> Set<E> retainNonZeros(Counter<E> counter) {
Set<E> removed = new HashSet<E>();
for (E key : counter.keySet()) {
if (counter.getCount(key) == 0.0) {
removed.add(key);
}
}
for (E key : removed) {
counter.remove(key);
}
return removed;
} } | public class class_name {
public static <E> Set<E> retainNonZeros(Counter<E> counter) {
Set<E> removed = new HashSet<E>();
for (E key : counter.keySet()) {
if (counter.getCount(key) == 0.0) {
removed.add(key);
// depends on control dependency: [if], data = [none]
}
}
for (E key : removed) {
counter.remove(key);
// depends on control dependency: [for], data = [key]
}
return removed;
} } |
public class class_name {
public final void eval() throws IOException {
final String component = this.parsedArguments.getString("component");
final String testFile = this.parsedArguments.getString("testSet");
final String model = this.parsedArguments.getString("model");
Evaluate evaluator = null;
if (component.equalsIgnoreCase("pos")) {
evaluator = new POSEvaluate(testFile, model);
} else {
evaluator = new LemmaEvaluate(testFile, model);
}
if (this.parsedArguments.getString("evalReport") != null) {
if (this.parsedArguments.getString("evalReport").equalsIgnoreCase(
"detailed")) {
evaluator.detailEvaluate();
} else if (this.parsedArguments.getString("evalReport").equalsIgnoreCase(
"error")) {
evaluator.evalError();
} else if (this.parsedArguments.getString("evalReport").equalsIgnoreCase(
"brief")) {
evaluator.evaluate();
}
} else {
evaluator.evaluate();
}
} } | public class class_name {
public final void eval() throws IOException {
final String component = this.parsedArguments.getString("component");
final String testFile = this.parsedArguments.getString("testSet");
final String model = this.parsedArguments.getString("model");
Evaluate evaluator = null;
if (component.equalsIgnoreCase("pos")) {
evaluator = new POSEvaluate(testFile, model);
} else {
evaluator = new LemmaEvaluate(testFile, model);
}
if (this.parsedArguments.getString("evalReport") != null) {
if (this.parsedArguments.getString("evalReport").equalsIgnoreCase(
"detailed")) {
evaluator.detailEvaluate(); // depends on control dependency: [if], data = [none]
} else if (this.parsedArguments.getString("evalReport").equalsIgnoreCase(
"error")) {
evaluator.evalError(); // depends on control dependency: [if], data = [none]
} else if (this.parsedArguments.getString("evalReport").equalsIgnoreCase(
"brief")) {
evaluator.evaluate(); // depends on control dependency: [if], data = [none]
}
} else {
evaluator.evaluate();
}
} } |
public class class_name {
private static @Nullable Dimension getDimensionFromRenditionMetadata(@NotNull Rendition rendition) {
Asset asset = rendition.getAsset();
String metadataPath = JCR_CONTENT + "/" + NN_RENDITIONS_METADATA + "/" + rendition.getName();
Resource metadataResource = AdaptTo.notNull(asset, Resource.class).getChild(metadataPath);
if (metadataResource != null) {
ValueMap props = metadataResource.getValueMap();
long width = props.get(PN_IMAGE_WIDTH, 0L);
long height = props.get(PN_IMAGE_HEIGHT, 0L);
return toDimension(width, height);
}
return null;
} } | public class class_name {
private static @Nullable Dimension getDimensionFromRenditionMetadata(@NotNull Rendition rendition) {
Asset asset = rendition.getAsset();
String metadataPath = JCR_CONTENT + "/" + NN_RENDITIONS_METADATA + "/" + rendition.getName();
Resource metadataResource = AdaptTo.notNull(asset, Resource.class).getChild(metadataPath);
if (metadataResource != null) {
ValueMap props = metadataResource.getValueMap();
long width = props.get(PN_IMAGE_WIDTH, 0L);
long height = props.get(PN_IMAGE_HEIGHT, 0L);
return toDimension(width, height); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
final int getIndexValue() {
if (anteContextLength == pattern.length()) {
// A pattern with just ante context {such as foo)>bar} can
// match any key.
return -1;
}
int c = UTF16.charAt(pattern, anteContextLength);
return data.lookupMatcher(c) == null ? (c & 0xFF) : -1;
} } | public class class_name {
final int getIndexValue() {
if (anteContextLength == pattern.length()) {
// A pattern with just ante context {such as foo)>bar} can
// match any key.
return -1; // depends on control dependency: [if], data = [none]
}
int c = UTF16.charAt(pattern, anteContextLength);
return data.lookupMatcher(c) == null ? (c & 0xFF) : -1;
} } |
public class class_name {
private void ensureWatchThreadRunning() {
if (!threadRunning) {
thread = new Thread(watchThread);
thread.setDaemon(true);
thread.start();
watchThread.setThread(thread);
watchThread.updateName();
threadRunning = true;
}
} } | public class class_name {
private void ensureWatchThreadRunning() {
if (!threadRunning) {
thread = new Thread(watchThread); // depends on control dependency: [if], data = [none]
thread.setDaemon(true); // depends on control dependency: [if], data = [none]
thread.start(); // depends on control dependency: [if], data = [none]
watchThread.setThread(thread); // depends on control dependency: [if], data = [none]
watchThread.updateName(); // depends on control dependency: [if], data = [none]
threadRunning = true; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static ScriptableObject getGlobal(Context cx) {
final String GLOBAL_CLASS = "org.mozilla.javascript.tools.shell.Global";
Class<?> globalClass = Kit.classOrNull(GLOBAL_CLASS);
if (globalClass != null) {
try {
Class<?>[] parm = { ScriptRuntime.ContextClass };
Constructor<?> globalClassCtor = globalClass.getConstructor(parm);
Object[] arg = { cx };
return (ScriptableObject) globalClassCtor.newInstance(arg);
}
catch (RuntimeException e) {
throw e;
}
catch (Exception e) {
// fall through...
}
}
return new ImporterTopLevel(cx);
} } | public class class_name {
public static ScriptableObject getGlobal(Context cx) {
final String GLOBAL_CLASS = "org.mozilla.javascript.tools.shell.Global";
Class<?> globalClass = Kit.classOrNull(GLOBAL_CLASS);
if (globalClass != null) {
try {
Class<?>[] parm = { ScriptRuntime.ContextClass };
Constructor<?> globalClassCtor = globalClass.getConstructor(parm);
Object[] arg = { cx };
return (ScriptableObject) globalClassCtor.newInstance(arg); // depends on control dependency: [try], data = [none]
}
catch (RuntimeException e) {
throw e;
} // depends on control dependency: [catch], data = [none]
catch (Exception e) {
// fall through...
} // depends on control dependency: [catch], data = [none]
}
return new ImporterTopLevel(cx);
} } |
public class class_name {
public void checkForErrorResponse()
{
lock.lock();
try
{
ensureOpen();
if (controlResponsePoller.poll() != 0 && controlResponsePoller.isPollComplete())
{
if (controlResponsePoller.controlSessionId() == controlSessionId &&
controlResponsePoller.templateId() == ControlResponseDecoder.TEMPLATE_ID &&
controlResponsePoller.code() == ControlResponseCode.ERROR)
{
final ArchiveException ex = new ArchiveException(
controlResponsePoller.errorMessage(), (int)controlResponsePoller.relevantId());
if (null != context.errorHandler())
{
context.errorHandler().onError(ex);
}
else
{
throw ex;
}
}
}
}
finally
{
lock.unlock();
}
} } | public class class_name {
public void checkForErrorResponse()
{
lock.lock();
try
{
ensureOpen(); // depends on control dependency: [try], data = [none]
if (controlResponsePoller.poll() != 0 && controlResponsePoller.isPollComplete())
{
if (controlResponsePoller.controlSessionId() == controlSessionId &&
controlResponsePoller.templateId() == ControlResponseDecoder.TEMPLATE_ID &&
controlResponsePoller.code() == ControlResponseCode.ERROR)
{
final ArchiveException ex = new ArchiveException(
controlResponsePoller.errorMessage(), (int)controlResponsePoller.relevantId());
if (null != context.errorHandler())
{
context.errorHandler().onError(ex); // depends on control dependency: [if], data = [none]
}
else
{
throw ex;
}
}
}
}
finally
{
lock.unlock();
}
} } |
public class class_name {
private MIMETypedStream getFromWeb(String url, String user, String pass,
String knownMimeType, boolean headOnly, Context context)
throws GeneralException, RangeNotSatisfiableException {
logger.debug("DefaultExternalContentManager.getFromWeb({})", url);
if (url == null) throw new GeneralException("null url");
HttpInputStream response = null;
try {
if (headOnly) {
response = m_http.head(url, true, user, pass,
context.getHeaderValue(HttpHeaders.IF_NONE_MATCH),
context.getHeaderValue(HttpHeaders.IF_MODIFIED_SINCE),
context.getHeaderValue("Range"));
} else {
response = m_http.get(
url, true, user, pass,
context.getHeaderValue(HttpHeaders.IF_NONE_MATCH),
context.getHeaderValue(HttpHeaders.IF_MODIFIED_SINCE),
context.getHeaderValue("Range"));
}
String mimeType =
response.getResponseHeaderValue(HttpHeaders.CONTENT_TYPE,
knownMimeType);
long length = Long.parseLong(response.getResponseHeaderValue(HttpHeaders.CONTENT_LENGTH,"-1"));
Property[] headerArray =
toPropertyArray(response.getResponseHeaders());
if (mimeType == null || mimeType.isEmpty()) {
mimeType = DEFAULT_MIMETYPE;
}
if (response.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
response.close();
Header[] respHeaders = response.getResponseHeaders();
Property[] properties = new Property[respHeaders.length];
for (int i = 0; i < respHeaders.length; i++){
properties[i] =
new Property(respHeaders[i].getName(), respHeaders[i].getValue());
}
return MIMETypedStream.getNotModified(properties);
} else if (response.getStatusCode() == HttpStatus.SC_PARTIAL_CONTENT) {
MIMETypedStream pc_response = new MIMETypedStream(mimeType, response,
headerArray, length);
pc_response.setStatusCode(HttpStatus.SC_PARTIAL_CONTENT);
return pc_response;
} else if (response.getStatusCode() == HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE) {
response.close();
throw new RangeNotSatisfiableException("External URL datastream request returned 416 Range Not Satisfiable");
} else {
if (headOnly) {
try {
response.close();
} catch (IOException ioe) {
logger.warn("problem closing HEAD response: {}", ioe.getMessage());
}
return new MIMETypedStream(mimeType, NullInputStream.NULL_STREAM,
headerArray, length);
} else {
return new MIMETypedStream(mimeType, response, headerArray, length);
}
}
} catch (RangeNotSatisfiableException re){
logger.error(re.getMessage(), re);
throw re;
} catch (Exception e) {
throw new GeneralException("Error getting " + url, e);
}
} } | public class class_name {
private MIMETypedStream getFromWeb(String url, String user, String pass,
String knownMimeType, boolean headOnly, Context context)
throws GeneralException, RangeNotSatisfiableException {
logger.debug("DefaultExternalContentManager.getFromWeb({})", url);
if (url == null) throw new GeneralException("null url");
HttpInputStream response = null;
try {
if (headOnly) {
response = m_http.head(url, true, user, pass,
context.getHeaderValue(HttpHeaders.IF_NONE_MATCH),
context.getHeaderValue(HttpHeaders.IF_MODIFIED_SINCE),
context.getHeaderValue("Range")); // depends on control dependency: [if], data = [none]
} else {
response = m_http.get(
url, true, user, pass,
context.getHeaderValue(HttpHeaders.IF_NONE_MATCH),
context.getHeaderValue(HttpHeaders.IF_MODIFIED_SINCE),
context.getHeaderValue("Range")); // depends on control dependency: [if], data = [none]
}
String mimeType =
response.getResponseHeaderValue(HttpHeaders.CONTENT_TYPE,
knownMimeType);
long length = Long.parseLong(response.getResponseHeaderValue(HttpHeaders.CONTENT_LENGTH,"-1"));
Property[] headerArray =
toPropertyArray(response.getResponseHeaders());
if (mimeType == null || mimeType.isEmpty()) {
mimeType = DEFAULT_MIMETYPE; // depends on control dependency: [if], data = [none]
}
if (response.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
response.close(); // depends on control dependency: [if], data = [none]
Header[] respHeaders = response.getResponseHeaders();
Property[] properties = new Property[respHeaders.length];
for (int i = 0; i < respHeaders.length; i++){
properties[i] =
new Property(respHeaders[i].getName(), respHeaders[i].getValue()); // depends on control dependency: [for], data = [i]
}
return MIMETypedStream.getNotModified(properties); // depends on control dependency: [if], data = [none]
} else if (response.getStatusCode() == HttpStatus.SC_PARTIAL_CONTENT) {
MIMETypedStream pc_response = new MIMETypedStream(mimeType, response,
headerArray, length);
pc_response.setStatusCode(HttpStatus.SC_PARTIAL_CONTENT); // depends on control dependency: [if], data = [HttpStatus.SC_PARTIAL_CONTENT)]
return pc_response; // depends on control dependency: [if], data = [none]
} else if (response.getStatusCode() == HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE) {
response.close(); // depends on control dependency: [if], data = [none]
throw new RangeNotSatisfiableException("External URL datastream request returned 416 Range Not Satisfiable");
} else {
if (headOnly) {
try {
response.close(); // depends on control dependency: [try], data = [none]
} catch (IOException ioe) {
logger.warn("problem closing HEAD response: {}", ioe.getMessage());
} // depends on control dependency: [catch], data = [none]
return new MIMETypedStream(mimeType, NullInputStream.NULL_STREAM,
headerArray, length); // depends on control dependency: [if], data = [none]
} else {
return new MIMETypedStream(mimeType, response, headerArray, length); // depends on control dependency: [if], data = [none]
}
}
} catch (RangeNotSatisfiableException re){
logger.error(re.getMessage(), re);
throw re;
} catch (Exception e) {
throw new GeneralException("Error getting " + url, e);
}
} } |
public class class_name {
@Override
public void prepare ( CommonServerMessageBlockRequest next ) {
if ( isReceived() && ( next instanceof RequestWithFileId ) ) {
( (RequestWithFileId) next ).setFileId(this.fileId);
}
super.prepare(next);
} } | public class class_name {
@Override
public void prepare ( CommonServerMessageBlockRequest next ) {
if ( isReceived() && ( next instanceof RequestWithFileId ) ) {
( (RequestWithFileId) next ).setFileId(this.fileId); // depends on control dependency: [if], data = [none]
}
super.prepare(next);
} } |
public class class_name {
protected void addOverviewComment(Content htmltree) {
if (root.inlineTags().length > 0) {
htmltree.addContent(
getMarkerAnchor(SectionName.OVERVIEW_DESCRIPTION));
addInlineComment(root, htmltree);
}
} } | public class class_name {
protected void addOverviewComment(Content htmltree) {
if (root.inlineTags().length > 0) {
htmltree.addContent(
getMarkerAnchor(SectionName.OVERVIEW_DESCRIPTION)); // depends on control dependency: [if], data = [none]
addInlineComment(root, htmltree); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void logAuditTrail(LogTarget lt) {
if(lt.isLoggable()) {
StringBuilder sb = new StringBuilder();
auditTrail(1, sb);
lt.log(sb);
}
} } | public class class_name {
@Override
public void logAuditTrail(LogTarget lt) {
if(lt.isLoggable()) {
StringBuilder sb = new StringBuilder();
auditTrail(1, sb); // depends on control dependency: [if], data = [none]
lt.log(sb); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private static int unsignedBinarySearch(int[] a, int fromIndex, int toIndex, int key,
Comparator<? super Integer> c) {
int low = fromIndex;
int high = toIndex - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
int midVal = a[mid];
int cmp = c.compare(midVal, key);
if (cmp < 0) {
low = mid + 1;
} else if (cmp > 0) {
high = mid - 1;
} else {
return mid; // key found
}
}
return -(low + 1); // key not found.
} } | public class class_name {
private static int unsignedBinarySearch(int[] a, int fromIndex, int toIndex, int key,
Comparator<? super Integer> c) {
int low = fromIndex;
int high = toIndex - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
int midVal = a[mid];
int cmp = c.compare(midVal, key);
if (cmp < 0) {
low = mid + 1; // depends on control dependency: [if], data = [none]
} else if (cmp > 0) {
high = mid - 1; // depends on control dependency: [if], data = [none]
} else {
return mid; // key found // depends on control dependency: [if], data = [none]
}
}
return -(low + 1); // key not found.
} } |
public class class_name {
public static DigestInputStream wrapStream(InputStream inStream,
Algorithm algorithm) {
MessageDigest streamDigest = null;
try {
streamDigest = MessageDigest.getInstance(algorithm.toString());
} catch (NoSuchAlgorithmException e) {
String error = "Could not create a MessageDigest because the " +
"required algorithm " + algorithm.toString() +
" is not supported.";
throw new RuntimeException(error);
}
DigestInputStream wrappedContent =
new DigestInputStream(inStream, streamDigest);
return wrappedContent;
} } | public class class_name {
public static DigestInputStream wrapStream(InputStream inStream,
Algorithm algorithm) {
MessageDigest streamDigest = null;
try {
streamDigest = MessageDigest.getInstance(algorithm.toString()); // depends on control dependency: [try], data = [none]
} catch (NoSuchAlgorithmException e) {
String error = "Could not create a MessageDigest because the " +
"required algorithm " + algorithm.toString() +
" is not supported.";
throw new RuntimeException(error);
} // depends on control dependency: [catch], data = [none]
DigestInputStream wrappedContent =
new DigestInputStream(inStream, streamDigest);
return wrappedContent;
} } |
public class class_name {
public static List<File> find(File directory, String pattern) {
pattern = wildcardsToRegExp(pattern);
List<File> files = findFilesInDirectory(directory,
Pattern.compile(pattern), true);
List<File> result = new ArrayList<File>();
for (File file : files) {
String fileString = file.getPath().substring(
directory.getPath().length());
result.add(new File(fileString));
}
return result;
} } | public class class_name {
public static List<File> find(File directory, String pattern) {
pattern = wildcardsToRegExp(pattern);
List<File> files = findFilesInDirectory(directory,
Pattern.compile(pattern), true);
List<File> result = new ArrayList<File>();
for (File file : files) {
String fileString = file.getPath().substring(
directory.getPath().length());
result.add(new File(fileString)); // depends on control dependency: [for], data = [file]
}
return result;
} } |
public class class_name {
protected void broadcastNodeConnected(Tree info, boolean reconnected) {
if (info != null) {
Tree msg = new Tree();
msg.putObject("node", info);
msg.put("reconnected", reconnected);
eventbus.broadcast("$node.connected", msg, null, true);
}
} } | public class class_name {
protected void broadcastNodeConnected(Tree info, boolean reconnected) {
if (info != null) {
Tree msg = new Tree();
msg.putObject("node", info);
// depends on control dependency: [if], data = [none]
msg.put("reconnected", reconnected);
// depends on control dependency: [if], data = [none]
eventbus.broadcast("$node.connected", msg, null, true);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void marshall(GetBackupPlanFromJSONRequest getBackupPlanFromJSONRequest, ProtocolMarshaller protocolMarshaller) {
if (getBackupPlanFromJSONRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getBackupPlanFromJSONRequest.getBackupPlanTemplateJson(), BACKUPPLANTEMPLATEJSON_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(GetBackupPlanFromJSONRequest getBackupPlanFromJSONRequest, ProtocolMarshaller protocolMarshaller) {
if (getBackupPlanFromJSONRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getBackupPlanFromJSONRequest.getBackupPlanTemplateJson(), BACKUPPLANTEMPLATEJSON_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 Priority[] getPriorities() {
List<Priority> actualPriorities = new ArrayList<Priority>();
for (String priority : getAvailablePriorities()) {
if (provider.getNumberOfAnnotations(priority) > 0) {
actualPriorities.add(Priority.fromString(priority));
}
}
return actualPriorities.toArray(new Priority[actualPriorities.size()]);
} } | public class class_name {
public Priority[] getPriorities() {
List<Priority> actualPriorities = new ArrayList<Priority>();
for (String priority : getAvailablePriorities()) {
if (provider.getNumberOfAnnotations(priority) > 0) {
actualPriorities.add(Priority.fromString(priority)); // depends on control dependency: [if], data = [none]
}
}
return actualPriorities.toArray(new Priority[actualPriorities.size()]);
} } |
public class class_name {
public Chronology getChronology(Object object, Chronology chrono) {
if (chrono == null) {
chrono = ((ReadableInstant) object).getChronology();
chrono = DateTimeUtils.getChronology(chrono);
}
return chrono;
} } | public class class_name {
public Chronology getChronology(Object object, Chronology chrono) {
if (chrono == null) {
chrono = ((ReadableInstant) object).getChronology(); // depends on control dependency: [if], data = [none]
chrono = DateTimeUtils.getChronology(chrono); // depends on control dependency: [if], data = [(chrono]
}
return chrono;
} } |
public class class_name {
public void marshall(LogSetup logSetup, ProtocolMarshaller protocolMarshaller) {
if (logSetup == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(logSetup.getTypes(), TYPES_BINDING);
protocolMarshaller.marshall(logSetup.getEnabled(), ENABLED_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(LogSetup logSetup, ProtocolMarshaller protocolMarshaller) {
if (logSetup == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(logSetup.getTypes(), TYPES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(logSetup.getEnabled(), ENABLED_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 List<DependencyError> checkAllowedSection(final Dependencies dependencies, final Package<DependsOn> allowedPkg,
final ClassInfo classInfo) {
final List<DependencyError> errors = new ArrayList<DependencyError>();
final Iterator<String> it = classInfo.getImports().iterator();
while (it.hasNext()) {
final String importedPkg = it.next();
if (!importedPkg.equals(allowedPkg.getName()) && !dependencies.isAlwaysAllowed(importedPkg)) {
final DependsOn dep = Utils.findAllowedByName(allowedPkg.getDependencies(), importedPkg);
if (dep == null) {
errors.add(new DependencyError(classInfo.getName(), importedPkg, allowedPkg.getComment()));
}
}
}
return errors;
} } | public class class_name {
private List<DependencyError> checkAllowedSection(final Dependencies dependencies, final Package<DependsOn> allowedPkg,
final ClassInfo classInfo) {
final List<DependencyError> errors = new ArrayList<DependencyError>();
final Iterator<String> it = classInfo.getImports().iterator();
while (it.hasNext()) {
final String importedPkg = it.next();
if (!importedPkg.equals(allowedPkg.getName()) && !dependencies.isAlwaysAllowed(importedPkg)) {
final DependsOn dep = Utils.findAllowedByName(allowedPkg.getDependencies(), importedPkg);
if (dep == null) {
errors.add(new DependencyError(classInfo.getName(), importedPkg, allowedPkg.getComment()));
// depends on control dependency: [if], data = [none]
}
}
}
return errors;
} } |
public class class_name {
@Override
@ConstantTime(amortized = true)
public void insert(K key) {
if (key == null) {
throw new IllegalArgumentException("Null keys not permitted");
}
if (compare(key, maxKey) > 0) {
throw new IllegalArgumentException("Key is more than the maximum allowed key");
}
if (compare(key, lastDeletedKey) < 0) {
throw new IllegalArgumentException("Invalid key. Monotone heap.");
}
int b = computeBucket(key, lastDeletedKey);
buckets[b].add(key);
// update current minimum cache
if (currentMin == null || compare(key, currentMin) < 0) {
currentMin = key;
currentMinBucket = b;
currentMinPos = buckets[b].size() - 1;
}
size++;
} } | public class class_name {
@Override
@ConstantTime(amortized = true)
public void insert(K key) {
if (key == null) {
throw new IllegalArgumentException("Null keys not permitted");
}
if (compare(key, maxKey) > 0) {
throw new IllegalArgumentException("Key is more than the maximum allowed key");
}
if (compare(key, lastDeletedKey) < 0) {
throw new IllegalArgumentException("Invalid key. Monotone heap.");
}
int b = computeBucket(key, lastDeletedKey);
buckets[b].add(key);
// update current minimum cache
if (currentMin == null || compare(key, currentMin) < 0) {
currentMin = key; // depends on control dependency: [if], data = [none]
currentMinBucket = b; // depends on control dependency: [if], data = [none]
currentMinPos = buckets[b].size() - 1; // depends on control dependency: [if], data = [none]
}
size++;
} } |
public class class_name {
private void initiateParameterMap2(EntryReact entry) {
List<List<String>> paramDic = entry.getParameterClass();
paramsMap2 = new ArrayList<IParameterReact>();
for (Iterator<List<String>> it = paramDic.iterator(); it.hasNext();) {
List<String> param = it.next();
String paramName = "org.openscience.cdk.reaction.type.parameters." + param.get(0);
try {
IParameterReact ipc = (IParameterReact) this.getClass().getClassLoader().loadClass(paramName)
.newInstance();
ipc.setParameter(Boolean.parseBoolean(param.get(1)));
ipc.setValue(param.get(2));
logger.info("Loaded parameter class: ", paramName);
paramsMap2.add(ipc);
} catch (ClassNotFoundException exception) {
logger.error("Could not find this IParameterReact: ", paramName);
logger.debug(exception);
} catch (InstantiationException | IllegalAccessException exception) {
logger.error("Could not load this IParameterReact: ", paramName);
logger.debug(exception);
}
}
} } | public class class_name {
private void initiateParameterMap2(EntryReact entry) {
List<List<String>> paramDic = entry.getParameterClass();
paramsMap2 = new ArrayList<IParameterReact>();
for (Iterator<List<String>> it = paramDic.iterator(); it.hasNext();) {
List<String> param = it.next();
String paramName = "org.openscience.cdk.reaction.type.parameters." + param.get(0);
try {
IParameterReact ipc = (IParameterReact) this.getClass().getClassLoader().loadClass(paramName)
.newInstance();
ipc.setParameter(Boolean.parseBoolean(param.get(1))); // depends on control dependency: [try], data = [none]
ipc.setValue(param.get(2)); // depends on control dependency: [try], data = [none]
logger.info("Loaded parameter class: ", paramName); // depends on control dependency: [try], data = [none]
paramsMap2.add(ipc); // depends on control dependency: [try], data = [none]
} catch (ClassNotFoundException exception) {
logger.error("Could not find this IParameterReact: ", paramName);
logger.debug(exception);
} catch (InstantiationException | IllegalAccessException exception) { // depends on control dependency: [catch], data = [none]
logger.error("Could not load this IParameterReact: ", paramName);
logger.debug(exception);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public static synchronized void init(Configuration conf) {
if (!initDone) {
DefaultConfiguration.conf = conf;
DefaultConfiguration.initDone = true;
}
} } | public class class_name {
public static synchronized void init(Configuration conf) {
if (!initDone) {
DefaultConfiguration.conf = conf; // depends on control dependency: [if], data = [none]
DefaultConfiguration.initDone = true; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public int executeUpdate(String cmd, Transaction tx) {
if (tx.isReadOnly())
throw new UnsupportedOperationException();
Parser parser = new Parser(cmd);
Object obj = parser.updateCommand();
if (obj.getClass().equals(InsertData.class)) {
Verifier.verifyInsertData((InsertData) obj, tx);
return uPlanner.executeInsert((InsertData) obj, tx);
} else if (obj.getClass().equals(DeleteData.class)) {
Verifier.verifyDeleteData((DeleteData) obj, tx);
return uPlanner.executeDelete((DeleteData) obj, tx);
} else if (obj.getClass().equals(ModifyData.class)) {
Verifier.verifyModifyData((ModifyData) obj, tx);
return uPlanner.executeModify((ModifyData) obj, tx);
} else if (obj.getClass().equals(CreateTableData.class)) {
Verifier.verifyCreateTableData((CreateTableData) obj, tx);
return uPlanner.executeCreateTable((CreateTableData) obj, tx);
} else if (obj.getClass().equals(CreateViewData.class)) {
Verifier.verifyCreateViewData((CreateViewData) obj, tx);
return uPlanner.executeCreateView((CreateViewData) obj, tx);
} else if (obj.getClass().equals(CreateIndexData.class)) {
Verifier.verifyCreateIndexData((CreateIndexData) obj, tx);
return uPlanner.executeCreateIndex((CreateIndexData) obj, tx);
} else if (obj.getClass().equals(DropTableData.class)) {
Verifier.verifyDropTableData((DropTableData) obj, tx);
return uPlanner.executeDropTable((DropTableData) obj, tx);
} else if (obj.getClass().equals(DropViewData.class)) {
Verifier.verifyDropViewData((DropViewData) obj, tx);
return uPlanner.executeDropView((DropViewData) obj, tx);
} else if (obj.getClass().equals(DropIndexData.class)) {
Verifier.verifyDropIndexData((DropIndexData) obj, tx);
return uPlanner.executeDropIndex((DropIndexData) obj, tx);
} else
throw new UnsupportedOperationException();
} } | public class class_name {
public int executeUpdate(String cmd, Transaction tx) {
if (tx.isReadOnly())
throw new UnsupportedOperationException();
Parser parser = new Parser(cmd);
Object obj = parser.updateCommand();
if (obj.getClass().equals(InsertData.class)) {
Verifier.verifyInsertData((InsertData) obj, tx);
// depends on control dependency: [if], data = [none]
return uPlanner.executeInsert((InsertData) obj, tx);
// depends on control dependency: [if], data = [none]
} else if (obj.getClass().equals(DeleteData.class)) {
Verifier.verifyDeleteData((DeleteData) obj, tx);
// depends on control dependency: [if], data = [none]
return uPlanner.executeDelete((DeleteData) obj, tx);
// depends on control dependency: [if], data = [none]
} else if (obj.getClass().equals(ModifyData.class)) {
Verifier.verifyModifyData((ModifyData) obj, tx);
// depends on control dependency: [if], data = [none]
return uPlanner.executeModify((ModifyData) obj, tx);
// depends on control dependency: [if], data = [none]
} else if (obj.getClass().equals(CreateTableData.class)) {
Verifier.verifyCreateTableData((CreateTableData) obj, tx);
// depends on control dependency: [if], data = [none]
return uPlanner.executeCreateTable((CreateTableData) obj, tx);
// depends on control dependency: [if], data = [none]
} else if (obj.getClass().equals(CreateViewData.class)) {
Verifier.verifyCreateViewData((CreateViewData) obj, tx);
// depends on control dependency: [if], data = [none]
return uPlanner.executeCreateView((CreateViewData) obj, tx);
// depends on control dependency: [if], data = [none]
} else if (obj.getClass().equals(CreateIndexData.class)) {
Verifier.verifyCreateIndexData((CreateIndexData) obj, tx);
// depends on control dependency: [if], data = [none]
return uPlanner.executeCreateIndex((CreateIndexData) obj, tx);
// depends on control dependency: [if], data = [none]
} else if (obj.getClass().equals(DropTableData.class)) {
Verifier.verifyDropTableData((DropTableData) obj, tx);
// depends on control dependency: [if], data = [none]
return uPlanner.executeDropTable((DropTableData) obj, tx);
// depends on control dependency: [if], data = [none]
} else if (obj.getClass().equals(DropViewData.class)) {
Verifier.verifyDropViewData((DropViewData) obj, tx);
// depends on control dependency: [if], data = [none]
return uPlanner.executeDropView((DropViewData) obj, tx);
// depends on control dependency: [if], data = [none]
} else if (obj.getClass().equals(DropIndexData.class)) {
Verifier.verifyDropIndexData((DropIndexData) obj, tx);
// depends on control dependency: [if], data = [none]
return uPlanner.executeDropIndex((DropIndexData) obj, tx);
// depends on control dependency: [if], data = [none]
} else
throw new UnsupportedOperationException();
} } |
public class class_name {
public XWPFParagraph insertNewParagraph(XWPFRun run) {
// XmlCursor cursor = run.getCTR().newCursor();
XmlCursor cursor = ((XWPFParagraph) run.getParent()).getCTP().newCursor();
if (isCursorInBody(cursor)) {
String uri = CTP.type.getName().getNamespaceURI();
/*
* TODO DO not use a coded constant, find the constant in the OOXML
* classes instead, as the child of type CT_Paragraph is defined in
* the OOXML schema as 'p'
*/
String localPart = "p";
// creates a new Paragraph, cursor is positioned inside the new
// element
cursor.beginElement(localPart, uri);
// move the cursor to the START token to the paragraph just created
cursor.toParent();
CTP p = (CTP) cursor.getObject();
XWPFParagraph newP = new XWPFParagraph(p, this);
XmlObject o = null;
/*
* move the cursor to the previous element until a) the next
* paragraph is found or b) all elements have been passed
*/
while (!(o instanceof CTP) && (cursor.toPrevSibling())) {
o = cursor.getObject();
}
/*
* if the object that has been found is a) not a paragraph or b) is
* the paragraph that has just been inserted, as the cursor in the
* while loop above was not moved as there were no other siblings,
* then the paragraph that was just inserted is the first paragraph
* in the body. Otherwise, take the previous paragraph and calculate
* the new index for the new paragraph.
*/
if ((!(o instanceof CTP)) || (CTP) o == p) {
paragraphs.add(0, newP);
} else {
int pos = paragraphs.indexOf(getParagraph((CTP) o)) + 1;
paragraphs.add(pos, newP);
}
/*
* create a new cursor, that points to the START token of the just
* inserted paragraph
*/
XmlCursor newParaPos = p.newCursor();
try {
/*
* Calculate the paragraphs index in the list of all body
* elements
*/
int i = 0;
cursor.toCursor(newParaPos);
while (cursor.toPrevSibling()) {
o = cursor.getObject();
if (o instanceof CTP || o instanceof CTTbl) i++;
}
bodyElements.add(i > bodyElements.size() ? bodyElements.size() : i, newP);
cursor.toCursor(newParaPos);
cursor.toEndToken();
return newP;
}
finally {
newParaPos.dispose();
}
}
return null;
} } | public class class_name {
public XWPFParagraph insertNewParagraph(XWPFRun run) {
// XmlCursor cursor = run.getCTR().newCursor();
XmlCursor cursor = ((XWPFParagraph) run.getParent()).getCTP().newCursor();
if (isCursorInBody(cursor)) {
String uri = CTP.type.getName().getNamespaceURI();
/*
* TODO DO not use a coded constant, find the constant in the OOXML
* classes instead, as the child of type CT_Paragraph is defined in
* the OOXML schema as 'p'
*/
String localPart = "p";
// creates a new Paragraph, cursor is positioned inside the new
// element
cursor.beginElement(localPart, uri); // depends on control dependency: [if], data = [none]
// move the cursor to the START token to the paragraph just created
cursor.toParent(); // depends on control dependency: [if], data = [none]
CTP p = (CTP) cursor.getObject();
XWPFParagraph newP = new XWPFParagraph(p, this);
XmlObject o = null;
/*
* move the cursor to the previous element until a) the next
* paragraph is found or b) all elements have been passed
*/
while (!(o instanceof CTP) && (cursor.toPrevSibling())) {
o = cursor.getObject(); // depends on control dependency: [while], data = [none]
}
/*
* if the object that has been found is a) not a paragraph or b) is
* the paragraph that has just been inserted, as the cursor in the
* while loop above was not moved as there were no other siblings,
* then the paragraph that was just inserted is the first paragraph
* in the body. Otherwise, take the previous paragraph and calculate
* the new index for the new paragraph.
*/
if ((!(o instanceof CTP)) || (CTP) o == p) {
paragraphs.add(0, newP); // depends on control dependency: [if], data = [none]
} else {
int pos = paragraphs.indexOf(getParagraph((CTP) o)) + 1;
paragraphs.add(pos, newP); // depends on control dependency: [if], data = [none]
}
/*
* create a new cursor, that points to the START token of the just
* inserted paragraph
*/
XmlCursor newParaPos = p.newCursor();
try {
/*
* Calculate the paragraphs index in the list of all body
* elements
*/
int i = 0;
cursor.toCursor(newParaPos); // depends on control dependency: [try], data = [none]
while (cursor.toPrevSibling()) {
o = cursor.getObject(); // depends on control dependency: [while], data = [none]
if (o instanceof CTP || o instanceof CTTbl) i++;
}
bodyElements.add(i > bodyElements.size() ? bodyElements.size() : i, newP); // depends on control dependency: [try], data = [none]
cursor.toCursor(newParaPos); // depends on control dependency: [try], data = [none]
cursor.toEndToken(); // depends on control dependency: [try], data = [none]
return newP; // depends on control dependency: [try], data = [none]
}
finally {
newParaPos.dispose();
}
}
return null;
} } |
public class class_name {
public void shutdown() {
/**
* Probably we don't need this method in practice
*/
if (initLocker.get() && shutdownLocker.compareAndSet(false, true)) {
// do shutdown
log.info("Shutting down transport...");
// we just sending out ShutdownRequestMessage
//transport.sendMessage(new ShutdownRequestMessage());
transport.shutdown();
executor.shutdown();
initFinished.set(false);
initLocker.set(false);
shutdownLocker.set(false);
}
} } | public class class_name {
public void shutdown() {
/**
* Probably we don't need this method in practice
*/
if (initLocker.get() && shutdownLocker.compareAndSet(false, true)) {
// do shutdown
log.info("Shutting down transport..."); // depends on control dependency: [if], data = [none]
// we just sending out ShutdownRequestMessage
//transport.sendMessage(new ShutdownRequestMessage());
transport.shutdown(); // depends on control dependency: [if], data = [none]
executor.shutdown(); // depends on control dependency: [if], data = [none]
initFinished.set(false); // depends on control dependency: [if], data = [none]
initLocker.set(false); // depends on control dependency: [if], data = [none]
shutdownLocker.set(false); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Nullable
public static AnnotationTree getAnnotationWithSimpleName(
List<? extends AnnotationTree> annotations, String name) {
for (AnnotationTree annotation : annotations) {
if (hasSimpleName(annotation, name)) {
return annotation;
}
}
return null;
} } | public class class_name {
@Nullable
public static AnnotationTree getAnnotationWithSimpleName(
List<? extends AnnotationTree> annotations, String name) {
for (AnnotationTree annotation : annotations) {
if (hasSimpleName(annotation, name)) {
return annotation; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public void compileNode(DecisionService ds, DMNCompilerImpl compiler, DMNModelImpl model) {
DMNType type = null;
if (ds.getVariable() == null) { // even for the v1.1 backport, variable creation is taken care in DMNCompiler.
DMNCompilerHelper.reportMissingVariable(model, ds, ds, Msg.MISSING_VARIABLE_FOR_DS);
return;
}
DMNCompilerHelper.checkVariableName(model, ds, ds.getName());
if (ds.getVariable() != null && ds.getVariable().getTypeRef() != null) {
type = compiler.resolveTypeRef(model, ds, ds.getVariable(), ds.getVariable().getTypeRef());
} else {
// for now the call bellow will return type UNKNOWN
type = compiler.resolveTypeRef(model, ds, ds, null);
}
DecisionServiceNodeImpl bkmn = new DecisionServiceNodeImpl(ds, type);
model.addDecisionService(bkmn);
} } | public class class_name {
public void compileNode(DecisionService ds, DMNCompilerImpl compiler, DMNModelImpl model) {
DMNType type = null;
if (ds.getVariable() == null) { // even for the v1.1 backport, variable creation is taken care in DMNCompiler.
DMNCompilerHelper.reportMissingVariable(model, ds, ds, Msg.MISSING_VARIABLE_FOR_DS); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
DMNCompilerHelper.checkVariableName(model, ds, ds.getName());
if (ds.getVariable() != null && ds.getVariable().getTypeRef() != null) {
type = compiler.resolveTypeRef(model, ds, ds.getVariable(), ds.getVariable().getTypeRef()); // depends on control dependency: [if], data = [none]
} else {
// for now the call bellow will return type UNKNOWN
type = compiler.resolveTypeRef(model, ds, ds, null); // depends on control dependency: [if], data = [none]
}
DecisionServiceNodeImpl bkmn = new DecisionServiceNodeImpl(ds, type);
model.addDecisionService(bkmn);
} } |
public class class_name {
@Override
public SecuritySetter<HttpURLConnection> basicAuth(String user, String password) throws CadiException {
if(password.startsWith("enc:???")) {
try {
password = access.decrypt(password, true);
} catch (IOException e) {
throw new CadiException("Error decrypting password",e);
}
}
try {
return new HBasicAuthSS(user,password,si);
} catch (IOException e) {
throw new CadiException("Error creating HBasicAuthSS",e);
}
} } | public class class_name {
@Override
public SecuritySetter<HttpURLConnection> basicAuth(String user, String password) throws CadiException {
if(password.startsWith("enc:???")) {
try {
password = access.decrypt(password, true); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new CadiException("Error decrypting password",e);
} // depends on control dependency: [catch], data = [none]
}
try {
return new HBasicAuthSS(user,password,si);
} catch (IOException e) {
throw new CadiException("Error creating HBasicAuthSS",e);
}
} } |
public class class_name {
public void prependMessage(String message) {
if (iMessage == null) {
iMessage = message;
} else if (message != null) {
iMessage = message + ": " + iMessage;
}
} } | public class class_name {
public void prependMessage(String message) {
if (iMessage == null) {
iMessage = message; // depends on control dependency: [if], data = [none]
} else if (message != null) {
iMessage = message + ": " + iMessage; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static void addEvidence(ProbabilisticNetwork bn, String nodeName,
String status) throws ShanksException {
ProbabilisticNode node = ShanksAgentBayesianReasoningCapability
.getNode(bn, nodeName);
if (node.hasEvidence()) {
ShanksAgentBayesianReasoningCapability.clearEvidence(bn, node);
}
int states = node.getStatesSize();
for (int i = 0; i < states; i++) {
if (status.equals(node.getStateAt(i))) {
node.addFinding(i);
try {
bn.updateEvidences();
} catch (Exception e) {
throw new ShanksException(e);
}
return;
}
}
throw new UnknowkNodeStateException(bn, nodeName, status);
} } | public class class_name {
public static void addEvidence(ProbabilisticNetwork bn, String nodeName,
String status) throws ShanksException {
ProbabilisticNode node = ShanksAgentBayesianReasoningCapability
.getNode(bn, nodeName);
if (node.hasEvidence()) {
ShanksAgentBayesianReasoningCapability.clearEvidence(bn, node);
}
int states = node.getStatesSize();
for (int i = 0; i < states; i++) {
if (status.equals(node.getStateAt(i))) {
node.addFinding(i);
try {
bn.updateEvidences(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new ShanksException(e);
} // depends on control dependency: [catch], data = [none]
return;
}
}
throw new UnknowkNodeStateException(bn, nodeName, status);
} } |
public class class_name {
private void selectQueryNode(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_selectQueryNode
String currentQuery = "";
DefaultMutableTreeNode node = (DefaultMutableTreeNode) evt.getPath().getLastPathComponent();
if (node instanceof QueryTreeElement) {
QueryTreeElement queryElement = (QueryTreeElement)node;
currentQuery = queryElement.getQuery();
currentId = queryElement;
TreeNode parent = queryElement.getParent();
if (parent == null || parent.toString().equals("")) {
fireQueryChanged("", currentQuery, currentId.getID());
}
else {
fireQueryChanged(parent.toString(), currentQuery, currentId.getID());
}
}
else if (node instanceof QueryGroupTreeElement) {
QueryGroupTreeElement groupElement = (QueryGroupTreeElement)node;
currentId = null;
currentQuery = null;
fireQueryChanged(groupElement.toString(), "", "");
}
else if (node == null) {
currentId = null;
currentQuery = null;
}
} } | public class class_name {
private void selectQueryNode(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_selectQueryNode
String currentQuery = "";
DefaultMutableTreeNode node = (DefaultMutableTreeNode) evt.getPath().getLastPathComponent();
if (node instanceof QueryTreeElement) {
QueryTreeElement queryElement = (QueryTreeElement)node;
currentQuery = queryElement.getQuery(); // depends on control dependency: [if], data = [none]
currentId = queryElement; // depends on control dependency: [if], data = [none]
TreeNode parent = queryElement.getParent();
if (parent == null || parent.toString().equals("")) {
fireQueryChanged("", currentQuery, currentId.getID()); // depends on control dependency: [if], data = [none]
}
else {
fireQueryChanged(parent.toString(), currentQuery, currentId.getID()); // depends on control dependency: [if], data = [(parent]
}
}
else if (node instanceof QueryGroupTreeElement) {
QueryGroupTreeElement groupElement = (QueryGroupTreeElement)node;
currentId = null; // depends on control dependency: [if], data = [none]
currentQuery = null; // depends on control dependency: [if], data = [none]
fireQueryChanged(groupElement.toString(), "", ""); // depends on control dependency: [if], data = [none]
}
else if (node == null) {
currentId = null; // depends on control dependency: [if], data = [none]
currentQuery = null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected final O execute(@Nullable EventLoop eventLoop,
HttpMethod method, String path, @Nullable String query, @Nullable String fragment,
I req, BiFunction<ClientRequestContext, Throwable, O> fallback) {
final ClientRequestContext ctx;
if (eventLoop == null) {
final ReleasableHolder<EventLoop> releasableEventLoop = factory().acquireEventLoop(endpoint);
ctx = new DefaultClientRequestContext(
releasableEventLoop.get(), meterRegistry, sessionProtocol, endpoint,
method, path, query, fragment, options(), req);
ctx.log().addListener(log -> releasableEventLoop.release(), RequestLogAvailability.COMPLETE);
} else {
ctx = new DefaultClientRequestContext(eventLoop, meterRegistry, sessionProtocol, endpoint,
method, path, query, fragment, options(), req);
}
return executeWithFallback(delegate(), ctx, req, fallback);
} } | public class class_name {
protected final O execute(@Nullable EventLoop eventLoop,
HttpMethod method, String path, @Nullable String query, @Nullable String fragment,
I req, BiFunction<ClientRequestContext, Throwable, O> fallback) {
final ClientRequestContext ctx;
if (eventLoop == null) {
final ReleasableHolder<EventLoop> releasableEventLoop = factory().acquireEventLoop(endpoint);
ctx = new DefaultClientRequestContext(
releasableEventLoop.get(), meterRegistry, sessionProtocol, endpoint,
method, path, query, fragment, options(), req); // depends on control dependency: [if], data = [none]
ctx.log().addListener(log -> releasableEventLoop.release(), RequestLogAvailability.COMPLETE); // depends on control dependency: [if], data = [none]
} else {
ctx = new DefaultClientRequestContext(eventLoop, meterRegistry, sessionProtocol, endpoint,
method, path, query, fragment, options(), req); // depends on control dependency: [if], data = [(eventLoop]
}
return executeWithFallback(delegate(), ctx, req, fallback);
} } |
public class class_name {
public Object expand(Context activeCtx, String activeProperty, Object element)
throws JsonLdError {
final boolean frameExpansion = this.opts.getFrameExpansion();
// 1)
if (element == null) {
return null;
}
// 3)
if (element instanceof List) {
// 3.1)
final List<Object> result = new ArrayList<Object>();
// 3.2)
for (final Object item : (List<Object>) element) {
// 3.2.1)
final Object v = expand(activeCtx, activeProperty, item);
// 3.2.2)
if ((JsonLdConsts.LIST.equals(activeProperty)
|| JsonLdConsts.LIST.equals(activeCtx.getContainer(activeProperty)))
&& (v instanceof List || (v instanceof Map
&& ((Map<String, Object>) v).containsKey(JsonLdConsts.LIST)))) {
throw new JsonLdError(Error.LIST_OF_LISTS, "lists of lists are not permitted.");
}
// 3.2.3)
else if (v != null) {
if (v instanceof List) {
result.addAll((Collection<? extends Object>) v);
} else {
result.add(v);
}
}
}
// 3.3)
return result;
}
// 4)
else if (element instanceof Map) {
// access helper
final Map<String, Object> elem = (Map<String, Object>) element;
// 5)
if (elem.containsKey(JsonLdConsts.CONTEXT)) {
activeCtx = activeCtx.parse(elem.get(JsonLdConsts.CONTEXT));
}
// 6)
Map<String, Object> result = newMap();
// 7)
final List<String> keys = new ArrayList<String>(elem.keySet());
Collections.sort(keys);
for (final String key : keys) {
final Object value = elem.get(key);
// 7.1)
if (key.equals(JsonLdConsts.CONTEXT)) {
continue;
}
// 7.2)
final String expandedProperty = activeCtx.expandIri(key, false, true, null, null);
Object expandedValue = null;
// 7.3)
if (expandedProperty == null
|| (!expandedProperty.contains(":") && !isKeyword(expandedProperty))) {
continue;
}
// 7.4)
if (isKeyword(expandedProperty)) {
// 7.4.1)
if (JsonLdConsts.REVERSE.equals(activeProperty)) {
throw new JsonLdError(Error.INVALID_REVERSE_PROPERTY_MAP,
"a keyword cannot be used as a @reverse propery");
}
// 7.4.2)
if (result.containsKey(expandedProperty)) {
throw new JsonLdError(Error.COLLIDING_KEYWORDS,
expandedProperty + " already exists in result");
}
// 7.4.3)
if (JsonLdConsts.ID.equals(expandedProperty)) {
if (value instanceof String) {
expandedValue = activeCtx.expandIri((String) value, true, false, null,
null);
} else if (frameExpansion) {
if (value instanceof Map) {
if (((Map<String, Object>) value).size() != 0) {
throw new JsonLdError(Error.INVALID_ID_VALUE,
"@id value must be a an empty object for framing");
}
expandedValue = value;
} else if (value instanceof List) {
expandedValue = new ArrayList<String>();
for (final Object v : (List<Object>) value) {
if (!(v instanceof String)) {
throw new JsonLdError(Error.INVALID_ID_VALUE,
"@id value must be a string, an array of strings or an empty dictionary");
}
((List<String>) expandedValue).add(activeCtx
.expandIri((String) v, true, true, null, null));
}
} else {
throw new JsonLdError(Error.INVALID_ID_VALUE,
"value of @id must be a string, an array of strings or an empty dictionary");
}
} else {
throw new JsonLdError(Error.INVALID_ID_VALUE,
"value of @id must be a string");
}
}
// 7.4.4)
else if (JsonLdConsts.TYPE.equals(expandedProperty)) {
if (value instanceof List) {
expandedValue = new ArrayList<String>();
for (final Object v : (List) value) {
if (!(v instanceof String)) {
throw new JsonLdError(Error.INVALID_TYPE_VALUE,
"@type value must be a string or array of strings");
}
((List<String>) expandedValue).add(
activeCtx.expandIri((String) v, true, true, null, null));
}
} else if (value instanceof String) {
expandedValue = activeCtx.expandIri((String) value, true, true, null,
null);
}
// TODO: SPEC: no mention of empty map check
else if (frameExpansion && value instanceof Map) {
if (!((Map<String, Object>) value).isEmpty()) {
throw new JsonLdError(Error.INVALID_TYPE_VALUE,
"@type value must be a an empty object for framing");
}
expandedValue = value;
} else {
throw new JsonLdError(Error.INVALID_TYPE_VALUE,
"@type value must be a string or array of strings");
}
}
// 7.4.5)
else if (JsonLdConsts.GRAPH.equals(expandedProperty)) {
expandedValue = expand(activeCtx, JsonLdConsts.GRAPH, value);
}
// 7.4.6)
else if (JsonLdConsts.VALUE.equals(expandedProperty)) {
if (value != null && (value instanceof Map || value instanceof List)) {
throw new JsonLdError(Error.INVALID_VALUE_OBJECT_VALUE,
"value of " + expandedProperty + " must be a scalar or null");
}
expandedValue = value;
if (expandedValue == null) {
result.put(JsonLdConsts.VALUE, null);
continue;
}
}
// 7.4.7)
else if (JsonLdConsts.LANGUAGE.equals(expandedProperty)) {
if (!(value instanceof String)) {
throw new JsonLdError(Error.INVALID_LANGUAGE_TAGGED_STRING,
"Value of " + expandedProperty + " must be a string");
}
expandedValue = ((String) value).toLowerCase();
}
// 7.4.8)
else if (JsonLdConsts.INDEX.equals(expandedProperty)) {
if (!(value instanceof String)) {
throw new JsonLdError(Error.INVALID_INDEX_VALUE,
"Value of " + expandedProperty + " must be a string");
}
expandedValue = value;
}
// 7.4.9)
else if (JsonLdConsts.LIST.equals(expandedProperty)) {
// 7.4.9.1)
if (activeProperty == null || JsonLdConsts.GRAPH.equals(activeProperty)) {
continue;
}
// 7.4.9.2)
expandedValue = expand(activeCtx, activeProperty, value);
// NOTE: step not in the spec yet
if (!(expandedValue instanceof List)) {
final List<Object> tmp = new ArrayList<Object>();
tmp.add(expandedValue);
expandedValue = tmp;
}
// 7.4.9.3)
for (final Object o : (List<Object>) expandedValue) {
if (o instanceof Map
&& ((Map<String, Object>) o).containsKey(JsonLdConsts.LIST)) {
throw new JsonLdError(Error.LIST_OF_LISTS,
"A list may not contain another list");
}
}
}
// 7.4.10)
else if (JsonLdConsts.SET.equals(expandedProperty)) {
expandedValue = expand(activeCtx, activeProperty, value);
}
// 7.4.11)
else if (JsonLdConsts.REVERSE.equals(expandedProperty)) {
if (!(value instanceof Map)) {
throw new JsonLdError(Error.INVALID_REVERSE_VALUE,
"@reverse value must be an object");
}
// 7.4.11.1)
expandedValue = expand(activeCtx, JsonLdConsts.REVERSE, value);
// NOTE: algorithm assumes the result is a map
// 7.4.11.2)
if (((Map<String, Object>) expandedValue)
.containsKey(JsonLdConsts.REVERSE)) {
final Map<String, Object> reverse = (Map<String, Object>) ((Map<String, Object>) expandedValue)
.get(JsonLdConsts.REVERSE);
for (final String property : reverse.keySet()) {
final Object item = reverse.get(property);
// 7.4.11.2.1)
if (!result.containsKey(property)) {
result.put(property, new ArrayList<Object>());
}
// 7.4.11.2.2)
if (item instanceof List) {
((List<Object>) result.get(property))
.addAll((List<Object>) item);
} else {
((List<Object>) result.get(property)).add(item);
}
}
}
// 7.4.11.3)
if (((Map<String, Object>) expandedValue)
.size() > (((Map<String, Object>) expandedValue)
.containsKey(JsonLdConsts.REVERSE) ? 1 : 0)) {
// 7.4.11.3.1)
if (!result.containsKey(JsonLdConsts.REVERSE)) {
result.put(JsonLdConsts.REVERSE, newMap());
}
// 7.4.11.3.2)
final Map<String, Object> reverseMap = (Map<String, Object>) result
.get(JsonLdConsts.REVERSE);
// 7.4.11.3.3)
for (final String property : ((Map<String, Object>) expandedValue)
.keySet()) {
if (JsonLdConsts.REVERSE.equals(property)) {
continue;
}
// 7.4.11.3.3.1)
final List<Object> items = (List<Object>) ((Map<String, Object>) expandedValue)
.get(property);
for (final Object item : items) {
// 7.4.11.3.3.1.1)
if (item instanceof Map && (((Map<String, Object>) item)
.containsKey(JsonLdConsts.VALUE)
|| ((Map<String, Object>) item)
.containsKey(JsonLdConsts.LIST))) {
throw new JsonLdError(Error.INVALID_REVERSE_PROPERTY_VALUE);
}
// 7.4.11.3.3.1.2)
if (!reverseMap.containsKey(property)) {
reverseMap.put(property, new ArrayList<Object>());
}
// 7.4.11.3.3.1.3)
((List<Object>) reverseMap.get(property)).add(item);
}
}
}
// 7.4.11.4)
continue;
}
// TODO: SPEC no mention of @explicit etc in spec
else if (frameExpansion && (JsonLdConsts.EXPLICIT.equals(expandedProperty)
|| JsonLdConsts.DEFAULT.equals(expandedProperty)
|| JsonLdConsts.EMBED.equals(expandedProperty)
|| JsonLdConsts.REQUIRE_ALL.equals(expandedProperty)
|| JsonLdConsts.EMBED_CHILDREN.equals(expandedProperty)
|| JsonLdConsts.OMIT_DEFAULT.equals(expandedProperty))) {
expandedValue = expand(activeCtx, expandedProperty, value);
}
// 7.4.12)
if (expandedValue != null) {
result.put(expandedProperty, expandedValue);
}
// 7.4.13)
continue;
}
// 7.5
else if (JsonLdConsts.LANGUAGE.equals(activeCtx.getContainer(key))
&& value instanceof Map) {
// 7.5.1)
expandedValue = new ArrayList<Object>();
// 7.5.2)
for (final String language : ((Map<String, Object>) value).keySet()) {
Object languageValue = ((Map<String, Object>) value).get(language);
// 7.5.2.1)
if (!(languageValue instanceof List)) {
final Object tmp = languageValue;
languageValue = new ArrayList<Object>();
((List<Object>) languageValue).add(tmp);
}
// 7.5.2.2)
for (final Object item : (List<Object>) languageValue) {
// 7.5.2.2.1)
if (!(item instanceof String)) {
throw new JsonLdError(Error.INVALID_LANGUAGE_MAP_VALUE,
"Expected " + item.toString() + " to be a string");
}
// 7.5.2.2.2)
final Map<String, Object> tmp = newMap();
tmp.put(JsonLdConsts.VALUE, item);
tmp.put(JsonLdConsts.LANGUAGE, language.toLowerCase());
((List<Object>) expandedValue).add(tmp);
}
}
}
// 7.6)
else if (JsonLdConsts.INDEX.equals(activeCtx.getContainer(key))
&& value instanceof Map) {
// 7.6.1)
expandedValue = new ArrayList<Object>();
// 7.6.2)
final List<String> indexKeys = new ArrayList<String>(
((Map<String, Object>) value).keySet());
Collections.sort(indexKeys);
for (final String index : indexKeys) {
Object indexValue = ((Map<String, Object>) value).get(index);
// 7.6.2.1)
if (!(indexValue instanceof List)) {
final Object tmp = indexValue;
indexValue = new ArrayList<Object>();
((List<Object>) indexValue).add(tmp);
}
// 7.6.2.2)
indexValue = expand(activeCtx, key, indexValue);
// 7.6.2.3)
for (final Map<String, Object> item : (List<Map<String, Object>>) indexValue) {
// 7.6.2.3.1)
if (!item.containsKey(JsonLdConsts.INDEX)) {
item.put(JsonLdConsts.INDEX, index);
}
// 7.6.2.3.2)
((List<Object>) expandedValue).add(item);
}
}
}
// 7.7)
else {
expandedValue = expand(activeCtx, key, value);
}
// 7.8)
if (expandedValue == null) {
continue;
}
// 7.9)
if (JsonLdConsts.LIST.equals(activeCtx.getContainer(key))) {
if (!(expandedValue instanceof Map) || !((Map<String, Object>) expandedValue)
.containsKey(JsonLdConsts.LIST)) {
Object tmp = expandedValue;
if (!(tmp instanceof List)) {
tmp = new ArrayList<Object>();
((List<Object>) tmp).add(expandedValue);
}
expandedValue = newMap();
((Map<String, Object>) expandedValue).put(JsonLdConsts.LIST, tmp);
}
}
// 7.10)
if (activeCtx.isReverseProperty(key)) {
// 7.10.1)
if (!result.containsKey(JsonLdConsts.REVERSE)) {
result.put(JsonLdConsts.REVERSE, newMap());
}
// 7.10.2)
final Map<String, Object> reverseMap = (Map<String, Object>) result
.get(JsonLdConsts.REVERSE);
// 7.10.3)
if (!(expandedValue instanceof List)) {
final Object tmp = expandedValue;
expandedValue = new ArrayList<Object>();
((List<Object>) expandedValue).add(tmp);
}
// 7.10.4)
for (final Object item : (List<Object>) expandedValue) {
// 7.10.4.1)
if (item instanceof Map && (((Map<String, Object>) item)
.containsKey(JsonLdConsts.VALUE)
|| ((Map<String, Object>) item).containsKey(JsonLdConsts.LIST))) {
throw new JsonLdError(Error.INVALID_REVERSE_PROPERTY_VALUE);
}
// 7.10.4.2)
if (!reverseMap.containsKey(expandedProperty)) {
reverseMap.put(expandedProperty, new ArrayList<Object>());
}
// 7.10.4.3)
if (item instanceof List) {
((List<Object>) reverseMap.get(expandedProperty))
.addAll((List<Object>) item);
} else {
((List<Object>) reverseMap.get(expandedProperty)).add(item);
}
}
}
// 7.11)
else {
// 7.11.1)
if (!result.containsKey(expandedProperty)) {
result.put(expandedProperty, new ArrayList<Object>());
}
// 7.11.2)
if (expandedValue instanceof List) {
((List<Object>) result.get(expandedProperty))
.addAll((List<Object>) expandedValue);
} else {
((List<Object>) result.get(expandedProperty)).add(expandedValue);
}
}
}
// 8)
if (result.containsKey(JsonLdConsts.VALUE)) {
// 8.1)
// TODO: is this method faster than just using containsKey for
// each?
final Set<String> keySet = new HashSet<>(result.keySet());
keySet.remove(JsonLdConsts.VALUE);
keySet.remove(JsonLdConsts.INDEX);
final boolean langremoved = keySet.remove(JsonLdConsts.LANGUAGE);
final boolean typeremoved = keySet.remove(JsonLdConsts.TYPE);
if ((langremoved && typeremoved) || !keySet.isEmpty()) {
throw new JsonLdError(Error.INVALID_VALUE_OBJECT,
"value object has unknown keys");
}
// 8.2)
final Object rval = result.get(JsonLdConsts.VALUE);
if (rval == null) {
// nothing else is possible with result if we set it to
// null, so simply return it
return null;
}
// 8.3)
if (!(rval instanceof String) && result.containsKey(JsonLdConsts.LANGUAGE)) {
throw new JsonLdError(Error.INVALID_LANGUAGE_TAGGED_VALUE,
"when @language is used, @value must be a string");
}
// 8.4)
else if (result.containsKey(JsonLdConsts.TYPE)) {
// TODO: is this enough for "is an IRI"
if (!(result.get(JsonLdConsts.TYPE) instanceof String)
|| ((String) result.get(JsonLdConsts.TYPE)).startsWith("_:")
|| !((String) result.get(JsonLdConsts.TYPE)).contains(":")) {
throw new JsonLdError(Error.INVALID_TYPED_VALUE,
"value of @type must be an IRI");
}
}
}
// 9)
else if (result.containsKey(JsonLdConsts.TYPE)) {
final Object rtype = result.get(JsonLdConsts.TYPE);
if (!(rtype instanceof List)) {
final List<Object> tmp = new ArrayList<Object>();
tmp.add(rtype);
result.put(JsonLdConsts.TYPE, tmp);
}
}
// 10)
else if (result.containsKey(JsonLdConsts.SET)
|| result.containsKey(JsonLdConsts.LIST)) {
// 10.1)
if (result.size() > (result.containsKey(JsonLdConsts.INDEX) ? 2 : 1)) {
throw new JsonLdError(Error.INVALID_SET_OR_LIST_OBJECT,
"@set or @list may only contain @index");
}
// 10.2)
if (result.containsKey(JsonLdConsts.SET)) {
// result becomes an array here, thus the remaining checks
// will never be true from here on
// so simply return the value rather than have to make
// result an object and cast it with every
// other use in the function.
return result.get(JsonLdConsts.SET);
}
}
// 11)
if (result.containsKey(JsonLdConsts.LANGUAGE) && result.size() == 1) {
result = null;
}
// 12)
if (activeProperty == null || JsonLdConsts.GRAPH.equals(activeProperty)) {
// 12.1)
if (result != null && (result.size() == 0 || result.containsKey(JsonLdConsts.VALUE)
|| result.containsKey(JsonLdConsts.LIST))) {
result = null;
}
// 12.2)
else if (result != null && !frameExpansion && result.containsKey(JsonLdConsts.ID)
&& result.size() == 1) {
result = null;
}
}
// 13)
return result;
}
// 2) If element is a scalar
else {
// 2.1)
if (activeProperty == null || JsonLdConsts.GRAPH.equals(activeProperty)) {
return null;
}
return activeCtx.expandValue(activeProperty, element);
}
} } | public class class_name {
public Object expand(Context activeCtx, String activeProperty, Object element)
throws JsonLdError {
final boolean frameExpansion = this.opts.getFrameExpansion();
// 1)
if (element == null) {
return null;
}
// 3)
if (element instanceof List) {
// 3.1)
final List<Object> result = new ArrayList<Object>();
// 3.2)
for (final Object item : (List<Object>) element) {
// 3.2.1)
final Object v = expand(activeCtx, activeProperty, item);
// 3.2.2)
if ((JsonLdConsts.LIST.equals(activeProperty)
|| JsonLdConsts.LIST.equals(activeCtx.getContainer(activeProperty)))
&& (v instanceof List || (v instanceof Map
&& ((Map<String, Object>) v).containsKey(JsonLdConsts.LIST)))) {
throw new JsonLdError(Error.LIST_OF_LISTS, "lists of lists are not permitted.");
}
// 3.2.3)
else if (v != null) {
if (v instanceof List) {
result.addAll((Collection<? extends Object>) v); // depends on control dependency: [if], data = [none]
} else {
result.add(v); // depends on control dependency: [if], data = [none]
}
}
}
// 3.3)
return result;
}
// 4)
else if (element instanceof Map) {
// access helper
final Map<String, Object> elem = (Map<String, Object>) element;
// 5)
if (elem.containsKey(JsonLdConsts.CONTEXT)) {
activeCtx = activeCtx.parse(elem.get(JsonLdConsts.CONTEXT)); // depends on control dependency: [if], data = [none]
}
// 6)
Map<String, Object> result = newMap();
// 7)
final List<String> keys = new ArrayList<String>(elem.keySet());
Collections.sort(keys);
for (final String key : keys) {
final Object value = elem.get(key);
// 7.1)
if (key.equals(JsonLdConsts.CONTEXT)) {
continue;
}
// 7.2)
final String expandedProperty = activeCtx.expandIri(key, false, true, null, null);
Object expandedValue = null;
// 7.3)
if (expandedProperty == null
|| (!expandedProperty.contains(":") && !isKeyword(expandedProperty))) {
continue;
}
// 7.4)
if (isKeyword(expandedProperty)) {
// 7.4.1)
if (JsonLdConsts.REVERSE.equals(activeProperty)) {
throw new JsonLdError(Error.INVALID_REVERSE_PROPERTY_MAP,
"a keyword cannot be used as a @reverse propery");
}
// 7.4.2)
if (result.containsKey(expandedProperty)) {
throw new JsonLdError(Error.COLLIDING_KEYWORDS,
expandedProperty + " already exists in result");
}
// 7.4.3)
if (JsonLdConsts.ID.equals(expandedProperty)) {
if (value instanceof String) {
expandedValue = activeCtx.expandIri((String) value, true, false, null,
null); // depends on control dependency: [if], data = [none]
} else if (frameExpansion) {
if (value instanceof Map) {
if (((Map<String, Object>) value).size() != 0) {
throw new JsonLdError(Error.INVALID_ID_VALUE,
"@id value must be a an empty object for framing");
}
expandedValue = value; // depends on control dependency: [if], data = [none]
} else if (value instanceof List) {
expandedValue = new ArrayList<String>(); // depends on control dependency: [if], data = [none]
for (final Object v : (List<Object>) value) {
if (!(v instanceof String)) {
throw new JsonLdError(Error.INVALID_ID_VALUE,
"@id value must be a string, an array of strings or an empty dictionary");
}
((List<String>) expandedValue).add(activeCtx
.expandIri((String) v, true, true, null, null)); // depends on control dependency: [for], data = [v]
}
} else {
throw new JsonLdError(Error.INVALID_ID_VALUE,
"value of @id must be a string, an array of strings or an empty dictionary");
}
} else {
throw new JsonLdError(Error.INVALID_ID_VALUE,
"value of @id must be a string");
}
}
// 7.4.4)
else if (JsonLdConsts.TYPE.equals(expandedProperty)) {
if (value instanceof List) {
expandedValue = new ArrayList<String>(); // depends on control dependency: [if], data = [none]
for (final Object v : (List) value) {
if (!(v instanceof String)) {
throw new JsonLdError(Error.INVALID_TYPE_VALUE,
"@type value must be a string or array of strings");
}
((List<String>) expandedValue).add(
activeCtx.expandIri((String) v, true, true, null, null)); // depends on control dependency: [for], data = [none]
}
} else if (value instanceof String) {
expandedValue = activeCtx.expandIri((String) value, true, true, null,
null); // depends on control dependency: [if], data = [none]
}
// TODO: SPEC: no mention of empty map check
else if (frameExpansion && value instanceof Map) {
if (!((Map<String, Object>) value).isEmpty()) {
throw new JsonLdError(Error.INVALID_TYPE_VALUE,
"@type value must be a an empty object for framing");
}
expandedValue = value; // depends on control dependency: [if], data = [none]
} else {
throw new JsonLdError(Error.INVALID_TYPE_VALUE,
"@type value must be a string or array of strings");
}
}
// 7.4.5)
else if (JsonLdConsts.GRAPH.equals(expandedProperty)) {
expandedValue = expand(activeCtx, JsonLdConsts.GRAPH, value); // depends on control dependency: [if], data = [none]
}
// 7.4.6)
else if (JsonLdConsts.VALUE.equals(expandedProperty)) {
if (value != null && (value instanceof Map || value instanceof List)) {
throw new JsonLdError(Error.INVALID_VALUE_OBJECT_VALUE,
"value of " + expandedProperty + " must be a scalar or null");
}
expandedValue = value; // depends on control dependency: [if], data = [none]
if (expandedValue == null) {
result.put(JsonLdConsts.VALUE, null); // depends on control dependency: [if], data = [null)]
continue;
}
}
// 7.4.7)
else if (JsonLdConsts.LANGUAGE.equals(expandedProperty)) {
if (!(value instanceof String)) {
throw new JsonLdError(Error.INVALID_LANGUAGE_TAGGED_STRING,
"Value of " + expandedProperty + " must be a string");
}
expandedValue = ((String) value).toLowerCase(); // depends on control dependency: [if], data = [none]
}
// 7.4.8)
else if (JsonLdConsts.INDEX.equals(expandedProperty)) {
if (!(value instanceof String)) {
throw new JsonLdError(Error.INVALID_INDEX_VALUE,
"Value of " + expandedProperty + " must be a string");
}
expandedValue = value; // depends on control dependency: [if], data = [none]
}
// 7.4.9)
else if (JsonLdConsts.LIST.equals(expandedProperty)) {
// 7.4.9.1)
if (activeProperty == null || JsonLdConsts.GRAPH.equals(activeProperty)) {
continue;
}
// 7.4.9.2)
expandedValue = expand(activeCtx, activeProperty, value); // depends on control dependency: [if], data = [none]
// NOTE: step not in the spec yet
if (!(expandedValue instanceof List)) {
final List<Object> tmp = new ArrayList<Object>();
tmp.add(expandedValue); // depends on control dependency: [if], data = [none]
expandedValue = tmp; // depends on control dependency: [if], data = [none]
}
// 7.4.9.3)
for (final Object o : (List<Object>) expandedValue) {
if (o instanceof Map
&& ((Map<String, Object>) o).containsKey(JsonLdConsts.LIST)) {
throw new JsonLdError(Error.LIST_OF_LISTS,
"A list may not contain another list");
}
}
}
// 7.4.10)
else if (JsonLdConsts.SET.equals(expandedProperty)) {
expandedValue = expand(activeCtx, activeProperty, value); // depends on control dependency: [if], data = [none]
}
// 7.4.11)
else if (JsonLdConsts.REVERSE.equals(expandedProperty)) {
if (!(value instanceof Map)) {
throw new JsonLdError(Error.INVALID_REVERSE_VALUE,
"@reverse value must be an object");
}
// 7.4.11.1)
expandedValue = expand(activeCtx, JsonLdConsts.REVERSE, value); // depends on control dependency: [if], data = [none]
// NOTE: algorithm assumes the result is a map
// 7.4.11.2)
if (((Map<String, Object>) expandedValue)
.containsKey(JsonLdConsts.REVERSE)) {
final Map<String, Object> reverse = (Map<String, Object>) ((Map<String, Object>) expandedValue)
.get(JsonLdConsts.REVERSE);
for (final String property : reverse.keySet()) {
final Object item = reverse.get(property);
// 7.4.11.2.1)
if (!result.containsKey(property)) {
result.put(property, new ArrayList<Object>()); // depends on control dependency: [if], data = [none]
}
// 7.4.11.2.2)
if (item instanceof List) {
((List<Object>) result.get(property))
.addAll((List<Object>) item); // depends on control dependency: [if], data = [none]
} else {
((List<Object>) result.get(property)).add(item); // depends on control dependency: [if], data = [none]
}
}
}
// 7.4.11.3)
if (((Map<String, Object>) expandedValue)
.size() > (((Map<String, Object>) expandedValue)
.containsKey(JsonLdConsts.REVERSE) ? 1 : 0)) {
// 7.4.11.3.1)
if (!result.containsKey(JsonLdConsts.REVERSE)) {
result.put(JsonLdConsts.REVERSE, newMap()); // depends on control dependency: [if], data = [none]
}
// 7.4.11.3.2)
final Map<String, Object> reverseMap = (Map<String, Object>) result
.get(JsonLdConsts.REVERSE);
// 7.4.11.3.3)
for (final String property : ((Map<String, Object>) expandedValue)
.keySet()) {
if (JsonLdConsts.REVERSE.equals(property)) {
continue;
}
// 7.4.11.3.3.1)
final List<Object> items = (List<Object>) ((Map<String, Object>) expandedValue)
.get(property);
for (final Object item : items) {
// 7.4.11.3.3.1.1)
if (item instanceof Map && (((Map<String, Object>) item)
.containsKey(JsonLdConsts.VALUE)
|| ((Map<String, Object>) item)
.containsKey(JsonLdConsts.LIST))) {
throw new JsonLdError(Error.INVALID_REVERSE_PROPERTY_VALUE);
}
// 7.4.11.3.3.1.2)
if (!reverseMap.containsKey(property)) {
reverseMap.put(property, new ArrayList<Object>()); // depends on control dependency: [if], data = [none]
}
// 7.4.11.3.3.1.3)
((List<Object>) reverseMap.get(property)).add(item); // depends on control dependency: [for], data = [item]
}
}
}
// 7.4.11.4)
continue;
}
// TODO: SPEC no mention of @explicit etc in spec
else if (frameExpansion && (JsonLdConsts.EXPLICIT.equals(expandedProperty)
|| JsonLdConsts.DEFAULT.equals(expandedProperty)
|| JsonLdConsts.EMBED.equals(expandedProperty)
|| JsonLdConsts.REQUIRE_ALL.equals(expandedProperty)
|| JsonLdConsts.EMBED_CHILDREN.equals(expandedProperty)
|| JsonLdConsts.OMIT_DEFAULT.equals(expandedProperty))) {
expandedValue = expand(activeCtx, expandedProperty, value); // depends on control dependency: [if], data = [none]
}
// 7.4.12)
if (expandedValue != null) {
result.put(expandedProperty, expandedValue); // depends on control dependency: [if], data = [none]
}
// 7.4.13)
continue;
}
// 7.5
else if (JsonLdConsts.LANGUAGE.equals(activeCtx.getContainer(key))
&& value instanceof Map) {
// 7.5.1)
expandedValue = new ArrayList<Object>(); // depends on control dependency: [if], data = [none]
// 7.5.2)
for (final String language : ((Map<String, Object>) value).keySet()) {
Object languageValue = ((Map<String, Object>) value).get(language);
// 7.5.2.1)
if (!(languageValue instanceof List)) {
final Object tmp = languageValue;
languageValue = new ArrayList<Object>(); // depends on control dependency: [if], data = [none]
((List<Object>) languageValue).add(tmp); // depends on control dependency: [if], data = [none]
}
// 7.5.2.2)
for (final Object item : (List<Object>) languageValue) {
// 7.5.2.2.1)
if (!(item instanceof String)) {
throw new JsonLdError(Error.INVALID_LANGUAGE_MAP_VALUE,
"Expected " + item.toString() + " to be a string");
}
// 7.5.2.2.2)
final Map<String, Object> tmp = newMap();
tmp.put(JsonLdConsts.VALUE, item); // depends on control dependency: [for], data = [item]
tmp.put(JsonLdConsts.LANGUAGE, language.toLowerCase()); // depends on control dependency: [for], data = [none]
((List<Object>) expandedValue).add(tmp); // depends on control dependency: [for], data = [none]
}
}
}
// 7.6)
else if (JsonLdConsts.INDEX.equals(activeCtx.getContainer(key))
&& value instanceof Map) {
// 7.6.1)
expandedValue = new ArrayList<Object>(); // depends on control dependency: [if], data = [none]
// 7.6.2)
final List<String> indexKeys = new ArrayList<String>(
((Map<String, Object>) value).keySet());
Collections.sort(indexKeys); // depends on control dependency: [if], data = [none]
for (final String index : indexKeys) {
Object indexValue = ((Map<String, Object>) value).get(index);
// 7.6.2.1)
if (!(indexValue instanceof List)) {
final Object tmp = indexValue;
indexValue = new ArrayList<Object>(); // depends on control dependency: [if], data = [none]
((List<Object>) indexValue).add(tmp); // depends on control dependency: [if], data = [none]
}
// 7.6.2.2)
indexValue = expand(activeCtx, key, indexValue); // depends on control dependency: [for], data = [index]
// 7.6.2.3)
for (final Map<String, Object> item : (List<Map<String, Object>>) indexValue) {
// 7.6.2.3.1)
if (!item.containsKey(JsonLdConsts.INDEX)) {
item.put(JsonLdConsts.INDEX, index); // depends on control dependency: [if], data = [none]
}
// 7.6.2.3.2)
((List<Object>) expandedValue).add(item); // depends on control dependency: [for], data = [item]
}
}
}
// 7.7)
else {
expandedValue = expand(activeCtx, key, value); // depends on control dependency: [if], data = [none]
}
// 7.8)
if (expandedValue == null) {
continue;
}
// 7.9)
if (JsonLdConsts.LIST.equals(activeCtx.getContainer(key))) {
if (!(expandedValue instanceof Map) || !((Map<String, Object>) expandedValue)
.containsKey(JsonLdConsts.LIST)) {
Object tmp = expandedValue;
if (!(tmp instanceof List)) {
tmp = new ArrayList<Object>(); // depends on control dependency: [if], data = [none]
((List<Object>) tmp).add(expandedValue); // depends on control dependency: [if], data = [none]
}
expandedValue = newMap(); // depends on control dependency: [if], data = [none]
((Map<String, Object>) expandedValue).put(JsonLdConsts.LIST, tmp); // depends on control dependency: [if], data = [none]
}
}
// 7.10)
if (activeCtx.isReverseProperty(key)) {
// 7.10.1)
if (!result.containsKey(JsonLdConsts.REVERSE)) {
result.put(JsonLdConsts.REVERSE, newMap()); // depends on control dependency: [if], data = [none]
}
// 7.10.2)
final Map<String, Object> reverseMap = (Map<String, Object>) result
.get(JsonLdConsts.REVERSE);
// 7.10.3)
if (!(expandedValue instanceof List)) {
final Object tmp = expandedValue;
expandedValue = new ArrayList<Object>(); // depends on control dependency: [if], data = [none]
((List<Object>) expandedValue).add(tmp); // depends on control dependency: [if], data = [none]
}
// 7.10.4)
for (final Object item : (List<Object>) expandedValue) {
// 7.10.4.1)
if (item instanceof Map && (((Map<String, Object>) item)
.containsKey(JsonLdConsts.VALUE)
|| ((Map<String, Object>) item).containsKey(JsonLdConsts.LIST))) {
throw new JsonLdError(Error.INVALID_REVERSE_PROPERTY_VALUE);
}
// 7.10.4.2)
if (!reverseMap.containsKey(expandedProperty)) {
reverseMap.put(expandedProperty, new ArrayList<Object>()); // depends on control dependency: [if], data = [none]
}
// 7.10.4.3)
if (item instanceof List) {
((List<Object>) reverseMap.get(expandedProperty))
.addAll((List<Object>) item); // depends on control dependency: [if], data = [none]
} else {
((List<Object>) reverseMap.get(expandedProperty)).add(item); // depends on control dependency: [if], data = [none]
}
}
}
// 7.11)
else {
// 7.11.1)
if (!result.containsKey(expandedProperty)) {
result.put(expandedProperty, new ArrayList<Object>()); // depends on control dependency: [if], data = [none]
}
// 7.11.2)
if (expandedValue instanceof List) {
((List<Object>) result.get(expandedProperty))
.addAll((List<Object>) expandedValue); // depends on control dependency: [if], data = [none]
} else {
((List<Object>) result.get(expandedProperty)).add(expandedValue); // depends on control dependency: [if], data = [none]
}
}
}
// 8)
if (result.containsKey(JsonLdConsts.VALUE)) {
// 8.1)
// TODO: is this method faster than just using containsKey for
// each?
final Set<String> keySet = new HashSet<>(result.keySet());
keySet.remove(JsonLdConsts.VALUE); // depends on control dependency: [if], data = [none]
keySet.remove(JsonLdConsts.INDEX); // depends on control dependency: [if], data = [none]
final boolean langremoved = keySet.remove(JsonLdConsts.LANGUAGE);
final boolean typeremoved = keySet.remove(JsonLdConsts.TYPE);
if ((langremoved && typeremoved) || !keySet.isEmpty()) {
throw new JsonLdError(Error.INVALID_VALUE_OBJECT,
"value object has unknown keys");
}
// 8.2)
final Object rval = result.get(JsonLdConsts.VALUE);
if (rval == null) {
// nothing else is possible with result if we set it to
// null, so simply return it
return null; // depends on control dependency: [if], data = [none]
}
// 8.3)
if (!(rval instanceof String) && result.containsKey(JsonLdConsts.LANGUAGE)) {
throw new JsonLdError(Error.INVALID_LANGUAGE_TAGGED_VALUE,
"when @language is used, @value must be a string");
}
// 8.4)
else if (result.containsKey(JsonLdConsts.TYPE)) {
// TODO: is this enough for "is an IRI"
if (!(result.get(JsonLdConsts.TYPE) instanceof String)
|| ((String) result.get(JsonLdConsts.TYPE)).startsWith("_:")
|| !((String) result.get(JsonLdConsts.TYPE)).contains(":")) {
throw new JsonLdError(Error.INVALID_TYPED_VALUE,
"value of @type must be an IRI");
}
}
}
// 9)
else if (result.containsKey(JsonLdConsts.TYPE)) {
final Object rtype = result.get(JsonLdConsts.TYPE);
if (!(rtype instanceof List)) {
final List<Object> tmp = new ArrayList<Object>();
tmp.add(rtype); // depends on control dependency: [if], data = [none]
result.put(JsonLdConsts.TYPE, tmp); // depends on control dependency: [if], data = [none]
}
}
// 10)
else if (result.containsKey(JsonLdConsts.SET)
|| result.containsKey(JsonLdConsts.LIST)) {
// 10.1)
if (result.size() > (result.containsKey(JsonLdConsts.INDEX) ? 2 : 1)) {
throw new JsonLdError(Error.INVALID_SET_OR_LIST_OBJECT,
"@set or @list may only contain @index");
}
// 10.2)
if (result.containsKey(JsonLdConsts.SET)) {
// result becomes an array here, thus the remaining checks
// will never be true from here on
// so simply return the value rather than have to make
// result an object and cast it with every
// other use in the function.
return result.get(JsonLdConsts.SET); // depends on control dependency: [if], data = [none]
}
}
// 11)
if (result.containsKey(JsonLdConsts.LANGUAGE) && result.size() == 1) {
result = null; // depends on control dependency: [if], data = [none]
}
// 12)
if (activeProperty == null || JsonLdConsts.GRAPH.equals(activeProperty)) {
// 12.1)
if (result != null && (result.size() == 0 || result.containsKey(JsonLdConsts.VALUE)
|| result.containsKey(JsonLdConsts.LIST))) {
result = null; // depends on control dependency: [if], data = [none]
}
// 12.2)
else if (result != null && !frameExpansion && result.containsKey(JsonLdConsts.ID)
&& result.size() == 1) {
result = null; // depends on control dependency: [if], data = [none]
}
}
// 13)
return result;
}
// 2) If element is a scalar
else {
// 2.1)
if (activeProperty == null || JsonLdConsts.GRAPH.equals(activeProperty)) {
return null; // depends on control dependency: [if], data = [none]
}
return activeCtx.expandValue(activeProperty, element);
}
} } |
public class class_name {
private <T extends Index> List<T> listIndexType(String type, Class<T> modelType) {
List<T> indexesOfType = new ArrayList<T>();
Gson g = new Gson();
for (JsonElement index : indexes) {
if (index.isJsonObject()) {
JsonObject indexDefinition = index.getAsJsonObject();
JsonElement indexType = indexDefinition.get("type");
if (indexType != null && indexType.isJsonPrimitive()) {
JsonPrimitive indexTypePrimitive = indexType.getAsJsonPrimitive();
if (type == null || (indexTypePrimitive.isString() && indexTypePrimitive
.getAsString().equals(type))) {
indexesOfType.add(g.fromJson(indexDefinition, modelType));
}
}
}
}
return indexesOfType;
} } | public class class_name {
private <T extends Index> List<T> listIndexType(String type, Class<T> modelType) {
List<T> indexesOfType = new ArrayList<T>();
Gson g = new Gson();
for (JsonElement index : indexes) {
if (index.isJsonObject()) {
JsonObject indexDefinition = index.getAsJsonObject();
JsonElement indexType = indexDefinition.get("type");
if (indexType != null && indexType.isJsonPrimitive()) {
JsonPrimitive indexTypePrimitive = indexType.getAsJsonPrimitive();
if (type == null || (indexTypePrimitive.isString() && indexTypePrimitive
.getAsString().equals(type))) {
indexesOfType.add(g.fromJson(indexDefinition, modelType)); // depends on control dependency: [if], data = [none]
}
}
}
}
return indexesOfType;
} } |
public class class_name {
public OnPremisesTagSet withOnPremisesTagSetList(java.util.List<TagFilter>... onPremisesTagSetList) {
if (this.onPremisesTagSetList == null) {
setOnPremisesTagSetList(new com.amazonaws.internal.SdkInternalList<java.util.List<TagFilter>>(onPremisesTagSetList.length));
}
for (java.util.List<TagFilter> ele : onPremisesTagSetList) {
this.onPremisesTagSetList.add(ele);
}
return this;
} } | public class class_name {
public OnPremisesTagSet withOnPremisesTagSetList(java.util.List<TagFilter>... onPremisesTagSetList) {
if (this.onPremisesTagSetList == null) {
setOnPremisesTagSetList(new com.amazonaws.internal.SdkInternalList<java.util.List<TagFilter>>(onPremisesTagSetList.length)); // depends on control dependency: [if], data = [none]
}
for (java.util.List<TagFilter> ele : onPremisesTagSetList) {
this.onPremisesTagSetList.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
protected void formatCommaSeparatedList(Collection<? extends EObject> elements, IFormattableDocument document) {
for (final EObject element : elements) {
document.format(element);
final ISemanticRegionFinder immediatelyFollowing = this.textRegionExtensions.immediatelyFollowing(element);
final ISemanticRegion keyword = immediatelyFollowing.keyword(this.keywords.getCommaKeyword());
document.prepend(keyword, NO_SPACE);
document.append(keyword, ONE_SPACE);
}
} } | public class class_name {
protected void formatCommaSeparatedList(Collection<? extends EObject> elements, IFormattableDocument document) {
for (final EObject element : elements) {
document.format(element); // depends on control dependency: [for], data = [element]
final ISemanticRegionFinder immediatelyFollowing = this.textRegionExtensions.immediatelyFollowing(element);
final ISemanticRegion keyword = immediatelyFollowing.keyword(this.keywords.getCommaKeyword());
document.prepend(keyword, NO_SPACE); // depends on control dependency: [for], data = [none]
document.append(keyword, ONE_SPACE); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
public BoxRequestsFile.UploadNewVersion getUploadNewVersionRequest(File file, String destinationFileId) {
try {
BoxRequestsFile.UploadNewVersion request = getUploadNewVersionRequest(new FileInputStream(file), destinationFileId);
request.setUploadSize(file.length());
request.setModifiedDate(new Date(file.lastModified()));
return request;
} catch (FileNotFoundException e) {
throw new IllegalArgumentException(e);
}
} } | public class class_name {
public BoxRequestsFile.UploadNewVersion getUploadNewVersionRequest(File file, String destinationFileId) {
try {
BoxRequestsFile.UploadNewVersion request = getUploadNewVersionRequest(new FileInputStream(file), destinationFileId);
request.setUploadSize(file.length()); // depends on control dependency: [try], data = [none]
request.setModifiedDate(new Date(file.lastModified())); // depends on control dependency: [try], data = [none]
return request; // depends on control dependency: [try], data = [none]
} catch (FileNotFoundException e) {
throw new IllegalArgumentException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected void doExecuteCommand() {
if(!ValkyrieRepository.getInstance().getApplicationConfig().applicationSecurityManager().isSecuritySupported()) {
return ;
}
CompositeDialogPage tabbedPage = new TabbedDialogPage( "loginForm" );
final LoginForm loginForm = createLoginForm();
tabbedPage.addForm( loginForm );
if( getDefaultUserName() != null ) {
loginForm.setUserName( getDefaultUserName() );
}
dialog = new TitledPageApplicationDialog( tabbedPage ) {
protected boolean onFinish() {
loginForm.commit();
Authentication authentication = loginForm.getAuthentication();
// Hand this token to the security manager to actually attempt the login
ApplicationSecurityManager sm = getApplicationConfig().applicationSecurityManager();
try {
sm.doLogin( authentication );
postLogin();
return true;
} finally {
if( isClearPasswordOnFailure() ) {
loginForm.setPassword("");
}
loginForm.requestFocusInWindow();
}
}
protected void onCancel() {
super.onCancel(); // Close the dialog
// Now exit if configured
if( isCloseOnCancel() ) {
ApplicationSecurityManager sm = getApplicationConfig().applicationSecurityManager();
Authentication authentication = sm.getAuthentication();
if( authentication == null ) {
LoginCommand.this.logger.info( "User canceled login; close the application." );
getApplicationConfig().application().close();
}
}
}
protected ActionCommand getCallingCommand() {
return LoginCommand.this;
}
protected void onAboutToShow() {
loginForm.requestFocusInWindow();
}
};
dialog.setDisplayFinishSuccessMessage( displaySuccessMessage );
dialog.showDialog();
} } | public class class_name {
protected void doExecuteCommand() {
if(!ValkyrieRepository.getInstance().getApplicationConfig().applicationSecurityManager().isSecuritySupported()) {
return ; // depends on control dependency: [if], data = [none]
}
CompositeDialogPage tabbedPage = new TabbedDialogPage( "loginForm" );
final LoginForm loginForm = createLoginForm();
tabbedPage.addForm( loginForm );
if( getDefaultUserName() != null ) {
loginForm.setUserName( getDefaultUserName() ); // depends on control dependency: [if], data = [( getDefaultUserName()]
}
dialog = new TitledPageApplicationDialog( tabbedPage ) {
protected boolean onFinish() {
loginForm.commit();
Authentication authentication = loginForm.getAuthentication();
// Hand this token to the security manager to actually attempt the login
ApplicationSecurityManager sm = getApplicationConfig().applicationSecurityManager();
try {
sm.doLogin( authentication ); // depends on control dependency: [try], data = [none]
postLogin(); // depends on control dependency: [try], data = [none]
return true; // depends on control dependency: [try], data = [none]
} finally {
if( isClearPasswordOnFailure() ) {
loginForm.setPassword(""); // depends on control dependency: [if], data = [none]
}
loginForm.requestFocusInWindow();
}
}
protected void onCancel() {
super.onCancel(); // Close the dialog
// Now exit if configured
if( isCloseOnCancel() ) {
ApplicationSecurityManager sm = getApplicationConfig().applicationSecurityManager();
Authentication authentication = sm.getAuthentication();
if( authentication == null ) {
LoginCommand.this.logger.info( "User canceled login; close the application." ); // depends on control dependency: [if], data = [none]
getApplicationConfig().application().close(); // depends on control dependency: [if], data = [none]
}
}
}
protected ActionCommand getCallingCommand() {
return LoginCommand.this;
}
protected void onAboutToShow() {
loginForm.requestFocusInWindow();
}
};
dialog.setDisplayFinishSuccessMessage( displaySuccessMessage );
dialog.showDialog();
} } |
public class class_name {
@Override
public void sortByLabel() {
Map<Integer, Queue<DataSet>> map = new HashMap<>();
List<DataSet> data = asList();
int numLabels = numOutcomes();
int examples = numExamples();
for (DataSet d : data) {
int label = d.outcome();
Queue<DataSet> q = map.get(label);
if (q == null) {
q = new ArrayDeque<>();
map.put(label, q);
}
q.add(d);
}
for (Map.Entry<Integer, Queue<DataSet>> label : map.entrySet()) {
log.info("Label " + label + " has " + label.getValue().size() + " elements");
}
//ideal input splits: 1 of each label in each batch
//after we run out of ideal batches: fall back to a new strategy
boolean optimal = true;
for (int i = 0; i < examples; i++) {
if (optimal) {
for (int j = 0; j < numLabels; j++) {
Queue<DataSet> q = map.get(j);
if (q == null) {
optimal = false;
break;
}
DataSet next = q.poll();
//add a row; go to next
if (next != null) {
addRow(next, i);
i++;
} else {
optimal = false;
break;
}
}
} else {
DataSet add = null;
for (Queue<DataSet> q : map.values()) {
if (!q.isEmpty()) {
add = q.poll();
break;
}
}
addRow(add, i);
}
}
} } | public class class_name {
@Override
public void sortByLabel() {
Map<Integer, Queue<DataSet>> map = new HashMap<>();
List<DataSet> data = asList();
int numLabels = numOutcomes();
int examples = numExamples();
for (DataSet d : data) {
int label = d.outcome();
Queue<DataSet> q = map.get(label);
if (q == null) {
q = new ArrayDeque<>(); // depends on control dependency: [if], data = [none]
map.put(label, q); // depends on control dependency: [if], data = [none]
}
q.add(d); // depends on control dependency: [for], data = [d]
}
for (Map.Entry<Integer, Queue<DataSet>> label : map.entrySet()) {
log.info("Label " + label + " has " + label.getValue().size() + " elements"); // depends on control dependency: [for], data = [label]
}
//ideal input splits: 1 of each label in each batch
//after we run out of ideal batches: fall back to a new strategy
boolean optimal = true;
for (int i = 0; i < examples; i++) {
if (optimal) {
for (int j = 0; j < numLabels; j++) {
Queue<DataSet> q = map.get(j);
if (q == null) {
optimal = false; // depends on control dependency: [if], data = [none]
break;
}
DataSet next = q.poll();
//add a row; go to next
if (next != null) {
addRow(next, i); // depends on control dependency: [if], data = [(next]
i++; // depends on control dependency: [if], data = [none]
} else {
optimal = false; // depends on control dependency: [if], data = [none]
break;
}
}
} else {
DataSet add = null;
for (Queue<DataSet> q : map.values()) {
if (!q.isEmpty()) {
add = q.poll(); // depends on control dependency: [if], data = [none]
break;
}
}
addRow(add, i); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
protected final void awaitShutdown() throws InterruptedException {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
shutdown();
finishLatch.await();
Thread.sleep(10); // wait a bit for things outside `launch` call, such as JUnit finishing or whatever
} catch (InterruptedException e) {
logger.error("Shutdown took too long", e);
}
}, "shutdownNotification"));
shutdownLatch.await();
} } | public class class_name {
protected final void awaitShutdown() throws InterruptedException {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
shutdown(); // depends on control dependency: [try], data = [none]
finishLatch.await(); // depends on control dependency: [try], data = [none]
Thread.sleep(10); // wait a bit for things outside `launch` call, such as JUnit finishing or whatever // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
logger.error("Shutdown took too long", e);
} // depends on control dependency: [catch], data = [none]
}, "shutdownNotification"));
shutdownLatch.await();
} } |
public class class_name {
protected ScriptContext getScriptContext(Bindings nn) {
SimpleScriptContext ctxt = new SimpleScriptContext();
Bindings gs = getBindings(ScriptContext.GLOBAL_SCOPE);
if (gs != null) {
ctxt.setBindings(gs, ScriptContext.GLOBAL_SCOPE);
}
if (nn != null) {
ctxt.setBindings(nn, ScriptContext.ENGINE_SCOPE);
}
else {
throw new NullPointerException("Engine scope Bindings may not be null.");
}
ctxt.setReader(context.getReader());
ctxt.setWriter(context.getWriter());
ctxt.setErrorWriter(context.getErrorWriter());
return ctxt;
} } | public class class_name {
protected ScriptContext getScriptContext(Bindings nn) {
SimpleScriptContext ctxt = new SimpleScriptContext();
Bindings gs = getBindings(ScriptContext.GLOBAL_SCOPE);
if (gs != null) {
ctxt.setBindings(gs, ScriptContext.GLOBAL_SCOPE); // depends on control dependency: [if], data = [(gs]
}
if (nn != null) {
ctxt.setBindings(nn, ScriptContext.ENGINE_SCOPE); // depends on control dependency: [if], data = [(nn]
}
else {
throw new NullPointerException("Engine scope Bindings may not be null.");
}
ctxt.setReader(context.getReader());
ctxt.setWriter(context.getWriter());
ctxt.setErrorWriter(context.getErrorWriter());
return ctxt;
} } |
public class class_name {
public void filterTable(String search) {
m_container.removeAllContainerFilters();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(search)) {
if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_dialog.getFurtherColumnId())) {
m_container.addContainerFilter(new Or(new SimpleStringFilter(PROP_NAME, search, true, false)));
} else {
m_container.addContainerFilter(
new Or(
new SimpleStringFilter(PROP_NAME, search, true, false),
new SimpleStringFilter(m_dialog.getFurtherColumnId(), search, true, false)));
}
}
if ((getValue() != null) & !((Set<String>)getValue()).isEmpty()) {
setCurrentPageFirstItemId(((Set<String>)getValue()).iterator().next());
}
} } | public class class_name {
public void filterTable(String search) {
m_container.removeAllContainerFilters();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(search)) {
if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_dialog.getFurtherColumnId())) {
m_container.addContainerFilter(new Or(new SimpleStringFilter(PROP_NAME, search, true, false))); // depends on control dependency: [if], data = [none]
} else {
m_container.addContainerFilter(
new Or(
new SimpleStringFilter(PROP_NAME, search, true, false),
new SimpleStringFilter(m_dialog.getFurtherColumnId(), search, true, false))); // depends on control dependency: [if], data = [none]
}
}
if ((getValue() != null) & !((Set<String>)getValue()).isEmpty()) {
setCurrentPageFirstItemId(((Set<String>)getValue()).iterator().next()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected Expanded doExpand(Record record, long fullConsistencyTimestamp, long compactionConsistencyTimeStamp, long compactionControlTimestamp, MutableIntrinsics intrinsics, boolean ignoreRecent)
throws RestartException {
List<DeltaClusteringKey> keysToDelete = Lists.newArrayList();
DeltasArchive deltasArchive = new DeltasArchive();
// Loop through the compaction records and find the one that is most up-to-date. Obsolete ones may be deleted.
Map.Entry<DeltaClusteringKey, Compaction> compactionEntry = findEffectiveCompaction(record.passOneIterator(), keysToDelete, compactionConsistencyTimeStamp);
// Check to see if this is a legacy compaction
if (compactionEntry != null && !compactionEntry.getValue().hasCompactedDelta()) {
// Legacy compaction found. Can't use this compactor.
return _legacyCompactor.doExpand(record, fullConsistencyTimestamp, intrinsics, ignoreRecent, compactionEntry);
}
// Save the number of collected compaction Ids to delete in the pending compaction
List<DeltaClusteringKey> compactionKeysToDelete = Lists.newArrayList(keysToDelete.iterator());
PeekingIterator<Map.Entry<DeltaClusteringKey, DeltaTagPair>> deltaIterator = Iterators.peekingIterator(
deltaIterator(record.passTwoIterator(), compactionEntry));
UUID compactionKey = null;
Compaction compaction = null;
UUID cutoffId = null;
UUID initialCutoff = null;
Delta cutoffDelta = null;
Delta initialCutoffDelta = null;
boolean compactionChanged = false;
// Stats for slow query logging ignore compaction performed as result of this method
int numPersistentDeltas = 0;
long numDeletedDeltas = 0;
// Check if we should delete deltas for the selected compaction
boolean deleteDeltasForCompaction;
// Check if we should be creating a compaction.
// If a compaction is found outside of the FCT, then we should hold off making new compactions.
boolean createNewCompaction = true;
// Initialize the resolver based on the current effective compaction state.
Resolver resolver;
if (compactionEntry == null) {
resolver = new DefaultResolver(intrinsics);
} else {
deleteDeltasForCompaction = TimeUUIDs.getTimeMillis(compactionEntry.getKey().getChangeId()) < compactionConsistencyTimeStamp;
createNewCompaction = deleteDeltasForCompaction;
compactionKey = compactionEntry.getKey().getChangeId();
compaction = compactionEntry.getValue();
numDeletedDeltas = compaction.getCount();
resolver = new DefaultResolver(intrinsics, compaction);
// Concurrent compaction operations can race and leave deltas older than the chosen cutoff. Delete those deltas.
// Also, safe-delete: We need to make sure that compaction is fully consistent before we delete any deltas
cutoffId = compaction.getCutoff();
initialCutoff = compaction.getCutoff();
while (deltaIterator.hasNext() && TimeUUIDs.compare(deltaIterator.peek().getKey().getChangeId(), cutoffId) <= 0) {
if (!deleteDeltasForCompaction) {
deltaIterator.next();
continue;
}
Map.Entry<DeltaClusteringKey, DeltaTagPair> deltaEntry = deltaIterator.next();
keysToDelete.add(deltaEntry.getKey());
numPersistentDeltas++;
}
// Assert that the resolved compacted content is always a literal
assert (compaction.getCompactedDelta().isConstant()) : "Compacted delta was not a literal";
cutoffDelta = compaction.getCompactedDelta();
initialCutoffDelta = compaction.getCompactedDelta();
}
List<DeltaClusteringKey> compactibleChangeIds = Lists.newArrayList();
while (createNewCompaction && deltaIterator.hasNext() && TimeUUIDs.getTimeMillis(deltaIterator.peek().getKey().getChangeId()) < fullConsistencyTimestamp) {
Map.Entry<DeltaClusteringKey, DeltaTagPair> entry = deltaIterator.next();
resolver.update(entry.getKey().getChangeId(), entry.getValue().delta, entry.getValue().tags);
compactibleChangeIds.add(entry.getKey());
// We would like to keep these deltas in pending compaction object in memory so we don't have to
// go to C* to get them.
deltasArchive.addDeltaArchive(entry.getKey().getChangeId(), entry.getValue().delta);
numPersistentDeltas++;
}
if (!compactibleChangeIds.isEmpty()) {
// Merge the N oldest deltas and write the result into the new compaction.
Resolved resolved = resolver.resolved();
// Note: We should *not* delete the compaction that the new compaction is based upon, and defer
// its delete once the new compaction is also behind FCT.
// Write a new compaction record and re-write the preceding delta with the content resolved to this point.
compactionKey = TimeUUIDs.newUUID();
compaction = new Compaction(
resolved.getIntrinsics().getVersion(),
resolved.getIntrinsics().getFirstUpdateAtUuid(),
resolved.getIntrinsics().getLastUpdateAtUuid(),
resolved.getIntrinsics().getSignature(),
resolved.getIntrinsics().getLastMutateAtUuid(),
resolved.getLastMutation(),
// Compacted Delta
resolved.getConstant(), resolved.getLastTags());
cutoffId = compaction.getCutoff();
cutoffDelta = resolved.getConstant();
compactionChanged = true;
// Re-initialize the resolver with the new compaction state.
resolver = new DefaultResolver(intrinsics, compaction);
}
// consider compactionControlTimestamp here (one case could be that there is a stash run in progress) and not include those Ids.
// With this, we are halting the deletion of these deltas in this run.
// We could have not included these Ids at the first place in the top section, but just to be cleaner and for better separation, excluding these Ids here.
keysToDelete = keysToDelete.stream().filter(keyToDelete -> (TimeUUIDs.getTimeMillis(keyToDelete.getChangeId()) > compactionControlTimestamp)).collect(Collectors.toList());
compactionKeysToDelete = compactionKeysToDelete.stream().filter(compactionKeyToDelete -> (TimeUUIDs.getTimeMillis(compactionKeyToDelete.getChangeId()) > compactionControlTimestamp)).collect(Collectors.toList());
// Persist the compaction, and keys-to-delete. We must write compaction and delete synchronously to
// be sure that eventually consistent readers don't see the result of the deletions w/o also
// seeing the accompanying compaction.
PendingCompaction pendingCompaction = (compactionChanged || !keysToDelete.isEmpty()) ?
new PendingCompaction(compactionKey, compaction, cutoffId, initialCutoff, cutoffDelta, initialCutoffDelta, keysToDelete,
compactionKeysToDelete, deltasArchive.deltasToArchive)
: null;
try {
updateSizeCounter(pendingCompaction);
} catch (DeltaHistorySizeExceededException ex) {
// Too big to write via thrift - clear the delta archives
assert pendingCompaction != null : "Unexpected NPE for pendingCompaction";
pendingCompaction.getDeltasToArchive().clear();
}
// Resolve recent deltas.
while (deltaIterator.hasNext()) {
Map.Entry<DeltaClusteringKey, DeltaTagPair> entry = deltaIterator.next();
if (ignoreRecent && TimeUUIDs.getTimeMillis(entry.getKey().getChangeId()) >= fullConsistencyTimestamp) {
break;
}
resolver.update(entry.getKey().getChangeId(), entry.getValue().delta, entry.getValue().tags);
numPersistentDeltas++;
}
return new Expanded(resolver.resolved(), pendingCompaction, numPersistentDeltas, numDeletedDeltas);
} } | public class class_name {
protected Expanded doExpand(Record record, long fullConsistencyTimestamp, long compactionConsistencyTimeStamp, long compactionControlTimestamp, MutableIntrinsics intrinsics, boolean ignoreRecent)
throws RestartException {
List<DeltaClusteringKey> keysToDelete = Lists.newArrayList();
DeltasArchive deltasArchive = new DeltasArchive();
// Loop through the compaction records and find the one that is most up-to-date. Obsolete ones may be deleted.
Map.Entry<DeltaClusteringKey, Compaction> compactionEntry = findEffectiveCompaction(record.passOneIterator(), keysToDelete, compactionConsistencyTimeStamp);
// Check to see if this is a legacy compaction
if (compactionEntry != null && !compactionEntry.getValue().hasCompactedDelta()) {
// Legacy compaction found. Can't use this compactor.
return _legacyCompactor.doExpand(record, fullConsistencyTimestamp, intrinsics, ignoreRecent, compactionEntry);
}
// Save the number of collected compaction Ids to delete in the pending compaction
List<DeltaClusteringKey> compactionKeysToDelete = Lists.newArrayList(keysToDelete.iterator());
PeekingIterator<Map.Entry<DeltaClusteringKey, DeltaTagPair>> deltaIterator = Iterators.peekingIterator(
deltaIterator(record.passTwoIterator(), compactionEntry));
UUID compactionKey = null;
Compaction compaction = null;
UUID cutoffId = null;
UUID initialCutoff = null;
Delta cutoffDelta = null;
Delta initialCutoffDelta = null;
boolean compactionChanged = false;
// Stats for slow query logging ignore compaction performed as result of this method
int numPersistentDeltas = 0;
long numDeletedDeltas = 0;
// Check if we should delete deltas for the selected compaction
boolean deleteDeltasForCompaction;
// Check if we should be creating a compaction.
// If a compaction is found outside of the FCT, then we should hold off making new compactions.
boolean createNewCompaction = true;
// Initialize the resolver based on the current effective compaction state.
Resolver resolver;
if (compactionEntry == null) {
resolver = new DefaultResolver(intrinsics);
} else {
deleteDeltasForCompaction = TimeUUIDs.getTimeMillis(compactionEntry.getKey().getChangeId()) < compactionConsistencyTimeStamp;
createNewCompaction = deleteDeltasForCompaction;
compactionKey = compactionEntry.getKey().getChangeId();
compaction = compactionEntry.getValue();
numDeletedDeltas = compaction.getCount();
resolver = new DefaultResolver(intrinsics, compaction);
// Concurrent compaction operations can race and leave deltas older than the chosen cutoff. Delete those deltas.
// Also, safe-delete: We need to make sure that compaction is fully consistent before we delete any deltas
cutoffId = compaction.getCutoff();
initialCutoff = compaction.getCutoff();
while (deltaIterator.hasNext() && TimeUUIDs.compare(deltaIterator.peek().getKey().getChangeId(), cutoffId) <= 0) {
if (!deleteDeltasForCompaction) {
deltaIterator.next(); // depends on control dependency: [if], data = [none]
continue;
}
Map.Entry<DeltaClusteringKey, DeltaTagPair> deltaEntry = deltaIterator.next();
keysToDelete.add(deltaEntry.getKey()); // depends on control dependency: [while], data = [none]
numPersistentDeltas++; // depends on control dependency: [while], data = [none]
}
// Assert that the resolved compacted content is always a literal
assert (compaction.getCompactedDelta().isConstant()) : "Compacted delta was not a literal";
cutoffDelta = compaction.getCompactedDelta();
initialCutoffDelta = compaction.getCompactedDelta();
}
List<DeltaClusteringKey> compactibleChangeIds = Lists.newArrayList();
while (createNewCompaction && deltaIterator.hasNext() && TimeUUIDs.getTimeMillis(deltaIterator.peek().getKey().getChangeId()) < fullConsistencyTimestamp) {
Map.Entry<DeltaClusteringKey, DeltaTagPair> entry = deltaIterator.next();
resolver.update(entry.getKey().getChangeId(), entry.getValue().delta, entry.getValue().tags);
compactibleChangeIds.add(entry.getKey());
// We would like to keep these deltas in pending compaction object in memory so we don't have to
// go to C* to get them.
deltasArchive.addDeltaArchive(entry.getKey().getChangeId(), entry.getValue().delta);
numPersistentDeltas++;
}
if (!compactibleChangeIds.isEmpty()) {
// Merge the N oldest deltas and write the result into the new compaction.
Resolved resolved = resolver.resolved();
// Note: We should *not* delete the compaction that the new compaction is based upon, and defer
// its delete once the new compaction is also behind FCT.
// Write a new compaction record and re-write the preceding delta with the content resolved to this point.
compactionKey = TimeUUIDs.newUUID();
compaction = new Compaction(
resolved.getIntrinsics().getVersion(),
resolved.getIntrinsics().getFirstUpdateAtUuid(),
resolved.getIntrinsics().getLastUpdateAtUuid(),
resolved.getIntrinsics().getSignature(),
resolved.getIntrinsics().getLastMutateAtUuid(),
resolved.getLastMutation(),
// Compacted Delta
resolved.getConstant(), resolved.getLastTags());
cutoffId = compaction.getCutoff();
cutoffDelta = resolved.getConstant();
compactionChanged = true;
// Re-initialize the resolver with the new compaction state.
resolver = new DefaultResolver(intrinsics, compaction);
}
// consider compactionControlTimestamp here (one case could be that there is a stash run in progress) and not include those Ids.
// With this, we are halting the deletion of these deltas in this run.
// We could have not included these Ids at the first place in the top section, but just to be cleaner and for better separation, excluding these Ids here.
keysToDelete = keysToDelete.stream().filter(keyToDelete -> (TimeUUIDs.getTimeMillis(keyToDelete.getChangeId()) > compactionControlTimestamp)).collect(Collectors.toList());
compactionKeysToDelete = compactionKeysToDelete.stream().filter(compactionKeyToDelete -> (TimeUUIDs.getTimeMillis(compactionKeyToDelete.getChangeId()) > compactionControlTimestamp)).collect(Collectors.toList());
// Persist the compaction, and keys-to-delete. We must write compaction and delete synchronously to
// be sure that eventually consistent readers don't see the result of the deletions w/o also
// seeing the accompanying compaction.
PendingCompaction pendingCompaction = (compactionChanged || !keysToDelete.isEmpty()) ?
new PendingCompaction(compactionKey, compaction, cutoffId, initialCutoff, cutoffDelta, initialCutoffDelta, keysToDelete,
compactionKeysToDelete, deltasArchive.deltasToArchive)
: null;
try {
updateSizeCounter(pendingCompaction);
} catch (DeltaHistorySizeExceededException ex) {
// Too big to write via thrift - clear the delta archives
assert pendingCompaction != null : "Unexpected NPE for pendingCompaction";
pendingCompaction.getDeltasToArchive().clear();
}
// Resolve recent deltas.
while (deltaIterator.hasNext()) {
Map.Entry<DeltaClusteringKey, DeltaTagPair> entry = deltaIterator.next();
if (ignoreRecent && TimeUUIDs.getTimeMillis(entry.getKey().getChangeId()) >= fullConsistencyTimestamp) {
break;
}
resolver.update(entry.getKey().getChangeId(), entry.getValue().delta, entry.getValue().tags);
numPersistentDeltas++;
}
return new Expanded(resolver.resolved(), pendingCompaction, numPersistentDeltas, numDeletedDeltas);
} } |
public class class_name {
public static int getResources_getInteger(Context context, int id) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
return context.getResources().getInteger(id);
}
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
float widthDp = metrics.widthPixels / metrics.density;
if (id == R.integer.abs__max_action_buttons) {
if (widthDp >= 600) {
return 5; //values-w600dp
}
if (widthDp >= 500) {
return 4; //values-w500dp
}
if (widthDp >= 360) {
return 3; //values-w360dp
}
return 2; //values
}
throw new IllegalArgumentException("Unknown integer resource ID " + id);
} } | public class class_name {
public static int getResources_getInteger(Context context, int id) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
return context.getResources().getInteger(id); // depends on control dependency: [if], data = [none]
}
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
float widthDp = metrics.widthPixels / metrics.density;
if (id == R.integer.abs__max_action_buttons) {
if (widthDp >= 600) {
return 5; //values-w600dp // depends on control dependency: [if], data = [none]
}
if (widthDp >= 500) {
return 4; //values-w500dp // depends on control dependency: [if], data = [none]
}
if (widthDp >= 360) {
return 3; //values-w360dp // depends on control dependency: [if], data = [none]
}
return 2; //values // depends on control dependency: [if], data = [none]
}
throw new IllegalArgumentException("Unknown integer resource ID " + id);
} } |
public class class_name {
public void setScheduledInstanceAvailabilitySet(java.util.Collection<ScheduledInstanceAvailability> scheduledInstanceAvailabilitySet) {
if (scheduledInstanceAvailabilitySet == null) {
this.scheduledInstanceAvailabilitySet = null;
return;
}
this.scheduledInstanceAvailabilitySet = new com.amazonaws.internal.SdkInternalList<ScheduledInstanceAvailability>(scheduledInstanceAvailabilitySet);
} } | public class class_name {
public void setScheduledInstanceAvailabilitySet(java.util.Collection<ScheduledInstanceAvailability> scheduledInstanceAvailabilitySet) {
if (scheduledInstanceAvailabilitySet == null) {
this.scheduledInstanceAvailabilitySet = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.scheduledInstanceAvailabilitySet = new com.amazonaws.internal.SdkInternalList<ScheduledInstanceAvailability>(scheduledInstanceAvailabilitySet);
} } |
public class class_name {
public void addRequest(RecordRequest request) {
if (request.getRequestSize() + getRequestSize() > 248) {
throw new IllegalArgumentException();
}
if (records == null) {
records = new RecordRequest[1];
}
else {
RecordRequest old[] = records;
records = new RecordRequest[old.length + 1];
System.arraycopy(old, 0, records, 0, old.length);
}
records[records.length - 1] = request;
setDataLength(getRequestSize());
} } | public class class_name {
public void addRequest(RecordRequest request) {
if (request.getRequestSize() + getRequestSize() > 248) {
throw new IllegalArgumentException();
}
if (records == null) {
records = new RecordRequest[1]; // depends on control dependency: [if], data = [none]
}
else {
RecordRequest old[] = records;
records = new RecordRequest[old.length + 1]; // depends on control dependency: [if], data = [none]
System.arraycopy(old, 0, records, 0, old.length); // depends on control dependency: [if], data = [none]
}
records[records.length - 1] = request;
setDataLength(getRequestSize());
} } |
public class class_name {
private void addDiscriminatorNode(DiscriminatorNode dn) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "addDiscriminatorNode, weight=" + dn.weight);
}
if (discriminators == null) {
// add it as the first node
discriminators = dn;
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "addDiscriminatorNode");
}
return;
}
DiscriminatorNode thisDN = discriminators;
if (thisDN.weight > dn.weight) {
// add it as the first node
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Adding disc first in list");
}
thisDN.prev = dn;
dn.next = thisDN;
discriminators = dn;
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "addDiscriminatorNode");
}
return;
}
DiscriminatorNode lastDN = discriminators;
while (thisDN.next != null) {
// somewhere in the middle
lastDN = thisDN;
thisDN = thisDN.next;
if (thisDN.weight > dn.weight) {
// put it in the middle
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Adding disc before " + thisDN.disc.getChannel().getName());
}
thisDN.prev = dn;
dn.next = thisDN;
lastDN.next = dn;
dn.prev = lastDN;
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "addDiscriminatorNode");
}
return;
}
}
// guess its at the end
thisDN.next = dn;
dn.prev = thisDN;
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "addDiscriminatorNode");
}
} } | public class class_name {
private void addDiscriminatorNode(DiscriminatorNode dn) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "addDiscriminatorNode, weight=" + dn.weight); // depends on control dependency: [if], data = [none]
}
if (discriminators == null) {
// add it as the first node
discriminators = dn; // depends on control dependency: [if], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "addDiscriminatorNode"); // depends on control dependency: [if], data = [none]
}
return; // depends on control dependency: [if], data = [none]
}
DiscriminatorNode thisDN = discriminators;
if (thisDN.weight > dn.weight) {
// add it as the first node
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Adding disc first in list"); // depends on control dependency: [if], data = [none]
}
thisDN.prev = dn; // depends on control dependency: [if], data = [none]
dn.next = thisDN; // depends on control dependency: [if], data = [none]
discriminators = dn; // depends on control dependency: [if], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "addDiscriminatorNode"); // depends on control dependency: [if], data = [none]
}
return; // depends on control dependency: [if], data = [none]
}
DiscriminatorNode lastDN = discriminators;
while (thisDN.next != null) {
// somewhere in the middle
lastDN = thisDN; // depends on control dependency: [while], data = [none]
thisDN = thisDN.next; // depends on control dependency: [while], data = [none]
if (thisDN.weight > dn.weight) {
// put it in the middle
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Adding disc before " + thisDN.disc.getChannel().getName()); // depends on control dependency: [if], data = [none]
}
thisDN.prev = dn; // depends on control dependency: [if], data = [none]
dn.next = thisDN; // depends on control dependency: [if], data = [none]
lastDN.next = dn; // depends on control dependency: [if], data = [none]
dn.prev = lastDN; // depends on control dependency: [if], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "addDiscriminatorNode"); // depends on control dependency: [if], data = [none]
}
return; // depends on control dependency: [if], data = [none]
}
}
// guess its at the end
thisDN.next = dn;
dn.prev = thisDN;
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "addDiscriminatorNode"); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static Duration ofMillis(long millis) {
long secs = millis / 1000;
int mos = (int) (millis % 1000);
if (mos < 0) {
mos += 1000;
secs--;
}
return create(secs, mos * NANOS_PER_MILLI);
} } | public class class_name {
public static Duration ofMillis(long millis) {
long secs = millis / 1000;
int mos = (int) (millis % 1000);
if (mos < 0) {
mos += 1000; // depends on control dependency: [if], data = [none]
secs--; // depends on control dependency: [if], data = [none]
}
return create(secs, mos * NANOS_PER_MILLI);
} } |
public class class_name {
public boolean isEditorAvailableForResource(CmsResource res) {
I_CmsResourceType type = OpenCms.getResourceManager().getResourceType(res);
String typeName = type.getTypeName();
for (CmsWorkplaceEditorConfiguration editorConfig : m_editorConfigurations) {
if (editorConfig.matchesResourceType(typeName)) {
return true;
}
}
return false;
} } | public class class_name {
public boolean isEditorAvailableForResource(CmsResource res) {
I_CmsResourceType type = OpenCms.getResourceManager().getResourceType(res);
String typeName = type.getTypeName();
for (CmsWorkplaceEditorConfiguration editorConfig : m_editorConfigurations) {
if (editorConfig.matchesResourceType(typeName)) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
public void setParamTabExFileEntries(String value) {
try {
m_userSettings.setExplorerFileEntries(Integer.parseInt(value));
} catch (Throwable t) {
// should usually never happen
}
} } | public class class_name {
public void setParamTabExFileEntries(String value) {
try {
m_userSettings.setExplorerFileEntries(Integer.parseInt(value)); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
// should usually never happen
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected final void runOnUiThread(@NonNull Runnable runnable) {
checkNotNull(runnable, "runnable");
if (Looper.myLooper() == Looper.getMainLooper()) {
runnable.run();
} else {
mPoster.post(runnable);
}
} } | public class class_name {
protected final void runOnUiThread(@NonNull Runnable runnable) {
checkNotNull(runnable, "runnable");
if (Looper.myLooper() == Looper.getMainLooper()) {
runnable.run(); // depends on control dependency: [if], data = [none]
} else {
mPoster.post(runnable); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public CreateFleetResult withInstances(CreateFleetInstance... instances) {
if (this.instances == null) {
setInstances(new com.amazonaws.internal.SdkInternalList<CreateFleetInstance>(instances.length));
}
for (CreateFleetInstance ele : instances) {
this.instances.add(ele);
}
return this;
} } | public class class_name {
public CreateFleetResult withInstances(CreateFleetInstance... instances) {
if (this.instances == null) {
setInstances(new com.amazonaws.internal.SdkInternalList<CreateFleetInstance>(instances.length)); // depends on control dependency: [if], data = [none]
}
for (CreateFleetInstance ele : instances) {
this.instances.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public void addChildProperties(final NodeData parentData, final List<PropertyData> childItems)
{
if (enabled && parentData != null && childItems != null)
{
String logInfo = null;
if (LOG.isDebugEnabled())
{
logInfo =
"parent: " + parentData.getQPath().getAsString() + " " + parentData.getIdentifier() + " "
+ childItems.size();
LOG.debug(name + ", addChildProperties() >>> " + logInfo);
}
String operName = ""; // for debug/trace only
writeLock.lock();
try
{
// remove parent (no childs)
operName = "removing parent";
removeItem(parentData);
operName = "caching parent";
putItem(parentData); // put parent in cache
synchronized (childItems)
{
operName = "caching child properties list";
propertiesCache.put(parentData.getIdentifier(), childItems); // put childs in cache CP
operName = "caching child properties";
// put childs in cache C
for (ItemData p : childItems)
{
if (LOG.isDebugEnabled())
{
LOG.debug(name + ", addChildProperties() " + p.getQPath().getAsString() + " "
+ p.getIdentifier() + " -- " + p);
}
putItem(p);
}
}
}
catch (Exception e)
{
LOG.error(name + ", Error in addChildProperties() " + operName + ": parent "
+ (parentData != null ? parentData.getQPath().getAsString() : "[null]"), e);
}
finally
{
writeLock.unlock();
}
if (LOG.isDebugEnabled())
{
LOG.debug(name + ", addChildProperties() <<< " + logInfo);
}
}
} } | public class class_name {
public void addChildProperties(final NodeData parentData, final List<PropertyData> childItems)
{
if (enabled && parentData != null && childItems != null)
{
String logInfo = null;
if (LOG.isDebugEnabled())
{
logInfo =
"parent: " + parentData.getQPath().getAsString() + " " + parentData.getIdentifier() + " "
+ childItems.size(); // depends on control dependency: [if], data = [none]
LOG.debug(name + ", addChildProperties() >>> " + logInfo); // depends on control dependency: [if], data = [none]
}
String operName = ""; // for debug/trace only
writeLock.lock();
try
{
// remove parent (no childs)
operName = "removing parent"; // depends on control dependency: [try], data = [none]
removeItem(parentData); // depends on control dependency: [try], data = [none]
operName = "caching parent"; // depends on control dependency: [try], data = [none]
putItem(parentData); // put parent in cache // depends on control dependency: [try], data = [none]
synchronized (childItems) // depends on control dependency: [try], data = [none]
{
operName = "caching child properties list";
propertiesCache.put(parentData.getIdentifier(), childItems); // put childs in cache CP
operName = "caching child properties";
// put childs in cache C
for (ItemData p : childItems)
{
if (LOG.isDebugEnabled())
{
LOG.debug(name + ", addChildProperties() " + p.getQPath().getAsString() + " "
+ p.getIdentifier() + " -- " + p); // depends on control dependency: [if], data = [none]
}
putItem(p); // depends on control dependency: [for], data = [p]
}
}
}
catch (Exception e)
{
LOG.error(name + ", Error in addChildProperties() " + operName + ": parent "
+ (parentData != null ? parentData.getQPath().getAsString() : "[null]"), e);
} // depends on control dependency: [catch], data = [none]
finally
{
writeLock.unlock();
}
if (LOG.isDebugEnabled())
{
LOG.debug(name + ", addChildProperties() <<< " + logInfo); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
@Nonnull
public DataBuilder appendDevicePattern(@Nonnull final DevicePattern pattern) {
Check.notNull(pattern, "pattern");
if (!devicePatterns.containsKey(pattern.getId())) {
devicePatterns.put(pattern.getId(), new TreeSet<DevicePattern>(DEVICE_PATTERN_COMPARATOR));
}
devicePatterns.get(pattern.getId()).add(pattern);
return this;
} } | public class class_name {
@Nonnull
public DataBuilder appendDevicePattern(@Nonnull final DevicePattern pattern) {
Check.notNull(pattern, "pattern");
if (!devicePatterns.containsKey(pattern.getId())) {
devicePatterns.put(pattern.getId(), new TreeSet<DevicePattern>(DEVICE_PATTERN_COMPARATOR)); // depends on control dependency: [if], data = [none]
}
devicePatterns.get(pattern.getId()).add(pattern);
return this;
} } |
public class class_name {
public int getValue(int ch)
{
// valid, uncompacted trie and valid c?
if (m_isCompacted_ || ch > UCharacter.MAX_VALUE || ch < 0) {
return 0;
}
int block = m_index_[ch >> SHIFT_];
return m_data_[Math.abs(block) + (ch & MASK_)];
} } | public class class_name {
public int getValue(int ch)
{
// valid, uncompacted trie and valid c?
if (m_isCompacted_ || ch > UCharacter.MAX_VALUE || ch < 0) {
return 0; // depends on control dependency: [if], data = [none]
}
int block = m_index_[ch >> SHIFT_];
return m_data_[Math.abs(block) + (ch & MASK_)];
} } |
public class class_name {
public void registerHanders(String packageString) {
List<String> list = AnnotationDetector.scanAsList(ExceptionHandler.class, packageString);
for (String handler : list) {
// System.out.println(handler);
JKExceptionHandler<? extends Throwable> newInstance = JKObjectUtil.newInstance(handler);
Class<? extends Throwable> clas = JKObjectUtil.getGenericParamter(handler);
setHandler(clas, newInstance);
}
} } | public class class_name {
public void registerHanders(String packageString) {
List<String> list = AnnotationDetector.scanAsList(ExceptionHandler.class, packageString);
for (String handler : list) {
// System.out.println(handler);
JKExceptionHandler<? extends Throwable> newInstance = JKObjectUtil.newInstance(handler); // depends on control dependency: [for], data = [handler]
Class<? extends Throwable> clas = JKObjectUtil.getGenericParamter(handler);
setHandler(clas, newInstance);
}
} } |
public class class_name {
public String buildSelectStartGalleries(String htmlAttributes) {
StringBuffer result = new StringBuffer(1024);
HttpServletRequest request = getJsp().getRequest();
// set the attributes for the select tag
if (htmlAttributes != null) {
htmlAttributes += " name=\"" + PARAM_STARTGALLERY_PREFIX;
}
Map<String, A_CmsAjaxGallery> galleriesTypes = OpenCms.getWorkplaceManager().getGalleries();
if (galleriesTypes != null) {
// sort the galleries by localized name
Map<String, String> localizedGalleries = new TreeMap<String, String>();
for (Iterator<String> i = galleriesTypes.keySet().iterator(); i.hasNext();) {
String currentGalleryType = i.next();
String localizedName = CmsWorkplaceMessages.getResourceTypeName(this, currentGalleryType);
localizedGalleries.put(localizedName, currentGalleryType);
}
for (Iterator<Map.Entry<String, String>> i = localizedGalleries.entrySet().iterator(); i.hasNext();) {
Map.Entry<String, String> entry = i.next();
// first: retrieve the gallery type
String currentGalleryType = entry.getValue();
// second: retrieve the gallery type id
int currentGalleryTypeId = 0;
try {
currentGalleryTypeId = OpenCms.getResourceManager().getResourceType(currentGalleryType).getTypeId();
} catch (CmsLoaderException e) {
// resource type not found, log error
if (LOG.isErrorEnabled()) {
LOG.error(e.getLocalizedMessage(), e);
}
continue;
}
// third: get the available galleries for this gallery type id
List<CmsResource> availableGalleries = A_CmsAjaxGallery.getGalleries(currentGalleryTypeId, getCms());
// forth: fill the select box
List<String> options = new ArrayList<String>(availableGalleries.size() + 2);
List<String> values = new ArrayList<String>(availableGalleries.size() + 2);
options.add(key(Messages.GUI_PREF_STARTGALLERY_PRESELECT_0));
values.add(INPUT_DEFAULT);
options.add(key(Messages.GUI_PREF_STARTGALLERY_NONE_0));
values.add(INPUT_NONE);
String savedValue = computeStartGalleryPreselection(request, currentGalleryType);
int counter = 2;
int selectedIndex = 0;
Iterator<CmsResource> iGalleries = availableGalleries.iterator();
while (iGalleries.hasNext()) {
CmsResource res = iGalleries.next();
String rootPath = res.getRootPath();
String sitePath = getCms().getSitePath(res);
// select the value
if ((savedValue != null) && (savedValue.equals(rootPath))) {
selectedIndex = counter;
}
counter++;
// gallery title
String title = "";
try {
// read the gallery title
title = getCms().readPropertyObject(
sitePath,
CmsPropertyDefinition.PROPERTY_TITLE,
false).getValue("");
} catch (CmsException e) {
// error reading title property
if (LOG.isErrorEnabled()) {
LOG.error(e.getLocalizedMessage(), e);
}
}
options.add(title.concat(" (").concat(sitePath).concat(")"));
values.add(rootPath);
}
// select the value
if ((savedValue != null) && savedValue.equals(INPUT_NONE)) {
selectedIndex = 1;
}
// create the table row for the current resource type
result.append("<tr>\n\t<td style=\"white-space: nowrap;\">");
result.append(entry.getKey());
result.append("</td>\n\t<td>");
result.append(buildSelect(htmlAttributes + currentGalleryType + "\"", options, values, selectedIndex));
result.append("</td>\n</tr>\n");
}
}
return result.toString();
} } | public class class_name {
public String buildSelectStartGalleries(String htmlAttributes) {
StringBuffer result = new StringBuffer(1024);
HttpServletRequest request = getJsp().getRequest();
// set the attributes for the select tag
if (htmlAttributes != null) {
htmlAttributes += " name=\"" + PARAM_STARTGALLERY_PREFIX; // depends on control dependency: [if], data = [none]
}
Map<String, A_CmsAjaxGallery> galleriesTypes = OpenCms.getWorkplaceManager().getGalleries();
if (galleriesTypes != null) {
// sort the galleries by localized name
Map<String, String> localizedGalleries = new TreeMap<String, String>();
for (Iterator<String> i = galleriesTypes.keySet().iterator(); i.hasNext();) {
String currentGalleryType = i.next();
String localizedName = CmsWorkplaceMessages.getResourceTypeName(this, currentGalleryType);
localizedGalleries.put(localizedName, currentGalleryType); // depends on control dependency: [for], data = [none]
}
for (Iterator<Map.Entry<String, String>> i = localizedGalleries.entrySet().iterator(); i.hasNext();) {
Map.Entry<String, String> entry = i.next();
// first: retrieve the gallery type
String currentGalleryType = entry.getValue();
// second: retrieve the gallery type id
int currentGalleryTypeId = 0;
try {
currentGalleryTypeId = OpenCms.getResourceManager().getResourceType(currentGalleryType).getTypeId(); // depends on control dependency: [try], data = [none]
} catch (CmsLoaderException e) {
// resource type not found, log error
if (LOG.isErrorEnabled()) {
LOG.error(e.getLocalizedMessage(), e); // depends on control dependency: [if], data = [none]
}
continue;
} // depends on control dependency: [catch], data = [none]
// third: get the available galleries for this gallery type id
List<CmsResource> availableGalleries = A_CmsAjaxGallery.getGalleries(currentGalleryTypeId, getCms());
// forth: fill the select box
List<String> options = new ArrayList<String>(availableGalleries.size() + 2);
List<String> values = new ArrayList<String>(availableGalleries.size() + 2);
options.add(key(Messages.GUI_PREF_STARTGALLERY_PRESELECT_0)); // depends on control dependency: [for], data = [none]
values.add(INPUT_DEFAULT); // depends on control dependency: [for], data = [none]
options.add(key(Messages.GUI_PREF_STARTGALLERY_NONE_0)); // depends on control dependency: [for], data = [none]
values.add(INPUT_NONE); // depends on control dependency: [for], data = [none]
String savedValue = computeStartGalleryPreselection(request, currentGalleryType);
int counter = 2;
int selectedIndex = 0;
Iterator<CmsResource> iGalleries = availableGalleries.iterator();
while (iGalleries.hasNext()) {
CmsResource res = iGalleries.next();
String rootPath = res.getRootPath();
String sitePath = getCms().getSitePath(res);
// select the value
if ((savedValue != null) && (savedValue.equals(rootPath))) {
selectedIndex = counter; // depends on control dependency: [if], data = [none]
}
counter++; // depends on control dependency: [while], data = [none]
// gallery title
String title = "";
try {
// read the gallery title
title = getCms().readPropertyObject(
sitePath,
CmsPropertyDefinition.PROPERTY_TITLE,
false).getValue(""); // depends on control dependency: [try], data = [none]
} catch (CmsException e) {
// error reading title property
if (LOG.isErrorEnabled()) {
LOG.error(e.getLocalizedMessage(), e); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
options.add(title.concat(" (").concat(sitePath).concat(")")); // depends on control dependency: [while], data = [none]
values.add(rootPath); // depends on control dependency: [while], data = [none]
}
// select the value
if ((savedValue != null) && savedValue.equals(INPUT_NONE)) {
selectedIndex = 1; // depends on control dependency: [if], data = [none]
}
// create the table row for the current resource type
result.append("<tr>\n\t<td style=\"white-space: nowrap;\">"); // depends on control dependency: [for], data = [none]
result.append(entry.getKey()); // depends on control dependency: [for], data = [none]
result.append("</td>\n\t<td>"); // depends on control dependency: [for], data = [none]
result.append(buildSelect(htmlAttributes + currentGalleryType + "\"", options, values, selectedIndex)); // depends on control dependency: [for], data = [none]
result.append("</td>\n</tr>\n"); // depends on control dependency: [for], data = [none]
}
}
return result.toString();
} } |
public class class_name {
public String path() {
/* build the fully qualified url with all query parameters */
StringBuilder path = new StringBuilder();
if (this.target != null) {
path.append(this.target);
}
if (this.uriTemplate != null) {
path.append(this.uriTemplate.toString());
}
if (path.length() == 0) {
/* no path indicates the root uri */
path.append("/");
}
return path.toString();
} } | public class class_name {
public String path() {
/* build the fully qualified url with all query parameters */
StringBuilder path = new StringBuilder();
if (this.target != null) {
path.append(this.target); // depends on control dependency: [if], data = [(this.target]
}
if (this.uriTemplate != null) {
path.append(this.uriTemplate.toString()); // depends on control dependency: [if], data = [(this.uriTemplate]
}
if (path.length() == 0) {
/* no path indicates the root uri */
path.append("/"); // depends on control dependency: [if], data = [none]
}
return path.toString();
} } |
public class class_name {
public static IWebSocketConnection getConnection4Session(final String _sessionId)
{
IWebSocketConnection ret = null;
if (RegistryManager.getCache().containsKey(_sessionId)) {
final UserSession userSession = RegistryManager.getCache().get(_sessionId);
if (userSession.getConnectionKey() != null) {
final IWebSocketConnectionRegistry registry = WebSocketSettings.Holder.get(EFapsApplication.get())
.getConnectionRegistry();
ret = registry.getConnection(EFapsApplication.get(),
userSession.getSessionId(), userSession.getConnectionKey());
}
}
return ret;
} } | public class class_name {
public static IWebSocketConnection getConnection4Session(final String _sessionId)
{
IWebSocketConnection ret = null;
if (RegistryManager.getCache().containsKey(_sessionId)) {
final UserSession userSession = RegistryManager.getCache().get(_sessionId);
if (userSession.getConnectionKey() != null) {
final IWebSocketConnectionRegistry registry = WebSocketSettings.Holder.get(EFapsApplication.get())
.getConnectionRegistry();
ret = registry.getConnection(EFapsApplication.get(),
userSession.getSessionId(), userSession.getConnectionKey()); // depends on control dependency: [if], data = [none]
}
}
return ret;
} } |
public class class_name {
@SuppressWarnings("unchecked")
public static Stream<Statement> encode(final Stream<? extends Record> stream,
@Nullable final Iterable<? extends URI> types) {
Preconditions.checkNotNull(stream);
if (types != null) {
stream.setProperty("types", types);
}
final Stream<Record> records = (Stream<Record>) stream;
return records.transform(null, new Function<Handler<Statement>, Handler<Record>>() {
@Override
public Handler<Record> apply(final Handler<Statement> handler) {
final Iterable<? extends URI> types = stream.getProperty("types", Iterable.class);
return new Encoder(handler, types);
}
});
} } | public class class_name {
@SuppressWarnings("unchecked")
public static Stream<Statement> encode(final Stream<? extends Record> stream,
@Nullable final Iterable<? extends URI> types) {
Preconditions.checkNotNull(stream);
if (types != null) {
stream.setProperty("types", types); // depends on control dependency: [if], data = [none]
}
final Stream<Record> records = (Stream<Record>) stream;
return records.transform(null, new Function<Handler<Statement>, Handler<Record>>() {
@Override
public Handler<Record> apply(final Handler<Statement> handler) {
final Iterable<? extends URI> types = stream.getProperty("types", Iterable.class);
return new Encoder(handler, types);
}
});
} } |
public class class_name {
private void updateStateAndNotify() {
Boolean oldGroupValid = groupValid;
groupValid = true;
for (Boolean valid : fields.values()) {
groupValid &= valid;
}
if (groupValid != oldGroupValid) {
eventBus.fireEvent(new ValidationChangedEvent(groupValid));
}
} } | public class class_name {
private void updateStateAndNotify() {
Boolean oldGroupValid = groupValid;
groupValid = true;
for (Boolean valid : fields.values()) {
groupValid &= valid; // depends on control dependency: [for], data = [valid]
}
if (groupValid != oldGroupValid) {
eventBus.fireEvent(new ValidationChangedEvent(groupValid)); // depends on control dependency: [if], data = [(groupValid]
}
} } |
public class class_name {
public ColorImg copyArea(int x, int y, int w, int h, ColorImg dest, int destX, int destY){
ImagingKitUtils.requireAreaInImageBounds(x, y, w, h, this);
if(dest == null){
return copyArea(x, y, w, h, new ColorImg(w,h,this.hasAlpha()), 0, 0);
}
if(x==0 && destX==0 && w==dest.getWidth() && w==this.getWidth()){
if(destY < 0){
/* negative destination y
* need to shrink area by overlap and translate area origin */
y -= destY;
h += destY;
destY = 0;
}
// limit area height to not exceed targets bounds
h = Math.min(h, dest.getHeight()-destY);
if(h > 0){
int srcPos = y*w, destPos = destY*w, len=w*h;
System.arraycopy(this.getDataR(), srcPos, dest.getDataR(), destPos, len);
System.arraycopy(this.getDataG(), srcPos, dest.getDataG(), destPos, len);
System.arraycopy(this.getDataB(), srcPos, dest.getDataB(), destPos, len);
if(this.hasAlpha() && dest.hasAlpha())
System.arraycopy(this.getDataA(), srcPos, dest.getDataA(), destPos, len);
}
} else {
if(destX < 0){
/* negative destination x
* need to shrink area by overlap and translate area origin */
x -= destX;
w += destX;
destX = 0;
}
if(destY < 0){
/* negative destination y
* need to shrink area by overlap and translate area origin */
y -= destY;
h += destY;
destY = 0;
}
// limit area to not exceed targets bounds
w = Math.min(w, dest.getWidth()-destX);
h = Math.min(h, dest.getHeight()-destY);
if(w > 0 && h > 0){
for(int i = 0; i < h; i++){
int srcPos = (y+i)*getWidth()+x;
int destPos = (destY+i)*dest.getWidth()+destX;
int len = w;
System.arraycopy(
this.getDataR(), srcPos,
dest.getDataR(), destPos,
len);
System.arraycopy(
this.getDataG(), srcPos,
dest.getDataG(), destPos,
len);
System.arraycopy(
this.getDataB(), srcPos,
dest.getDataB(), destPos,
len);
if(this.hasAlpha() && dest.hasAlpha()) {
System.arraycopy(
this.getDataA(), srcPos,
dest.getDataA(), destPos,
len);
}
}
}
}
return dest;
} } | public class class_name {
public ColorImg copyArea(int x, int y, int w, int h, ColorImg dest, int destX, int destY){
ImagingKitUtils.requireAreaInImageBounds(x, y, w, h, this);
if(dest == null){
return copyArea(x, y, w, h, new ColorImg(w,h,this.hasAlpha()), 0, 0); // depends on control dependency: [if], data = [none]
}
if(x==0 && destX==0 && w==dest.getWidth() && w==this.getWidth()){
if(destY < 0){
/* negative destination y
* need to shrink area by overlap and translate area origin */
y -= destY; // depends on control dependency: [if], data = [none]
h += destY; // depends on control dependency: [if], data = [none]
destY = 0; // depends on control dependency: [if], data = [none]
}
// limit area height to not exceed targets bounds
h = Math.min(h, dest.getHeight()-destY); // depends on control dependency: [if], data = [none]
if(h > 0){
int srcPos = y*w, destPos = destY*w, len=w*h;
System.arraycopy(this.getDataR(), srcPos, dest.getDataR(), destPos, len); // depends on control dependency: [if], data = [none]
System.arraycopy(this.getDataG(), srcPos, dest.getDataG(), destPos, len); // depends on control dependency: [if], data = [none]
System.arraycopy(this.getDataB(), srcPos, dest.getDataB(), destPos, len); // depends on control dependency: [if], data = [none]
if(this.hasAlpha() && dest.hasAlpha())
System.arraycopy(this.getDataA(), srcPos, dest.getDataA(), destPos, len);
}
} else {
if(destX < 0){
/* negative destination x
* need to shrink area by overlap and translate area origin */
x -= destX; // depends on control dependency: [if], data = [none]
w += destX; // depends on control dependency: [if], data = [none]
destX = 0; // depends on control dependency: [if], data = [none]
}
if(destY < 0){
/* negative destination y
* need to shrink area by overlap and translate area origin */
y -= destY; // depends on control dependency: [if], data = [none]
h += destY; // depends on control dependency: [if], data = [none]
destY = 0; // depends on control dependency: [if], data = [none]
}
// limit area to not exceed targets bounds
w = Math.min(w, dest.getWidth()-destX); // depends on control dependency: [if], data = [none]
h = Math.min(h, dest.getHeight()-destY); // depends on control dependency: [if], data = [none]
if(w > 0 && h > 0){
for(int i = 0; i < h; i++){
int srcPos = (y+i)*getWidth()+x;
int destPos = (destY+i)*dest.getWidth()+destX;
int len = w;
System.arraycopy(
this.getDataR(), srcPos,
dest.getDataR(), destPos,
len); // depends on control dependency: [for], data = [none]
System.arraycopy(
this.getDataG(), srcPos,
dest.getDataG(), destPos,
len); // depends on control dependency: [for], data = [none]
System.arraycopy(
this.getDataB(), srcPos,
dest.getDataB(), destPos,
len); // depends on control dependency: [for], data = [none]
if(this.hasAlpha() && dest.hasAlpha()) {
System.arraycopy(
this.getDataA(), srcPos,
dest.getDataA(), destPos,
len); // depends on control dependency: [if], data = [none]
}
}
}
}
return dest;
} } |
public class class_name {
public List<Card> parseData(@Nullable T data) {
List<Card> cardList = mDataParser.parseGroup(data, this);
MVHelper mvHelper = (MVHelper) mServices.get(MVHelper.class);
if (mvHelper != null) {
mvHelper.renderManager().onDownloadTemplate();
}
return cardList;
} } | public class class_name {
public List<Card> parseData(@Nullable T data) {
List<Card> cardList = mDataParser.parseGroup(data, this);
MVHelper mvHelper = (MVHelper) mServices.get(MVHelper.class);
if (mvHelper != null) {
mvHelper.renderManager().onDownloadTemplate(); // depends on control dependency: [if], data = [none]
}
return cardList;
} } |
public class class_name {
public NamedEntityGraph<Entity<T>> getOrCreateNamedEntityGraph()
{
List<Node> nodeList = childNode.get("named-entity-graph");
if (nodeList != null && nodeList.size() > 0)
{
return new NamedEntityGraphImpl<Entity<T>>(this, "named-entity-graph", childNode, nodeList.get(0));
}
return createNamedEntityGraph();
} } | public class class_name {
public NamedEntityGraph<Entity<T>> getOrCreateNamedEntityGraph()
{
List<Node> nodeList = childNode.get("named-entity-graph");
if (nodeList != null && nodeList.size() > 0)
{
return new NamedEntityGraphImpl<Entity<T>>(this, "named-entity-graph", childNode, nodeList.get(0)); // depends on control dependency: [if], data = [none]
}
return createNamedEntityGraph();
} } |
public class class_name {
protected void addLineageSourceInfo(WorkUnit workUnit, State state) {
if (!lineageInfo.isPresent()) {
log.info("Lineage is not enabled");
return;
}
String platform = state.getProp(ConfigurationKeys.SOURCE_FILEBASED_PLATFORM, DatasetConstants.PLATFORM_HDFS);
Path dataDir = new Path(state.getProp(ConfigurationKeys.SOURCE_FILEBASED_DATA_DIRECTORY));
String dataset = Path.getPathWithoutSchemeAndAuthority(dataDir).toString();
DatasetDescriptor source = new DatasetDescriptor(platform, dataset);
lineageInfo.get().setSource(source, workUnit);
} } | public class class_name {
protected void addLineageSourceInfo(WorkUnit workUnit, State state) {
if (!lineageInfo.isPresent()) {
log.info("Lineage is not enabled"); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
String platform = state.getProp(ConfigurationKeys.SOURCE_FILEBASED_PLATFORM, DatasetConstants.PLATFORM_HDFS);
Path dataDir = new Path(state.getProp(ConfigurationKeys.SOURCE_FILEBASED_DATA_DIRECTORY));
String dataset = Path.getPathWithoutSchemeAndAuthority(dataDir).toString();
DatasetDescriptor source = new DatasetDescriptor(platform, dataset);
lineageInfo.get().setSource(source, workUnit);
} } |
public class class_name {
public DescribeHsmConfigurationsRequest withTagValues(String... tagValues) {
if (this.tagValues == null) {
setTagValues(new com.amazonaws.internal.SdkInternalList<String>(tagValues.length));
}
for (String ele : tagValues) {
this.tagValues.add(ele);
}
return this;
} } | public class class_name {
public DescribeHsmConfigurationsRequest withTagValues(String... tagValues) {
if (this.tagValues == null) {
setTagValues(new com.amazonaws.internal.SdkInternalList<String>(tagValues.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : tagValues) {
this.tagValues.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
static void bindTabWithData(BottomNavigationItem bottomNavigationItem, BottomNavigationTab bottomNavigationTab, BottomNavigationBar bottomNavigationBar) {
Context context = bottomNavigationBar.getContext();
bottomNavigationTab.setLabel(bottomNavigationItem.getTitle(context));
bottomNavigationTab.setIcon(bottomNavigationItem.getIcon(context));
int activeColor = bottomNavigationItem.getActiveColor(context);
int inActiveColor = bottomNavigationItem.getInActiveColor(context);
if (activeColor != Utils.NO_COLOR) {
bottomNavigationTab.setActiveColor(activeColor);
} else {
bottomNavigationTab.setActiveColor(bottomNavigationBar.getActiveColor());
}
if (inActiveColor != Utils.NO_COLOR) {
bottomNavigationTab.setInactiveColor(inActiveColor);
} else {
bottomNavigationTab.setInactiveColor(bottomNavigationBar.getInActiveColor());
}
if (bottomNavigationItem.isInActiveIconAvailable()) {
Drawable inactiveDrawable = bottomNavigationItem.getInactiveIcon(context);
if (inactiveDrawable != null) {
bottomNavigationTab.setInactiveIcon(inactiveDrawable);
}
}
bottomNavigationTab.setItemBackgroundColor(bottomNavigationBar.getBackgroundColor());
BadgeItem badgeItem = bottomNavigationItem.getBadgeItem();
if (badgeItem != null) {
badgeItem.bindToBottomTab(bottomNavigationTab);
}
} } | public class class_name {
static void bindTabWithData(BottomNavigationItem bottomNavigationItem, BottomNavigationTab bottomNavigationTab, BottomNavigationBar bottomNavigationBar) {
Context context = bottomNavigationBar.getContext();
bottomNavigationTab.setLabel(bottomNavigationItem.getTitle(context));
bottomNavigationTab.setIcon(bottomNavigationItem.getIcon(context));
int activeColor = bottomNavigationItem.getActiveColor(context);
int inActiveColor = bottomNavigationItem.getInActiveColor(context);
if (activeColor != Utils.NO_COLOR) {
bottomNavigationTab.setActiveColor(activeColor); // depends on control dependency: [if], data = [(activeColor]
} else {
bottomNavigationTab.setActiveColor(bottomNavigationBar.getActiveColor()); // depends on control dependency: [if], data = [none]
}
if (inActiveColor != Utils.NO_COLOR) {
bottomNavigationTab.setInactiveColor(inActiveColor); // depends on control dependency: [if], data = [(inActiveColor]
} else {
bottomNavigationTab.setInactiveColor(bottomNavigationBar.getInActiveColor()); // depends on control dependency: [if], data = [none]
}
if (bottomNavigationItem.isInActiveIconAvailable()) {
Drawable inactiveDrawable = bottomNavigationItem.getInactiveIcon(context);
if (inactiveDrawable != null) {
bottomNavigationTab.setInactiveIcon(inactiveDrawable); // depends on control dependency: [if], data = [(inactiveDrawable]
}
}
bottomNavigationTab.setItemBackgroundColor(bottomNavigationBar.getBackgroundColor());
BadgeItem badgeItem = bottomNavigationItem.getBadgeItem();
if (badgeItem != null) {
badgeItem.bindToBottomTab(bottomNavigationTab); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static void validate(HppRequest hppRequest) {
Set<ConstraintViolation<HppRequest>> constraintViolations = validator.validate(hppRequest);
if (constraintViolations.size() > 0) {
List<String> validationMessages = new ArrayList<String>();
Iterator<ConstraintViolation<HppRequest>> i = constraintViolations.iterator();
while (i.hasNext()) {
ConstraintViolation<HppRequest> constraitViolation = i.next();
validationMessages.add(constraitViolation.getMessage());
}
LOGGER.info("HppRequest failed validation with the following errors {}", validationMessages);
throw new RealexValidationException("HppRequest failed validation", validationMessages);
}
} } | public class class_name {
public static void validate(HppRequest hppRequest) {
Set<ConstraintViolation<HppRequest>> constraintViolations = validator.validate(hppRequest);
if (constraintViolations.size() > 0) {
List<String> validationMessages = new ArrayList<String>();
Iterator<ConstraintViolation<HppRequest>> i = constraintViolations.iterator();
while (i.hasNext()) {
ConstraintViolation<HppRequest> constraitViolation = i.next();
validationMessages.add(constraitViolation.getMessage()); // depends on control dependency: [while], data = [none]
}
LOGGER.info("HppRequest failed validation with the following errors {}", validationMessages); // depends on control dependency: [if], data = [none]
throw new RealexValidationException("HppRequest failed validation", validationMessages);
}
} } |
public class class_name {
public static void replaceNonWordChars(StringValue string, char replacement) {
final char[] chars = string.getCharArray();
final int len = string.length();
for (int i = 0; i < len; i++) {
final char c = chars[i];
if (!(Character.isLetter(c) || Character.isDigit(c) || c == '_')) {
chars[i] = replacement;
}
}
} } | public class class_name {
public static void replaceNonWordChars(StringValue string, char replacement) {
final char[] chars = string.getCharArray();
final int len = string.length();
for (int i = 0; i < len; i++) {
final char c = chars[i];
if (!(Character.isLetter(c) || Character.isDigit(c) || c == '_')) {
chars[i] = replacement; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static void closeQuietly(XMLStreamWriter writer) {
if (writer != null) {
try {
writer.close();
} catch (XMLStreamException e) {
logger.warn("Error while closing", e);
}
}
} } | public class class_name {
public static void closeQuietly(XMLStreamWriter writer) {
if (writer != null) {
try {
writer.close(); // depends on control dependency: [try], data = [none]
} catch (XMLStreamException e) {
logger.warn("Error while closing", e);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
private static byte[] getBytes(String string, Charset charset) {
if (string == null) {
return null;
}
return string.getBytes(charset);
} } | public class class_name {
private static byte[] getBytes(String string, Charset charset) {
if (string == null) {
return null; // depends on control dependency: [if], data = [none]
}
return string.getBytes(charset);
} } |
public class class_name {
@Override
public void generateWriteParam2ContentValues(Builder methodBuilder, SQLiteModelMethod method, String paramName, TypeName paramTypeName, ModelProperty property) {
if (property != null && property.hasTypeAdapter()) {
methodBuilder.addCode(WRITE_COSTANT + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER, SQLTypeAdapterUtils.class, property.typeAdapter.getAdapterTypeName(), paramName);
} else if (method.hasAdapterForParam(paramName)) {
methodBuilder.addCode(WRITE_COSTANT + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER, SQLTypeAdapterUtils.class, method.getAdapterForParam(paramName), paramName);
} else {
methodBuilder.addCode(WRITE_COSTANT + "$L", paramName);
}
} } | public class class_name {
@Override
public void generateWriteParam2ContentValues(Builder methodBuilder, SQLiteModelMethod method, String paramName, TypeName paramTypeName, ModelProperty property) {
if (property != null && property.hasTypeAdapter()) {
methodBuilder.addCode(WRITE_COSTANT + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER, SQLTypeAdapterUtils.class, property.typeAdapter.getAdapterTypeName(), paramName); // depends on control dependency: [if], data = [none]
} else if (method.hasAdapterForParam(paramName)) {
methodBuilder.addCode(WRITE_COSTANT + PRE_TYPE_ADAPTER_TO_DATA + "$L" + POST_TYPE_ADAPTER, SQLTypeAdapterUtils.class, method.getAdapterForParam(paramName), paramName); // depends on control dependency: [if], data = [none]
} else {
methodBuilder.addCode(WRITE_COSTANT + "$L", paramName); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private IAsyncResultHandler<IEngineResult> wrapResultHandler(final IAsyncResultHandler<IEngineResult> handler) {
return (IAsyncResult<IEngineResult> result) -> {
boolean doRecord = true;
if (result.isError()) {
recordErrorMetrics(result.getError());
} else {
IEngineResult engineResult = result.getResult();
if (engineResult.isFailure()) {
recordFailureMetrics(engineResult.getPolicyFailure());
} else {
recordSuccessMetrics(engineResult.getApiResponse());
doRecord = false; // don't record the metric now because we need to record # of bytes downloaded, which hasn't happened yet
}
}
requestMetric.setRequestEnd(new Date());
if (doRecord) {
metrics.record(requestMetric);
}
handler.handle(result);
};
} } | public class class_name {
private IAsyncResultHandler<IEngineResult> wrapResultHandler(final IAsyncResultHandler<IEngineResult> handler) {
return (IAsyncResult<IEngineResult> result) -> {
boolean doRecord = true;
if (result.isError()) {
recordErrorMetrics(result.getError()); // depends on control dependency: [if], data = [none]
} else {
IEngineResult engineResult = result.getResult();
if (engineResult.isFailure()) {
recordFailureMetrics(engineResult.getPolicyFailure()); // depends on control dependency: [if], data = [none]
} else {
recordSuccessMetrics(engineResult.getApiResponse()); // depends on control dependency: [if], data = [none]
doRecord = false; // don't record the metric now because we need to record # of bytes downloaded, which hasn't happened yet // depends on control dependency: [if], data = [none]
}
}
requestMetric.setRequestEnd(new Date());
if (doRecord) {
metrics.record(requestMetric); // depends on control dependency: [if], data = [none]
}
handler.handle(result);
};
} } |
public class class_name {
@Override
public List<MonitorLine> getLinesFrom(Object actual) throws Exception {
//TODO Enhance line retrieve to get last lines directly
String line;
Integer currentLineNo = 0;
final List<MonitorLine> result = new ArrayList<MonitorLine>();
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(getFilename()));
Integer startLine = (actual == null) ? 0 : (Integer) actual;
//read to startLine
while (currentLineNo < startLine + 1) {
if (in.readLine() == null) {
throw new IOException("File too small");
}
currentLineNo++;
}
//read until endLine
line = in.readLine();
while (line != null) {
result.add(new MonitorLine(currentLineNo, line));
currentLineNo++;
line = in.readLine();
}
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ignore) {
}
}
return result;
} } | public class class_name {
@Override
public List<MonitorLine> getLinesFrom(Object actual) throws Exception {
//TODO Enhance line retrieve to get last lines directly
String line;
Integer currentLineNo = 0;
final List<MonitorLine> result = new ArrayList<MonitorLine>();
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(getFilename()));
Integer startLine = (actual == null) ? 0 : (Integer) actual;
//read to startLine
while (currentLineNo < startLine + 1) {
if (in.readLine() == null) {
throw new IOException("File too small");
}
currentLineNo++; // depends on control dependency: [while], data = [none]
}
//read until endLine
line = in.readLine();
while (line != null) {
result.add(new MonitorLine(currentLineNo, line)); // depends on control dependency: [while], data = [none]
currentLineNo++; // depends on control dependency: [while], data = [none]
line = in.readLine(); // depends on control dependency: [while], data = [none]
}
} finally {
try {
if (in != null) {
in.close(); // depends on control dependency: [if], data = [none]
}
} catch (IOException ignore) {
} // depends on control dependency: [catch], data = [none]
}
return result;
} } |
public class class_name {
public static float getDimension(@NonNull final Context context,
@StyleRes final int themeResourceId,
@AttrRes final int resourceId) {
TypedArray typedArray = null;
try {
typedArray = obtainStyledAttributes(context, themeResourceId, resourceId);
float dimension = typedArray.getDimension(0, -1);
if (dimension == -1) {
throw new NotFoundException(
"Resource ID #0x" + Integer.toHexString(resourceId) + " is not valid");
}
return dimension;
} finally {
if (typedArray != null) {
typedArray.recycle();
}
}
} } | public class class_name {
public static float getDimension(@NonNull final Context context,
@StyleRes final int themeResourceId,
@AttrRes final int resourceId) {
TypedArray typedArray = null;
try {
typedArray = obtainStyledAttributes(context, themeResourceId, resourceId); // depends on control dependency: [try], data = [none]
float dimension = typedArray.getDimension(0, -1);
if (dimension == -1) {
throw new NotFoundException(
"Resource ID #0x" + Integer.toHexString(resourceId) + " is not valid");
}
return dimension; // depends on control dependency: [try], data = [none]
} finally {
if (typedArray != null) {
typedArray.recycle(); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public void printTo(StringBuffer buf, ReadablePartial partial) {
try {
printTo((Appendable) buf, partial);
} catch (IOException ex) {
// StringBuffer does not throw IOException
}
} } | public class class_name {
public void printTo(StringBuffer buf, ReadablePartial partial) {
try {
printTo((Appendable) buf, partial); // depends on control dependency: [try], data = [none]
} catch (IOException ex) {
// StringBuffer does not throw IOException
} // depends on control dependency: [catch], data = [none]
} } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.