code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { protected void addRequestHandler(I_CmsRequestHandler handler) { if (handler == null) { return; } String[] names = handler.getHandlerNames(); for (int i = 0; i < names.length; i++) { String name = names[i]; if (m_requestHandlers.get(name) != null) { CmsLog.INIT.error(Messages.get().getBundle().key(Messages.LOG_DUPLICATE_REQUEST_HANDLER_1, name)); continue; } m_requestHandlers.put(name, handler); if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info( Messages.get().getBundle().key( Messages.INIT_ADDED_REQUEST_HANDLER_2, name, handler.getClass().getName())); } } } }
public class class_name { protected void addRequestHandler(I_CmsRequestHandler handler) { if (handler == null) { return; // depends on control dependency: [if], data = [none] } String[] names = handler.getHandlerNames(); for (int i = 0; i < names.length; i++) { String name = names[i]; if (m_requestHandlers.get(name) != null) { CmsLog.INIT.error(Messages.get().getBundle().key(Messages.LOG_DUPLICATE_REQUEST_HANDLER_1, name)); // depends on control dependency: [if], data = [none] continue; } m_requestHandlers.put(name, handler); // depends on control dependency: [for], data = [none] if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info( Messages.get().getBundle().key( Messages.INIT_ADDED_REQUEST_HANDLER_2, name, handler.getClass().getName())); // depends on control dependency: [if], data = [none] } } } }
public class class_name { @Override public void init() { ControlType type = ctrl.getControlType(); if (type != null && type.toString().startsWith("I")) { sign = NEGATIVE; } else { sign = POSITIVE; } if (ctrl instanceof TemplateReactionRegulation) transcription = true; } }
public class class_name { @Override public void init() { ControlType type = ctrl.getControlType(); if (type != null && type.toString().startsWith("I")) { sign = NEGATIVE; // depends on control dependency: [if], data = [none] } else { sign = POSITIVE; // depends on control dependency: [if], data = [none] } if (ctrl instanceof TemplateReactionRegulation) transcription = true; } }
public class class_name { public List<LogEvent> getLogsFrom(LogLevel level) { List<LogEvent> levelLogs = new LinkedList<LogEvent>(); for (LogEvent log : this) { if (log.getLevel().compareTo(level) <= 0) { levelLogs.add(log); } } return levelLogs; } }
public class class_name { public List<LogEvent> getLogsFrom(LogLevel level) { List<LogEvent> levelLogs = new LinkedList<LogEvent>(); for (LogEvent log : this) { if (log.getLevel().compareTo(level) <= 0) { levelLogs.add(log); // depends on control dependency: [if], data = [none] } } return levelLogs; } }
public class class_name { private static <I> boolean checkInputs(Query<I, ?> query, Collection<? extends I> inputs) { for (I sym : query.getPrefix()) { if (!inputs.contains(sym)) { return false; } } for (I sym : query.getSuffix()) { if (!inputs.contains(sym)) { return false; } } return true; } }
public class class_name { private static <I> boolean checkInputs(Query<I, ?> query, Collection<? extends I> inputs) { for (I sym : query.getPrefix()) { if (!inputs.contains(sym)) { return false; // depends on control dependency: [if], data = [none] } } for (I sym : query.getSuffix()) { if (!inputs.contains(sym)) { return false; // depends on control dependency: [if], data = [none] } } return true; } }
public class class_name { public void setCascadingDelete(Class target, String referenceField, boolean doCascade) { ClassDescriptor cld = getBroker().getClassDescriptor(target); ObjectReferenceDescriptor ord = cld.getObjectReferenceDescriptorByName(referenceField); if(ord == null) { ord = cld.getCollectionDescriptorByName(referenceField); } if(ord == null) { throw new CascadeSettingException("Invalid reference field name '" + referenceField + "', can't find 1:1, 1:n or m:n relation with that name in " + target); } runtimeCascadeDeleteMap.put(ord, (doCascade ? Boolean.TRUE : Boolean.FALSE)); } }
public class class_name { public void setCascadingDelete(Class target, String referenceField, boolean doCascade) { ClassDescriptor cld = getBroker().getClassDescriptor(target); ObjectReferenceDescriptor ord = cld.getObjectReferenceDescriptorByName(referenceField); if(ord == null) { ord = cld.getCollectionDescriptorByName(referenceField); // depends on control dependency: [if], data = [none] } if(ord == null) { throw new CascadeSettingException("Invalid reference field name '" + referenceField + "', can't find 1:1, 1:n or m:n relation with that name in " + target); } runtimeCascadeDeleteMap.put(ord, (doCascade ? Boolean.TRUE : Boolean.FALSE)); } }
public class class_name { private Collection<MailFolder> listMailboxes(GreenMailUser user, String mailboxPattern, boolean subscribedOnly) throws FolderException { List<MailFolder> mailboxes = new ArrayList<>(); String qualifiedPattern = getQualifiedMailboxName(user, mailboxPattern); for (MailFolder folder : store.listMailboxes(qualifiedPattern)) { // TODO check subscriptions. if (subscribedOnly && !subscriptions.isSubscribed(user, folder)) { // if not subscribed folder = null; } // Sets the store to null if it's not viewable. folder = checkViewable(folder); if (folder != null) { mailboxes.add(folder); } } return mailboxes; } }
public class class_name { private Collection<MailFolder> listMailboxes(GreenMailUser user, String mailboxPattern, boolean subscribedOnly) throws FolderException { List<MailFolder> mailboxes = new ArrayList<>(); String qualifiedPattern = getQualifiedMailboxName(user, mailboxPattern); for (MailFolder folder : store.listMailboxes(qualifiedPattern)) { // TODO check subscriptions. if (subscribedOnly && !subscriptions.isSubscribed(user, folder)) { // if not subscribed folder = null; // depends on control dependency: [if], data = [none] } // Sets the store to null if it's not viewable. folder = checkViewable(folder); if (folder != null) { mailboxes.add(folder); // depends on control dependency: [if], data = [(folder] } } return mailboxes; } }
public class class_name { public static int[] range(int includedStart, int excludedEnd, int step) { if (includedStart > excludedEnd) { int tmp = includedStart; includedStart = excludedEnd; excludedEnd = tmp; } if (step <= 0) { step = 1; } int deviation = excludedEnd - includedStart; int length = deviation / step; if (deviation % step != 0) { length += 1; } int[] range = new int[length]; for (int i = 0; i < length; i++) { range[i] = includedStart; includedStart += step; } return range; } }
public class class_name { public static int[] range(int includedStart, int excludedEnd, int step) { if (includedStart > excludedEnd) { int tmp = includedStart; includedStart = excludedEnd; // depends on control dependency: [if], data = [none] excludedEnd = tmp; // depends on control dependency: [if], data = [none] } if (step <= 0) { step = 1; // depends on control dependency: [if], data = [none] } int deviation = excludedEnd - includedStart; int length = deviation / step; if (deviation % step != 0) { length += 1; // depends on control dependency: [if], data = [none] } int[] range = new int[length]; for (int i = 0; i < length; i++) { range[i] = includedStart; // depends on control dependency: [for], data = [i] includedStart += step; // depends on control dependency: [for], data = [none] } return range; } }
public class class_name { public static void squashNulls( Object input ) { if ( input instanceof List ) { List inputList = (List) input; inputList.removeIf( java.util.Objects::isNull ); } else if ( input instanceof Map ) { Map<String,Object> inputMap = (Map<String,Object>) input; List<String> keysToNuke = new ArrayList<>(); for (Map.Entry<String,Object> entry : inputMap.entrySet()) { if ( entry.getValue() == null ) { keysToNuke.add( entry.getKey() ); } } inputMap.keySet().removeAll( keysToNuke ); } } }
public class class_name { public static void squashNulls( Object input ) { if ( input instanceof List ) { List inputList = (List) input; inputList.removeIf( java.util.Objects::isNull ); // depends on control dependency: [if], data = [none] } else if ( input instanceof Map ) { Map<String,Object> inputMap = (Map<String,Object>) input; List<String> keysToNuke = new ArrayList<>(); for (Map.Entry<String,Object> entry : inputMap.entrySet()) { if ( entry.getValue() == null ) { keysToNuke.add( entry.getKey() ); // depends on control dependency: [if], data = [none] } } inputMap.keySet().removeAll( keysToNuke ); // depends on control dependency: [if], data = [none] } } }
public class class_name { public URL discoverResource(Method m, String uri) { for (String s : possibleLocations(m, uri)) { try { URL resource = this.getClass().getClassLoader().getResource(resourcePrefix + "/" + URLDecoder.decode(s, UTF_8)); if (resource == null) { throw new IllegalArgumentException(String.format("Resource %s not found.", uri)); } if (!new File(URLDecoder.decode(resource.getFile(), UTF_8)).isFile()) { continue; // Probably directory } return resource; } catch (IllegalArgumentException ignored) { } // just go on } throw new IllegalArgumentException(String.format("Can not discover resource for method [%s] and URI [%s]", m, uri)); } }
public class class_name { public URL discoverResource(Method m, String uri) { for (String s : possibleLocations(m, uri)) { try { URL resource = this.getClass().getClassLoader().getResource(resourcePrefix + "/" + URLDecoder.decode(s, UTF_8)); if (resource == null) { throw new IllegalArgumentException(String.format("Resource %s not found.", uri)); } if (!new File(URLDecoder.decode(resource.getFile(), UTF_8)).isFile()) { continue; // Probably directory } return resource; // depends on control dependency: [try], data = [none] } catch (IllegalArgumentException ignored) { } // just go on // depends on control dependency: [catch], data = [none] } throw new IllegalArgumentException(String.format("Can not discover resource for method [%s] and URI [%s]", m, uri)); } }
public class class_name { public void marshall(UpdateConstraintRequest updateConstraintRequest, ProtocolMarshaller protocolMarshaller) { if (updateConstraintRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(updateConstraintRequest.getAcceptLanguage(), ACCEPTLANGUAGE_BINDING); protocolMarshaller.marshall(updateConstraintRequest.getId(), ID_BINDING); protocolMarshaller.marshall(updateConstraintRequest.getDescription(), DESCRIPTION_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(UpdateConstraintRequest updateConstraintRequest, ProtocolMarshaller protocolMarshaller) { if (updateConstraintRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(updateConstraintRequest.getAcceptLanguage(), ACCEPTLANGUAGE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(updateConstraintRequest.getId(), ID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(updateConstraintRequest.getDescription(), DESCRIPTION_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private void loadDataAsynchronously( @NonNull final Task<DataType, KeyType, ViewType, ParamType> task) { threadPool.submit(new Runnable() { @Override public void run() { if (!isCanceled()) { while (!notifyOnLoad(task.key, task.params)) { try { Thread.sleep(100); } catch (InterruptedException e) { break; } } task.result = loadData(task); Message message = Message.obtain(); message.obj = task; sendMessage(message); } } }); } }
public class class_name { private void loadDataAsynchronously( @NonNull final Task<DataType, KeyType, ViewType, ParamType> task) { threadPool.submit(new Runnable() { @Override public void run() { if (!isCanceled()) { while (!notifyOnLoad(task.key, task.params)) { try { Thread.sleep(100); // depends on control dependency: [try], data = [none] } catch (InterruptedException e) { break; } // depends on control dependency: [catch], data = [none] } task.result = loadData(task); // depends on control dependency: [if], data = [none] Message message = Message.obtain(); message.obj = task; // depends on control dependency: [if], data = [none] sendMessage(message); // depends on control dependency: [if], data = [none] } } }); } }
public class class_name { public void setPadding(float padding, Layout.Axis axis) { OrientedLayout layout = null; switch(axis) { case X: layout = mShiftLayout; break; case Y: layout = mShiftLayout; break; case Z: layout = mStackLayout; break; } if (layout != null) { if (!equal(layout.getDividerPadding(axis), padding)) { layout.setDividerPadding(padding, axis); if (layout.getOrientationAxis() == axis) { requestLayout(); } } } } }
public class class_name { public void setPadding(float padding, Layout.Axis axis) { OrientedLayout layout = null; switch(axis) { case X: layout = mShiftLayout; break; case Y: layout = mShiftLayout; break; case Z: layout = mStackLayout; break; } if (layout != null) { if (!equal(layout.getDividerPadding(axis), padding)) { layout.setDividerPadding(padding, axis); // depends on control dependency: [if], data = [none] if (layout.getOrientationAxis() == axis) { requestLayout(); // depends on control dependency: [if], data = [none] } } } } }
public class class_name { protected RetryInfo evaluateRetryInfo(final RetryContext retryContext, final boolean secondaryNotFound, final long retryInterval) { RetryInfo retryInfo = new RetryInfo(retryContext); // Moreover, in case of 404 when trying the secondary location, instead of retrying on the // secondary, further requests should be sent only to the primary location, as it most // probably has a higher chance of succeeding there. if (secondaryNotFound && (retryContext.getLocationMode() != LocationMode.SECONDARY_ONLY)) { retryInfo.setUpdatedLocationMode(LocationMode.PRIMARY_ONLY); retryInfo.setTargetLocation(StorageLocation.PRIMARY); } // Now is the time to calculate the exact retry interval. ShouldRetry call above already // returned back how long two requests to the same location should be apart from each other. // However, for the reasons explained above, the time spent between the last attempt to // the target location and current time must be subtracted from the total retry interval // that ShouldRetry returned. Date lastAttemptTime = retryInfo.getTargetLocation() == StorageLocation.PRIMARY ? this.lastPrimaryAttempt : this.lastSecondaryAttempt; if (lastAttemptTime != null) { long sinceLastAttempt = (new Date().getTime() - lastAttemptTime.getTime() > 0) ? new Date().getTime() - lastAttemptTime.getTime() : 0; retryInfo.setRetryInterval((int) (retryInterval - sinceLastAttempt)); } else { retryInfo.setRetryInterval(0); } return retryInfo; } }
public class class_name { protected RetryInfo evaluateRetryInfo(final RetryContext retryContext, final boolean secondaryNotFound, final long retryInterval) { RetryInfo retryInfo = new RetryInfo(retryContext); // Moreover, in case of 404 when trying the secondary location, instead of retrying on the // secondary, further requests should be sent only to the primary location, as it most // probably has a higher chance of succeeding there. if (secondaryNotFound && (retryContext.getLocationMode() != LocationMode.SECONDARY_ONLY)) { retryInfo.setUpdatedLocationMode(LocationMode.PRIMARY_ONLY); // depends on control dependency: [if], data = [none] retryInfo.setTargetLocation(StorageLocation.PRIMARY); // depends on control dependency: [if], data = [none] } // Now is the time to calculate the exact retry interval. ShouldRetry call above already // returned back how long two requests to the same location should be apart from each other. // However, for the reasons explained above, the time spent between the last attempt to // the target location and current time must be subtracted from the total retry interval // that ShouldRetry returned. Date lastAttemptTime = retryInfo.getTargetLocation() == StorageLocation.PRIMARY ? this.lastPrimaryAttempt : this.lastSecondaryAttempt; if (lastAttemptTime != null) { long sinceLastAttempt = (new Date().getTime() - lastAttemptTime.getTime() > 0) ? new Date().getTime() - lastAttemptTime.getTime() : 0; retryInfo.setRetryInterval((int) (retryInterval - sinceLastAttempt)); // depends on control dependency: [if], data = [none] } else { retryInfo.setRetryInterval(0); // depends on control dependency: [if], data = [none] } return retryInfo; } }
public class class_name { @Nullable // Since Bundle#getParcelableArrayList returns concrete ArrayList type, so this method follows that implementation. public static <T extends Parcelable> ArrayList<T> optParcelableArrayList(@Nullable Bundle bundle, @Nullable String key, @Nullable ArrayList<T> fallback) { if (bundle == null) { return fallback; } return bundle.getParcelableArrayList(key); } }
public class class_name { @Nullable // Since Bundle#getParcelableArrayList returns concrete ArrayList type, so this method follows that implementation. public static <T extends Parcelable> ArrayList<T> optParcelableArrayList(@Nullable Bundle bundle, @Nullable String key, @Nullable ArrayList<T> fallback) { if (bundle == null) { return fallback; // depends on control dependency: [if], data = [none] } return bundle.getParcelableArrayList(key); } }
public class class_name { private void renderScopeItems(final ContextTreeConfig config, final TreeNode root, final Class<?> scope) { final List<Class<Object>> items = service.getData() .getItems(Filters.registeredBy(scope).and(Filters.type(ConfigItem.Bundle).negate())); final List<String> markers = Lists.newArrayList(); for (Class<?> item : items) { markers.clear(); final ItemInfo info = service.getData().getInfo(item); if (isHidden(config, info, scope)) { continue; } fillCommonMarkers(info, markers, scope); renderLeaf(root, info.getItemType().name().toLowerCase(), item, markers); } if (!config.isHideDisables()) { final List<Class<Object>> disabled = service.getData().getItems(Filters.disabledBy(scope)); for (Class<?> item : disabled) { renderLeaf(root, "-disable", item, null); } } } }
public class class_name { private void renderScopeItems(final ContextTreeConfig config, final TreeNode root, final Class<?> scope) { final List<Class<Object>> items = service.getData() .getItems(Filters.registeredBy(scope).and(Filters.type(ConfigItem.Bundle).negate())); final List<String> markers = Lists.newArrayList(); for (Class<?> item : items) { markers.clear(); // depends on control dependency: [for], data = [none] final ItemInfo info = service.getData().getInfo(item); if (isHidden(config, info, scope)) { continue; } fillCommonMarkers(info, markers, scope); // depends on control dependency: [for], data = [none] renderLeaf(root, info.getItemType().name().toLowerCase(), item, markers); // depends on control dependency: [for], data = [item] } if (!config.isHideDisables()) { final List<Class<Object>> disabled = service.getData().getItems(Filters.disabledBy(scope)); for (Class<?> item : disabled) { renderLeaf(root, "-disable", item, null); // depends on control dependency: [for], data = [item] } } } }
public class class_name { private void configureFormatter(NumberFormat formatter) { if (groupingUsedSpecified) { formatter.setGroupingUsed(isGroupingUsed); } if (maxIntegerDigitsSpecified) { formatter.setMaximumIntegerDigits(maxIntegerDigits); } if (minIntegerDigitsSpecified) { formatter.setMinimumIntegerDigits(minIntegerDigits); } if (maxFractionDigitsSpecified) { formatter.setMaximumFractionDigits(maxFractionDigits); } if (minFractionDigitsSpecified) { formatter.setMinimumFractionDigits(minFractionDigits); } } }
public class class_name { private void configureFormatter(NumberFormat formatter) { if (groupingUsedSpecified) { formatter.setGroupingUsed(isGroupingUsed); // depends on control dependency: [if], data = [none] } if (maxIntegerDigitsSpecified) { formatter.setMaximumIntegerDigits(maxIntegerDigits); // depends on control dependency: [if], data = [none] } if (minIntegerDigitsSpecified) { formatter.setMinimumIntegerDigits(minIntegerDigits); // depends on control dependency: [if], data = [none] } if (maxFractionDigitsSpecified) { formatter.setMaximumFractionDigits(maxFractionDigits); // depends on control dependency: [if], data = [none] } if (minFractionDigitsSpecified) { formatter.setMinimumFractionDigits(minFractionDigits); // depends on control dependency: [if], data = [none] } } }
public class class_name { static double getZmqVersion() { XLOGGER.entry(); if (zmqVersion < 0.0) { // Not already checked. zmqVersion = 0.0; try { String strVersion = org.zeromq.ZMQ.getVersionString(); final StringTokenizer stk = new StringTokenizer(strVersion, "."); final ArrayList<String> list = new ArrayList<String>(); while (stk.hasMoreTokens()) { list.add(stk.nextToken()); } strVersion = list.get(0) + "." + list.get(1); if (list.size() > 2) { strVersion += list.get(2); } try { zmqVersion = Double.parseDouble(strVersion); } catch (final NumberFormatException e) { } } catch (final Exception e) { /*System.err.println(e);*/ } catch (final Error e) { /*System.err.println(e);*/ } } XLOGGER.exit(); return zmqVersion; } }
public class class_name { static double getZmqVersion() { XLOGGER.entry(); if (zmqVersion < 0.0) { // Not already checked. zmqVersion = 0.0; // depends on control dependency: [if], data = [none] try { String strVersion = org.zeromq.ZMQ.getVersionString(); final StringTokenizer stk = new StringTokenizer(strVersion, "."); final ArrayList<String> list = new ArrayList<String>(); while (stk.hasMoreTokens()) { list.add(stk.nextToken()); // depends on control dependency: [while], data = [none] } strVersion = list.get(0) + "." + list.get(1); // depends on control dependency: [try], data = [none] if (list.size() > 2) { strVersion += list.get(2); // depends on control dependency: [if], data = [2)] } try { zmqVersion = Double.parseDouble(strVersion); // depends on control dependency: [try], data = [none] } catch (final NumberFormatException e) { } // depends on control dependency: [catch], data = [none] } catch (final Exception e) { /*System.err.println(e);*/ } catch (final Error e) { /*System.err.println(e);*/ // depends on control dependency: [catch], data = [none] } // depends on control dependency: [catch], data = [none] } XLOGGER.exit(); return zmqVersion; } }
public class class_name { public static byte[] toAsciiByteArray(CharSequence charSequence) { byte[] barr = new byte[charSequence.length()]; for (int i = 0; i < barr.length; i++) { char c = charSequence.charAt(i); barr[i] = (byte) ((int) (c <= 0xFF ? c : 0x3F)); } return barr; } }
public class class_name { public static byte[] toAsciiByteArray(CharSequence charSequence) { byte[] barr = new byte[charSequence.length()]; for (int i = 0; i < barr.length; i++) { char c = charSequence.charAt(i); barr[i] = (byte) ((int) (c <= 0xFF ? c : 0x3F)); // depends on control dependency: [for], data = [i] } return barr; } }
public class class_name { private double manhattanSegmentalDistance(NumberVector o1, double[] o2, long[] dimensions) { double result = 0; int card = 0; for(int d = BitsUtil.nextSetBit(dimensions, 0); d >= 0; d = BitsUtil.nextSetBit(dimensions, d + 1)) { result += Math.abs(o1.doubleValue(d) - o2[d]); ++card; } return result / card; } }
public class class_name { private double manhattanSegmentalDistance(NumberVector o1, double[] o2, long[] dimensions) { double result = 0; int card = 0; for(int d = BitsUtil.nextSetBit(dimensions, 0); d >= 0; d = BitsUtil.nextSetBit(dimensions, d + 1)) { result += Math.abs(o1.doubleValue(d) - o2[d]); // depends on control dependency: [for], data = [d] ++card; // depends on control dependency: [for], data = [none] } return result / card; } }
public class class_name { protected Boolean checkHandshake() { if (this.sentHandshake == null) { log.debug("Sent handshake is null, not checking."); return null; } if (this.receivedHandshake == null) { log.debug("Received handshake is null, not checking."); return null; } if (!this.sentHandshake.equals(this.receivedHandshake)) { log.error( "Handshakes do not match. Closing connection to aggregator at {}.", this.session.getRemoteAddress()); boolean prevValue = this.stayConnected; this.stayConnected = false; this._disconnect(); this.stayConnected = prevValue; return Boolean.FALSE; } return Boolean.TRUE; } }
public class class_name { protected Boolean checkHandshake() { if (this.sentHandshake == null) { log.debug("Sent handshake is null, not checking."); // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [none] } if (this.receivedHandshake == null) { log.debug("Received handshake is null, not checking."); // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [none] } if (!this.sentHandshake.equals(this.receivedHandshake)) { log.error( "Handshakes do not match. Closing connection to aggregator at {}.", this.session.getRemoteAddress()); // depends on control dependency: [if], data = [none] boolean prevValue = this.stayConnected; this.stayConnected = false; // depends on control dependency: [if], data = [none] this._disconnect(); // depends on control dependency: [if], data = [none] this.stayConnected = prevValue; // depends on control dependency: [if], data = [none] return Boolean.FALSE; // depends on control dependency: [if], data = [none] } return Boolean.TRUE; } }
public class class_name { public void update(final float value) { if (Float.isNaN(value)) { return; } if (isEmpty()) { minValue_ = value; maxValue_ = value; } else { if (value < minValue_) { minValue_ = value; } if (value > maxValue_) { maxValue_ = value; } } if (levels_[0] == 0) { compressWhileUpdating(); } n_++; isLevelZeroSorted_ = false; final int nextPos = levels_[0] - 1; assert levels_[0] >= 0; levels_[0] = nextPos; items_[nextPos] = value; } }
public class class_name { public void update(final float value) { if (Float.isNaN(value)) { return; } // depends on control dependency: [if], data = [none] if (isEmpty()) { minValue_ = value; // depends on control dependency: [if], data = [none] maxValue_ = value; // depends on control dependency: [if], data = [none] } else { if (value < minValue_) { minValue_ = value; } // depends on control dependency: [if], data = [none] if (value > maxValue_) { maxValue_ = value; } // depends on control dependency: [if], data = [none] } if (levels_[0] == 0) { compressWhileUpdating(); // depends on control dependency: [if], data = [none] } n_++; isLevelZeroSorted_ = false; final int nextPos = levels_[0] - 1; assert levels_[0] >= 0; levels_[0] = nextPos; items_[nextPos] = value; } }
public class class_name { private boolean areNextStatesAvailable(Automaton source) { ArrayList<Transition> r = possibleTransitions.get(source); if (r != null) { for (Transition t : r) { if (t.evaluate()) { return true; } } } return false; } }
public class class_name { private boolean areNextStatesAvailable(Automaton source) { ArrayList<Transition> r = possibleTransitions.get(source); if (r != null) { for (Transition t : r) { if (t.evaluate()) { return true; // depends on control dependency: [if], data = [none] } } } return false; } }
public class class_name { private MutablePage getWrittenPage(long alignedAddress) { MutablePage currentPage = this.currentPage; do { final long highPageAddress = currentPage.pageAddress; if (alignedAddress == highPageAddress) { return currentPage; } currentPage = currentPage.previousPage; } while (currentPage != null); return null; } }
public class class_name { private MutablePage getWrittenPage(long alignedAddress) { MutablePage currentPage = this.currentPage; do { final long highPageAddress = currentPage.pageAddress; if (alignedAddress == highPageAddress) { return currentPage; // depends on control dependency: [if], data = [none] } currentPage = currentPage.previousPage; } while (currentPage != null); return null; } }
public class class_name { private void configureFromBundles() { context.lifecycle().runPhase(context.getConfiguration(), context.getConfigurationTree(), context.getEnvironment()); final Stopwatch timer = context.stat().timer(BundleTime); final Stopwatch resolutionTimer = context.stat().timer(BundleResolutionTime); if (context.option(ConfigureFromDropwizardBundles)) { context.registerDwBundles(BundleSupport.findBundles(context.getBootstrap(), GuiceyBundle.class)); } context.registerLookupBundles(bundleLookup.lookup()); resolutionTimer.stop(); BundleSupport.processBundles(context); timer.stop(); } }
public class class_name { private void configureFromBundles() { context.lifecycle().runPhase(context.getConfiguration(), context.getConfigurationTree(), context.getEnvironment()); final Stopwatch timer = context.stat().timer(BundleTime); final Stopwatch resolutionTimer = context.stat().timer(BundleResolutionTime); if (context.option(ConfigureFromDropwizardBundles)) { context.registerDwBundles(BundleSupport.findBundles(context.getBootstrap(), GuiceyBundle.class)); // depends on control dependency: [if], data = [none] } context.registerLookupBundles(bundleLookup.lookup()); resolutionTimer.stop(); BundleSupport.processBundles(context); timer.stop(); } }
public class class_name { public static String truncate(String contentType) { if (contentType == null) { contentType = NO_TYPE_MIMETYPE; } else { Matcher matcher = TRUNCATION_REGEX.matcher(contentType); if (matcher.matches()) { contentType = matcher.group(1); } else { contentType = NO_TYPE_MIMETYPE; } } return contentType; } }
public class class_name { public static String truncate(String contentType) { if (contentType == null) { contentType = NO_TYPE_MIMETYPE; // depends on control dependency: [if], data = [none] } else { Matcher matcher = TRUNCATION_REGEX.matcher(contentType); if (matcher.matches()) { contentType = matcher.group(1); // depends on control dependency: [if], data = [none] } else { contentType = NO_TYPE_MIMETYPE; // depends on control dependency: [if], data = [none] } } return contentType; } }
public class class_name { public void setImage(Resource resource) { ImageIcon image = null; if (resource != null && resource.exists()) { try { image = new ImageIcon(resource.getURL()); } catch (IOException e) { logger.warn("Error reading resource: " + resource); throw new RuntimeException("Error reading resource " + resource, e); } } setImage(image); } }
public class class_name { public void setImage(Resource resource) { ImageIcon image = null; if (resource != null && resource.exists()) { try { image = new ImageIcon(resource.getURL()); // depends on control dependency: [try], data = [none] } catch (IOException e) { logger.warn("Error reading resource: " + resource); throw new RuntimeException("Error reading resource " + resource, e); } // depends on control dependency: [catch], data = [none] } setImage(image); } }
public class class_name { public static void sort( List list, String sortBy, boolean ascending, boolean nullsFirst ) { if ( list == null || list.size() == 0 ) { return; } if (sortBy.equals("this")) { Collections.sort(list, thisUniversalComparator(ascending, nullsFirst)); return; } Iterator iterator = list.iterator(); Object object = iterator.next(); Map<String, FieldAccess> fields = null; if (object != null) { fields = BeanUtils.getFieldsFromObject( object ); } else { while(iterator.hasNext()) { object = iterator.next(); if (object!=null) { fields = BeanUtils.getFieldsFromObject( object ); break; } } } if (fields!=null) { final FieldAccess field = fields.get( sortBy ); if ( field != null ) { Collections.sort( list, Sorting.universalComparator(field, ascending, nullsFirst) ); } } } }
public class class_name { public static void sort( List list, String sortBy, boolean ascending, boolean nullsFirst ) { if ( list == null || list.size() == 0 ) { return; // depends on control dependency: [if], data = [none] } if (sortBy.equals("this")) { Collections.sort(list, thisUniversalComparator(ascending, nullsFirst)); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } Iterator iterator = list.iterator(); Object object = iterator.next(); Map<String, FieldAccess> fields = null; if (object != null) { fields = BeanUtils.getFieldsFromObject( object ); // depends on control dependency: [if], data = [none] } else { while(iterator.hasNext()) { object = iterator.next(); // depends on control dependency: [while], data = [none] if (object!=null) { fields = BeanUtils.getFieldsFromObject( object ); // depends on control dependency: [if], data = [none] break; } } } if (fields!=null) { final FieldAccess field = fields.get( sortBy ); if ( field != null ) { Collections.sort( list, Sorting.universalComparator(field, ascending, nullsFirst) ); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public static final Parser<Date> instance() { // NOPMD it's thread save! if (MonthParser.instanceParser == null) { synchronized (MonthParser.class) { if (MonthParser.instanceParser == null) { MonthParser.instanceParser = new MonthParser("yyyy-MM"); } } } return MonthParser.instanceParser; } }
public class class_name { public static final Parser<Date> instance() { // NOPMD it's thread save! if (MonthParser.instanceParser == null) { synchronized (MonthParser.class) { // depends on control dependency: [if], data = [none] if (MonthParser.instanceParser == null) { MonthParser.instanceParser = new MonthParser("yyyy-MM"); // depends on control dependency: [if], data = [none] } } } return MonthParser.instanceParser; } }
public class class_name { protected void unpackEmbeddedDb() { if (configuration.getBinariesClassPathLocation() == null) { logger.info("Not unpacking any embedded database (as BinariesClassPathLocation configuration is null)"); return; } try { Util.extractFromClasspathToFile(configuration.getBinariesClassPathLocation(), baseDir); if (!configuration.isWindows()) { Util.forceExecutable(newExecutableFile("bin", "my_print_defaults")); Util.forceExecutable(newExecutableFile("bin", "mysql_install_db")); Util.forceExecutable(newExecutableFile("scripts", "mysql_install_db")); Util.forceExecutable(newExecutableFile("bin", "mysqld")); Util.forceExecutable(newExecutableFile("bin", "mysqldump")); Util.forceExecutable(newExecutableFile("bin", "mysql")); } } catch (IOException e) { throw new RuntimeException("Error unpacking embedded DB", e); } } }
public class class_name { protected void unpackEmbeddedDb() { if (configuration.getBinariesClassPathLocation() == null) { logger.info("Not unpacking any embedded database (as BinariesClassPathLocation configuration is null)"); // depends on control dependency: [if], data = [null)] return; // depends on control dependency: [if], data = [none] } try { Util.extractFromClasspathToFile(configuration.getBinariesClassPathLocation(), baseDir); // depends on control dependency: [try], data = [none] if (!configuration.isWindows()) { Util.forceExecutable(newExecutableFile("bin", "my_print_defaults")); // depends on control dependency: [if], data = [none] Util.forceExecutable(newExecutableFile("bin", "mysql_install_db")); // depends on control dependency: [if], data = [none] Util.forceExecutable(newExecutableFile("scripts", "mysql_install_db")); // depends on control dependency: [if], data = [none] Util.forceExecutable(newExecutableFile("bin", "mysqld")); // depends on control dependency: [if], data = [none] Util.forceExecutable(newExecutableFile("bin", "mysqldump")); // depends on control dependency: [if], data = [none] Util.forceExecutable(newExecutableFile("bin", "mysql")); // depends on control dependency: [if], data = [none] } } catch (IOException e) { throw new RuntimeException("Error unpacking embedded DB", e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static boolean isAbstractInterface(Class<?> valueClass, int rmicCompatible) { if (JITDeploy.isRMICCompatibleValues(rmicCompatible)) { for (Method method : valueClass.getMethods()) { if (!hasRemoteException(method)) { return false; } } } return true; } }
public class class_name { public static boolean isAbstractInterface(Class<?> valueClass, int rmicCompatible) { if (JITDeploy.isRMICCompatibleValues(rmicCompatible)) { for (Method method : valueClass.getMethods()) { if (!hasRemoteException(method)) { return false; // depends on control dependency: [if], data = [none] } } } return true; } }
public class class_name { protected boolean onBusLineAdded(BusLine line, int index) { if (this.autoUpdate.get()) { try { addMapLayer(index, new BusLineLayer(line, isLayerAutoUpdated())); return true; } catch (Throwable exception) { // } } return false; } }
public class class_name { protected boolean onBusLineAdded(BusLine line, int index) { if (this.autoUpdate.get()) { try { addMapLayer(index, new BusLineLayer(line, isLayerAutoUpdated())); // depends on control dependency: [try], data = [none] return true; // depends on control dependency: [try], data = [none] } catch (Throwable exception) { // } // depends on control dependency: [catch], data = [none] } return false; } }
public class class_name { protected final void notifyStarted() { monitor.enter(); try { // We have to examine the internal state of the snapshot here to properly handle the stop // while starting case. if (snapshot.state != STARTING) { IllegalStateException failure = new IllegalStateException( "Cannot notifyStarted() when the service is " + snapshot.state); notifyFailed(failure); throw failure; } if (snapshot.shutdownWhenStartupFinishes) { snapshot = new StateSnapshot(STOPPING); // We don't call listeners here because we already did that when we set the // shutdownWhenStartupFinishes flag. doStop(); } else { snapshot = new StateSnapshot(RUNNING); running(); } } finally { monitor.leave(); executeListeners(); } } }
public class class_name { protected final void notifyStarted() { monitor.enter(); try { // We have to examine the internal state of the snapshot here to properly handle the stop // while starting case. if (snapshot.state != STARTING) { IllegalStateException failure = new IllegalStateException( "Cannot notifyStarted() when the service is " + snapshot.state); notifyFailed(failure); // depends on control dependency: [if], data = [none] throw failure; } if (snapshot.shutdownWhenStartupFinishes) { snapshot = new StateSnapshot(STOPPING); // depends on control dependency: [if], data = [none] // We don't call listeners here because we already did that when we set the // shutdownWhenStartupFinishes flag. doStop(); // depends on control dependency: [if], data = [none] } else { snapshot = new StateSnapshot(RUNNING); // depends on control dependency: [if], data = [none] running(); // depends on control dependency: [if], data = [none] } } finally { monitor.leave(); executeListeners(); } } }
public class class_name { protected boolean isSarlFile(IPackageFragment packageFragment, String filename) { if (isFileExists(packageFragment, filename, this.sarlFileExtension)) { return true; } final IJavaProject project = getPackageFragmentRoot().getJavaProject(); if (project != null) { try { final String packageName = packageFragment.getElementName(); for (final IPackageFragmentRoot root : project.getPackageFragmentRoots()) { final IPackageFragment fragment = root.getPackageFragment(packageName); if (isFileExists(fragment, filename, JAVA_FILE_EXTENSION)) { return true; } } } catch (JavaModelException exception) { // silent error } } return false; } }
public class class_name { protected boolean isSarlFile(IPackageFragment packageFragment, String filename) { if (isFileExists(packageFragment, filename, this.sarlFileExtension)) { return true; // depends on control dependency: [if], data = [none] } final IJavaProject project = getPackageFragmentRoot().getJavaProject(); if (project != null) { try { final String packageName = packageFragment.getElementName(); for (final IPackageFragmentRoot root : project.getPackageFragmentRoots()) { final IPackageFragment fragment = root.getPackageFragment(packageName); if (isFileExists(fragment, filename, JAVA_FILE_EXTENSION)) { return true; // depends on control dependency: [if], data = [none] } } } catch (JavaModelException exception) { // silent error } // depends on control dependency: [catch], data = [none] } return false; } }
public class class_name { @Override protected void onShutDown() { for (PoolKey<K> k : pool.keySet()) { PoolableObjects<V> pobjs = objectPool(k, Boolean.FALSE); pobjs.shutdown(); } } }
public class class_name { @Override protected void onShutDown() { for (PoolKey<K> k : pool.keySet()) { PoolableObjects<V> pobjs = objectPool(k, Boolean.FALSE); pobjs.shutdown(); // depends on control dependency: [for], data = [none] } } }
public class class_name { private MethodSpec newBuilder(NameAllocator nameAllocator, MessageType message) { NameAllocator localNameAllocator = nameAllocator.clone(); String builderName = localNameAllocator.newName("builder"); ClassName javaType = (ClassName) typeName(message.type()); ClassName builderJavaType = javaType.nestedClass("Builder"); MethodSpec.Builder result = MethodSpec.methodBuilder("newBuilder") .addAnnotation(Override.class) .addModifiers(PUBLIC) .returns(builderJavaType) .addStatement("$1T $2L = new $1T()", builderJavaType, builderName); List<Field> fields = message.fieldsAndOneOfFields(); for (Field field : fields) { String fieldName = localNameAllocator.get(field); if (field.isRepeated() || field.type().isMap()) { result.addStatement("$1L.$2L = $3T.copyOf($2S, $2L)", builderName, fieldName, Internal.class); } else { result.addStatement("$1L.$2L = $2L", builderName, fieldName); } } result.addStatement("$L.addUnknownFields(unknownFields())", builderName); result.addStatement("return $L", builderName); return result.build(); } }
public class class_name { private MethodSpec newBuilder(NameAllocator nameAllocator, MessageType message) { NameAllocator localNameAllocator = nameAllocator.clone(); String builderName = localNameAllocator.newName("builder"); ClassName javaType = (ClassName) typeName(message.type()); ClassName builderJavaType = javaType.nestedClass("Builder"); MethodSpec.Builder result = MethodSpec.methodBuilder("newBuilder") .addAnnotation(Override.class) .addModifiers(PUBLIC) .returns(builderJavaType) .addStatement("$1T $2L = new $1T()", builderJavaType, builderName); List<Field> fields = message.fieldsAndOneOfFields(); for (Field field : fields) { String fieldName = localNameAllocator.get(field); if (field.isRepeated() || field.type().isMap()) { result.addStatement("$1L.$2L = $3T.copyOf($2S, $2L)", builderName, fieldName, Internal.class); // depends on control dependency: [if], data = [none] } else { result.addStatement("$1L.$2L = $2L", builderName, fieldName); // depends on control dependency: [if], data = [none] } } result.addStatement("$L.addUnknownFields(unknownFields())", builderName); result.addStatement("return $L", builderName); return result.build(); } }
public class class_name { public void push(double value) { if (top >= stack.length) { stack = Arrays.copyOf(stack, (int) (stack.length*growFactor)); } stack[top++] = value; } }
public class class_name { public void push(double value) { if (top >= stack.length) { stack = Arrays.copyOf(stack, (int) (stack.length*growFactor)); // depends on control dependency: [if], data = [none] } stack[top++] = value; } }
public class class_name { public Histogram toHistogram(int size) { Preconditions.checkArgument(size > 1, "histogram size must be greater than 1"); float[] breaks = new float[size + 1]; float delta = (max - min) / (size - 1); breaks[0] = min - delta; for (int i = 1; i < breaks.length - 1; ++i) { breaks[i] = breaks[i - 1] + delta; } breaks[breaks.length - 1] = max; return toHistogram(breaks); } }
public class class_name { public Histogram toHistogram(int size) { Preconditions.checkArgument(size > 1, "histogram size must be greater than 1"); float[] breaks = new float[size + 1]; float delta = (max - min) / (size - 1); breaks[0] = min - delta; for (int i = 1; i < breaks.length - 1; ++i) { breaks[i] = breaks[i - 1] + delta; // depends on control dependency: [for], data = [i] } breaks[breaks.length - 1] = max; return toHistogram(breaks); } }
public class class_name { public void free() { super.free(); if (m_closeOnFreeBehavior != null) if (m_record != null) { FileListener listener = m_closeOnFreeBehavior; m_closeOnFreeBehavior = null; m_record.removeListener(listener, false); } } }
public class class_name { public void free() { super.free(); if (m_closeOnFreeBehavior != null) if (m_record != null) { FileListener listener = m_closeOnFreeBehavior; m_closeOnFreeBehavior = null; // depends on control dependency: [if], data = [none] m_record.removeListener(listener, false); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static QueryParameters updateTypesByName(QueryParameters original, QueryParameters source) { QueryParameters updatedParams = new QueryParameters(original); if (source != null) { for (String sourceKey : source.keySet()) { if (updatedParams.containsKey(sourceKey) == true) { updatedParams.updateType(sourceKey, source.getType(sourceKey)); } } } return updatedParams; } }
public class class_name { public static QueryParameters updateTypesByName(QueryParameters original, QueryParameters source) { QueryParameters updatedParams = new QueryParameters(original); if (source != null) { for (String sourceKey : source.keySet()) { if (updatedParams.containsKey(sourceKey) == true) { updatedParams.updateType(sourceKey, source.getType(sourceKey)); // depends on control dependency: [if], data = [none] } } } return updatedParams; } }
public class class_name { protected PseudoExpression expression() throws ParserException { List<Item> items = new ArrayList<Item>(); StringBuilder sb = new StringBuilder(); int initialPos = pos; if (current == '\'' || current == '"') { //string Character quote = current; StringValue s = string(); sb.append(quote); sb.append(s.getContext().toString()); sb.append(quote); items.add(new Item(Type.STRING, s.getActualValue())); return new PseudoExpression(items, null, s.getActualValue(), new Context(content, sb.toString(), initialPos, pos)); } else { while (!end()) { if (current == '+') { items.add(new Item(Type.SIGNAL, "+")); sb.append(current); next(); } else if (current == '-') { items.add(new Item(Type.SIGNAL, "-")); sb.append(current); next(); } else if (Character.isLetter(current)) { //identifier String ident = simpleIdentifier(); sb.append(ident); items.add(new Item(Type.IDENTIFIER, ident)); } else if (Character.isDigit(current)) { //number or dimension String number = number(); sb.append(number); items.add(new Item(Type.NUMBER, number)); } else { break; } ignoreWhitespaces(); } } return new PseudoExpression(items, PseudoExpressionEvaluator.evaluate(items), sb.toString(), new Context(content, sb.toString(), initialPos, pos)); } }
public class class_name { protected PseudoExpression expression() throws ParserException { List<Item> items = new ArrayList<Item>(); StringBuilder sb = new StringBuilder(); int initialPos = pos; if (current == '\'' || current == '"') { //string Character quote = current; StringValue s = string(); sb.append(quote); sb.append(s.getContext().toString()); sb.append(quote); items.add(new Item(Type.STRING, s.getActualValue())); return new PseudoExpression(items, null, s.getActualValue(), new Context(content, sb.toString(), initialPos, pos)); } else { while (!end()) { if (current == '+') { items.add(new Item(Type.SIGNAL, "+")); // depends on control dependency: [if], data = [none] sb.append(current); // depends on control dependency: [if], data = [(current] next(); // depends on control dependency: [if], data = [none] } else if (current == '-') { items.add(new Item(Type.SIGNAL, "-")); // depends on control dependency: [if], data = [none] sb.append(current); // depends on control dependency: [if], data = [(current] next(); // depends on control dependency: [if], data = [none] } else if (Character.isLetter(current)) { //identifier String ident = simpleIdentifier(); sb.append(ident); // depends on control dependency: [if], data = [none] items.add(new Item(Type.IDENTIFIER, ident)); // depends on control dependency: [if], data = [none] } else if (Character.isDigit(current)) { //number or dimension String number = number(); sb.append(number); // depends on control dependency: [if], data = [none] items.add(new Item(Type.NUMBER, number)); // depends on control dependency: [if], data = [none] } else { break; } ignoreWhitespaces(); // depends on control dependency: [while], data = [none] } } return new PseudoExpression(items, PseudoExpressionEvaluator.evaluate(items), sb.toString(), new Context(content, sb.toString(), initialPos, pos)); } }
public class class_name { @Override public Map<String, Object> detail() { final Map<String, Object> details = super.detail(); details.put("link", link); details.put("caption", caption); if (pendingPhotos != null && pendingPhotos.size() > 0) { PhotoType type = pendingPhotos.get(0).getType(); if (type == PhotoType.SOURCE) { details.put(type.getPrefix(), pendingPhotos.get(0).getDetail()); } else if (type == PhotoType.FILE) { for (int i = 0; i < pendingPhotos.size(); i++) { details.put(type.getPrefix() + "[" + i + "]", pendingPhotos.get(i).getDetail()); } } } return details; } }
public class class_name { @Override public Map<String, Object> detail() { final Map<String, Object> details = super.detail(); details.put("link", link); details.put("caption", caption); if (pendingPhotos != null && pendingPhotos.size() > 0) { PhotoType type = pendingPhotos.get(0).getType(); if (type == PhotoType.SOURCE) { details.put(type.getPrefix(), pendingPhotos.get(0).getDetail()); // depends on control dependency: [if], data = [(type] } else if (type == PhotoType.FILE) { for (int i = 0; i < pendingPhotos.size(); i++) { details.put(type.getPrefix() + "[" + i + "]", pendingPhotos.get(i).getDetail()); // depends on control dependency: [for], data = [i] } } } return details; } }
public class class_name { public java.util.List<Queue> getQueues() { if (queues == null) { queues = new com.amazonaws.internal.SdkInternalList<Queue>(); } return queues; } }
public class class_name { public java.util.List<Queue> getQueues() { if (queues == null) { queues = new com.amazonaws.internal.SdkInternalList<Queue>(); // depends on control dependency: [if], data = [none] } return queues; } }
public class class_name { public synchronized int purge() { int recordsRemaining = -1; SQLiteDatabase db = null; Cursor cursor = null; try { db = getWritableDatabase(); // Purge records. long earliestValidTime = System.currentTimeMillis() - RECORD_EXPIRY_TIME; int recordsDeleted = db.delete(ShareRequestTable.NAME, WHERE_CLAUSE_PURGE_POLICY, new String[]{String.valueOf(earliestValidTime), String.valueOf(ShareRequest.STATE_PROCESSED), String.valueOf(RECORD_MAX_FAILS)} ); // Check number of records remaining in the table. cursor = db.query(ShareRequestTable.NAME, new String[]{ShareRequestTable.COLUMN_ID}, null, null, null, null, null); if (cursor != null) { recordsRemaining = cursor.getCount(); } sLogger.log(WingsDbHelper.class, "purge", "recordsDeleted=" + recordsDeleted + " recordsRemaining=" + recordsRemaining); } catch (SQLException e) { // Do nothing. } finally { if (cursor != null) { cursor.close(); } db.close(); } return recordsRemaining; } }
public class class_name { public synchronized int purge() { int recordsRemaining = -1; SQLiteDatabase db = null; Cursor cursor = null; try { db = getWritableDatabase(); // depends on control dependency: [try], data = [none] // Purge records. long earliestValidTime = System.currentTimeMillis() - RECORD_EXPIRY_TIME; int recordsDeleted = db.delete(ShareRequestTable.NAME, WHERE_CLAUSE_PURGE_POLICY, new String[]{String.valueOf(earliestValidTime), String.valueOf(ShareRequest.STATE_PROCESSED), String.valueOf(RECORD_MAX_FAILS)} ); // Check number of records remaining in the table. cursor = db.query(ShareRequestTable.NAME, new String[]{ShareRequestTable.COLUMN_ID}, null, null, null, null, null); // depends on control dependency: [try], data = [none] if (cursor != null) { recordsRemaining = cursor.getCount(); // depends on control dependency: [if], data = [none] } sLogger.log(WingsDbHelper.class, "purge", "recordsDeleted=" + recordsDeleted + " recordsRemaining=" + recordsRemaining); // depends on control dependency: [try], data = [none] } catch (SQLException e) { // Do nothing. } finally { // depends on control dependency: [catch], data = [none] if (cursor != null) { cursor.close(); // depends on control dependency: [if], data = [none] } db.close(); } return recordsRemaining; } }
public class class_name { public boolean isArtefactClass(@SuppressWarnings("rawtypes") Class clazz) { if (clazz == null) return false; boolean ok = clazz.getName().endsWith(artefactSuffix) && !Closure.class.isAssignableFrom(clazz); if (ok && !allowAbstract) { ok &= !Modifier.isAbstract(clazz.getModifiers()); } return ok; } }
public class class_name { public boolean isArtefactClass(@SuppressWarnings("rawtypes") Class clazz) { if (clazz == null) return false; boolean ok = clazz.getName().endsWith(artefactSuffix) && !Closure.class.isAssignableFrom(clazz); if (ok && !allowAbstract) { ok &= !Modifier.isAbstract(clazz.getModifiers()); // depends on control dependency: [if], data = [none] } return ok; } }
public class class_name { public static Date parseUsingPattern(String date, String pattern) { SimpleDateFormat df = new SimpleDateFormat(pattern); df.setLenient(false); try { ParsePosition pp = new ParsePosition(0); Date d = df.parse(date, pp); if (d != null && pp.getIndex() != date.length()) { return d; } } catch (Exception e) { } return null; } }
public class class_name { public static Date parseUsingPattern(String date, String pattern) { SimpleDateFormat df = new SimpleDateFormat(pattern); df.setLenient(false); try { ParsePosition pp = new ParsePosition(0); Date d = df.parse(date, pp); if (d != null && pp.getIndex() != date.length()) { return d; // depends on control dependency: [if], data = [none] } } catch (Exception e) { } // depends on control dependency: [catch], data = [none] return null; } }
public class class_name { public int[] extractUShortArray() { final short[] argOut = element.value.ushort_att_value(); final int[] val = new int[argOut.length]; for (int i = 0; i < argOut.length; i++) { val[i] = 0xFFFF & argOut[i]; } return val; } }
public class class_name { public int[] extractUShortArray() { final short[] argOut = element.value.ushort_att_value(); final int[] val = new int[argOut.length]; for (int i = 0; i < argOut.length; i++) { val[i] = 0xFFFF & argOut[i]; // depends on control dependency: [for], data = [i] } return val; } }
public class class_name { public void setItemFocusEnabled(boolean enabled) { if (enabled != mItemFocusEnabled) { mItemFocusEnabled = enabled; Log.d(Log.SUBSYSTEM.LAYOUT, TAG, "setItemFocusEnabled(%s): item focus enabled: %b", getName(), enabled); for (Widget view: getAllViews()) { if (view != null) { view.setFocusEnabled(enabled); } else { Log.w(TAG, "setItemFocusEnabled(%s): Host has no view!", getName()); } } } } }
public class class_name { public void setItemFocusEnabled(boolean enabled) { if (enabled != mItemFocusEnabled) { mItemFocusEnabled = enabled; // depends on control dependency: [if], data = [none] Log.d(Log.SUBSYSTEM.LAYOUT, TAG, "setItemFocusEnabled(%s): item focus enabled: %b", getName(), enabled); // depends on control dependency: [if], data = [none] for (Widget view: getAllViews()) { if (view != null) { view.setFocusEnabled(enabled); // depends on control dependency: [if], data = [none] } else { Log.w(TAG, "setItemFocusEnabled(%s): Host has no view!", getName()); } } } } }
public class class_name { public void setSymbolPosition(CurrencySymbolPosition posn) { if (posn == null) { posn = DEFAULT_CURRENCY_SYMBOL_POSITION; } set(ProjectField.CURRENCY_SYMBOL_POSITION, posn); } }
public class class_name { public void setSymbolPosition(CurrencySymbolPosition posn) { if (posn == null) { posn = DEFAULT_CURRENCY_SYMBOL_POSITION; // depends on control dependency: [if], data = [none] } set(ProjectField.CURRENCY_SYMBOL_POSITION, posn); } }
public class class_name { public void marshall(ListCuratedEnvironmentImagesRequest listCuratedEnvironmentImagesRequest, ProtocolMarshaller protocolMarshaller) { if (listCuratedEnvironmentImagesRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(ListCuratedEnvironmentImagesRequest listCuratedEnvironmentImagesRequest, ProtocolMarshaller protocolMarshaller) { if (listCuratedEnvironmentImagesRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void warn(Object o) { if (o instanceof Throwable) { logger.warn(o, (Throwable) o); } else { logger.warn(o); } } }
public class class_name { public void warn(Object o) { if (o instanceof Throwable) { logger.warn(o, (Throwable) o); // depends on control dependency: [if], data = [none] } else { logger.warn(o); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void readImageResources(final boolean pParseData) throws IOException { readHeader(); if (pParseData && metadata.imageResources == null || metadata.layerAndMaskInfoStart == 0) { imageInput.seek(metadata.imageResourcesStart); long imageResourcesLength = imageInput.readUnsignedInt(); if (pParseData && metadata.imageResources == null && imageResourcesLength > 0) { long expectedEnd = imageInput.getStreamPosition() + imageResourcesLength; metadata.imageResources = new ArrayList<>(); while (imageInput.getStreamPosition() < expectedEnd) { PSDImageResource resource = PSDImageResource.read(imageInput); metadata.imageResources.add(resource); } if (DEBUG) { System.out.println("imageResources: " + metadata.imageResources); } if (imageInput.getStreamPosition() != expectedEnd) { throw new IIOException("Corrupt PSD document"); // ..or maybe just a bug in the reader.. ;-) } } // TODO: We should now be able to flush input // imageInput.flushBefore(metadata.imageResourcesStart + imageResourcesLength + 4); metadata.layerAndMaskInfoStart = metadata.imageResourcesStart + imageResourcesLength + 4; // + 4 for the length field itself } } }
public class class_name { private void readImageResources(final boolean pParseData) throws IOException { readHeader(); if (pParseData && metadata.imageResources == null || metadata.layerAndMaskInfoStart == 0) { imageInput.seek(metadata.imageResourcesStart); long imageResourcesLength = imageInput.readUnsignedInt(); if (pParseData && metadata.imageResources == null && imageResourcesLength > 0) { long expectedEnd = imageInput.getStreamPosition() + imageResourcesLength; metadata.imageResources = new ArrayList<>(); // depends on control dependency: [if], data = [none] while (imageInput.getStreamPosition() < expectedEnd) { PSDImageResource resource = PSDImageResource.read(imageInput); metadata.imageResources.add(resource); // depends on control dependency: [while], data = [none] } if (DEBUG) { System.out.println("imageResources: " + metadata.imageResources); // depends on control dependency: [if], data = [none] } if (imageInput.getStreamPosition() != expectedEnd) { throw new IIOException("Corrupt PSD document"); // ..or maybe just a bug in the reader.. ;-) } } // TODO: We should now be able to flush input // imageInput.flushBefore(metadata.imageResourcesStart + imageResourcesLength + 4); metadata.layerAndMaskInfoStart = metadata.imageResourcesStart + imageResourcesLength + 4; // + 4 for the length field itself } } }
public class class_name { protected void addSiblings(Set<CmsResource> publishResources) { List<CmsResource> toAdd = Lists.newArrayList(); for (CmsResource resource : publishResources) { if (!resource.getState().isUnchanged()) { try { List<CmsResource> changedSiblings = getCmsObject().readSiblings( resource, CmsResourceFilter.ALL_MODIFIED); toAdd.addAll(changedSiblings); } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } } } publishResources.addAll(toAdd); } }
public class class_name { protected void addSiblings(Set<CmsResource> publishResources) { List<CmsResource> toAdd = Lists.newArrayList(); for (CmsResource resource : publishResources) { if (!resource.getState().isUnchanged()) { try { List<CmsResource> changedSiblings = getCmsObject().readSiblings( resource, CmsResourceFilter.ALL_MODIFIED); toAdd.addAll(changedSiblings); // depends on control dependency: [try], data = [none] } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } // depends on control dependency: [catch], data = [none] } } publishResources.addAll(toAdd); } }
public class class_name { @Override public void run() { if (state.compareAndSet(State.STARTED, State.STOPPING)) { for (final Runnable hook : hooks) { try { hook.run(); } catch (final Throwable t) { LOGGER.error(SHUTDOWN_HOOK_MARKER, "Caught exception executing shutdown hook {}", hook, t); } } state.set(State.STOPPED); } } }
public class class_name { @Override public void run() { if (state.compareAndSet(State.STARTED, State.STOPPING)) { for (final Runnable hook : hooks) { try { hook.run(); // depends on control dependency: [try], data = [none] } catch (final Throwable t) { LOGGER.error(SHUTDOWN_HOOK_MARKER, "Caught exception executing shutdown hook {}", hook, t); } // depends on control dependency: [catch], data = [none] } state.set(State.STOPPED); // depends on control dependency: [if], data = [none] } } }
public class class_name { public R run(A... arg) throws E { final TransactionManager tm = getTransactionManager(); Transaction tx = null; try { if (tm != null) { try { tx = tm.suspend(); } catch (SystemException e) { LOG.warn("Cannot suspend the current transaction", e); } } return execute(arg); } finally { if (tx != null) { try { tm.resume(tx); } catch (Exception e) { LOG.warn("Cannot resume the current transaction", e); } } } } }
public class class_name { public R run(A... arg) throws E { final TransactionManager tm = getTransactionManager(); Transaction tx = null; try { if (tm != null) { try { tx = tm.suspend(); // depends on control dependency: [try], data = [none] } catch (SystemException e) { LOG.warn("Cannot suspend the current transaction", e); } // depends on control dependency: [catch], data = [none] } return execute(arg); // depends on control dependency: [try], data = [none] } finally { if (tx != null) { try { tm.resume(tx); // depends on control dependency: [try], data = [none] } catch (Exception e) { LOG.warn("Cannot resume the current transaction", e); } // depends on control dependency: [catch], data = [none] } } } }
public class class_name { public boolean isValidProfileSize(String profileSize) { if (StringUtils.isBlank(profileSize) || profileSizes.isEmpty()) { return false; } return profileSizes.contains(profileSize); } }
public class class_name { public boolean isValidProfileSize(String profileSize) { if (StringUtils.isBlank(profileSize) || profileSizes.isEmpty()) { return false; // depends on control dependency: [if], data = [none] } return profileSizes.contains(profileSize); } }
public class class_name { @SuppressWarnings("unchecked") // types must agree public static <T> T createMockObject(Type type) { Class<T> rawType; if (type instanceof ParameterizedType) { rawType = (Class<T>) ((ParameterizedType) type).getRawType(); } else if (type instanceof Class) { rawType = (Class<T>) type; } else { throw new UnsupportedOperationException("Unsupported type: " + type.getClass().getSimpleName()); } T instance = instantiateObject(rawType); return populateObject(instance); } }
public class class_name { @SuppressWarnings("unchecked") // types must agree public static <T> T createMockObject(Type type) { Class<T> rawType; if (type instanceof ParameterizedType) { rawType = (Class<T>) ((ParameterizedType) type).getRawType(); // depends on control dependency: [if], data = [none] } else if (type instanceof Class) { rawType = (Class<T>) type; // depends on control dependency: [if], data = [none] } else { throw new UnsupportedOperationException("Unsupported type: " + type.getClass().getSimpleName()); } T instance = instantiateObject(rawType); return populateObject(instance); } }
public class class_name { private static String toReadableString(Collection<TypedDependency> dependencies) { StringBuilder buf = new StringBuilder(); buf.append(String.format("%-20s%-20s%-20s%n", "dep", "reln", "gov")); buf.append(String.format("%-20s%-20s%-20s%n", "---", "----", "---")); for (TypedDependency td : dependencies) { buf.append(String.format("%-20s%-20s%-20s%n", td.dep(), td.reln(), td.gov())); } return buf.toString(); } }
public class class_name { private static String toReadableString(Collection<TypedDependency> dependencies) { StringBuilder buf = new StringBuilder(); buf.append(String.format("%-20s%-20s%-20s%n", "dep", "reln", "gov")); buf.append(String.format("%-20s%-20s%-20s%n", "---", "----", "---")); for (TypedDependency td : dependencies) { buf.append(String.format("%-20s%-20s%-20s%n", td.dep(), td.reln(), td.gov())); // depends on control dependency: [for], data = [td] } return buf.toString(); } }
public class class_name { public File convertDocumentToPDF(File inputDocumentParam) { if(inputDocumentParam == null || !inputDocumentParam.exists()) { throw new UtilException( "Input document to convert not provided or does not exist.", UtilException.ErrorCode.COMMAND); } if(!inputDocumentParam.isFile()) { throw new UtilException( "Input document '' is not a file.", UtilException.ErrorCode.COMMAND); } File parentFolder = inputDocumentParam.getParentFile(); String inputFilenameWithoutExt = inputDocumentParam.getName(); int indexOfDot = -1; if((indexOfDot = inputFilenameWithoutExt.indexOf('.')) > -1) { inputFilenameWithoutExt = inputFilenameWithoutExt.substring(0,indexOfDot); } File generatedPdfFileOut = new File(parentFolder.getAbsolutePath().concat( File.separator).concat(inputFilenameWithoutExt).concat(".pdf")); String completeOutputPath = generatedPdfFileOut.getAbsolutePath(); try { CommandUtil.CommandResult commandResult = this.commandUtil.executeCommand( CommandUtil.FLUID_CLI, COMMAND_CONVERT_DOC_TO_PDF, "-i", inputDocumentParam.getAbsolutePath(), "-o", completeOutputPath); //There is a problem... if(commandResult.getExitCode() != 0) { throw new UtilException( "Unable to convert '"+ inputDocumentParam.getName()+ "' to PDF. "+ commandResult.toString(), UtilException.ErrorCode.COMMAND); } File returnVal = new File(completeOutputPath); if(!returnVal.exists()) { throw new UtilException( "Command executed, but no output file. Expected PDF at '"+ completeOutputPath+"'.", UtilException.ErrorCode.GENERAL); } return returnVal; } // catch (IOException eParam) { throw new UtilException( "Problem executing command. "+eParam.getMessage(), eParam,UtilException.ErrorCode.GENERAL); } } }
public class class_name { public File convertDocumentToPDF(File inputDocumentParam) { if(inputDocumentParam == null || !inputDocumentParam.exists()) { throw new UtilException( "Input document to convert not provided or does not exist.", UtilException.ErrorCode.COMMAND); } if(!inputDocumentParam.isFile()) { throw new UtilException( "Input document '' is not a file.", UtilException.ErrorCode.COMMAND); } File parentFolder = inputDocumentParam.getParentFile(); String inputFilenameWithoutExt = inputDocumentParam.getName(); int indexOfDot = -1; if((indexOfDot = inputFilenameWithoutExt.indexOf('.')) > -1) { inputFilenameWithoutExt = inputFilenameWithoutExt.substring(0,indexOfDot); // depends on control dependency: [if], data = [none] } File generatedPdfFileOut = new File(parentFolder.getAbsolutePath().concat( File.separator).concat(inputFilenameWithoutExt).concat(".pdf")); String completeOutputPath = generatedPdfFileOut.getAbsolutePath(); try { CommandUtil.CommandResult commandResult = this.commandUtil.executeCommand( CommandUtil.FLUID_CLI, COMMAND_CONVERT_DOC_TO_PDF, "-i", inputDocumentParam.getAbsolutePath(), "-o", completeOutputPath); //There is a problem... if(commandResult.getExitCode() != 0) { throw new UtilException( "Unable to convert '"+ inputDocumentParam.getName()+ "' to PDF. "+ commandResult.toString(), UtilException.ErrorCode.COMMAND); } File returnVal = new File(completeOutputPath); if(!returnVal.exists()) { throw new UtilException( "Command executed, but no output file. Expected PDF at '"+ completeOutputPath+"'.", UtilException.ErrorCode.GENERAL); } return returnVal; // depends on control dependency: [try], data = [none] } // catch (IOException eParam) { throw new UtilException( "Problem executing command. "+eParam.getMessage(), eParam,UtilException.ErrorCode.GENERAL); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public void sawOpcode(int seen) { JPAUserValue userValue = null; try { switch (seen) { case Const.INVOKEVIRTUAL: case Const.INVOKEINTERFACE: { userValue = processInvoke(); break; } case Const.POP: { if (stack.getStackDepth() > 0) { OpcodeStack.Item itm = stack.getStackItem(0); if (itm.getUserValue() == JPAUserValue.MERGE) { bugReporter.reportBug(new BugInstance(this, BugType.JPAI_IGNORED_MERGE_RESULT.name(), LOW_PRIORITY).addClass(this).addMethod(this) .addSourceLine(this)); } } break; } default: break; } } finally { stack.sawOpcode(this, seen); if ((userValue != null) && (stack.getStackDepth() > 0)) { OpcodeStack.Item itm = stack.getStackItem(0); itm.setUserValue(userValue); } } } }
public class class_name { @Override public void sawOpcode(int seen) { JPAUserValue userValue = null; try { switch (seen) { case Const.INVOKEVIRTUAL: case Const.INVOKEINTERFACE: { userValue = processInvoke(); break; } case Const.POP: { if (stack.getStackDepth() > 0) { OpcodeStack.Item itm = stack.getStackItem(0); if (itm.getUserValue() == JPAUserValue.MERGE) { bugReporter.reportBug(new BugInstance(this, BugType.JPAI_IGNORED_MERGE_RESULT.name(), LOW_PRIORITY).addClass(this).addMethod(this) .addSourceLine(this)); // depends on control dependency: [if], data = [none] } } break; } default: break; } } finally { stack.sawOpcode(this, seen); if ((userValue != null) && (stack.getStackDepth() > 0)) { OpcodeStack.Item itm = stack.getStackItem(0); itm.setUserValue(userValue); // depends on control dependency: [if], data = [none] } } } }
public class class_name { private static String notReadyToString(Iterable<HasMetadata> resources) { StringBuilder sb = new StringBuilder(); sb.append("Resources that are not ready: "); boolean first = true; for (HasMetadata r : resources) { if (first) { first = false; } else { sb.append(", "); } sb.append("[Kind:").append(r.getKind()) .append(" Name:").append(r.getMetadata().getName()) .append(" Namespace:").append(r.getMetadata().getNamespace()) .append("]"); } return sb.toString(); } }
public class class_name { private static String notReadyToString(Iterable<HasMetadata> resources) { StringBuilder sb = new StringBuilder(); sb.append("Resources that are not ready: "); boolean first = true; for (HasMetadata r : resources) { if (first) { first = false; // depends on control dependency: [if], data = [none] } else { sb.append(", "); // depends on control dependency: [if], data = [none] } sb.append("[Kind:").append(r.getKind()) .append(" Name:").append(r.getMetadata().getName()) .append(" Namespace:").append(r.getMetadata().getNamespace()) .append("]"); // depends on control dependency: [for], data = [none] } return sb.toString(); } }
public class class_name { public List<ConfigPropertyType<ConnectionDefinitionType<T>>> getAllConfigProperty() { List<ConfigPropertyType<ConnectionDefinitionType<T>>> list = new ArrayList<ConfigPropertyType<ConnectionDefinitionType<T>>>(); List<Node> nodeList = childNode.get("config-property"); for(Node node: nodeList) { ConfigPropertyType<ConnectionDefinitionType<T>> type = new ConfigPropertyTypeImpl<ConnectionDefinitionType<T>>(this, "config-property", childNode, node); list.add(type); } return list; } }
public class class_name { public List<ConfigPropertyType<ConnectionDefinitionType<T>>> getAllConfigProperty() { List<ConfigPropertyType<ConnectionDefinitionType<T>>> list = new ArrayList<ConfigPropertyType<ConnectionDefinitionType<T>>>(); List<Node> nodeList = childNode.get("config-property"); for(Node node: nodeList) { ConfigPropertyType<ConnectionDefinitionType<T>> type = new ConfigPropertyTypeImpl<ConnectionDefinitionType<T>>(this, "config-property", childNode, node); list.add(type); // depends on control dependency: [for], data = [none] } return list; } }
public class class_name { @Override public PipelineEventReader<XMLEventReader, XMLEvent> getEventReader( HttpServletRequest request, HttpServletResponse response) { final PipelineEventReader<XMLEventReader, XMLEvent> pipelineEventReader = this.wrappedComponent.getEventReader(request, response); final Transformer transformer = this.transformerSource.getTransformer(request, response); // Setup a URIResolver based on the current resource loader transformer.setURIResolver(this.uriResolver); // Configure the Transformer via injected class if (this.xsltParameterSource != null) { final Map<String, Object> transformerParameters = this.xsltParameterSource.getParameters(request, response); if (transformerParameters != null) { this.logger.debug( "{} - Setting Transformer Parameters: ", this.beanName, transformerParameters); for (final Map.Entry<String, Object> transformerParametersEntry : transformerParameters.entrySet()) { final String name = transformerParametersEntry.getKey(); final Object value = transformerParametersEntry.getValue(); if (value != null) { transformer.setParameter(name, value); } } } final Properties outputProperties = this.xsltParameterSource.getOutputProperties(request, response); if (outputProperties != null) { this.logger.debug( "{} - Setting Transformer Output Properties: ", this.beanName, outputProperties); transformer.setOutputProperties(outputProperties); } } // The event reader from the previous component in the pipeline final XMLEventReader eventReader = pipelineEventReader.getEventReader(); // Wrap the event reader in a stream reader to avoid a JDK bug final XMLStreamReader streamReader; try { streamReader = new FixedXMLEventStreamReader(eventReader); } catch (XMLStreamException e) { throw new RuntimeException("Failed to create XMLStreamReader from XMLEventReader", e); } final Source xmlReaderSource = new StAXSource(streamReader); // Setup logging for the transform transformer.setErrorListener(this.errorListener); // Transform to a SAX ContentHandler to avoid JDK bug: // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6775588 final XMLEventBufferWriter eventWriterBuffer = new XMLEventBufferWriter(); final ContentHandler contentHandler = StaxUtils.createContentHandler(eventWriterBuffer); contentHandler.setDocumentLocator(new LocatorImpl()); final SAXResult outputTarget = new SAXResult(contentHandler); try { this.logger.debug("{} - Begining XML Transformation", this.beanName); transformer.transform(xmlReaderSource, outputTarget); this.logger.debug("{} - XML Transformation complete", this.beanName); } catch (TransformerException e) { throw new RuntimeException("Failed to transform document", e); } final String mediaType = transformer.getOutputProperty(OutputKeys.MEDIA_TYPE); final List<XMLEvent> eventBuffer = eventWriterBuffer.getEventBuffer(); final XMLEventReader outputEventReader = new XMLEventBufferReader(eventBuffer.listIterator()); final Map<String, String> outputProperties = pipelineEventReader.getOutputProperties(); final PipelineEventReaderImpl<XMLEventReader, XMLEvent> pipelineEventReaderImpl = new PipelineEventReaderImpl<XMLEventReader, XMLEvent>( outputEventReader, outputProperties); pipelineEventReaderImpl.setOutputProperty(OutputKeys.MEDIA_TYPE, mediaType); return pipelineEventReaderImpl; } }
public class class_name { @Override public PipelineEventReader<XMLEventReader, XMLEvent> getEventReader( HttpServletRequest request, HttpServletResponse response) { final PipelineEventReader<XMLEventReader, XMLEvent> pipelineEventReader = this.wrappedComponent.getEventReader(request, response); final Transformer transformer = this.transformerSource.getTransformer(request, response); // Setup a URIResolver based on the current resource loader transformer.setURIResolver(this.uriResolver); // Configure the Transformer via injected class if (this.xsltParameterSource != null) { final Map<String, Object> transformerParameters = this.xsltParameterSource.getParameters(request, response); if (transformerParameters != null) { this.logger.debug( "{} - Setting Transformer Parameters: ", this.beanName, transformerParameters); // depends on control dependency: [if], data = [none] for (final Map.Entry<String, Object> transformerParametersEntry : transformerParameters.entrySet()) { final String name = transformerParametersEntry.getKey(); final Object value = transformerParametersEntry.getValue(); if (value != null) { transformer.setParameter(name, value); // depends on control dependency: [if], data = [none] } } } final Properties outputProperties = this.xsltParameterSource.getOutputProperties(request, response); if (outputProperties != null) { this.logger.debug( "{} - Setting Transformer Output Properties: ", this.beanName, outputProperties); // depends on control dependency: [if], data = [none] transformer.setOutputProperties(outputProperties); // depends on control dependency: [if], data = [(outputProperties] } } // The event reader from the previous component in the pipeline final XMLEventReader eventReader = pipelineEventReader.getEventReader(); // Wrap the event reader in a stream reader to avoid a JDK bug final XMLStreamReader streamReader; try { streamReader = new FixedXMLEventStreamReader(eventReader); // depends on control dependency: [try], data = [none] } catch (XMLStreamException e) { throw new RuntimeException("Failed to create XMLStreamReader from XMLEventReader", e); } // depends on control dependency: [catch], data = [none] final Source xmlReaderSource = new StAXSource(streamReader); // Setup logging for the transform transformer.setErrorListener(this.errorListener); // Transform to a SAX ContentHandler to avoid JDK bug: // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6775588 final XMLEventBufferWriter eventWriterBuffer = new XMLEventBufferWriter(); final ContentHandler contentHandler = StaxUtils.createContentHandler(eventWriterBuffer); contentHandler.setDocumentLocator(new LocatorImpl()); final SAXResult outputTarget = new SAXResult(contentHandler); try { this.logger.debug("{} - Begining XML Transformation", this.beanName); // depends on control dependency: [try], data = [none] transformer.transform(xmlReaderSource, outputTarget); // depends on control dependency: [try], data = [none] this.logger.debug("{} - XML Transformation complete", this.beanName); // depends on control dependency: [try], data = [none] } catch (TransformerException e) { throw new RuntimeException("Failed to transform document", e); } // depends on control dependency: [catch], data = [none] final String mediaType = transformer.getOutputProperty(OutputKeys.MEDIA_TYPE); final List<XMLEvent> eventBuffer = eventWriterBuffer.getEventBuffer(); final XMLEventReader outputEventReader = new XMLEventBufferReader(eventBuffer.listIterator()); final Map<String, String> outputProperties = pipelineEventReader.getOutputProperties(); final PipelineEventReaderImpl<XMLEventReader, XMLEvent> pipelineEventReaderImpl = new PipelineEventReaderImpl<XMLEventReader, XMLEvent>( outputEventReader, outputProperties); pipelineEventReaderImpl.setOutputProperty(OutputKeys.MEDIA_TYPE, mediaType); return pipelineEventReaderImpl; } }
public class class_name { public static InetAddress forUriString(String hostAddr) { Preconditions.checkNotNull(hostAddr); // Decide if this should be an IPv6 or IPv4 address. String ipString; int expectBytes; if (hostAddr.startsWith("[") && hostAddr.endsWith("]")) { ipString = hostAddr.substring(1, hostAddr.length() - 1); expectBytes = 16; } else { ipString = hostAddr; expectBytes = 4; } // Parse the address, and make sure the length/version is correct. byte[] addr = ipStringToBytes(ipString); if (addr == null || addr.length != expectBytes) { throw new IllegalArgumentException( String.format("Not a valid URI IP literal: '%s'", hostAddr)); } return bytesToInetAddress(addr); } }
public class class_name { public static InetAddress forUriString(String hostAddr) { Preconditions.checkNotNull(hostAddr); // Decide if this should be an IPv6 or IPv4 address. String ipString; int expectBytes; if (hostAddr.startsWith("[") && hostAddr.endsWith("]")) { ipString = hostAddr.substring(1, hostAddr.length() - 1); // depends on control dependency: [if], data = [none] expectBytes = 16; // depends on control dependency: [if], data = [none] } else { ipString = hostAddr; // depends on control dependency: [if], data = [none] expectBytes = 4; // depends on control dependency: [if], data = [none] } // Parse the address, and make sure the length/version is correct. byte[] addr = ipStringToBytes(ipString); if (addr == null || addr.length != expectBytes) { throw new IllegalArgumentException( String.format("Not a valid URI IP literal: '%s'", hostAddr)); } return bytesToInetAddress(addr); } }
public class class_name { public static FormatterBuilder createFormatterBuilder(Properties formatterProperties) throws Exception { FormatterBuilder builder; AbstractFormatterFactory factory; if (formatterProperties.size() > 0) { String formatterClass = formatterProperties.getProperty("formatter"); String format = formatterProperties.getProperty("format", "csv"); Class<?> classz = Class.forName(formatterClass); Class<?>[] ctorParmTypes = new Class[]{ String.class, Properties.class }; Constructor<?> ctor = classz.getDeclaredConstructor(ctorParmTypes); Object[] ctorParms = new Object[]{ format, formatterProperties }; factory = new AbstractFormatterFactory() { @Override public Formatter create(String formatName, Properties props) { try { return (Formatter) ctor.newInstance(ctorParms); } catch (Exception e) { VoltDB.crashLocalVoltDB("Failed to create formatter " + formatName); return null; } } }; builder = new FormatterBuilder(format, formatterProperties); } else { factory = new VoltCSVFormatterFactory(); Properties props = new Properties(); factory.create("csv", props); builder = new FormatterBuilder("csv", props); } builder.setFormatterFactory(factory); return builder; } }
public class class_name { public static FormatterBuilder createFormatterBuilder(Properties formatterProperties) throws Exception { FormatterBuilder builder; AbstractFormatterFactory factory; if (formatterProperties.size() > 0) { String formatterClass = formatterProperties.getProperty("formatter"); String format = formatterProperties.getProperty("format", "csv"); Class<?> classz = Class.forName(formatterClass); Class<?>[] ctorParmTypes = new Class[]{ String.class, Properties.class }; Constructor<?> ctor = classz.getDeclaredConstructor(ctorParmTypes); Object[] ctorParms = new Object[]{ format, formatterProperties }; factory = new AbstractFormatterFactory() { @Override public Formatter create(String formatName, Properties props) { try { return (Formatter) ctor.newInstance(ctorParms); // depends on control dependency: [try], data = [none] } catch (Exception e) { VoltDB.crashLocalVoltDB("Failed to create formatter " + formatName); return null; } // depends on control dependency: [catch], data = [none] } }; builder = new FormatterBuilder(format, formatterProperties); } else { factory = new VoltCSVFormatterFactory(); Properties props = new Properties(); factory.create("csv", props); builder = new FormatterBuilder("csv", props); } builder.setFormatterFactory(factory); return builder; } }
public class class_name { static Dimension getSize(int pOriginalWidth, int pOriginalHeight, int pWidth, int pHeight, boolean pPercent, boolean pUniform) { // If uniform, make sure width and height are scaled the same amount // (use ONLY height or ONLY width). // // Algorithm: // if uniform // if newHeight not set // find ratio newWidth / oldWidth // oldHeight *= ratio // else if newWidth not set // find ratio newWidth / oldWidth // oldHeight *= ratio // else // find both ratios and use the smallest one // (this will be the largest version of the image that fits // inside the rectangle given) // (if PERCENT, just use smallest percentage). // // If units is percent, we only need old height and width float ratio; if (pPercent) { if (pWidth >= 0 && pHeight >= 0) { // Non-uniform pWidth = Math.round((float) pOriginalWidth * (float) pWidth / 100f); pHeight = Math.round((float) pOriginalHeight * (float) pHeight / 100f); } else if (pWidth >= 0) { // Find ratio from pWidth ratio = (float) pWidth / 100f; pWidth = Math.round((float) pOriginalWidth * ratio); pHeight = Math.round((float) pOriginalHeight * ratio); } else if (pHeight >= 0) { // Find ratio from pHeight ratio = (float) pHeight / 100f; pWidth = Math.round((float) pOriginalWidth * ratio); pHeight = Math.round((float) pOriginalHeight * ratio); } // Else: No scale } else { if (pUniform) { if (pWidth >= 0 && pHeight >= 0) { // Compute both ratios ratio = (float) pWidth / (float) pOriginalWidth; float heightRatio = (float) pHeight / (float) pOriginalHeight; // Find the largest ratio, and use that for both if (heightRatio < ratio) { ratio = heightRatio; pWidth = Math.round((float) pOriginalWidth * ratio); } else { pHeight = Math.round((float) pOriginalHeight * ratio); } } else if (pWidth >= 0) { // Find ratio from pWidth ratio = (float) pWidth / (float) pOriginalWidth; pHeight = Math.round((float) pOriginalHeight * ratio); } else if (pHeight >= 0) { // Find ratio from pHeight ratio = (float) pHeight / (float) pOriginalHeight; pWidth = Math.round((float) pOriginalWidth * ratio); } // Else: No scale } } // Default is no scale, just work as a proxy if (pWidth < 0) { pWidth = pOriginalWidth; } if (pHeight < 0) { pHeight = pOriginalHeight; } // Create new Dimension object and return return new Dimension(pWidth, pHeight); } }
public class class_name { static Dimension getSize(int pOriginalWidth, int pOriginalHeight, int pWidth, int pHeight, boolean pPercent, boolean pUniform) { // If uniform, make sure width and height are scaled the same amount // (use ONLY height or ONLY width). // // Algorithm: // if uniform // if newHeight not set // find ratio newWidth / oldWidth // oldHeight *= ratio // else if newWidth not set // find ratio newWidth / oldWidth // oldHeight *= ratio // else // find both ratios and use the smallest one // (this will be the largest version of the image that fits // inside the rectangle given) // (if PERCENT, just use smallest percentage). // // If units is percent, we only need old height and width float ratio; if (pPercent) { if (pWidth >= 0 && pHeight >= 0) { // Non-uniform pWidth = Math.round((float) pOriginalWidth * (float) pWidth / 100f); // depends on control dependency: [if], data = [none] pHeight = Math.round((float) pOriginalHeight * (float) pHeight / 100f); // depends on control dependency: [if], data = [none] } else if (pWidth >= 0) { // Find ratio from pWidth ratio = (float) pWidth / 100f; // depends on control dependency: [if], data = [none] pWidth = Math.round((float) pOriginalWidth * ratio); // depends on control dependency: [if], data = [none] pHeight = Math.round((float) pOriginalHeight * ratio); // depends on control dependency: [if], data = [none] } else if (pHeight >= 0) { // Find ratio from pHeight ratio = (float) pHeight / 100f; // depends on control dependency: [if], data = [none] pWidth = Math.round((float) pOriginalWidth * ratio); // depends on control dependency: [if], data = [none] pHeight = Math.round((float) pOriginalHeight * ratio); // depends on control dependency: [if], data = [none] } // Else: No scale } else { if (pUniform) { if (pWidth >= 0 && pHeight >= 0) { // Compute both ratios ratio = (float) pWidth / (float) pOriginalWidth; // depends on control dependency: [if], data = [none] float heightRatio = (float) pHeight / (float) pOriginalHeight; // Find the largest ratio, and use that for both if (heightRatio < ratio) { ratio = heightRatio; // depends on control dependency: [if], data = [none] pWidth = Math.round((float) pOriginalWidth * ratio); // depends on control dependency: [if], data = [ratio)] } else { pHeight = Math.round((float) pOriginalHeight * ratio); // depends on control dependency: [if], data = [ratio)] } } else if (pWidth >= 0) { // Find ratio from pWidth ratio = (float) pWidth / (float) pOriginalWidth; // depends on control dependency: [if], data = [none] pHeight = Math.round((float) pOriginalHeight * ratio); // depends on control dependency: [if], data = [none] } else if (pHeight >= 0) { // Find ratio from pHeight ratio = (float) pHeight / (float) pOriginalHeight; // depends on control dependency: [if], data = [none] pWidth = Math.round((float) pOriginalWidth * ratio); // depends on control dependency: [if], data = [none] } // Else: No scale } } // Default is no scale, just work as a proxy if (pWidth < 0) { pWidth = pOriginalWidth; // depends on control dependency: [if], data = [none] } if (pHeight < 0) { pHeight = pOriginalHeight; // depends on control dependency: [if], data = [none] } // Create new Dimension object and return return new Dimension(pWidth, pHeight); } }
public class class_name { boolean matchText( final boolean blockMatching, final int markupLevel, final int markupBlockIndex) { checkMarkupLevel(markupLevel); if (this.markupSelectorItem.anyLevel() || markupLevel == 0 || (this.prev != null && this.prev.matchedMarkupLevels[markupLevel - 1])) { // This text has not matched yet, but might match, so we should check this.matchesThisLevel = this.markupSelectorItem.matchesText(markupBlockIndex, this.markupBlockMatchingCounter); if (matchesPreviousOrCurrentLevel(markupLevel)) { // This filter was already matched by a previous level (through an "open" event), so just delegate to next. if (this.next != null) { return this.next.matchText(blockMatching, markupLevel, markupBlockIndex); } return (blockMatching? true : this.matchesThisLevel); } else if (this.matchesThisLevel) { // This filter was not matched before. So the fact that it matches now means we need to consume it, // therefore not delegating. return (this.next == null); } } else if (matchesPreviousOrCurrentLevel(markupLevel)) { // This filter was already matched by a previous level (through an "open" event), so just delegate to next. if (this.next != null) { return this.next.matchText(blockMatching, markupLevel, markupBlockIndex); } return blockMatching; } return false; } }
public class class_name { boolean matchText( final boolean blockMatching, final int markupLevel, final int markupBlockIndex) { checkMarkupLevel(markupLevel); if (this.markupSelectorItem.anyLevel() || markupLevel == 0 || (this.prev != null && this.prev.matchedMarkupLevels[markupLevel - 1])) { // This text has not matched yet, but might match, so we should check this.matchesThisLevel = this.markupSelectorItem.matchesText(markupBlockIndex, this.markupBlockMatchingCounter); // depends on control dependency: [if], data = [none] if (matchesPreviousOrCurrentLevel(markupLevel)) { // This filter was already matched by a previous level (through an "open" event), so just delegate to next. if (this.next != null) { return this.next.matchText(blockMatching, markupLevel, markupBlockIndex); // depends on control dependency: [if], data = [none] } return (blockMatching? true : this.matchesThisLevel); // depends on control dependency: [if], data = [none] } else if (this.matchesThisLevel) { // This filter was not matched before. So the fact that it matches now means we need to consume it, // therefore not delegating. return (this.next == null); // depends on control dependency: [if], data = [none] } } else if (matchesPreviousOrCurrentLevel(markupLevel)) { // This filter was already matched by a previous level (through an "open" event), so just delegate to next. if (this.next != null) { return this.next.matchText(blockMatching, markupLevel, markupBlockIndex); // depends on control dependency: [if], data = [none] } return blockMatching; // depends on control dependency: [if], data = [none] } return false; } }
public class class_name { public VpnConnectionOptionsSpecification withTunnelOptions(VpnTunnelOptionsSpecification... tunnelOptions) { if (this.tunnelOptions == null) { setTunnelOptions(new com.amazonaws.internal.SdkInternalList<VpnTunnelOptionsSpecification>(tunnelOptions.length)); } for (VpnTunnelOptionsSpecification ele : tunnelOptions) { this.tunnelOptions.add(ele); } return this; } }
public class class_name { public VpnConnectionOptionsSpecification withTunnelOptions(VpnTunnelOptionsSpecification... tunnelOptions) { if (this.tunnelOptions == null) { setTunnelOptions(new com.amazonaws.internal.SdkInternalList<VpnTunnelOptionsSpecification>(tunnelOptions.length)); // depends on control dependency: [if], data = [none] } for (VpnTunnelOptionsSpecification ele : tunnelOptions) { this.tunnelOptions.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { protected String findValue(T object,String path) { String value=null; if((path!=null)&&(object!=null)) { //find value value=this.findValueImpl(object,path); if(value!=null) { value=value.trim(); if(value.length()==0) { value=null; } } } return value; } }
public class class_name { protected String findValue(T object,String path) { String value=null; if((path!=null)&&(object!=null)) { //find value value=this.findValueImpl(object,path); // depends on control dependency: [if], data = [none] if(value!=null) { value=value.trim(); // depends on control dependency: [if], data = [none] if(value.length()==0) { value=null; // depends on control dependency: [if], data = [none] } } } return value; } }
public class class_name { public void writer(String bucketName, String blobName) throws IOException { // [START writer] BlobId blobId = BlobId.of(bucketName, blobName); byte[] content = "Hello, World!".getBytes(UTF_8); BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build(); try (WriteChannel writer = storage.writer(blobInfo)) { try { writer.write(ByteBuffer.wrap(content, 0, content.length)); } catch (Exception ex) { // handle exception } } // [END writer] } }
public class class_name { public void writer(String bucketName, String blobName) throws IOException { // [START writer] BlobId blobId = BlobId.of(bucketName, blobName); byte[] content = "Hello, World!".getBytes(UTF_8); BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build(); try (WriteChannel writer = storage.writer(blobInfo)) { try { writer.write(ByteBuffer.wrap(content, 0, content.length)); // depends on control dependency: [try], data = [none] } catch (Exception ex) { // handle exception } // depends on control dependency: [catch], data = [none] } // [END writer] } }
public class class_name { private void saveNestedVariables() { if (nestedVars != null) { Iterator iter = nestedVars.iterator(); while (iter.hasNext()) { String varName = (String) iter.next(); varName = findAlias(varName); Object obj = invokingJspCtxt.getAttribute(varName); if (obj != null) { originalNestedVars.put(varName, obj); } } } } }
public class class_name { private void saveNestedVariables() { if (nestedVars != null) { Iterator iter = nestedVars.iterator(); while (iter.hasNext()) { String varName = (String) iter.next(); varName = findAlias(varName); // depends on control dependency: [while], data = [none] Object obj = invokingJspCtxt.getAttribute(varName); if (obj != null) { originalNestedVars.put(varName, obj); // depends on control dependency: [if], data = [none] } } } } }
public class class_name { public static String replace(String text, String searchString, String replacement, int max) { if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) { return text; } int start = 0; int end = text.indexOf(searchString, start); if (end == INDEX_NOT_FOUND) { return text; } int replLength = searchString.length(); int increase = replacement.length() - replLength; increase = (increase < 0 ? 0 : increase); increase *= (max < 0 ? 16 : (max > 64 ? 64 : max)); StringBuilder buf = new StringBuilder(text.length() + increase); while (end != INDEX_NOT_FOUND) { buf.append(text.substring(start, end)).append(replacement); start = end + replLength; if (--max == 0) { break; } end = text.indexOf(searchString, start); } buf.append(text.substring(start)); return buf.toString(); } }
public class class_name { public static String replace(String text, String searchString, String replacement, int max) { if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) { return text; // depends on control dependency: [if], data = [none] } int start = 0; int end = text.indexOf(searchString, start); if (end == INDEX_NOT_FOUND) { return text; // depends on control dependency: [if], data = [none] } int replLength = searchString.length(); int increase = replacement.length() - replLength; increase = (increase < 0 ? 0 : increase); increase *= (max < 0 ? 16 : (max > 64 ? 64 : max)); StringBuilder buf = new StringBuilder(text.length() + increase); while (end != INDEX_NOT_FOUND) { buf.append(text.substring(start, end)).append(replacement); // depends on control dependency: [while], data = [none] start = end + replLength; // depends on control dependency: [while], data = [none] if (--max == 0) { break; } end = text.indexOf(searchString, start); // depends on control dependency: [while], data = [none] } buf.append(text.substring(start)); return buf.toString(); } }
public class class_name { public static void runExample(AdManagerServices adManagerServices, AdManagerSession session) throws RemoteException { CdnConfigurationServiceInterface cdnConfigurationService = adManagerServices.get(session, CdnConfigurationServiceInterface.class); // Create a statement to select CDN configurations. int pageSize = StatementBuilder.SUGGESTED_PAGE_LIMIT; StatementBuilder statementBuilder = new StatementBuilder().orderBy("id ASC").limit(pageSize); // Retrieve a small amount of CDN configurations at a time, paging through until all // CDN configurations have been retrieved. int totalResultSetSize = 0; do { CdnConfigurationPage page = cdnConfigurationService.getCdnConfigurationsByStatement(statementBuilder.toStatement()); // Print out some information for each CDN configuration. if (page.getResults() != null) { totalResultSetSize = page.getTotalResultSetSize(); int i = page.getStartIndex(); for (CdnConfiguration cdnConfiguration : page.getResults()) { System.out.printf( "%d) CDN configuration with ID %d and name '%s' was found.%n", i++, cdnConfiguration.getId(), cdnConfiguration.getName()); } } statementBuilder.increaseOffsetBy(pageSize); } while (statementBuilder.getOffset() < totalResultSetSize); System.out.printf("Number of results found: %d%n", totalResultSetSize); } }
public class class_name { public static void runExample(AdManagerServices adManagerServices, AdManagerSession session) throws RemoteException { CdnConfigurationServiceInterface cdnConfigurationService = adManagerServices.get(session, CdnConfigurationServiceInterface.class); // Create a statement to select CDN configurations. int pageSize = StatementBuilder.SUGGESTED_PAGE_LIMIT; StatementBuilder statementBuilder = new StatementBuilder().orderBy("id ASC").limit(pageSize); // Retrieve a small amount of CDN configurations at a time, paging through until all // CDN configurations have been retrieved. int totalResultSetSize = 0; do { CdnConfigurationPage page = cdnConfigurationService.getCdnConfigurationsByStatement(statementBuilder.toStatement()); // Print out some information for each CDN configuration. if (page.getResults() != null) { totalResultSetSize = page.getTotalResultSetSize(); // depends on control dependency: [if], data = [none] int i = page.getStartIndex(); for (CdnConfiguration cdnConfiguration : page.getResults()) { System.out.printf( "%d) CDN configuration with ID %d and name '%s' was found.%n", i++, cdnConfiguration.getId(), cdnConfiguration.getName()); // depends on control dependency: [for], data = [cdnConfiguration] } } statementBuilder.increaseOffsetBy(pageSize); } while (statementBuilder.getOffset() < totalResultSetSize); System.out.printf("Number of results found: %d%n", totalResultSetSize); } }
public class class_name { public static UUID getOrCreateUserToken() { UUID userToken; if (Request.getPerThreadRequestData().getRequestId() != null) { try { userToken = UUID.fromString(Request.getPerThreadRequestData().getRequestId()); } catch (final IllegalArgumentException ignored) { userToken = UUIDs.randomUUID(); } } else { userToken = UUIDs.randomUUID(); } return userToken; } }
public class class_name { public static UUID getOrCreateUserToken() { UUID userToken; if (Request.getPerThreadRequestData().getRequestId() != null) { try { userToken = UUID.fromString(Request.getPerThreadRequestData().getRequestId()); // depends on control dependency: [try], data = [none] } catch (final IllegalArgumentException ignored) { userToken = UUIDs.randomUUID(); } // depends on control dependency: [catch], data = [none] } else { userToken = UUIDs.randomUUID(); // depends on control dependency: [if], data = [none] } return userToken; } }
public class class_name { public GVRTexture loadTexture(GVRAndroidResource resource, TextureCallback callback, GVRTextureParameters texparams, int priority, int quality) { if (texparams == null) { texparams = mDefaultTextureParameters; } GVRTexture texture = new GVRTexture(mContext, texparams); TextureRequest request = new TextureRequest(resource, texture, callback); GVRAsynchronousResourceLoader.loadTexture(mContext, mTextureCache, request, resource, priority, quality); return texture; } }
public class class_name { public GVRTexture loadTexture(GVRAndroidResource resource, TextureCallback callback, GVRTextureParameters texparams, int priority, int quality) { if (texparams == null) { texparams = mDefaultTextureParameters; // depends on control dependency: [if], data = [none] } GVRTexture texture = new GVRTexture(mContext, texparams); TextureRequest request = new TextureRequest(resource, texture, callback); GVRAsynchronousResourceLoader.loadTexture(mContext, mTextureCache, request, resource, priority, quality); return texture; } }
public class class_name { public void saveToFilename(String file) { try { File tgtFile = new File(file); BufferedWriter out = new BufferedWriter(new FileWriter(tgtFile)); // output index first, blank delimiter, outline feature index, then weights labelIndex.saveToWriter(out); featureIndex.saveToWriter(out); int numLabels = labelIndex.size(); int numFeatures = featureIndex.size(); for (int featIndex=0; featIndex<numFeatures; featIndex++) { for (int labelIndex=0;labelIndex<numLabels;labelIndex++) { out.write(String.valueOf(featIndex)); out.write(TEXT_SERIALIZATION_DELIMITER); out.write(String.valueOf(labelIndex)); out.write(TEXT_SERIALIZATION_DELIMITER); out.write(String.valueOf(weight(featIndex, labelIndex))); out.write("\n"); } } // write out thresholds: first item after blank is the number of thresholds, after is the threshold array values. out.write("\n"); out.write(String.valueOf(thresholds.length)); out.write("\n"); for (double val : thresholds) { out.write(String.valueOf(val)); out.write("\n"); } out.close(); } catch (Exception e) { System.err.println("Error attempting to save classifier to file="+file); e.printStackTrace(); } } }
public class class_name { public void saveToFilename(String file) { try { File tgtFile = new File(file); BufferedWriter out = new BufferedWriter(new FileWriter(tgtFile)); // output index first, blank delimiter, outline feature index, then weights labelIndex.saveToWriter(out); // depends on control dependency: [try], data = [none] featureIndex.saveToWriter(out); // depends on control dependency: [try], data = [none] int numLabels = labelIndex.size(); int numFeatures = featureIndex.size(); for (int featIndex=0; featIndex<numFeatures; featIndex++) { for (int labelIndex=0;labelIndex<numLabels;labelIndex++) { out.write(String.valueOf(featIndex)); // depends on control dependency: [for], data = [none] out.write(TEXT_SERIALIZATION_DELIMITER); // depends on control dependency: [for], data = [none] out.write(String.valueOf(labelIndex)); // depends on control dependency: [for], data = [labelIndex] out.write(TEXT_SERIALIZATION_DELIMITER); // depends on control dependency: [for], data = [none] out.write(String.valueOf(weight(featIndex, labelIndex))); // depends on control dependency: [for], data = [labelIndex] out.write("\n"); // depends on control dependency: [for], data = [none] } } // write out thresholds: first item after blank is the number of thresholds, after is the threshold array values. out.write("\n"); // depends on control dependency: [try], data = [none] out.write(String.valueOf(thresholds.length)); // depends on control dependency: [try], data = [none] out.write("\n"); // depends on control dependency: [try], data = [none] for (double val : thresholds) { out.write(String.valueOf(val)); // depends on control dependency: [for], data = [val] out.write("\n"); // depends on control dependency: [for], data = [none] } out.close(); // depends on control dependency: [try], data = [none] } catch (Exception e) { System.err.println("Error attempting to save classifier to file="+file); e.printStackTrace(); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static final void chkBMTFromAnnotations(Method[] beanMethods, J2EEName j2eeName) { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(tc, "chkBMTFromAnnotations"); javax.ejb.TransactionAttribute methTranAttr = null; for (int i = 0; i < beanMethods.length; i++) { // Unless a Remove method is added the last index in the beanMethods // array will be null causing an NPE. So we need to check for // null first. if (beanMethods[i] != null) { methTranAttr = beanMethods[i].getAnnotation(javax.ejb.TransactionAttribute.class); if (methTranAttr == null) { methTranAttr = beanMethods[i].getDeclaringClass().getAnnotation(javax.ejb.TransactionAttribute.class); } // If a Transaction attribute exists then create a warning message. if (methTranAttr != null) { Tr.warning(tc, "BMT_DEFINES_CMT_ATTRIBUTES_CNTR0067W", new Object[] { j2eeName }); } } } if (isTraceOn && tc.isEntryEnabled()) Tr.exit(tc, "chkBMTFromAnnotations"); return; } }
public class class_name { public static final void chkBMTFromAnnotations(Method[] beanMethods, J2EEName j2eeName) { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(tc, "chkBMTFromAnnotations"); javax.ejb.TransactionAttribute methTranAttr = null; for (int i = 0; i < beanMethods.length; i++) { // Unless a Remove method is added the last index in the beanMethods // array will be null causing an NPE. So we need to check for // null first. if (beanMethods[i] != null) { methTranAttr = beanMethods[i].getAnnotation(javax.ejb.TransactionAttribute.class); // depends on control dependency: [if], data = [none] if (methTranAttr == null) { methTranAttr = beanMethods[i].getDeclaringClass().getAnnotation(javax.ejb.TransactionAttribute.class); // depends on control dependency: [if], data = [none] } // If a Transaction attribute exists then create a warning message. if (methTranAttr != null) { Tr.warning(tc, "BMT_DEFINES_CMT_ATTRIBUTES_CNTR0067W", new Object[] { j2eeName }); // depends on control dependency: [if], data = [none] } } } if (isTraceOn && tc.isEntryEnabled()) Tr.exit(tc, "chkBMTFromAnnotations"); return; } }
public class class_name { protected void renderDirectly(int statusCode, RouteContext routeContext) { if (application.getPippoSettings().isProd()) { routeContext.getResponse().commit(); } else { if (statusCode == HttpConstants.StatusCode.NOT_FOUND) { StringBuilder content = new StringBuilder(); content.append("<html><body>"); content.append("<pre>"); content.append("Cannot find a route for '"); content.append(routeContext.getRequestMethod()).append(' ').append(routeContext.getRequestUri()); content.append('\''); content.append('\n'); content.append("Available routes:"); content.append('\n'); List<Route> routes = application.getRouter().getRoutes(); for (Route route : routes) { content.append('\t').append(route.getRequestMethod()).append(' ').append(route.getUriPattern()); content.append('\n'); } content.append("</pre>"); content.append("</body></html>"); routeContext.send(content); } else if (statusCode == HttpConstants.StatusCode.INTERNAL_ERROR) { StringBuilder content = new StringBuilder(); content.append("<html><body>"); content.append("<pre>"); Error error = prepareError(statusCode, routeContext); content.append(error.toString()); content.append("</pre>"); content.append("</body></html>"); routeContext.send(content); } } } }
public class class_name { protected void renderDirectly(int statusCode, RouteContext routeContext) { if (application.getPippoSettings().isProd()) { routeContext.getResponse().commit(); // depends on control dependency: [if], data = [none] } else { if (statusCode == HttpConstants.StatusCode.NOT_FOUND) { StringBuilder content = new StringBuilder(); content.append("<html><body>"); // depends on control dependency: [if], data = [none] content.append("<pre>"); // depends on control dependency: [if], data = [none] content.append("Cannot find a route for '"); // depends on control dependency: [if], data = [none] content.append(routeContext.getRequestMethod()).append(' ').append(routeContext.getRequestUri()); // depends on control dependency: [if], data = [none] content.append('\''); // depends on control dependency: [if], data = [none] content.append('\n'); // depends on control dependency: [if], data = [none] content.append("Available routes:"); // depends on control dependency: [if], data = [none] content.append('\n'); // depends on control dependency: [if], data = [none] List<Route> routes = application.getRouter().getRoutes(); for (Route route : routes) { content.append('\t').append(route.getRequestMethod()).append(' ').append(route.getUriPattern()); // depends on control dependency: [for], data = [route] content.append('\n'); // depends on control dependency: [for], data = [none] } content.append("</pre>"); // depends on control dependency: [if], data = [none] content.append("</body></html>"); // depends on control dependency: [if], data = [none] routeContext.send(content); // depends on control dependency: [if], data = [none] } else if (statusCode == HttpConstants.StatusCode.INTERNAL_ERROR) { StringBuilder content = new StringBuilder(); content.append("<html><body>"); // depends on control dependency: [if], data = [none] content.append("<pre>"); // depends on control dependency: [if], data = [none] Error error = prepareError(statusCode, routeContext); content.append(error.toString()); // depends on control dependency: [if], data = [none] content.append("</pre>"); // depends on control dependency: [if], data = [none] content.append("</body></html>"); // depends on control dependency: [if], data = [none] routeContext.send(content); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public GetReservedInstancesExchangeQuoteResult withReservedInstanceValueSet(ReservedInstanceReservationValue... reservedInstanceValueSet) { if (this.reservedInstanceValueSet == null) { setReservedInstanceValueSet(new com.amazonaws.internal.SdkInternalList<ReservedInstanceReservationValue>(reservedInstanceValueSet.length)); } for (ReservedInstanceReservationValue ele : reservedInstanceValueSet) { this.reservedInstanceValueSet.add(ele); } return this; } }
public class class_name { public GetReservedInstancesExchangeQuoteResult withReservedInstanceValueSet(ReservedInstanceReservationValue... reservedInstanceValueSet) { if (this.reservedInstanceValueSet == null) { setReservedInstanceValueSet(new com.amazonaws.internal.SdkInternalList<ReservedInstanceReservationValue>(reservedInstanceValueSet.length)); // depends on control dependency: [if], data = [none] } for (ReservedInstanceReservationValue ele : reservedInstanceValueSet) { this.reservedInstanceValueSet.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { public void addDirtyRegion (Rectangle rect) { // Only add dirty regions where rect intersects our actual media as the set region will // propagate out to the repaint manager. for (AbstractMedia media : _metamgr) { Rectangle intersection = media.getBounds().intersection(rect); if (!intersection.isEmpty()) { _metamgr.getRegionManager().addDirtyRegion(intersection); } } } }
public class class_name { public void addDirtyRegion (Rectangle rect) { // Only add dirty regions where rect intersects our actual media as the set region will // propagate out to the repaint manager. for (AbstractMedia media : _metamgr) { Rectangle intersection = media.getBounds().intersection(rect); if (!intersection.isEmpty()) { _metamgr.getRegionManager().addDirtyRegion(intersection); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public static char[] toPrimitive(Character[] array, char valueForNull) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_CHAR_ARRAY; } final char[] result = new char[array.length]; for (int i = 0; i < array.length; i++) { Character b = array[i]; result[i] = (b == null ? valueForNull : b); } return result; } }
public class class_name { public static char[] toPrimitive(Character[] array, char valueForNull) { if (array == null) { return null; // depends on control dependency: [if], data = [none] } else if (array.length == 0) { return EMPTY_CHAR_ARRAY; // depends on control dependency: [if], data = [none] } final char[] result = new char[array.length]; for (int i = 0; i < array.length; i++) { Character b = array[i]; result[i] = (b == null ? valueForNull : b); // depends on control dependency: [for], data = [i] } return result; } }
public class class_name { public FacesConfigPropertyType<FacesConfigConverterType<T>> getOrCreateProperty() { List<Node> nodeList = childNode.get("property"); if (nodeList != null && nodeList.size() > 0) { return new FacesConfigPropertyTypeImpl<FacesConfigConverterType<T>>(this, "property", childNode, nodeList.get(0)); } return createProperty(); } }
public class class_name { public FacesConfigPropertyType<FacesConfigConverterType<T>> getOrCreateProperty() { List<Node> nodeList = childNode.get("property"); if (nodeList != null && nodeList.size() > 0) { return new FacesConfigPropertyTypeImpl<FacesConfigConverterType<T>>(this, "property", childNode, nodeList.get(0)); // depends on control dependency: [if], data = [none] } return createProperty(); } }
public class class_name { public void remove(E edge) { if (! edge.added){ return; } boolean contained; contained = edges.remove(edge); assert(contained); contained = edge.getChild().inEdges.remove(edge); assert(contained); contained = edge.getParent().outEdges.remove(edge); assert(contained); edge.added = false; } }
public class class_name { public void remove(E edge) { if (! edge.added){ return; // depends on control dependency: [if], data = [none] } boolean contained; contained = edges.remove(edge); assert(contained); contained = edge.getChild().inEdges.remove(edge); assert(contained); contained = edge.getParent().outEdges.remove(edge); assert(contained); edge.added = false; } }
public class class_name { public static String encode(Byte[] in) { byte[] tmp = new byte[in.length]; for(int i = 0; i < tmp.length; i++) { tmp[i] = in[i]; } return encode(tmp); } }
public class class_name { public static String encode(Byte[] in) { byte[] tmp = new byte[in.length]; for(int i = 0; i < tmp.length; i++) { tmp[i] = in[i]; // depends on control dependency: [for], data = [i] } return encode(tmp); } }
public class class_name { @Override public IScan getScanByNumClosest(int scanNum) { IScan result = null; Map.Entry<Integer, IScan> lower = getNum2scan().lowerEntry(scanNum); Map.Entry<Integer, IScan> upper = getNum2scan().ceilingEntry(scanNum); if (upper != null && lower != null) { result = Integer.compare(lower.getKey(), upper.getKey()) > 0 ? lower.getValue() : upper.getValue(); } else if (upper != null) { result = upper.getValue(); } else if (lower != null) { result = lower.getValue(); } return result; } }
public class class_name { @Override public IScan getScanByNumClosest(int scanNum) { IScan result = null; Map.Entry<Integer, IScan> lower = getNum2scan().lowerEntry(scanNum); Map.Entry<Integer, IScan> upper = getNum2scan().ceilingEntry(scanNum); if (upper != null && lower != null) { result = Integer.compare(lower.getKey(), upper.getKey()) > 0 ? lower.getValue() : upper.getValue(); // depends on control dependency: [if], data = [none] } else if (upper != null) { result = upper.getValue(); // depends on control dependency: [if], data = [none] } else if (lower != null) { result = lower.getValue(); // depends on control dependency: [if], data = [none] } return result; } }
public class class_name { public Object get(Object old) { if (old == null || old.getClass() == String.class) { return old; } return oldNewMap.get(old); } }
public class class_name { public Object get(Object old) { if (old == null || old.getClass() == String.class) { return old; // depends on control dependency: [if], data = [none] } return oldNewMap.get(old); } }
public class class_name { public Element appendToXml(Element parentNode, List<String> parametersToIgnore) { for (Map.Entry<String, Serializable> entry : m_configurationObjects.entrySet()) { String name = entry.getKey(); // check if the parameter should be ignored if ((parametersToIgnore == null) || !parametersToIgnore.contains(name)) { // now serialize the parameter name and value Object value = entry.getValue(); if (value instanceof List) { @SuppressWarnings("unchecked") List<String> values = (List<String>)value; for (String strValue : values) { // use the original String as value Element paramNode = parentNode.addElement(I_CmsXmlConfiguration.N_PARAM); // set the name attribute paramNode.addAttribute(I_CmsXmlConfiguration.A_NAME, name); // set the text of <param> node paramNode.addText(strValue); } } else { // use the original String as value String strValue = get(name); Element paramNode = parentNode.addElement(I_CmsXmlConfiguration.N_PARAM); // set the name attribute paramNode.addAttribute(I_CmsXmlConfiguration.A_NAME, name); // set the text of <param> node paramNode.addText(strValue); } } } return parentNode; } }
public class class_name { public Element appendToXml(Element parentNode, List<String> parametersToIgnore) { for (Map.Entry<String, Serializable> entry : m_configurationObjects.entrySet()) { String name = entry.getKey(); // check if the parameter should be ignored if ((parametersToIgnore == null) || !parametersToIgnore.contains(name)) { // now serialize the parameter name and value Object value = entry.getValue(); if (value instanceof List) { @SuppressWarnings("unchecked") List<String> values = (List<String>)value; for (String strValue : values) { // use the original String as value Element paramNode = parentNode.addElement(I_CmsXmlConfiguration.N_PARAM); // set the name attribute paramNode.addAttribute(I_CmsXmlConfiguration.A_NAME, name); // depends on control dependency: [for], data = [none] // set the text of <param> node paramNode.addText(strValue); // depends on control dependency: [for], data = [strValue] } } else { // use the original String as value String strValue = get(name); Element paramNode = parentNode.addElement(I_CmsXmlConfiguration.N_PARAM); // set the name attribute paramNode.addAttribute(I_CmsXmlConfiguration.A_NAME, name); // depends on control dependency: [if], data = [none] // set the text of <param> node paramNode.addText(strValue); // depends on control dependency: [if], data = [none] } } } return parentNode; } }
public class class_name { @Action(name = "Convert XML to Json", outputs = { @Output(NAMESPACES_PREFIXES), @Output(NAMESPACES_URIS), @Output(RETURN_RESULT), @Output(RETURN_CODE), @Output(EXCEPTION) }, responses = { @Response(text = ResponseNames.SUCCESS, field = RETURN_CODE, value = SUCCESS), @Response(text = ResponseNames.FAILURE, field = RETURN_CODE, value = FAILURE) }) public Map<String, String> execute( @Param(value = XML, required = true) String xml, @Param(value = TEXT_ELEMENTS_NAME) String textElementsName, @Param(value = INCLUDE_ROOT) String includeRootElement, @Param(value = INCLUDE_ATTRIBUTES) String includeAttributes, @Param(value = PRETTY_PRINT) String prettyPrint, @Param(value = PARSING_FEATURES) String parsingFeatures) { try { includeRootElement = defaultIfEmpty(includeRootElement, TRUE); includeAttributes = defaultIfEmpty(includeAttributes, TRUE); prettyPrint = defaultIfEmpty(prettyPrint, TRUE); ValidateUtils.validateInputs(includeRootElement, includeAttributes, prettyPrint); final ConvertXmlToJsonInputs inputs = new ConvertXmlToJsonInputs.ConvertXmlToJsonInputsBuilder() .withXml(xml) .withTextElementsName(textElementsName) .withIncludeRootElement(Boolean.parseBoolean(includeRootElement)) .withIncludeAttributes(Boolean.parseBoolean(includeAttributes)) .withPrettyPrint(Boolean.parseBoolean(prettyPrint)) .withParsingFeatures(parsingFeatures) .build(); final ConvertXmlToJsonService converter = new ConvertXmlToJsonService(); final String json = converter.convertToJsonString(inputs); final Map<String, String> result = getSuccessResultsMap(json); result.put(NAMESPACES_PREFIXES, converter.getNamespacesPrefixes()); result.put(NAMESPACES_URIS, converter.getNamespacesUris()); return result; } catch (Exception e) { final Map<String, String> result = getFailureResultsMap(e); result.put(NAMESPACES_PREFIXES, EMPTY); result.put(NAMESPACES_URIS, EMPTY); return result; } } }
public class class_name { @Action(name = "Convert XML to Json", outputs = { @Output(NAMESPACES_PREFIXES), @Output(NAMESPACES_URIS), @Output(RETURN_RESULT), @Output(RETURN_CODE), @Output(EXCEPTION) }, responses = { @Response(text = ResponseNames.SUCCESS, field = RETURN_CODE, value = SUCCESS), @Response(text = ResponseNames.FAILURE, field = RETURN_CODE, value = FAILURE) }) public Map<String, String> execute( @Param(value = XML, required = true) String xml, @Param(value = TEXT_ELEMENTS_NAME) String textElementsName, @Param(value = INCLUDE_ROOT) String includeRootElement, @Param(value = INCLUDE_ATTRIBUTES) String includeAttributes, @Param(value = PRETTY_PRINT) String prettyPrint, @Param(value = PARSING_FEATURES) String parsingFeatures) { try { includeRootElement = defaultIfEmpty(includeRootElement, TRUE); // depends on control dependency: [try], data = [none] includeAttributes = defaultIfEmpty(includeAttributes, TRUE); // depends on control dependency: [try], data = [none] prettyPrint = defaultIfEmpty(prettyPrint, TRUE); // depends on control dependency: [try], data = [none] ValidateUtils.validateInputs(includeRootElement, includeAttributes, prettyPrint); // depends on control dependency: [try], data = [none] final ConvertXmlToJsonInputs inputs = new ConvertXmlToJsonInputs.ConvertXmlToJsonInputsBuilder() .withXml(xml) .withTextElementsName(textElementsName) .withIncludeRootElement(Boolean.parseBoolean(includeRootElement)) .withIncludeAttributes(Boolean.parseBoolean(includeAttributes)) .withPrettyPrint(Boolean.parseBoolean(prettyPrint)) .withParsingFeatures(parsingFeatures) .build(); final ConvertXmlToJsonService converter = new ConvertXmlToJsonService(); final String json = converter.convertToJsonString(inputs); final Map<String, String> result = getSuccessResultsMap(json); result.put(NAMESPACES_PREFIXES, converter.getNamespacesPrefixes()); // depends on control dependency: [try], data = [none] result.put(NAMESPACES_URIS, converter.getNamespacesUris()); // depends on control dependency: [try], data = [none] return result; // depends on control dependency: [try], data = [none] } catch (Exception e) { final Map<String, String> result = getFailureResultsMap(e); result.put(NAMESPACES_PREFIXES, EMPTY); result.put(NAMESPACES_URIS, EMPTY); return result; } // depends on control dependency: [catch], data = [none] } }
public class class_name { private void setExcludeDefaultInterceptors() { EJBInterceptorBinding binding = ivClassInterceptorBinding; boolean useAnnotation = false; if (binding == null) { // Use annotation provided metadata-complete is false. useAnnotation = !ivMetadataComplete; } else { // Assumption is xml overrides annotation, although EJB spec implies // interceptor-binding is used to augment annotation. Not clear what // is intended, but we are going to assume xml overrides annotation. Boolean exclude = binding.ivExcludeDefaultLevelInterceptors; if (exclude == null) { // exclude is not set in ejb-jar.xml for class level binding, // Use annotation provided metadata-complete is false. useAnnotation = !ivMetadataComplete; } else if (exclude == Boolean.TRUE) { ivExcludeDefaultFromClassLevel = true; } else { ivExcludeDefaultFromClassLevel = false; } } // If xml did not have a exclude-default-interceptor setting for // class level binding, then see if annotation indicates to exclude // default level interceptors. if (useAnnotation) { ExcludeDefaultInterceptors a = ivEjbClass.getAnnotation(ExcludeDefaultInterceptors.class); if (a != null) { ivExcludeDefaultFromClassLevel = true; } else { ivExcludeDefaultFromClassLevel = false; } } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "setExcludeDefaultInterceptors: " + ivExcludeDefaultFromClassLevel); } } }
public class class_name { private void setExcludeDefaultInterceptors() { EJBInterceptorBinding binding = ivClassInterceptorBinding; boolean useAnnotation = false; if (binding == null) { // Use annotation provided metadata-complete is false. useAnnotation = !ivMetadataComplete; // depends on control dependency: [if], data = [none] } else { // Assumption is xml overrides annotation, although EJB spec implies // interceptor-binding is used to augment annotation. Not clear what // is intended, but we are going to assume xml overrides annotation. Boolean exclude = binding.ivExcludeDefaultLevelInterceptors; if (exclude == null) { // exclude is not set in ejb-jar.xml for class level binding, // Use annotation provided metadata-complete is false. useAnnotation = !ivMetadataComplete; // depends on control dependency: [if], data = [none] } else if (exclude == Boolean.TRUE) { ivExcludeDefaultFromClassLevel = true; // depends on control dependency: [if], data = [none] } else { ivExcludeDefaultFromClassLevel = false; // depends on control dependency: [if], data = [none] } } // If xml did not have a exclude-default-interceptor setting for // class level binding, then see if annotation indicates to exclude // default level interceptors. if (useAnnotation) { ExcludeDefaultInterceptors a = ivEjbClass.getAnnotation(ExcludeDefaultInterceptors.class); if (a != null) { ivExcludeDefaultFromClassLevel = true; // depends on control dependency: [if], data = [none] } else { ivExcludeDefaultFromClassLevel = false; // depends on control dependency: [if], data = [none] } } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "setExcludeDefaultInterceptors: " + ivExcludeDefaultFromClassLevel); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static File normalizePath(File file) { if (file == null) { return new File(""); } String normalizedFile = file.getPath(); // remove all '//'... String quotedSeparator = Pattern.quote(File.separator); String replacementSeparator = File.separator.equals("/") ? File.separator : File.separator + File.separator; boolean isAbsolute = file.isAbsolute() || normalizedFile.startsWith(File.separator); while (normalizedFile.contains(replacementSeparator + replacementSeparator)) { normalizedFile = normalizedFile.replaceAll(quotedSeparator + quotedSeparator, replacementSeparator); } // remove all redundant '..' Pattern pattern = Pattern.compile("([^\\." + replacementSeparator + "]+" + quotedSeparator + "\\.\\.)"); Matcher matcher = pattern.matcher(normalizedFile); while (matcher.find()) { normalizedFile = normalizedFile.replace(matcher.group(1), "") .replaceAll(quotedSeparator + quotedSeparator, replacementSeparator); if ((!isAbsolute) && (normalizedFile.startsWith(File.separator))) { normalizedFile = normalizedFile.replaceFirst(quotedSeparator, ""); } else if ((isAbsolute) && (!normalizedFile.startsWith(File.separator))) { normalizedFile = File.separator + normalizedFile; } matcher = pattern.matcher(normalizedFile); } /* remove all '/./' and /. at the end */ pattern = Pattern.compile(quotedSeparator + "\\." + quotedSeparator); matcher = pattern.matcher(normalizedFile); while (matcher.find()) { normalizedFile = normalizedFile.replace(matcher.group(0), replacementSeparator); matcher = pattern.matcher(normalizedFile); } if (normalizedFile.endsWith(File.separator + ".")) { normalizedFile = normalizedFile.substring(0, normalizedFile.length() - 2); } return new File(normalizedFile); } }
public class class_name { public static File normalizePath(File file) { if (file == null) { return new File(""); // depends on control dependency: [if], data = [none] } String normalizedFile = file.getPath(); // remove all '//'... String quotedSeparator = Pattern.quote(File.separator); String replacementSeparator = File.separator.equals("/") ? File.separator : File.separator + File.separator; boolean isAbsolute = file.isAbsolute() || normalizedFile.startsWith(File.separator); while (normalizedFile.contains(replacementSeparator + replacementSeparator)) { normalizedFile = normalizedFile.replaceAll(quotedSeparator + quotedSeparator, replacementSeparator); // depends on control dependency: [while], data = [none] } // remove all redundant '..' Pattern pattern = Pattern.compile("([^\\." + replacementSeparator + "]+" + quotedSeparator + "\\.\\.)"); Matcher matcher = pattern.matcher(normalizedFile); while (matcher.find()) { normalizedFile = normalizedFile.replace(matcher.group(1), "") .replaceAll(quotedSeparator + quotedSeparator, replacementSeparator); // depends on control dependency: [while], data = [none] if ((!isAbsolute) && (normalizedFile.startsWith(File.separator))) { normalizedFile = normalizedFile.replaceFirst(quotedSeparator, ""); // depends on control dependency: [if], data = [none] } else if ((isAbsolute) && (!normalizedFile.startsWith(File.separator))) { normalizedFile = File.separator + normalizedFile; // depends on control dependency: [if], data = [none] } matcher = pattern.matcher(normalizedFile); // depends on control dependency: [while], data = [none] } /* remove all '/./' and /. at the end */ pattern = Pattern.compile(quotedSeparator + "\\." + quotedSeparator); matcher = pattern.matcher(normalizedFile); while (matcher.find()) { normalizedFile = normalizedFile.replace(matcher.group(0), replacementSeparator); // depends on control dependency: [while], data = [none] matcher = pattern.matcher(normalizedFile); // depends on control dependency: [while], data = [none] } if (normalizedFile.endsWith(File.separator + ".")) { normalizedFile = normalizedFile.substring(0, normalizedFile.length() - 2); // depends on control dependency: [if], data = [none] } return new File(normalizedFile); } }
public class class_name { public static String escapeHtml(String htmlString) { StringBuffer sb = new StringBuffer(htmlString.length()); // true if last char was blank boolean lastWasBlankChar = false; int len = htmlString.length(); char c; for (int i = 0; i < len; i++) { c = htmlString.charAt(i); if (c == ' ') { // blank gets extra work, // this solves the problem you get if you replace all // blanks with &nbsp;, if you do that you loss // word breaking if (lastWasBlankChar) { lastWasBlankChar = false; sb.append("&nbsp;"); } else { lastWasBlankChar = true; sb.append(' '); } } else { lastWasBlankChar = false; // // HTML Special Chars if (c == '"') sb.append("&quot;"); else if (c == '&') sb.append("&amp;"); else if (c == '<') sb.append("&lt;"); else if (c == '>') sb.append("&gt;"); else if (c == '/') sb.append("-"); else if (c == '\\') sb.append("-"); else if (c == '\n') // Handle Newline sb.append("&lt;br/&gt;"); else { int ci = 0xffff & c; if (ci < 160 ) // nothing special only 7 Bit sb.append(c); else { // Not 7 Bit use the unicode system sb.append("&#"); sb.append(String.valueOf(ci)); sb.append(';'); } } } } return sb.toString(); } }
public class class_name { public static String escapeHtml(String htmlString) { StringBuffer sb = new StringBuffer(htmlString.length()); // true if last char was blank boolean lastWasBlankChar = false; int len = htmlString.length(); char c; for (int i = 0; i < len; i++) { c = htmlString.charAt(i); // depends on control dependency: [for], data = [i] if (c == ' ') { // blank gets extra work, // this solves the problem you get if you replace all // blanks with &nbsp;, if you do that you loss // word breaking if (lastWasBlankChar) { lastWasBlankChar = false; // depends on control dependency: [if], data = [none] sb.append("&nbsp;"); // depends on control dependency: [if], data = [none] } else { lastWasBlankChar = true; // depends on control dependency: [if], data = [none] sb.append(' '); // depends on control dependency: [if], data = [none] } } else { lastWasBlankChar = false; // depends on control dependency: [if], data = [none] // // HTML Special Chars if (c == '"') sb.append("&quot;"); else if (c == '&') // depends on control dependency: [if], data = [(c] sb.append("&amp;"); // depends on control dependency: [if], data = [none] else if (c == '<') // depends on control dependency: [if], data = [(c] sb.append("&lt;"); // depends on control dependency: [if], data = [none] else if (c == '>') // depends on control dependency: [if], data = [(c] sb.append("&gt;"); // depends on control dependency: [if], data = [none] else if (c == '/') // depends on control dependency: [if], data = [(c] sb.append("-"); // depends on control dependency: [if], data = [none] else if (c == '\\') // depends on control dependency: [if], data = [(c] sb.append("-"); // depends on control dependency: [if], data = [none] else if (c == '\n') // Handle Newline // depends on control dependency: [if], data = [(c] sb.append("&lt;br/&gt;"); // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none] else { // depends on control dependency: [if], data = [none] int ci = 0xffff & c; if (ci < 160 ) // nothing special only 7 Bit sb.append(c); else { // Not 7 Bit use the unicode system sb.append("&#"); // depends on control dependency: [if], data = [none] sb.append(String.valueOf(ci)); // depends on control dependency: [if], data = [(ci] sb.append(';'); // depends on control dependency: [if], data = [none] } } } } return sb.toString(); } }
public class class_name { public Map<String, String> extract(InputStream xml, String[] fields) { Map<String, String> parsedFields = Maps.newHashMap(); try { DocumentBuilder documentBuilder = documentBuilderSupplier.get(); if (documentBuilder == null) { logger.warn("Could not create DocumentBuilder"); return parsedFields; } Document doc = documentBuilder.parse(xml); for (String field : fields) { try { String value = extract(doc, field); if (value != null) { parsedFields.put(field, value); } } catch (XPathExpressionException e) { // Ignore problems with the xpath. logger.warn("Invalid XPath: " + field, e); } } } catch (SAXException e) { logger.warn("Couldn't process XML into a Document", e); } catch (IOException e) { logger.warn("Problem reading input stream", e); } return parsedFields; } }
public class class_name { public Map<String, String> extract(InputStream xml, String[] fields) { Map<String, String> parsedFields = Maps.newHashMap(); try { DocumentBuilder documentBuilder = documentBuilderSupplier.get(); if (documentBuilder == null) { logger.warn("Could not create DocumentBuilder"); // depends on control dependency: [if], data = [none] return parsedFields; // depends on control dependency: [if], data = [none] } Document doc = documentBuilder.parse(xml); for (String field : fields) { try { String value = extract(doc, field); if (value != null) { parsedFields.put(field, value); // depends on control dependency: [if], data = [none] } } catch (XPathExpressionException e) { // Ignore problems with the xpath. logger.warn("Invalid XPath: " + field, e); } // depends on control dependency: [catch], data = [none] } } catch (SAXException e) { logger.warn("Couldn't process XML into a Document", e); } catch (IOException e) { // depends on control dependency: [catch], data = [none] logger.warn("Problem reading input stream", e); } // depends on control dependency: [catch], data = [none] return parsedFields; } }
public class class_name { @Deprecated public Decoder<S> getDecoder(int generation) throws FetchNoneException, FetchException { try { synchronized (mLayout) { IntHashMap decoders = mDecoders; if (decoders == null) { mDecoders = decoders = new IntHashMap(); } Decoder<S> decoder = (Decoder<S>) decoders.get(generation); if (decoder == null) { synchronized (cCodecDecoders) { Object altLayoutKey = new LayoutKey(mLayout.getGeneration(generation)); Object key = KeyFactory.createKey // Note: Generation is still required in the key // because an equivalent layout (with different generation) // might have been supplied by Layout.getGeneration. (new Object[] {mCodecKey, generation, altLayoutKey}); decoder = (Decoder<S>) cCodecDecoders.get(key); if (decoder == null) { decoder = generateDecoder(generation); cCodecDecoders.put(key, decoder); } } mDecoders.put(generation, decoder); } return decoder; } } catch (NullPointerException e) { if (mLayout == null) { throw new FetchNoneException("Layout evolution not supported"); } throw e; } } }
public class class_name { @Deprecated public Decoder<S> getDecoder(int generation) throws FetchNoneException, FetchException { try { synchronized (mLayout) { IntHashMap decoders = mDecoders; if (decoders == null) { mDecoders = decoders = new IntHashMap(); } Decoder<S> decoder = (Decoder<S>) decoders.get(generation); if (decoder == null) { synchronized (cCodecDecoders) { Object altLayoutKey = new LayoutKey(mLayout.getGeneration(generation)); Object key = KeyFactory.createKey // Note: Generation is still required in the key // because an equivalent layout (with different generation) // might have been supplied by Layout.getGeneration. (new Object[] {mCodecKey, generation, altLayoutKey}); decoder = (Decoder<S>) cCodecDecoders.get(key); if (decoder == null) { decoder = generateDecoder(generation); // depends on control dependency: [if], data = [none] cCodecDecoders.put(key, decoder); // depends on control dependency: [if], data = [none] } } mDecoders.put(generation, decoder); } return decoder; } } catch (NullPointerException e) { if (mLayout == null) { throw new FetchNoneException("Layout evolution not supported"); } throw e; } } }
public class class_name { private boolean matches(MethodDescription target, List<? extends TypeDefinition> typeDefinitions, Set<TypeDescription> duplicates) { for (TypeDefinition anInterface : typeDefinitions) { if (duplicates.add(anInterface.asErasure()) && (matches(target, anInterface) || matches(target, anInterface.getInterfaces(), duplicates))) { return true; } } return false; } }
public class class_name { private boolean matches(MethodDescription target, List<? extends TypeDefinition> typeDefinitions, Set<TypeDescription> duplicates) { for (TypeDefinition anInterface : typeDefinitions) { if (duplicates.add(anInterface.asErasure()) && (matches(target, anInterface) || matches(target, anInterface.getInterfaces(), duplicates))) { return true; // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { public Collection<String> getValues(String property) { Multimap<Optional<String>, String> values = properties.get(property); if (values == null) { return Collections.emptyList(); } return values.values(); } }
public class class_name { public Collection<String> getValues(String property) { Multimap<Optional<String>, String> values = properties.get(property); if (values == null) { return Collections.emptyList(); // depends on control dependency: [if], data = [none] } return values.values(); } }
public class class_name { protected void closeStatement(PreparedStatement preparedStatementParam, ResultSet resultSetParam ) { if(resultSetParam == null) { this.closeStatement(preparedStatementParam); return; } try { resultSetParam.close(); this.closeStatement(preparedStatementParam); } catch (SQLException sqlExcept) { throw new FluidSQLException(sqlExcept); } } }
public class class_name { protected void closeStatement(PreparedStatement preparedStatementParam, ResultSet resultSetParam ) { if(resultSetParam == null) { this.closeStatement(preparedStatementParam); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } try { resultSetParam.close(); // depends on control dependency: [try], data = [none] this.closeStatement(preparedStatementParam); // depends on control dependency: [try], data = [none] } catch (SQLException sqlExcept) { throw new FluidSQLException(sqlExcept); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private static String toJsonCollection(Collection objects) { Iterator iterator = objects.iterator(); if (!iterator.hasNext()) { return ""; } final Object first = iterator.next(); if (!iterator.hasNext()) { return toJson(first); } final StringBuilder buf = new StringBuilder(); if (first != null) { buf.append(toJson(first)); } while (iterator.hasNext()) { buf.append(','); final Object obj = iterator.next(); if (obj != null) { buf.append(toJson(obj)); } } return buf.toString(); } }
public class class_name { private static String toJsonCollection(Collection objects) { Iterator iterator = objects.iterator(); if (!iterator.hasNext()) { return ""; // depends on control dependency: [if], data = [none] } final Object first = iterator.next(); if (!iterator.hasNext()) { return toJson(first); // depends on control dependency: [if], data = [none] } final StringBuilder buf = new StringBuilder(); if (first != null) { buf.append(toJson(first)); // depends on control dependency: [if], data = [(first] } while (iterator.hasNext()) { buf.append(','); // depends on control dependency: [while], data = [none] final Object obj = iterator.next(); if (obj != null) { buf.append(toJson(obj)); // depends on control dependency: [if], data = [(obj] } } return buf.toString(); } }
public class class_name { public QueryNode[] getPredicates() { if (operands == null) { return EMPTY; } else { return (QueryNode[]) operands.toArray(new QueryNode[operands.size()]); } } }
public class class_name { public QueryNode[] getPredicates() { if (operands == null) { return EMPTY; // depends on control dependency: [if], data = [none] } else { return (QueryNode[]) operands.toArray(new QueryNode[operands.size()]); // depends on control dependency: [if], data = [none] } } }
public class class_name { public AssetAttributes withIpv4Addresses(String... ipv4Addresses) { if (this.ipv4Addresses == null) { setIpv4Addresses(new java.util.ArrayList<String>(ipv4Addresses.length)); } for (String ele : ipv4Addresses) { this.ipv4Addresses.add(ele); } return this; } }
public class class_name { public AssetAttributes withIpv4Addresses(String... ipv4Addresses) { if (this.ipv4Addresses == null) { setIpv4Addresses(new java.util.ArrayList<String>(ipv4Addresses.length)); // depends on control dependency: [if], data = [none] } for (String ele : ipv4Addresses) { this.ipv4Addresses.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { private static boolean processAtomLabels(final CharIter iter, final Map<Integer, String> dest) { int atomIdx = 0; while (iter.hasNext()) { // fast forward through empty labels while (iter.nextIf(';')) atomIdx++; char c = iter.next(); if (c == '$') { iter.nextIf(','); // optional // end of atom label return true; } else { iter.pos--; // push back int beg = iter.pos; int rollback = beg; while (iter.hasNext()) { if (iter.pos == beg && iter.curr() == '_' && iter.peek() == 'R') { ++beg; } // correct step over of escaped label if (iter.curr() == '&') { rollback = iter.pos; if (iter.nextIf('&') && iter.nextIf('#') && iter.nextIfDigit()) { while (iter.nextIfDigit()){} // more digits if (!iter.nextIf(';')) { iter.pos = rollback; } else { } } else { iter.pos = rollback; } } else if (iter.curr() == ';') break; else if (iter.curr() == '$') break; else iter.next(); } dest.put(atomIdx, unescape(iter.substr(beg, iter.pos))); atomIdx++; if (iter.nextIf('$')) { iter.nextIf(','); // optional return true; } if (!iter.nextIf(';')) return false; } } return false; } }
public class class_name { private static boolean processAtomLabels(final CharIter iter, final Map<Integer, String> dest) { int atomIdx = 0; while (iter.hasNext()) { // fast forward through empty labels while (iter.nextIf(';')) atomIdx++; char c = iter.next(); if (c == '$') { iter.nextIf(','); // optional // depends on control dependency: [if], data = [none] // end of atom label return true; // depends on control dependency: [if], data = [none] } else { iter.pos--; // push back // depends on control dependency: [if], data = [none] int beg = iter.pos; int rollback = beg; while (iter.hasNext()) { if (iter.pos == beg && iter.curr() == '_' && iter.peek() == 'R') { ++beg; // depends on control dependency: [if], data = [none] } // correct step over of escaped label if (iter.curr() == '&') { rollback = iter.pos; // depends on control dependency: [if], data = [none] if (iter.nextIf('&') && iter.nextIf('#') && iter.nextIfDigit()) { while (iter.nextIfDigit()){} // more digits if (!iter.nextIf(';')) { iter.pos = rollback; // depends on control dependency: [if], data = [none] } else { } } else { iter.pos = rollback; // depends on control dependency: [if], data = [none] } } else if (iter.curr() == ';') break; else if (iter.curr() == '$') break; else iter.next(); } dest.put(atomIdx, unescape(iter.substr(beg, iter.pos))); // depends on control dependency: [if], data = [none] atomIdx++; // depends on control dependency: [if], data = [none] if (iter.nextIf('$')) { iter.nextIf(','); // optional // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } if (!iter.nextIf(';')) return false; } } return false; } }
public class class_name { @Override public boolean removeListener(NotificationListener listenerToRemove) { // Find the listener we actually registered and remove that NotificationListener interpretedListener = this.listeners.remove(listenerToRemove); if (interpretedListener != null) { return this.delegateNotifier.removeListener(interpretedListener); } else { return false; } } }
public class class_name { @Override public boolean removeListener(NotificationListener listenerToRemove) { // Find the listener we actually registered and remove that NotificationListener interpretedListener = this.listeners.remove(listenerToRemove); if (interpretedListener != null) { return this.delegateNotifier.removeListener(interpretedListener); // depends on control dependency: [if], data = [(interpretedListener] } else { return false; // depends on control dependency: [if], data = [none] } } }