code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { public static Platform detect() throws UnsupportedPlatformException { String osArch = getProperty("os.arch"); String osName = getProperty("os.name"); for (Arch arch : Arch.values()) { if (arch.pattern.matcher(osArch).matches()) { for (OS os : OS.values()) { if (os.pattern.matcher(osName).matches()) { return new Platform(arch, os); } } } } String msg = String.format("Unsupported platform %s %s", osArch, osName); throw new UnsupportedPlatformException(msg); } }
public class class_name { public static Platform detect() throws UnsupportedPlatformException { String osArch = getProperty("os.arch"); String osName = getProperty("os.name"); for (Arch arch : Arch.values()) { if (arch.pattern.matcher(osArch).matches()) { for (OS os : OS.values()) { if (os.pattern.matcher(osName).matches()) { return new Platform(arch, os); // depends on control dependency: [if], data = [none] } } } } String msg = String.format("Unsupported platform %s %s", osArch, osName); throw new UnsupportedPlatformException(msg); } }
public class class_name { final boolean select(int extension, ExplorationStep state) throws WrongFirstParentException { if (this.allowExploration(extension, state)) { return (this.next == null || this.next.select(extension, state)); } else { PLCMCounters key = this.getCountersKey(); if (key != null) { ((PLCM.PLCMThread) Thread.currentThread()).counters[key.ordinal()]++; } return false; } } }
public class class_name { final boolean select(int extension, ExplorationStep state) throws WrongFirstParentException { if (this.allowExploration(extension, state)) { return (this.next == null || this.next.select(extension, state)); } else { PLCMCounters key = this.getCountersKey(); if (key != null) { ((PLCM.PLCMThread) Thread.currentThread()).counters[key.ordinal()]++; // depends on control dependency: [if], data = [none] } return false; } } }
public class class_name { Violation areFieldsImmutable( Optional<ClassTree> tree, ImmutableSet<String> immutableTyParams, ClassType classType, ViolationReporter reporter) { ClassSymbol classSym = (ClassSymbol) classType.tsym; if (classSym.members() == null) { return Violation.absent(); } Filter<Symbol> instanceFieldFilter = new Filter<Symbol>() { @Override public boolean accepts(Symbol symbol) { return symbol.getKind() == ElementKind.FIELD && !symbol.isStatic(); } }; Map<Symbol, Tree> declarations = new HashMap<>(); if (tree.isPresent()) { for (Tree member : tree.get().getMembers()) { Symbol sym = ASTHelpers.getSymbol(member); if (sym != null) { declarations.put(sym, member); } } } // javac gives us members in reverse declaration order // handling them in declaration order leads to marginally better diagnostics List<Symbol> members = ImmutableList.copyOf(classSym.members().getSymbols(instanceFieldFilter)).reverse(); for (Symbol member : members) { Optional<Tree> memberTree = Optional.ofNullable(declarations.get(member)); Violation info = isFieldImmutable( memberTree, immutableTyParams, classSym, classType, (VarSymbol) member, reporter); if (info.isPresent()) { return info; } } return Violation.absent(); } }
public class class_name { Violation areFieldsImmutable( Optional<ClassTree> tree, ImmutableSet<String> immutableTyParams, ClassType classType, ViolationReporter reporter) { ClassSymbol classSym = (ClassSymbol) classType.tsym; if (classSym.members() == null) { return Violation.absent(); // depends on control dependency: [if], data = [none] } Filter<Symbol> instanceFieldFilter = new Filter<Symbol>() { @Override public boolean accepts(Symbol symbol) { return symbol.getKind() == ElementKind.FIELD && !symbol.isStatic(); } }; Map<Symbol, Tree> declarations = new HashMap<>(); if (tree.isPresent()) { for (Tree member : tree.get().getMembers()) { Symbol sym = ASTHelpers.getSymbol(member); if (sym != null) { declarations.put(sym, member); // depends on control dependency: [if], data = [(sym] } } } // javac gives us members in reverse declaration order // handling them in declaration order leads to marginally better diagnostics List<Symbol> members = ImmutableList.copyOf(classSym.members().getSymbols(instanceFieldFilter)).reverse(); for (Symbol member : members) { Optional<Tree> memberTree = Optional.ofNullable(declarations.get(member)); Violation info = isFieldImmutable( memberTree, immutableTyParams, classSym, classType, (VarSymbol) member, reporter); if (info.isPresent()) { return info; // depends on control dependency: [if], data = [none] } } return Violation.absent(); } }
public class class_name { public ImageDownloadResult getImageDownloadResult() throws Exception { Future<ImageDownloadResult> future = pool.poll(); if (future == null) { // no completed tasks in the pool return null; } else { try { ImageDownloadResult imdr = future.get(); return imdr; } catch (Exception e) { throw e; } finally { // in any case (Exception or not) the numPendingTask should be reduced numPendingTasks--; } } } }
public class class_name { public ImageDownloadResult getImageDownloadResult() throws Exception { Future<ImageDownloadResult> future = pool.poll(); if (future == null) { // no completed tasks in the pool return null; } else { try { ImageDownloadResult imdr = future.get(); return imdr; // depends on control dependency: [try], data = [none] } catch (Exception e) { throw e; } finally { // depends on control dependency: [catch], data = [none] // in any case (Exception or not) the numPendingTask should be reduced numPendingTasks--; } } } }
public class class_name { protected boolean isSuppressed() { if (_suppressed == null) { // we haven't called this method before, so determine the suppressed // value and cache it for later calls to this method. if (isFacet()) { // facets are always rendered by their parents --> suppressed _suppressed = Boolean.TRUE; return true; } UIComponent component = getComponentInstance(); // Does any parent render its children? // (We must determine this first, before calling any isRendered method // because rendered properties might reference a data var of a nesting UIData, // which is not set at this time, and would cause a VariableResolver error!) UIComponent parent = component.getParent(); while (parent != null) { if (parent.getRendersChildren()) { // Yes, parent found, that renders children --> suppressed _suppressed = Boolean.TRUE; return true; } parent = parent.getParent(); } // does component or any parent has a false rendered attribute? while (component != null) { if (!component.isRendered()) { // Yes, component or any parent must not be rendered --> suppressed _suppressed = Boolean.TRUE; return true; } component = component.getParent(); } // else --> not suppressed _suppressed = Boolean.FALSE; } return _suppressed.booleanValue(); } }
public class class_name { protected boolean isSuppressed() { if (_suppressed == null) { // we haven't called this method before, so determine the suppressed // value and cache it for later calls to this method. if (isFacet()) { // facets are always rendered by their parents --> suppressed _suppressed = Boolean.TRUE; // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } UIComponent component = getComponentInstance(); // Does any parent render its children? // (We must determine this first, before calling any isRendered method // because rendered properties might reference a data var of a nesting UIData, // which is not set at this time, and would cause a VariableResolver error!) UIComponent parent = component.getParent(); while (parent != null) { if (parent.getRendersChildren()) { // Yes, parent found, that renders children --> suppressed _suppressed = Boolean.TRUE; // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } parent = parent.getParent(); // depends on control dependency: [while], data = [none] } // does component or any parent has a false rendered attribute? while (component != null) { if (!component.isRendered()) { // Yes, component or any parent must not be rendered --> suppressed _suppressed = Boolean.TRUE; // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } component = component.getParent(); // depends on control dependency: [while], data = [none] } // else --> not suppressed _suppressed = Boolean.FALSE; // depends on control dependency: [if], data = [none] } return _suppressed.booleanValue(); } }
public class class_name { public ZooKeeperUpdatingListener build() { final boolean internalClient; if (client == null) { client = CuratorFrameworkFactory.builder() .connectString(connectionStr) .retryPolicy(ZooKeeperDefaults.DEFAULT_RETRY_POLICY) .connectionTimeoutMs(connectTimeoutMillis) .sessionTimeoutMs(sessionTimeoutMillis) .build(); internalClient = true; } else { internalClient = false; } return new ZooKeeperUpdatingListener(client, zNodePath, nodeValueCodec, endpoint, internalClient); } }
public class class_name { public ZooKeeperUpdatingListener build() { final boolean internalClient; if (client == null) { client = CuratorFrameworkFactory.builder() .connectString(connectionStr) .retryPolicy(ZooKeeperDefaults.DEFAULT_RETRY_POLICY) .connectionTimeoutMs(connectTimeoutMillis) .sessionTimeoutMs(sessionTimeoutMillis) .build(); // depends on control dependency: [if], data = [none] internalClient = true; // depends on control dependency: [if], data = [none] } else { internalClient = false; // depends on control dependency: [if], data = [none] } return new ZooKeeperUpdatingListener(client, zNodePath, nodeValueCodec, endpoint, internalClient); } }
public class class_name { public boolean deselectAll(Collection<Integer> IDs) { boolean modified = false; for(int ID : IDs){ if(deselect(ID)){ modified = true; } } return modified; } }
public class class_name { public boolean deselectAll(Collection<Integer> IDs) { boolean modified = false; for(int ID : IDs){ if(deselect(ID)){ modified = true; // depends on control dependency: [if], data = [none] } } return modified; } }
public class class_name { protected void initialise() throws InstallationException { if (!this.initialised) { this.initialised = true; this.cache.clear(); AppDependency.initialise(); for (final FileType fileType : FileType.values()) { if (fileType == FileType.XML) { for (final InstallFile file : this.files) { if (file.getType() == fileType) { final SaxHandler handler = new SaxHandler(); try { final IUpdate elem = handler.parse(file); final List<IUpdate> list; if (this.cache.containsKey(elem.getIdentifier())) { list = this.cache.get(elem.getIdentifier()); } else { list = new ArrayList<>(); this.cache.put(elem.getIdentifier(), list); } list.add(handler.getUpdate()); } catch (final SAXException e) { throw new InstallationException("initialise()", e); } catch (final IOException e) { throw new InstallationException("initialise()", e); } } } } else { for (final Class<? extends IUpdate> updateClass : fileType.getClazzes()) { Method method = null; try { method = updateClass.getMethod("readFile", InstallFile.class); } catch (final SecurityException e) { throw new InstallationException("initialise()", e); } catch (final NoSuchMethodException e) { throw new InstallationException("initialise()", e); } for (final InstallFile file : this.files) { if (file.getType() == fileType) { Object obj = null; try { obj = method.invoke(null, file); } catch (final IllegalArgumentException e) { throw new InstallationException("initialise()", e); } catch (final IllegalAccessException e) { throw new InstallationException("initialise()", e); } catch (final InvocationTargetException e) { throw new InstallationException("initialise()", e); } if (obj != null && obj instanceof IUpdate) { final IUpdate iUpdate = (IUpdate) obj; final List<IUpdate> list; if (this.cache.containsKey(iUpdate.getIdentifier())) { list = this.cache.get(iUpdate.getIdentifier()); } else { list = new ArrayList<>(); this.cache.put(iUpdate.getIdentifier(), list); } list.add(iUpdate); } } } } } } } } }
public class class_name { protected void initialise() throws InstallationException { if (!this.initialised) { this.initialised = true; this.cache.clear(); AppDependency.initialise(); for (final FileType fileType : FileType.values()) { if (fileType == FileType.XML) { for (final InstallFile file : this.files) { if (file.getType() == fileType) { final SaxHandler handler = new SaxHandler(); try { final IUpdate elem = handler.parse(file); final List<IUpdate> list; if (this.cache.containsKey(elem.getIdentifier())) { list = this.cache.get(elem.getIdentifier()); // depends on control dependency: [if], data = [none] } else { list = new ArrayList<>(); // depends on control dependency: [if], data = [none] this.cache.put(elem.getIdentifier(), list); // depends on control dependency: [if], data = [none] } list.add(handler.getUpdate()); // depends on control dependency: [try], data = [none] } catch (final SAXException e) { throw new InstallationException("initialise()", e); } catch (final IOException e) { // depends on control dependency: [catch], data = [none] throw new InstallationException("initialise()", e); } // depends on control dependency: [catch], data = [none] } } } else { for (final Class<? extends IUpdate> updateClass : fileType.getClazzes()) { Method method = null; try { method = updateClass.getMethod("readFile", InstallFile.class); // depends on control dependency: [try], data = [none] } catch (final SecurityException e) { throw new InstallationException("initialise()", e); } catch (final NoSuchMethodException e) { // depends on control dependency: [catch], data = [none] throw new InstallationException("initialise()", e); } // depends on control dependency: [catch], data = [none] for (final InstallFile file : this.files) { if (file.getType() == fileType) { Object obj = null; try { obj = method.invoke(null, file); // depends on control dependency: [try], data = [none] } catch (final IllegalArgumentException e) { throw new InstallationException("initialise()", e); } catch (final IllegalAccessException e) { // depends on control dependency: [catch], data = [none] throw new InstallationException("initialise()", e); } catch (final InvocationTargetException e) { // depends on control dependency: [catch], data = [none] throw new InstallationException("initialise()", e); } // depends on control dependency: [catch], data = [none] if (obj != null && obj instanceof IUpdate) { final IUpdate iUpdate = (IUpdate) obj; final List<IUpdate> list; if (this.cache.containsKey(iUpdate.getIdentifier())) { list = this.cache.get(iUpdate.getIdentifier()); // depends on control dependency: [if], data = [none] } else { list = new ArrayList<>(); // depends on control dependency: [if], data = [none] this.cache.put(iUpdate.getIdentifier(), list); // depends on control dependency: [if], data = [none] } list.add(iUpdate); // depends on control dependency: [if], data = [none] } } } } } } } } }
public class class_name { public void setConsumers(java.util.Collection<Consumer> consumers) { if (consumers == null) { this.consumers = null; return; } this.consumers = new com.amazonaws.internal.SdkInternalList<Consumer>(consumers); } }
public class class_name { public void setConsumers(java.util.Collection<Consumer> consumers) { if (consumers == null) { this.consumers = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.consumers = new com.amazonaws.internal.SdkInternalList<Consumer>(consumers); } }
public class class_name { private static Observable<Bitmap> getThumbnailFromUriWithSizeAndKind(final Context context, final Uri data, final int requiredWidth, final int requiredHeight, final int kind) { return Observable.fromCallable(new Func0<Bitmap>() { @Override public Bitmap call() { Bitmap bitmap = null; ParcelFileDescriptor parcelFileDescriptor; final BitmapFactory.Options options = new BitmapFactory.Options(); if (requiredWidth > 0 && requiredHeight > 0) { options.inJustDecodeBounds = true; options.inSampleSize = calculateInSampleSize(options, requiredWidth, requiredHeight); options.inJustDecodeBounds = false; } if (!isMediaUri(data)) { logDebug("Not a media uri:" + data); if (isGoogleDriveDocument(data)) { logDebug("Google Drive Uri:" + data); DocumentFile file = DocumentFile.fromSingleUri(context, data); if (file.getType().startsWith(Constants.IMAGE_TYPE) || file.getType() .startsWith(Constants.VIDEO_TYPE)) { logDebug("Google Drive Uri:" + data + " (Video or Image)"); try { parcelFileDescriptor = context.getContentResolver(). openFileDescriptor(data, Constants.READ_MODE); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); parcelFileDescriptor.close(); return bitmap; } catch (IOException e) { logError(e); } } } else if (data.getScheme().equals(Constants.FILE)) { logDebug("Dropbox or other DocumentsProvider Uri:" + data); try { parcelFileDescriptor = context.getContentResolver(). openFileDescriptor(data, Constants.READ_MODE); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); parcelFileDescriptor.close(); return bitmap; } catch (IOException e) { logError(e); } } else { try { parcelFileDescriptor = context.getContentResolver(). openFileDescriptor(data, Constants.READ_MODE); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); parcelFileDescriptor.close(); return bitmap; } catch (IOException e) { logError(e); } } } else { logDebug("Uri for thumbnail:" + data); String[] parts = data.getLastPathSegment().split(":"); String fileId = parts[1]; Cursor cursor = null; try { cursor = context.getContentResolver().query(data, null, null, null, null); if (cursor != null) { logDebug("Cursor size:" + cursor.getCount()); if (cursor.moveToFirst()) { if (data.toString().contains(Constants.VIDEO)) { bitmap = MediaStore.Video.Thumbnails.getThumbnail(context.getContentResolver(), Long.parseLong(fileId), kind, options); } else if (data.toString().contains(Constants.IMAGE)) { bitmap = MediaStore.Images.Thumbnails.getThumbnail(context.getContentResolver(), Long.parseLong(fileId), kind, options); } } } return bitmap; } catch (Exception e) { logError(e); } finally { if (cursor != null) cursor.close(); } } return bitmap; } }); } }
public class class_name { private static Observable<Bitmap> getThumbnailFromUriWithSizeAndKind(final Context context, final Uri data, final int requiredWidth, final int requiredHeight, final int kind) { return Observable.fromCallable(new Func0<Bitmap>() { @Override public Bitmap call() { Bitmap bitmap = null; ParcelFileDescriptor parcelFileDescriptor; final BitmapFactory.Options options = new BitmapFactory.Options(); if (requiredWidth > 0 && requiredHeight > 0) { options.inJustDecodeBounds = true; // depends on control dependency: [if], data = [none] options.inSampleSize = calculateInSampleSize(options, requiredWidth, requiredHeight); // depends on control dependency: [if], data = [none] options.inJustDecodeBounds = false; // depends on control dependency: [if], data = [none] } if (!isMediaUri(data)) { logDebug("Not a media uri:" + data); if (isGoogleDriveDocument(data)) { logDebug("Google Drive Uri:" + data); DocumentFile file = DocumentFile.fromSingleUri(context, data); if (file.getType().startsWith(Constants.IMAGE_TYPE) || file.getType() .startsWith(Constants.VIDEO_TYPE)) { logDebug("Google Drive Uri:" + data + " (Video or Image)"); try { parcelFileDescriptor = context.getContentResolver(). openFileDescriptor(data, Constants.READ_MODE); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); parcelFileDescriptor.close(); return bitmap; } catch (IOException e) { logError(e); } } } else if (data.getScheme().equals(Constants.FILE)) { logDebug("Dropbox or other DocumentsProvider Uri:" + data); try { parcelFileDescriptor = context.getContentResolver(). openFileDescriptor(data, Constants.READ_MODE); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); parcelFileDescriptor.close(); return bitmap; } catch (IOException e) { logError(e); } } else { try { parcelFileDescriptor = context.getContentResolver(). openFileDescriptor(data, Constants.READ_MODE); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); parcelFileDescriptor.close(); return bitmap; } catch (IOException e) { logError(e); } } } else { logDebug("Uri for thumbnail:" + data); String[] parts = data.getLastPathSegment().split(":"); String fileId = parts[1]; Cursor cursor = null; try { cursor = context.getContentResolver().query(data, null, null, null, null); if (cursor != null) { logDebug("Cursor size:" + cursor.getCount()); if (cursor.moveToFirst()) { if (data.toString().contains(Constants.VIDEO)) { bitmap = MediaStore.Video.Thumbnails.getThumbnail(context.getContentResolver(), Long.parseLong(fileId), kind, options); } else if (data.toString().contains(Constants.IMAGE)) { bitmap = MediaStore.Images.Thumbnails.getThumbnail(context.getContentResolver(), Long.parseLong(fileId), kind, options); } } } return bitmap; } catch (Exception e) { logError(e); } finally { if (cursor != null) cursor.close(); } } return bitmap; } }); } }
public class class_name { public synchronized Schema create(URI id, String refFragmentPathDelimiters) { if (!schemas.containsKey(id)) { URI baseId = removeFragment(id); JsonNode baseContent = contentResolver.resolve(baseId); Schema baseSchema = new Schema(baseId, baseContent, null); if (id.toString().contains("#")) { JsonNode childContent = fragmentResolver.resolve(baseContent, '#' + id.getFragment(), refFragmentPathDelimiters); schemas.put(id, new Schema(id, childContent, baseSchema)); } else { schemas.put(id, baseSchema); } } return schemas.get(id); } }
public class class_name { public synchronized Schema create(URI id, String refFragmentPathDelimiters) { if (!schemas.containsKey(id)) { URI baseId = removeFragment(id); JsonNode baseContent = contentResolver.resolve(baseId); Schema baseSchema = new Schema(baseId, baseContent, null); if (id.toString().contains("#")) { JsonNode childContent = fragmentResolver.resolve(baseContent, '#' + id.getFragment(), refFragmentPathDelimiters); schemas.put(id, new Schema(id, childContent, baseSchema)); // depends on control dependency: [if], data = [none] } else { schemas.put(id, baseSchema); // depends on control dependency: [if], data = [none] } } return schemas.get(id); } }
public class class_name { @Override public void throwFailoverMessage(HostAddress failHostAddress, boolean wasMaster, SQLException queryException, boolean reconnected) throws SQLException { String firstPart = "Communications link failure with " + (wasMaster ? "primary" : "secondary") + ((failHostAddress != null) ? " host " + failHostAddress.host + ":" + failHostAddress.port : "") + ". "; String error = ""; if (reconnected) { error += " Driver has reconnect connection"; } else { if (currentConnectionAttempts.get() > urlParser.getOptions().retriesAllDown) { error += " Driver will not try to reconnect (too much failure > " + urlParser .getOptions().retriesAllDown + ")"; } } String message; String sqlState; int vendorCode = 0; Throwable cause = null; if (queryException == null) { message = firstPart + error; sqlState = CONNECTION_EXCEPTION.getSqlState(); } else { message = firstPart + queryException.getMessage() + ". " + error; sqlState = queryException.getSQLState(); vendorCode = queryException.getErrorCode(); cause = queryException.getCause(); } if (sqlState != null && sqlState.startsWith("08")) { if (reconnected) { //change sqlState to "Transaction has been rolled back", to transaction exception, since reconnection has succeed sqlState = "25S03"; } else { throw new SQLNonTransientConnectionException(message, sqlState, vendorCode, cause); } } throw new SQLException(message, sqlState, vendorCode, cause); } }
public class class_name { @Override public void throwFailoverMessage(HostAddress failHostAddress, boolean wasMaster, SQLException queryException, boolean reconnected) throws SQLException { String firstPart = "Communications link failure with " + (wasMaster ? "primary" : "secondary") + ((failHostAddress != null) ? " host " + failHostAddress.host + ":" + failHostAddress.port : "") + ". "; String error = ""; if (reconnected) { error += " Driver has reconnect connection"; } else { if (currentConnectionAttempts.get() > urlParser.getOptions().retriesAllDown) { error += " Driver will not try to reconnect (too much failure > " + urlParser // depends on control dependency: [if], data = [none] .getOptions().retriesAllDown + ")"; } } String message; String sqlState; int vendorCode = 0; Throwable cause = null; if (queryException == null) { message = firstPart + error; sqlState = CONNECTION_EXCEPTION.getSqlState(); } else { message = firstPart + queryException.getMessage() + ". " + error; sqlState = queryException.getSQLState(); vendorCode = queryException.getErrorCode(); cause = queryException.getCause(); } if (sqlState != null && sqlState.startsWith("08")) { if (reconnected) { //change sqlState to "Transaction has been rolled back", to transaction exception, since reconnection has succeed sqlState = "25S03"; // depends on control dependency: [if], data = [none] } else { throw new SQLNonTransientConnectionException(message, sqlState, vendorCode, cause); } } throw new SQLException(message, sqlState, vendorCode, cause); } }
public class class_name { private JLabel getAddedCountNameLabel() { if (addedCountNameLabel == null) { addedCountNameLabel = new JLabel(); addedCountNameLabel.setText(Constant.messages.getString("spider.toolbar.added.label")); } return addedCountNameLabel; } }
public class class_name { private JLabel getAddedCountNameLabel() { if (addedCountNameLabel == null) { addedCountNameLabel = new JLabel(); // depends on control dependency: [if], data = [none] addedCountNameLabel.setText(Constant.messages.getString("spider.toolbar.added.label")); } return addedCountNameLabel; // depends on control dependency: [if], data = [none] } }
public class class_name { public static Type createParameterizedType(final Type ownerType0, final Type rawType0, final Type... actualTypeArguments0) { if (ownerType0 == null && rawType0 instanceof Class) { int count = 0; for (Type t : actualTypeArguments0) { if (isClassType(t)) count++; } if (count == actualTypeArguments0.length) return createParameterizedType((Class) rawType0, actualTypeArguments0); } return new ParameterizedType() { private final Class<?> rawType = (Class<?>) rawType0; private final Type ownerType = ownerType0; private final Type[] actualTypeArguments = actualTypeArguments0; @Override public Type[] getActualTypeArguments() { return actualTypeArguments.clone(); } @Override public Type getRawType() { return rawType; } @Override public Type getOwnerType() { return ownerType; } @Override public int hashCode() { return Arrays.hashCode(actualTypeArguments) ^ Objects.hashCode(rawType) ^ Objects.hashCode(ownerType); } @Override public boolean equals(Object o) { if (!(o instanceof ParameterizedType)) return false; final ParameterizedType that = (ParameterizedType) o; if (this == that) return true; return Objects.equals(ownerType, that.getOwnerType()) && Objects.equals(rawType, that.getRawType()) && Arrays.equals(actualTypeArguments, that.getActualTypeArguments()); } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (ownerType != null) sb.append((ownerType instanceof Class) ? (((Class) ownerType).getName()) : ownerType.toString()).append("."); sb.append(rawType.getName()); if (actualTypeArguments != null && actualTypeArguments.length > 0) { sb.append("<"); boolean first = true; for (Type t : actualTypeArguments) { if (!first) sb.append(", "); sb.append(t); first = false; } sb.append(">"); } return sb.toString(); } }; } }
public class class_name { public static Type createParameterizedType(final Type ownerType0, final Type rawType0, final Type... actualTypeArguments0) { if (ownerType0 == null && rawType0 instanceof Class) { int count = 0; for (Type t : actualTypeArguments0) { if (isClassType(t)) count++; } if (count == actualTypeArguments0.length) return createParameterizedType((Class) rawType0, actualTypeArguments0); } return new ParameterizedType() { private final Class<?> rawType = (Class<?>) rawType0; private final Type ownerType = ownerType0; private final Type[] actualTypeArguments = actualTypeArguments0; @Override public Type[] getActualTypeArguments() { return actualTypeArguments.clone(); } @Override public Type getRawType() { return rawType; } @Override public Type getOwnerType() { return ownerType; } @Override public int hashCode() { return Arrays.hashCode(actualTypeArguments) ^ Objects.hashCode(rawType) ^ Objects.hashCode(ownerType); } @Override public boolean equals(Object o) { if (!(o instanceof ParameterizedType)) return false; final ParameterizedType that = (ParameterizedType) o; if (this == that) return true; return Objects.equals(ownerType, that.getOwnerType()) && Objects.equals(rawType, that.getRawType()) && Arrays.equals(actualTypeArguments, that.getActualTypeArguments()); } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (ownerType != null) sb.append((ownerType instanceof Class) ? (((Class) ownerType).getName()) : ownerType.toString()).append("."); sb.append(rawType.getName()); if (actualTypeArguments != null && actualTypeArguments.length > 0) { sb.append("<"); // depends on control dependency: [if], data = [none] boolean first = true; for (Type t : actualTypeArguments) { if (!first) sb.append(", "); sb.append(t); // depends on control dependency: [for], data = [t] first = false; // depends on control dependency: [for], data = [t] } sb.append(">"); // depends on control dependency: [if], data = [none] } return sb.toString(); } }; } }
public class class_name { private static void propagateResponse(BotMillNetworkResponse response) { String output = response.getResponse(); if (response.isError()) { // Parses the error message and logs it. FacebookErrorMessage errorMessage = FbBotMillJsonUtils.fromJson( output, FacebookErrorMessage.class); FacebookError error = errorMessage.getError(); logger.error( "Error message from Facebook. Message: [{}], Code: [{}], Type: [{}], FbTraceID: [{}].", error.getMessage(), error.getCode(), error.getType(), error.getFbTraceId()); // Sends the callback to the registered network monitors. for (FbBotMillMonitor monitor : registeredMonitors) { monitor.onError(errorMessage); } } else { FacebookConfirmationMessage confirmationMessage = FbBotMillJsonUtils .fromJson(output, FacebookConfirmationMessage.class); logger.debug( "Confirmation from Facebook. Recipient ID: [{}], Message ID: [{}], Result Message: [{}]", confirmationMessage.getRecipientId(), confirmationMessage.getMessageId(), confirmationMessage.getResult()); // Sends the callback to the registered network monitors. for (FbBotMillMonitor monitor : registeredMonitors) { monitor.onConfirmation(confirmationMessage); } } } }
public class class_name { private static void propagateResponse(BotMillNetworkResponse response) { String output = response.getResponse(); if (response.isError()) { // Parses the error message and logs it. FacebookErrorMessage errorMessage = FbBotMillJsonUtils.fromJson( output, FacebookErrorMessage.class); FacebookError error = errorMessage.getError(); logger.error( "Error message from Facebook. Message: [{}], Code: [{}], Type: [{}], FbTraceID: [{}].", error.getMessage(), error.getCode(), error.getType(), error.getFbTraceId()); // depends on control dependency: [if], data = [none] // Sends the callback to the registered network monitors. for (FbBotMillMonitor monitor : registeredMonitors) { monitor.onError(errorMessage); // depends on control dependency: [for], data = [monitor] } } else { FacebookConfirmationMessage confirmationMessage = FbBotMillJsonUtils .fromJson(output, FacebookConfirmationMessage.class); logger.debug( "Confirmation from Facebook. Recipient ID: [{}], Message ID: [{}], Result Message: [{}]", confirmationMessage.getRecipientId(), confirmationMessage.getMessageId(), confirmationMessage.getResult()); // depends on control dependency: [if], data = [none] // Sends the callback to the registered network monitors. for (FbBotMillMonitor monitor : registeredMonitors) { monitor.onConfirmation(confirmationMessage); // depends on control dependency: [for], data = [monitor] } } } }
public class class_name { @Override public TagAttribute[] getAll(String namespace) { if (namespace==null) namespace=""; List<TagAttribute> list = new ArrayList<TagAttribute>(); for (TagAttribute a:attrs) { if (namespace.equals(a.getNamespace())) { list.add(a); } } TagAttribute[] result = new TagAttribute[list.size()]; list.toArray(result); return result; } }
public class class_name { @Override public TagAttribute[] getAll(String namespace) { if (namespace==null) namespace=""; List<TagAttribute> list = new ArrayList<TagAttribute>(); for (TagAttribute a:attrs) { if (namespace.equals(a.getNamespace())) { list.add(a); // depends on control dependency: [if], data = [none] } } TagAttribute[] result = new TagAttribute[list.size()]; list.toArray(result); return result; } }
public class class_name { public void setDuration(TimeDuration duration) { this.duration = duration; useDuration = true; if (useStart) { this.isMoving = this.start.isPresent(); this.end = this.start.add(duration); useEnd = false; } else { this.isMoving = this.end.isPresent(); this.start = this.end.subtract(duration); } checkIfEmpty(); } }
public class class_name { public void setDuration(TimeDuration duration) { this.duration = duration; useDuration = true; if (useStart) { this.isMoving = this.start.isPresent(); // depends on control dependency: [if], data = [none] this.end = this.start.add(duration); // depends on control dependency: [if], data = [none] useEnd = false; // depends on control dependency: [if], data = [none] } else { this.isMoving = this.end.isPresent(); // depends on control dependency: [if], data = [none] this.start = this.end.subtract(duration); // depends on control dependency: [if], data = [none] } checkIfEmpty(); } }
public class class_name { public static <T> T newInstance(final Class<T> clazz) { Constructor<?>[] constructors = getAllConstructorsOfClass(clazz, true); if (constructors == null || constructors.length == 0) { return null; } Object[] initParameters = getInitParameters(constructors[0].getParameterTypes()); try { @SuppressWarnings("unchecked") T instance = (T) constructors[0].newInstance(initParameters); return instance; } catch (Exception e) { log.error("newInstance", e); return null; } } }
public class class_name { public static <T> T newInstance(final Class<T> clazz) { Constructor<?>[] constructors = getAllConstructorsOfClass(clazz, true); if (constructors == null || constructors.length == 0) { return null; // depends on control dependency: [if], data = [none] } Object[] initParameters = getInitParameters(constructors[0].getParameterTypes()); try { @SuppressWarnings("unchecked") T instance = (T) constructors[0].newInstance(initParameters); return instance; // depends on control dependency: [try], data = [none] } catch (Exception e) { log.error("newInstance", e); return null; } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public Map<String, String> getRedisInfo() { return PoolUtils.doWorkInPoolNicely(this.jedisPool, new PoolWork<Jedis, Map<String, String>>() { /** * {@inheritDoc} */ @Override public Map<String, String> doWork(final Jedis jedis) throws Exception { final Map<String, String> infoMap = new TreeMap<String, String>(); final String infoStr = jedis.info(); final String[] keyValueStrs = NEW_LINE_PATTERN.split(infoStr); for (final String keyValueStr : keyValueStrs) { if (!keyValueStr.isEmpty() && keyValueStr.charAt(0) != '#') { // Ignore categories for now final String[] keyAndValue = COLON_PATTERN.split(keyValueStr, 2); final String value = (keyAndValue.length == 1) ? null : keyAndValue[1]; infoMap.put(keyAndValue[0], value); } } return new LinkedHashMap<String, String>(infoMap); } }); } }
public class class_name { @Override public Map<String, String> getRedisInfo() { return PoolUtils.doWorkInPoolNicely(this.jedisPool, new PoolWork<Jedis, Map<String, String>>() { /** * {@inheritDoc} */ @Override public Map<String, String> doWork(final Jedis jedis) throws Exception { final Map<String, String> infoMap = new TreeMap<String, String>(); final String infoStr = jedis.info(); final String[] keyValueStrs = NEW_LINE_PATTERN.split(infoStr); for (final String keyValueStr : keyValueStrs) { if (!keyValueStr.isEmpty() && keyValueStr.charAt(0) != '#') { // Ignore categories for now final String[] keyAndValue = COLON_PATTERN.split(keyValueStr, 2); final String value = (keyAndValue.length == 1) ? null : keyAndValue[1]; infoMap.put(keyAndValue[0], value); // depends on control dependency: [if], data = [none] } } return new LinkedHashMap<String, String>(infoMap); } }); } }
public class class_name { public static float makeFloatValue( Object obj ) { if( obj == null ) { return Float.NaN; } return CommonServices.getCoercionManager().makePrimitiveFloatFrom( obj ); } }
public class class_name { public static float makeFloatValue( Object obj ) { if( obj == null ) { return Float.NaN; // depends on control dependency: [if], data = [none] } return CommonServices.getCoercionManager().makePrimitiveFloatFrom( obj ); } }
public class class_name { private String getAuthMethod(final Deployment dep) { for (final Endpoint ejbEndpoint : dep.getService().getEndpoints()) { final String beanAuthMethod = ejb3SecurityAccessor.getAuthMethod(ejbEndpoint); final boolean hasBeanAuthMethod = beanAuthMethod != null; if (hasBeanAuthMethod) { // First found auth-method defines war // login-config/auth-method return beanAuthMethod; } } return null; } }
public class class_name { private String getAuthMethod(final Deployment dep) { for (final Endpoint ejbEndpoint : dep.getService().getEndpoints()) { final String beanAuthMethod = ejb3SecurityAccessor.getAuthMethod(ejbEndpoint); final boolean hasBeanAuthMethod = beanAuthMethod != null; if (hasBeanAuthMethod) { // First found auth-method defines war // login-config/auth-method return beanAuthMethod; // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { @Override protected boolean loginToRemoteRegistry() { Pair<Integer, InputStream> result; try { // Check if user already logged in to azure isUserLoggedIn(); // If user isn't logged in, then login to azure via az cli. if(!loggedInToAzure) { Process process = Runtime.getRuntime().exec(azureCli.getLoginCommand(config.getAzureUserName(), config.getAzureUserPassword())); int resultValue = process.waitFor(); if (resultValue == 0) { logger.info("Log in to Azure account {} - Succeeded", config.getAzureUserName()); } else { logger.info("Log in to Azure account {} - Failed", config.getAzureUserName()); String errorMessage = IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8.name()); logger.error("Failed to log in to Azure account {} - {}", config.getAzureUserName(), errorMessage); return false; } } // Log in to registry via azure cli, Run azure command: "az acr login -n <RegistryName>" // Once azure login command to registry succeeded - docker obtains authentication to pull images from registry. for (String registryName : config.getAzureRegistryNames()) { if (registryName != null && !registryName.trim().equals(Constants.EMPTY_STRING)) { logger.info("Log in to Azure container registry {}", registryName); result = executeCommand(azureCli.getLoginContainerRegistryCommand(registryName)); if (result.getKey() == 0) { logger.info("Login to registry : {} - Succeeded", registryName); loggedInRegistries.add(registryName); } else { logger.info("Login to registry {} - Failed", registryName); logger.error("Failed to login registry {} - {}", registryName, IOUtils.toString(result.getValue(), StandardCharsets.UTF_8.name())); } } } return true; } catch (InterruptedException interruptedException) { logger.debug("Failed to login to Azure account, Exception: {}", interruptedException.getMessage()); } catch (IOException ioException) { // this exception occurred when parsing inputStream to String logger.debug("Failed to parse command error result, Exception: {}", ioException.getMessage()); } return false; } }
public class class_name { @Override protected boolean loginToRemoteRegistry() { Pair<Integer, InputStream> result; try { // Check if user already logged in to azure isUserLoggedIn(); // depends on control dependency: [try], data = [none] // If user isn't logged in, then login to azure via az cli. if(!loggedInToAzure) { Process process = Runtime.getRuntime().exec(azureCli.getLoginCommand(config.getAzureUserName(), config.getAzureUserPassword())); int resultValue = process.waitFor(); if (resultValue == 0) { logger.info("Log in to Azure account {} - Succeeded", config.getAzureUserName()); // depends on control dependency: [if], data = [none] } else { logger.info("Log in to Azure account {} - Failed", config.getAzureUserName()); // depends on control dependency: [if], data = [none] String errorMessage = IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8.name()); logger.error("Failed to log in to Azure account {} - {}", config.getAzureUserName(), errorMessage); // depends on control dependency: [if], data = [none] return false; // depends on control dependency: [if], data = [none] } } // Log in to registry via azure cli, Run azure command: "az acr login -n <RegistryName>" // Once azure login command to registry succeeded - docker obtains authentication to pull images from registry. for (String registryName : config.getAzureRegistryNames()) { if (registryName != null && !registryName.trim().equals(Constants.EMPTY_STRING)) { logger.info("Log in to Azure container registry {}", registryName); // depends on control dependency: [if], data = [none] result = executeCommand(azureCli.getLoginContainerRegistryCommand(registryName)); // depends on control dependency: [if], data = [(registryName] if (result.getKey() == 0) { logger.info("Login to registry : {} - Succeeded", registryName); // depends on control dependency: [if], data = [none] loggedInRegistries.add(registryName); // depends on control dependency: [if], data = [none] } else { logger.info("Login to registry {} - Failed", registryName); // depends on control dependency: [if], data = [none] logger.error("Failed to login registry {} - {}", registryName, IOUtils.toString(result.getValue(), StandardCharsets.UTF_8.name())); // depends on control dependency: [if], data = [none] } } } return true; // depends on control dependency: [try], data = [none] } catch (InterruptedException interruptedException) { logger.debug("Failed to login to Azure account, Exception: {}", interruptedException.getMessage()); } catch (IOException ioException) { // this exception occurred when parsing inputStream to String // depends on control dependency: [catch], data = [none] logger.debug("Failed to parse command error result, Exception: {}", ioException.getMessage()); } // depends on control dependency: [catch], data = [none] return false; } }
public class class_name { public void addAttribute(String name, final String value) { if (m_elemContext.m_startTagOpen) { final String patchedName = patchName(name); final String localName = getLocalName(patchedName); final String uri = getNamespaceURI(patchedName, false); addAttributeAlways(uri,localName, patchedName, "CDATA", value, false); } } }
public class class_name { public void addAttribute(String name, final String value) { if (m_elemContext.m_startTagOpen) { final String patchedName = patchName(name); final String localName = getLocalName(patchedName); final String uri = getNamespaceURI(patchedName, false); addAttributeAlways(uri,localName, patchedName, "CDATA", value, false); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static ObjectName makeObjectName(Object obj) { JmxResource jmxResource = obj.getClass().getAnnotation(JmxResource.class); if (obj instanceof JmxSelfNaming) { return makeObjectName(jmxResource, (JmxSelfNaming) obj); } else { if (jmxResource == null) { throw new IllegalArgumentException( "Registered class must either implement JmxSelfNaming or have JmxResource annotation"); } return makeObjectName(jmxResource, obj); } } }
public class class_name { public static ObjectName makeObjectName(Object obj) { JmxResource jmxResource = obj.getClass().getAnnotation(JmxResource.class); if (obj instanceof JmxSelfNaming) { return makeObjectName(jmxResource, (JmxSelfNaming) obj); // depends on control dependency: [if], data = [none] } else { if (jmxResource == null) { throw new IllegalArgumentException( "Registered class must either implement JmxSelfNaming or have JmxResource annotation"); } return makeObjectName(jmxResource, obj); // depends on control dependency: [if], data = [none] } } }
public class class_name { public Optional<Member> getOptionalMember(Object projectIdOrPath, Integer userId) { try { return (Optional.ofNullable(getMember(projectIdOrPath, userId))); } catch (GitLabApiException glae) { return (GitLabApi.createOptionalFromException(glae)); } } }
public class class_name { public Optional<Member> getOptionalMember(Object projectIdOrPath, Integer userId) { try { return (Optional.ofNullable(getMember(projectIdOrPath, userId))); // depends on control dependency: [try], data = [none] } catch (GitLabApiException glae) { return (GitLabApi.createOptionalFromException(glae)); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void setDisabled(boolean disabled) { this.disabled = disabled; if (disabled) { handlerManager.fireEvent(new ToolbarActionDisabledEvent()); } else { handlerManager.fireEvent(new ToolbarActionEnabledEvent()); } } }
public class class_name { public void setDisabled(boolean disabled) { this.disabled = disabled; if (disabled) { handlerManager.fireEvent(new ToolbarActionDisabledEvent()); // depends on control dependency: [if], data = [none] } else { handlerManager.fireEvent(new ToolbarActionEnabledEvent()); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static synchronized ModbusSlave createTCPSlave(InetAddress address, int port, int poolSize, boolean useRtuOverTcp) throws ModbusException { String key = ModbusSlaveType.TCP.getKey(port); if (slaves.containsKey(key)) { return slaves.get(key); } else { ModbusSlave slave = new ModbusSlave(address, port, poolSize, useRtuOverTcp); slaves.put(key, slave); return slave; } } }
public class class_name { public static synchronized ModbusSlave createTCPSlave(InetAddress address, int port, int poolSize, boolean useRtuOverTcp) throws ModbusException { String key = ModbusSlaveType.TCP.getKey(port); if (slaves.containsKey(key)) { return slaves.get(key); // depends on control dependency: [if], data = [none] } else { ModbusSlave slave = new ModbusSlave(address, port, poolSize, useRtuOverTcp); slaves.put(key, slave); // depends on control dependency: [if], data = [none] return slave; // depends on control dependency: [if], data = [none] } } }
public class class_name { public boolean isPanelsComment(QueryQuestionComment comment, Panel panel) { Panel queryPanel = resourceController.getResourcePanel(comment.getQueryPage().getQuerySection().getQuery()); if (queryPanel == null || panel == null) { return false; } return queryPanel.getId().equals(panel.getId()); } }
public class class_name { public boolean isPanelsComment(QueryQuestionComment comment, Panel panel) { Panel queryPanel = resourceController.getResourcePanel(comment.getQueryPage().getQuerySection().getQuery()); if (queryPanel == null || panel == null) { return false; // depends on control dependency: [if], data = [none] } return queryPanel.getId().equals(panel.getId()); } }
public class class_name { public boolean fastUnorderedRemoveInt(final int value) { @DoNotSub final int index = indexOf(value); if (-1 != index) { elements[index] = elements[--size]; return true; } return false; } }
public class class_name { public boolean fastUnorderedRemoveInt(final int value) { @DoNotSub final int index = indexOf(value); if (-1 != index) { elements[index] = elements[--size]; // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } return false; } }
public class class_name { public void wipeZeros() { Set<T> objToBeRemoved = new HashSet<T>(); for (T obj : objToCounts.keySet()) { if (shouldBeRemovedFromCounter(obj)) { objToBeRemoved.add(obj); } } for (T obj : objToBeRemoved) { objToCounts.remove(obj); } } }
public class class_name { public void wipeZeros() { Set<T> objToBeRemoved = new HashSet<T>(); for (T obj : objToCounts.keySet()) { if (shouldBeRemovedFromCounter(obj)) { objToBeRemoved.add(obj); // depends on control dependency: [if], data = [none] } } for (T obj : objToBeRemoved) { objToCounts.remove(obj); // depends on control dependency: [for], data = [obj] } } }
public class class_name { public V get(K key, V defaultValue) { // Check if we only know an equal entry V sharedValue = get(key); if (sharedValue == null) { // If no entry can be found, store and return the passed one sharedValue = defaultValue; // Make sure to remember the entry put(key, defaultValue); } // Return the shared entry return sharedValue; } }
public class class_name { public V get(K key, V defaultValue) { // Check if we only know an equal entry V sharedValue = get(key); if (sharedValue == null) { // If no entry can be found, store and return the passed one sharedValue = defaultValue; // depends on control dependency: [if], data = [none] // Make sure to remember the entry put(key, defaultValue); // depends on control dependency: [if], data = [none] } // Return the shared entry return sharedValue; } }
public class class_name { @Override public List<Object> collectMilestoningOverlaps() { List<Object> duplicateData = FastList.newList(); for (SemiUniqueEntry obj : nonDatedTable) { collectMilestoningOverlaps(duplicateData, obj); } return duplicateData; } }
public class class_name { @Override public List<Object> collectMilestoningOverlaps() { List<Object> duplicateData = FastList.newList(); for (SemiUniqueEntry obj : nonDatedTable) { collectMilestoningOverlaps(duplicateData, obj); // depends on control dependency: [for], data = [obj] } return duplicateData; } }
public class class_name { public void createTableIfNotExists(HBaseAdmin admin, byte[] tableName, HTableDescriptor tableDescriptor, byte[][] splitKeys, long timeout, TimeUnit timeoutUnit) throws IOException { if (admin.tableExists(tableName)) { return; } setDefaultConfiguration(tableDescriptor, admin.getConfiguration()); String tableNameString = Bytes.toString(tableName); try { LOG.info("Creating table '{}'", tableNameString); // HBaseAdmin.createTable can handle null splitKeys. admin.createTable(tableDescriptor, splitKeys); LOG.info("Table created '{}'", tableNameString); return; } catch (TableExistsException e) { // table may exist because someone else is creating it at the same // time. But it may not be available yet, and opening it might fail. LOG.info("Failed to create table '{}'. {}.", tableNameString, e.getMessage(), e); } // Wait for table to materialize try { Stopwatch stopwatch = new Stopwatch(); stopwatch.start(); long sleepTime = timeoutUnit.toNanos(timeout) / 10; sleepTime = sleepTime <= 0 ? 1 : sleepTime; do { if (admin.tableExists(tableName)) { LOG.info("Table '{}' exists now. Assuming that another process concurrently created it.", tableName); return; } else { TimeUnit.NANOSECONDS.sleep(sleepTime); } } while (stopwatch.elapsedTime(timeoutUnit) < timeout); } catch (InterruptedException e) { LOG.warn("Sleeping thread interrupted."); } LOG.error("Table '{}' does not exist after waiting {} ms. Giving up.", tableName, MAX_CREATE_TABLE_WAIT); } }
public class class_name { public void createTableIfNotExists(HBaseAdmin admin, byte[] tableName, HTableDescriptor tableDescriptor, byte[][] splitKeys, long timeout, TimeUnit timeoutUnit) throws IOException { if (admin.tableExists(tableName)) { return; } setDefaultConfiguration(tableDescriptor, admin.getConfiguration()); String tableNameString = Bytes.toString(tableName); try { LOG.info("Creating table '{}'", tableNameString); // HBaseAdmin.createTable can handle null splitKeys. admin.createTable(tableDescriptor, splitKeys); LOG.info("Table created '{}'", tableNameString); return; } catch (TableExistsException e) { // table may exist because someone else is creating it at the same // time. But it may not be available yet, and opening it might fail. LOG.info("Failed to create table '{}'. {}.", tableNameString, e.getMessage(), e); } // Wait for table to materialize try { Stopwatch stopwatch = new Stopwatch(); stopwatch.start(); long sleepTime = timeoutUnit.toNanos(timeout) / 10; sleepTime = sleepTime <= 0 ? 1 : sleepTime; do { if (admin.tableExists(tableName)) { LOG.info("Table '{}' exists now. Assuming that another process concurrently created it.", tableName); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } else { TimeUnit.NANOSECONDS.sleep(sleepTime); // depends on control dependency: [if], data = [none] } } while (stopwatch.elapsedTime(timeoutUnit) < timeout); } catch (InterruptedException e) { LOG.warn("Sleeping thread interrupted."); } LOG.error("Table '{}' does not exist after waiting {} ms. Giving up.", tableName, MAX_CREATE_TABLE_WAIT); } }
public class class_name { protected void createExportBackupFolders( File staticExport, String exportPath, int exportBackups, String ruleBackupExtension) { if (staticExport.exists()) { String backupFolderName = exportPath.substring(0, exportPath.lastIndexOf(File.separator) + 1); if (ruleBackupExtension != null) { backupFolderName = backupFolderName + EXPORT_BACKUP_FOLDER_NAME + ruleBackupExtension; } else { backupFolderName = backupFolderName + EXPORT_BACKUP_FOLDER_NAME; } for (int i = exportBackups; i > 0; i--) { File staticExportBackupOld = new File(backupFolderName + new Integer(i).toString()); if (staticExportBackupOld.exists()) { if ((i + 1) > exportBackups) { // delete folder if it is the last backup folder CmsFileUtil.purgeDirectory(staticExportBackupOld); } else { // set backup folder to the next backup folder name staticExportBackupOld.renameTo(new File(backupFolderName + new Integer(i + 1).toString())); } } // old export folder rename to first backup folder if (i == 1) { staticExport.renameTo(staticExportBackupOld); } } // if no backups will be stored the old export folder has to be deleted if (exportBackups == 0) { CmsFileUtil.purgeDirectory(staticExport); } } } }
public class class_name { protected void createExportBackupFolders( File staticExport, String exportPath, int exportBackups, String ruleBackupExtension) { if (staticExport.exists()) { String backupFolderName = exportPath.substring(0, exportPath.lastIndexOf(File.separator) + 1); if (ruleBackupExtension != null) { backupFolderName = backupFolderName + EXPORT_BACKUP_FOLDER_NAME + ruleBackupExtension; // depends on control dependency: [if], data = [none] } else { backupFolderName = backupFolderName + EXPORT_BACKUP_FOLDER_NAME; // depends on control dependency: [if], data = [none] } for (int i = exportBackups; i > 0; i--) { File staticExportBackupOld = new File(backupFolderName + new Integer(i).toString()); if (staticExportBackupOld.exists()) { if ((i + 1) > exportBackups) { // delete folder if it is the last backup folder CmsFileUtil.purgeDirectory(staticExportBackupOld); // depends on control dependency: [if], data = [none] } else { // set backup folder to the next backup folder name staticExportBackupOld.renameTo(new File(backupFolderName + new Integer(i + 1).toString())); // depends on control dependency: [if], data = [none] } } // old export folder rename to first backup folder if (i == 1) { staticExport.renameTo(staticExportBackupOld); // depends on control dependency: [if], data = [none] } } // if no backups will be stored the old export folder has to be deleted if (exportBackups == 0) { CmsFileUtil.purgeDirectory(staticExport); // depends on control dependency: [if], data = [none] } } } }
public class class_name { @Override public EEnum getIfcEngineTypeEnum() { if (ifcEngineTypeEnumEEnum == null) { ifcEngineTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(982); } return ifcEngineTypeEnumEEnum; } }
public class class_name { @Override public EEnum getIfcEngineTypeEnum() { if (ifcEngineTypeEnumEEnum == null) { ifcEngineTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(982); // depends on control dependency: [if], data = [none] } return ifcEngineTypeEnumEEnum; } }
public class class_name { public static List<ComputerPanelBox> all(Computer computer) { List<ComputerPanelBox> boxs = new ArrayList<>(); for(ComputerPanelBox box: ExtensionList.lookup(ComputerPanelBox.class)){ box.setComputer(computer); boxs.add(box); } return boxs; } }
public class class_name { public static List<ComputerPanelBox> all(Computer computer) { List<ComputerPanelBox> boxs = new ArrayList<>(); for(ComputerPanelBox box: ExtensionList.lookup(ComputerPanelBox.class)){ box.setComputer(computer); // depends on control dependency: [for], data = [box] boxs.add(box); // depends on control dependency: [for], data = [box] } return boxs; } }
public class class_name { private void blockBySessionOrIpFailedLoginAttempts(final String sessionId, final LoginBlockResultImpl loginBlockResultImpl) { final ApplicationSession applicationSession = applicationSessionDAO .findFirstByProperty(ApplicationSession_.sessionId, sessionId); if (applicationSession != null) { final ApplicationConfiguration maxLoginAttemptsBySession = applicationConfigurationService.checkValueOrLoadDefault(MAX_FAILED_LOGIN_ATTEMPTS_RECENT_HOUR_PER_SESSION, BLOCKS_ANY_LOGIN_ATTEMPTS_AFTER_THIS_NUMBER_IS_REACHED, ConfigurationGroup.AUTHENTICATION, LoginBlockedAccessImpl.class.getSimpleName(), LOGIN_BLOCKER, BLOCKS_LOGIN_ATTEMPTS, APPLICATION_AUTHENTICATION_ALLOW_MAX_RECENT_FAILED_LOGINS_BY_SESSION,DEFAULT_MAX_LOGIN_ATTEMPTS); final List<ApplicationActionEvent> failedLoginsByThisSession = applicationActionEventDAO.findListByProperty( new Object[] { sessionId, ApplicationOperationType.AUTHENTICATION, ServiceResult.FAILURE.toString() }, ApplicationActionEvent_.sessionId, ApplicationActionEvent_.applicationOperation, ApplicationActionEvent_.applicationMessage); if (failedLoginsByThisSession.size() > NumberUtils.toInt(maxLoginAttemptsBySession.getPropertyValue(),DEFAULT_MAX_LOGINS)) { loginBlockResultImpl.setBlocked(true); loginBlockResultImpl.addMessages(BLOCKED_BY_MORE_THAN_5_LOGIN_ATTEMPTS_BY_THIS_SESSION); } if (!("0:0:0:0:0:0:0:1".equals(applicationSession.getIpInformation()) || "127.0.0.1".equals(applicationSession.getIpInformation()))) { final List<ApplicationSession> applicationSessionsByIp = applicationSessionDAO .findListByProperty(ApplicationSession_.ipInformation, applicationSession.getIpInformation()); final List<String> sessionIdsWithIp = applicationSessionsByIp.stream().map(ApplicationSession::getSessionId) .collect(Collectors.toList()); final List<ApplicationActionEvent> applicationEventsWithIp = applicationActionEventDAO .findListByPropertyInList(ApplicationActionEvent_.sessionId, sessionIdsWithIp.toArray(new Object[sessionIdsWithIp.size()])); final Date oneHourAgo = new Date(System.currentTimeMillis() - ONE_HOUR); final Map<Boolean, List<ApplicationActionEvent>> recentOldLoginAttemptsMap = applicationEventsWithIp .stream() .filter((final ApplicationActionEvent x) -> x.getApplicationOperation() == ApplicationOperationType.AUTHENTICATION && x.getApplicationMessage().equals(ServiceResult.FAILURE.toString())) .collect(Collectors.groupingBy((final ApplicationActionEvent x) -> x.getCreatedDate().after(oneHourAgo))); final List<ApplicationActionEvent> recentFailedLogins = recentOldLoginAttemptsMap .get(Boolean.TRUE); final ApplicationConfiguration maxLoginAttemptsByIp = applicationConfigurationService.checkValueOrLoadDefault(MAX_FAILED_LOGIN_ATTEMPTS_RECENT_HOUR_PER_IP, BLOCKS_ANY_LOGIN_ATTEMPTS_AFTER_THIS_NUMBER_IS_REACHED, ConfigurationGroup.AUTHENTICATION, LoginBlockedAccessImpl.class.getSimpleName(), LOGIN_BLOCKER, BLOCKS_LOGIN_ATTEMPTS, APPLICATION_AUTHENTICATION_ALLOW_MAX_RECENT_FAILED_LOGINS_BY_IP, DEFAULT_MAX_LOGIN_ATTEMPTS); if (recentFailedLogins != null && recentFailedLogins.size() > NumberUtils.toInt(maxLoginAttemptsByIp.getPropertyValue(),DEFAULT_MAX_LOGINS_BY_IP)) { loginBlockResultImpl.setBlocked(true); loginBlockResultImpl.addMessages(BLOCKED_BY_MORE_THAN_5_RECENT_LOGIN_ATTEMPTS_BY_THIS_IP); } } } } }
public class class_name { private void blockBySessionOrIpFailedLoginAttempts(final String sessionId, final LoginBlockResultImpl loginBlockResultImpl) { final ApplicationSession applicationSession = applicationSessionDAO .findFirstByProperty(ApplicationSession_.sessionId, sessionId); if (applicationSession != null) { final ApplicationConfiguration maxLoginAttemptsBySession = applicationConfigurationService.checkValueOrLoadDefault(MAX_FAILED_LOGIN_ATTEMPTS_RECENT_HOUR_PER_SESSION, BLOCKS_ANY_LOGIN_ATTEMPTS_AFTER_THIS_NUMBER_IS_REACHED, ConfigurationGroup.AUTHENTICATION, LoginBlockedAccessImpl.class.getSimpleName(), LOGIN_BLOCKER, BLOCKS_LOGIN_ATTEMPTS, APPLICATION_AUTHENTICATION_ALLOW_MAX_RECENT_FAILED_LOGINS_BY_SESSION,DEFAULT_MAX_LOGIN_ATTEMPTS); final List<ApplicationActionEvent> failedLoginsByThisSession = applicationActionEventDAO.findListByProperty( new Object[] { sessionId, ApplicationOperationType.AUTHENTICATION, ServiceResult.FAILURE.toString() }, ApplicationActionEvent_.sessionId, ApplicationActionEvent_.applicationOperation, ApplicationActionEvent_.applicationMessage); if (failedLoginsByThisSession.size() > NumberUtils.toInt(maxLoginAttemptsBySession.getPropertyValue(),DEFAULT_MAX_LOGINS)) { loginBlockResultImpl.setBlocked(true); // depends on control dependency: [if], data = [none] loginBlockResultImpl.addMessages(BLOCKED_BY_MORE_THAN_5_LOGIN_ATTEMPTS_BY_THIS_SESSION); // depends on control dependency: [if], data = [none] } if (!("0:0:0:0:0:0:0:1".equals(applicationSession.getIpInformation()) || "127.0.0.1".equals(applicationSession.getIpInformation()))) { final List<ApplicationSession> applicationSessionsByIp = applicationSessionDAO .findListByProperty(ApplicationSession_.ipInformation, applicationSession.getIpInformation()); final List<String> sessionIdsWithIp = applicationSessionsByIp.stream().map(ApplicationSession::getSessionId) .collect(Collectors.toList()); final List<ApplicationActionEvent> applicationEventsWithIp = applicationActionEventDAO .findListByPropertyInList(ApplicationActionEvent_.sessionId, sessionIdsWithIp.toArray(new Object[sessionIdsWithIp.size()])); final Date oneHourAgo = new Date(System.currentTimeMillis() - ONE_HOUR); final Map<Boolean, List<ApplicationActionEvent>> recentOldLoginAttemptsMap = applicationEventsWithIp .stream() .filter((final ApplicationActionEvent x) -> x.getApplicationOperation() == ApplicationOperationType.AUTHENTICATION && x.getApplicationMessage().equals(ServiceResult.FAILURE.toString())) .collect(Collectors.groupingBy((final ApplicationActionEvent x) -> x.getCreatedDate().after(oneHourAgo))); final List<ApplicationActionEvent> recentFailedLogins = recentOldLoginAttemptsMap .get(Boolean.TRUE); final ApplicationConfiguration maxLoginAttemptsByIp = applicationConfigurationService.checkValueOrLoadDefault(MAX_FAILED_LOGIN_ATTEMPTS_RECENT_HOUR_PER_IP, BLOCKS_ANY_LOGIN_ATTEMPTS_AFTER_THIS_NUMBER_IS_REACHED, ConfigurationGroup.AUTHENTICATION, LoginBlockedAccessImpl.class.getSimpleName(), LOGIN_BLOCKER, BLOCKS_LOGIN_ATTEMPTS, APPLICATION_AUTHENTICATION_ALLOW_MAX_RECENT_FAILED_LOGINS_BY_IP, DEFAULT_MAX_LOGIN_ATTEMPTS); if (recentFailedLogins != null && recentFailedLogins.size() > NumberUtils.toInt(maxLoginAttemptsByIp.getPropertyValue(),DEFAULT_MAX_LOGINS_BY_IP)) { loginBlockResultImpl.setBlocked(true); // depends on control dependency: [if], data = [none] loginBlockResultImpl.addMessages(BLOCKED_BY_MORE_THAN_5_RECENT_LOGIN_ATTEMPTS_BY_THIS_IP); // depends on control dependency: [if], data = [none] } } } } }
public class class_name { @Override public boolean isSelected(final Comparable<E> value, final boolean caseSensitive) { if (!list.isEmpty() && list.get(0) instanceof String && !caseSensitive) { return list.contains(((String) value).toLowerCase()); } return list.contains(value); } }
public class class_name { @Override public boolean isSelected(final Comparable<E> value, final boolean caseSensitive) { if (!list.isEmpty() && list.get(0) instanceof String && !caseSensitive) { return list.contains(((String) value).toLowerCase()); } // depends on control dependency: [if], data = [lis] return list.contains(value); } }
public class class_name { public String getClassName() { switch (sort) { case VOID: return "void"; case BOOLEAN: return "boolean"; case CHAR: return "char"; case BYTE: return "byte"; case SHORT: return "short"; case INT: return "int"; case FLOAT: return "float"; case LONG: return "long"; case DOUBLE: return "double"; case ARRAY: StringBuffer b = new StringBuffer(getElementType().getClassName()); for (int i = getDimensions(); i > 0; --i) { b.append("[]"); } return b.toString(); // case OBJECT: default: return new String(buf, off, len).replace('/', '.'); } } }
public class class_name { public String getClassName() { switch (sort) { case VOID: return "void"; case BOOLEAN: return "boolean"; case CHAR: return "char"; case BYTE: return "byte"; case SHORT: return "short"; case INT: return "int"; case FLOAT: return "float"; case LONG: return "long"; case DOUBLE: return "double"; case ARRAY: StringBuffer b = new StringBuffer(getElementType().getClassName()); for (int i = getDimensions(); i > 0; --i) { b.append("[]"); // depends on control dependency: [for], data = [none] } return b.toString(); // case OBJECT: default: return new String(buf, off, len).replace('/', '.'); } } }
public class class_name { public void marshall(PutLogEventsRequest putLogEventsRequest, ProtocolMarshaller protocolMarshaller) { if (putLogEventsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(putLogEventsRequest.getLogGroupName(), LOGGROUPNAME_BINDING); protocolMarshaller.marshall(putLogEventsRequest.getLogStreamName(), LOGSTREAMNAME_BINDING); protocolMarshaller.marshall(putLogEventsRequest.getLogEvents(), LOGEVENTS_BINDING); protocolMarshaller.marshall(putLogEventsRequest.getSequenceToken(), SEQUENCETOKEN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(PutLogEventsRequest putLogEventsRequest, ProtocolMarshaller protocolMarshaller) { if (putLogEventsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(putLogEventsRequest.getLogGroupName(), LOGGROUPNAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(putLogEventsRequest.getLogStreamName(), LOGSTREAMNAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(putLogEventsRequest.getLogEvents(), LOGEVENTS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(putLogEventsRequest.getSequenceToken(), SEQUENCETOKEN_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public void processClass (File source, Class<?> oclass) throws Exception { // make sure we extend distributed object if (!_doclass.isAssignableFrom(oclass) || _doclass.equals(oclass)) { // System.err.println("Skipping " + oclass.getName() + "..."); return; } // determine which fields we need to deal with ArrayList<Field> flist = Lists.newArrayList(); Field[] fields = oclass.getDeclaredFields(); for (Field f : fields) { int mods = f.getModifiers(); if (!Modifier.isPublic(mods) || Modifier.isStatic(mods) || Modifier.isTransient(mods)) { continue; } flist.add(f); } // slurp our source file into newline separated strings SourceFile sfile = new SourceFile(); sfile.readFrom(source); // generate our fields section and our methods section StringBuilder fsection = new StringBuilder(); StringBuilder msection = new StringBuilder(); for (int ii = 0; ii < flist.size(); ii++) { Field f = flist.get(ii); Class<?> ftype = f.getType(); String fname = f.getName(); // create a map to hold our template data Map<String, Object> data = new HashMap<String, Object>(); data.put("field", fname); data.put("generated", GenUtil.getGeneratedAnnotation(getClass(), 4, false)); data.put("type", GenUtil.simpleName(f)); data.put("wrapfield", GenUtil.boxArgument(ftype, "value")); data.put("wrapofield", GenUtil.boxArgument(ftype, "ovalue")); data.put("clonefield", GenUtil.cloneArgument(_dsclass, f, "value")); data.put("capfield", StringUtil.unStudlyName(fname).toUpperCase()); data.put("upfield", StringUtil.capitalize(fname)); // determine the type of transport TransportHint hint = f.getAnnotation(TransportHint.class); if (hint == null) { // inherit hint from class annotation hint = f.getDeclaringClass().getAnnotation(TransportHint.class); } String transport; if (hint == null) { transport = ""; } else { transport = ",\n" + " com.threerings.presents.net.Transport.getInstance(\n" + " com.threerings.presents.net.Transport.Type." + hint.type().name() + ", " + hint.channel() + ")"; } data.put("transport", transport); // if this field is an array, we need its component types boolean array = ftype.isArray(); data.put("have_elem", array); if (array) { Class<?> etype = ftype.getComponentType(); data.put("elemtype", GenUtil.simpleName(etype)); data.put("wrapelem", GenUtil.boxArgument(etype, "value")); data.put("wrapoelem", GenUtil.boxArgument(etype, "ovalue")); } // if this field is a generic DSet, we need its bound type if (_dsclass.isAssignableFrom(ftype)) { Type t = f.getGenericType(); // we need to walk up the heirarchy until we get to the parameterized DSet while (t instanceof Class<?>) { t = ((Class<?>)t).getGenericSuperclass(); } if (t instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType)t; if (pt.getActualTypeArguments().length > 0) { data.put("etype", GenUtil.simpleName(pt.getActualTypeArguments()[0])); } } else { data.put("etype", "DSet.Entry"); } } // now figure out which template to use String tname = "field.tmpl"; if (_dsclass.isAssignableFrom(ftype)) { tname = "set.tmpl"; } else if (_olclass.isAssignableFrom(ftype)) { tname = "oidlist.tmpl"; } // append the merged templates as appropriate to the string buffers if (ii > 0) { fsection.append(EOL); msection.append(EOL); } fsection.append(mergeTemplate(NAME_TMPL, data)); msection.append(mergeTemplate(BASE_TMPL + tname, data)); } // now bolt everything back together into a class declaration writeFile(source.getAbsolutePath(), sfile.generate(fsection.toString(), msection.toString())); } }
public class class_name { @Override public void processClass (File source, Class<?> oclass) throws Exception { // make sure we extend distributed object if (!_doclass.isAssignableFrom(oclass) || _doclass.equals(oclass)) { // System.err.println("Skipping " + oclass.getName() + "..."); return; } // determine which fields we need to deal with ArrayList<Field> flist = Lists.newArrayList(); Field[] fields = oclass.getDeclaredFields(); for (Field f : fields) { int mods = f.getModifiers(); if (!Modifier.isPublic(mods) || Modifier.isStatic(mods) || Modifier.isTransient(mods)) { continue; } flist.add(f); } // slurp our source file into newline separated strings SourceFile sfile = new SourceFile(); sfile.readFrom(source); // generate our fields section and our methods section StringBuilder fsection = new StringBuilder(); StringBuilder msection = new StringBuilder(); for (int ii = 0; ii < flist.size(); ii++) { Field f = flist.get(ii); Class<?> ftype = f.getType(); String fname = f.getName(); // create a map to hold our template data Map<String, Object> data = new HashMap<String, Object>(); data.put("field", fname); data.put("generated", GenUtil.getGeneratedAnnotation(getClass(), 4, false)); data.put("type", GenUtil.simpleName(f)); data.put("wrapfield", GenUtil.boxArgument(ftype, "value")); data.put("wrapofield", GenUtil.boxArgument(ftype, "ovalue")); data.put("clonefield", GenUtil.cloneArgument(_dsclass, f, "value")); data.put("capfield", StringUtil.unStudlyName(fname).toUpperCase()); data.put("upfield", StringUtil.capitalize(fname)); // determine the type of transport TransportHint hint = f.getAnnotation(TransportHint.class); if (hint == null) { // inherit hint from class annotation hint = f.getDeclaringClass().getAnnotation(TransportHint.class); } String transport; if (hint == null) { transport = ""; } else { transport = ",\n" + " com.threerings.presents.net.Transport.getInstance(\n" + " com.threerings.presents.net.Transport.Type." + hint.type().name() + ", " + hint.channel() + ")"; } data.put("transport", transport); // if this field is an array, we need its component types boolean array = ftype.isArray(); data.put("have_elem", array); if (array) { Class<?> etype = ftype.getComponentType(); data.put("elemtype", GenUtil.simpleName(etype)); data.put("wrapelem", GenUtil.boxArgument(etype, "value")); data.put("wrapoelem", GenUtil.boxArgument(etype, "ovalue")); } // if this field is a generic DSet, we need its bound type if (_dsclass.isAssignableFrom(ftype)) { Type t = f.getGenericType(); // we need to walk up the heirarchy until we get to the parameterized DSet while (t instanceof Class<?>) { t = ((Class<?>)t).getGenericSuperclass(); } if (t instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType)t; if (pt.getActualTypeArguments().length > 0) { data.put("etype", GenUtil.simpleName(pt.getActualTypeArguments()[0])); // depends on control dependency: [if], data = [none] } } else { data.put("etype", "DSet.Entry"); } } // now figure out which template to use String tname = "field.tmpl"; if (_dsclass.isAssignableFrom(ftype)) { tname = "set.tmpl"; } else if (_olclass.isAssignableFrom(ftype)) { tname = "oidlist.tmpl"; } // append the merged templates as appropriate to the string buffers if (ii > 0) { fsection.append(EOL); // depends on control dependency: [if], data = [none] msection.append(EOL); // depends on control dependency: [if], data = [none] } fsection.append(mergeTemplate(NAME_TMPL, data)); msection.append(mergeTemplate(BASE_TMPL + tname, data)); } // now bolt everything back together into a class declaration writeFile(source.getAbsolutePath(), sfile.generate(fsection.toString(), msection.toString())); } }
public class class_name { public Collection<ValidationMessage<Origin>> getMessages(String messageKey) { Collection<ValidationMessage<Origin>> result = new ArrayList<ValidationMessage<Origin>>(); for (ValidationMessage<Origin> message : messages) { if (messageKey.equals(message.getMessageKey())) { result.add(message); } } return result; } }
public class class_name { public Collection<ValidationMessage<Origin>> getMessages(String messageKey) { Collection<ValidationMessage<Origin>> result = new ArrayList<ValidationMessage<Origin>>(); for (ValidationMessage<Origin> message : messages) { if (messageKey.equals(message.getMessageKey())) { result.add(message); // depends on control dependency: [if], data = [none] } } return result; } }
public class class_name { public static String formatAsDirectory(final String dotSep) { if (dotSep == null || "".equals(dotSep)) { return ""; } return dotSep.replace(GROUP_SEPARATOR, PATH_SEPARATOR); } }
public class class_name { public static String formatAsDirectory(final String dotSep) { if (dotSep == null || "".equals(dotSep)) { return ""; // depends on control dependency: [if], data = [none] } return dotSep.replace(GROUP_SEPARATOR, PATH_SEPARATOR); } }
public class class_name { private static MultiLineString splitMultiLineStringWithPoint(MultiLineString multiLineString, Point pointToSplit, double tolerance) { ArrayList<LineString> linestrings = new ArrayList<LineString>(); boolean notChanged = true; int nb = multiLineString.getNumGeometries(); for (int i = 0; i < nb; i++) { LineString subGeom = (LineString) multiLineString.getGeometryN(i); LineString[] result = splitLineStringWithPoint(subGeom, pointToSplit, tolerance); if (result != null) { Collections.addAll(linestrings, result); notChanged = false; } else { linestrings.add(subGeom); } } if (!notChanged) { return FACTORY.createMultiLineString(linestrings.toArray(new LineString[0])); } return null; } }
public class class_name { private static MultiLineString splitMultiLineStringWithPoint(MultiLineString multiLineString, Point pointToSplit, double tolerance) { ArrayList<LineString> linestrings = new ArrayList<LineString>(); boolean notChanged = true; int nb = multiLineString.getNumGeometries(); for (int i = 0; i < nb; i++) { LineString subGeom = (LineString) multiLineString.getGeometryN(i); LineString[] result = splitLineStringWithPoint(subGeom, pointToSplit, tolerance); if (result != null) { Collections.addAll(linestrings, result); // depends on control dependency: [if], data = [none] notChanged = false; // depends on control dependency: [if], data = [none] } else { linestrings.add(subGeom); // depends on control dependency: [if], data = [none] } } if (!notChanged) { return FACTORY.createMultiLineString(linestrings.toArray(new LineString[0])); // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { public void uninit() { if (initialized.get()) { log.debug("Uninit"); if (writer != null) { if (writerFuture != null) { try { writerFuture.get(); } catch (Exception e) { log.warn("Exception waiting for write result on uninit", e); } if (writerFuture.cancel(false)) { log.debug("Future completed"); } } writerFuture = null; // write all the queued items doWrites(); // clear the queue queue.clear(); queue = null; // close the writer writer.close(); writer = null; } // clear path ref path = null; } } }
public class class_name { public void uninit() { if (initialized.get()) { log.debug("Uninit"); // depends on control dependency: [if], data = [none] if (writer != null) { if (writerFuture != null) { try { writerFuture.get(); // depends on control dependency: [try], data = [none] } catch (Exception e) { log.warn("Exception waiting for write result on uninit", e); } // depends on control dependency: [catch], data = [none] if (writerFuture.cancel(false)) { log.debug("Future completed"); // depends on control dependency: [if], data = [none] } } writerFuture = null; // depends on control dependency: [if], data = [none] // write all the queued items doWrites(); // depends on control dependency: [if], data = [none] // clear the queue queue.clear(); // depends on control dependency: [if], data = [none] queue = null; // depends on control dependency: [if], data = [none] // close the writer writer.close(); // depends on control dependency: [if], data = [none] writer = null; // depends on control dependency: [if], data = [none] } // clear path ref path = null; // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override public String extract(OAuthRequest request) { checkPreconditions(request); final Map<String, String> parameters = request.getOauthParameters(); final StringBuilder header = new StringBuilder(PREAMBLE); for (Map.Entry<String, String> parameter : parameters.entrySet()) { if (header.length() > PREAMBLE.length()) { header.append(PARAM_SEPARATOR); } header.append(parameter.getKey()) .append("=\"") .append(OAuthEncoder.encode(parameter.getValue())) .append('"'); } if (request.getRealm() != null && !request.getRealm().isEmpty()) { header.append(PARAM_SEPARATOR) .append(OAuthConstants.REALM) .append("=\"") .append(request.getRealm()) .append('"'); } return header.toString(); } }
public class class_name { @Override public String extract(OAuthRequest request) { checkPreconditions(request); final Map<String, String> parameters = request.getOauthParameters(); final StringBuilder header = new StringBuilder(PREAMBLE); for (Map.Entry<String, String> parameter : parameters.entrySet()) { if (header.length() > PREAMBLE.length()) { header.append(PARAM_SEPARATOR); // depends on control dependency: [if], data = [none] } header.append(parameter.getKey()) .append("=\"") .append(OAuthEncoder.encode(parameter.getValue())) .append('"'); // depends on control dependency: [for], data = [none] } if (request.getRealm() != null && !request.getRealm().isEmpty()) { header.append(PARAM_SEPARATOR) .append(OAuthConstants.REALM) .append("=\"") .append(request.getRealm()) .append('"'); // depends on control dependency: [if], data = [none] } return header.toString(); } }
public class class_name { public Observable<ServiceResponse<UserInner>> getPublishingUserWithServiceResponseAsync() { if (this.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } return service.getPublishingUser(this.apiVersion(), this.acceptLanguage(), this.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<UserInner>>>() { @Override public Observable<ServiceResponse<UserInner>> call(Response<ResponseBody> response) { try { ServiceResponse<UserInner> clientResponse = getPublishingUserDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } }
public class class_name { public Observable<ServiceResponse<UserInner>> getPublishingUserWithServiceResponseAsync() { if (this.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } return service.getPublishingUser(this.apiVersion(), this.acceptLanguage(), this.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<UserInner>>>() { @Override public Observable<ServiceResponse<UserInner>> call(Response<ResponseBody> response) { try { ServiceResponse<UserInner> clientResponse = getPublishingUserDelegate(response); return Observable.just(clientResponse); // depends on control dependency: [try], data = [none] } catch (Throwable t) { return Observable.error(t); } // depends on control dependency: [catch], data = [none] } }); } }
public class class_name { public synchronized Counter findCounter(Enum key) { Counter counter = cache.get(key); if (counter == null) { Group group = getGroup(key.getDeclaringClass().getName()); counter = group.getCounterForName(key.toString()); cache.put(key, counter); } return counter; } }
public class class_name { public synchronized Counter findCounter(Enum key) { Counter counter = cache.get(key); if (counter == null) { Group group = getGroup(key.getDeclaringClass().getName()); counter = group.getCounterForName(key.toString()); // depends on control dependency: [if], data = [none] cache.put(key, counter); // depends on control dependency: [if], data = [none] } return counter; } }
public class class_name { private boolean processMultiBulkReply(ByteBuf in) { final int length = lineLength(); if (length == 0) { return false; } in.skipBytes(length); int num = readInt(length - 2); if (num == -1) { return true; } for (int i = 0; i < num; i++) { if (hasFrame(in) == false) { return false; } } return true; } }
public class class_name { private boolean processMultiBulkReply(ByteBuf in) { final int length = lineLength(); if (length == 0) { return false; // depends on control dependency: [if], data = [none] } in.skipBytes(length); int num = readInt(length - 2); if (num == -1) { return true; // depends on control dependency: [if], data = [none] } for (int i = 0; i < num; i++) { if (hasFrame(in) == false) { return false; // depends on control dependency: [if], data = [none] } } return true; } }
public class class_name { private Project.Calendars.Calendar writeCalendar(ProjectCalendar bc) { // // Create a calendar // Project.Calendars.Calendar calendar = m_factory.createProjectCalendarsCalendar(); calendar.setUID(NumberHelper.getBigInteger(bc.getUniqueID())); calendar.setIsBaseCalendar(Boolean.valueOf(!bc.isDerived())); ProjectCalendar base = bc.getParent(); // SF-329: null default required to keep Powerproject happy when importing MSPDI files calendar.setBaseCalendarUID(base == null ? NULL_CALENDAR_ID : NumberHelper.getBigInteger(base.getUniqueID())); calendar.setName(bc.getName()); // // Create a list of normal days // Project.Calendars.Calendar.WeekDays days = m_factory.createProjectCalendarsCalendarWeekDays(); Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime time; ProjectCalendarHours bch; List<Project.Calendars.Calendar.WeekDays.WeekDay> dayList = days.getWeekDay(); for (int loop = 1; loop < 8; loop++) { DayType workingFlag = bc.getWorkingDay(Day.getInstance(loop)); if (workingFlag != DayType.DEFAULT) { Project.Calendars.Calendar.WeekDays.WeekDay day = m_factory.createProjectCalendarsCalendarWeekDaysWeekDay(); dayList.add(day); day.setDayType(BigInteger.valueOf(loop)); day.setDayWorking(Boolean.valueOf(workingFlag == DayType.WORKING)); if (workingFlag == DayType.WORKING) { Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes times = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayWorkingTimes(); day.setWorkingTimes(times); List<Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime> timesList = times.getWorkingTime(); bch = bc.getCalendarHours(Day.getInstance(loop)); if (bch != null) { for (DateRange range : bch) { if (range != null) { time = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayWorkingTimesWorkingTime(); timesList.add(time); time.setFromTime(range.getStart()); time.setToTime(range.getEnd()); } } } } } } // // Create a list of exceptions // // A quirk of MS Project is that these exceptions must be // in date order in the file, otherwise they are ignored // List<ProjectCalendarException> exceptions = new ArrayList<ProjectCalendarException>(bc.getCalendarExceptions()); if (!exceptions.isEmpty()) { Collections.sort(exceptions); writeExceptions(calendar, dayList, exceptions); } // // Do not add a weekdays tag to the calendar unless it // has valid entries. // Fixes SourceForge bug 1854747: MPXJ and MSP 2007 XML formats // if (!dayList.isEmpty()) { calendar.setWeekDays(days); } writeWorkWeeks(calendar, bc); m_eventManager.fireCalendarWrittenEvent(bc); return (calendar); } }
public class class_name { private Project.Calendars.Calendar writeCalendar(ProjectCalendar bc) { // // Create a calendar // Project.Calendars.Calendar calendar = m_factory.createProjectCalendarsCalendar(); calendar.setUID(NumberHelper.getBigInteger(bc.getUniqueID())); calendar.setIsBaseCalendar(Boolean.valueOf(!bc.isDerived())); ProjectCalendar base = bc.getParent(); // SF-329: null default required to keep Powerproject happy when importing MSPDI files calendar.setBaseCalendarUID(base == null ? NULL_CALENDAR_ID : NumberHelper.getBigInteger(base.getUniqueID())); calendar.setName(bc.getName()); // // Create a list of normal days // Project.Calendars.Calendar.WeekDays days = m_factory.createProjectCalendarsCalendarWeekDays(); Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime time; ProjectCalendarHours bch; List<Project.Calendars.Calendar.WeekDays.WeekDay> dayList = days.getWeekDay(); for (int loop = 1; loop < 8; loop++) { DayType workingFlag = bc.getWorkingDay(Day.getInstance(loop)); if (workingFlag != DayType.DEFAULT) { Project.Calendars.Calendar.WeekDays.WeekDay day = m_factory.createProjectCalendarsCalendarWeekDaysWeekDay(); dayList.add(day); // depends on control dependency: [if], data = [none] day.setDayType(BigInteger.valueOf(loop)); // depends on control dependency: [if], data = [none] day.setDayWorking(Boolean.valueOf(workingFlag == DayType.WORKING)); // depends on control dependency: [if], data = [(workingFlag] if (workingFlag == DayType.WORKING) { Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes times = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayWorkingTimes(); day.setWorkingTimes(times); // depends on control dependency: [if], data = [none] List<Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime> timesList = times.getWorkingTime(); bch = bc.getCalendarHours(Day.getInstance(loop)); // depends on control dependency: [if], data = [none] if (bch != null) { for (DateRange range : bch) { if (range != null) { time = m_factory.createProjectCalendarsCalendarWeekDaysWeekDayWorkingTimesWorkingTime(); // depends on control dependency: [if], data = [none] timesList.add(time); // depends on control dependency: [if], data = [none] time.setFromTime(range.getStart()); // depends on control dependency: [if], data = [(range] time.setToTime(range.getEnd()); // depends on control dependency: [if], data = [(range] } } } } } } // // Create a list of exceptions // // A quirk of MS Project is that these exceptions must be // in date order in the file, otherwise they are ignored // List<ProjectCalendarException> exceptions = new ArrayList<ProjectCalendarException>(bc.getCalendarExceptions()); if (!exceptions.isEmpty()) { Collections.sort(exceptions); // depends on control dependency: [if], data = [none] writeExceptions(calendar, dayList, exceptions); // depends on control dependency: [if], data = [none] } // // Do not add a weekdays tag to the calendar unless it // has valid entries. // Fixes SourceForge bug 1854747: MPXJ and MSP 2007 XML formats // if (!dayList.isEmpty()) { calendar.setWeekDays(days); // depends on control dependency: [if], data = [none] } writeWorkWeeks(calendar, bc); m_eventManager.fireCalendarWrittenEvent(bc); return (calendar); } }
public class class_name { private void unbindValue(Session session, String name, Object value) { if (value instanceof SessionBindingListener) { ((SessionBindingListener)value).valueUnbound(session, name, value); } } }
public class class_name { private void unbindValue(Session session, String name, Object value) { if (value instanceof SessionBindingListener) { ((SessionBindingListener)value).valueUnbound(session, name, value); // depends on control dependency: [if], data = [none] } } }
public class class_name { private static <T> T withinLocale(final Callable<T> operation, final Locale locale) { DefaultICUContext ctx = context.get(); Locale oldLocale = ctx.getLocale(); try { ctx.setLocale(locale); return operation.call(); } catch (Exception e) { throw new RuntimeException(e); } finally { ctx.setLocale(oldLocale); context.set(ctx); } } }
public class class_name { private static <T> T withinLocale(final Callable<T> operation, final Locale locale) { DefaultICUContext ctx = context.get(); Locale oldLocale = ctx.getLocale(); try { ctx.setLocale(locale); // depends on control dependency: [try], data = [none] return operation.call(); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new RuntimeException(e); } finally // depends on control dependency: [catch], data = [none] { ctx.setLocale(oldLocale); context.set(ctx); } } }
public class class_name { public void setNames(java.util.Collection<String> names) { if (names == null) { this.names = null; return; } this.names = new java.util.ArrayList<String>(names); } }
public class class_name { public void setNames(java.util.Collection<String> names) { if (names == null) { this.names = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.names = new java.util.ArrayList<String>(names); } }
public class class_name { public static void warn(Object... message) { StringBuilder builder = new StringBuilder(APP_WARN); for (Object object : message) { builder.append(object.toString()); } warnStream.println(builder.toString()); } }
public class class_name { public static void warn(Object... message) { StringBuilder builder = new StringBuilder(APP_WARN); for (Object object : message) { builder.append(object.toString()); // depends on control dependency: [for], data = [object] } warnStream.println(builder.toString()); } }
public class class_name { public synchronized void putSITransaction(SITransaction transaction) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "putSITransaction", transaction); Transaction commsTx = (Transaction)transaction; int flags = -1; if (transaction == null) { // No transaction - add "no transaction" flags to buffer. putInt(0x00000000); } else { // First we must search for any optimized transactions as they hold much more information // than the old-style ones. OptimizedTransaction optTx = null; // First see if the transaction is a global one. This could be both optimized or // unoptimized but the result is buried within it if (transaction instanceof SuspendableXAResource) { SIXAResource suspendableXARes = ((SuspendableXAResource) transaction).getCurrentXAResource(); if (suspendableXARes instanceof OptimizedTransaction) { // The current XA Resource is indeed optimized optTx = (OptimizedTransaction) suspendableXARes; } } // Otherwise the actual transaction itself may be an optimized one - this is in the case // of an optimized local transaction. else if (transaction instanceof OptimizedTransaction) { optTx = (OptimizedTransaction) transaction; } // If we are optimized... if (optTx != null) { // Optimized transaction flags = CommsConstants.OPTIMIZED_TX_FLAGS_TRANSACTED_BIT; boolean local = optTx instanceof SIUncoordinatedTransaction; boolean addXid = false; boolean endPreviousUow = false; if (local) { flags |= CommsConstants.OPTIMIZED_TX_FLAGS_LOCAL_BIT; } if (!optTx.isServerTransactionCreated()) { flags |= CommsConstants.OPTIMIZED_TX_FLAGS_CREATE_BIT; if (local && optTx.areSubordinatesAllowed()) flags |= CommsConstants.OPTIMIZED_TX_FLAGS_SUBORDINATES_ALLOWED; optTx.setServerTransactionCreated(); addXid = !local; } if (addXid && (optTx.isEndRequired())) { flags |= CommsConstants.OPTIMIZED_TX_END_PREVIOUS_BIT; endPreviousUow = true; } putInt(flags); putInt(optTx.getCreatingConversationId()); putInt(commsTx.getTransactionId()); if (addXid) { if (endPreviousUow) { putInt(optTx.getEndFlags()); optTx.setEndNotRequired(); } putXid(new XidProxy(optTx.getXidForCurrentUow())); } } else { // This is an un-optimized transaction - simply append transaction ID. putInt(commsTx.getTransactionId()); } } if (TraceComponent.isAnyTracingEnabled()) { int commsId = -1; if (commsTx != null) commsId = commsTx.getTransactionId(); CommsLightTrace.traceTransaction(tc, "PutTxnTrace", commsTx, commsId, flags); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "putSITransaction"); } }
public class class_name { public synchronized void putSITransaction(SITransaction transaction) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "putSITransaction", transaction); Transaction commsTx = (Transaction)transaction; int flags = -1; if (transaction == null) { // No transaction - add "no transaction" flags to buffer. putInt(0x00000000); // depends on control dependency: [if], data = [none] } else { // First we must search for any optimized transactions as they hold much more information // than the old-style ones. OptimizedTransaction optTx = null; // First see if the transaction is a global one. This could be both optimized or // unoptimized but the result is buried within it if (transaction instanceof SuspendableXAResource) { SIXAResource suspendableXARes = ((SuspendableXAResource) transaction).getCurrentXAResource(); if (suspendableXARes instanceof OptimizedTransaction) { // The current XA Resource is indeed optimized optTx = (OptimizedTransaction) suspendableXARes; // depends on control dependency: [if], data = [none] } } // Otherwise the actual transaction itself may be an optimized one - this is in the case // of an optimized local transaction. else if (transaction instanceof OptimizedTransaction) { optTx = (OptimizedTransaction) transaction; // depends on control dependency: [if], data = [none] } // If we are optimized... if (optTx != null) { // Optimized transaction flags = CommsConstants.OPTIMIZED_TX_FLAGS_TRANSACTED_BIT; // depends on control dependency: [if], data = [none] boolean local = optTx instanceof SIUncoordinatedTransaction; boolean addXid = false; boolean endPreviousUow = false; if (local) { flags |= CommsConstants.OPTIMIZED_TX_FLAGS_LOCAL_BIT; // depends on control dependency: [if], data = [none] } if (!optTx.isServerTransactionCreated()) { flags |= CommsConstants.OPTIMIZED_TX_FLAGS_CREATE_BIT; // depends on control dependency: [if], data = [none] if (local && optTx.areSubordinatesAllowed()) flags |= CommsConstants.OPTIMIZED_TX_FLAGS_SUBORDINATES_ALLOWED; optTx.setServerTransactionCreated(); // depends on control dependency: [if], data = [none] addXid = !local; // depends on control dependency: [if], data = [none] } if (addXid && (optTx.isEndRequired())) { flags |= CommsConstants.OPTIMIZED_TX_END_PREVIOUS_BIT; // depends on control dependency: [if], data = [none] endPreviousUow = true; // depends on control dependency: [if], data = [none] } putInt(flags); // depends on control dependency: [if], data = [none] putInt(optTx.getCreatingConversationId()); // depends on control dependency: [if], data = [(optTx] putInt(commsTx.getTransactionId()); // depends on control dependency: [if], data = [none] if (addXid) { if (endPreviousUow) { putInt(optTx.getEndFlags()); // depends on control dependency: [if], data = [none] optTx.setEndNotRequired(); // depends on control dependency: [if], data = [none] } putXid(new XidProxy(optTx.getXidForCurrentUow())); // depends on control dependency: [if], data = [none] } } else { // This is an un-optimized transaction - simply append transaction ID. putInt(commsTx.getTransactionId()); // depends on control dependency: [if], data = [none] } } if (TraceComponent.isAnyTracingEnabled()) { int commsId = -1; if (commsTx != null) commsId = commsTx.getTransactionId(); CommsLightTrace.traceTransaction(tc, "PutTxnTrace", commsTx, commsId, flags); // depends on control dependency: [if], data = [none] } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "putSITransaction"); } }
public class class_name { static boolean validateUsageParameterInterface(ComponentID id, boolean isSlee11, Class<?> usageInterface, List<UsageParameterDescriptor> parameters) { boolean passed = true; String errorBuffer = new String(""); try { if (!usageInterface.isInterface()) { passed = false; errorBuffer = appendToBuffer(id, "Usage parameter interface class is not an interface", "11.2", errorBuffer); return passed; } // Interface constraints if (isSlee11 && usageInterface.getPackage() == null) { passed = false; errorBuffer = appendToBuffer(id, "Usage parameter interface must be declared in pacakge name space.", "11.2", errorBuffer); } if (!Modifier.isPublic(usageInterface.getModifiers())) { passed = false; errorBuffer = appendToBuffer(id, "Usage parameter interface must be declared as public.", "11.2", errorBuffer); } // parameters check Set<String> ignore = new HashSet<String>(); ignore.add("java.lang.Object"); Map<String, Method> interfaceMethods = ClassUtils.getAllInterfacesMethods(usageInterface, ignore); Map<String, UsageParameterDescriptor> localParametersMap = new HashMap<String, UsageParameterDescriptor>(); Set<String> identifiedIncrement = new HashSet<String>(); Set<String> identifiedGetIncrement = new HashSet<String>(); Set<String> identifiedSample = new HashSet<String>(); Set<String> identifiedGetSample = new HashSet<String>(); // this is for 1.1, get and increment methods must match with type // validate parameter names if we are slee11 if (isSlee11) for (UsageParameterDescriptor usage : parameters) { char c = usage.getName().charAt(0); if (!Character.isLowerCase(c)) { passed = false; errorBuffer = appendToBuffer(id, "Parameter name must start with lower case character and be start of valid jva identifier, parameter name from descriptor: " + usage.getName(), "11.2", errorBuffer); } localParametersMap.put(usage.getName(), usage); } // at the end we have to have empty list for (Entry<String, Method> entry : interfaceMethods.entrySet()) { // String declaredLongMethodName = entry.getKey(); Method m = entry.getValue(); String declaredMethodName = m.getName(); String declaredPrameterName = null; Character c = null; // he we just do checks, methods against constraints // we remove them from parameters map, there is something left // or not present in map in case of 1.1 // some variable that we need to store info about method boolean isIncrement = false; boolean isGetIncrement = false; boolean isGetSample = false; boolean isSample = false; // 1.0 comp if (declaredMethodName.startsWith(_SAMPLE_METHOD_PREFIX)) { declaredPrameterName = declaredMethodName.replaceFirst(_SAMPLE_METHOD_PREFIX, ""); c = declaredPrameterName.charAt(0); isSample = true; // 1.0 comp } else if (declaredMethodName.startsWith(_INCREMENT_METHOD_PREFIX)) { declaredPrameterName = declaredMethodName.replaceFirst(_INCREMENT_METHOD_PREFIX, ""); c = declaredPrameterName.charAt(0); isIncrement = true; // 1.1 only } else if (declaredMethodName.startsWith(_GET_METHOD_PREFIX)) { declaredPrameterName = declaredMethodName.replaceFirst(_GET_METHOD_PREFIX, ""); c = declaredPrameterName.charAt(0); if (!isSlee11) { passed = false; errorBuffer = appendToBuffer(id, "Wrong method declared in parameter usage interface. Get method for counter parameter types are allowed only in JSLEE 1.1, method: " + declaredMethodName, "11.2.X", errorBuffer); } if (m.getReturnType().getName().compareTo("javax.slee.usage.SampleStatistics") == 0) { isGetSample = true; } else { // we asume thats increment get isGetIncrement = true; } } else { passed = false; errorBuffer = appendToBuffer(id, "Wrong method decalred in parameter usage interface. Methods must start with either \"get\", \"sample\" or \"increment\", method: " + declaredMethodName, "11.2.X", errorBuffer); continue; } if (!Character.isUpperCase(c)) { passed = false; errorBuffer = appendToBuffer(id, "Method stripped of prefix, either \"get\", \"sample\" or \"increment\", must have following upper case character,method: " + declaredMethodName, "11.2", errorBuffer); } declaredPrameterName = Introspector.decapitalize(declaredPrameterName); if (!isValidJavaIdentifier(declaredPrameterName)) { passed = false; errorBuffer = appendToBuffer(id, "Parameter name must be valid java identifier: " + declaredPrameterName, "11.2", errorBuffer); } // well we have indentified parameter, lets store; if (isIncrement) { if (identifiedIncrement.contains(declaredMethodName)) { passed = false; errorBuffer = appendToBuffer(id, "Duplicate declaration of usage parameter, possibly twe methods with the same name and different signature, method: " + declaredMethodName, "11.2", errorBuffer); } else { identifiedIncrement.add(declaredPrameterName); if (!validateParameterSetterSignatureMethod(id, m, "11.2.3")) { passed = false; } } } else if (isGetIncrement) { if (identifiedGetIncrement.contains(declaredMethodName)) { passed = false; errorBuffer = appendToBuffer(id, "Duplicate declaration of usage parameter, possibly twe methods with the same name and different signature, method: " + declaredMethodName, "11.2", errorBuffer); } else { identifiedGetIncrement.add(declaredPrameterName); if (!validateParameterGetterSignatureMethod(id, m, "11.2.2", Long.TYPE)) { passed = false; } } } else if (isGetSample) { if (identifiedGetSample.contains(declaredMethodName)) { passed = false; errorBuffer = appendToBuffer(id, "Duplicate declaration of usage parameter, possibly twe methods with the same name and different signature, method: " + declaredMethodName, "11.2", errorBuffer); } else { identifiedGetSample.add(declaredPrameterName); if (!validateParameterGetterSignatureMethod(id, m, "11.2.4", javax.slee.usage.SampleStatistics.class)) { passed = false; } } } else if (isSample) { if (identifiedSample.contains(declaredMethodName)) { passed = false; errorBuffer = appendToBuffer(id, "Duplicate declaration of usage parameter, possibly twe methods with the same name and different signature, method: " + declaredMethodName, "11.2", errorBuffer); } else { identifiedSample.add(declaredPrameterName); if (!validateParameterSetterSignatureMethod(id, m, "11.2.1")) { passed = false; errorBuffer = appendToBuffer(id, "Duplicate declaration of usage parameter, possibly twe methods with the same name and different signature, method: " + declaredMethodName, "11.2", errorBuffer); } } } // UFFF, lets start the play // /uh its a bit complicated } // we siganture here is ok, return types also, no duplicates, left: // 1. cross check field types that we found - sample vs increments - // there cant be doubles // 2. remove all from list, if something is left, bam, we lack one // method or have to many :) Set<String> agregatedIncrement = new HashSet<String>(); Set<String> agregatedSample = new HashSet<String>(); agregatedIncrement.addAll(identifiedGetIncrement); agregatedIncrement.addAll(identifiedIncrement); agregatedSample.addAll(identifiedGetSample); agregatedSample.addAll(identifiedSample); Set<String> tmp = new HashSet<String>(agregatedSample); tmp.retainAll(agregatedIncrement); if (!tmp.isEmpty()) { // ugh, its the end passed = false; errorBuffer = appendToBuffer(id, "Usage parameters can be associated only with single type - increment or sample, offending parameters: " + Arrays.toString(tmp.toArray()), "11.2", errorBuffer); return passed; } if (isSlee11) { tmp.clear(); tmp.addAll(agregatedSample); tmp.addAll(agregatedIncrement); // localParametersMap.size()!=0 - cause we can have zero of them // - usage-parameter may not be present so its generation is // turned off if (localParametersMap.size() != tmp.size() && localParametersMap.size() != 0) { passed = false; String errorPart = null; if (localParametersMap.size() > tmp.size()) { // is there any bettter way? for (String s : localParametersMap.keySet()) tmp.remove(s); errorPart = "More parameters are defined in descriptor, offending parameters: " + Arrays.toString(tmp.toArray()); } else { for (String s : tmp) localParametersMap.remove(s); errorPart = "More parameters are defined in descriptor, offending parameters: " + Arrays.toString(localParametersMap.keySet().toArray()); } errorBuffer = appendToBuffer(id, "Failed to map descriptor defined usage parameters against interface class methods. " + errorPart, "11.2", errorBuffer); } } } finally { if (!passed) { logger.error(errorBuffer); // System.err.println(errorBuffer); } } return passed; } }
public class class_name { static boolean validateUsageParameterInterface(ComponentID id, boolean isSlee11, Class<?> usageInterface, List<UsageParameterDescriptor> parameters) { boolean passed = true; String errorBuffer = new String(""); try { if (!usageInterface.isInterface()) { passed = false; // depends on control dependency: [if], data = [none] errorBuffer = appendToBuffer(id, "Usage parameter interface class is not an interface", "11.2", errorBuffer); // depends on control dependency: [if], data = [none] return passed; // depends on control dependency: [if], data = [none] } // Interface constraints if (isSlee11 && usageInterface.getPackage() == null) { passed = false; // depends on control dependency: [if], data = [none] errorBuffer = appendToBuffer(id, "Usage parameter interface must be declared in pacakge name space.", "11.2", errorBuffer); // depends on control dependency: [if], data = [none] } if (!Modifier.isPublic(usageInterface.getModifiers())) { passed = false; // depends on control dependency: [if], data = [none] errorBuffer = appendToBuffer(id, "Usage parameter interface must be declared as public.", "11.2", errorBuffer); // depends on control dependency: [if], data = [none] } // parameters check Set<String> ignore = new HashSet<String>(); ignore.add("java.lang.Object"); // depends on control dependency: [try], data = [none] Map<String, Method> interfaceMethods = ClassUtils.getAllInterfacesMethods(usageInterface, ignore); Map<String, UsageParameterDescriptor> localParametersMap = new HashMap<String, UsageParameterDescriptor>(); Set<String> identifiedIncrement = new HashSet<String>(); Set<String> identifiedGetIncrement = new HashSet<String>(); Set<String> identifiedSample = new HashSet<String>(); Set<String> identifiedGetSample = new HashSet<String>(); // this is for 1.1, get and increment methods must match with type // validate parameter names if we are slee11 if (isSlee11) for (UsageParameterDescriptor usage : parameters) { char c = usage.getName().charAt(0); if (!Character.isLowerCase(c)) { passed = false; // depends on control dependency: [if], data = [none] errorBuffer = appendToBuffer(id, "Parameter name must start with lower case character and be start of valid jva identifier, parameter name from descriptor: " + usage.getName(), "11.2", errorBuffer); // depends on control dependency: [if], data = [none] } localParametersMap.put(usage.getName(), usage); // depends on control dependency: [for], data = [usage] } // at the end we have to have empty list for (Entry<String, Method> entry : interfaceMethods.entrySet()) { // String declaredLongMethodName = entry.getKey(); Method m = entry.getValue(); String declaredMethodName = m.getName(); String declaredPrameterName = null; Character c = null; // he we just do checks, methods against constraints // we remove them from parameters map, there is something left // or not present in map in case of 1.1 // some variable that we need to store info about method boolean isIncrement = false; boolean isGetIncrement = false; boolean isGetSample = false; boolean isSample = false; // 1.0 comp if (declaredMethodName.startsWith(_SAMPLE_METHOD_PREFIX)) { declaredPrameterName = declaredMethodName.replaceFirst(_SAMPLE_METHOD_PREFIX, ""); // depends on control dependency: [if], data = [none] c = declaredPrameterName.charAt(0); // depends on control dependency: [if], data = [none] isSample = true; // depends on control dependency: [if], data = [none] // 1.0 comp } else if (declaredMethodName.startsWith(_INCREMENT_METHOD_PREFIX)) { declaredPrameterName = declaredMethodName.replaceFirst(_INCREMENT_METHOD_PREFIX, ""); // depends on control dependency: [if], data = [none] c = declaredPrameterName.charAt(0); // depends on control dependency: [if], data = [none] isIncrement = true; // depends on control dependency: [if], data = [none] // 1.1 only } else if (declaredMethodName.startsWith(_GET_METHOD_PREFIX)) { declaredPrameterName = declaredMethodName.replaceFirst(_GET_METHOD_PREFIX, ""); // depends on control dependency: [if], data = [none] c = declaredPrameterName.charAt(0); // depends on control dependency: [if], data = [none] if (!isSlee11) { passed = false; // depends on control dependency: [if], data = [none] errorBuffer = appendToBuffer(id, "Wrong method declared in parameter usage interface. Get method for counter parameter types are allowed only in JSLEE 1.1, method: " + declaredMethodName, "11.2.X", errorBuffer); // depends on control dependency: [if], data = [none] } if (m.getReturnType().getName().compareTo("javax.slee.usage.SampleStatistics") == 0) { isGetSample = true; // depends on control dependency: [if], data = [none] } else { // we asume thats increment get isGetIncrement = true; // depends on control dependency: [if], data = [none] } } else { passed = false; // depends on control dependency: [if], data = [none] errorBuffer = appendToBuffer(id, "Wrong method decalred in parameter usage interface. Methods must start with either \"get\", \"sample\" or \"increment\", method: " + declaredMethodName, "11.2.X", errorBuffer); // depends on control dependency: [if], data = [none] continue; } if (!Character.isUpperCase(c)) { passed = false; // depends on control dependency: [if], data = [none] errorBuffer = appendToBuffer(id, "Method stripped of prefix, either \"get\", \"sample\" or \"increment\", must have following upper case character,method: " + declaredMethodName, "11.2", errorBuffer); // depends on control dependency: [if], data = [none] } declaredPrameterName = Introspector.decapitalize(declaredPrameterName); // depends on control dependency: [for], data = [none] if (!isValidJavaIdentifier(declaredPrameterName)) { passed = false; // depends on control dependency: [if], data = [none] errorBuffer = appendToBuffer(id, "Parameter name must be valid java identifier: " + declaredPrameterName, "11.2", errorBuffer); // depends on control dependency: [if], data = [none] } // well we have indentified parameter, lets store; if (isIncrement) { if (identifiedIncrement.contains(declaredMethodName)) { passed = false; // depends on control dependency: [if], data = [none] errorBuffer = appendToBuffer(id, "Duplicate declaration of usage parameter, possibly twe methods with the same name and different signature, method: " + declaredMethodName, "11.2", errorBuffer); // depends on control dependency: [if], data = [none] } else { identifiedIncrement.add(declaredPrameterName); // depends on control dependency: [if], data = [none] if (!validateParameterSetterSignatureMethod(id, m, "11.2.3")) { passed = false; // depends on control dependency: [if], data = [none] } } } else if (isGetIncrement) { if (identifiedGetIncrement.contains(declaredMethodName)) { passed = false; // depends on control dependency: [if], data = [none] errorBuffer = appendToBuffer(id, "Duplicate declaration of usage parameter, possibly twe methods with the same name and different signature, method: " + declaredMethodName, "11.2", errorBuffer); // depends on control dependency: [if], data = [none] } else { identifiedGetIncrement.add(declaredPrameterName); // depends on control dependency: [if], data = [none] if (!validateParameterGetterSignatureMethod(id, m, "11.2.2", Long.TYPE)) { passed = false; // depends on control dependency: [if], data = [none] } } } else if (isGetSample) { if (identifiedGetSample.contains(declaredMethodName)) { passed = false; // depends on control dependency: [if], data = [none] errorBuffer = appendToBuffer(id, "Duplicate declaration of usage parameter, possibly twe methods with the same name and different signature, method: " + declaredMethodName, "11.2", errorBuffer); // depends on control dependency: [if], data = [none] } else { identifiedGetSample.add(declaredPrameterName); // depends on control dependency: [if], data = [none] if (!validateParameterGetterSignatureMethod(id, m, "11.2.4", javax.slee.usage.SampleStatistics.class)) { passed = false; // depends on control dependency: [if], data = [none] } } } else if (isSample) { if (identifiedSample.contains(declaredMethodName)) { passed = false; // depends on control dependency: [if], data = [none] errorBuffer = appendToBuffer(id, "Duplicate declaration of usage parameter, possibly twe methods with the same name and different signature, method: " + declaredMethodName, "11.2", errorBuffer); // depends on control dependency: [if], data = [none] } else { identifiedSample.add(declaredPrameterName); // depends on control dependency: [if], data = [none] if (!validateParameterSetterSignatureMethod(id, m, "11.2.1")) { passed = false; // depends on control dependency: [if], data = [none] errorBuffer = appendToBuffer(id, "Duplicate declaration of usage parameter, possibly twe methods with the same name and different signature, method: " + declaredMethodName, "11.2", errorBuffer); // depends on control dependency: [if], data = [none] } } } // UFFF, lets start the play // /uh its a bit complicated } // we siganture here is ok, return types also, no duplicates, left: // 1. cross check field types that we found - sample vs increments - // there cant be doubles // 2. remove all from list, if something is left, bam, we lack one // method or have to many :) Set<String> agregatedIncrement = new HashSet<String>(); Set<String> agregatedSample = new HashSet<String>(); agregatedIncrement.addAll(identifiedGetIncrement); // depends on control dependency: [try], data = [none] agregatedIncrement.addAll(identifiedIncrement); // depends on control dependency: [try], data = [none] agregatedSample.addAll(identifiedGetSample); // depends on control dependency: [try], data = [none] agregatedSample.addAll(identifiedSample); // depends on control dependency: [try], data = [none] Set<String> tmp = new HashSet<String>(agregatedSample); tmp.retainAll(agregatedIncrement); // depends on control dependency: [try], data = [none] if (!tmp.isEmpty()) { // ugh, its the end passed = false; // depends on control dependency: [if], data = [none] errorBuffer = appendToBuffer(id, "Usage parameters can be associated only with single type - increment or sample, offending parameters: " + Arrays.toString(tmp.toArray()), "11.2", errorBuffer); // depends on control dependency: [if], data = [none] return passed; // depends on control dependency: [if], data = [none] } if (isSlee11) { tmp.clear(); // depends on control dependency: [if], data = [none] tmp.addAll(agregatedSample); // depends on control dependency: [if], data = [none] tmp.addAll(agregatedIncrement); // depends on control dependency: [if], data = [none] // localParametersMap.size()!=0 - cause we can have zero of them // - usage-parameter may not be present so its generation is // turned off if (localParametersMap.size() != tmp.size() && localParametersMap.size() != 0) { passed = false; // depends on control dependency: [if], data = [none] String errorPart = null; if (localParametersMap.size() > tmp.size()) { // is there any bettter way? for (String s : localParametersMap.keySet()) tmp.remove(s); errorPart = "More parameters are defined in descriptor, offending parameters: " + Arrays.toString(tmp.toArray()); // depends on control dependency: [if], data = [none] } else { for (String s : tmp) localParametersMap.remove(s); errorPart = "More parameters are defined in descriptor, offending parameters: " + Arrays.toString(localParametersMap.keySet().toArray()); // depends on control dependency: [if], data = [none] } errorBuffer = appendToBuffer(id, "Failed to map descriptor defined usage parameters against interface class methods. " + errorPart, "11.2", errorBuffer); // depends on control dependency: [if], data = [none] } } } finally { if (!passed) { logger.error(errorBuffer); // depends on control dependency: [if], data = [none] // System.err.println(errorBuffer); } } return passed; } }
public class class_name { private static Prefix getPrefix(final String string, final Set<Prefix> set) { for (final Iterator<Prefix> iter = set.iterator(); iter.hasNext();) { final Prefix prefix = iter.next(); final int comp = prefix.compareTo(string); if (comp == 0) { return prefix; } if (comp > 0) { break; } } return null; } }
public class class_name { private static Prefix getPrefix(final String string, final Set<Prefix> set) { for (final Iterator<Prefix> iter = set.iterator(); iter.hasNext();) { final Prefix prefix = iter.next(); final int comp = prefix.compareTo(string); if (comp == 0) { return prefix; // depends on control dependency: [if], data = [none] } if (comp > 0) { break; } } return null; } }
public class class_name { public static ArrayList<Trajectory> splitTrackInSubTracks(Trajectory t, int windowWidth, boolean overlapping){ int increment = 1; if(overlapping==false){ increment=windowWidth; } ArrayList<Trajectory> subTrajectories = new ArrayList<Trajectory>(); boolean trackEndReached = false; for(int i = 0; i < t.size(); i=i+increment) { int upperBound = i+(windowWidth); if(upperBound>t.size()){ upperBound=t.size(); trackEndReached=true; } Trajectory help = new Trajectory(2, i); for(int j = i; j < upperBound; j++){ help.add(t.get(j)); } subTrajectories.add(help); if(trackEndReached){ i=t.size(); } } return subTrajectories; } }
public class class_name { public static ArrayList<Trajectory> splitTrackInSubTracks(Trajectory t, int windowWidth, boolean overlapping){ int increment = 1; if(overlapping==false){ increment=windowWidth; // depends on control dependency: [if], data = [none] } ArrayList<Trajectory> subTrajectories = new ArrayList<Trajectory>(); boolean trackEndReached = false; for(int i = 0; i < t.size(); i=i+increment) { int upperBound = i+(windowWidth); if(upperBound>t.size()){ upperBound=t.size(); // depends on control dependency: [if], data = [none] trackEndReached=true; // depends on control dependency: [if], data = [none] } Trajectory help = new Trajectory(2, i); for(int j = i; j < upperBound; j++){ help.add(t.get(j)); // depends on control dependency: [for], data = [j] } subTrajectories.add(help); // depends on control dependency: [for], data = [none] if(trackEndReached){ i=t.size(); // depends on control dependency: [if], data = [none] } } return subTrajectories; } }
public class class_name { protected IConstructorLinkingCandidate getKnownConstructor(XConstructorCall constructorCall, AbstractTypeComputationState state, ResolvedTypes resolvedTypes) { IConstructorLinkingCandidate result = resolvedTypes.getConstructor(constructorCall); if (result != null) { return result; } EObject proxyOrResolved = (EObject) constructorCall.eGet(XbasePackage.Literals.XCONSTRUCTOR_CALL__CONSTRUCTOR, false); if (proxyOrResolved == null) { result = new NullConstructorLinkingCandidate(constructorCall, state); return result; } if (!proxyOrResolved.eIsProxy()) { result = state.createResolvedLink(constructorCall, (JvmConstructor) proxyOrResolved); return result; } if (!encoder.isCrossLinkFragment(constructorCall.eResource(), EcoreUtil.getURI(proxyOrResolved).fragment())) { JvmConstructor constructor = constructorCall.getConstructor(); if (!constructor.eIsProxy()) { return state.createResolvedLink(constructorCall, constructor); } } return null; } }
public class class_name { protected IConstructorLinkingCandidate getKnownConstructor(XConstructorCall constructorCall, AbstractTypeComputationState state, ResolvedTypes resolvedTypes) { IConstructorLinkingCandidate result = resolvedTypes.getConstructor(constructorCall); if (result != null) { return result; // depends on control dependency: [if], data = [none] } EObject proxyOrResolved = (EObject) constructorCall.eGet(XbasePackage.Literals.XCONSTRUCTOR_CALL__CONSTRUCTOR, false); if (proxyOrResolved == null) { result = new NullConstructorLinkingCandidate(constructorCall, state); // depends on control dependency: [if], data = [none] return result; // depends on control dependency: [if], data = [none] } if (!proxyOrResolved.eIsProxy()) { result = state.createResolvedLink(constructorCall, (JvmConstructor) proxyOrResolved); // depends on control dependency: [if], data = [none] return result; // depends on control dependency: [if], data = [none] } if (!encoder.isCrossLinkFragment(constructorCall.eResource(), EcoreUtil.getURI(proxyOrResolved).fragment())) { JvmConstructor constructor = constructorCall.getConstructor(); if (!constructor.eIsProxy()) { return state.createResolvedLink(constructorCall, constructor); // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { public ServiceCall<CounterexampleCollection> listCounterexamples( ListCounterexamplesOptions listCounterexamplesOptions) { Validator.notNull(listCounterexamplesOptions, "listCounterexamplesOptions cannot be null"); String[] pathSegments = { "v1/workspaces", "counterexamples" }; String[] pathParameters = { listCounterexamplesOptions.workspaceId() }; RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments, pathParameters)); builder.query("version", versionDate); Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("conversation", "v1", "listCounterexamples"); for (Entry<String, String> header : sdkHeaders.entrySet()) { builder.header(header.getKey(), header.getValue()); } builder.header("Accept", "application/json"); if (listCounterexamplesOptions.pageLimit() != null) { builder.query("page_limit", String.valueOf(listCounterexamplesOptions.pageLimit())); } if (listCounterexamplesOptions.includeCount() != null) { builder.query("include_count", String.valueOf(listCounterexamplesOptions.includeCount())); } if (listCounterexamplesOptions.sort() != null) { builder.query("sort", listCounterexamplesOptions.sort()); } if (listCounterexamplesOptions.cursor() != null) { builder.query("cursor", listCounterexamplesOptions.cursor()); } if (listCounterexamplesOptions.includeAudit() != null) { builder.query("include_audit", String.valueOf(listCounterexamplesOptions.includeAudit())); } return createServiceCall(builder.build(), ResponseConverterUtils.getObject(CounterexampleCollection.class)); } }
public class class_name { public ServiceCall<CounterexampleCollection> listCounterexamples( ListCounterexamplesOptions listCounterexamplesOptions) { Validator.notNull(listCounterexamplesOptions, "listCounterexamplesOptions cannot be null"); String[] pathSegments = { "v1/workspaces", "counterexamples" }; String[] pathParameters = { listCounterexamplesOptions.workspaceId() }; RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments, pathParameters)); builder.query("version", versionDate); Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("conversation", "v1", "listCounterexamples"); for (Entry<String, String> header : sdkHeaders.entrySet()) { builder.header(header.getKey(), header.getValue()); // depends on control dependency: [for], data = [header] } builder.header("Accept", "application/json"); if (listCounterexamplesOptions.pageLimit() != null) { builder.query("page_limit", String.valueOf(listCounterexamplesOptions.pageLimit())); // depends on control dependency: [if], data = [(listCounterexamplesOptions.pageLimit()] } if (listCounterexamplesOptions.includeCount() != null) { builder.query("include_count", String.valueOf(listCounterexamplesOptions.includeCount())); // depends on control dependency: [if], data = [(listCounterexamplesOptions.includeCount()] } if (listCounterexamplesOptions.sort() != null) { builder.query("sort", listCounterexamplesOptions.sort()); // depends on control dependency: [if], data = [none] } if (listCounterexamplesOptions.cursor() != null) { builder.query("cursor", listCounterexamplesOptions.cursor()); // depends on control dependency: [if], data = [none] } if (listCounterexamplesOptions.includeAudit() != null) { builder.query("include_audit", String.valueOf(listCounterexamplesOptions.includeAudit())); // depends on control dependency: [if], data = [(listCounterexamplesOptions.includeAudit()] } return createServiceCall(builder.build(), ResponseConverterUtils.getObject(CounterexampleCollection.class)); } }
public class class_name { public ItemList getItemList() { if (!atomics.containsKey(mRTX)) { atomics.put(mRTX, new ItemList()); } return atomics.get(mRTX); } }
public class class_name { public ItemList getItemList() { if (!atomics.containsKey(mRTX)) { atomics.put(mRTX, new ItemList()); // depends on control dependency: [if], data = [none] } return atomics.get(mRTX); } }
public class class_name { static IDataSet toDataSet(final DataSetDto dto) { IDataSet dataSet = new DataSet(dto.name); dataSet.setDataModelId(new DataModelId(dto.dataModelId)); for (List<Object> row : dto.table) { IDsRow dsrow = dataSet.addRow(); for (Object value : row) { dsrow.addCell().setValue(CellValue.from(value)); } } return dataSet; } }
public class class_name { static IDataSet toDataSet(final DataSetDto dto) { IDataSet dataSet = new DataSet(dto.name); dataSet.setDataModelId(new DataModelId(dto.dataModelId)); for (List<Object> row : dto.table) { IDsRow dsrow = dataSet.addRow(); for (Object value : row) { dsrow.addCell().setValue(CellValue.from(value)); // depends on control dependency: [for], data = [value] } } return dataSet; } }
public class class_name { private boolean sameKeys(KTypeSet<?> other) { if (other.size() != size()) { return false; } for (KTypeCursor<?> c : other) { if (!contains(Intrinsics.<KType> cast(c.value))) { return false; } } return true; } }
public class class_name { private boolean sameKeys(KTypeSet<?> other) { if (other.size() != size()) { return false; // depends on control dependency: [if], data = [none] } for (KTypeCursor<?> c : other) { if (!contains(Intrinsics.<KType> cast(c.value))) { return false; // depends on control dependency: [if], data = [none] } } return true; } }
public class class_name { private PortalSearchResults getPortalSearchResults(PortletRequest request, String queryId) { final PortletSession session = request.getPortletSession(); @SuppressWarnings("unchecked") final Cache<String, PortalSearchResults> searchResultsCache = (Cache<String, PortalSearchResults>) session.getAttribute(SEARCH_RESULTS_CACHE_NAME); if (searchResultsCache == null) { return null; } return searchResultsCache.getIfPresent(queryId); } }
public class class_name { private PortalSearchResults getPortalSearchResults(PortletRequest request, String queryId) { final PortletSession session = request.getPortletSession(); @SuppressWarnings("unchecked") final Cache<String, PortalSearchResults> searchResultsCache = (Cache<String, PortalSearchResults>) session.getAttribute(SEARCH_RESULTS_CACHE_NAME); if (searchResultsCache == null) { return null; // depends on control dependency: [if], data = [none] } return searchResultsCache.getIfPresent(queryId); } }
public class class_name { @Override public void sawOpcode(int seen) { int pc = 0; try { stack.precomputation(this); switch (state) { case SAW_NOTHING: pc = sawOpcodeAfterNothing(seen); break; case SAW_CTOR: if ((seen == Const.POP) || (seen == Const.RETURN)) { bugReporter.reportBug(new BugInstance(this, BugType.SEC_SIDE_EFFECT_CONSTRUCTOR.name(), NORMAL_PRIORITY).addClass(this).addMethod(this) .addSourceLine(this)); } state = State.SAW_NOTHING; break; } } finally { TernaryPatcher.pre(stack, seen); stack.sawOpcode(this, seen); TernaryPatcher.post(stack, seen); if ((pc != 0) && (stack.getStackDepth() > 0)) { OpcodeStack.Item item = stack.getStackItem(0); item.setUserValue(Integer.valueOf(pc)); } } } }
public class class_name { @Override public void sawOpcode(int seen) { int pc = 0; try { stack.precomputation(this); // depends on control dependency: [try], data = [none] switch (state) { case SAW_NOTHING: pc = sawOpcodeAfterNothing(seen); break; case SAW_CTOR: if ((seen == Const.POP) || (seen == Const.RETURN)) { bugReporter.reportBug(new BugInstance(this, BugType.SEC_SIDE_EFFECT_CONSTRUCTOR.name(), NORMAL_PRIORITY).addClass(this).addMethod(this) .addSourceLine(this)); // depends on control dependency: [if], data = [none] } state = State.SAW_NOTHING; break; } } finally { TernaryPatcher.pre(stack, seen); stack.sawOpcode(this, seen); TernaryPatcher.post(stack, seen); if ((pc != 0) && (stack.getStackDepth() > 0)) { OpcodeStack.Item item = stack.getStackItem(0); item.setUserValue(Integer.valueOf(pc)); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public static void setText(EfficientCacheView cacheView, int viewId, CharSequence text) { View view = cacheView.findViewByIdEfficient(viewId); if (view instanceof TextView) { ((TextView) view).setText(text); } } }
public class class_name { public static void setText(EfficientCacheView cacheView, int viewId, CharSequence text) { View view = cacheView.findViewByIdEfficient(viewId); if (view instanceof TextView) { ((TextView) view).setText(text); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void initStack() { if (log.isInfoEnabled()) { log.info("Initializing Stack..."); } InputStream is = null; try { //Parse dictionary, it is used for user friendly info. dictionary.parseDictionary(this.getClass().getClassLoader().getResourceAsStream(dictionaryFile)); log.info("AVP Dictionary successfully parsed."); this.stack = new StackImpl(); //Parse stack configuration is = this.getClass().getClassLoader().getResourceAsStream(configFile); Configuration config = new XMLConfiguration(is); factory = stack.init(config); if (log.isInfoEnabled()) { log.info("Stack Configuration successfully loaded."); } //Print info about applicatio Set<org.jdiameter.api.ApplicationId> appIds = stack.getMetaData().getLocalPeer().getCommonApplications(); log.info("Diameter Stack :: Supporting " + appIds.size() + " applications."); for (org.jdiameter.api.ApplicationId x : appIds) { log.info("Diameter Stack :: Common :: " + x); } is.close(); //Register network req listener, even though we wont receive requests //this has to be done to inform stack that we support application Network network = stack.unwrap(Network.class); network.addNetworkReqListener(new NetworkReqListener() { @Override public Answer processRequest(Request request) { //this wontbe called. return null; } }, this.authAppId); //passing our example app id. } catch (Exception e) { e.printStackTrace(); if (this.stack != null) { this.stack.destroy(); } if (is != null) { try { is.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } return; } MetaData metaData = stack.getMetaData(); //ignore for now. if (metaData.getStackType() != StackType.TYPE_SERVER || metaData.getMinorVersion() <= 0) { stack.destroy(); if (log.isEnabledFor(org.apache.log4j.Level.ERROR)) { log.error("Incorrect driver"); } return; } try { if (log.isInfoEnabled()) { log.info("Starting stack"); } stack.start(); if (log.isInfoEnabled()) { log.info("Stack is running."); } } catch (Exception e) { e.printStackTrace(); stack.destroy(); return; } if (log.isInfoEnabled()) { log.info("Stack initialization successfully completed."); } } }
public class class_name { private void initStack() { if (log.isInfoEnabled()) { log.info("Initializing Stack..."); // depends on control dependency: [if], data = [none] } InputStream is = null; try { //Parse dictionary, it is used for user friendly info. dictionary.parseDictionary(this.getClass().getClassLoader().getResourceAsStream(dictionaryFile)); // depends on control dependency: [try], data = [none] log.info("AVP Dictionary successfully parsed."); // depends on control dependency: [try], data = [none] this.stack = new StackImpl(); // depends on control dependency: [try], data = [none] //Parse stack configuration is = this.getClass().getClassLoader().getResourceAsStream(configFile); // depends on control dependency: [try], data = [none] Configuration config = new XMLConfiguration(is); factory = stack.init(config); // depends on control dependency: [try], data = [none] if (log.isInfoEnabled()) { log.info("Stack Configuration successfully loaded."); // depends on control dependency: [if], data = [none] } //Print info about applicatio Set<org.jdiameter.api.ApplicationId> appIds = stack.getMetaData().getLocalPeer().getCommonApplications(); log.info("Diameter Stack :: Supporting " + appIds.size() + " applications."); // depends on control dependency: [try], data = [none] for (org.jdiameter.api.ApplicationId x : appIds) { log.info("Diameter Stack :: Common :: " + x); // depends on control dependency: [for], data = [x] } is.close(); // depends on control dependency: [try], data = [none] //Register network req listener, even though we wont receive requests //this has to be done to inform stack that we support application Network network = stack.unwrap(Network.class); network.addNetworkReqListener(new NetworkReqListener() { @Override public Answer processRequest(Request request) { //this wontbe called. return null; } }, this.authAppId); //passing our example app id. // depends on control dependency: [try], data = [none] } catch (Exception e) { e.printStackTrace(); if (this.stack != null) { this.stack.destroy(); // depends on control dependency: [if], data = [none] } if (is != null) { try { is.close(); // depends on control dependency: [try], data = [none] } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // depends on control dependency: [catch], data = [none] } return; } // depends on control dependency: [catch], data = [none] MetaData metaData = stack.getMetaData(); //ignore for now. if (metaData.getStackType() != StackType.TYPE_SERVER || metaData.getMinorVersion() <= 0) { stack.destroy(); // depends on control dependency: [if], data = [none] if (log.isEnabledFor(org.apache.log4j.Level.ERROR)) { log.error("Incorrect driver"); // depends on control dependency: [if], data = [none] } return; // depends on control dependency: [if], data = [none] } try { if (log.isInfoEnabled()) { log.info("Starting stack"); // depends on control dependency: [if], data = [none] } stack.start(); // depends on control dependency: [try], data = [none] if (log.isInfoEnabled()) { log.info("Stack is running."); // depends on control dependency: [if], data = [none] } } catch (Exception e) { e.printStackTrace(); stack.destroy(); return; } // depends on control dependency: [catch], data = [none] if (log.isInfoEnabled()) { log.info("Stack initialization successfully completed."); // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override public ConcurrentMap<String, Object> deserializeAttributes(final byte[] in ) { if ( LOG.isDebugEnabled() ) { LOG.debug( "Reading serialized data:\n" + new String( in ) ); } return doDeserialize( in, "attributes" ); } }
public class class_name { @Override public ConcurrentMap<String, Object> deserializeAttributes(final byte[] in ) { if ( LOG.isDebugEnabled() ) { LOG.debug( "Reading serialized data:\n" + new String( in ) ); // depends on control dependency: [if], data = [none] } return doDeserialize( in, "attributes" ); } }
public class class_name { public void meanShiftLocation( ChessboardCorner c ) { float meanX = (float)c.x; float meanY = (float)c.y; // The peak in intensity will be in -r to r region, but smaller values will be -2*r to 2*r int radius = this.shiRadius*2; for (int iteration = 0; iteration < 5; iteration++) { float adjX = 0; float adjY = 0; float total = 0; for (int y = -radius; y < radius; y++) { float yy = y; for (int x = -radius; x < radius; x++) { float xx = x; float v = intensityInterp.get(meanX+xx,meanY+yy); // Again, this adjustment to account for how pixels are counted. See center from contour computation adjX += (xx+0.5)*v; adjY += (yy+0.5)*v; total += v; } } meanX += adjX/total; meanY += adjY/total; } c.x = meanX; c.y = meanY; } }
public class class_name { public void meanShiftLocation( ChessboardCorner c ) { float meanX = (float)c.x; float meanY = (float)c.y; // The peak in intensity will be in -r to r region, but smaller values will be -2*r to 2*r int radius = this.shiRadius*2; for (int iteration = 0; iteration < 5; iteration++) { float adjX = 0; float adjY = 0; float total = 0; for (int y = -radius; y < radius; y++) { float yy = y; for (int x = -radius; x < radius; x++) { float xx = x; float v = intensityInterp.get(meanX+xx,meanY+yy); // Again, this adjustment to account for how pixels are counted. See center from contour computation adjX += (xx+0.5)*v; // depends on control dependency: [for], data = [none] adjY += (yy+0.5)*v; // depends on control dependency: [for], data = [none] total += v; // depends on control dependency: [for], data = [none] } } meanX += adjX/total; // depends on control dependency: [for], data = [none] meanY += adjY/total; // depends on control dependency: [for], data = [none] } c.x = meanX; c.y = meanY; } }
public class class_name { public org.inferred.freebuilder.processor.property.Property.Builder clearAccessorAnnotations() { if (accessorAnnotations instanceof ImmutableList) { accessorAnnotations = ImmutableList.of(); } else { accessorAnnotations.clear(); } return (org.inferred.freebuilder.processor.property.Property.Builder) this; } }
public class class_name { public org.inferred.freebuilder.processor.property.Property.Builder clearAccessorAnnotations() { if (accessorAnnotations instanceof ImmutableList) { accessorAnnotations = ImmutableList.of(); // depends on control dependency: [if], data = [none] } else { accessorAnnotations.clear(); // depends on control dependency: [if], data = [none] } return (org.inferred.freebuilder.processor.property.Property.Builder) this; } }
public class class_name { public static String getHash(final String password, final String salt) { if (StringUtils.isEmpty(salt)) { return getSimpleHash(password); } return DigestUtils.sha512Hex(DigestUtils.sha512Hex(password).concat(salt)); } }
public class class_name { public static String getHash(final String password, final String salt) { if (StringUtils.isEmpty(salt)) { return getSimpleHash(password); // depends on control dependency: [if], data = [none] } return DigestUtils.sha512Hex(DigestUtils.sha512Hex(password).concat(salt)); } }
public class class_name { public void update (T value) { // store our new current value _value = value; // notify our listeners; we snapshot our listeners before iterating to avoid problems if // listeners add or remove themselves while we're dispatching this notification for (Listener<T> listener : new ArrayList<Listener<T>>(_listeners)) { listener.valueChanged(value); } } }
public class class_name { public void update (T value) { // store our new current value _value = value; // notify our listeners; we snapshot our listeners before iterating to avoid problems if // listeners add or remove themselves while we're dispatching this notification for (Listener<T> listener : new ArrayList<Listener<T>>(_listeners)) { listener.valueChanged(value); // depends on control dependency: [for], data = [listener] } } }
public class class_name { public int getNumberWaiting() { final ReentrantLock lock = this.lock; lock.lock(); try { return parties - count; } finally { lock.unlock(); } } }
public class class_name { public int getNumberWaiting() { final ReentrantLock lock = this.lock; lock.lock(); try { return parties - count; // depends on control dependency: [try], data = [none] } finally { lock.unlock(); } } }
public class class_name { public void marshall(DeliveryOptions deliveryOptions, ProtocolMarshaller protocolMarshaller) { if (deliveryOptions == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deliveryOptions.getSendingPoolName(), SENDINGPOOLNAME_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(DeliveryOptions deliveryOptions, ProtocolMarshaller protocolMarshaller) { if (deliveryOptions == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deliveryOptions.getSendingPoolName(), SENDINGPOOLNAME_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static GVRTexture loadFutureCubemapTexture( GVRContext gvrContext, ResourceCache<GVRImage> textureCache, GVRAndroidResource resource, int priority, Map<String, Integer> faceIndexMap) { GVRTexture tex = new GVRTexture(gvrContext); GVRImage cached = textureCache.get(resource); if (cached != null) { Log.v("ASSET", "Future Texture: %s loaded from cache", cached.getFileName()); tex.setImage(cached); } else { AsyncCubemapTexture.get().loadTexture(gvrContext, CancelableCallbackWrapper.wrap(GVRCubemapImage.class, tex), resource, priority, faceIndexMap); } return tex; } }
public class class_name { public static GVRTexture loadFutureCubemapTexture( GVRContext gvrContext, ResourceCache<GVRImage> textureCache, GVRAndroidResource resource, int priority, Map<String, Integer> faceIndexMap) { GVRTexture tex = new GVRTexture(gvrContext); GVRImage cached = textureCache.get(resource); if (cached != null) { Log.v("ASSET", "Future Texture: %s loaded from cache", cached.getFileName()); // depends on control dependency: [if], data = [none] tex.setImage(cached); // depends on control dependency: [if], data = [(cached] } else { AsyncCubemapTexture.get().loadTexture(gvrContext, CancelableCallbackWrapper.wrap(GVRCubemapImage.class, tex), resource, priority, faceIndexMap); // depends on control dependency: [if], data = [none] } return tex; } }
public class class_name { public void afterDistribute(RunReportHistory history, DistributionContext context) { for (String username : users) { try { context.getSecurityService().grantUser(history.getPath(), username, PermissionUtil.getRead(), false); } catch (Exception e) { LOG.error(e.getMessage(), e); } } } }
public class class_name { public void afterDistribute(RunReportHistory history, DistributionContext context) { for (String username : users) { try { context.getSecurityService().grantUser(history.getPath(), username, PermissionUtil.getRead(), false); // depends on control dependency: [try], data = [none] } catch (Exception e) { LOG.error(e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { @Override public void removeByUuid(String uuid) { for (CPSpecificationOption cpSpecificationOption : findByUuid(uuid, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(cpSpecificationOption); } } }
public class class_name { @Override public void removeByUuid(String uuid) { for (CPSpecificationOption cpSpecificationOption : findByUuid(uuid, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(cpSpecificationOption); // depends on control dependency: [for], data = [cpSpecificationOption] } } }
public class class_name { protected boolean parseLine(final ParserData parserData, final String line, int lineNumber) throws IndentationException { assert line != null; // Trim the whitespace final String trimmedLine = line.trim(); // If the line is a blank or a comment, then nothing needs processing. So add the line and return if (isBlankLine(trimmedLine) || isCommentLine(trimmedLine)) { return parseEmptyOrCommentLine(parserData, line); } else { // Calculate the lines indentation level int lineIndentationLevel = calculateLineIndentationLevel(parserData, line, lineNumber); if (lineIndentationLevel > parserData.getIndentationLevel()) { // The line was indented without a new level so throw an error throw new IndentationException(format(ProcessorConstants.ERROR_INCORRECT_INDENTATION_MSG, lineNumber, trimmedLine)); } else if (lineIndentationLevel < parserData.getIndentationLevel()) { // The line has left the previous level so move the current level up to the right level Level newCurrentLevel = parserData.getCurrentLevel(); for (int i = (parserData.getIndentationLevel() - lineIndentationLevel); i > 0; i--) { if (newCurrentLevel.getParent() != null) { newCurrentLevel = newCurrentLevel.getParent(); } } changeCurrentLevel(parserData, newCurrentLevel, lineIndentationLevel); } // Process the line based on what type the line is try { if (isMetaDataLine(parserData, trimmedLine)) { parseMetaDataLine(parserData, line, lineNumber); } else if (isCommonContentLine(trimmedLine)) { final CommonContent commonContent = parseCommonContentLine(parserData, line, lineNumber); parserData.getCurrentLevel().appendChild(commonContent); } else if (isLevelInitialContentLine(trimmedLine)) { final Level initialContent = parseLevelLine(parserData, trimmedLine, lineNumber); parserData.getCurrentLevel().appendChild(initialContent); // Change the current level to use the new parsed level changeCurrentLevel(parserData, initialContent, parserData.getIndentationLevel() + 1); } else if (isLevelLine(trimmedLine)) { final Level level = parseLevelLine(parserData, trimmedLine, lineNumber); if (level instanceof Process) { parserData.getProcesses().add((Process) level); } parserData.getCurrentLevel().appendChild(level); // Change the current level to use the new parsed level changeCurrentLevel(parserData, level, parserData.getIndentationLevel() + 1); // } else if (trimmedLine.toUpperCase(Locale.ENGLISH).matches("^CS[ ]*:.*")) { // processExternalLevelLine(getCurrentLevel(), line); } else if (StringUtilities.indexOf(trimmedLine, '[') == 0 && parserData.getCurrentLevel().getLevelType() == LevelType.BASE) { parseGlobalOptionsLine(parserData, line, lineNumber); } else { // Process a new topic final SpecTopic tempTopic = parseTopic(parserData, trimmedLine, lineNumber); // Adds the topic to the current level parserData.getCurrentLevel().appendSpecTopic(tempTopic); } } catch (ParsingException e) { log.error(e.getMessage()); return false; } return true; } } }
public class class_name { protected boolean parseLine(final ParserData parserData, final String line, int lineNumber) throws IndentationException { assert line != null; // Trim the whitespace final String trimmedLine = line.trim(); // If the line is a blank or a comment, then nothing needs processing. So add the line and return if (isBlankLine(trimmedLine) || isCommentLine(trimmedLine)) { return parseEmptyOrCommentLine(parserData, line); } else { // Calculate the lines indentation level int lineIndentationLevel = calculateLineIndentationLevel(parserData, line, lineNumber); if (lineIndentationLevel > parserData.getIndentationLevel()) { // The line was indented without a new level so throw an error throw new IndentationException(format(ProcessorConstants.ERROR_INCORRECT_INDENTATION_MSG, lineNumber, trimmedLine)); } else if (lineIndentationLevel < parserData.getIndentationLevel()) { // The line has left the previous level so move the current level up to the right level Level newCurrentLevel = parserData.getCurrentLevel(); for (int i = (parserData.getIndentationLevel() - lineIndentationLevel); i > 0; i--) { if (newCurrentLevel.getParent() != null) { newCurrentLevel = newCurrentLevel.getParent(); // depends on control dependency: [if], data = [none] } } changeCurrentLevel(parserData, newCurrentLevel, lineIndentationLevel); // depends on control dependency: [if], data = [none] } // Process the line based on what type the line is try { if (isMetaDataLine(parserData, trimmedLine)) { parseMetaDataLine(parserData, line, lineNumber); // depends on control dependency: [if], data = [none] } else if (isCommonContentLine(trimmedLine)) { final CommonContent commonContent = parseCommonContentLine(parserData, line, lineNumber); parserData.getCurrentLevel().appendChild(commonContent); // depends on control dependency: [if], data = [none] } else if (isLevelInitialContentLine(trimmedLine)) { final Level initialContent = parseLevelLine(parserData, trimmedLine, lineNumber); parserData.getCurrentLevel().appendChild(initialContent); // depends on control dependency: [if], data = [none] // Change the current level to use the new parsed level changeCurrentLevel(parserData, initialContent, parserData.getIndentationLevel() + 1); // depends on control dependency: [if], data = [none] } else if (isLevelLine(trimmedLine)) { final Level level = parseLevelLine(parserData, trimmedLine, lineNumber); if (level instanceof Process) { parserData.getProcesses().add((Process) level); // depends on control dependency: [if], data = [none] } parserData.getCurrentLevel().appendChild(level); // depends on control dependency: [if], data = [none] // Change the current level to use the new parsed level changeCurrentLevel(parserData, level, parserData.getIndentationLevel() + 1); // depends on control dependency: [if], data = [none] // } else if (trimmedLine.toUpperCase(Locale.ENGLISH).matches("^CS[ ]*:.*")) { // processExternalLevelLine(getCurrentLevel(), line); } else if (StringUtilities.indexOf(trimmedLine, '[') == 0 && parserData.getCurrentLevel().getLevelType() == LevelType.BASE) { parseGlobalOptionsLine(parserData, line, lineNumber); // depends on control dependency: [if], data = [none] } else { // Process a new topic final SpecTopic tempTopic = parseTopic(parserData, trimmedLine, lineNumber); // Adds the topic to the current level parserData.getCurrentLevel().appendSpecTopic(tempTopic); // depends on control dependency: [if], data = [none] } } catch (ParsingException e) { log.error(e.getMessage()); return false; } // depends on control dependency: [catch], data = [none] return true; } } }
public class class_name { public String getThreadDump(int depth, boolean onlyActive) { ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); long []ids = threadBean.getAllThreadIds(); ThreadInfo []info = threadBean.getThreadInfo(ids, depth); StringBuilder sb = new StringBuilder(); sb.append("Thread Dump generated " + new Date(CurrentTime.currentTime())); Arrays.sort(info, new ThreadCompare()); buildThreads(sb, info, Thread.State.RUNNABLE, false); buildThreads(sb, info, Thread.State.RUNNABLE, true); if (! onlyActive) { buildThreads(sb, info, Thread.State.BLOCKED, false); buildThreads(sb, info, Thread.State.WAITING, false); buildThreads(sb, info, Thread.State.TIMED_WAITING, false); buildThreads(sb, info, null, false); } return sb.toString(); } }
public class class_name { public String getThreadDump(int depth, boolean onlyActive) { ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); long []ids = threadBean.getAllThreadIds(); ThreadInfo []info = threadBean.getThreadInfo(ids, depth); StringBuilder sb = new StringBuilder(); sb.append("Thread Dump generated " + new Date(CurrentTime.currentTime())); Arrays.sort(info, new ThreadCompare()); buildThreads(sb, info, Thread.State.RUNNABLE, false); buildThreads(sb, info, Thread.State.RUNNABLE, true); if (! onlyActive) { buildThreads(sb, info, Thread.State.BLOCKED, false); // depends on control dependency: [if], data = [none] buildThreads(sb, info, Thread.State.WAITING, false); // depends on control dependency: [if], data = [none] buildThreads(sb, info, Thread.State.TIMED_WAITING, false); // depends on control dependency: [if], data = [none] buildThreads(sb, info, null, false); // depends on control dependency: [if], data = [none] } return sb.toString(); } }
public class class_name { public static <T> VicariousThreadLocal<T> newThreadLocal(final java.util.concurrent.Callable<T> doCall) { return new VicariousThreadLocal<T>() { @Override public T initialValue() { try { return doCall.call(); } catch (RuntimeException exc) { throw exc; } catch (Exception exc) { throw new Error(exc); } } }; } }
public class class_name { public static <T> VicariousThreadLocal<T> newThreadLocal(final java.util.concurrent.Callable<T> doCall) { return new VicariousThreadLocal<T>() { @Override public T initialValue() { try { return doCall.call(); // depends on control dependency: [try], data = [none] } catch (RuntimeException exc) { throw exc; } catch (Exception exc) { // depends on control dependency: [catch], data = [none] throw new Error(exc); } // depends on control dependency: [catch], data = [none] } }; } }
public class class_name { public Map<String, String> findMatches(String incoming) { String[] pieces = incoming.split(PATH_SEPARATOR); int i = 0; //too many matchers, short circuit if (path.size() > pieces.length) return null; Map<String, String> values = new HashMap<String, String>(); for (PathMatcher pathMatcher : path) { //sanity to prevent fencepost if (i == pieces.length) return pathMatcher.matches("") ? values : null; //go greedy on index paths String piece = pieces[i]; if (!pathMatcher.matches(piece)) return null; //store variable as needed final String name = pathMatcher.name(); if (null != name) values.put(name, piece); //next piece i++; } return (i == pieces.length) ? values : null; } }
public class class_name { public Map<String, String> findMatches(String incoming) { String[] pieces = incoming.split(PATH_SEPARATOR); int i = 0; //too many matchers, short circuit if (path.size() > pieces.length) return null; Map<String, String> values = new HashMap<String, String>(); for (PathMatcher pathMatcher : path) { //sanity to prevent fencepost if (i == pieces.length) return pathMatcher.matches("") ? values : null; //go greedy on index paths String piece = pieces[i]; if (!pathMatcher.matches(piece)) return null; //store variable as needed final String name = pathMatcher.name(); if (null != name) values.put(name, piece); //next piece i++; // depends on control dependency: [for], data = [none] } return (i == pieces.length) ? values : null; } }
public class class_name { public static void sleep(final TimeUnit timeUnit, final long units){ try{ timeUnit.sleep(units); }catch(final InterruptedException ignored){ ignore(ignored); } } }
public class class_name { public static void sleep(final TimeUnit timeUnit, final long units){ try{ timeUnit.sleep(units); // depends on control dependency: [try], data = [none] }catch(final InterruptedException ignored){ ignore(ignored); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private String getRowLineBuf(int colCount, List<Integer> colMaxLenList, String[][] data) { StringBuilder rowBuilder = new StringBuilder(); int colWidth = 0; for (int i = 0; i < colCount; i++) { colWidth = colMaxLenList.get(i) + 3; for (int j = 0; j < colWidth; j++) { if (j == 0) { rowBuilder.append("+"); } else if ((i + 1 == colCount && j + 1 == colWidth)) {//for last column close the border rowBuilder.append("-+"); } else { rowBuilder.append("-"); } } } return rowBuilder.append("\n").toString(); } }
public class class_name { private String getRowLineBuf(int colCount, List<Integer> colMaxLenList, String[][] data) { StringBuilder rowBuilder = new StringBuilder(); int colWidth = 0; for (int i = 0; i < colCount; i++) { colWidth = colMaxLenList.get(i) + 3; // depends on control dependency: [for], data = [i] for (int j = 0; j < colWidth; j++) { if (j == 0) { rowBuilder.append("+"); // depends on control dependency: [if], data = [none] } else if ((i + 1 == colCount && j + 1 == colWidth)) {//for last column close the border rowBuilder.append("-+"); // depends on control dependency: [if], data = [none] } else { rowBuilder.append("-"); // depends on control dependency: [if], data = [none] } } } return rowBuilder.append("\n").toString(); } }
public class class_name { private static long pickTTLMillis(long operationTTLMillis, long existingTTLMillis, MapConfig mapConfig, boolean consultMapConfig) { // if user set operationTTLMillis when calling operation, use it if (operationTTLMillis > 0) { return checkedTime(operationTTLMillis); } // if this is the first creation of entry, try to get TTL from mapConfig if (consultMapConfig && operationTTLMillis < 0 && mapConfig.getTimeToLiveSeconds() > 0) { return checkedTime(SECONDS.toMillis(mapConfig.getTimeToLiveSeconds())); } // if operationTTLMillis < 0, keep previously set TTL on record if (operationTTLMillis < 0) { return checkedTime(existingTTLMillis); } // if we are here, entry should live forever return Long.MAX_VALUE; } }
public class class_name { private static long pickTTLMillis(long operationTTLMillis, long existingTTLMillis, MapConfig mapConfig, boolean consultMapConfig) { // if user set operationTTLMillis when calling operation, use it if (operationTTLMillis > 0) { return checkedTime(operationTTLMillis); // depends on control dependency: [if], data = [(operationTTLMillis] } // if this is the first creation of entry, try to get TTL from mapConfig if (consultMapConfig && operationTTLMillis < 0 && mapConfig.getTimeToLiveSeconds() > 0) { return checkedTime(SECONDS.toMillis(mapConfig.getTimeToLiveSeconds())); // depends on control dependency: [if], data = [none] } // if operationTTLMillis < 0, keep previously set TTL on record if (operationTTLMillis < 0) { return checkedTime(existingTTLMillis); // depends on control dependency: [if], data = [none] } // if we are here, entry should live forever return Long.MAX_VALUE; } }
public class class_name { static Optional<ACLHandle> getEffectiveAcl(final FedoraResource resource, final boolean ancestorAcl, final SessionFactory sessionFactory) { try { final FedoraResource aclResource = resource.getAcl(); if (aclResource != null) { final List<WebACAuthorization> authorizations = getAuthorizations(aclResource, ancestorAcl, sessionFactory); if (authorizations.size() > 0) { return Optional.of( new ACLHandle(resource, authorizations)); } } if (getJcrNode(resource).getDepth() == 0) { LOGGER.debug("No ACLs defined on this node or in parent hierarchy"); return Optional.empty(); } else { LOGGER.trace("Checking parent resource for ACL. No ACL found at {}", resource.getPath()); return getEffectiveAcl(resource.getContainer(), true, sessionFactory); } } catch (final RepositoryException ex) { LOGGER.debug("Exception finding effective ACL: {}", ex.getMessage()); return Optional.empty(); } } }
public class class_name { static Optional<ACLHandle> getEffectiveAcl(final FedoraResource resource, final boolean ancestorAcl, final SessionFactory sessionFactory) { try { final FedoraResource aclResource = resource.getAcl(); if (aclResource != null) { final List<WebACAuthorization> authorizations = getAuthorizations(aclResource, ancestorAcl, sessionFactory); if (authorizations.size() > 0) { return Optional.of( new ACLHandle(resource, authorizations)); // depends on control dependency: [if], data = [none] } } if (getJcrNode(resource).getDepth() == 0) { LOGGER.debug("No ACLs defined on this node or in parent hierarchy"); return Optional.empty(); } else { LOGGER.trace("Checking parent resource for ACL. No ACL found at {}", resource.getPath()); return getEffectiveAcl(resource.getContainer(), true, sessionFactory); } } catch (final RepositoryException ex) { LOGGER.debug("Exception finding effective ACL: {}", ex.getMessage()); return Optional.empty(); } } }
public class class_name { private static int getNumberOfInserts(String messageKey) { String unInsertedMessage = nls.getString(messageKey); int numInserts = 0; // Not much point in going any further than 20 inserts! for (int i = 0; i < 20; i++) { if (unInsertedMessage.indexOf("{" + i + "}") != -1) { numInserts++; } else { // This message insert was not found break; } } return numInserts; } }
public class class_name { private static int getNumberOfInserts(String messageKey) { String unInsertedMessage = nls.getString(messageKey); int numInserts = 0; // Not much point in going any further than 20 inserts! for (int i = 0; i < 20; i++) { if (unInsertedMessage.indexOf("{" + i + "}") != -1) { numInserts++; // depends on control dependency: [if], data = [none] } else { // This message insert was not found break; } } return numInserts; } }
public class class_name { public static String printToString(Message message) { try { StringBuilder text = new StringBuilder(); print(message, text); return text.toString(); } catch (IOException e) { throw new RuntimeException("Writing to a StringBuilder threw an IOException (should never " + "happen).", e); } } }
public class class_name { public static String printToString(Message message) { try { StringBuilder text = new StringBuilder(); print(message, text); // depends on control dependency: [try], data = [none] return text.toString(); // depends on control dependency: [try], data = [none] } catch (IOException e) { throw new RuntimeException("Writing to a StringBuilder threw an IOException (should never " + "happen).", e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void setMemberAccounts(java.util.Collection<MemberAccount> memberAccounts) { if (memberAccounts == null) { this.memberAccounts = null; return; } this.memberAccounts = new java.util.ArrayList<MemberAccount>(memberAccounts); } }
public class class_name { public void setMemberAccounts(java.util.Collection<MemberAccount> memberAccounts) { if (memberAccounts == null) { this.memberAccounts = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.memberAccounts = new java.util.ArrayList<MemberAccount>(memberAccounts); } }
public class class_name { protected void addDescription(MemberDoc member, Content dlTree, SearchIndexItem si) { String name = (member instanceof ExecutableMemberDoc)? member.name() + ((ExecutableMemberDoc)member).flatSignature() : member.name(); si.setContainingPackage(utils.getPackageName((member.containingClass()).containingPackage())); si.setContainingClass((member.containingClass()).typeName()); if (member instanceof ExecutableMemberDoc) { ExecutableMemberDoc emd = (ExecutableMemberDoc)member; si.setLabel(member.name() + emd.flatSignature()); if (!((emd.signature()).equals(emd.flatSignature()))) { si.setUrl(getName(getAnchor((ExecutableMemberDoc) member))); } } else { si.setLabel(member.name()); } si.setCategory(getResource("doclet.Members").toString()); Content span = HtmlTree.SPAN(HtmlStyle.memberNameLink, getDocLink(LinkInfoImpl.Kind.INDEX, member, name)); Content dt = HtmlTree.DT(span); dt.addContent(" - "); addMemberDesc(member, dt); dlTree.addContent(dt); Content dd = new HtmlTree(HtmlTag.DD); addComment(member, dd); dlTree.addContent(dd); } }
public class class_name { protected void addDescription(MemberDoc member, Content dlTree, SearchIndexItem si) { String name = (member instanceof ExecutableMemberDoc)? member.name() + ((ExecutableMemberDoc)member).flatSignature() : member.name(); si.setContainingPackage(utils.getPackageName((member.containingClass()).containingPackage())); si.setContainingClass((member.containingClass()).typeName()); if (member instanceof ExecutableMemberDoc) { ExecutableMemberDoc emd = (ExecutableMemberDoc)member; si.setLabel(member.name() + emd.flatSignature()); // depends on control dependency: [if], data = [none] if (!((emd.signature()).equals(emd.flatSignature()))) { si.setUrl(getName(getAnchor((ExecutableMemberDoc) member))); // depends on control dependency: [if], data = [none] } } else { si.setLabel(member.name()); // depends on control dependency: [if], data = [none] } si.setCategory(getResource("doclet.Members").toString()); Content span = HtmlTree.SPAN(HtmlStyle.memberNameLink, getDocLink(LinkInfoImpl.Kind.INDEX, member, name)); Content dt = HtmlTree.DT(span); dt.addContent(" - "); addMemberDesc(member, dt); dlTree.addContent(dt); Content dd = new HtmlTree(HtmlTag.DD); addComment(member, dd); dlTree.addContent(dd); } }
public class class_name { protected String embeddedIconsInConsole(String iconRef, String prefix) { if (iconRef == null) { return null; } if (iconRef.startsWith("icons/")) { iconRef = iconRef.substring(6); } // special for fabric8 as its in a different dir if (iconRef.contains("META-INF/fabric8")) { return "img/fabric8_icon.svg"; } if (iconRef.contains("activemq")) { return prefix + "activemq.svg"; } else if (iconRef.contains("apiman")) { return prefix + "apiman.png"; } else if (iconRef.contains("api-registry")) { return prefix + "api-registry.svg"; } else if (iconRef.contains("brackets")) { return prefix + "brackets.svg"; } else if (iconRef.contains("camel")) { return prefix + "camel.svg"; } else if (iconRef.contains("chaos-monkey")) { return prefix + "chaos-monkey.png"; } else if (iconRef.contains("docker-registry")) { return prefix + "docker-registry.png"; } else if (iconRef.contains("elasticsearch")) { return prefix + "elasticsearch.png"; } else if (iconRef.contains("fluentd")) { return prefix + "fluentd.png"; } else if (iconRef.contains("forge")) { return prefix + "forge.svg"; } else if (iconRef.contains("funktion")) { return prefix + "funktion.png"; } else if (iconRef.contains("gerrit")) { return prefix + "gerrit.png"; } else if (iconRef.contains("gitlab")) { return prefix + "gitlab.svg"; } else if (iconRef.contains("gogs")) { return prefix + "gogs.png"; } else if (iconRef.contains("grafana")) { return prefix + "grafana.png"; } else if (iconRef.contains("hubot-irc")) { return prefix + "hubot-irc.png"; } else if (iconRef.contains("hubot-letschat")) { return prefix + "hubot-letschat.png"; } else if (iconRef.contains("hubot-notifier")) { return prefix + "hubot-notifier.png"; } else if (iconRef.contains("hubot-slack")) { return prefix + "hubot-slack.png"; } else if (iconRef.contains("image-linker")) { return prefix + "image-linker.svg"; } else if (iconRef.contains("javascript")) { return prefix + "javascript.png"; } else if (iconRef.contains("java")) { return prefix + "java.svg"; } else if (iconRef.contains("jenkins")) { return prefix + "jenkins.svg"; } else if (iconRef.contains("jetty")) { return prefix + "jetty.svg"; } else if (iconRef.contains("karaf")) { return prefix + "karaf.svg"; } else if (iconRef.contains("keycloak")) { return prefix + "keycloak.svg"; } else if (iconRef.contains("kibana")) { return prefix + "kibana.svg"; } else if (iconRef.contains("kiwiirc")) { return prefix + "kiwiirc.png"; } else if (iconRef.contains("letschat")) { return prefix + "letschat.png"; } else if (iconRef.contains("mule")) { return prefix + "mule.svg"; } else if (iconRef.contains("nexus")) { return prefix + "nexus.png"; } else if (iconRef.contains("node")) { return prefix + "node.svg"; } else if (iconRef.contains("orion")) { return prefix + "orion.png"; } else if (iconRef.contains("prometheus")) { return prefix + "prometheus.png"; } else if (iconRef.contains("django") || iconRef.contains("python")) { return prefix + "python.png"; } else if (iconRef.contains("spring-boot")) { return prefix + "spring-boot.svg"; } else if (iconRef.contains("taiga")) { return prefix + "taiga.png"; } else if (iconRef.contains("tomcat")) { return prefix + "tomcat.svg"; } else if (iconRef.contains("tomee")) { return prefix + "tomee.svg"; } else if (iconRef.contains("vertx")) { return prefix + "vertx.svg"; } else if (iconRef.contains("wildfly")) { return prefix + "wildfly.svg"; } else if (iconRef.contains("wildfly-swarm")) { return prefix + "wildfly-swarm.png"; } else if (iconRef.contains("weld")) { return prefix + "weld.svg"; } else if (iconRef.contains("zipkin")) { return prefix + "zipkin.png"; } return null; } }
public class class_name { protected String embeddedIconsInConsole(String iconRef, String prefix) { if (iconRef == null) { return null; // depends on control dependency: [if], data = [none] } if (iconRef.startsWith("icons/")) { iconRef = iconRef.substring(6); // depends on control dependency: [if], data = [none] } // special for fabric8 as its in a different dir if (iconRef.contains("META-INF/fabric8")) { return "img/fabric8_icon.svg"; // depends on control dependency: [if], data = [none] } if (iconRef.contains("activemq")) { return prefix + "activemq.svg"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("apiman")) { return prefix + "apiman.png"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("api-registry")) { return prefix + "api-registry.svg"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("brackets")) { return prefix + "brackets.svg"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("camel")) { return prefix + "camel.svg"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("chaos-monkey")) { return prefix + "chaos-monkey.png"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("docker-registry")) { return prefix + "docker-registry.png"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("elasticsearch")) { return prefix + "elasticsearch.png"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("fluentd")) { return prefix + "fluentd.png"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("forge")) { return prefix + "forge.svg"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("funktion")) { return prefix + "funktion.png"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("gerrit")) { return prefix + "gerrit.png"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("gitlab")) { return prefix + "gitlab.svg"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("gogs")) { return prefix + "gogs.png"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("grafana")) { return prefix + "grafana.png"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("hubot-irc")) { return prefix + "hubot-irc.png"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("hubot-letschat")) { return prefix + "hubot-letschat.png"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("hubot-notifier")) { return prefix + "hubot-notifier.png"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("hubot-slack")) { return prefix + "hubot-slack.png"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("image-linker")) { return prefix + "image-linker.svg"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("javascript")) { return prefix + "javascript.png"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("java")) { return prefix + "java.svg"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("jenkins")) { return prefix + "jenkins.svg"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("jetty")) { return prefix + "jetty.svg"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("karaf")) { return prefix + "karaf.svg"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("keycloak")) { return prefix + "keycloak.svg"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("kibana")) { return prefix + "kibana.svg"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("kiwiirc")) { return prefix + "kiwiirc.png"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("letschat")) { return prefix + "letschat.png"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("mule")) { return prefix + "mule.svg"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("nexus")) { return prefix + "nexus.png"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("node")) { return prefix + "node.svg"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("orion")) { return prefix + "orion.png"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("prometheus")) { return prefix + "prometheus.png"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("django") || iconRef.contains("python")) { return prefix + "python.png"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("spring-boot")) { return prefix + "spring-boot.svg"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("taiga")) { return prefix + "taiga.png"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("tomcat")) { return prefix + "tomcat.svg"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("tomee")) { return prefix + "tomee.svg"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("vertx")) { return prefix + "vertx.svg"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("wildfly")) { return prefix + "wildfly.svg"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("wildfly-swarm")) { return prefix + "wildfly-swarm.png"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("weld")) { return prefix + "weld.svg"; // depends on control dependency: [if], data = [none] } else if (iconRef.contains("zipkin")) { return prefix + "zipkin.png"; // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { public static Byte[] toObject(byte[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_BYTE_OBJECT_ARRAY; } final Byte[] result = new Byte[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i]; } return result; } }
public class class_name { public static Byte[] toObject(byte[] array) { if (array == null) { return null; // depends on control dependency: [if], data = [none] } else if (array.length == 0) { return EMPTY_BYTE_OBJECT_ARRAY; // depends on control dependency: [if], data = [none] } final Byte[] result = new Byte[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i]; // depends on control dependency: [for], data = [i] } return result; } }
public class class_name { public ArrayList readAllCreateObs(CancelTask cancel) throws IOException { // see if its a station or point dataset boolean hasStations = stnIdVName != null; if (hasStations) stnHash = new HashMap<Object, ucar.unidata.geoloc.Station>(); // get min and max date and lat,lon double minDate = Double.MAX_VALUE; double maxDate = -Double.MAX_VALUE; double minLat = Double.MAX_VALUE; double maxLat = -Double.MAX_VALUE; double minLon = Double.MAX_VALUE; double maxLon = -Double.MAX_VALUE; // read all the data, create a RecordObs ArrayList records = new ArrayList(); int recno = 0; try (StructureDataIterator ii = recordVar.getStructureIterator()) { while (ii.hasNext()) { StructureData sdata = ii.next(); StructureMembers members = sdata.getStructureMembers(); Object stationId = null; if (hasStations) { if (stationIdType == DataType.INT) { int stationNum = sdata.getScalarInt(stnIdVName); stationId = new Integer(stationNum); } else stationId = sdata.getScalarString(stnIdVName).trim(); } String desc = (stnDescVName == null) ? null : sdata.getScalarString(stnDescVName); double lat = sdata.convertScalarDouble(latVName); double lon = sdata.convertScalarDouble(lonVName); double alt = (altVName == null) ? Double.NaN : altScaleFactor * sdata.convertScalarDouble(altVName); double obsTime = sdata.convertScalarDouble(members.findMember(obsTimeVName)); double nomTime = (nomTimeVName == null) ? obsTime : sdata.convertScalarDouble(members.findMember(nomTimeVName)); //double obsTime = sdata.convertScalarDouble( members.findMember( obsTimeVName) ); //double nomTime = (nomTimeVName == null) ? obsTime : sdata.convertScalarDouble( members.findMember( nomTimeVName)); if (hasStations) { StationImpl stn = (StationImpl) stnHash.get(stationId); if (stn == null) { stn = new StationImpl(stationId.toString(), desc, lat, lon, alt); stnHash.put(stationId, stn); } RecordStationObs stnObs = new RecordStationObs(stn, obsTime, nomTime, recno); records.add(stnObs); stn.addObs(stnObs); } else { records.add(new RecordPointObs(new ucar.unidata.geoloc.EarthLocationImpl(lat, lon, alt), obsTime, nomTime, recno)); } // track date range and bounding box minDate = Math.min(minDate, obsTime); maxDate = Math.max(maxDate, obsTime); minLat = Math.min(minLat, lat); maxLat = Math.max(maxLat, lat); minLon = Math.min(minLon, lon); maxLon = Math.max(maxLon, lon); recno++; if ((cancel != null) && cancel.isCancel()) return null; } } boundingBox = new LatLonRect(new LatLonPointImpl(minLat, minLon), new LatLonPointImpl(maxLat, maxLon)); return records; } }
public class class_name { public ArrayList readAllCreateObs(CancelTask cancel) throws IOException { // see if its a station or point dataset boolean hasStations = stnIdVName != null; if (hasStations) stnHash = new HashMap<Object, ucar.unidata.geoloc.Station>(); // get min and max date and lat,lon double minDate = Double.MAX_VALUE; double maxDate = -Double.MAX_VALUE; double minLat = Double.MAX_VALUE; double maxLat = -Double.MAX_VALUE; double minLon = Double.MAX_VALUE; double maxLon = -Double.MAX_VALUE; // read all the data, create a RecordObs ArrayList records = new ArrayList(); int recno = 0; try (StructureDataIterator ii = recordVar.getStructureIterator()) { while (ii.hasNext()) { StructureData sdata = ii.next(); StructureMembers members = sdata.getStructureMembers(); Object stationId = null; if (hasStations) { if (stationIdType == DataType.INT) { int stationNum = sdata.getScalarInt(stnIdVName); stationId = new Integer(stationNum); // depends on control dependency: [if], data = [none] } else stationId = sdata.getScalarString(stnIdVName).trim(); } String desc = (stnDescVName == null) ? null : sdata.getScalarString(stnDescVName); double lat = sdata.convertScalarDouble(latVName); double lon = sdata.convertScalarDouble(lonVName); double alt = (altVName == null) ? Double.NaN : altScaleFactor * sdata.convertScalarDouble(altVName); double obsTime = sdata.convertScalarDouble(members.findMember(obsTimeVName)); double nomTime = (nomTimeVName == null) ? obsTime : sdata.convertScalarDouble(members.findMember(nomTimeVName)); //double obsTime = sdata.convertScalarDouble( members.findMember( obsTimeVName) ); //double nomTime = (nomTimeVName == null) ? obsTime : sdata.convertScalarDouble( members.findMember( nomTimeVName)); if (hasStations) { StationImpl stn = (StationImpl) stnHash.get(stationId); if (stn == null) { stn = new StationImpl(stationId.toString(), desc, lat, lon, alt); // depends on control dependency: [if], data = [none] stnHash.put(stationId, stn); // depends on control dependency: [if], data = [none] } RecordStationObs stnObs = new RecordStationObs(stn, obsTime, nomTime, recno); records.add(stnObs); // depends on control dependency: [if], data = [none] stn.addObs(stnObs); // depends on control dependency: [if], data = [none] } else { records.add(new RecordPointObs(new ucar.unidata.geoloc.EarthLocationImpl(lat, lon, alt), obsTime, nomTime, recno)); // depends on control dependency: [if], data = [none] } // track date range and bounding box minDate = Math.min(minDate, obsTime); maxDate = Math.max(maxDate, obsTime); minLat = Math.min(minLat, lat); maxLat = Math.max(maxLat, lat); minLon = Math.min(minLon, lon); maxLon = Math.max(maxLon, lon); recno++; if ((cancel != null) && cancel.isCancel()) return null; } } boundingBox = new LatLonRect(new LatLonPointImpl(minLat, minLon), new LatLonPointImpl(maxLat, maxLon)); return records; } }
public class class_name { private String encodeBytesFromBuffer(int howMany) { String result; if (innerStreamHasMoreData) { howMany = howMany - howMany % 3; } if (howMany == 0) { return ""; } byte[] encodeBuffer = new byte[howMany]; System.arraycopy(buffer, 0, encodeBuffer, 0, howMany); result = Base64.encodeToString(encodeBuffer); bytesInBuffer -= howMany; if (bytesInBuffer != 0) { System.arraycopy(buffer, howMany, buffer, 0, bytesInBuffer); } return result; } }
public class class_name { private String encodeBytesFromBuffer(int howMany) { String result; if (innerStreamHasMoreData) { howMany = howMany - howMany % 3; // depends on control dependency: [if], data = [none] } if (howMany == 0) { return ""; // depends on control dependency: [if], data = [none] } byte[] encodeBuffer = new byte[howMany]; System.arraycopy(buffer, 0, encodeBuffer, 0, howMany); result = Base64.encodeToString(encodeBuffer); bytesInBuffer -= howMany; if (bytesInBuffer != 0) { System.arraycopy(buffer, howMany, buffer, 0, bytesInBuffer); // depends on control dependency: [if], data = [none] } return result; } }
public class class_name { private String toTypeString(ClassTemplateSpec spec) { // If we're supporting projections, all fields, even required ones, may be absent. // To support this, we box all primitive field types. if (spec.getSchema() == null) { // custom type return escapedFullname(spec); } Type schemaType = spec.getSchema().getType(); if (schemaType == Type.INT) { return "Int"; // TODO: just use Int32 here? (On a 32-bit platform, Int is the same size as Int32.) } else if (schemaType == Type.LONG) { return "Int"; // TODO: just use Int32 here? (On a 64-bit platform, Int is the same size as Int64.) } else if (schemaType == Type.FLOAT) { return "Float"; } else if (schemaType == Type.DOUBLE) { return "Double"; } else if (schemaType == Type.STRING) { return "String"; } else if (schemaType == Type.BOOLEAN) { return "Bool"; } else if (schemaType == Type.BYTES) { return "String"; // TODO(jbetz): provide an adapter for converting pegasus byte strings to swift byte[] } else if (schemaType == Type.FIXED) { return "String"; // TODO(jbetz): provide an adapter for converting pegasus byte strings to swift byte[] } else if (schemaType == Type.ENUM) { return escapedFullname(spec); } else if (schemaType == Type.RECORD) { return escapedFullname(spec); } else if (schemaType == Type.UNION) { return escapedFullname(spec); } else if (schemaType == Type.MAP) { return "[String: " + toTypeString(((CourierMapTemplateSpec) spec).getValueClass()) + "]"; } else if (schemaType == Type.ARRAY) { return "[" + toTypeString(((ArrayTemplateSpec) spec).getItemClass()) + "]"; } else { throw new IllegalArgumentException("unrecognized type: " + schemaType); } } }
public class class_name { private String toTypeString(ClassTemplateSpec spec) { // If we're supporting projections, all fields, even required ones, may be absent. // To support this, we box all primitive field types. if (spec.getSchema() == null) { // custom type return escapedFullname(spec); // depends on control dependency: [if], data = [none] } Type schemaType = spec.getSchema().getType(); if (schemaType == Type.INT) { return "Int"; // TODO: just use Int32 here? (On a 32-bit platform, Int is the same size as Int32.) // depends on control dependency: [if], data = [none] } else if (schemaType == Type.LONG) { return "Int"; // TODO: just use Int32 here? (On a 64-bit platform, Int is the same size as Int64.) // depends on control dependency: [if], data = [none] } else if (schemaType == Type.FLOAT) { return "Float"; // depends on control dependency: [if], data = [none] } else if (schemaType == Type.DOUBLE) { return "Double"; // depends on control dependency: [if], data = [none] } else if (schemaType == Type.STRING) { return "String"; // depends on control dependency: [if], data = [none] } else if (schemaType == Type.BOOLEAN) { return "Bool"; // depends on control dependency: [if], data = [none] } else if (schemaType == Type.BYTES) { return "String"; // TODO(jbetz): provide an adapter for converting pegasus byte strings to swift byte[] // depends on control dependency: [if], data = [none] } else if (schemaType == Type.FIXED) { return "String"; // TODO(jbetz): provide an adapter for converting pegasus byte strings to swift byte[] // depends on control dependency: [if], data = [none] } else if (schemaType == Type.ENUM) { return escapedFullname(spec); // depends on control dependency: [if], data = [none] } else if (schemaType == Type.RECORD) { return escapedFullname(spec); // depends on control dependency: [if], data = [none] } else if (schemaType == Type.UNION) { return escapedFullname(spec); // depends on control dependency: [if], data = [none] } else if (schemaType == Type.MAP) { return "[String: " + toTypeString(((CourierMapTemplateSpec) spec).getValueClass()) + "]"; // depends on control dependency: [if], data = [none] } else if (schemaType == Type.ARRAY) { return "[" + toTypeString(((ArrayTemplateSpec) spec).getItemClass()) + "]"; // depends on control dependency: [if], data = [none] } else { throw new IllegalArgumentException("unrecognized type: " + schemaType); } } }
public class class_name { public void gatherOutput() { try { final Copier errorCopier = new Copier(this.processErrorStream); final Copier outputCopier = new Copier(this.processOutputStream); errorCopier.start(); outputCopier.start(); errorCopier.join(); outputCopier.join(); this.stderr = new String[errorCopier.getLines().size()]; errorCopier.getLines().copyInto(this.stderr); this.stdout = new String[outputCopier.getLines().size()]; outputCopier.getLines().copyInto(this.stdout); } catch (final Exception e) { this.stderr = this.stdout = new String[0]; } } }
public class class_name { public void gatherOutput() { try { final Copier errorCopier = new Copier(this.processErrorStream); final Copier outputCopier = new Copier(this.processOutputStream); errorCopier.start(); // depends on control dependency: [try], data = [none] outputCopier.start(); // depends on control dependency: [try], data = [none] errorCopier.join(); // depends on control dependency: [try], data = [none] outputCopier.join(); // depends on control dependency: [try], data = [none] this.stderr = new String[errorCopier.getLines().size()]; // depends on control dependency: [try], data = [none] errorCopier.getLines().copyInto(this.stderr); // depends on control dependency: [try], data = [none] this.stdout = new String[outputCopier.getLines().size()]; // depends on control dependency: [try], data = [none] outputCopier.getLines().copyInto(this.stdout); // depends on control dependency: [try], data = [none] } catch (final Exception e) { this.stderr = this.stdout = new String[0]; } // depends on control dependency: [catch], data = [none] } }
public class class_name { public Task getTask(int index) { final Lock readLock = lock.readLock(); try { readLock.lock(); return tasks.get(index); } finally { readLock.unlock(); } } }
public class class_name { public Task getTask(int index) { final Lock readLock = lock.readLock(); try { readLock.lock(); // depends on control dependency: [try], data = [none] return tasks.get(index); // depends on control dependency: [try], data = [none] } finally { readLock.unlock(); } } }
public class class_name { public void send(String toAddress, String subject, String message, List<File> attachments, boolean highPriority) throws NamingException, MessagingException { assert toAddress != null; assert subject != null; assert message != null; final InternetAddress[] toAddresses = InternetAddress.parse(toAddress, false); final Message msg = new MimeMessage(getSession()); msg.setRecipients(Message.RecipientType.TO, toAddresses); msg.setSubject(subject); msg.setSentDate(new Date()); msg.setFrom(fromAddress); if (highPriority) { msg.setHeader("X-Priority", "1"); msg.setHeader("x-msmail-priority", "high"); } // Content is stored in a MIME multi-part message with one body part final MimeBodyPart mbp = new MimeBodyPart(); mbp.setText(message); final Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mbp); if (attachments != null && !attachments.isEmpty()) { for (final File attachment : attachments) { final DataSource source = new FileDataSource(attachment); final MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachment.getName()); multipart.addBodyPart(messageBodyPart); } } msg.setContent(multipart); // protocol smtp, ou smpts si mail.transport.protocol=smtps est indiqué dans la configuration de la session mail String protocol = session.getProperty("mail.transport.protocol"); if (protocol == null) { protocol = "smtp"; } // authentification avec user et password si mail.smtp.auth=true (ou mail.smtps.auth=true) if (Boolean.parseBoolean(session.getProperty("mail." + protocol + ".auth"))) { final Transport tr = session.getTransport(protocol); try { tr.connect(session.getProperty("mail." + protocol + ".user"), session.getProperty("mail." + protocol + ".password")); msg.saveChanges(); // don't forget this tr.sendMessage(msg, msg.getAllRecipients()); } finally { tr.close(); } } else { Transport.send(msg); } } }
public class class_name { public void send(String toAddress, String subject, String message, List<File> attachments, boolean highPriority) throws NamingException, MessagingException { assert toAddress != null; assert subject != null; assert message != null; final InternetAddress[] toAddresses = InternetAddress.parse(toAddress, false); final Message msg = new MimeMessage(getSession()); msg.setRecipients(Message.RecipientType.TO, toAddresses); msg.setSubject(subject); msg.setSentDate(new Date()); msg.setFrom(fromAddress); if (highPriority) { msg.setHeader("X-Priority", "1"); msg.setHeader("x-msmail-priority", "high"); } // Content is stored in a MIME multi-part message with one body part final MimeBodyPart mbp = new MimeBodyPart(); mbp.setText(message); final Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mbp); if (attachments != null && !attachments.isEmpty()) { for (final File attachment : attachments) { final DataSource source = new FileDataSource(attachment); final MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(source)); // depends on control dependency: [for], data = [none] messageBodyPart.setFileName(attachment.getName()); // depends on control dependency: [for], data = [attachment] multipart.addBodyPart(messageBodyPart); // depends on control dependency: [for], data = [none] } } msg.setContent(multipart); // protocol smtp, ou smpts si mail.transport.protocol=smtps est indiqué dans la configuration de la session mail String protocol = session.getProperty("mail.transport.protocol"); if (protocol == null) { protocol = "smtp"; } // authentification avec user et password si mail.smtp.auth=true (ou mail.smtps.auth=true) if (Boolean.parseBoolean(session.getProperty("mail." + protocol + ".auth"))) { final Transport tr = session.getTransport(protocol); try { tr.connect(session.getProperty("mail." + protocol + ".user"), session.getProperty("mail." + protocol + ".password")); msg.saveChanges(); // don't forget this tr.sendMessage(msg, msg.getAllRecipients()); } finally { tr.close(); } } else { Transport.send(msg); } } }
public class class_name { public static <T> String listToString(List<T> list, final boolean justValue, final String separator) { StringBuilder s = new StringBuilder(); for (Iterator<T> wordIterator = list.iterator(); wordIterator.hasNext();) { T o = wordIterator.next(); s.append(wordToString(o, justValue, separator)); if (wordIterator.hasNext()) { s.append(' '); } } return s.toString(); } }
public class class_name { public static <T> String listToString(List<T> list, final boolean justValue, final String separator) { StringBuilder s = new StringBuilder(); for (Iterator<T> wordIterator = list.iterator(); wordIterator.hasNext();) { T o = wordIterator.next(); s.append(wordToString(o, justValue, separator)); // depends on control dependency: [for], data = [none] if (wordIterator.hasNext()) { s.append(' '); // depends on control dependency: [if], data = [none] } } return s.toString(); } }
public class class_name { protected Variable[] createVariablesSub(int num, String component) { Variable[] ret = createVariablesSub(num); if (component != null) { logger.finest("Set component of " + Arrays.toString(ret) + " to " + component); this.setComponent(component, ret); } return ret; } }
public class class_name { protected Variable[] createVariablesSub(int num, String component) { Variable[] ret = createVariablesSub(num); if (component != null) { logger.finest("Set component of " + Arrays.toString(ret) + " to " + component); // depends on control dependency: [if], data = [none] this.setComponent(component, ret); // depends on control dependency: [if], data = [(component] } return ret; } }
public class class_name { public OutlierResult run(Relation<V> relation) { final int dim = RelationUtil.dimensionality(relation); final int size = relation.size(); ArrayList<ArrayList<DBIDs>> ranges = buildRanges(relation); ArrayList<int[]> Rk; // Build a list of all subspaces FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Subspace size", k, LOG) : null; // R1 initial one-dimensional subspaces. Rk = new ArrayList<>(); // Set of all dim*phi ranges ArrayList<IntIntPair> q = new ArrayList<>(); for(int i = 0; i < dim; i++) { for(int j = 0; j < phi; j++) { q.add(new IntIntPair(i, j)); Rk.add(new int[] { i, j }); } } LOG.incrementProcessed(prog); // build Ri for(int i = 2; i <= k; i++) { ArrayList<int[]> Rnew = new ArrayList<>(); for(int j = 0; j < Rk.size(); j++) { int[] c = Rk.get(j); for(IntIntPair pair : q) { boolean invalid = false; for(int t = 0; t < c.length; t += 2) { if(c[t] == pair.first) { invalid = true; break; } } if(!invalid) { int[] neu = Arrays.copyOf(c, c.length + 2); neu[c.length] = pair.first; neu[c.length + 1] = pair.second; Rnew.add(neu); } } } Rk = Rnew; LOG.incrementProcessed(prog); } if(prog != null) { prog.setProcessed(k, LOG); } LOG.ensureCompleted(prog); WritableDoubleDataStore sparsity = DataStoreUtil.makeDoubleStorage(relation.getDBIDs(), DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_STATIC); // calculate the sparsity coefficient for(int[] sub : Rk) { DBIDs ids = computeSubspace(sub, ranges); final double sparsityC = sparsity(ids.size(), size, k, phi); if(sparsityC < 0) { for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { double prev = sparsity.doubleValue(iter); if(Double.isNaN(prev) || sparsityC < prev) { sparsity.putDouble(iter, sparsityC); } } } } DoubleMinMax minmax = new DoubleMinMax(); for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) { double val = sparsity.doubleValue(iditer); if(Double.isNaN(val)) { sparsity.putDouble(iditer, 0.0); val = 0.0; } minmax.put(val); } DoubleRelation scoreResult = new MaterializedDoubleRelation("AggarwalYuNaive", "aggarwal-yu-outlier", sparsity, relation.getDBIDs()); OutlierScoreMeta meta = new InvertedOutlierScoreMeta(minmax.getMin(), minmax.getMax(), Double.NEGATIVE_INFINITY, 0.0); return new OutlierResult(meta, scoreResult); } }
public class class_name { public OutlierResult run(Relation<V> relation) { final int dim = RelationUtil.dimensionality(relation); final int size = relation.size(); ArrayList<ArrayList<DBIDs>> ranges = buildRanges(relation); ArrayList<int[]> Rk; // Build a list of all subspaces FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Subspace size", k, LOG) : null; // R1 initial one-dimensional subspaces. Rk = new ArrayList<>(); // Set of all dim*phi ranges ArrayList<IntIntPair> q = new ArrayList<>(); for(int i = 0; i < dim; i++) { for(int j = 0; j < phi; j++) { q.add(new IntIntPair(i, j)); // depends on control dependency: [for], data = [j] Rk.add(new int[] { i, j }); // depends on control dependency: [for], data = [j] } } LOG.incrementProcessed(prog); // build Ri for(int i = 2; i <= k; i++) { ArrayList<int[]> Rnew = new ArrayList<>(); for(int j = 0; j < Rk.size(); j++) { int[] c = Rk.get(j); for(IntIntPair pair : q) { boolean invalid = false; for(int t = 0; t < c.length; t += 2) { if(c[t] == pair.first) { invalid = true; // depends on control dependency: [if], data = [none] break; } } if(!invalid) { int[] neu = Arrays.copyOf(c, c.length + 2); neu[c.length] = pair.first; // depends on control dependency: [if], data = [none] neu[c.length + 1] = pair.second; // depends on control dependency: [if], data = [none] Rnew.add(neu); // depends on control dependency: [if], data = [none] } } } Rk = Rnew; // depends on control dependency: [for], data = [none] LOG.incrementProcessed(prog); // depends on control dependency: [for], data = [none] } if(prog != null) { prog.setProcessed(k, LOG); // depends on control dependency: [if], data = [none] } LOG.ensureCompleted(prog); WritableDoubleDataStore sparsity = DataStoreUtil.makeDoubleStorage(relation.getDBIDs(), DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_STATIC); // calculate the sparsity coefficient for(int[] sub : Rk) { DBIDs ids = computeSubspace(sub, ranges); final double sparsityC = sparsity(ids.size(), size, k, phi); if(sparsityC < 0) { for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { double prev = sparsity.doubleValue(iter); if(Double.isNaN(prev) || sparsityC < prev) { sparsity.putDouble(iter, sparsityC); // depends on control dependency: [if], data = [none] } } } } DoubleMinMax minmax = new DoubleMinMax(); for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) { double val = sparsity.doubleValue(iditer); if(Double.isNaN(val)) { sparsity.putDouble(iditer, 0.0); // depends on control dependency: [if], data = [none] val = 0.0; // depends on control dependency: [if], data = [none] } minmax.put(val); // depends on control dependency: [for], data = [none] } DoubleRelation scoreResult = new MaterializedDoubleRelation("AggarwalYuNaive", "aggarwal-yu-outlier", sparsity, relation.getDBIDs()); OutlierScoreMeta meta = new InvertedOutlierScoreMeta(minmax.getMin(), minmax.getMax(), Double.NEGATIVE_INFINITY, 0.0); return new OutlierResult(meta, scoreResult); } }