code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { private Array makeLazyTime2Darray(Variable coord, Time2Dinfo info) { CoordinateTime2D time2D = info.time2D; CalendarPeriod timeUnit = time2D.getTimeUnit(); int nruns = time2D.getNruns(); int ntimes = time2D.getNtimes(); int length = (int) coord.getSize(); if (info.which == Time2DinfoType.bounds) { length *= 2; } double[] data = new double[length]; for (int i = 0; i < length; i++) { data[i] = Double.NaN; } int count; // coordinate values switch (info.which) { case off: for (int runIdx = 0; runIdx < nruns; runIdx++) { CoordinateTime coordTime = (CoordinateTime) time2D.getTimeCoordinate(runIdx); int timeIdx = 0; for (int val : coordTime.getOffsetSorted()) { data[runIdx * ntimes + timeIdx] = timeUnit.getValue() * val + time2D.getOffset(runIdx); timeIdx++; } } break; case offU: count = 0; for (int runIdx = 0; runIdx < nruns; runIdx++) { CoordinateTime coordTime = (CoordinateTime) time2D.getTimeCoordinate(runIdx); for (int val : coordTime.getOffsetSorted()) { data[count++] = timeUnit.getValue() * val + time2D.getOffset(runIdx); } } break; case intv: for (int runIdx = 0; runIdx < nruns; runIdx++) { CoordinateTimeIntv timeIntv = (CoordinateTimeIntv) time2D.getTimeCoordinate(runIdx); int timeIdx = 0; for (TimeCoordIntvValue tinv : timeIntv.getTimeIntervals()) { data[runIdx * ntimes + timeIdx] = timeUnit.getValue() * tinv.getBounds2() + time2D .getOffset(runIdx); // use upper bounds for coord value timeIdx++; } } break; case intvU: count = 0; for (int runIdx = 0; runIdx < nruns; runIdx++) { CoordinateTimeIntv timeIntv = (CoordinateTimeIntv) time2D.getTimeCoordinate(runIdx); for (TimeCoordIntvValue tinv : timeIntv.getTimeIntervals()) { data[count++] = timeUnit.getValue() * tinv.getBounds2() + time2D .getOffset(runIdx); // use upper bounds for coord value } } break; case is1Dtime: CoordinateRuntime runtime = time2D.getRuntimeCoordinate(); count = 0; for (double val : runtime.getOffsetsInTimeUnits()) { // convert to udunits data[count++] = val; } break; case isUniqueRuntime: // the aux runtime coordinate CoordinateRuntime runtimeU = time2D.getRuntimeCoordinate(); List<Double> runOffsets = runtimeU.getOffsetsInTimeUnits(); count = 0; for (int run = 0; run < time2D.getNruns(); run++) { CoordinateTimeAbstract timeCoord = time2D.getTimeCoordinate(run); for (int time = 0; time < timeCoord.getNCoords(); time++) { data[count++] = runOffsets.get(run); } } break; case bounds: for (int runIdx = 0; runIdx < nruns; runIdx++) { CoordinateTimeIntv timeIntv = (CoordinateTimeIntv) time2D.getTimeCoordinate(runIdx); int timeIdx = 0; for (TimeCoordIntvValue tinv : timeIntv.getTimeIntervals()) { data[runIdx * ntimes * 2 + timeIdx] = timeUnit.getValue() * tinv.getBounds1() + time2D.getOffset(runIdx); data[runIdx * ntimes * 2 + timeIdx + 1] = timeUnit.getValue() * tinv.getBounds2() + time2D.getOffset(runIdx); timeIdx += 2; } } break; case boundsU: count = 0; for (int runIdx = 0; runIdx < nruns; runIdx++) { CoordinateTimeIntv timeIntv = (CoordinateTimeIntv) time2D.getTimeCoordinate(runIdx); for (TimeCoordIntvValue tinv : timeIntv.getTimeIntervals()) { data[count++] = timeUnit.getValue() * tinv.getBounds1() + time2D.getOffset(runIdx); data[count++] = timeUnit.getValue() * tinv.getBounds2() + time2D.getOffset(runIdx); } } break; default: throw new IllegalStateException(); } return Array.factory(DataType.DOUBLE, coord.getShape(), data); } }
public class class_name { private Array makeLazyTime2Darray(Variable coord, Time2Dinfo info) { CoordinateTime2D time2D = info.time2D; CalendarPeriod timeUnit = time2D.getTimeUnit(); int nruns = time2D.getNruns(); int ntimes = time2D.getNtimes(); int length = (int) coord.getSize(); if (info.which == Time2DinfoType.bounds) { length *= 2; // depends on control dependency: [if], data = [none] } double[] data = new double[length]; for (int i = 0; i < length; i++) { data[i] = Double.NaN; // depends on control dependency: [for], data = [i] } int count; // coordinate values switch (info.which) { case off: for (int runIdx = 0; runIdx < nruns; runIdx++) { CoordinateTime coordTime = (CoordinateTime) time2D.getTimeCoordinate(runIdx); int timeIdx = 0; for (int val : coordTime.getOffsetSorted()) { data[runIdx * ntimes + timeIdx] = timeUnit.getValue() * val + time2D.getOffset(runIdx); // depends on control dependency: [for], data = [val] timeIdx++; // depends on control dependency: [for], data = [none] } } break; case offU: count = 0; for (int runIdx = 0; runIdx < nruns; runIdx++) { CoordinateTime coordTime = (CoordinateTime) time2D.getTimeCoordinate(runIdx); for (int val : coordTime.getOffsetSorted()) { data[count++] = timeUnit.getValue() * val + time2D.getOffset(runIdx); // depends on control dependency: [for], data = [val] } } break; case intv: for (int runIdx = 0; runIdx < nruns; runIdx++) { CoordinateTimeIntv timeIntv = (CoordinateTimeIntv) time2D.getTimeCoordinate(runIdx); int timeIdx = 0; for (TimeCoordIntvValue tinv : timeIntv.getTimeIntervals()) { data[runIdx * ntimes + timeIdx] = timeUnit.getValue() * tinv.getBounds2() + time2D .getOffset(runIdx); // use upper bounds for coord value // depends on control dependency: [for], data = [none] timeIdx++; // depends on control dependency: [for], data = [none] } } break; case intvU: count = 0; for (int runIdx = 0; runIdx < nruns; runIdx++) { CoordinateTimeIntv timeIntv = (CoordinateTimeIntv) time2D.getTimeCoordinate(runIdx); for (TimeCoordIntvValue tinv : timeIntv.getTimeIntervals()) { data[count++] = timeUnit.getValue() * tinv.getBounds2() + time2D .getOffset(runIdx); // use upper bounds for coord value // depends on control dependency: [for], data = [none] } } break; case is1Dtime: CoordinateRuntime runtime = time2D.getRuntimeCoordinate(); count = 0; for (double val : runtime.getOffsetsInTimeUnits()) { // convert to udunits data[count++] = val; // depends on control dependency: [for], data = [val] } break; case isUniqueRuntime: // the aux runtime coordinate CoordinateRuntime runtimeU = time2D.getRuntimeCoordinate(); List<Double> runOffsets = runtimeU.getOffsetsInTimeUnits(); count = 0; for (int run = 0; run < time2D.getNruns(); run++) { CoordinateTimeAbstract timeCoord = time2D.getTimeCoordinate(run); for (int time = 0; time < timeCoord.getNCoords(); time++) { data[count++] = runOffsets.get(run); // depends on control dependency: [for], data = [none] } } break; case bounds: for (int runIdx = 0; runIdx < nruns; runIdx++) { CoordinateTimeIntv timeIntv = (CoordinateTimeIntv) time2D.getTimeCoordinate(runIdx); int timeIdx = 0; for (TimeCoordIntvValue tinv : timeIntv.getTimeIntervals()) { data[runIdx * ntimes * 2 + timeIdx] = timeUnit.getValue() * tinv.getBounds1() + time2D.getOffset(runIdx); // depends on control dependency: [for], data = [none] data[runIdx * ntimes * 2 + timeIdx + 1] = timeUnit.getValue() * tinv.getBounds2() + time2D.getOffset(runIdx); // depends on control dependency: [for], data = [none] timeIdx += 2; // depends on control dependency: [for], data = [none] } } break; case boundsU: count = 0; for (int runIdx = 0; runIdx < nruns; runIdx++) { CoordinateTimeIntv timeIntv = (CoordinateTimeIntv) time2D.getTimeCoordinate(runIdx); for (TimeCoordIntvValue tinv : timeIntv.getTimeIntervals()) { data[count++] = timeUnit.getValue() * tinv.getBounds1() + time2D.getOffset(runIdx); // depends on control dependency: [for], data = [tinv] data[count++] = timeUnit.getValue() * tinv.getBounds2() + time2D.getOffset(runIdx); // depends on control dependency: [for], data = [tinv] } } break; default: throw new IllegalStateException(); } return Array.factory(DataType.DOUBLE, coord.getShape(), data); } }
public class class_name { public static boolean isSourcePixel( RandomIter flowIter, int col, int row ) { double flowDirection = flowIter.getSampleDouble(col, row, 0); if (flowDirection < 9.0 && flowDirection > 0.0) { for( int k = 1; k <= 8; k++ ) { if (flowIter.getSampleDouble(col + dirIn[k][1], row + dirIn[k][0], 0) == dirIn[k][2]) { return false; } } return true; } else { return false; } } }
public class class_name { public static boolean isSourcePixel( RandomIter flowIter, int col, int row ) { double flowDirection = flowIter.getSampleDouble(col, row, 0); if (flowDirection < 9.0 && flowDirection > 0.0) { for( int k = 1; k <= 8; k++ ) { if (flowIter.getSampleDouble(col + dirIn[k][1], row + dirIn[k][0], 0) == dirIn[k][2]) { return false; // depends on control dependency: [if], data = [none] } } return true; // depends on control dependency: [if], data = [none] } else { return false; // depends on control dependency: [if], data = [none] } } }
public class class_name { private void processJsonSerializeAnnotations(final RoundEnvironment roundEnv) { final Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(JsonSerialize.class); for (final Element e : elements) { if (e.getKind() != ElementKind.CLASS) { debugMessages.add("kind for " + e + " is not CLASS, but " + e.getKind()); continue; } final TypeElement te = (TypeElement) e; final String className = te.getQualifiedName().toString(); if (jsonClasses.containsKey(className)) { // it has already been processed by other means continue; } getOrCreateTransferClass(className, processingEnv.getElementUtils().getDocComment(te)); } } }
public class class_name { private void processJsonSerializeAnnotations(final RoundEnvironment roundEnv) { final Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(JsonSerialize.class); for (final Element e : elements) { if (e.getKind() != ElementKind.CLASS) { debugMessages.add("kind for " + e + " is not CLASS, but " + e.getKind()); // depends on control dependency: [if], data = [none] continue; } final TypeElement te = (TypeElement) e; final String className = te.getQualifiedName().toString(); if (jsonClasses.containsKey(className)) { // it has already been processed by other means continue; } getOrCreateTransferClass(className, processingEnv.getElementUtils().getDocComment(te)); // depends on control dependency: [for], data = [e] } } }
public class class_name { public static String escape(char c) { final StringBuilder builder = new StringBuilder(); if (RE_KEYS.contains(c)) { builder.append('\\'); } builder.append(c); return builder.toString(); } }
public class class_name { public static String escape(char c) { final StringBuilder builder = new StringBuilder(); if (RE_KEYS.contains(c)) { builder.append('\\'); // depends on control dependency: [if], data = [none] } builder.append(c); return builder.toString(); } }
public class class_name { @Override public final Evaluation getCachedMoveEvaluation(Move<?> move) { if(evaluatedMove == null || !evaluatedMove.equals(move)){ // cache miss return null; } else { // cache hit return evaluation; } } }
public class class_name { @Override public final Evaluation getCachedMoveEvaluation(Move<?> move) { if(evaluatedMove == null || !evaluatedMove.equals(move)){ // cache miss return null; // depends on control dependency: [if], data = [none] } else { // cache hit return evaluation; // depends on control dependency: [if], data = [none] } } }
public class class_name { public synchronized void received(SSTableWriter sstable) { if (done) return; assert cfId.equals(sstable.metadata.cfId); sstables.add(sstable); if (sstables.size() == totalFiles) { done = true; executor.submit(new OnCompletionRunnable(this)); } } }
public class class_name { public synchronized void received(SSTableWriter sstable) { if (done) return; assert cfId.equals(sstable.metadata.cfId); sstables.add(sstable); if (sstables.size() == totalFiles) { done = true; // depends on control dependency: [if], data = [none] executor.submit(new OnCompletionRunnable(this)); // depends on control dependency: [if], data = [none] } } }
public class class_name { protected void addAppConfigToCategory(I_CmsWorkplaceAppConfiguration appConfig) { CmsAppCategoryNode node = m_nodes.get(appConfig.getAppCategory()); if (node == null) { LOG.info( "Missing parent [" + appConfig.getAppCategory() + "] for " + appConfig.getId() + " / " + appConfig.getClass().getName()); } else { node.addAppConfiguration(appConfig); } } }
public class class_name { protected void addAppConfigToCategory(I_CmsWorkplaceAppConfiguration appConfig) { CmsAppCategoryNode node = m_nodes.get(appConfig.getAppCategory()); if (node == null) { LOG.info( "Missing parent [" + appConfig.getAppCategory() + "] for " + appConfig.getId() + " / " + appConfig.getClass().getName()); // depends on control dependency: [if], data = [none] } else { node.addAppConfiguration(appConfig); // depends on control dependency: [if], data = [none] } } }
public class class_name { static public void dispose (ByteBuffer buffer) { if (!(buffer instanceof DirectBuffer)) return; if (cleanerMethod != null) { try { cleanMethod.invoke(cleanerMethod.invoke(buffer)); } catch (Throwable ignored) { } } } }
public class class_name { static public void dispose (ByteBuffer buffer) { if (!(buffer instanceof DirectBuffer)) return; if (cleanerMethod != null) { try { cleanMethod.invoke(cleanerMethod.invoke(buffer)); // depends on control dependency: [try], data = [none] } catch (Throwable ignored) { } // depends on control dependency: [catch], data = [none] } } }
public class class_name { private Address waitForReplicaAddress(int replica, IPartition partition, int backupCount) { int tryCount = RETRY_COUNT; Address replicaAddress = null; while (replicaAddress == null && partitionService.getMaxAllowedBackupCount() >= backupCount && tryCount-- > 0) { sleep(); replicaAddress = partition.getReplicaAddress(replica); } return replicaAddress; } }
public class class_name { private Address waitForReplicaAddress(int replica, IPartition partition, int backupCount) { int tryCount = RETRY_COUNT; Address replicaAddress = null; while (replicaAddress == null && partitionService.getMaxAllowedBackupCount() >= backupCount && tryCount-- > 0) { sleep(); // depends on control dependency: [while], data = [none] replicaAddress = partition.getReplicaAddress(replica); // depends on control dependency: [while], data = [none] } return replicaAddress; } }
public class class_name { public <T extends IncomingDataPoint> void processDataPoint(final TSDB tsdb, final HttpQuery query, final List<T> dps) { if (dps.size() < 1) { throw new BadRequestException("No datapoints found in content"); } final HashMap<String, String> query_tags = new HashMap<String, String>(); final boolean show_details = query.hasQueryStringParam("details"); final boolean show_summary = query.hasQueryStringParam("summary"); final boolean synchronous = query.hasQueryStringParam("sync"); final int sync_timeout = query.hasQueryStringParam("sync_timeout") ? Integer.parseInt(query.getQueryStringParam("sync_timeout")) : 0; // this is used to coordinate timeouts final AtomicBoolean sending_response = new AtomicBoolean(); sending_response.set(false); final List<Map<String, Object>> details = show_details ? new ArrayList<Map<String, Object>>() : null; int queued = 0; final List<Deferred<Boolean>> deferreds = synchronous ? new ArrayList<Deferred<Boolean>>(dps.size()) : null; if (tsdb.getConfig().enable_header_tag()) { if (LOG.isDebugEnabled()) { LOG.debug("Looking for tag header " + tsdb.getConfig().get_name_header_tag()); } final String header_tag_value = query.getHeaderValue( tsdb.getConfig().get_name_header_tag()) ; if (header_tag_value != null) { if (LOG.isDebugEnabled()) { LOG.debug(" header found with value:" + header_tag_value); } Tags.parse(query_tags, header_tag_value); } else if (LOG.isDebugEnabled()) { LOG.debug(" no such header in request"); } } for (final IncomingDataPoint dp : dps) { final DataPointType type; if (dp instanceof RollUpDataPoint) { type = DataPointType.ROLLUP; rollup_dps.incrementAndGet(); } else if (dp instanceof HistogramPojo) { type = DataPointType.HISTOGRAM; raw_histograms.incrementAndGet(); } else { type = DataPointType.PUT; raw_dps.incrementAndGet(); } /* Error back callback to handle storage failures */ final class PutErrback implements Callback<Boolean, Exception> { public Boolean call(final Exception arg) { if (arg instanceof PleaseThrottleException) { inflight_exceeded.incrementAndGet(); } else { hbase_errors.incrementAndGet(); } if (show_details) { details.add(getHttpDetails("Storage exception: " + arg.getMessage(), dp)); } // we handle the storage exceptions here so as to avoid creating yet // another callback object on every data point. handleStorageException(tsdb, dp, arg); return false; } public String toString() { return "HTTP Put exception"; } } final class SuccessCB implements Callback<Boolean, Object> { @Override public Boolean call(final Object obj) { switch (type) { case PUT: raw_stored.incrementAndGet(); break; case ROLLUP: rollup_stored.incrementAndGet(); break; case HISTOGRAM: raw_histograms_stored.incrementAndGet(); break; default: // don't care } return true; } } try { if (dp == null) { if (show_details) { details.add(this.getHttpDetails("Unexpected null datapoint encountered in set.", dp)); } LOG.warn("Datapoint null was encountered in set."); illegal_arguments.incrementAndGet(); continue; } if (!dp.validate(details)) { illegal_arguments.incrementAndGet(); continue; } // TODO - refactor the add calls someday or move some of this into the // actual data point class. final Deferred<Boolean> deferred; if (type == DataPointType.HISTOGRAM) { final HistogramPojo pojo = (HistogramPojo) dp; // validation and/or conversion before storage of histograms by // decoding then re-encoding. final Histogram hdp; if (Strings.isNullOrEmpty(dp.getValue())) { hdp = pojo.toSimpleHistogram(tsdb); } else { hdp = tsdb.histogramManager().decode( pojo.getId(), pojo.getBytes(), false); } deferred = tsdb.addHistogramPoint( pojo.getMetric(), pojo.getTimestamp(), tsdb.histogramManager().encode(hdp.getId(), hdp, true), pojo.getTags()) .addCallback(new SuccessCB()) .addErrback(new PutErrback()); } else { if (Tags.looksLikeInteger(dp.getValue())) { switch (type) { case ROLLUP: { final RollUpDataPoint rdp = (RollUpDataPoint)dp; deferred = tsdb.addAggregatePoint(rdp.getMetric(), rdp.getTimestamp(), Tags.parseLong(rdp.getValue()), dp.getTags(), rdp.getGroupByAggregator() != null, rdp.getInterval(), rdp.getAggregator(), rdp.getGroupByAggregator()) .addCallback(new SuccessCB()) .addErrback(new PutErrback()); break; } default: deferred = tsdb.addPoint(dp.getMetric(), dp.getTimestamp(), Tags.parseLong(dp.getValue()), dp.getTags()) .addCallback(new SuccessCB()) .addErrback(new PutErrback()); } } else { switch (type) { case ROLLUP: { final RollUpDataPoint rdp = (RollUpDataPoint)dp; deferred = tsdb.addAggregatePoint(rdp.getMetric(), rdp.getTimestamp(), (Tags.fitsInFloat(dp.getValue()) ? Float.parseFloat(dp.getValue()) : Double.parseDouble(dp.getValue())), dp.getTags(), rdp.getGroupByAggregator() != null, rdp.getInterval(), rdp.getAggregator(), rdp.getGroupByAggregator()) .addCallback(new SuccessCB()) .addErrback(new PutErrback()); break; } default: deferred = tsdb.addPoint(dp.getMetric(), dp.getTimestamp(), (Tags.fitsInFloat(dp.getValue()) ? Float.parseFloat(dp.getValue()) : Double.parseDouble(dp.getValue())), dp.getTags()) .addCallback(new SuccessCB()) .addErrback(new PutErrback()); } } } ++queued; if (synchronous) { deferreds.add(deferred); } } catch (NumberFormatException x) { if (show_details) { details.add(getHttpDetails("Unable to parse value to a number", dp)); } LOG.warn("Unable to parse value to a number: " + dp); invalid_values.incrementAndGet(); } catch (IllegalArgumentException iae) { if (show_details) { details.add(getHttpDetails(iae.getMessage(), dp)); } LOG.warn(iae.getMessage() + ": " + dp); illegal_arguments.incrementAndGet(); } catch (NoSuchUniqueName nsu) { if (show_details) { details.add(getHttpDetails("Unknown metric", dp)); } LOG.warn("Unknown metric: " + dp); unknown_metrics.incrementAndGet(); } catch (PleaseThrottleException x) { handleStorageException(tsdb, dp, x); if (show_details) { details.add(getHttpDetails("Please throttle", dp)); } inflight_exceeded.incrementAndGet(); } catch (TimeoutException tex) { handleStorageException(tsdb, dp, tex); if (show_details) { details.add(getHttpDetails("Timeout exception", dp)); } requests_timedout.incrementAndGet(); /*} catch (NoSuchUniqueNameInCache x) { handleStorageException(tsdb, dp, x); if (show_details) { details.add(getHttpDetails("Not cached yet", dp)); } */ } catch (RuntimeException e) { if (show_details) { details.add(getHttpDetails("Unexpected exception", dp)); } LOG.warn("Unexpected exception: " + dp); unknown_errors.incrementAndGet(); } } /** A timer task that will respond to the user with the number of timeouts * for synchronous writes. */ class PutTimeout implements TimerTask { final int queued; public PutTimeout(final int queued) { this.queued = queued; } @Override public void run(final Timeout timeout) throws Exception { if (sending_response.get()) { if (LOG.isDebugEnabled()) { LOG.debug("Put data point call " + query + " already responded successfully"); } return; } else { sending_response.set(true); } // figure out how many writes are outstanding int good_writes = 0; int failed_writes = 0; int timeouts = 0; for (int i = 0; i < deferreds.size(); i++) { try { if (deferreds.get(i).join(1)) { ++good_writes; } else { ++failed_writes; } } catch (TimeoutException te) { if (show_details) { details.add(getHttpDetails("Write timedout", dps.get(i))); } ++timeouts; } } writes_timedout.addAndGet(timeouts); final int failures = dps.size() - queued; if (!show_summary && !show_details) { query.sendReply(HttpResponseStatus.BAD_REQUEST, query.serializer().formatErrorV1( new BadRequestException(HttpResponseStatus.BAD_REQUEST, "The put call has timedout with " + good_writes + " successful writes, " + failed_writes + " failed writes and " + timeouts + " timed out writes.", "Please see the TSD logs or append \"details\" to the put request"))); } else { final HashMap<String, Object> summary = new HashMap<String, Object>(); summary.put("success", good_writes); summary.put("failed", failures + failed_writes); summary.put("timeouts", timeouts); if (show_details) { summary.put("errors", details); } query.sendReply(HttpResponseStatus.BAD_REQUEST, query.serializer().formatPutV1(summary)); } } } // now after everything has been sent we can schedule a timeout if so // the caller asked for a synchronous write. final Timeout timeout = sync_timeout > 0 ? tsdb.getTimer().newTimeout(new PutTimeout(queued), sync_timeout, TimeUnit.MILLISECONDS) : null; /** Serializes the response to the client */ class GroupCB implements Callback<Object, ArrayList<Boolean>> { final int queued; public GroupCB(final int queued) { this.queued = queued; } @Override public Object call(final ArrayList<Boolean> results) { if (sending_response.get()) { if (LOG.isDebugEnabled()) { LOG.debug("Put data point call " + query + " was marked as timedout"); } return null; } else { sending_response.set(true); if (timeout != null) { timeout.cancel(); } } int good_writes = 0; int failed_writes = 0; for (final boolean result : results) { if (result) { ++good_writes; } else { ++failed_writes; } } final int failures = dps.size() - queued; if (!show_summary && !show_details) { if (failures + failed_writes > 0) { query.sendReply(HttpResponseStatus.BAD_REQUEST, query.serializer().formatErrorV1( new BadRequestException(HttpResponseStatus.BAD_REQUEST, "One or more data points had errors", "Please see the TSD logs or append \"details\" to the put request"))); } else { query.sendReply(HttpResponseStatus.NO_CONTENT, "".getBytes()); } } else { final HashMap<String, Object> summary = new HashMap<String, Object>(); if (sync_timeout > 0) { summary.put("timeouts", 0); } summary.put("success", results.isEmpty() ? queued : good_writes); summary.put("failed", failures + failed_writes); if (show_details) { summary.put("errors", details); } if (failures > 0) { query.sendReply(HttpResponseStatus.BAD_REQUEST, query.serializer().formatPutV1(summary)); } else { query.sendReply(query.serializer().formatPutV1(summary)); } } return null; } @Override public String toString() { return "put data point serialization callback"; } } /** Catches any unexpected exceptions thrown in the callback chain */ class ErrCB implements Callback<Object, Exception> { @Override public Object call(final Exception e) throws Exception { if (sending_response.get()) { if (LOG.isDebugEnabled()) { LOG.debug("ERROR point call " + query + " was marked as timedout", e); } return null; } else { sending_response.set(true); if (timeout != null) { timeout.cancel(); } } LOG.error("Unexpected exception", e); throw new RuntimeException("Unexpected exception", e); } @Override public String toString() { return "put data point error callback"; } } if (synchronous) { Deferred.groupInOrder(deferreds) .addCallback(new GroupCB(queued)) .addErrback(new ErrCB()); } else { new GroupCB(queued).call(EMPTY_DEFERREDS); } } }
public class class_name { public <T extends IncomingDataPoint> void processDataPoint(final TSDB tsdb, final HttpQuery query, final List<T> dps) { if (dps.size() < 1) { throw new BadRequestException("No datapoints found in content"); } final HashMap<String, String> query_tags = new HashMap<String, String>(); final boolean show_details = query.hasQueryStringParam("details"); final boolean show_summary = query.hasQueryStringParam("summary"); final boolean synchronous = query.hasQueryStringParam("sync"); final int sync_timeout = query.hasQueryStringParam("sync_timeout") ? Integer.parseInt(query.getQueryStringParam("sync_timeout")) : 0; // this is used to coordinate timeouts final AtomicBoolean sending_response = new AtomicBoolean(); sending_response.set(false); final List<Map<String, Object>> details = show_details ? new ArrayList<Map<String, Object>>() : null; int queued = 0; final List<Deferred<Boolean>> deferreds = synchronous ? new ArrayList<Deferred<Boolean>>(dps.size()) : null; if (tsdb.getConfig().enable_header_tag()) { if (LOG.isDebugEnabled()) { LOG.debug("Looking for tag header " + tsdb.getConfig().get_name_header_tag()); // depends on control dependency: [if], data = [none] } final String header_tag_value = query.getHeaderValue( tsdb.getConfig().get_name_header_tag()) ; if (header_tag_value != null) { if (LOG.isDebugEnabled()) { LOG.debug(" header found with value:" + header_tag_value); // depends on control dependency: [if], data = [none] } Tags.parse(query_tags, header_tag_value); // depends on control dependency: [if], data = [none] } else if (LOG.isDebugEnabled()) { LOG.debug(" no such header in request"); // depends on control dependency: [if], data = [none] } } for (final IncomingDataPoint dp : dps) { final DataPointType type; if (dp instanceof RollUpDataPoint) { type = DataPointType.ROLLUP; // depends on control dependency: [if], data = [none] rollup_dps.incrementAndGet(); // depends on control dependency: [if], data = [none] } else if (dp instanceof HistogramPojo) { type = DataPointType.HISTOGRAM; // depends on control dependency: [if], data = [none] raw_histograms.incrementAndGet(); // depends on control dependency: [if], data = [none] } else { type = DataPointType.PUT; // depends on control dependency: [if], data = [none] raw_dps.incrementAndGet(); // depends on control dependency: [if], data = [none] } /* Error back callback to handle storage failures */ final class PutErrback implements Callback<Boolean, Exception> { public Boolean call(final Exception arg) { if (arg instanceof PleaseThrottleException) { inflight_exceeded.incrementAndGet(); // depends on control dependency: [if], data = [none] } else { hbase_errors.incrementAndGet(); // depends on control dependency: [if], data = [none] } if (show_details) { details.add(getHttpDetails("Storage exception: " + arg.getMessage(), dp)); // depends on control dependency: [if], data = [none] } // we handle the storage exceptions here so as to avoid creating yet // another callback object on every data point. handleStorageException(tsdb, dp, arg); return false; } public String toString() { return "HTTP Put exception"; } } final class SuccessCB implements Callback<Boolean, Object> { @Override public Boolean call(final Object obj) { switch (type) { case PUT: raw_stored.incrementAndGet(); break; case ROLLUP: rollup_stored.incrementAndGet(); break; case HISTOGRAM: raw_histograms_stored.incrementAndGet(); break; default: // don't care } return true; } } try { if (dp == null) { if (show_details) { details.add(this.getHttpDetails("Unexpected null datapoint encountered in set.", dp)); // depends on control dependency: [if], data = [none] } LOG.warn("Datapoint null was encountered in set."); // depends on control dependency: [if], data = [none] illegal_arguments.incrementAndGet(); // depends on control dependency: [if], data = [none] continue; } if (!dp.validate(details)) { illegal_arguments.incrementAndGet(); // depends on control dependency: [if], data = [none] continue; } // TODO - refactor the add calls someday or move some of this into the // actual data point class. final Deferred<Boolean> deferred; if (type == DataPointType.HISTOGRAM) { final HistogramPojo pojo = (HistogramPojo) dp; // validation and/or conversion before storage of histograms by // decoding then re-encoding. final Histogram hdp; if (Strings.isNullOrEmpty(dp.getValue())) { hdp = pojo.toSimpleHistogram(tsdb); // depends on control dependency: [if], data = [none] } else { hdp = tsdb.histogramManager().decode( pojo.getId(), pojo.getBytes(), false); // depends on control dependency: [if], data = [none] } deferred = tsdb.addHistogramPoint( pojo.getMetric(), pojo.getTimestamp(), tsdb.histogramManager().encode(hdp.getId(), hdp, true), pojo.getTags()) .addCallback(new SuccessCB()) .addErrback(new PutErrback()); // depends on control dependency: [if], data = [none] } else { if (Tags.looksLikeInteger(dp.getValue())) { switch (type) { case ROLLUP: { final RollUpDataPoint rdp = (RollUpDataPoint)dp; deferred = tsdb.addAggregatePoint(rdp.getMetric(), rdp.getTimestamp(), Tags.parseLong(rdp.getValue()), dp.getTags(), rdp.getGroupByAggregator() != null, rdp.getInterval(), rdp.getAggregator(), rdp.getGroupByAggregator()) .addCallback(new SuccessCB()) .addErrback(new PutErrback()); break; } default: deferred = tsdb.addPoint(dp.getMetric(), dp.getTimestamp(), Tags.parseLong(dp.getValue()), dp.getTags()) .addCallback(new SuccessCB()) .addErrback(new PutErrback()); } } else { // depends on control dependency: [try], data = [none] switch (type) { case ROLLUP: { final RollUpDataPoint rdp = (RollUpDataPoint)dp; deferred = tsdb.addAggregatePoint(rdp.getMetric(), rdp.getTimestamp(), (Tags.fitsInFloat(dp.getValue()) ? Float.parseFloat(dp.getValue()) : Double.parseDouble(dp.getValue())), dp.getTags(), rdp.getGroupByAggregator() != null, rdp.getInterval(), rdp.getAggregator(), rdp.getGroupByAggregator()) .addCallback(new SuccessCB()) .addErrback(new PutErrback()); break; } default: deferred = tsdb.addPoint(dp.getMetric(), dp.getTimestamp(), (Tags.fitsInFloat(dp.getValue()) ? Float.parseFloat(dp.getValue()) : Double.parseDouble(dp.getValue())), dp.getTags()) .addCallback(new SuccessCB()) .addErrback(new PutErrback()); } } } ++queued; if (synchronous) { deferreds.add(deferred); } } catch (NumberFormatException x) { if (show_details) { details.add(getHttpDetails("Unable to parse value to a number", dp)); // depends on control dependency: [if], data = [none] } LOG.warn("Unable to parse value to a number: " + dp); invalid_values.incrementAndGet(); } catch (IllegalArgumentException iae) { // depends on control dependency: [catch], data = [none] if (show_details) { details.add(getHttpDetails(iae.getMessage(), dp)); // depends on control dependency: [if], data = [none] } LOG.warn(iae.getMessage() + ": " + dp); illegal_arguments.incrementAndGet(); } catch (NoSuchUniqueName nsu) { // depends on control dependency: [catch], data = [none] if (show_details) { details.add(getHttpDetails("Unknown metric", dp)); // depends on control dependency: [if], data = [none] } LOG.warn("Unknown metric: " + dp); unknown_metrics.incrementAndGet(); } catch (PleaseThrottleException x) { // depends on control dependency: [catch], data = [none] handleStorageException(tsdb, dp, x); if (show_details) { details.add(getHttpDetails("Please throttle", dp)); // depends on control dependency: [if], data = [none] } inflight_exceeded.incrementAndGet(); } catch (TimeoutException tex) { // depends on control dependency: [catch], data = [none] handleStorageException(tsdb, dp, tex); if (show_details) { details.add(getHttpDetails("Timeout exception", dp)); // depends on control dependency: [if], data = [none] } requests_timedout.incrementAndGet(); /*} catch (NoSuchUniqueNameInCache x) { handleStorageException(tsdb, dp, x); if (show_details) { details.add(getHttpDetails("Not cached yet", dp)); } */ } catch (RuntimeException e) { // depends on control dependency: [catch], data = [none] if (show_details) { details.add(getHttpDetails("Unexpected exception", dp)); // depends on control dependency: [if], data = [none] } LOG.warn("Unexpected exception: " + dp); unknown_errors.incrementAndGet(); } // depends on control dependency: [catch], data = [none] } /** A timer task that will respond to the user with the number of timeouts * for synchronous writes. */ class PutTimeout implements TimerTask { final int queued; public PutTimeout(final int queued) { this.queued = queued; } @Override public void run(final Timeout timeout) throws Exception { if (sending_response.get()) { if (LOG.isDebugEnabled()) { LOG.debug("Put data point call " + query + " already responded successfully"); } return; } else { sending_response.set(true); } // figure out how many writes are outstanding int good_writes = 0; int failed_writes = 0; int timeouts = 0; for (int i = 0; i < deferreds.size(); i++) { try { if (deferreds.get(i).join(1)) { ++good_writes; // depends on control dependency: [if], data = [none] } else { ++failed_writes; // depends on control dependency: [if], data = [none] } } catch (TimeoutException te) { if (show_details) { details.add(getHttpDetails("Write timedout", dps.get(i))); // depends on control dependency: [if], data = [none] } ++timeouts; } // depends on control dependency: [catch], data = [none] } writes_timedout.addAndGet(timeouts); final int failures = dps.size() - queued; if (!show_summary && !show_details) { query.sendReply(HttpResponseStatus.BAD_REQUEST, query.serializer().formatErrorV1( new BadRequestException(HttpResponseStatus.BAD_REQUEST, "The put call has timedout with " + good_writes + " successful writes, " + failed_writes + " failed writes and " + timeouts + " timed out writes.", "Please see the TSD logs or append \"details\" to the put request"))); // depends on control dependency: [if], data = [none] } else { final HashMap<String, Object> summary = new HashMap<String, Object>(); summary.put("success", good_writes); // depends on control dependency: [if], data = [none] summary.put("failed", failures + failed_writes); // depends on control dependency: [if], data = [none] summary.put("timeouts", timeouts); // depends on control dependency: [if], data = [none] if (show_details) { summary.put("errors", details); // depends on control dependency: [if], data = [none] } query.sendReply(HttpResponseStatus.BAD_REQUEST, query.serializer().formatPutV1(summary)); // depends on control dependency: [if], data = [none] } } } // now after everything has been sent we can schedule a timeout if so // the caller asked for a synchronous write. final Timeout timeout = sync_timeout > 0 ? tsdb.getTimer().newTimeout(new PutTimeout(queued), sync_timeout, TimeUnit.MILLISECONDS) : null; /** Serializes the response to the client */ class GroupCB implements Callback<Object, ArrayList<Boolean>> { final int queued; public GroupCB(final int queued) { this.queued = queued; } @Override public Object call(final ArrayList<Boolean> results) { if (sending_response.get()) { if (LOG.isDebugEnabled()) { LOG.debug("Put data point call " + query + " was marked as timedout"); // depends on control dependency: [if], data = [none] } return null; // depends on control dependency: [if], data = [none] } else { sending_response.set(true); // depends on control dependency: [if], data = [none] if (timeout != null) { timeout.cancel(); // depends on control dependency: [if], data = [none] } } int good_writes = 0; int failed_writes = 0; for (final boolean result : results) { if (result) { ++good_writes; // depends on control dependency: [if], data = [none] } else { ++failed_writes; // depends on control dependency: [if], data = [none] } } final int failures = dps.size() - queued; if (!show_summary && !show_details) { if (failures + failed_writes > 0) { query.sendReply(HttpResponseStatus.BAD_REQUEST, query.serializer().formatErrorV1( new BadRequestException(HttpResponseStatus.BAD_REQUEST, "One or more data points had errors", "Please see the TSD logs or append \"details\" to the put request"))); // depends on control dependency: [if], data = [none] } else { query.sendReply(HttpResponseStatus.NO_CONTENT, "".getBytes()); // depends on control dependency: [if], data = [none] } } else { final HashMap<String, Object> summary = new HashMap<String, Object>(); if (sync_timeout > 0) { summary.put("timeouts", 0); // depends on control dependency: [if], data = [0)] } summary.put("success", results.isEmpty() ? queued : good_writes); // depends on control dependency: [if], data = [none] summary.put("failed", failures + failed_writes); // depends on control dependency: [if], data = [none] if (show_details) { summary.put("errors", details); // depends on control dependency: [if], data = [none] } if (failures > 0) { query.sendReply(HttpResponseStatus.BAD_REQUEST, query.serializer().formatPutV1(summary)); // depends on control dependency: [if], data = [none] } else { query.sendReply(query.serializer().formatPutV1(summary)); // depends on control dependency: [if], data = [none] } } return null; } @Override public String toString() { return "put data point serialization callback"; } } /** Catches any unexpected exceptions thrown in the callback chain */ class ErrCB implements Callback<Object, Exception> { @Override public Object call(final Exception e) throws Exception { if (sending_response.get()) { if (LOG.isDebugEnabled()) { LOG.debug("ERROR point call " + query + " was marked as timedout", e); } return null; } else { sending_response.set(true); if (timeout != null) { timeout.cancel(); } } LOG.error("Unexpected exception", e); throw new RuntimeException("Unexpected exception", e); } @Override public String toString() { return "put data point error callback"; } } if (synchronous) { Deferred.groupInOrder(deferreds) .addCallback(new GroupCB(queued)) .addErrback(new ErrCB()); } else { new GroupCB(queued).call(EMPTY_DEFERREDS); } } }
public class class_name { private void initUrl() { if (null != this.clazz) { super.url = this.clazz.getResource(this.path); } else if (null != this.classLoader) { super.url = this.classLoader.getResource(this.path); } else { super.url = ClassLoader.getSystemResource(this.path); } if (null == super.url) { throw new NoResourceException("Resource of path [{}] not exist!", this.path); } } }
public class class_name { private void initUrl() { if (null != this.clazz) { super.url = this.clazz.getResource(this.path); // depends on control dependency: [if], data = [none] } else if (null != this.classLoader) { super.url = this.classLoader.getResource(this.path); // depends on control dependency: [if], data = [none] } else { super.url = ClassLoader.getSystemResource(this.path); // depends on control dependency: [if], data = [none] } if (null == super.url) { throw new NoResourceException("Resource of path [{}] not exist!", this.path); } } }
public class class_name { private void renderMarker(Marker marker, MarkerVector pos) { float angle = 0f; float unitsScale; statePush(); // Calculate vector angle if (marker.orient != null) { if (Float.isNaN(marker.orient)) // Indicates "auto" { if (pos.dx != 0 || pos.dy != 0) { angle = (float) Math.toDegrees( Math.atan2(pos.dy, pos.dx) ); } } else { angle = marker.orient; } } // Calculate units scale unitsScale = marker.markerUnitsAreUser ? 1f : state.style.strokeWidth.floatValue(dpi); // "Properties inherit into the <marker> element from its ancestors; properties do not // inherit from the element referencing the <marker> element." (sect 11.6.2) state = findInheritFromAncestorState(marker); Matrix m = new Matrix(); m.preTranslate(pos.x, pos.y); m.preRotate(angle); m.preScale(unitsScale, unitsScale); // Scale and/or translate the marker to fit in the marker viewPort float _refX = (marker.refX != null) ? marker.refX.floatValueX(this) : 0f; float _refY = (marker.refY != null) ? marker.refY.floatValueY(this) : 0f; float _markerWidth = (marker.markerWidth != null) ? marker.markerWidth.floatValueX(this) : 3f; float _markerHeight = (marker.markerHeight != null) ? marker.markerHeight.floatValueY(this) : 3f; if (marker.viewBox != null) { // We now do a simplified version of calculateViewBoxTransform(). For now we will // ignore the alignment setting because refX and refY have to be aligned with the // marker position, and alignment would complicate the calculations. float xScale, yScale; xScale = _markerWidth / marker.viewBox.width; yScale = _markerHeight / marker.viewBox.height; // If we are keeping aspect ratio, then set both scales to the appropriate value depending on 'slice' PreserveAspectRatio positioning = (marker.preserveAspectRatio != null) ? marker.preserveAspectRatio : PreserveAspectRatio.LETTERBOX; if (!positioning.equals(PreserveAspectRatio.STRETCH)) { float aspectScale = (positioning.getScale() == PreserveAspectRatio.Scale.slice) ? Math.max(xScale, yScale) : Math.min(xScale, yScale); xScale = yScale = aspectScale; } //m.preTranslate(viewPort.minX, viewPort.minY); m.preTranslate(-_refX * xScale, -_refY * yScale); canvas.concat(m); // Now we need to take account of alignment setting, because it affects the // size and position of the clip rectangle. float imageW = marker.viewBox.width * xScale; float imageH = marker.viewBox.height * yScale; float xOffset = 0f; float yOffset = 0f; switch (positioning.getAlignment()) { case xMidYMin: case xMidYMid: case xMidYMax: xOffset -= (_markerWidth - imageW) / 2; break; case xMaxYMin: case xMaxYMid: case xMaxYMax: xOffset -= (_markerWidth - imageW); break; default: // nothing to do break; } // Determine final Y position switch (positioning.getAlignment()) { case xMinYMid: case xMidYMid: case xMaxYMid: yOffset -= (_markerHeight - imageH) / 2; break; case xMinYMax: case xMidYMax: case xMaxYMax: yOffset -= (_markerHeight - imageH); break; default: // nothing to do break; } if (!state.style.overflow) { setClipRect(xOffset, yOffset, _markerWidth, _markerHeight); } m.reset(); m.preScale(xScale, yScale); canvas.concat(m); } else { // No viewBox provided m.preTranslate(-_refX, -_refY); canvas.concat(m); if (!state.style.overflow) { setClipRect(0, 0, _markerWidth, _markerHeight); } } boolean compositing = pushLayer(); renderChildren(marker, false); if (compositing) popLayer(marker); statePop(); } }
public class class_name { private void renderMarker(Marker marker, MarkerVector pos) { float angle = 0f; float unitsScale; statePush(); // Calculate vector angle if (marker.orient != null) { if (Float.isNaN(marker.orient)) // Indicates "auto" { if (pos.dx != 0 || pos.dy != 0) { angle = (float) Math.toDegrees( Math.atan2(pos.dy, pos.dx) ); // depends on control dependency: [if], data = [none] } } else { angle = marker.orient; // depends on control dependency: [if], data = [none] } } // Calculate units scale unitsScale = marker.markerUnitsAreUser ? 1f : state.style.strokeWidth.floatValue(dpi); // "Properties inherit into the <marker> element from its ancestors; properties do not // inherit from the element referencing the <marker> element." (sect 11.6.2) state = findInheritFromAncestorState(marker); Matrix m = new Matrix(); m.preTranslate(pos.x, pos.y); m.preRotate(angle); m.preScale(unitsScale, unitsScale); // Scale and/or translate the marker to fit in the marker viewPort float _refX = (marker.refX != null) ? marker.refX.floatValueX(this) : 0f; float _refY = (marker.refY != null) ? marker.refY.floatValueY(this) : 0f; float _markerWidth = (marker.markerWidth != null) ? marker.markerWidth.floatValueX(this) : 3f; float _markerHeight = (marker.markerHeight != null) ? marker.markerHeight.floatValueY(this) : 3f; if (marker.viewBox != null) { // We now do a simplified version of calculateViewBoxTransform(). For now we will // ignore the alignment setting because refX and refY have to be aligned with the // marker position, and alignment would complicate the calculations. float xScale, yScale; xScale = _markerWidth / marker.viewBox.width; // depends on control dependency: [if], data = [none] yScale = _markerHeight / marker.viewBox.height; // depends on control dependency: [if], data = [none] // If we are keeping aspect ratio, then set both scales to the appropriate value depending on 'slice' PreserveAspectRatio positioning = (marker.preserveAspectRatio != null) ? marker.preserveAspectRatio : PreserveAspectRatio.LETTERBOX; if (!positioning.equals(PreserveAspectRatio.STRETCH)) { float aspectScale = (positioning.getScale() == PreserveAspectRatio.Scale.slice) ? Math.max(xScale, yScale) : Math.min(xScale, yScale); xScale = yScale = aspectScale; // depends on control dependency: [if], data = [none] } //m.preTranslate(viewPort.minX, viewPort.minY); m.preTranslate(-_refX * xScale, -_refY * yScale); // depends on control dependency: [if], data = [none] canvas.concat(m); // depends on control dependency: [if], data = [none] // Now we need to take account of alignment setting, because it affects the // size and position of the clip rectangle. float imageW = marker.viewBox.width * xScale; float imageH = marker.viewBox.height * yScale; float xOffset = 0f; float yOffset = 0f; switch (positioning.getAlignment()) { case xMidYMin: case xMidYMid: case xMidYMax: xOffset -= (_markerWidth - imageW) / 2; break; case xMaxYMin: case xMaxYMid: case xMaxYMax: xOffset -= (_markerWidth - imageW); break; default: // nothing to do break; } // Determine final Y position switch (positioning.getAlignment()) { case xMinYMid: case xMidYMid: case xMaxYMid: yOffset -= (_markerHeight - imageH) / 2; break; case xMinYMax: case xMidYMax: case xMaxYMax: yOffset -= (_markerHeight - imageH); break; default: // nothing to do break; } if (!state.style.overflow) { setClipRect(xOffset, yOffset, _markerWidth, _markerHeight); } m.reset(); m.preScale(xScale, yScale); canvas.concat(m); } else { // No viewBox provided m.preTranslate(-_refX, -_refY); canvas.concat(m); if (!state.style.overflow) { setClipRect(0, 0, _markerWidth, _markerHeight); } } boolean compositing = pushLayer(); renderChildren(marker, false); if (compositing) popLayer(marker); statePop(); } }
public class class_name { private void primeCache() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { for (Map.Entry<DeckReference, TrackMetadata> entry : MetadataFinder.getInstance().getLoadedTracks().entrySet()) { if (entry.getKey().hotCue == 0) { // The track is currently loaded in a main player deck handleUpdate(new TrackMetadataUpdate(entry.getKey().player, entry.getValue())); } } } }); } }
public class class_name { private void primeCache() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { for (Map.Entry<DeckReference, TrackMetadata> entry : MetadataFinder.getInstance().getLoadedTracks().entrySet()) { if (entry.getKey().hotCue == 0) { // The track is currently loaded in a main player deck handleUpdate(new TrackMetadataUpdate(entry.getKey().player, entry.getValue())); // depends on control dependency: [if], data = [none] } } } }); } }
public class class_name { public static Object instantiateWrapperArray(Class<?> type, String[] values) { logger.entering(new Object[] { type, values }); validateParams(type, values); boolean condition = (isWrapperArray(type) || hasOneArgStringConstructor(type.getComponentType())); checkArgument(condition, type.getName() + " is neither awrapper type nor has a 1 arg String constructor defined."); Class<?> componentType = type.getComponentType(); Object arrayToReturn = Array.newInstance(componentType, values.length); for (int i = 0; i < values.length; i++) { try { Array.set(arrayToReturn, i, componentType.getConstructor(String.class).newInstance(values[i])); } catch (ArrayIndexOutOfBoundsException | IllegalArgumentException | InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new ReflectionException(e); } } logger.exiting(arrayToReturn); return arrayToReturn; } }
public class class_name { public static Object instantiateWrapperArray(Class<?> type, String[] values) { logger.entering(new Object[] { type, values }); validateParams(type, values); boolean condition = (isWrapperArray(type) || hasOneArgStringConstructor(type.getComponentType())); checkArgument(condition, type.getName() + " is neither awrapper type nor has a 1 arg String constructor defined."); Class<?> componentType = type.getComponentType(); Object arrayToReturn = Array.newInstance(componentType, values.length); for (int i = 0; i < values.length; i++) { try { Array.set(arrayToReturn, i, componentType.getConstructor(String.class).newInstance(values[i])); // depends on control dependency: [try], data = [none] } catch (ArrayIndexOutOfBoundsException | IllegalArgumentException | InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new ReflectionException(e); } // depends on control dependency: [catch], data = [none] } logger.exiting(arrayToReturn); return arrayToReturn; } }
public class class_name { public EEnum getSTCFRGCOLOR() { if (stcfrgcolorEEnum == null) { stcfrgcolorEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(70); } return stcfrgcolorEEnum; } }
public class class_name { public EEnum getSTCFRGCOLOR() { if (stcfrgcolorEEnum == null) { stcfrgcolorEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(70); // depends on control dependency: [if], data = [none] } return stcfrgcolorEEnum; } }
public class class_name { public java.util.List<PlatformProgrammingLanguage> getProgrammingLanguages() { if (programmingLanguages == null) { programmingLanguages = new com.amazonaws.internal.SdkInternalList<PlatformProgrammingLanguage>(); } return programmingLanguages; } }
public class class_name { public java.util.List<PlatformProgrammingLanguage> getProgrammingLanguages() { if (programmingLanguages == null) { programmingLanguages = new com.amazonaws.internal.SdkInternalList<PlatformProgrammingLanguage>(); // depends on control dependency: [if], data = [none] } return programmingLanguages; } }
public class class_name { @Override protected void validate(List<TableInfo> tableInfos) { for (TableInfo tableInfo : tableInfos) { try { if (tableAPI.getTable(tableInfo.getTableName()) == null) { logger.error("No table found for " + tableInfo.getTableName()); throw new SchemaGenerationException("No table found for " + tableInfo.getTableName()); } } catch (FaultException e) { logger.error("Error while getting table " + tableInfo.getTableName() + ". Caused By: ", e); throw new SchemaGenerationException(e, "Error while getting table " + tableInfo.getTableName() + ". Caused By: "); } } } }
public class class_name { @Override protected void validate(List<TableInfo> tableInfos) { for (TableInfo tableInfo : tableInfos) { try { if (tableAPI.getTable(tableInfo.getTableName()) == null) { logger.error("No table found for " + tableInfo.getTableName()); // depends on control dependency: [if], data = [none] throw new SchemaGenerationException("No table found for " + tableInfo.getTableName()); } } catch (FaultException e) { logger.error("Error while getting table " + tableInfo.getTableName() + ". Caused By: ", e); throw new SchemaGenerationException(e, "Error while getting table " + tableInfo.getTableName() + ". Caused By: "); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { @CanIgnoreReturnValue @GwtIncompatible // TODO public static <V> V getUninterruptibly(Future<V> future, long timeout, TimeUnit unit) throws ExecutionException, TimeoutException { boolean interrupted = false; try { long remainingNanos = unit.toNanos(timeout); long end = System.nanoTime() + remainingNanos; while (true) { try { // Future treats negative timeouts just like zero. return future.get(remainingNanos, NANOSECONDS); } catch (InterruptedException e) { interrupted = true; remainingNanos = end - System.nanoTime(); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } }
public class class_name { @CanIgnoreReturnValue @GwtIncompatible // TODO public static <V> V getUninterruptibly(Future<V> future, long timeout, TimeUnit unit) throws ExecutionException, TimeoutException { boolean interrupted = false; try { long remainingNanos = unit.toNanos(timeout); long end = System.nanoTime() + remainingNanos; while (true) { try { // Future treats negative timeouts just like zero. return future.get(remainingNanos, NANOSECONDS); // depends on control dependency: [try], data = [none] } catch (InterruptedException e) { interrupted = true; remainingNanos = end - System.nanoTime(); } // depends on control dependency: [catch], data = [none] } } finally { if (interrupted) { Thread.currentThread().interrupt(); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public String cql() { if (sb == null) { throw new AbacusException("This CQLBuilder has been closed after cql() was called previously"); } init(true); String cql = null; try { cql = sb.toString(); } finally { Objectory.recycle(sb); sb = null; activeStringBuilderCounter.decrementAndGet(); } if (logger.isDebugEnabled()) { logger.debug(cql); } return cql; } }
public class class_name { public String cql() { if (sb == null) { throw new AbacusException("This CQLBuilder has been closed after cql() was called previously"); } init(true); String cql = null; try { cql = sb.toString(); // depends on control dependency: [try], data = [none] } finally { Objectory.recycle(sb); sb = null; activeStringBuilderCounter.decrementAndGet(); } if (logger.isDebugEnabled()) { logger.debug(cql); // depends on control dependency: [if], data = [none] } return cql; } }
public class class_name { public static StoreFactory init() { try { StoreFactory theStoreFactory = (StoreFactory) EPackage.Registry.INSTANCE.getEFactory(StorePackage.eNS_URI); if (theStoreFactory != null) { return theStoreFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new StoreFactoryImpl(); } }
public class class_name { public static StoreFactory init() { try { StoreFactory theStoreFactory = (StoreFactory) EPackage.Registry.INSTANCE.getEFactory(StorePackage.eNS_URI); if (theStoreFactory != null) { return theStoreFactory; // depends on control dependency: [if], data = [none] } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } // depends on control dependency: [catch], data = [none] return new StoreFactoryImpl(); } }
public class class_name { private static Matrix readSVDLIBCsingularVector(File sigmaMatrixFile) throws IOException { BufferedReader br = new BufferedReader(new FileReader(sigmaMatrixFile)); int dimension = -1; int valsSeen = 0; Matrix m = null; for (String line = null; (line = br.readLine()) != null; ) { String[] vals = line.split("\\s+"); for (int i = 0; i < vals.length; ++i) { // the first value seen should be the number of singular values if (dimension == -1) { dimension = Integer.parseInt(vals[i]); m = new DiagonalMatrix(dimension); } else { m.set(valsSeen, valsSeen, Double.parseDouble(vals[i])); ++valsSeen; } } } return m; } }
public class class_name { private static Matrix readSVDLIBCsingularVector(File sigmaMatrixFile) throws IOException { BufferedReader br = new BufferedReader(new FileReader(sigmaMatrixFile)); int dimension = -1; int valsSeen = 0; Matrix m = null; for (String line = null; (line = br.readLine()) != null; ) { String[] vals = line.split("\\s+"); for (int i = 0; i < vals.length; ++i) { // the first value seen should be the number of singular values if (dimension == -1) { dimension = Integer.parseInt(vals[i]); // depends on control dependency: [if], data = [none] m = new DiagonalMatrix(dimension); // depends on control dependency: [if], data = [(dimension] } else { m.set(valsSeen, valsSeen, Double.parseDouble(vals[i])); // depends on control dependency: [if], data = [none] ++valsSeen; // depends on control dependency: [if], data = [none] } } } return m; } }
public class class_name { public synchronized void addListener(CollectionProxyListener listener) { if (_listeners == null) { _listeners = new ArrayList(); } // to avoid multi-add of same listener, do check if(!_listeners.contains(listener)) { _listeners.add(listener); } } }
public class class_name { public synchronized void addListener(CollectionProxyListener listener) { if (_listeners == null) { _listeners = new ArrayList(); // depends on control dependency: [if], data = [none] } // to avoid multi-add of same listener, do check if(!_listeners.contains(listener)) { _listeners.add(listener); // depends on control dependency: [if], data = [none] } } }
public class class_name { protected void unsetFileMonitorRegistration() { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(this, tc, "unsetFileMonitorRegistration"); } if (keyStoreFileMonitorRegistration != null) { keyStoreFileMonitorRegistration.unregister(); keyStoreFileMonitorRegistration = null; } } }
public class class_name { protected void unsetFileMonitorRegistration() { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(this, tc, "unsetFileMonitorRegistration"); // depends on control dependency: [if], data = [none] } if (keyStoreFileMonitorRegistration != null) { keyStoreFileMonitorRegistration.unregister(); // depends on control dependency: [if], data = [none] keyStoreFileMonitorRegistration = null; // depends on control dependency: [if], data = [none] } } }
public class class_name { private static String formatTimeLive(long timeLive) { String timeString = "ms"; timeString = (timeLive % 1000) + timeString; timeLive = timeLive / 1000; if(timeLive > 0) { timeString = (timeLive % 60) + "s" + timeString; timeLive = timeLive / 60; if(timeLive > 0) { timeString = (timeLive % 60) + "m" + timeString; timeLive = timeLive / 60; if(timeLive > 0) { timeString = (timeLive % 24) + "h" + timeString; timeLive = timeLive / 24; if(timeLive > 0) { timeString = (timeLive) + "d" + timeString; } } } } return timeString; } }
public class class_name { private static String formatTimeLive(long timeLive) { String timeString = "ms"; timeString = (timeLive % 1000) + timeString; timeLive = timeLive / 1000; if(timeLive > 0) { timeString = (timeLive % 60) + "s" + timeString; // depends on control dependency: [if], data = [(timeLive] timeLive = timeLive / 60; // depends on control dependency: [if], data = [none] if(timeLive > 0) { timeString = (timeLive % 60) + "m" + timeString; // depends on control dependency: [if], data = [(timeLive] timeLive = timeLive / 60; // depends on control dependency: [if], data = [none] if(timeLive > 0) { timeString = (timeLive % 24) + "h" + timeString; // depends on control dependency: [if], data = [(timeLive] timeLive = timeLive / 24; // depends on control dependency: [if], data = [none] if(timeLive > 0) { timeString = (timeLive) + "d" + timeString; // depends on control dependency: [if], data = [(timeLive] } } } } return timeString; } }
public class class_name { @Pure @SuppressWarnings("checkstyle:nestedifdepth") List<AStarNode<ST, PT>> findPath(AStarNode<ST, PT> startPoint, PT endPoint) { final CloseComparator<ST, PT> cComparator = new CloseComparator<>(); final OpenComparator<ST, PT> oComparatorWithoutRef = new OpenComparator<>(); final List<AStarNode<ST, PT>> openList = new ArrayList<>(); final List<AStarNode<ST, PT>> closeList = new ArrayList<>(); openList.add(startPoint); fireNodeOpened(startPoint, openList); int idx; AStarNode<ST, PT> candidate; AStarNode<ST, PT> ocandidate; AStarNode<ST, PT> reachableCandidate; AStarNode<ST, PT> reachedCandidate; PT reachableNode; PT node; double gCost; double h1; boolean foundTarget = false; while (!foundTarget && !openList.isEmpty()) { ocandidate = openList.remove(0); fireNodeConsumed(ocandidate, openList); candidate = translateCandidate(endPoint, ocandidate); foundTarget = candidate == null; if (!foundTarget) { assert candidate != null; node = candidate.getGraphPoint(); // Update the nodes that are reachable from the current candidate. for (final ST segment : candidate.getGraphSegments()) { reachableNode = segment.getOtherSidePoint(node); if (reachableNode != null && !reachableNode.equals(node)) { gCost = candidate.getCost() + computeCostFor(node) + computeCostFor(segment); h1 = estimate(reachableNode, endPoint); reachableCandidate = newAStarNode(reachableNode, gCost, h1, segment); // Reopen node if better cost idx = (isClosedNodeReopeningEnabled()) ? ListUtil.indexOf(closeList, cComparator, reachableCandidate) : -1; if (idx >= 0) { reachedCandidate = closeList.get(idx); if (gCost < reachedCandidate.getCost()) { closeList.remove(idx); final AStarNode<ST, PT> nn = node( reachableNode, gCost, h1, segment); ListUtil.add( openList, oComparatorWithoutRef, nn, true, false); fireNodeOpened(nn, openList); } } else { idx = openList.indexOf(reachableCandidate); if (idx >= 0) { // Rearrange open list if better cost reachedCandidate = openList.get(idx); if ((gCost + h1) < reachedCandidate.getPathCost()) { openList.remove(idx); final AStarNode<ST, PT> nn = node( reachableNode, gCost, h1, segment); ListUtil.add(openList, oComparatorWithoutRef, nn, true, false); fireNodeReopened(nn, openList); } } else { // Node was neither treated nor seen, add it final AStarNode<ST, PT> nn = node( reachableNode, gCost, h1, segment); ListUtil.add(openList, oComparatorWithoutRef, nn, true, false); fireNodeOpened(nn, openList); } } } } } // Refresh the close list idx = ListUtil.add(closeList, cComparator, ocandidate, false, true); fireNodeClosed(ocandidate, closeList); assert idx >= 0; } return closeList; } }
public class class_name { @Pure @SuppressWarnings("checkstyle:nestedifdepth") List<AStarNode<ST, PT>> findPath(AStarNode<ST, PT> startPoint, PT endPoint) { final CloseComparator<ST, PT> cComparator = new CloseComparator<>(); final OpenComparator<ST, PT> oComparatorWithoutRef = new OpenComparator<>(); final List<AStarNode<ST, PT>> openList = new ArrayList<>(); final List<AStarNode<ST, PT>> closeList = new ArrayList<>(); openList.add(startPoint); fireNodeOpened(startPoint, openList); int idx; AStarNode<ST, PT> candidate; AStarNode<ST, PT> ocandidate; AStarNode<ST, PT> reachableCandidate; AStarNode<ST, PT> reachedCandidate; PT reachableNode; PT node; double gCost; double h1; boolean foundTarget = false; while (!foundTarget && !openList.isEmpty()) { ocandidate = openList.remove(0); // depends on control dependency: [while], data = [none] fireNodeConsumed(ocandidate, openList); // depends on control dependency: [while], data = [none] candidate = translateCandidate(endPoint, ocandidate); // depends on control dependency: [while], data = [none] foundTarget = candidate == null; // depends on control dependency: [while], data = [none] if (!foundTarget) { assert candidate != null; node = candidate.getGraphPoint(); // depends on control dependency: [if], data = [none] // Update the nodes that are reachable from the current candidate. for (final ST segment : candidate.getGraphSegments()) { reachableNode = segment.getOtherSidePoint(node); // depends on control dependency: [for], data = [segment] if (reachableNode != null && !reachableNode.equals(node)) { gCost = candidate.getCost() + computeCostFor(node) + computeCostFor(segment); // depends on control dependency: [if], data = [none] h1 = estimate(reachableNode, endPoint); // depends on control dependency: [if], data = [(reachableNode] reachableCandidate = newAStarNode(reachableNode, gCost, h1, segment); // depends on control dependency: [if], data = [(reachableNode] // Reopen node if better cost idx = (isClosedNodeReopeningEnabled()) ? ListUtil.indexOf(closeList, cComparator, reachableCandidate) : -1; // depends on control dependency: [if], data = [none] if (idx >= 0) { reachedCandidate = closeList.get(idx); // depends on control dependency: [if], data = [(idx] if (gCost < reachedCandidate.getCost()) { closeList.remove(idx); // depends on control dependency: [if], data = [none] final AStarNode<ST, PT> nn = node( reachableNode, gCost, h1, segment); ListUtil.add( openList, oComparatorWithoutRef, nn, true, false); // depends on control dependency: [if], data = [none] fireNodeOpened(nn, openList); // depends on control dependency: [if], data = [none] } } else { idx = openList.indexOf(reachableCandidate); // depends on control dependency: [if], data = [none] if (idx >= 0) { // Rearrange open list if better cost reachedCandidate = openList.get(idx); // depends on control dependency: [if], data = [(idx] if ((gCost + h1) < reachedCandidate.getPathCost()) { openList.remove(idx); // depends on control dependency: [if], data = [none] final AStarNode<ST, PT> nn = node( reachableNode, gCost, h1, segment); ListUtil.add(openList, oComparatorWithoutRef, nn, true, false); // depends on control dependency: [if], data = [none] fireNodeReopened(nn, openList); // depends on control dependency: [if], data = [none] } } else { // Node was neither treated nor seen, add it final AStarNode<ST, PT> nn = node( reachableNode, gCost, h1, segment); ListUtil.add(openList, oComparatorWithoutRef, nn, true, false); // depends on control dependency: [if], data = [none] fireNodeOpened(nn, openList); // depends on control dependency: [if], data = [none] } } } } } // Refresh the close list idx = ListUtil.add(closeList, cComparator, ocandidate, false, true); // depends on control dependency: [while], data = [none] fireNodeClosed(ocandidate, closeList); // depends on control dependency: [while], data = [none] assert idx >= 0; } return closeList; } }
public class class_name { private RhinoScriptBuilder initScriptBuilder() { try { RhinoScriptBuilder builder = null; if (scope == null) { final InputStream initStream = LessCss.class.getResourceAsStream(SCRIPT_INIT); builder = RhinoScriptBuilder.newClientSideAwareChain().evaluateChain(initStream, SCRIPT_INIT).evaluateChain( getScriptAsStream(), DEFAULT_LESS_JS); scope = builder.getScope(); } else { builder = RhinoScriptBuilder.newChain(scope); } return builder; } catch (final IOException ex) { throw new IllegalStateException("Failed reading javascript less.js", ex); } catch (final Exception e) { LOG.error("Processing error:" + e.getMessage(), e); throw new WroRuntimeException("Processing error", e); } } }
public class class_name { private RhinoScriptBuilder initScriptBuilder() { try { RhinoScriptBuilder builder = null; if (scope == null) { final InputStream initStream = LessCss.class.getResourceAsStream(SCRIPT_INIT); builder = RhinoScriptBuilder.newClientSideAwareChain().evaluateChain(initStream, SCRIPT_INIT).evaluateChain( getScriptAsStream(), DEFAULT_LESS_JS); // depends on control dependency: [if], data = [none] scope = builder.getScope(); // depends on control dependency: [if], data = [none] } else { builder = RhinoScriptBuilder.newChain(scope); // depends on control dependency: [if], data = [(scope] } return builder; // depends on control dependency: [try], data = [none] } catch (final IOException ex) { throw new IllegalStateException("Failed reading javascript less.js", ex); } catch (final Exception e) { LOG.error("Processing error:" + e.getMessage(), e); throw new WroRuntimeException("Processing error", e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @SuppressWarnings("unchecked") private void processExistingStaticInitializer(ClassTraceInfo info) { List<MethodNode> clinitMethods = getMethods("<clinit>", info.classNode.methods); MethodNode staticInitializer = clinitMethods.isEmpty() ? null : clinitMethods.get(0); if (staticInitializer == null) { return; } if (isMethodAlreadyInjectedAnnotationPresent(staticInitializer)) { return; } Iterator<? extends AbstractInsnNode> instructionIterator = staticInitializer.instructions.iterator(); while (instructionIterator.hasNext()) { AbstractInsnNode insnNode = instructionIterator.next(); // Determine if a Logger/TraceComponent field is being initialized. if (insnNode.getType() == AbstractInsnNode.FIELD_INSN) { FieldInsnNode fieldInsn = (FieldInsnNode) insnNode; if (fieldInsn.getOpcode() == Opcodes.PUTSTATIC) { if (info.libertyTraceComponentFieldNode != null && fieldInsn.name.equals(info.libertyTraceComponentFieldNode.name)) { info.libertyTraceComponentFieldAlreadyInitialized = true; } if (info.websphereTraceComponentFieldNode != null && fieldInsn.name.equals(info.websphereTraceComponentFieldNode.name)) { info.websphereTraceComponentFieldAlreadyInitialized = true; } if (info.loggerFieldNode != null && fieldInsn.name.equals(info.loggerFieldNode.name)) { info.loggerFieldAlreadyInitialized = true; } } } } } }
public class class_name { @SuppressWarnings("unchecked") private void processExistingStaticInitializer(ClassTraceInfo info) { List<MethodNode> clinitMethods = getMethods("<clinit>", info.classNode.methods); MethodNode staticInitializer = clinitMethods.isEmpty() ? null : clinitMethods.get(0); if (staticInitializer == null) { return; // depends on control dependency: [if], data = [none] } if (isMethodAlreadyInjectedAnnotationPresent(staticInitializer)) { return; // depends on control dependency: [if], data = [none] } Iterator<? extends AbstractInsnNode> instructionIterator = staticInitializer.instructions.iterator(); while (instructionIterator.hasNext()) { AbstractInsnNode insnNode = instructionIterator.next(); // Determine if a Logger/TraceComponent field is being initialized. if (insnNode.getType() == AbstractInsnNode.FIELD_INSN) { FieldInsnNode fieldInsn = (FieldInsnNode) insnNode; if (fieldInsn.getOpcode() == Opcodes.PUTSTATIC) { if (info.libertyTraceComponentFieldNode != null && fieldInsn.name.equals(info.libertyTraceComponentFieldNode.name)) { info.libertyTraceComponentFieldAlreadyInitialized = true; // depends on control dependency: [if], data = [none] } if (info.websphereTraceComponentFieldNode != null && fieldInsn.name.equals(info.websphereTraceComponentFieldNode.name)) { info.websphereTraceComponentFieldAlreadyInitialized = true; // depends on control dependency: [if], data = [none] } if (info.loggerFieldNode != null && fieldInsn.name.equals(info.loggerFieldNode.name)) { info.loggerFieldAlreadyInitialized = true; // depends on control dependency: [if], data = [none] } } } } } }
public class class_name { @Override public void saveContext(SecurityContext context, PortletRequestResponseHolder requestResponseHolder) { final Authentication authentication = context.getAuthentication(); final PortletRequest request = requestResponseHolder.getRequest(); PortletSession portletSession = request.getPortletSession(false); // See SEC-776 if (authentication == null || authenticationTrustResolver.isAnonymous(authentication)) { if (logger.isDebugEnabled()) { logger.debug("SecurityContext is empty or contents are anonymous - context will not be stored in PortletSession."); } if (portletSession != null) { // SEC-1587 A non-anonymous context may still be in the session portletSession.removeAttribute(springSecurityContextKey, this.sessionScope); } return; } if (portletSession == null) { portletSession = createNewSessionIfAllowed(context, requestResponseHolder); } // If PortletSession exists, store current SecurityContext but only if it has // actually changed in this thread (see SEC-37, SEC-1307, SEC-1528) if (portletSession != null) { // We may have a new session, so check also whether the context attribute is set SEC-1561 if (contextChanged(context, requestResponseHolder) || portletSession.getAttribute(springSecurityContextKey, this.sessionScope) == null) { portletSession.setAttribute(springSecurityContextKey, context, this.sessionScope); if (logger.isDebugEnabled()) { logger.debug("SecurityContext stored to PortletSession: '" + context + "'"); } } } } }
public class class_name { @Override public void saveContext(SecurityContext context, PortletRequestResponseHolder requestResponseHolder) { final Authentication authentication = context.getAuthentication(); final PortletRequest request = requestResponseHolder.getRequest(); PortletSession portletSession = request.getPortletSession(false); // See SEC-776 if (authentication == null || authenticationTrustResolver.isAnonymous(authentication)) { if (logger.isDebugEnabled()) { logger.debug("SecurityContext is empty or contents are anonymous - context will not be stored in PortletSession."); // depends on control dependency: [if], data = [none] } if (portletSession != null) { // SEC-1587 A non-anonymous context may still be in the session portletSession.removeAttribute(springSecurityContextKey, this.sessionScope); // depends on control dependency: [if], data = [none] } return; // depends on control dependency: [if], data = [none] } if (portletSession == null) { portletSession = createNewSessionIfAllowed(context, requestResponseHolder); // depends on control dependency: [if], data = [none] } // If PortletSession exists, store current SecurityContext but only if it has // actually changed in this thread (see SEC-37, SEC-1307, SEC-1528) if (portletSession != null) { // We may have a new session, so check also whether the context attribute is set SEC-1561 if (contextChanged(context, requestResponseHolder) || portletSession.getAttribute(springSecurityContextKey, this.sessionScope) == null) { portletSession.setAttribute(springSecurityContextKey, context, this.sessionScope); // depends on control dependency: [if], data = [none] if (logger.isDebugEnabled()) { logger.debug("SecurityContext stored to PortletSession: '" + context + "'"); // depends on control dependency: [if], data = [none] } } } } }
public class class_name { public final AbstractItem getItem() throws SevereMessageStoreException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getItem"); AbstractItem item = _getItemNoRestore(); synchronized (this) { if (isExpired()) { item = null; } else { // if we did not have a reference to the item then we try to recreate if (null == item) { try { item = _restoreItem(); } catch (SevereMessageStoreException e) { // No FFDC Code Needed. // PK54812 Ensure we dump a suitable FFDC containing all of the message store // information required in order to identify the rows etc. related to this entry. try { StringWriter stringWriter = new StringWriter(); FormattedWriter writer = new FormattedWriter(stringWriter); this.xmlWriteOn(writer); FFDCFilter.processException(e, "com.ibm.ws.sib.msgstore.cache.links.AbstractItemLink.getItem", "1:2252:1.241", this, new Object[] { stringWriter }); writer.close(); } catch (IOException ioe) { FFDCFilter.processException(ioe, "com.ibm.ws.sib.msgstore.cache.links.AbstractItemLink.getItem", "1:2257:1.241", this); } if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(this, tc, "RuntimeException caught restoring Item!", e); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "getItem"); throw e; } catch (RuntimeException re) { // No FFDC Code Needed. // PK54812 Ensure we dump a suitable FFDC containing all of the message store // information required in order to identify the rows etc. related to this entry. try { StringWriter stringWriter = new StringWriter(); FormattedWriter writer = new FormattedWriter(stringWriter); this.xmlWriteOn(writer); FFDCFilter.processException(re, "com.ibm.ws.sib.msgstore.cache.links.AbstractItemLink.getItem", "1:2274:1.241", this, new Object[] { stringWriter }); writer.close(); } catch (IOException ioe) { FFDCFilter.processException(ioe, "com.ibm.ws.sib.msgstore.cache.links.AbstractItemLink.getItem", "1:2279:1.241", this); } if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(this, tc, "RuntimeException caught restoring Item!", re); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "getItem"); throw re; } } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "getItem", item); } return item; } }
public class class_name { public final AbstractItem getItem() throws SevereMessageStoreException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getItem"); AbstractItem item = _getItemNoRestore(); synchronized (this) { if (isExpired()) { item = null; // depends on control dependency: [if], data = [none] } else { // if we did not have a reference to the item then we try to recreate if (null == item) { try { item = _restoreItem(); // depends on control dependency: [try], data = [none] } catch (SevereMessageStoreException e) { // No FFDC Code Needed. // PK54812 Ensure we dump a suitable FFDC containing all of the message store // information required in order to identify the rows etc. related to this entry. try { StringWriter stringWriter = new StringWriter(); FormattedWriter writer = new FormattedWriter(stringWriter); this.xmlWriteOn(writer); // depends on control dependency: [try], data = [none] FFDCFilter.processException(e, "com.ibm.ws.sib.msgstore.cache.links.AbstractItemLink.getItem", "1:2252:1.241", this, new Object[] { stringWriter }); // depends on control dependency: [try], data = [none] writer.close(); // depends on control dependency: [try], data = [none] } catch (IOException ioe) { FFDCFilter.processException(ioe, "com.ibm.ws.sib.msgstore.cache.links.AbstractItemLink.getItem", "1:2257:1.241", this); } // depends on control dependency: [catch], data = [none] if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(this, tc, "RuntimeException caught restoring Item!", e); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "getItem"); throw e; } catch (RuntimeException re) // depends on control dependency: [catch], data = [none] { // No FFDC Code Needed. // PK54812 Ensure we dump a suitable FFDC containing all of the message store // information required in order to identify the rows etc. related to this entry. try { StringWriter stringWriter = new StringWriter(); FormattedWriter writer = new FormattedWriter(stringWriter); this.xmlWriteOn(writer); // depends on control dependency: [try], data = [none] FFDCFilter.processException(re, "com.ibm.ws.sib.msgstore.cache.links.AbstractItemLink.getItem", "1:2274:1.241", this, new Object[] { stringWriter }); // depends on control dependency: [try], data = [none] writer.close(); // depends on control dependency: [try], data = [none] } catch (IOException ioe) { FFDCFilter.processException(ioe, "com.ibm.ws.sib.msgstore.cache.links.AbstractItemLink.getItem", "1:2279:1.241", this); } // depends on control dependency: [catch], data = [none] if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(this, tc, "RuntimeException caught restoring Item!", re); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "getItem"); throw re; } // depends on control dependency: [catch], data = [none] } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "getItem", item); } return item; } }
public class class_name { public int compareSwappedTo(IntDoublePair other) { int fdiff = Double.compare(this.second, other.second); if(fdiff != 0) { return fdiff; } return this.first - other.first; } }
public class class_name { public int compareSwappedTo(IntDoublePair other) { int fdiff = Double.compare(this.second, other.second); if(fdiff != 0) { return fdiff; // depends on control dependency: [if], data = [none] } return this.first - other.first; } }
public class class_name { public static <T> byte[] toByteArray(T message, Schema<T> schema, boolean numeric) { ArrayBufferOutput out = new ArrayBufferOutput(); try { writeTo(out, message, schema, numeric); } catch (IOException e) { throw new RuntimeException("Serializing to a byte array threw an IOException", e); } return out.toByteArray(); } }
public class class_name { public static <T> byte[] toByteArray(T message, Schema<T> schema, boolean numeric) { ArrayBufferOutput out = new ArrayBufferOutput(); try { writeTo(out, message, schema, numeric); // depends on control dependency: [try], data = [none] } catch (IOException e) { throw new RuntimeException("Serializing to a byte array threw an IOException", e); } // depends on control dependency: [catch], data = [none] return out.toByteArray(); } }
public class class_name { public ServletHolder mapPathToServlet(String pathSpec, String servletName) { ServletHolder holder =(ServletHolder)_nameMap.get(servletName); if (!pathSpec.startsWith("/") && !pathSpec.startsWith("*")) { log.warn("pathSpec should start with '/' or '*' : "+pathSpec); pathSpec="/"+pathSpec; } if (holder==null) throw new IllegalArgumentException("Unknown servlet: "+servletName); _servletMap.put(pathSpec,holder); return holder; } }
public class class_name { public ServletHolder mapPathToServlet(String pathSpec, String servletName) { ServletHolder holder =(ServletHolder)_nameMap.get(servletName); if (!pathSpec.startsWith("/") && !pathSpec.startsWith("*")) { log.warn("pathSpec should start with '/' or '*' : "+pathSpec); // depends on control dependency: [if], data = [none] pathSpec="/"+pathSpec; // depends on control dependency: [if], data = [none] } if (holder==null) throw new IllegalArgumentException("Unknown servlet: "+servletName); _servletMap.put(pathSpec,holder); return holder; } }
public class class_name { String getRandomAscii() { int count = 0; char[] randomAscii = new char[RANDOM_ASCII_BYTE_COUNT]; final Random random = SECURE_RANDOM.get(); while (count < RANDOM_ASCII_BYTE_COUNT) { int r = random.nextInt(128); char c = (char) r; // RFC 5802 § 5.1 specifies 'r:' to exclude the ',' character and to be only printable ASCII characters if (!isPrintableNonCommaAsciiChar(c)) { continue; } randomAscii[count++] = c; } return new String(randomAscii); } }
public class class_name { String getRandomAscii() { int count = 0; char[] randomAscii = new char[RANDOM_ASCII_BYTE_COUNT]; final Random random = SECURE_RANDOM.get(); while (count < RANDOM_ASCII_BYTE_COUNT) { int r = random.nextInt(128); char c = (char) r; // RFC 5802 § 5.1 specifies 'r:' to exclude the ',' character and to be only printable ASCII characters if (!isPrintableNonCommaAsciiChar(c)) { continue; } randomAscii[count++] = c; // depends on control dependency: [while], data = [none] } return new String(randomAscii); } }
public class class_name { @SuppressWarnings("unchecked") public <A extends Annotation> A getAnnotation(final Method method, final Class<A> annClas) throws AnnotationReadException { final Class<?> clazz = method.getDeclaringClass(); if(xmlInfo != null && xmlInfo.containsClassInfo(clazz.getName())) { final ClassInfo classInfo = xmlInfo.getClassInfo(clazz.getName()); if(classInfo.containsMethodInfo(method.getName())) { MethodInfo methodInfo = classInfo.getMethodInfo(method.getName()); if(methodInfo != null && methodInfo.containsAnnotationInfo(annClas.getName())) { AnnotationInfo annInfo = methodInfo.getAnnotationInfo(annClas.getName()); try { return (A)annotationBuilder.buildAnnotation(Class.forName(annInfo.getClassName()), annInfo); } catch (ClassNotFoundException e) { throw new AnnotationReadException(String.format("not found class '%s'", annInfo.getClassName()), e); } } } } return method.getAnnotation(annClas); } }
public class class_name { @SuppressWarnings("unchecked") public <A extends Annotation> A getAnnotation(final Method method, final Class<A> annClas) throws AnnotationReadException { final Class<?> clazz = method.getDeclaringClass(); if(xmlInfo != null && xmlInfo.containsClassInfo(clazz.getName())) { final ClassInfo classInfo = xmlInfo.getClassInfo(clazz.getName()); if(classInfo.containsMethodInfo(method.getName())) { MethodInfo methodInfo = classInfo.getMethodInfo(method.getName()); if(methodInfo != null && methodInfo.containsAnnotationInfo(annClas.getName())) { AnnotationInfo annInfo = methodInfo.getAnnotationInfo(annClas.getName()); try { return (A)annotationBuilder.buildAnnotation(Class.forName(annInfo.getClassName()), annInfo); // depends on control dependency: [try], data = [none] } catch (ClassNotFoundException e) { throw new AnnotationReadException(String.format("not found class '%s'", annInfo.getClassName()), e); } // depends on control dependency: [catch], data = [none] } } } return method.getAnnotation(annClas); } }
public class class_name { @SuppressWarnings("unchecked") public static <T> T unwrap(final T entity) { if (isProxy(entity)) { return (T) asProxy(entity).__unwrap(); } return entity; } }
public class class_name { @SuppressWarnings("unchecked") public static <T> T unwrap(final T entity) { if (isProxy(entity)) { return (T) asProxy(entity).__unwrap(); // depends on control dependency: [if], data = [none] } return entity; } }
public class class_name { public void setLine(Point2D[] points) { double[] pd = new double[points.length * 2]; for (int i = 0; i < points.length; i++) { Point2D p = points[i]; pd[i * 2] = p.getX(); pd[i * 2 + 1] = p.getY(); } setLine(pd); } }
public class class_name { public void setLine(Point2D[] points) { double[] pd = new double[points.length * 2]; for (int i = 0; i < points.length; i++) { Point2D p = points[i]; pd[i * 2] = p.getX(); // depends on control dependency: [for], data = [i] pd[i * 2 + 1] = p.getY(); // depends on control dependency: [for], data = [i] } setLine(pd); } }
public class class_name { public List<String> getRolesForUser(String name) { try { return model.model.get("g").get("g").rm.getRoles(name); } catch (Error e) { if (!e.getMessage().equals("error: name does not exist")) { throw e; } } return null; } }
public class class_name { public List<String> getRolesForUser(String name) { try { return model.model.get("g").get("g").rm.getRoles(name); // depends on control dependency: [try], data = [none] } catch (Error e) { if (!e.getMessage().equals("error: name does not exist")) { throw e; } } // depends on control dependency: [catch], data = [none] return null; } }
public class class_name { private final void appendNumericSegmentCEs(CharSequence digits) { int length = digits.length(); assert(1 <= length && length <= 254); assert(length == 1 || digits.charAt(0) != 0); long numericPrimary = data.numericPrimary; // Note: We use primary byte values 2..255: digits are not compressible. if(length <= 7) { // Very dense encoding for small numbers. int value = digits.charAt(0); for(int i = 1; i < length; ++i) { value = value * 10 + digits.charAt(i); } // Primary weight second byte values: // 74 byte values 2.. 75 for small numbers in two-byte primary weights. // 40 byte values 76..115 for medium numbers in three-byte primary weights. // 16 byte values 116..131 for large numbers in four-byte primary weights. // 124 byte values 132..255 for very large numbers with 4..127 digit pairs. int firstByte = 2; int numBytes = 74; if(value < numBytes) { // Two-byte primary for 0..73, good for day & month numbers etc. long primary = numericPrimary | ((firstByte + value) << 16); ceBuffer.append(Collation.makeCE(primary)); return; } value -= numBytes; firstByte += numBytes; numBytes = 40; if(value < numBytes * 254) { // Three-byte primary for 74..10233=74+40*254-1, good for year numbers and more. long primary = numericPrimary | ((firstByte + value / 254) << 16) | ((2 + value % 254) << 8); ceBuffer.append(Collation.makeCE(primary)); return; } value -= numBytes * 254; firstByte += numBytes; numBytes = 16; if(value < numBytes * 254 * 254) { // Four-byte primary for 10234..1042489=10234+16*254*254-1. long primary = numericPrimary | (2 + value % 254); value /= 254; primary |= (2 + value % 254) << 8; value /= 254; primary |= (firstByte + value % 254) << 16; ceBuffer.append(Collation.makeCE(primary)); return; } // original value > 1042489 } assert(length >= 7); // The second primary byte value 132..255 indicates the number of digit pairs (4..127), // then we generate primary bytes with those pairs. // Omit trailing 00 pairs. // Decrement the value for the last pair. // Set the exponent. 4 pairs.132, 5 pairs.133, ..., 127 pairs.255. int numPairs = (length + 1) / 2; long primary = numericPrimary | ((132 - 4 + numPairs) << 16); // Find the length without trailing 00 pairs. while(digits.charAt(length - 1) == 0 && digits.charAt(length - 2) == 0) { length -= 2; } // Read the first pair. int pair; int pos; if((length & 1) != 0) { // Only "half a pair" if we have an odd number of digits. pair = digits.charAt(0); pos = 1; } else { pair = digits.charAt(0) * 10 + digits.charAt(1); pos = 2; } pair = 11 + 2 * pair; // Add the pairs of digits between pos and length. int shift = 8; while(pos < length) { if(shift == 0) { // Every three pairs/bytes we need to store a 4-byte-primary CE // and start with a new CE with the '0' primary lead byte. primary |= pair; ceBuffer.append(Collation.makeCE(primary)); primary = numericPrimary; shift = 16; } else { primary |= pair << shift; shift -= 8; } pair = 11 + 2 * (digits.charAt(pos) * 10 + digits.charAt(pos + 1)); pos += 2; } primary |= (pair - 1) << shift; ceBuffer.append(Collation.makeCE(primary)); } }
public class class_name { private final void appendNumericSegmentCEs(CharSequence digits) { int length = digits.length(); assert(1 <= length && length <= 254); assert(length == 1 || digits.charAt(0) != 0); long numericPrimary = data.numericPrimary; // Note: We use primary byte values 2..255: digits are not compressible. if(length <= 7) { // Very dense encoding for small numbers. int value = digits.charAt(0); for(int i = 1; i < length; ++i) { value = value * 10 + digits.charAt(i); // depends on control dependency: [for], data = [i] } // Primary weight second byte values: // 74 byte values 2.. 75 for small numbers in two-byte primary weights. // 40 byte values 76..115 for medium numbers in three-byte primary weights. // 16 byte values 116..131 for large numbers in four-byte primary weights. // 124 byte values 132..255 for very large numbers with 4..127 digit pairs. int firstByte = 2; int numBytes = 74; if(value < numBytes) { // Two-byte primary for 0..73, good for day & month numbers etc. long primary = numericPrimary | ((firstByte + value) << 16); ceBuffer.append(Collation.makeCE(primary)); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } value -= numBytes; // depends on control dependency: [if], data = [none] firstByte += numBytes; // depends on control dependency: [if], data = [none] numBytes = 40; // depends on control dependency: [if], data = [none] if(value < numBytes * 254) { // Three-byte primary for 74..10233=74+40*254-1, good for year numbers and more. long primary = numericPrimary | ((firstByte + value / 254) << 16) | ((2 + value % 254) << 8); ceBuffer.append(Collation.makeCE(primary)); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } value -= numBytes * 254; // depends on control dependency: [if], data = [none] firstByte += numBytes; // depends on control dependency: [if], data = [none] numBytes = 16; // depends on control dependency: [if], data = [none] if(value < numBytes * 254 * 254) { // Four-byte primary for 10234..1042489=10234+16*254*254-1. long primary = numericPrimary | (2 + value % 254); value /= 254; // depends on control dependency: [if], data = [none] primary |= (2 + value % 254) << 8; // depends on control dependency: [if], data = [none] value /= 254; // depends on control dependency: [if], data = [none] primary |= (firstByte + value % 254) << 16; // depends on control dependency: [if], data = [none] ceBuffer.append(Collation.makeCE(primary)); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } // original value > 1042489 } assert(length >= 7); // The second primary byte value 132..255 indicates the number of digit pairs (4..127), // then we generate primary bytes with those pairs. // Omit trailing 00 pairs. // Decrement the value for the last pair. // Set the exponent. 4 pairs.132, 5 pairs.133, ..., 127 pairs.255. int numPairs = (length + 1) / 2; long primary = numericPrimary | ((132 - 4 + numPairs) << 16); // Find the length without trailing 00 pairs. while(digits.charAt(length - 1) == 0 && digits.charAt(length - 2) == 0) { length -= 2; // depends on control dependency: [while], data = [none] } // Read the first pair. int pair; int pos; if((length & 1) != 0) { // Only "half a pair" if we have an odd number of digits. pair = digits.charAt(0); // depends on control dependency: [if], data = [0)] pos = 1; // depends on control dependency: [if], data = [none] } else { pair = digits.charAt(0) * 10 + digits.charAt(1); // depends on control dependency: [if], data = [0)] pos = 2; // depends on control dependency: [if], data = [none] } pair = 11 + 2 * pair; // Add the pairs of digits between pos and length. int shift = 8; while(pos < length) { if(shift == 0) { // Every three pairs/bytes we need to store a 4-byte-primary CE // and start with a new CE with the '0' primary lead byte. primary |= pair; // depends on control dependency: [if], data = [none] ceBuffer.append(Collation.makeCE(primary)); // depends on control dependency: [if], data = [none] primary = numericPrimary; // depends on control dependency: [if], data = [none] shift = 16; // depends on control dependency: [if], data = [none] } else { primary |= pair << shift; // depends on control dependency: [if], data = [none] shift -= 8; // depends on control dependency: [if], data = [none] } pair = 11 + 2 * (digits.charAt(pos) * 10 + digits.charAt(pos + 1)); // depends on control dependency: [while], data = [(pos] pos += 2; // depends on control dependency: [while], data = [none] } primary |= (pair - 1) << shift; ceBuffer.append(Collation.makeCE(primary)); } }
public class class_name { public void process(ImagePyramid<GrayF32> image1 , ImagePyramid<GrayF32> image2 ) { // Process the pyramid from low resolution to high resolution boolean first = true; for( int i = image1.getNumLayers()-1; i >= 0; i-- ) { GrayF32 layer1 = image1.getLayer(i); GrayF32 layer2 = image2.getLayer(i); resizeForLayer(layer1.width,layer2.height); // compute image derivatives gradient.process(layer1,deriv1X,deriv1Y); gradient.process(layer2,deriv2X,deriv2Y); hessian.process(deriv2X,deriv2Y,deriv2XX,deriv2YY,deriv2XY); if( !first ) { // interpolate initial flow from previous layer interpolateFlowScale(layer1.width, layer1.height); } else { // for the very first layer there is no information on flow so set everything to 0 first = false; flowU.reshape(layer1.width, layer1.height); flowV.reshape(layer1.width, layer1.height); ImageMiscOps.fill(flowU,0); ImageMiscOps.fill(flowV,0); } // compute flow for this layer processLayer(layer1,layer2,deriv1X,deriv1Y,deriv2X,deriv2Y,deriv2XX,deriv2YY,deriv2XY); } } }
public class class_name { public void process(ImagePyramid<GrayF32> image1 , ImagePyramid<GrayF32> image2 ) { // Process the pyramid from low resolution to high resolution boolean first = true; for( int i = image1.getNumLayers()-1; i >= 0; i-- ) { GrayF32 layer1 = image1.getLayer(i); GrayF32 layer2 = image2.getLayer(i); resizeForLayer(layer1.width,layer2.height); // depends on control dependency: [for], data = [none] // compute image derivatives gradient.process(layer1,deriv1X,deriv1Y); // depends on control dependency: [for], data = [none] gradient.process(layer2,deriv2X,deriv2Y); // depends on control dependency: [for], data = [none] hessian.process(deriv2X,deriv2Y,deriv2XX,deriv2YY,deriv2XY); // depends on control dependency: [for], data = [none] if( !first ) { // interpolate initial flow from previous layer interpolateFlowScale(layer1.width, layer1.height); // depends on control dependency: [if], data = [none] } else { // for the very first layer there is no information on flow so set everything to 0 first = false; // depends on control dependency: [if], data = [none] flowU.reshape(layer1.width, layer1.height); // depends on control dependency: [if], data = [none] flowV.reshape(layer1.width, layer1.height); // depends on control dependency: [if], data = [none] ImageMiscOps.fill(flowU,0); // depends on control dependency: [if], data = [none] ImageMiscOps.fill(flowV,0); // depends on control dependency: [if], data = [none] } // compute flow for this layer processLayer(layer1,layer2,deriv1X,deriv1Y,deriv2X,deriv2Y,deriv2XX,deriv2YY,deriv2XY); // depends on control dependency: [for], data = [none] } } }
public class class_name { public void addChildren( Iterable<AstNode> otherChildren ) { assert otherChildren != null; for (AstNode planNode : otherChildren) { this.addLastChild(planNode); } } }
public class class_name { public void addChildren( Iterable<AstNode> otherChildren ) { assert otherChildren != null; for (AstNode planNode : otherChildren) { this.addLastChild(planNode); // depends on control dependency: [for], data = [planNode] } } }
public class class_name { public static Float extractToFloat(final DeviceData deviceDataArgout) throws DevFailed { final Object value = CommandHelper.extract(deviceDataArgout); Float argout = null; if (value instanceof Short) { argout = Float.valueOf(((Short) value).floatValue()); } else if (value instanceof String) { try { argout = Float.valueOf((String) value); } catch (final Exception e) { Except.throw_exception("TANGO_WRONG_DATA_ERROR", "output type " + value + " is not a numerical", "CommandHelper.extractToFloat(deviceDataArgin)"); } } else if (value instanceof Integer) { argout = Float.valueOf(((Integer) value).floatValue()); } else if (value instanceof Long) { argout = Float.valueOf(((Long) value).floatValue()); } else if (value instanceof Float) { argout = Float.valueOf(((Float) value).floatValue()); } else if (value instanceof Boolean) { if (((Boolean) value).booleanValue()) { argout = Float.valueOf(1); } else { argout = Float.valueOf(0); } } else if (value instanceof Double) { argout = Float.valueOf(((Double) value).floatValue()); } else if (value instanceof DevState) { argout = Float.valueOf(Integer.valueOf(((DevState) value).value()).floatValue()); } else { Except.throw_exception("TANGO_WRONG_DATA_ERROR", "output type " + value.getClass() + " not supported", "CommandHelper.extractToFloat(Object value,deviceDataArgin)"); } return argout; } }
public class class_name { public static Float extractToFloat(final DeviceData deviceDataArgout) throws DevFailed { final Object value = CommandHelper.extract(deviceDataArgout); Float argout = null; if (value instanceof Short) { argout = Float.valueOf(((Short) value).floatValue()); } else if (value instanceof String) { try { argout = Float.valueOf((String) value); // depends on control dependency: [try], data = [none] } catch (final Exception e) { Except.throw_exception("TANGO_WRONG_DATA_ERROR", "output type " + value + " is not a numerical", "CommandHelper.extractToFloat(deviceDataArgin)"); } // depends on control dependency: [catch], data = [none] } else if (value instanceof Integer) { argout = Float.valueOf(((Integer) value).floatValue()); } else if (value instanceof Long) { argout = Float.valueOf(((Long) value).floatValue()); } else if (value instanceof Float) { argout = Float.valueOf(((Float) value).floatValue()); } else if (value instanceof Boolean) { if (((Boolean) value).booleanValue()) { argout = Float.valueOf(1); // depends on control dependency: [if], data = [none] } else { argout = Float.valueOf(0); // depends on control dependency: [if], data = [none] } } else if (value instanceof Double) { argout = Float.valueOf(((Double) value).floatValue()); } else if (value instanceof DevState) { argout = Float.valueOf(Integer.valueOf(((DevState) value).value()).floatValue()); } else { Except.throw_exception("TANGO_WRONG_DATA_ERROR", "output type " + value.getClass() + " not supported", "CommandHelper.extractToFloat(Object value,deviceDataArgin)"); } return argout; } }
public class class_name { public Channel addPeer(Peer peer, PeerOptions peerOptions) throws InvalidArgumentException { if (shutdown) { throw new InvalidArgumentException(format("Channel %s has been shutdown.", name)); } if (null == peer) { throw new InvalidArgumentException("Peer is invalid can not be null."); } if (peer.getChannel() != null && peer.getChannel() != this) { throw new InvalidArgumentException(format("Peer already connected to channel %s", peer.getChannel().getName())); } if (null == peerOptions) { throw new InvalidArgumentException("peerOptions is invalid can not be null."); } logger.debug(format("%s adding peer: %s, peerOptions: %s", toString(), peer, "" + peerOptions)); peer.setChannel(this); peers.add(peer); peerOptionsMap.put(peer, peerOptions.clone()); peerEndpointMap.put(peer.getEndpoint(), peer); if (peerOptions.getPeerRoles().contains(PeerRole.SERVICE_DISCOVERY)) { final Properties properties = peer.getProperties(); if ((properties == null) || properties.isEmpty() || (isNullOrEmpty(properties.getProperty("clientCertFile")) && !properties.containsKey("clientCertBytes"))) { TLSCertificateBuilder tlsCertificateBuilder = new TLSCertificateBuilder(); TLSCertificateKeyPair tlsCertificateKeyPair = tlsCertificateBuilder.clientCert(); peer.setTLSCertificateKeyPair(tlsCertificateKeyPair); } discoveryEndpoints.add(peer.getEndpoint()); } for (Map.Entry<PeerRole, Set<Peer>> peerRole : peerRoleSetMap.entrySet()) { if (peerOptions.getPeerRoles().contains(peerRole.getKey())) { peerRole.getValue().add(peer); } } if (isInitialized() && peerOptions.getPeerRoles().contains(PeerRole.EVENT_SOURCE)) { try { peer.initiateEventing(getTransactionContext(), getPeersOptions(peer)); } catch (TransactionException e) { logger.error(format("Error channel %s enabling eventing on peer %s", toString(), peer)); } } return this; } }
public class class_name { public Channel addPeer(Peer peer, PeerOptions peerOptions) throws InvalidArgumentException { if (shutdown) { throw new InvalidArgumentException(format("Channel %s has been shutdown.", name)); } if (null == peer) { throw new InvalidArgumentException("Peer is invalid can not be null."); } if (peer.getChannel() != null && peer.getChannel() != this) { throw new InvalidArgumentException(format("Peer already connected to channel %s", peer.getChannel().getName())); } if (null == peerOptions) { throw new InvalidArgumentException("peerOptions is invalid can not be null."); } logger.debug(format("%s adding peer: %s, peerOptions: %s", toString(), peer, "" + peerOptions)); peer.setChannel(this); peers.add(peer); peerOptionsMap.put(peer, peerOptions.clone()); peerEndpointMap.put(peer.getEndpoint(), peer); if (peerOptions.getPeerRoles().contains(PeerRole.SERVICE_DISCOVERY)) { final Properties properties = peer.getProperties(); if ((properties == null) || properties.isEmpty() || (isNullOrEmpty(properties.getProperty("clientCertFile")) && !properties.containsKey("clientCertBytes"))) { TLSCertificateBuilder tlsCertificateBuilder = new TLSCertificateBuilder(); TLSCertificateKeyPair tlsCertificateKeyPair = tlsCertificateBuilder.clientCert(); peer.setTLSCertificateKeyPair(tlsCertificateKeyPair); // depends on control dependency: [if], data = [none] } discoveryEndpoints.add(peer.getEndpoint()); } for (Map.Entry<PeerRole, Set<Peer>> peerRole : peerRoleSetMap.entrySet()) { if (peerOptions.getPeerRoles().contains(peerRole.getKey())) { peerRole.getValue().add(peer); } } if (isInitialized() && peerOptions.getPeerRoles().contains(PeerRole.EVENT_SOURCE)) { try { peer.initiateEventing(getTransactionContext(), getPeersOptions(peer)); } catch (TransactionException e) { logger.error(format("Error channel %s enabling eventing on peer %s", toString(), peer)); } } return this; } }
public class class_name { private void adaptItemColor() { if (adapter != null) { RecyclerView.Adapter<?> wrappedAdapter = adapter.getWrappedAdapter(); if (wrappedAdapter instanceof ArrayRecyclerViewAdapter) { ((ArrayRecyclerViewAdapter) wrappedAdapter).setItemColor(itemColor); } } } }
public class class_name { private void adaptItemColor() { if (adapter != null) { RecyclerView.Adapter<?> wrappedAdapter = adapter.getWrappedAdapter(); if (wrappedAdapter instanceof ArrayRecyclerViewAdapter) { ((ArrayRecyclerViewAdapter) wrappedAdapter).setItemColor(itemColor); // depends on control dependency: [if], data = [none] } } } }
public class class_name { private static void writeUtf8(OutputAccessor out, CharSequence seq, int len) { // We can use the _set methods as these not need to do any index checks and reference checks. // This is possible as we called ensureWritable(...) before. for (int i = 0; i < len; i++) { char c = seq.charAt(i); switch (c) { case '\b': out.write(B); continue; case '\t': out.write(T); continue; case '\n': out.write(N); continue; case '\f': out.write(F); continue; case '\r': out.write(R); continue; case '\"': out.write(QUOT); continue; case '\\': out.write(BSLASH); continue; } if (c < 0x20) { escape(out, c); } else if (c < 0x80) { out.write((byte) c); } else if (c < 0x800) { out.write((byte) (0xc0 | (c >> 6))); out.write((byte) (0x80 | (c & 0x3f))); } else if (isSurrogate(c)) { if (!Character.isHighSurrogate(c)) { out.write(WRITE_UTF_UNKNOWN); continue; } final char c2; try { // Surrogate Pair consumes 2 characters. Optimistically try to get the next character to avoid // duplicate bounds checking with charAt. If an IndexOutOfBoundsException is thrown we will // re-throw a more informative exception describing the problem. c2 = seq.charAt(++i); } catch (IndexOutOfBoundsException e) { out.write(WRITE_UTF_UNKNOWN); break; } if (!Character.isLowSurrogate(c2)) { out.write(WRITE_UTF_UNKNOWN); out.write((byte) (Character.isHighSurrogate(c2) ? WRITE_UTF_UNKNOWN : c2)); continue; } int codePoint = Character.toCodePoint(c, c2); // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G2630. escape(out, c); escape(out, codePoint); } else { out.write((byte) (0xe0 | (c >> 12))); out.write((byte) (0x80 | ((c >> 6) & 0x3f))); out.write((byte) (0x80 | (c & 0x3f))); } } } }
public class class_name { private static void writeUtf8(OutputAccessor out, CharSequence seq, int len) { // We can use the _set methods as these not need to do any index checks and reference checks. // This is possible as we called ensureWritable(...) before. for (int i = 0; i < len; i++) { char c = seq.charAt(i); switch (c) { case '\b': out.write(B); continue; case '\t': out.write(T); continue; case '\n': out.write(N); continue; case '\f': out.write(F); continue; case '\r': out.write(R); continue; case '\"': out.write(QUOT); continue; case '\\': out.write(BSLASH); continue; } if (c < 0x20) { escape(out, c); // depends on control dependency: [if], data = [none] } else if (c < 0x80) { out.write((byte) c); // depends on control dependency: [if], data = [none] } else if (c < 0x800) { out.write((byte) (0xc0 | (c >> 6))); // depends on control dependency: [if], data = [(c] out.write((byte) (0x80 | (c & 0x3f))); // depends on control dependency: [if], data = [(c] } else if (isSurrogate(c)) { if (!Character.isHighSurrogate(c)) { out.write(WRITE_UTF_UNKNOWN); // depends on control dependency: [if], data = [none] continue; } final char c2; try { // Surrogate Pair consumes 2 characters. Optimistically try to get the next character to avoid // duplicate bounds checking with charAt. If an IndexOutOfBoundsException is thrown we will // re-throw a more informative exception describing the problem. c2 = seq.charAt(++i); // depends on control dependency: [try], data = [none] } catch (IndexOutOfBoundsException e) { out.write(WRITE_UTF_UNKNOWN); break; } // depends on control dependency: [catch], data = [none] if (!Character.isLowSurrogate(c2)) { out.write(WRITE_UTF_UNKNOWN); // depends on control dependency: [if], data = [none] out.write((byte) (Character.isHighSurrogate(c2) ? WRITE_UTF_UNKNOWN : c2)); // depends on control dependency: [if], data = [none] continue; } int codePoint = Character.toCodePoint(c, c2); // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G2630. escape(out, c); // depends on control dependency: [if], data = [none] escape(out, codePoint); // depends on control dependency: [if], data = [none] } else { out.write((byte) (0xe0 | (c >> 12))); // depends on control dependency: [if], data = [none] out.write((byte) (0x80 | ((c >> 6) & 0x3f))); // depends on control dependency: [if], data = [none] out.write((byte) (0x80 | (c & 0x3f))); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public void connect(IClientConnectCallback callback, boolean allowResolve) { if (context == null) { aSysnCallback(HMSAgent.AgentResultCode.HMSAGENT_NO_INIT, callback); return; } HuaweiApiClient client = getApiClient(); // client 有效,则直接回调 if (client != null && client.isConnected()) { HMSAgentLog.d("client is valid"); aSysnCallback(HMSAgent.AgentResultCode.HMSAGENT_SUCCESS, callback); return; } else { // client无效,将callback加入队列,并启动连接 synchronized (CALLBACK_LOCK) { HMSAgentLog.d("client is invalid:size=" + connCallbacks.size()); allowResolveConnectError = allowResolveConnectError || allowResolve; if (connCallbacks.isEmpty()) { connCallbacks.add(callback); // 连接尝试最大次数 curLeftResolveTimes = MAX_RESOLVE_TIMES; startConnect(); } else { connCallbacks.add(callback); } } } } }
public class class_name { public void connect(IClientConnectCallback callback, boolean allowResolve) { if (context == null) { aSysnCallback(HMSAgent.AgentResultCode.HMSAGENT_NO_INIT, callback); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } HuaweiApiClient client = getApiClient(); // client 有效,则直接回调 if (client != null && client.isConnected()) { HMSAgentLog.d("client is valid"); // depends on control dependency: [if], data = [none] aSysnCallback(HMSAgent.AgentResultCode.HMSAGENT_SUCCESS, callback); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } else { // client无效,将callback加入队列,并启动连接 synchronized (CALLBACK_LOCK) { // depends on control dependency: [if], data = [none] HMSAgentLog.d("client is invalid:size=" + connCallbacks.size()); allowResolveConnectError = allowResolveConnectError || allowResolve; if (connCallbacks.isEmpty()) { connCallbacks.add(callback); // depends on control dependency: [if], data = [none] // 连接尝试最大次数 curLeftResolveTimes = MAX_RESOLVE_TIMES; // depends on control dependency: [if], data = [none] startConnect(); // depends on control dependency: [if], data = [none] } else { connCallbacks.add(callback); // depends on control dependency: [if], data = [none] } } } } }
public class class_name { public List<T> getEvents() { List<T> returnEvents = new ArrayList<T>(); if (bufferedEvents.isEmpty()) { return returnEvents; } int returnSize = isBufferFull() ? bufferSize : bufferedEvents.size(); for (int i = 0 ; i < returnSize ; i++) { returnEvents.add(bufferedEvents.remove(0)); } return returnEvents; } }
public class class_name { public List<T> getEvents() { List<T> returnEvents = new ArrayList<T>(); if (bufferedEvents.isEmpty()) { return returnEvents; // depends on control dependency: [if], data = [none] } int returnSize = isBufferFull() ? bufferSize : bufferedEvents.size(); for (int i = 0 ; i < returnSize ; i++) { returnEvents.add(bufferedEvents.remove(0)); // depends on control dependency: [for], data = [none] } return returnEvents; } }
public class class_name { public void marshall(ConfigurationRecorderStatus configurationRecorderStatus, ProtocolMarshaller protocolMarshaller) { if (configurationRecorderStatus == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(configurationRecorderStatus.getName(), NAME_BINDING); protocolMarshaller.marshall(configurationRecorderStatus.getLastStartTime(), LASTSTARTTIME_BINDING); protocolMarshaller.marshall(configurationRecorderStatus.getLastStopTime(), LASTSTOPTIME_BINDING); protocolMarshaller.marshall(configurationRecorderStatus.getRecording(), RECORDING_BINDING); protocolMarshaller.marshall(configurationRecorderStatus.getLastStatus(), LASTSTATUS_BINDING); protocolMarshaller.marshall(configurationRecorderStatus.getLastErrorCode(), LASTERRORCODE_BINDING); protocolMarshaller.marshall(configurationRecorderStatus.getLastErrorMessage(), LASTERRORMESSAGE_BINDING); protocolMarshaller.marshall(configurationRecorderStatus.getLastStatusChangeTime(), LASTSTATUSCHANGETIME_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(ConfigurationRecorderStatus configurationRecorderStatus, ProtocolMarshaller protocolMarshaller) { if (configurationRecorderStatus == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(configurationRecorderStatus.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(configurationRecorderStatus.getLastStartTime(), LASTSTARTTIME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(configurationRecorderStatus.getLastStopTime(), LASTSTOPTIME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(configurationRecorderStatus.getRecording(), RECORDING_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(configurationRecorderStatus.getLastStatus(), LASTSTATUS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(configurationRecorderStatus.getLastErrorCode(), LASTERRORCODE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(configurationRecorderStatus.getLastErrorMessage(), LASTERRORMESSAGE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(configurationRecorderStatus.getLastStatusChangeTime(), LASTSTATUSCHANGETIME_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 { protected String renderCheckbox(FacesContext facesContext, UIComponent uiComponent, String value, boolean disabled, boolean checked, boolean renderId, Integer itemNum) throws IOException { String clientId = uiComponent.getClientId(facesContext); String itemId = (itemNum == null)? null : clientId + facesContext.getNamingContainerSeparatorChar() + itemNum; ResponseWriter writer = facesContext.getResponseWriter(); writer.startElement(HTML.INPUT_ELEM, uiComponent); if (itemId != null) { writer.writeAttribute(HTML.ID_ATTR, itemId, null); } else if (renderId) { writer.writeAttribute(HTML.ID_ATTR, clientId, null); } writer.writeAttribute(HTML.TYPE_ATTR, HTML.INPUT_TYPE_CHECKBOX, null); writer.writeAttribute(HTML.NAME_ATTR, clientId, null); if (checked) { writer.writeAttribute(HTML.CHECKED_ATTR, org.apache.myfaces.shared.renderkit.html.HTML.CHECKED_ATTR, null); } if (disabled) { writer.writeAttribute(HTML.DISABLED_ATTR, HTML.DISABLED_ATTR, null); } if ((value != null) && (value.length() > 0)) { writer.writeAttribute(HTML.VALUE_ATTR, value, null); } Map<String, List<ClientBehavior>> behaviors = null; if (uiComponent instanceof UISelectBoolean) { if (uiComponent instanceof ClientBehaviorHolder) { behaviors = ((ClientBehaviorHolder) uiComponent).getClientBehaviors(); if (behaviors.isEmpty() && isCommonPropertiesOptimizationEnabled(facesContext)) { long commonPropertiesMarked = CommonPropertyUtils.getCommonPropertiesMarked(uiComponent); CommonPropertyUtils.renderChangeEventProperty(writer, commonPropertiesMarked, uiComponent); CommonPropertyUtils.renderEventProperties(writer, commonPropertiesMarked, uiComponent); CommonPropertyUtils.renderFieldEventPropertiesWithoutOnchange(writer, commonPropertiesMarked, uiComponent); } else { long commonPropertiesMarked = CommonPropertyUtils.getCommonPropertiesMarked(uiComponent); HtmlRendererUtils.renderBehaviorizedOnchangeEventHandler( facesContext, writer, uiComponent, behaviors); if (isCommonEventsOptimizationEnabled(facesContext)) { Long commonEventsMarked = CommonEventUtils.getCommonEventsMarked(uiComponent); CommonEventUtils.renderBehaviorizedEventHandlers(facesContext, writer, commonPropertiesMarked, commonEventsMarked, uiComponent, behaviors); CommonEventUtils.renderBehaviorizedFieldEventHandlersWithoutOnchange( facesContext, writer, commonPropertiesMarked, commonEventsMarked, uiComponent, behaviors); } else { HtmlRendererUtils.renderBehaviorizedEventHandlers(facesContext, writer, uiComponent, behaviors); HtmlRendererUtils.renderBehaviorizedFieldEventHandlersWithoutOnchange( facesContext, writer, uiComponent, behaviors); } } HtmlRendererUtils.renderHTMLAttributes(writer, uiComponent, HTML.INPUT_PASSTHROUGH_ATTRIBUTES_WITHOUT_DISABLED_AND_EVENTS); } else { HtmlRendererUtils.renderHTMLAttributes(writer, uiComponent, HTML.INPUT_PASSTHROUGH_ATTRIBUTES_WITHOUT_DISABLED); } } else { if (uiComponent instanceof ClientBehaviorHolder) { behaviors = ((ClientBehaviorHolder) uiComponent).getClientBehaviors(); if (behaviors.isEmpty() && isCommonPropertiesOptimizationEnabled(facesContext)) { long commonPropertiesMarked = CommonPropertyUtils.getCommonPropertiesMarked(uiComponent); CommonPropertyUtils.renderChangeEventProperty(writer, commonPropertiesMarked, uiComponent); CommonPropertyUtils.renderEventProperties(writer, commonPropertiesMarked, uiComponent); CommonPropertyUtils.renderFieldEventPropertiesWithoutOnchange(writer, commonPropertiesMarked, uiComponent); } else { long commonPropertiesMarked = CommonPropertyUtils.getCommonPropertiesMarked(uiComponent); HtmlRendererUtils.renderBehaviorizedOnchangeEventHandler( facesContext, writer, uiComponent, behaviors); if (isCommonEventsOptimizationEnabled(facesContext)) { Long commonEventsMarked = CommonEventUtils.getCommonEventsMarked(uiComponent); CommonEventUtils.renderBehaviorizedEventHandlers(facesContext, writer, commonPropertiesMarked, commonEventsMarked, uiComponent, behaviors); CommonEventUtils.renderBehaviorizedFieldEventHandlersWithoutOnchange( facesContext, writer, commonPropertiesMarked, commonEventsMarked, uiComponent, behaviors); } else { HtmlRendererUtils.renderBehaviorizedEventHandlers(facesContext, writer, uiComponent, behaviors); HtmlRendererUtils.renderBehaviorizedFieldEventHandlersWithoutOnchange( facesContext, writer, uiComponent, behaviors); } } HtmlRendererUtils.renderHTMLAttributes(writer, uiComponent, HTML.INPUT_PASSTHROUGH_ATTRIBUTES_WITHOUT_DISABLED_AND_STYLE_AND_EVENTS); } else { HtmlRendererUtils.renderHTMLAttributes(writer, uiComponent, HTML.INPUT_PASSTHROUGH_ATTRIBUTES_WITHOUT_DISABLED_AND_STYLE); } } if (isDisabled(facesContext, uiComponent)) { writer.writeAttribute(HTML.DISABLED_ATTR, Boolean.TRUE, null); } writer.endElement(HTML.INPUT_ELEM); return itemId; } }
public class class_name { protected String renderCheckbox(FacesContext facesContext, UIComponent uiComponent, String value, boolean disabled, boolean checked, boolean renderId, Integer itemNum) throws IOException { String clientId = uiComponent.getClientId(facesContext); String itemId = (itemNum == null)? null : clientId + facesContext.getNamingContainerSeparatorChar() + itemNum; ResponseWriter writer = facesContext.getResponseWriter(); writer.startElement(HTML.INPUT_ELEM, uiComponent); if (itemId != null) { writer.writeAttribute(HTML.ID_ATTR, itemId, null); } else if (renderId) { writer.writeAttribute(HTML.ID_ATTR, clientId, null); } writer.writeAttribute(HTML.TYPE_ATTR, HTML.INPUT_TYPE_CHECKBOX, null); writer.writeAttribute(HTML.NAME_ATTR, clientId, null); if (checked) { writer.writeAttribute(HTML.CHECKED_ATTR, org.apache.myfaces.shared.renderkit.html.HTML.CHECKED_ATTR, null); } if (disabled) { writer.writeAttribute(HTML.DISABLED_ATTR, HTML.DISABLED_ATTR, null); } if ((value != null) && (value.length() > 0)) { writer.writeAttribute(HTML.VALUE_ATTR, value, null); } Map<String, List<ClientBehavior>> behaviors = null; if (uiComponent instanceof UISelectBoolean) { if (uiComponent instanceof ClientBehaviorHolder) { behaviors = ((ClientBehaviorHolder) uiComponent).getClientBehaviors(); // depends on control dependency: [if], data = [none] if (behaviors.isEmpty() && isCommonPropertiesOptimizationEnabled(facesContext)) { long commonPropertiesMarked = CommonPropertyUtils.getCommonPropertiesMarked(uiComponent); CommonPropertyUtils.renderChangeEventProperty(writer, commonPropertiesMarked, uiComponent); // depends on control dependency: [if], data = [none] CommonPropertyUtils.renderEventProperties(writer, commonPropertiesMarked, uiComponent); // depends on control dependency: [if], data = [none] CommonPropertyUtils.renderFieldEventPropertiesWithoutOnchange(writer, commonPropertiesMarked, uiComponent); // depends on control dependency: [if], data = [none] } else { long commonPropertiesMarked = CommonPropertyUtils.getCommonPropertiesMarked(uiComponent); HtmlRendererUtils.renderBehaviorizedOnchangeEventHandler( facesContext, writer, uiComponent, behaviors); // depends on control dependency: [if], data = [none] if (isCommonEventsOptimizationEnabled(facesContext)) { Long commonEventsMarked = CommonEventUtils.getCommonEventsMarked(uiComponent); CommonEventUtils.renderBehaviorizedEventHandlers(facesContext, writer, commonPropertiesMarked, commonEventsMarked, uiComponent, behaviors); // depends on control dependency: [if], data = [none] CommonEventUtils.renderBehaviorizedFieldEventHandlersWithoutOnchange( facesContext, writer, commonPropertiesMarked, commonEventsMarked, uiComponent, behaviors); // depends on control dependency: [if], data = [none] } else { HtmlRendererUtils.renderBehaviorizedEventHandlers(facesContext, writer, uiComponent, behaviors); // depends on control dependency: [if], data = [none] HtmlRendererUtils.renderBehaviorizedFieldEventHandlersWithoutOnchange( facesContext, writer, uiComponent, behaviors); // depends on control dependency: [if], data = [none] } } HtmlRendererUtils.renderHTMLAttributes(writer, uiComponent, HTML.INPUT_PASSTHROUGH_ATTRIBUTES_WITHOUT_DISABLED_AND_EVENTS); // depends on control dependency: [if], data = [none] } else { HtmlRendererUtils.renderHTMLAttributes(writer, uiComponent, HTML.INPUT_PASSTHROUGH_ATTRIBUTES_WITHOUT_DISABLED); // depends on control dependency: [if], data = [none] } } else { if (uiComponent instanceof ClientBehaviorHolder) { behaviors = ((ClientBehaviorHolder) uiComponent).getClientBehaviors(); // depends on control dependency: [if], data = [none] if (behaviors.isEmpty() && isCommonPropertiesOptimizationEnabled(facesContext)) { long commonPropertiesMarked = CommonPropertyUtils.getCommonPropertiesMarked(uiComponent); CommonPropertyUtils.renderChangeEventProperty(writer, commonPropertiesMarked, uiComponent); // depends on control dependency: [if], data = [none] CommonPropertyUtils.renderEventProperties(writer, commonPropertiesMarked, uiComponent); // depends on control dependency: [if], data = [none] CommonPropertyUtils.renderFieldEventPropertiesWithoutOnchange(writer, commonPropertiesMarked, uiComponent); // depends on control dependency: [if], data = [none] } else { long commonPropertiesMarked = CommonPropertyUtils.getCommonPropertiesMarked(uiComponent); HtmlRendererUtils.renderBehaviorizedOnchangeEventHandler( facesContext, writer, uiComponent, behaviors); // depends on control dependency: [if], data = [none] if (isCommonEventsOptimizationEnabled(facesContext)) { Long commonEventsMarked = CommonEventUtils.getCommonEventsMarked(uiComponent); CommonEventUtils.renderBehaviorizedEventHandlers(facesContext, writer, commonPropertiesMarked, commonEventsMarked, uiComponent, behaviors); // depends on control dependency: [if], data = [none] CommonEventUtils.renderBehaviorizedFieldEventHandlersWithoutOnchange( facesContext, writer, commonPropertiesMarked, commonEventsMarked, uiComponent, behaviors); // depends on control dependency: [if], data = [none] } else { HtmlRendererUtils.renderBehaviorizedEventHandlers(facesContext, writer, uiComponent, behaviors); // depends on control dependency: [if], data = [none] HtmlRendererUtils.renderBehaviorizedFieldEventHandlersWithoutOnchange( facesContext, writer, uiComponent, behaviors); // depends on control dependency: [if], data = [none] } } HtmlRendererUtils.renderHTMLAttributes(writer, uiComponent, HTML.INPUT_PASSTHROUGH_ATTRIBUTES_WITHOUT_DISABLED_AND_STYLE_AND_EVENTS); // depends on control dependency: [if], data = [none] } else { HtmlRendererUtils.renderHTMLAttributes(writer, uiComponent, HTML.INPUT_PASSTHROUGH_ATTRIBUTES_WITHOUT_DISABLED_AND_STYLE); // depends on control dependency: [if], data = [none] } } if (isDisabled(facesContext, uiComponent)) { writer.writeAttribute(HTML.DISABLED_ATTR, Boolean.TRUE, null); } writer.endElement(HTML.INPUT_ELEM); return itemId; } }
public class class_name { public CmsFolder readAncestor(CmsRequestContext context, CmsResource resource, CmsResourceFilter filter) throws CmsException { // get the full folder path of the resource to start from String path = CmsResource.getFolderPath(resource.getRootPath()); do { // check if the current folder matches the given filter if (existsResource(context, path, filter)) { // folder matches, return it return readFolder(context, path, filter); } else { // folder does not match filter criteria, go up one folder path = CmsResource.getParentFolder(path); } if (CmsStringUtil.isEmpty(path) || !path.startsWith(context.getSiteRoot())) { // site root or root folder reached and no matching folder found return null; } } while (true); } }
public class class_name { public CmsFolder readAncestor(CmsRequestContext context, CmsResource resource, CmsResourceFilter filter) throws CmsException { // get the full folder path of the resource to start from String path = CmsResource.getFolderPath(resource.getRootPath()); do { // check if the current folder matches the given filter if (existsResource(context, path, filter)) { // folder matches, return it return readFolder(context, path, filter); // depends on control dependency: [if], data = [none] } else { // folder does not match filter criteria, go up one folder path = CmsResource.getParentFolder(path); // depends on control dependency: [if], data = [none] } if (CmsStringUtil.isEmpty(path) || !path.startsWith(context.getSiteRoot())) { // site root or root folder reached and no matching folder found return null; // depends on control dependency: [if], data = [none] } } while (true); } }
public class class_name { public PropertyEditorRegistry getPropertyEditorRegistry() { final HttpServletRequest servletRequest = getCurrentRequest(); PropertyEditorRegistry registry = (PropertyEditorRegistry) servletRequest.getAttribute(GrailsApplicationAttributes.PROPERTY_REGISTRY); if (registry == null) { registry = new PropertyEditorRegistrySupport(); PropertyEditorRegistryUtils.registerCustomEditors(this, registry, RequestContextUtils.getLocale(servletRequest)); servletRequest.setAttribute(GrailsApplicationAttributes.PROPERTY_REGISTRY, registry); } return registry; } }
public class class_name { public PropertyEditorRegistry getPropertyEditorRegistry() { final HttpServletRequest servletRequest = getCurrentRequest(); PropertyEditorRegistry registry = (PropertyEditorRegistry) servletRequest.getAttribute(GrailsApplicationAttributes.PROPERTY_REGISTRY); if (registry == null) { registry = new PropertyEditorRegistrySupport(); // depends on control dependency: [if], data = [none] PropertyEditorRegistryUtils.registerCustomEditors(this, registry, RequestContextUtils.getLocale(servletRequest)); // depends on control dependency: [if], data = [none] servletRequest.setAttribute(GrailsApplicationAttributes.PROPERTY_REGISTRY, registry); // depends on control dependency: [if], data = [none] } return registry; } }
public class class_name { public void mergeHeader(InputStream is) throws java.io.IOException { if (is == null) return; char s[] = new char[10]; int firstc = is.read(); while (firstc != '\n' && firstc != '\r' && firstc >= 0) { int len = 0; int keyend = -1; int c; boolean inKey = firstc > ' '; s[len++] = (char) firstc; parseloop:{ while ((c = is.read()) >= 0) { switch (c) { case ':': if (inKey && len > 0) keyend = len; inKey = false; break; case '\t': c = ' '; case ' ': inKey = false; break; case '\r': case '\n': firstc = is.read(); if (c == '\r' && firstc == '\n') { firstc = is.read(); if (firstc == '\r') firstc = is.read(); } if (firstc == '\n' || firstc == '\r' || firstc > ' ') break parseloop; /* continuation */ c = ' '; break; } if (len >= s.length) { char ns[] = new char[s.length * 2]; System.arraycopy(s, 0, ns, 0, len); s = ns; } s[len++] = (char) c; } firstc = -1; } while (len > 0 && s[len - 1] <= ' ') len--; String k; if (keyend <= 0) { k = null; keyend = 0; } else { k = String.copyValueOf(s, 0, keyend); if (keyend < len && s[keyend] == ':') keyend++; while (keyend < len && s[keyend] <= ' ') keyend++; } String v; if (keyend >= len) v = new String(); else v = String.copyValueOf(s, keyend, len - keyend); add(k, v); } } }
public class class_name { public void mergeHeader(InputStream is) throws java.io.IOException { if (is == null) return; char s[] = new char[10]; int firstc = is.read(); while (firstc != '\n' && firstc != '\r' && firstc >= 0) { int len = 0; int keyend = -1; int c; boolean inKey = firstc > ' '; s[len++] = (char) firstc; parseloop:{ while ((c = is.read()) >= 0) { switch (c) { case ':': if (inKey && len > 0) keyend = len; inKey = false; break; case '\t': c = ' '; case ' ': inKey = false; break; case '\r': case '\n': firstc = is.read(); if (c == '\r' && firstc == '\n') { firstc = is.read(); // depends on control dependency: [if], data = [none] if (firstc == '\r') firstc = is.read(); } if (firstc == '\n' || firstc == '\r' || firstc > ' ') break parseloop; /* continuation */ c = ' '; break; } if (len >= s.length) { char ns[] = new char[s.length * 2]; System.arraycopy(s, 0, ns, 0, len); // depends on control dependency: [if], data = [none] s = ns; // depends on control dependency: [if], data = [none] } s[len++] = (char) c; // depends on control dependency: [while], data = [none] } firstc = -1; } while (len > 0 && s[len - 1] <= ' ') len--; String k; if (keyend <= 0) { k = null; // depends on control dependency: [if], data = [none] keyend = 0; // depends on control dependency: [if], data = [none] } else { k = String.copyValueOf(s, 0, keyend); // depends on control dependency: [if], data = [none] if (keyend < len && s[keyend] == ':') keyend++; while (keyend < len && s[keyend] <= ' ') keyend++; } String v; if (keyend >= len) v = new String(); else v = String.copyValueOf(s, keyend, len - keyend); add(k, v); } } }
public class class_name { public Atom getProjectedPoint(Atom point) { if(rotationPos == null) { // translation only return null; } Atom localPoint = Calc.subtract(point, rotationPos); double dot = Calc.scalarProduct(localPoint, rotationAxis); Atom localProjected = Calc.scale(rotationAxis, dot); Atom projected = Calc.add(localProjected, rotationPos); return projected; } }
public class class_name { public Atom getProjectedPoint(Atom point) { if(rotationPos == null) { // translation only return null; // depends on control dependency: [if], data = [none] } Atom localPoint = Calc.subtract(point, rotationPos); double dot = Calc.scalarProduct(localPoint, rotationAxis); Atom localProjected = Calc.scale(rotationAxis, dot); Atom projected = Calc.add(localProjected, rotationPos); return projected; } }
public class class_name { public void setUserStackAssociations(java.util.Collection<UserStackAssociation> userStackAssociations) { if (userStackAssociations == null) { this.userStackAssociations = null; return; } this.userStackAssociations = new java.util.ArrayList<UserStackAssociation>(userStackAssociations); } }
public class class_name { public void setUserStackAssociations(java.util.Collection<UserStackAssociation> userStackAssociations) { if (userStackAssociations == null) { this.userStackAssociations = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.userStackAssociations = new java.util.ArrayList<UserStackAssociation>(userStackAssociations); } }
public class class_name { public void addDataPoint (final DataPoint dataPoint) { if (m_nDataPoints >= m_aData.length) return; m_aData[m_nDataPoints] = dataPoint; m_aDivDiff[m_nDataPoints][0] = dataPoint.getY (); ++m_nDataPoints; for (int order = 1; order < m_nDataPoints; ++order) { final int bottom = m_nDataPoints - order - 1; final float numerator = m_aDivDiff[bottom + 1][order - 1] - m_aDivDiff[bottom][order - 1]; final float denominator = m_aData[bottom + order].getX () - m_aData[bottom].getX (); m_aDivDiff[bottom][order] = numerator / denominator; } } }
public class class_name { public void addDataPoint (final DataPoint dataPoint) { if (m_nDataPoints >= m_aData.length) return; m_aData[m_nDataPoints] = dataPoint; m_aDivDiff[m_nDataPoints][0] = dataPoint.getY (); ++m_nDataPoints; for (int order = 1; order < m_nDataPoints; ++order) { final int bottom = m_nDataPoints - order - 1; final float numerator = m_aDivDiff[bottom + 1][order - 1] - m_aDivDiff[bottom][order - 1]; final float denominator = m_aData[bottom + order].getX () - m_aData[bottom].getX (); m_aDivDiff[bottom][order] = numerator / denominator; // depends on control dependency: [for], data = [order] } } }
public class class_name { @Override public void close() { if (!this.closed.getAndSet(true)) { this.cache.close(); synchronized (this.segmentCaches) { this.segmentCaches.clear(); } } } }
public class class_name { @Override public void close() { if (!this.closed.getAndSet(true)) { this.cache.close(); // depends on control dependency: [if], data = [none] synchronized (this.segmentCaches) { // depends on control dependency: [if], data = [none] this.segmentCaches.clear(); } } } }
public class class_name { public static MimeType valueOf(String mimeType) { if (!StringUtils.hasLength(mimeType)) { throw new InvalidMimeTypeException(mimeType, "[mimeType] must not be empty"); } int index = mimeType.indexOf(';'); String fullType = (index >= 0 ? mimeType.substring(0, index) : mimeType).trim(); if (fullType.isEmpty()) { throw new InvalidMimeTypeException(mimeType, "'contentType' must not be empty"); } // java.net.HttpURLConnection returns a *; q=.2 Accept header if (MimeType.WILDCARD_TYPE.equals(fullType)) { fullType = "*/*"; } int subIndex = fullType.indexOf('/'); if (subIndex == -1) { throw new InvalidMimeTypeException(mimeType, "does not contain '/'"); } if (subIndex == fullType.length() - 1) { throw new InvalidMimeTypeException(mimeType, "does not contain subtype after '/'"); } String type = fullType.substring(0, subIndex); String subtype = fullType.substring(subIndex + 1, fullType.length()); if (MimeType.WILDCARD_TYPE.equals(type) && !MimeType.WILDCARD_TYPE.equals(subtype)) { throw new InvalidMimeTypeException(mimeType, "wildcard type is legal only in '*/*' (all mime " + "types)"); } Map<String, String> parameters = null; do { int nextIndex = index + 1; boolean quoted = false; while (nextIndex < mimeType.length()) { char ch = mimeType.charAt(nextIndex); if (ch == ';') { if (!quoted) { break; } } else if (ch == '"') { quoted = !quoted; } nextIndex++; } String parameter = mimeType.substring(index + 1, nextIndex).trim(); if (parameter.length() > 0) { if (parameters == null) { parameters = new LinkedHashMap<>(4); } int eqIndex = parameter.indexOf('='); if (eqIndex >= 0) { String attribute = parameter.substring(0, eqIndex); String value = parameter.substring(eqIndex + 1, parameter.length()); parameters.put(attribute, value); } } index = nextIndex; } while (index < mimeType.length()); try { return new MimeType(type, subtype, parameters); } catch (UnsupportedCharsetException ex) { throw new InvalidMimeTypeException(mimeType, "unsupported charset '" + ex.getCharsetName() + "'"); } catch (IllegalArgumentException ex) { throw new InvalidMimeTypeException(mimeType, ex.getMessage()); } } }
public class class_name { public static MimeType valueOf(String mimeType) { if (!StringUtils.hasLength(mimeType)) { throw new InvalidMimeTypeException(mimeType, "[mimeType] must not be empty"); } int index = mimeType.indexOf(';'); String fullType = (index >= 0 ? mimeType.substring(0, index) : mimeType).trim(); if (fullType.isEmpty()) { throw new InvalidMimeTypeException(mimeType, "'contentType' must not be empty"); } // java.net.HttpURLConnection returns a *; q=.2 Accept header if (MimeType.WILDCARD_TYPE.equals(fullType)) { fullType = "*/*"; } int subIndex = fullType.indexOf('/'); if (subIndex == -1) { throw new InvalidMimeTypeException(mimeType, "does not contain '/'"); } if (subIndex == fullType.length() - 1) { throw new InvalidMimeTypeException(mimeType, "does not contain subtype after '/'"); } String type = fullType.substring(0, subIndex); String subtype = fullType.substring(subIndex + 1, fullType.length()); if (MimeType.WILDCARD_TYPE.equals(type) && !MimeType.WILDCARD_TYPE.equals(subtype)) { throw new InvalidMimeTypeException(mimeType, "wildcard type is legal only in '*/*' (all mime " + "types)"); } Map<String, String> parameters = null; do { int nextIndex = index + 1; boolean quoted = false; while (nextIndex < mimeType.length()) { char ch = mimeType.charAt(nextIndex); if (ch == ';') { if (!quoted) { break; } } else if (ch == '"') { // depends on control dependency: [if], data = [none] quoted = !quoted; // depends on control dependency: [if], data = [none] } nextIndex++; } String parameter = mimeType.substring(index + 1, nextIndex).trim(); if (parameter.length() > 0) { if (parameters == null) { parameters = new LinkedHashMap<>(4); } int eqIndex = parameter.indexOf('='); if (eqIndex >= 0) { String attribute = parameter.substring(0, eqIndex); String value = parameter.substring(eqIndex + 1, parameter.length()); parameters.put(attribute, value); } } index = nextIndex; } while (index < mimeType.length()); try { return new MimeType(type, subtype, parameters); } catch (UnsupportedCharsetException ex) { throw new InvalidMimeTypeException(mimeType, "unsupported charset '" + ex.getCharsetName() + "'"); } catch (IllegalArgumentException ex) { throw new InvalidMimeTypeException(mimeType, ex.getMessage()); } } }
public class class_name { public Archetype parse(String adl) { try { return parse(new StringReader(adl)); } catch (IOException e) { // StringReader should never throw an IOException throw new AssertionError(e); } } }
public class class_name { public Archetype parse(String adl) { try { return parse(new StringReader(adl)); // depends on control dependency: [try], data = [none] } catch (IOException e) { // StringReader should never throw an IOException throw new AssertionError(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static String replace(String inString, String oldPattern, String newPattern) { if (isEmpty(inString) || isEmpty(oldPattern) || newPattern == null) { return inString; } StringBuilder sbuf = new StringBuilder(); // output StringBuilder we'll build up int pos = 0; // our position in the old string int index = inString.indexOf(oldPattern); // the index of an occurrence we've found, or -1 int patLen = oldPattern.length(); while (index >= 0) { sbuf.append(inString.substring(pos, index)); sbuf.append(newPattern); pos = index + patLen; index = inString.indexOf(oldPattern, pos); } sbuf.append(inString.substring(pos)); // remember to append any characters to the right of a match return sbuf.toString(); } }
public class class_name { public static String replace(String inString, String oldPattern, String newPattern) { if (isEmpty(inString) || isEmpty(oldPattern) || newPattern == null) { return inString; // depends on control dependency: [if], data = [none] } StringBuilder sbuf = new StringBuilder(); // output StringBuilder we'll build up int pos = 0; // our position in the old string int index = inString.indexOf(oldPattern); // the index of an occurrence we've found, or -1 int patLen = oldPattern.length(); while (index >= 0) { sbuf.append(inString.substring(pos, index)); // depends on control dependency: [while], data = [none] sbuf.append(newPattern); // depends on control dependency: [while], data = [none] pos = index + patLen; // depends on control dependency: [while], data = [none] index = inString.indexOf(oldPattern, pos); // depends on control dependency: [while], data = [none] } sbuf.append(inString.substring(pos)); // remember to append any characters to the right of a match return sbuf.toString(); } }
public class class_name { public boolean remove(Object object) { sleeContainer.getTransactionManager().mandateTransaction(); if(logger.isDebugEnabled()) { logger.debug("removing sbb local object " + object); } if (object == null) throw new NullPointerException("Null arg for remove "); if (!(object instanceof SbbLocalObject)) return false; final SbbLocalObjectImpl sbbLocalObjectImpl = (SbbLocalObjectImpl) object; if(!idBelongsToChildRelation(sbbLocalObjectImpl.getSbbEntityId()) && !sbbLocalObjectImpl.getSbbEntity().isRemoved()) { return false; } else { sbbLocalObjectImpl.remove(); return true; } } }
public class class_name { public boolean remove(Object object) { sleeContainer.getTransactionManager().mandateTransaction(); if(logger.isDebugEnabled()) { logger.debug("removing sbb local object " + object); // depends on control dependency: [if], data = [none] } if (object == null) throw new NullPointerException("Null arg for remove "); if (!(object instanceof SbbLocalObject)) return false; final SbbLocalObjectImpl sbbLocalObjectImpl = (SbbLocalObjectImpl) object; if(!idBelongsToChildRelation(sbbLocalObjectImpl.getSbbEntityId()) && !sbbLocalObjectImpl.getSbbEntity().isRemoved()) { return false; // depends on control dependency: [if], data = [none] } else { sbbLocalObjectImpl.remove(); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } } }
public class class_name { public static Trajectory concactTrajectorie(Trajectory a, Trajectory b){ if(a.getDimension()!=b.getDimension()){ throw new IllegalArgumentException("Combination not possible: The trajectorys does not have the same dimension"); } Trajectory c = new Trajectory(a.getDimension()); for(int i = 0 ; i < a.size(); i++){ Point3d pos = new Point3d(a.get(i).x, a.get(i).y, a.get(i).z); c.add(pos); } double dx = a.get(a.size()-1).x - b.get(0).x; double dy = a.get(a.size()-1).y - b.get(0).y; double dz = a.get(a.size()-1).z - b.get(0).z; for(int i = 1 ; i < b.size(); i++){ Point3d pos = new Point3d(b.get(i).x+dx, b.get(i).y+dy, b.get(i).z+dz); c.add(pos); } return c; } }
public class class_name { public static Trajectory concactTrajectorie(Trajectory a, Trajectory b){ if(a.getDimension()!=b.getDimension()){ throw new IllegalArgumentException("Combination not possible: The trajectorys does not have the same dimension"); } Trajectory c = new Trajectory(a.getDimension()); for(int i = 0 ; i < a.size(); i++){ Point3d pos = new Point3d(a.get(i).x, a.get(i).y, a.get(i).z); c.add(pos); // depends on control dependency: [for], data = [none] } double dx = a.get(a.size()-1).x - b.get(0).x; double dy = a.get(a.size()-1).y - b.get(0).y; double dz = a.get(a.size()-1).z - b.get(0).z; for(int i = 1 ; i < b.size(); i++){ Point3d pos = new Point3d(b.get(i).x+dx, b.get(i).y+dy, b.get(i).z+dz); c.add(pos); // depends on control dependency: [for], data = [none] } return c; } }
public class class_name { private Map<Integer, Integer> getNodeIdToZonePrimaryCount(Cluster cluster, StoreRoutingPlan storeRoutingPlan) { Map<Integer, Integer> nodeIdToZonePrimaryCount = Maps.newHashMap(); for(Integer nodeId: cluster.getNodeIds()) { nodeIdToZonePrimaryCount.put(nodeId, storeRoutingPlan.getZonePrimaryPartitionIds(nodeId).size()); } return nodeIdToZonePrimaryCount; } }
public class class_name { private Map<Integer, Integer> getNodeIdToZonePrimaryCount(Cluster cluster, StoreRoutingPlan storeRoutingPlan) { Map<Integer, Integer> nodeIdToZonePrimaryCount = Maps.newHashMap(); for(Integer nodeId: cluster.getNodeIds()) { nodeIdToZonePrimaryCount.put(nodeId, storeRoutingPlan.getZonePrimaryPartitionIds(nodeId).size()); // depends on control dependency: [for], data = [nodeId] } return nodeIdToZonePrimaryCount; } }
public class class_name { public MACAddressSection toOUIPrefixBlock() { int ouiSegmentCount = getOUISegmentCount(); int segmentCount = getSegmentCount(); Integer currentPref = getPrefixLength(); int newPref = ouiSegmentCount << 3;//ouiSegmentCount * MACAddress.BITS_PER_SEGMENT boolean createNew; if(!(createNew = (currentPref == null || currentPref > newPref))) { newPref = currentPref; for(int i = ouiSegmentCount; i < segmentCount; i++) { MACAddressSegment segment = getSegment(i); if(!segment.isFullRange()) { createNew = true; break; } } } if(createNew) { MACAddressCreator creator = getAddressCreator(); MACAddressSegment allRangeSegment = creator.createRangeSegment(0, MACAddress.MAX_VALUE_PER_SEGMENT); MACAddressSegment newSegments[] = setPrefixedSegments( getNetwork(), newPref, getSegments(), //this clones MACAddress.BITS_PER_SEGMENT, MACAddress.BYTES_PER_SEGMENT, creator, (seg, prefixLength) -> (prefixLength == 0) ? allRangeSegment : seg); MACAddressSection result = creator.createSectionInternal(newSegments); result.assignPrefixLength(newPref); return result; } return this; } }
public class class_name { public MACAddressSection toOUIPrefixBlock() { int ouiSegmentCount = getOUISegmentCount(); int segmentCount = getSegmentCount(); Integer currentPref = getPrefixLength(); int newPref = ouiSegmentCount << 3;//ouiSegmentCount * MACAddress.BITS_PER_SEGMENT boolean createNew; if(!(createNew = (currentPref == null || currentPref > newPref))) { newPref = currentPref; // depends on control dependency: [if], data = [none] for(int i = ouiSegmentCount; i < segmentCount; i++) { MACAddressSegment segment = getSegment(i); if(!segment.isFullRange()) { createNew = true; // depends on control dependency: [if], data = [none] break; } } } if(createNew) { MACAddressCreator creator = getAddressCreator(); MACAddressSegment allRangeSegment = creator.createRangeSegment(0, MACAddress.MAX_VALUE_PER_SEGMENT); MACAddressSegment newSegments[] = setPrefixedSegments( getNetwork(), newPref, getSegments(), //this clones MACAddress.BITS_PER_SEGMENT, MACAddress.BYTES_PER_SEGMENT, creator, (seg, prefixLength) -> (prefixLength == 0) ? allRangeSegment : seg); MACAddressSection result = creator.createSectionInternal(newSegments); result.assignPrefixLength(newPref); // depends on control dependency: [if], data = [none] return result; // depends on control dependency: [if], data = [none] } return this; } }
public class class_name { public static int[] getOrder(int[] values, int[] indices, boolean descending) { // Create an index series: Integer[] opIndices = ArrayUtils.toObject(indices); // Sort indices: Arrays.sort(opIndices, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { if (descending) { return Double.compare(values[o2], values[o1]); } else { return Double.compare(values[o1], values[o2]); } } }); return ArrayUtils.toPrimitive(opIndices); } }
public class class_name { public static int[] getOrder(int[] values, int[] indices, boolean descending) { // Create an index series: Integer[] opIndices = ArrayUtils.toObject(indices); // Sort indices: Arrays.sort(opIndices, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { if (descending) { return Double.compare(values[o2], values[o1]); // depends on control dependency: [if], data = [none] } else { return Double.compare(values[o1], values[o2]); // depends on control dependency: [if], data = [none] } } }); return ArrayUtils.toPrimitive(opIndices); } }
public class class_name { public void closeAll(CmsDbContext dbc, Connection con, Statement stmnt, ResultSet res) { // NOTE: we have to close Connections/Statements that way, because a dbcp PoolablePreparedStatement // is not a DelegatedStatement; for that reason its not removed from the trace of the connection when it is closed. // So, the connection tries to close it again when the connection is closed itself; // as a result there is an error that forces the connection to be destroyed and not pooled if (dbc == null) { LOG.error(Messages.get().getBundle().key(Messages.LOG_NULL_DB_CONTEXT_0)); } try { // first, close the result set if (res != null) { res.close(); } } catch (SQLException e) { LOG.debug(e.getLocalizedMessage(), e); } finally { res = null; } try { // close the statement if (stmnt != null) { stmnt.close(); } } catch (SQLException e) { LOG.debug(e.getLocalizedMessage(), e); } finally { stmnt = null; } try { // close the connection if ((con != null) && !con.isClosed()) { con.close(); } } catch (SQLException e) { LOG.debug(e.getLocalizedMessage(), e); } finally { con = null; } } }
public class class_name { public void closeAll(CmsDbContext dbc, Connection con, Statement stmnt, ResultSet res) { // NOTE: we have to close Connections/Statements that way, because a dbcp PoolablePreparedStatement // is not a DelegatedStatement; for that reason its not removed from the trace of the connection when it is closed. // So, the connection tries to close it again when the connection is closed itself; // as a result there is an error that forces the connection to be destroyed and not pooled if (dbc == null) { LOG.error(Messages.get().getBundle().key(Messages.LOG_NULL_DB_CONTEXT_0)); // depends on control dependency: [if], data = [none] } try { // first, close the result set if (res != null) { res.close(); // depends on control dependency: [if], data = [none] } } catch (SQLException e) { LOG.debug(e.getLocalizedMessage(), e); } finally { // depends on control dependency: [catch], data = [none] res = null; } try { // close the statement if (stmnt != null) { stmnt.close(); // depends on control dependency: [if], data = [none] } } catch (SQLException e) { LOG.debug(e.getLocalizedMessage(), e); } finally { // depends on control dependency: [catch], data = [none] stmnt = null; } try { // close the connection if ((con != null) && !con.isClosed()) { con.close(); // depends on control dependency: [if], data = [none] } } catch (SQLException e) { LOG.debug(e.getLocalizedMessage(), e); } finally { // depends on control dependency: [catch], data = [none] con = null; } } }
public class class_name { public static <T extends Annotation> T getAnnotation(AnnotatedElement ae, Class<T> annotationType) { T ann = ae.getAnnotation(annotationType); if (ann == null) { for (Annotation metaAnn : ae.getAnnotations()) { ann = metaAnn.annotationType().getAnnotation(annotationType); if (ann != null) { break; } } } return ann; } }
public class class_name { public static <T extends Annotation> T getAnnotation(AnnotatedElement ae, Class<T> annotationType) { T ann = ae.getAnnotation(annotationType); if (ann == null) { for (Annotation metaAnn : ae.getAnnotations()) { ann = metaAnn.annotationType().getAnnotation(annotationType); // depends on control dependency: [for], data = [metaAnn] if (ann != null) { break; } } } return ann; } }
public class class_name { private static Object getPrivateAttributes(HttpServletRequest req, String key) { HttpServletRequest sr = req; if (sr instanceof HttpServletRequestWrapper) { HttpServletRequestWrapper w = (HttpServletRequestWrapper) sr; sr = (HttpServletRequest) w.getRequest(); while (sr != null && sr instanceof HttpServletRequestWrapper) sr = (HttpServletRequest) ((HttpServletRequestWrapper) sr).getRequest(); } if (sr != null && sr instanceof IPrivateRequestAttributes) { return ((IPrivateRequestAttributes) sr).getPrivateAttribute(key); } return null; } }
public class class_name { private static Object getPrivateAttributes(HttpServletRequest req, String key) { HttpServletRequest sr = req; if (sr instanceof HttpServletRequestWrapper) { HttpServletRequestWrapper w = (HttpServletRequestWrapper) sr; sr = (HttpServletRequest) w.getRequest(); // depends on control dependency: [if], data = [none] while (sr != null && sr instanceof HttpServletRequestWrapper) sr = (HttpServletRequest) ((HttpServletRequestWrapper) sr).getRequest(); } if (sr != null && sr instanceof IPrivateRequestAttributes) { return ((IPrivateRequestAttributes) sr).getPrivateAttribute(key); // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { @PublicAPI(usage = ACCESS) public JavaClasses importJars(Iterable<JarFile> jarFiles) { Set<Location> locations = new HashSet<>(); for (JarFile jarFile : jarFiles) { locations.add(Location.of(jarFile)); } return importLocations(locations); } }
public class class_name { @PublicAPI(usage = ACCESS) public JavaClasses importJars(Iterable<JarFile> jarFiles) { Set<Location> locations = new HashSet<>(); for (JarFile jarFile : jarFiles) { locations.add(Location.of(jarFile)); // depends on control dependency: [for], data = [jarFile] } return importLocations(locations); } }
public class class_name { public static String getExtensionValue(List extensions, String extensionName) { for (Object obj : extensions) { if (obj instanceof Extension) { Extension extension = (Extension) obj; if (extensionName.equalsIgnoreCase(extension.getName())) { return extension.getValue(); } } } return null; } }
public class class_name { public static String getExtensionValue(List extensions, String extensionName) { for (Object obj : extensions) { if (obj instanceof Extension) { Extension extension = (Extension) obj; if (extensionName.equalsIgnoreCase(extension.getName())) { return extension.getValue(); // depends on control dependency: [if], data = [none] } } } return null; } }
public class class_name { public static INDArrayIndex[] adjustIndices(int[] originalShape, INDArrayIndex... indexes) { if (Shape.isVector(originalShape) && indexes.length == 1) return indexes; if (indexes.length < originalShape.length) indexes = fillIn(originalShape, indexes); if (indexes.length > originalShape.length) { INDArrayIndex[] ret = new INDArrayIndex[originalShape.length]; System.arraycopy(indexes, 0, ret, 0, originalShape.length); return ret; } if (indexes.length == originalShape.length) return indexes; for (int i = 0; i < indexes.length; i++) { if (indexes[i].end() >= originalShape[i] || indexes[i] instanceof NDArrayIndexAll) indexes[i] = NDArrayIndex.interval(0, originalShape[i] - 1); } return indexes; } }
public class class_name { public static INDArrayIndex[] adjustIndices(int[] originalShape, INDArrayIndex... indexes) { if (Shape.isVector(originalShape) && indexes.length == 1) return indexes; if (indexes.length < originalShape.length) indexes = fillIn(originalShape, indexes); if (indexes.length > originalShape.length) { INDArrayIndex[] ret = new INDArrayIndex[originalShape.length]; System.arraycopy(indexes, 0, ret, 0, originalShape.length); // depends on control dependency: [if], data = [originalShape.length)] return ret; // depends on control dependency: [if], data = [none] } if (indexes.length == originalShape.length) return indexes; for (int i = 0; i < indexes.length; i++) { if (indexes[i].end() >= originalShape[i] || indexes[i] instanceof NDArrayIndexAll) indexes[i] = NDArrayIndex.interval(0, originalShape[i] - 1); } return indexes; } }
public class class_name { @UiThread public List<Fill> create(@NonNull FeatureCollection featureCollection) { List<Feature> features = featureCollection.features(); List<FillOptions> options = new ArrayList<>(); if (features != null) { for (Feature feature : features) { FillOptions option = FillOptions.fromFeature(feature); if (option != null) { options.add(option); } } } return create(options); } }
public class class_name { @UiThread public List<Fill> create(@NonNull FeatureCollection featureCollection) { List<Feature> features = featureCollection.features(); List<FillOptions> options = new ArrayList<>(); if (features != null) { for (Feature feature : features) { FillOptions option = FillOptions.fromFeature(feature); if (option != null) { options.add(option); // depends on control dependency: [if], data = [(option] } } } return create(options); } }
public class class_name { private static ExpressionTree getNullCheckedExpression(ExpressionTree condition) { condition = stripParentheses(condition); if (!(condition instanceof BinaryTree)) { return null; } BinaryTree bin = (BinaryTree) condition; ExpressionTree other; if (bin.getLeftOperand().getKind() == Kind.NULL_LITERAL) { other = bin.getRightOperand(); } else if (bin.getRightOperand().getKind() == Kind.NULL_LITERAL) { other = bin.getLeftOperand(); } else { return null; } return other; } }
public class class_name { private static ExpressionTree getNullCheckedExpression(ExpressionTree condition) { condition = stripParentheses(condition); if (!(condition instanceof BinaryTree)) { return null; // depends on control dependency: [if], data = [none] } BinaryTree bin = (BinaryTree) condition; ExpressionTree other; if (bin.getLeftOperand().getKind() == Kind.NULL_LITERAL) { other = bin.getRightOperand(); // depends on control dependency: [if], data = [none] } else if (bin.getRightOperand().getKind() == Kind.NULL_LITERAL) { other = bin.getLeftOperand(); // depends on control dependency: [if], data = [none] } else { return null; // depends on control dependency: [if], data = [none] } return other; } }
public class class_name { @Deactivate protected void deactivate(Map<String, Object> properties, int reason) { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(this, tc, "HttpDispatcher deactivated, id=" + properties.get(ComponentConstants.COMPONENT_ID) + ",reason=" + reason); } // Clear this as the active HttpDispatcher instance (unless another has already replaced) instance.get().compareAndSet(this, null); } }
public class class_name { @Deactivate protected void deactivate(Map<String, Object> properties, int reason) { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(this, tc, "HttpDispatcher deactivated, id=" + properties.get(ComponentConstants.COMPONENT_ID) + ",reason=" + reason); // depends on control dependency: [if], data = [none] } // Clear this as the active HttpDispatcher instance (unless another has already replaced) instance.get().compareAndSet(this, null); } }
public class class_name { ActiveFile getOngoingCreates(int namespaceId, Block block) { checkBlock(block); NamespaceMap nm = getNamespaceMap(namespaceId); if (nm == null) { return null; } return nm.getOngoingCreates(block); } }
public class class_name { ActiveFile getOngoingCreates(int namespaceId, Block block) { checkBlock(block); NamespaceMap nm = getNamespaceMap(namespaceId); if (nm == null) { return null; // depends on control dependency: [if], data = [none] } return nm.getOngoingCreates(block); } }
public class class_name { protected void extractDynamicName(Tag tag, CharSequence name, OutParameter<String> dynamicName) { if (tag.hasDynamicName()) { final Pattern pattern = Pattern.compile(getDynamicNameExtractionPattern()); final Matcher matcher = pattern.matcher(name); if (matcher.matches()) { dynamicName.set(Strings.nullToEmpty(matcher.group(1))); return; } } dynamicName.set(name.toString()); } }
public class class_name { protected void extractDynamicName(Tag tag, CharSequence name, OutParameter<String> dynamicName) { if (tag.hasDynamicName()) { final Pattern pattern = Pattern.compile(getDynamicNameExtractionPattern()); final Matcher matcher = pattern.matcher(name); if (matcher.matches()) { dynamicName.set(Strings.nullToEmpty(matcher.group(1))); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } } dynamicName.set(name.toString()); } }
public class class_name { public static double nextDouble(final double startInclusive, final double endInclusive) { Validate.isTrue(endInclusive >= startInclusive, "Start value must be smaller or equal to end value."); Validate.isTrue(startInclusive >= 0, "Both range values must be non-negative."); if (startInclusive == endInclusive) { return startInclusive; } return startInclusive + ((endInclusive - startInclusive) * RANDOM.nextDouble()); } }
public class class_name { public static double nextDouble(final double startInclusive, final double endInclusive) { Validate.isTrue(endInclusive >= startInclusive, "Start value must be smaller or equal to end value."); Validate.isTrue(startInclusive >= 0, "Both range values must be non-negative."); if (startInclusive == endInclusive) { return startInclusive; // depends on control dependency: [if], data = [none] } return startInclusive + ((endInclusive - startInclusive) * RANDOM.nextDouble()); } }
public class class_name { public ScanWriter createScanWriter(final int taskId, Set<ScanDestination> destinations) { checkArgument(!destinations.isEmpty(), "destinations.isEmpty()"); if (destinations.size() == 1) { return createScanWriter(taskId, Iterables.getOnlyElement(destinations)); } return new MultiScanWriter(ImmutableList.copyOf( Iterables.transform(destinations, new Function<ScanDestination, ScanWriter>() { @Override public ScanWriter apply(ScanDestination destination) { return createScanWriter(taskId, destination); } }) )); } }
public class class_name { public ScanWriter createScanWriter(final int taskId, Set<ScanDestination> destinations) { checkArgument(!destinations.isEmpty(), "destinations.isEmpty()"); if (destinations.size() == 1) { return createScanWriter(taskId, Iterables.getOnlyElement(destinations)); // depends on control dependency: [if], data = [none] } return new MultiScanWriter(ImmutableList.copyOf( Iterables.transform(destinations, new Function<ScanDestination, ScanWriter>() { @Override public ScanWriter apply(ScanDestination destination) { return createScanWriter(taskId, destination); } }) )); } }
public class class_name { @Override public Url mapHandler(final IRequestHandler handler) { for (final IRequestMapper requestMapper : this.requestMappers) { final Url url = requestMapper.mapHandler(handler); if (url != null) { return url; } } return null; } }
public class class_name { @Override public Url mapHandler(final IRequestHandler handler) { for (final IRequestMapper requestMapper : this.requestMappers) { final Url url = requestMapper.mapHandler(handler); if (url != null) { return url; // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { public void create() { RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId(amiId).withInstanceType(size).withKeyName(keyPair) .withMinCount(1).withSecurityGroupIds(securityGroupId).withMaxCount(numBoxes); AmazonEC2 ec2 = getEc2(); ec2.setRegion(com.amazonaws.regions.Region.getRegion(regions)); List<Instance> boxes = ec2.runInstances(runInstancesRequest).getReservation().getInstances(); if (boxesCreated == null) { boxesCreated = new ArrayList<>(); for (Instance i : boxes) boxesCreated.add(i.getInstanceId()); log.info("Boxes created " + boxesCreated); } else { blowupBoxes(); boxesCreated.clear(); for (Instance i : boxes) boxesCreated.add(i.getInstanceId()); } } }
public class class_name { public void create() { RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId(amiId).withInstanceType(size).withKeyName(keyPair) .withMinCount(1).withSecurityGroupIds(securityGroupId).withMaxCount(numBoxes); AmazonEC2 ec2 = getEc2(); ec2.setRegion(com.amazonaws.regions.Region.getRegion(regions)); List<Instance> boxes = ec2.runInstances(runInstancesRequest).getReservation().getInstances(); if (boxesCreated == null) { boxesCreated = new ArrayList<>(); // depends on control dependency: [if], data = [none] for (Instance i : boxes) boxesCreated.add(i.getInstanceId()); log.info("Boxes created " + boxesCreated); // depends on control dependency: [if], data = [none] } else { blowupBoxes(); // depends on control dependency: [if], data = [none] boxesCreated.clear(); // depends on control dependency: [if], data = [none] for (Instance i : boxes) boxesCreated.add(i.getInstanceId()); } } }
public class class_name { private boolean checkFreeSlotAt(final long sequence) { final long wrapPoint = sequence - bufferSize; if (wrapPoint > flushSequence.get()) { // 刚好追上一轮 return false; } else { return true; } } }
public class class_name { private boolean checkFreeSlotAt(final long sequence) { final long wrapPoint = sequence - bufferSize; if (wrapPoint > flushSequence.get()) { // 刚好追上一轮 return false; // depends on control dependency: [if], data = [none] } else { return true; // depends on control dependency: [if], data = [none] } } }
public class class_name { public static Bits toBits(Consumer<BitOutputStream> fn) { try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); BitOutputStream out = new BitOutputStream(buffer); fn.accept(out); out.flush(); return new Bits(buffer.toByteArray(), out.getTotalBitsWritten()); } catch (IOException e) { throw new RuntimeException(e); } } }
public class class_name { public static Bits toBits(Consumer<BitOutputStream> fn) { try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); BitOutputStream out = new BitOutputStream(buffer); fn.accept(out); // depends on control dependency: [try], data = [none] out.flush(); // depends on control dependency: [try], data = [none] return new Bits(buffer.toByteArray(), out.getTotalBitsWritten()); // depends on control dependency: [try], data = [none] } catch (IOException e) { throw new RuntimeException(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public UserDetails loadUserDetails(OpenIDAuthenticationToken token) { String id = token.getIdentityUrl(); CustomUserDetails user = registeredUsers.get(id); if (user != null) { return user; } String email = null; String firstName = null; String lastName = null; String fullName = null; List<OpenIDAttribute> attributes = token.getAttributes(); for (OpenIDAttribute attribute : attributes) { if (attribute.getName().equals("email")) { email = attribute.getValues().get(0); } if (attribute.getName().equals("firstname")) { firstName = attribute.getValues().get(0); } if (attribute.getName().equals("lastname")) { lastName = attribute.getValues().get(0); } if (attribute.getName().equals("fullname")) { fullName = attribute.getValues().get(0); } } if (fullName == null) { StringBuilder fullNameBldr = new StringBuilder(); if (firstName != null) { fullNameBldr.append(firstName); } if (lastName != null) { fullNameBldr.append(" ").append(lastName); } fullName = fullNameBldr.toString(); } user = new CustomUserDetails(id, DEFAULT_AUTHORITIES); user.setEmail(email); user.setName(fullName); registeredUsers.put(id, user); user = new CustomUserDetails(id, DEFAULT_AUTHORITIES); user.setEmail(email); user.setName(fullName); user.setNewUser(true); return user; } }
public class class_name { public UserDetails loadUserDetails(OpenIDAuthenticationToken token) { String id = token.getIdentityUrl(); CustomUserDetails user = registeredUsers.get(id); if (user != null) { return user; // depends on control dependency: [if], data = [none] } String email = null; String firstName = null; String lastName = null; String fullName = null; List<OpenIDAttribute> attributes = token.getAttributes(); for (OpenIDAttribute attribute : attributes) { if (attribute.getName().equals("email")) { email = attribute.getValues().get(0); // depends on control dependency: [if], data = [none] } if (attribute.getName().equals("firstname")) { firstName = attribute.getValues().get(0); // depends on control dependency: [if], data = [none] } if (attribute.getName().equals("lastname")) { lastName = attribute.getValues().get(0); // depends on control dependency: [if], data = [none] } if (attribute.getName().equals("fullname")) { fullName = attribute.getValues().get(0); // depends on control dependency: [if], data = [none] } } if (fullName == null) { StringBuilder fullNameBldr = new StringBuilder(); if (firstName != null) { fullNameBldr.append(firstName); // depends on control dependency: [if], data = [(firstName] } if (lastName != null) { fullNameBldr.append(" ").append(lastName); // depends on control dependency: [if], data = [(lastName] } fullName = fullNameBldr.toString(); // depends on control dependency: [if], data = [none] } user = new CustomUserDetails(id, DEFAULT_AUTHORITIES); user.setEmail(email); user.setName(fullName); registeredUsers.put(id, user); user = new CustomUserDetails(id, DEFAULT_AUTHORITIES); user.setEmail(email); user.setName(fullName); user.setNewUser(true); return user; } }
public class class_name { public static void applyChange(IDatabase db, Change change) { if (isApplicable(change)) { ITextNode textNode = db.getTextNode(change.getKey()); if (textNode != null) { // textNode would be null for TYPE_KEY_ADDITION String language = change.getLanguage(); IValueNode valueNode = textNode.getValueNode(language); if (valueNode != null) { // valueNode would be null for TYPE_LANGUAGE_ADDITION valueNode.setStatus(change.getAcceptStatus()); valueNode.setValue(change.getAcceptValue()); } if (change.hasMasterLanguage()) { String masterLanguage = change.getMasterLanguage(); IValueNode masterValueNode = textNode.getValueNode(masterLanguage); if (masterValueNode != null) { // masterValueNode would be null for TYPE_MASTER_LANGUAGE_ADDITION masterValueNode.setValue(change.getAcceptMasterValue()); } } } } } }
public class class_name { public static void applyChange(IDatabase db, Change change) { if (isApplicable(change)) { ITextNode textNode = db.getTextNode(change.getKey()); if (textNode != null) { // textNode would be null for TYPE_KEY_ADDITION String language = change.getLanguage(); IValueNode valueNode = textNode.getValueNode(language); if (valueNode != null) { // valueNode would be null for TYPE_LANGUAGE_ADDITION valueNode.setStatus(change.getAcceptStatus()); // depends on control dependency: [if], data = [none] valueNode.setValue(change.getAcceptValue()); // depends on control dependency: [if], data = [none] } if (change.hasMasterLanguage()) { String masterLanguage = change.getMasterLanguage(); IValueNode masterValueNode = textNode.getValueNode(masterLanguage); if (masterValueNode != null) { // masterValueNode would be null for TYPE_MASTER_LANGUAGE_ADDITION masterValueNode.setValue(change.getAcceptMasterValue()); // depends on control dependency: [if], data = [none] } } } } } }
public class class_name { public boolean createConfigurationXML() { errors = new ConfigVerification(); xmlConfig = new StringBuilder(); xmlConfig.append("<config>\r\n"); components.toXML(xmlConfig, errors); xmlConfig.append("</config>\r\n"); if (errors.getRowCount() != 0) { // TODO: invoke the dialog at another place new ConfigDialog(this).setVisible(true); return false; } return true; } }
public class class_name { public boolean createConfigurationXML() { errors = new ConfigVerification(); xmlConfig = new StringBuilder(); xmlConfig.append("<config>\r\n"); components.toXML(xmlConfig, errors); xmlConfig.append("</config>\r\n"); if (errors.getRowCount() != 0) { // TODO: invoke the dialog at another place new ConfigDialog(this).setVisible(true); // depends on control dependency: [if], data = [none] return false; // depends on control dependency: [if], data = [none] } return true; } }
public class class_name { public String capitalize(final Object target) { if (target == null) { return null; } return StringUtils.capitalize(target); } }
public class class_name { public String capitalize(final Object target) { if (target == null) { return null; // depends on control dependency: [if], data = [none] } return StringUtils.capitalize(target); } }
public class class_name { protected void variableCreated(Type type) { char charType = type.getDescriptor().charAt(0); if (charType == 'J' || charType == 'D') { this.methodOffset += 2; } else { this.methodOffset += 1; } } }
public class class_name { protected void variableCreated(Type type) { char charType = type.getDescriptor().charAt(0); if (charType == 'J' || charType == 'D') { this.methodOffset += 2; // depends on control dependency: [if], data = [none] } else { this.methodOffset += 1; // depends on control dependency: [if], data = [none] } } }
public class class_name { public void notifyError( URL resource, String message ) { synchronized( m_Monitors ) { for( StreamMonitor monitor : m_Monitors ) { monitor.notifyError( resource, message ); } } } }
public class class_name { public void notifyError( URL resource, String message ) { synchronized( m_Monitors ) { for( StreamMonitor monitor : m_Monitors ) { monitor.notifyError( resource, message ); // depends on control dependency: [for], data = [monitor] } } } }
public class class_name { public void marshall(RespondActivityTaskCompletedRequest respondActivityTaskCompletedRequest, ProtocolMarshaller protocolMarshaller) { if (respondActivityTaskCompletedRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(respondActivityTaskCompletedRequest.getTaskToken(), TASKTOKEN_BINDING); protocolMarshaller.marshall(respondActivityTaskCompletedRequest.getResult(), RESULT_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(RespondActivityTaskCompletedRequest respondActivityTaskCompletedRequest, ProtocolMarshaller protocolMarshaller) { if (respondActivityTaskCompletedRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(respondActivityTaskCompletedRequest.getTaskToken(), TASKTOKEN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(respondActivityTaskCompletedRequest.getResult(), RESULT_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 { protected void updateOverwriteExisting() { if (m_overwriteExisting != null) { boolean move = (m_dialogMode == DialogMode.move) || (m_actionCombo.getValue() == Action.move); if (move) { m_overwriteExisting.setValue(Boolean.FALSE); m_overwriteExisting.setVisible(false); } else { m_overwriteExisting.setVisible(true); } } } }
public class class_name { protected void updateOverwriteExisting() { if (m_overwriteExisting != null) { boolean move = (m_dialogMode == DialogMode.move) || (m_actionCombo.getValue() == Action.move); if (move) { m_overwriteExisting.setValue(Boolean.FALSE); // depends on control dependency: [if], data = [none] m_overwriteExisting.setVisible(false); // depends on control dependency: [if], data = [none] } else { m_overwriteExisting.setVisible(true); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public final V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (Thread.interrupted()) throw new InterruptedException(); // Messy in part because we measure in nanosecs, but wait in millisecs int s; long ns, ms; if ((s = status) >= 0 && (ns = unit.toNanos(timeout)) > 0L) { long deadline = System.nanoTime() + ns; ForkJoinPool p = null; ForkJoinPool.WorkQueue w = null; Thread t = Thread.currentThread(); if (t instanceof ForkJoinWorkerThread) { ForkJoinWorkerThread wt = (ForkJoinWorkerThread)t; p = wt.pool; w = wt.workQueue; s = p.helpJoinOnce(w, this); // no retries on failure } boolean canBlock = false; boolean interrupted = false; try { while ((s = status) >= 0) { if (w != null && w.runState < 0) cancelIgnoringExceptions(this); else if (!canBlock) { if (p == null || p.tryCompensate(this, null)) canBlock = true; } else { if ((ms = TimeUnit.NANOSECONDS.toMillis(ns)) > 0L && U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) { synchronized (this) { if (status >= 0) { try { wait(ms); } catch (InterruptedException ie) { if (p == null) interrupted = true; } } else notifyAll(); } } if ((s = status) < 0 || interrupted || (ns = deadline - System.nanoTime()) <= 0L) break; } } } finally { if (p != null && canBlock) p.incrementActiveCount(); } if (interrupted) throw new InterruptedException(); } if ((s &= DONE_MASK) != NORMAL) { Throwable ex; if (s == CANCELLED) throw new CancellationException(); if (s != EXCEPTIONAL) throw new TimeoutException(); if ((ex = getThrowableException()) != null) throw new ExecutionException(ex); } return getRawResult(); } }
public class class_name { public final V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (Thread.interrupted()) throw new InterruptedException(); // Messy in part because we measure in nanosecs, but wait in millisecs int s; long ns, ms; if ((s = status) >= 0 && (ns = unit.toNanos(timeout)) > 0L) { long deadline = System.nanoTime() + ns; ForkJoinPool p = null; ForkJoinPool.WorkQueue w = null; Thread t = Thread.currentThread(); if (t instanceof ForkJoinWorkerThread) { ForkJoinWorkerThread wt = (ForkJoinWorkerThread)t; p = wt.pool; // depends on control dependency: [if], data = [none] w = wt.workQueue; // depends on control dependency: [if], data = [none] s = p.helpJoinOnce(w, this); // no retries on failure // depends on control dependency: [if], data = [none] } boolean canBlock = false; boolean interrupted = false; try { while ((s = status) >= 0) { if (w != null && w.runState < 0) cancelIgnoringExceptions(this); else if (!canBlock) { if (p == null || p.tryCompensate(this, null)) canBlock = true; } else { if ((ms = TimeUnit.NANOSECONDS.toMillis(ns)) > 0L && U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) { synchronized (this) { // depends on control dependency: [if], data = [none] if (status >= 0) { try { wait(ms); // depends on control dependency: [try], data = [none] } catch (InterruptedException ie) { if (p == null) interrupted = true; } // depends on control dependency: [catch], data = [none] } else notifyAll(); } } if ((s = status) < 0 || interrupted || (ns = deadline - System.nanoTime()) <= 0L) break; } } } finally { if (p != null && canBlock) p.incrementActiveCount(); } if (interrupted) throw new InterruptedException(); } if ((s &= DONE_MASK) != NORMAL) { Throwable ex; if (s == CANCELLED) throw new CancellationException(); if (s != EXCEPTIONAL) throw new TimeoutException(); if ((ex = getThrowableException()) != null) throw new ExecutionException(ex); } return getRawResult(); } }
public class class_name { private static <T extends MPBase> JsonObject generatePayload(HttpMethod httpMethod, T resource) { JsonObject payload = null; if (httpMethod.equals(HttpMethod.POST) || (httpMethod.equals(HttpMethod.PUT) && resource._lastKnownJson == null)) { payload = MPCoreUtils.getJsonFromResource(resource); } else if (httpMethod.equals(HttpMethod.PUT)) { JsonObject actualJson = MPCoreUtils.getJsonFromResource(resource); Type mapType = new TypeToken<Map<String, Object>>(){}.getType(); Gson gson = new Gson(); Map<String, Object> oldMap = gson.fromJson(resource._lastKnownJson, mapType); Map<String, Object> newMap = gson.fromJson(actualJson, mapType); MapDifference<String, Object> mapDifferences = Maps.difference(oldMap, newMap); payload = new JsonObject(); for (Map.Entry<String, MapDifference.ValueDifference<Object>> entry : mapDifferences.entriesDiffering().entrySet()) { if (entry.getValue().rightValue() instanceof LinkedTreeMap) { JsonElement jsonObject = gson.toJsonTree(entry.getValue().rightValue()).getAsJsonObject(); payload.add(entry.getKey(), jsonObject); } else { if (entry.getValue().rightValue() instanceof Boolean) { payload.addProperty(entry.getKey(), (Boolean)entry.getValue().rightValue()); } else if (entry.getValue().rightValue() instanceof Number) { payload.addProperty(entry.getKey(), (Number)entry.getValue().rightValue()); } else { payload.addProperty(entry.getKey(), entry.getValue().rightValue().toString()); } } } for (Map.Entry<String, Object> entry : mapDifferences.entriesOnlyOnRight().entrySet()) { if (entry.getValue() instanceof Boolean) { payload.addProperty(entry.getKey(), (Boolean)entry.getValue()); } else if (entry.getValue() instanceof Number) { payload.addProperty(entry.getKey(), (Number)entry.getValue()); } else { payload.addProperty(entry.getKey(), entry.getValue().toString()); } } } return payload; } }
public class class_name { private static <T extends MPBase> JsonObject generatePayload(HttpMethod httpMethod, T resource) { JsonObject payload = null; if (httpMethod.equals(HttpMethod.POST) || (httpMethod.equals(HttpMethod.PUT) && resource._lastKnownJson == null)) { payload = MPCoreUtils.getJsonFromResource(resource); // depends on control dependency: [if], data = [none] } else if (httpMethod.equals(HttpMethod.PUT)) { JsonObject actualJson = MPCoreUtils.getJsonFromResource(resource); Type mapType = new TypeToken<Map<String, Object>>(){}.getType(); Gson gson = new Gson(); Map<String, Object> oldMap = gson.fromJson(resource._lastKnownJson, mapType); Map<String, Object> newMap = gson.fromJson(actualJson, mapType); MapDifference<String, Object> mapDifferences = Maps.difference(oldMap, newMap); payload = new JsonObject(); // depends on control dependency: [if], data = [none] for (Map.Entry<String, MapDifference.ValueDifference<Object>> entry : mapDifferences.entriesDiffering().entrySet()) { if (entry.getValue().rightValue() instanceof LinkedTreeMap) { JsonElement jsonObject = gson.toJsonTree(entry.getValue().rightValue()).getAsJsonObject(); payload.add(entry.getKey(), jsonObject); // depends on control dependency: [if], data = [none] } else { if (entry.getValue().rightValue() instanceof Boolean) { payload.addProperty(entry.getKey(), (Boolean)entry.getValue().rightValue()); // depends on control dependency: [if], data = [none] } else if (entry.getValue().rightValue() instanceof Number) { payload.addProperty(entry.getKey(), (Number)entry.getValue().rightValue()); // depends on control dependency: [if], data = [none] } else { payload.addProperty(entry.getKey(), entry.getValue().rightValue().toString()); // depends on control dependency: [if], data = [none] } } } for (Map.Entry<String, Object> entry : mapDifferences.entriesOnlyOnRight().entrySet()) { if (entry.getValue() instanceof Boolean) { payload.addProperty(entry.getKey(), (Boolean)entry.getValue()); // depends on control dependency: [if], data = [none] } else if (entry.getValue() instanceof Number) { payload.addProperty(entry.getKey(), (Number)entry.getValue()); // depends on control dependency: [if], data = [none] } else { payload.addProperty(entry.getKey(), entry.getValue().toString()); // depends on control dependency: [if], data = [none] } } } return payload; } }
public class class_name { public String findInContent(String content) { // First check for a simple exact occurrence for (BoyerMooreMatcher matcher : strings) { if (matcher.findInContent(content) >= 0) return matcher.getPattern(); } // Then check for a regex occurrence Matcher matcher; for (Pattern pattern : patterns) { matcher = pattern.matcher(content); if (matcher.find()) { return matcher.group(); } } // No match found return null return null; } }
public class class_name { public String findInContent(String content) { // First check for a simple exact occurrence for (BoyerMooreMatcher matcher : strings) { if (matcher.findInContent(content) >= 0) return matcher.getPattern(); } // Then check for a regex occurrence Matcher matcher; for (Pattern pattern : patterns) { matcher = pattern.matcher(content); // depends on control dependency: [for], data = [pattern] if (matcher.find()) { return matcher.group(); // depends on control dependency: [if], data = [none] } } // No match found return null return null; } }
public class class_name { @Bind(id = "exportDeclarations", specification = ExportDeclaration.class, aggregate = true, optional = true) void bindExportDeclaration(ServiceReference<ExportDeclaration> exportDeclarationSRef) { synchronized (lock) { declarationsManager.add(exportDeclarationSRef); LOG.debug(linkerName + " : Bind the ExportDeclaration " + declarationsManager.getDeclaration(exportDeclarationSRef)); if (!declarationsManager.matched(exportDeclarationSRef)) { return; } declarationsManager.createLinks(exportDeclarationSRef); } } }
public class class_name { @Bind(id = "exportDeclarations", specification = ExportDeclaration.class, aggregate = true, optional = true) void bindExportDeclaration(ServiceReference<ExportDeclaration> exportDeclarationSRef) { synchronized (lock) { declarationsManager.add(exportDeclarationSRef); LOG.debug(linkerName + " : Bind the ExportDeclaration " + declarationsManager.getDeclaration(exportDeclarationSRef)); if (!declarationsManager.matched(exportDeclarationSRef)) { return; // depends on control dependency: [if], data = [none] } declarationsManager.createLinks(exportDeclarationSRef); } } }
public class class_name { public ArrayList<String> collections() { string_vector v = ti.collections(); int size = (int) v.size(); ArrayList<String> l = new ArrayList<>(size); for (int i = 0; i < size; i++) { l.add(v.get(i)); } return l; } }
public class class_name { public ArrayList<String> collections() { string_vector v = ti.collections(); int size = (int) v.size(); ArrayList<String> l = new ArrayList<>(size); for (int i = 0; i < size; i++) { l.add(v.get(i)); // depends on control dependency: [for], data = [i] } return l; } }
public class class_name { private static Field getCachedTypemapFieldFor(Class<?> key) { if (key == null) { return null; } lock.lock(); try { // Must use containsKey because we do store null values for when the class has no // JsonPolymorphicTypeMap field. if (cachedTypemapFields.containsKey(key)) { return cachedTypemapFields.get(key); } // Find the field that determines the type and cache it. Field value = null; Collection<FieldInfo> fieldInfos = ClassInfo.of(key).getFieldInfos(); for (FieldInfo fieldInfo : fieldInfos) { Field field = fieldInfo.getField(); JsonPolymorphicTypeMap typemapAnnotation = field.getAnnotation(JsonPolymorphicTypeMap.class); if (typemapAnnotation != null) { Preconditions.checkArgument( value == null, "Class contains more than one field with @JsonPolymorphicTypeMap annotation: %s", key); Preconditions.checkArgument( Data.isPrimitive(field.getType()), "Field which has the @JsonPolymorphicTypeMap, %s, is not a supported type: %s", key, field.getType()); value = field; // Check for duplicate typeDef keys TypeDef[] typeDefs = typemapAnnotation.typeDefinitions(); HashSet<String> typeDefKeys = Sets.newHashSet(); Preconditions.checkArgument( typeDefs.length > 0, "@JsonPolymorphicTypeMap must have at least one @TypeDef"); for (TypeDef typeDef : typeDefs) { Preconditions.checkArgument( typeDefKeys.add(typeDef.key()), "Class contains two @TypeDef annotations with identical key: %s", typeDef.key()); } } } cachedTypemapFields.put(key, value); return value; } finally { lock.unlock(); } } }
public class class_name { private static Field getCachedTypemapFieldFor(Class<?> key) { if (key == null) { return null; // depends on control dependency: [if], data = [none] } lock.lock(); try { // Must use containsKey because we do store null values for when the class has no // JsonPolymorphicTypeMap field. if (cachedTypemapFields.containsKey(key)) { return cachedTypemapFields.get(key); // depends on control dependency: [if], data = [none] } // Find the field that determines the type and cache it. Field value = null; Collection<FieldInfo> fieldInfos = ClassInfo.of(key).getFieldInfos(); for (FieldInfo fieldInfo : fieldInfos) { Field field = fieldInfo.getField(); JsonPolymorphicTypeMap typemapAnnotation = field.getAnnotation(JsonPolymorphicTypeMap.class); if (typemapAnnotation != null) { Preconditions.checkArgument( value == null, "Class contains more than one field with @JsonPolymorphicTypeMap annotation: %s", key); Preconditions.checkArgument( Data.isPrimitive(field.getType()), "Field which has the @JsonPolymorphicTypeMap, %s, is not a supported type: %s", key, field.getType()); // depends on control dependency: [if], data = [none] value = field; // depends on control dependency: [if], data = [none] // Check for duplicate typeDef keys TypeDef[] typeDefs = typemapAnnotation.typeDefinitions(); HashSet<String> typeDefKeys = Sets.newHashSet(); Preconditions.checkArgument( typeDefs.length > 0, "@JsonPolymorphicTypeMap must have at least one @TypeDef"); for (TypeDef typeDef : typeDefs) { Preconditions.checkArgument( typeDefKeys.add(typeDef.key()), "Class contains two @TypeDef annotations with identical key: %s", typeDef.key()); // depends on control dependency: [for], data = [none] } } } cachedTypemapFields.put(key, value); // depends on control dependency: [try], data = [none] return value; // depends on control dependency: [try], data = [none] } finally { lock.unlock(); } } }
public class class_name { @SuppressWarnings("WeakerAccess") protected final void addAnnotation(String annotation, Map<CharSequence, Object> values) { if (annotation != null) { String repeatedName = getRepeatedName(annotation); Object v = values.get(AnnotationMetadata.VALUE_MEMBER); if (v instanceof io.micronaut.core.annotation.AnnotationValue[]) { io.micronaut.core.annotation.AnnotationValue[] avs = (io.micronaut.core.annotation.AnnotationValue[]) v; for (io.micronaut.core.annotation.AnnotationValue av : avs) { addRepeatable(annotation, av); } } else if (v instanceof Iterable && repeatedName != null) { Iterable i = (Iterable) v; for (Object o : i) { if (o instanceof io.micronaut.core.annotation.AnnotationValue) { addRepeatable(annotation, ((io.micronaut.core.annotation.AnnotationValue) o)); } } } else { Map<String, Map<CharSequence, Object>> allAnnotations = getAllAnnotations(); addAnnotation(annotation, values, null, allAnnotations, false); } } } }
public class class_name { @SuppressWarnings("WeakerAccess") protected final void addAnnotation(String annotation, Map<CharSequence, Object> values) { if (annotation != null) { String repeatedName = getRepeatedName(annotation); Object v = values.get(AnnotationMetadata.VALUE_MEMBER); if (v instanceof io.micronaut.core.annotation.AnnotationValue[]) { io.micronaut.core.annotation.AnnotationValue[] avs = (io.micronaut.core.annotation.AnnotationValue[]) v; for (io.micronaut.core.annotation.AnnotationValue av : avs) { addRepeatable(annotation, av); // depends on control dependency: [for], data = [av] } } else if (v instanceof Iterable && repeatedName != null) { Iterable i = (Iterable) v; for (Object o : i) { if (o instanceof io.micronaut.core.annotation.AnnotationValue) { addRepeatable(annotation, ((io.micronaut.core.annotation.AnnotationValue) o)); // depends on control dependency: [if], data = [none] } } } else { Map<String, Map<CharSequence, Object>> allAnnotations = getAllAnnotations(); addAnnotation(annotation, values, null, allAnnotations, false); // depends on control dependency: [if], data = [none] } } } }
public class class_name { protected boolean isDirectory(Resource directory) { if (directory.exists()) return directory.isDirectory(); try { directory.createDirectory(true); return true; } catch (IOException e) { e.printStackTrace(getErrWriter()); } return false; } }
public class class_name { protected boolean isDirectory(Resource directory) { if (directory.exists()) return directory.isDirectory(); try { directory.createDirectory(true); // depends on control dependency: [try], data = [none] return true; // depends on control dependency: [try], data = [none] } catch (IOException e) { e.printStackTrace(getErrWriter()); } // depends on control dependency: [catch], data = [none] return false; } }
public class class_name { private DocletTag findParamDocByNameOrIndex(String name, int paramIndex, List<DocletTag> tags) { for (DocletTag tag : tags) { if (name.equals(tag.getParameters().get(0))) { return tag; } } if (paramIndex < tags.size()) { return tags.get(paramIndex); } return null; } }
public class class_name { private DocletTag findParamDocByNameOrIndex(String name, int paramIndex, List<DocletTag> tags) { for (DocletTag tag : tags) { if (name.equals(tag.getParameters().get(0))) { return tag; // depends on control dependency: [if], data = [none] } } if (paramIndex < tags.size()) { return tags.get(paramIndex); // depends on control dependency: [if], data = [(paramIndex] } return null; } }
public class class_name { private void handleNextButtonTextIntent(@NonNull final Bundle extras) { CharSequence text = extras.getString(EXTRA_NEXT_BUTTON_TEXT); if (!TextUtils.isEmpty(text)) { setNextButtonText(text); } } }
public class class_name { private void handleNextButtonTextIntent(@NonNull final Bundle extras) { CharSequence text = extras.getString(EXTRA_NEXT_BUTTON_TEXT); if (!TextUtils.isEmpty(text)) { setNextButtonText(text); // depends on control dependency: [if], data = [none] } } }
public class class_name { public String instantiate(String... keysAndValues) { ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); for (int i = 0; i < keysAndValues.length; i += 2) { builder.put(keysAndValues[i], keysAndValues[i + 1]); } return instantiate(builder.build()); } }
public class class_name { public String instantiate(String... keysAndValues) { ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); for (int i = 0; i < keysAndValues.length; i += 2) { builder.put(keysAndValues[i], keysAndValues[i + 1]); // depends on control dependency: [for], data = [i] } return instantiate(builder.build()); } }
public class class_name { public <T extends Com4jObject> T object( final Class<T> type ) { // native method invocation changeType needs to happen in the COM thread, that is responsible for this variant // @see ComCollection#fetch ComThread t = thread != null ? thread : ComThread.get(); return t.execute(new Task<T>() { public T call() { Com4jObject wrapper = convertTo(Com4jObject.class); if(null == wrapper) { return null; } T ret = wrapper.queryInterface(type); wrapper.dispose(); return ret; } }); } }
public class class_name { public <T extends Com4jObject> T object( final Class<T> type ) { // native method invocation changeType needs to happen in the COM thread, that is responsible for this variant // @see ComCollection#fetch ComThread t = thread != null ? thread : ComThread.get(); return t.execute(new Task<T>() { public T call() { Com4jObject wrapper = convertTo(Com4jObject.class); if(null == wrapper) { return null; // depends on control dependency: [if], data = [none] } T ret = wrapper.queryInterface(type); wrapper.dispose(); return ret; } }); } }