code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { public EClass getIfcVertexPoint() { if (ifcVertexPointEClass == null) { ifcVertexPointEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(636); } return ifcVertexPointEClass; } }
public class class_name { public EClass getIfcVertexPoint() { if (ifcVertexPointEClass == null) { ifcVertexPointEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(636); // depends on control dependency: [if], data = [none] } return ifcVertexPointEClass; } }
public class class_name { public static String[] getDefaultWhiteList(Field field) { Method values = null; if (!field.getType().isEnum()) { try { values = field.getType().getMethod("values"); } catch (NoSuchMethodException e) { log.info("field : " + field.getName() + " values method not found "); } try { Object[] objs = (Object[]) values.invoke(field.getType()); return (String[]) Arrays.stream(objs).map(obj -> String.valueOf(obj)).toArray(); } catch (IllegalAccessException | InvocationTargetException e) { log.info("values invoke error : " + e.getMessage()); } } return null; } }
public class class_name { public static String[] getDefaultWhiteList(Field field) { Method values = null; if (!field.getType().isEnum()) { try { values = field.getType().getMethod("values"); // depends on control dependency: [try], data = [none] } catch (NoSuchMethodException e) { log.info("field : " + field.getName() + " values method not found "); } // depends on control dependency: [catch], data = [none] try { Object[] objs = (Object[]) values.invoke(field.getType()); return (String[]) Arrays.stream(objs).map(obj -> String.valueOf(obj)).toArray(); // depends on control dependency: [try], data = [none] } catch (IllegalAccessException | InvocationTargetException e) { log.info("values invoke error : " + e.getMessage()); } // depends on control dependency: [catch], data = [none] } return null; } }
public class class_name { public void setFallbackIntervalPattern(String fallbackPattern) { if ( frozen ) { throw new UnsupportedOperationException("no modification is allowed after DII is frozen"); } int firstPatternIndex = fallbackPattern.indexOf("{0}"); int secondPatternIndex = fallbackPattern.indexOf("{1}"); if ( firstPatternIndex == -1 || secondPatternIndex == -1 ) { throw new IllegalArgumentException("no pattern {0} or pattern {1} in fallbackPattern"); } if ( firstPatternIndex > secondPatternIndex ) { fFirstDateInPtnIsLaterDate = true; } fFallbackIntervalPattern = fallbackPattern; } }
public class class_name { public void setFallbackIntervalPattern(String fallbackPattern) { if ( frozen ) { throw new UnsupportedOperationException("no modification is allowed after DII is frozen"); } int firstPatternIndex = fallbackPattern.indexOf("{0}"); int secondPatternIndex = fallbackPattern.indexOf("{1}"); if ( firstPatternIndex == -1 || secondPatternIndex == -1 ) { throw new IllegalArgumentException("no pattern {0} or pattern {1} in fallbackPattern"); } if ( firstPatternIndex > secondPatternIndex ) { fFirstDateInPtnIsLaterDate = true; // depends on control dependency: [if], data = [none] } fFallbackIntervalPattern = fallbackPattern; } }
public class class_name { @Override public String indexValue(String name, Object value) { if (value == null) { return null; } else { return value.toString(); } } }
public class class_name { @Override public String indexValue(String name, Object value) { if (value == null) { return null; // depends on control dependency: [if], data = [none] } else { return value.toString(); // depends on control dependency: [if], data = [none] } } }
public class class_name { private BellaDatiRuntimeException buildException(int code, byte[] content, boolean hasToken) { try { HttpParameters oauthParams = OAuth.decodeForm(new ByteArrayInputStream(content)); if (oauthParams.containsKey("oauth_problem")) { String problem = oauthParams.getFirst("oauth_problem"); if ("missing_consumer".equals(problem) || "invalid_consumer".equals(problem)) { return new AuthorizationException(Reason.CONSUMER_KEY_UNKNOWN); } else if ("invalid_signature".equals(problem) || "signature_invalid".equals(problem)) { return new AuthorizationException(hasToken ? Reason.TOKEN_INVALID : Reason.CONSUMER_SECRET_INVALID); } else if ("domain_expired".equals(problem)) { return new AuthorizationException(Reason.DOMAIN_EXPIRED); } else if ("missing_token".equals(problem) || "invalid_token".equals(problem)) { return new AuthorizationException(Reason.TOKEN_INVALID); } else if ("unauthorized_token".equals(problem)) { return new AuthorizationException(Reason.TOKEN_UNAUTHORIZED); } else if ("token_expired".equals(problem)) { return new AuthorizationException(Reason.TOKEN_EXPIRED); } else if ("x_auth_disabled".equals(problem)) { return new AuthorizationException(Reason.X_AUTH_DISABLED); } else if ("piccolo_not_enabled".equals(problem)) { return new AuthorizationException(Reason.BD_MOBILE_DISABLED); } else if ("missing_username".equals(problem) || "missing_password".equals(problem) || "invalid_credentials".equals(problem) || "permission_denied".equals(problem)) { return new AuthorizationException(Reason.USER_CREDENTIALS_INVALID); } else if ("account_locked".equals(problem) || "user_not_active".equals(problem)) { return new AuthorizationException(Reason.USER_ACCOUNT_LOCKED); } else if ("domain_restricted".equals(problem)) { return new AuthorizationException(Reason.USER_DOMAIN_MISMATCH); } else if ("timestamp_refused".equals(problem)) { String acceptable = oauthParams.getFirst("oauth_acceptable_timestamps"); if (acceptable != null && acceptable.contains("-")) { return new InvalidTimestampException(Long.parseLong(acceptable.split("-")[0]), Long.parseLong(acceptable.split("-")[1])); } } return new AuthorizationException(Reason.OTHER, problem); } return new UnexpectedResponseException(code, new String(content)); } catch (IOException e) { throw new UnexpectedResponseException(code, new String(content), e); } } }
public class class_name { private BellaDatiRuntimeException buildException(int code, byte[] content, boolean hasToken) { try { HttpParameters oauthParams = OAuth.decodeForm(new ByteArrayInputStream(content)); if (oauthParams.containsKey("oauth_problem")) { String problem = oauthParams.getFirst("oauth_problem"); if ("missing_consumer".equals(problem) || "invalid_consumer".equals(problem)) { return new AuthorizationException(Reason.CONSUMER_KEY_UNKNOWN); // depends on control dependency: [if], data = [none] } else if ("invalid_signature".equals(problem) || "signature_invalid".equals(problem)) { return new AuthorizationException(hasToken ? Reason.TOKEN_INVALID : Reason.CONSUMER_SECRET_INVALID); // depends on control dependency: [if], data = [none] } else if ("domain_expired".equals(problem)) { return new AuthorizationException(Reason.DOMAIN_EXPIRED); // depends on control dependency: [if], data = [none] } else if ("missing_token".equals(problem) || "invalid_token".equals(problem)) { return new AuthorizationException(Reason.TOKEN_INVALID); // depends on control dependency: [if], data = [none] } else if ("unauthorized_token".equals(problem)) { return new AuthorizationException(Reason.TOKEN_UNAUTHORIZED); // depends on control dependency: [if], data = [none] } else if ("token_expired".equals(problem)) { return new AuthorizationException(Reason.TOKEN_EXPIRED); // depends on control dependency: [if], data = [none] } else if ("x_auth_disabled".equals(problem)) { return new AuthorizationException(Reason.X_AUTH_DISABLED); // depends on control dependency: [if], data = [none] } else if ("piccolo_not_enabled".equals(problem)) { return new AuthorizationException(Reason.BD_MOBILE_DISABLED); // depends on control dependency: [if], data = [none] } else if ("missing_username".equals(problem) || "missing_password".equals(problem) || "invalid_credentials".equals(problem) || "permission_denied".equals(problem)) { return new AuthorizationException(Reason.USER_CREDENTIALS_INVALID); // depends on control dependency: [if], data = [none] } else if ("account_locked".equals(problem) || "user_not_active".equals(problem)) { return new AuthorizationException(Reason.USER_ACCOUNT_LOCKED); // depends on control dependency: [if], data = [none] } else if ("domain_restricted".equals(problem)) { return new AuthorizationException(Reason.USER_DOMAIN_MISMATCH); // depends on control dependency: [if], data = [none] } else if ("timestamp_refused".equals(problem)) { String acceptable = oauthParams.getFirst("oauth_acceptable_timestamps"); if (acceptable != null && acceptable.contains("-")) { return new InvalidTimestampException(Long.parseLong(acceptable.split("-")[0]), Long.parseLong(acceptable.split("-")[1])); // depends on control dependency: [if], data = [none] } } return new AuthorizationException(Reason.OTHER, problem); // depends on control dependency: [if], data = [none] } return new UnexpectedResponseException(code, new String(content)); // depends on control dependency: [try], data = [none] } catch (IOException e) { throw new UnexpectedResponseException(code, new String(content), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private boolean isInZkWathcedNamespacePaths(String path) { if (StringUtil.isEmpty(path)) { return false; } for (String watchNamespacePath : RpcClientConf.ZK_WATCH_NAMESPACE_PATHS) { if (StringUtil.isEmpty(watchNamespacePath)) { continue; } if (path.contains(watchNamespacePath)) { return true; } } return false; } }
public class class_name { private boolean isInZkWathcedNamespacePaths(String path) { if (StringUtil.isEmpty(path)) { return false; // depends on control dependency: [if], data = [none] } for (String watchNamespacePath : RpcClientConf.ZK_WATCH_NAMESPACE_PATHS) { if (StringUtil.isEmpty(watchNamespacePath)) { continue; } if (path.contains(watchNamespacePath)) { return true; // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { public int getNameAndTypeIndex(String name, String descriptor) { for (ConstantInfo ci : listConstantInfo(NameAndType.class)) { NameAndType nat = (NameAndType) ci; int nameIndex = nat.getName_index(); String str = getString(nameIndex); if (name.equals(str)) { int descriptorIndex = nat.getDescriptor_index(); String descr = getString(descriptorIndex); if (descriptor.equals(descr)) { return constantPoolIndexMap.get(ci); } } } return -1; } }
public class class_name { public int getNameAndTypeIndex(String name, String descriptor) { for (ConstantInfo ci : listConstantInfo(NameAndType.class)) { NameAndType nat = (NameAndType) ci; int nameIndex = nat.getName_index(); String str = getString(nameIndex); if (name.equals(str)) { int descriptorIndex = nat.getDescriptor_index(); String descr = getString(descriptorIndex); if (descriptor.equals(descr)) { return constantPoolIndexMap.get(ci); // depends on control dependency: [if], data = [none] } } } return -1; } }
public class class_name { @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (errorToShow != null) { if (errorToShow != null) { Set<? extends Element> rootElements = roundEnv.getRootElements(); if (!rootElements.isEmpty()) { processingEnv.getMessager().printMessage(Kind.WARNING, errorToShow, rootElements.iterator().next()); errorToShow = null; } } } return false; } }
public class class_name { @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (errorToShow != null) { if (errorToShow != null) { Set<? extends Element> rootElements = roundEnv.getRootElements(); // depends on control dependency: [if], data = [none] if (!rootElements.isEmpty()) { processingEnv.getMessager().printMessage(Kind.WARNING, errorToShow, rootElements.iterator().next()); // depends on control dependency: [if], data = [none] errorToShow = null; // depends on control dependency: [if], data = [none] } } } return false; } }
public class class_name { @Override protected Object customKey(Object key) { if (null != key && key instanceof CharSequence) { key = StrUtil.toCamelCase(key.toString()); } return key; } }
public class class_name { @Override protected Object customKey(Object key) { if (null != key && key instanceof CharSequence) { key = StrUtil.toCamelCase(key.toString()); // depends on control dependency: [if], data = [none] } return key; } }
public class class_name { public final int get(int i) { if (fullWidth) { return array.get(i); } return unPack(array.get(getIndex(i)), getSubIndex(i)); } }
public class class_name { public final int get(int i) { if (fullWidth) { return array.get(i); // depends on control dependency: [if], data = [none] } return unPack(array.get(getIndex(i)), getSubIndex(i)); } }
public class class_name { Integer getColBufLen(int i) { int size; int type; ColumnSchema column; column = table.getColumn(i); type = column.getDataType().getJDBCTypeCode(); switch (type) { case Types.SQL_CHAR : case Types.SQL_CLOB : case Types.VARCHAR_IGNORECASE : case Types.SQL_VARCHAR : { size = column.getDataType().precision > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) column.getDataType().precision; if (size == 0) {} else if (size > HALF_MAX_INT) { size = 0; } else { size = 2 * size; } break; } case Types.SQL_BINARY : case Types.SQL_BLOB : case Types.SQL_VARBINARY : { size = column.getDataType().precision > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) column.getDataType().precision; break; } case Types.SQL_BIGINT : case Types.SQL_DOUBLE : case Types.SQL_FLOAT : case Types.SQL_DATE : case Types.SQL_REAL : case Types.SQL_TIME_WITH_TIME_ZONE : case Types.SQL_TIME : { size = 8; break; } case Types.SQL_TIMESTAMP_WITH_TIME_ZONE : case Types.SQL_TIMESTAMP : { size = 12; break; } case Types.SQL_INTEGER : case Types.SQL_SMALLINT : case Types.TINYINT : { size = 4; break; } case Types.SQL_BOOLEAN : { size = 1; break; } default : { size = 0; break; } } return (size > 0) ? ValuePool.getInt(size) : null; } }
public class class_name { Integer getColBufLen(int i) { int size; int type; ColumnSchema column; column = table.getColumn(i); type = column.getDataType().getJDBCTypeCode(); switch (type) { case Types.SQL_CHAR : case Types.SQL_CLOB : case Types.VARCHAR_IGNORECASE : case Types.SQL_VARCHAR : { size = column.getDataType().precision > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) column.getDataType().precision; if (size == 0) {} else if (size > HALF_MAX_INT) { size = 0; // depends on control dependency: [if], data = [none] } else { size = 2 * size; // depends on control dependency: [if], data = [none] } break; } case Types.SQL_BINARY : case Types.SQL_BLOB : case Types.SQL_VARBINARY : { size = column.getDataType().precision > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) column.getDataType().precision; break; } case Types.SQL_BIGINT : case Types.SQL_DOUBLE : case Types.SQL_FLOAT : case Types.SQL_DATE : case Types.SQL_REAL : case Types.SQL_TIME_WITH_TIME_ZONE : case Types.SQL_TIME : { size = 8; break; } case Types.SQL_TIMESTAMP_WITH_TIME_ZONE : case Types.SQL_TIMESTAMP : { size = 12; break; } case Types.SQL_INTEGER : case Types.SQL_SMALLINT : case Types.TINYINT : { size = 4; break; } case Types.SQL_BOOLEAN : { size = 1; break; } default : { size = 0; break; } } return (size > 0) ? ValuePool.getInt(size) : null; } }
public class class_name { public static void registerExternalConfigLoader(ExternalConfigLoader configLoader) { wLock.lock(); try { CONFIG_LOADERS.add(configLoader); Collections.sort(CONFIG_LOADERS, new OrderedComparator<ExternalConfigLoader>()); } finally { wLock.unlock(); } } }
public class class_name { public static void registerExternalConfigLoader(ExternalConfigLoader configLoader) { wLock.lock(); try { CONFIG_LOADERS.add(configLoader); // depends on control dependency: [try], data = [none] Collections.sort(CONFIG_LOADERS, new OrderedComparator<ExternalConfigLoader>()); // depends on control dependency: [try], data = [none] } finally { wLock.unlock(); } } }
public class class_name { public int defineTurnBits(int index, int shift) { if (maxTurnCosts == 0) return shift; // optimization for turn restrictions only else if (maxTurnCosts == 1) { turnRestrictionBit = 1L << shift; return shift + 1; } int turnBits = Helper.countBitValue(maxTurnCosts); turnCostEncoder = new EncodedValueOld("TurnCost", shift, turnBits, 1, 0, maxTurnCosts) { // override to avoid expensive Math.round @Override public final long getValue(long flags) { // find value flags &= mask; flags >>>= shift; return flags; } }; return shift + turnBits; } }
public class class_name { public int defineTurnBits(int index, int shift) { if (maxTurnCosts == 0) return shift; // optimization for turn restrictions only else if (maxTurnCosts == 1) { turnRestrictionBit = 1L << shift; // depends on control dependency: [if], data = [none] return shift + 1; // depends on control dependency: [if], data = [none] } int turnBits = Helper.countBitValue(maxTurnCosts); turnCostEncoder = new EncodedValueOld("TurnCost", shift, turnBits, 1, 0, maxTurnCosts) { // override to avoid expensive Math.round @Override public final long getValue(long flags) { // find value flags &= mask; flags >>>= shift; return flags; } }; return shift + turnBits; } }
public class class_name { public void setThreatIntelIndicatorCategory(java.util.Collection<StringFilter> threatIntelIndicatorCategory) { if (threatIntelIndicatorCategory == null) { this.threatIntelIndicatorCategory = null; return; } this.threatIntelIndicatorCategory = new java.util.ArrayList<StringFilter>(threatIntelIndicatorCategory); } }
public class class_name { public void setThreatIntelIndicatorCategory(java.util.Collection<StringFilter> threatIntelIndicatorCategory) { if (threatIntelIndicatorCategory == null) { this.threatIntelIndicatorCategory = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.threatIntelIndicatorCategory = new java.util.ArrayList<StringFilter>(threatIntelIndicatorCategory); } }
public class class_name { private SeverityEnumType getSeverity(Severity severity, Severity defaultSeverity) { if (severity == null) { severity = defaultSeverity; } return defaultSeverity != null ? SeverityEnumType.fromValue(severity.getValue()) : null; } }
public class class_name { private SeverityEnumType getSeverity(Severity severity, Severity defaultSeverity) { if (severity == null) { severity = defaultSeverity; // depends on control dependency: [if], data = [none] } return defaultSeverity != null ? SeverityEnumType.fromValue(severity.getValue()) : null; } }
public class class_name { public Observable<ServiceResponse<StorageBundle>> restoreStorageAccountWithServiceResponseAsync(String vaultBaseUrl, byte[] storageBundleBackup) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } if (this.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } if (storageBundleBackup == null) { throw new IllegalArgumentException("Parameter storageBundleBackup is required and cannot be null."); } StorageRestoreParameters parameters = new StorageRestoreParameters(); parameters.withStorageBundleBackup(storageBundleBackup); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); return service.restoreStorageAccount(this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<StorageBundle>>>() { @Override public Observable<ServiceResponse<StorageBundle>> call(Response<ResponseBody> response) { try { ServiceResponse<StorageBundle> clientResponse = restoreStorageAccountDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } }
public class class_name { public Observable<ServiceResponse<StorageBundle>> restoreStorageAccountWithServiceResponseAsync(String vaultBaseUrl, byte[] storageBundleBackup) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } if (this.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } if (storageBundleBackup == null) { throw new IllegalArgumentException("Parameter storageBundleBackup is required and cannot be null."); } StorageRestoreParameters parameters = new StorageRestoreParameters(); parameters.withStorageBundleBackup(storageBundleBackup); String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); return service.restoreStorageAccount(this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<StorageBundle>>>() { @Override public Observable<ServiceResponse<StorageBundle>> call(Response<ResponseBody> response) { try { ServiceResponse<StorageBundle> clientResponse = restoreStorageAccountDelegate(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 static String normalize(String dateStr) { if (!dateStr.contains("-")) { StringBuilder dateBuf = new StringBuilder(dateStr); dateBuf.insert("yyyyMM".length(), '-'); dateBuf.insert("yyyy".length(), '-'); return dateBuf.toString(); } else { if (dateStr.length() >= 10) return dateStr; else if (dateStr.length() < 8) throw new IllegalArgumentException(); else { // try 2009-9-1 char[] value = dateStr.toCharArray(); int dayIndex = -1; if (value[6] == '-') dayIndex = 7; if (value[7] == '-') dayIndex = 8; if (dayIndex < 0) throw new IllegalArgumentException(); StringBuilder sb = new StringBuilder(10); // append year- sb.append(value, 0, 5); // append month- if (dayIndex - 5 < 3) sb.append('0').append(value, 5, 2); else sb.append(value, 5, 3); // append day if (value.length - dayIndex < 2) sb.append('0').append(value, dayIndex, 1); else sb.append(value, dayIndex, 2); return sb.toString(); } } } }
public class class_name { public static String normalize(String dateStr) { if (!dateStr.contains("-")) { StringBuilder dateBuf = new StringBuilder(dateStr); dateBuf.insert("yyyyMM".length(), '-'); // depends on control dependency: [if], data = [none] dateBuf.insert("yyyy".length(), '-'); // depends on control dependency: [if], data = [none] return dateBuf.toString(); // depends on control dependency: [if], data = [none] } else { if (dateStr.length() >= 10) return dateStr; else if (dateStr.length() < 8) throw new IllegalArgumentException(); else { // try 2009-9-1 char[] value = dateStr.toCharArray(); int dayIndex = -1; if (value[6] == '-') dayIndex = 7; if (value[7] == '-') dayIndex = 8; if (dayIndex < 0) throw new IllegalArgumentException(); StringBuilder sb = new StringBuilder(10); // append year- sb.append(value, 0, 5); // depends on control dependency: [if], data = [none] // append month- if (dayIndex - 5 < 3) sb.append('0').append(value, 5, 2); else sb.append(value, 5, 3); // append day if (value.length - dayIndex < 2) sb.append('0').append(value, dayIndex, 1); else sb.append(value, dayIndex, 2); return sb.toString(); // depends on control dependency: [if], data = [none] } } } }
public class class_name { @Override public final void close() { if (this.inputReader != null) { try { this.inputReader.close(); } catch (IOException ioe) { logger.error("Unable to close input reader.", ioe); } finally { this.inputReader = null; } } dispose(); } }
public class class_name { @Override public final void close() { if (this.inputReader != null) { try { this.inputReader.close(); // depends on control dependency: [try], data = [none] } catch (IOException ioe) { logger.error("Unable to close input reader.", ioe); } finally { // depends on control dependency: [catch], data = [none] this.inputReader = null; } } dispose(); } }
public class class_name { public static void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } }
public class class_name { public static void sleep(long millis) { try { Thread.sleep(millis); // depends on control dependency: [try], data = [none] } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static String calculateMD5(Object val) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.error("Unable to calculate MD5 for file, Caused By: ", e); } md.update((byte[]) val); byte[] digest = md.digest(); return DatatypeConverter.printHexBinary(digest).toLowerCase(); } }
public class class_name { public static String calculateMD5(Object val) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); // depends on control dependency: [try], data = [none] } catch (NoSuchAlgorithmException e) { logger.error("Unable to calculate MD5 for file, Caused By: ", e); } // depends on control dependency: [catch], data = [none] md.update((byte[]) val); byte[] digest = md.digest(); return DatatypeConverter.printHexBinary(digest).toLowerCase(); } }
public class class_name { @Override public void doRender(final WComponent component, final WebXmlRenderContext renderContext) { WSuggestions suggestions = (WSuggestions) component; XmlStringBuilder xml = renderContext.getWriter(); // Cache key for a lookup table String dataKey = suggestions.getListCacheKey(); // Use AJAX if not using a cached list and have a refresh action boolean useAjax = dataKey == null && suggestions.getRefreshAction() != null; // Start tag xml.appendTagOpen("ui:suggestions"); xml.appendAttribute("id", component.getId()); xml.appendOptionalAttribute("class", component.getHtmlClass()); xml.appendOptionalAttribute("track", component.isTracking(), "true"); xml.appendOptionalAttribute("min", suggestions.getMinRefresh() > 0, suggestions. getMinRefresh()); xml.appendOptionalAttribute("ajax", useAjax, "true"); xml.appendOptionalAttribute("data", dataKey); WSuggestions.Autocomplete autocomplete = suggestions.getAutocomplete(); if (autocomplete == WSuggestions.Autocomplete.LIST) { xml.appendOptionalAttribute("autocomplete", "list"); } xml.appendClose(); // Check if this is the current AJAX trigger boolean isTrigger = useAjax && AjaxHelper.isCurrentAjaxTrigger(suggestions); // Render suggestions if (isTrigger || (dataKey == null && !useAjax)) { for (String suggestion : suggestions.getSuggestions()) { xml.appendTagOpen("ui:suggestion"); xml.appendAttribute("value", suggestion); xml.appendEnd(); } } // End tag xml.appendEndTag("ui:suggestions"); } }
public class class_name { @Override public void doRender(final WComponent component, final WebXmlRenderContext renderContext) { WSuggestions suggestions = (WSuggestions) component; XmlStringBuilder xml = renderContext.getWriter(); // Cache key for a lookup table String dataKey = suggestions.getListCacheKey(); // Use AJAX if not using a cached list and have a refresh action boolean useAjax = dataKey == null && suggestions.getRefreshAction() != null; // Start tag xml.appendTagOpen("ui:suggestions"); xml.appendAttribute("id", component.getId()); xml.appendOptionalAttribute("class", component.getHtmlClass()); xml.appendOptionalAttribute("track", component.isTracking(), "true"); xml.appendOptionalAttribute("min", suggestions.getMinRefresh() > 0, suggestions. getMinRefresh()); xml.appendOptionalAttribute("ajax", useAjax, "true"); xml.appendOptionalAttribute("data", dataKey); WSuggestions.Autocomplete autocomplete = suggestions.getAutocomplete(); if (autocomplete == WSuggestions.Autocomplete.LIST) { xml.appendOptionalAttribute("autocomplete", "list"); // depends on control dependency: [if], data = [none] } xml.appendClose(); // Check if this is the current AJAX trigger boolean isTrigger = useAjax && AjaxHelper.isCurrentAjaxTrigger(suggestions); // Render suggestions if (isTrigger || (dataKey == null && !useAjax)) { for (String suggestion : suggestions.getSuggestions()) { xml.appendTagOpen("ui:suggestion"); // depends on control dependency: [for], data = [suggestion] xml.appendAttribute("value", suggestion); // depends on control dependency: [for], data = [suggestion] xml.appendEnd(); // depends on control dependency: [for], data = [none] } } // End tag xml.appendEndTag("ui:suggestions"); } }
public class class_name { public static String last(String list, String delimiter, boolean ignoreEmpty) { if (StringUtil.isEmpty(list)) return ""; int len = list.length(); char[] del; if (StringUtil.isEmpty(delimiter)) { del = new char[] { ',' }; } else del = delimiter.toCharArray(); int index; int x; while (true) { index = -1; for (int i = 0; i < del.length; i++) { x = list.lastIndexOf(del[i]); if (x > index) index = x; } if (index == -1) { return list; } else if (index + 1 == len) { if (!ignoreEmpty) return ""; list = list.substring(0, len - 1); len--; } else { return list.substring(index + 1); } } } }
public class class_name { public static String last(String list, String delimiter, boolean ignoreEmpty) { if (StringUtil.isEmpty(list)) return ""; int len = list.length(); char[] del; if (StringUtil.isEmpty(delimiter)) { del = new char[] { ',' }; // depends on control dependency: [if], data = [none] } else del = delimiter.toCharArray(); int index; int x; while (true) { index = -1; // depends on control dependency: [while], data = [none] for (int i = 0; i < del.length; i++) { x = list.lastIndexOf(del[i]); // depends on control dependency: [for], data = [i] if (x > index) index = x; } if (index == -1) { return list; // depends on control dependency: [if], data = [none] } else if (index + 1 == len) { if (!ignoreEmpty) return ""; list = list.substring(0, len - 1); // depends on control dependency: [if], data = [none] len--; // depends on control dependency: [if], data = [none] } else { return list.substring(index + 1); // depends on control dependency: [if], data = [(index + 1] } } } }
public class class_name { private void consolidate() { if (decreasePoolSize == 0) { return; } // lazily initialize comparator if (decreasePoolComparator == null) { if (comparator == null) { decreasePoolComparator = new Comparator<Node<K, V>>() { @Override @SuppressWarnings("unchecked") public int compare(Node<K, V> o1, Node<K, V> o2) { return ((Comparable<? super K>) o1.key).compareTo(o2.key); } }; } else { decreasePoolComparator = new Comparator<Node<K, V>>() { @Override public int compare(Node<K, V> o1, Node<K, V> o2) { return CostlessMeldPairingHeap.this.comparator.compare(o1.key, o2.key); } }; } } // sort Arrays.sort(decreasePool, 0, decreasePoolSize, decreasePoolComparator); int i = decreasePoolSize - 1; Node<K, V> s = decreasePool[i]; s.poolIndex = Node.NO_INDEX; while (i > 0) { Node<K, V> f = decreasePool[i - 1]; f.poolIndex = Node.NO_INDEX; decreasePool[i] = null; // link (no comparison, due to sort) s.y_s = f.o_c; s.o_s = f; if (f.o_c != null) { f.o_c.o_s = s; } f.o_c = s; // advance s = f; i--; } // empty decrease pool decreasePool[0] = null; decreasePoolSize = 0; decreasePoolMinPos = 0; // merge tree with root if (comparator == null) { root = link(root, s); } else { root = linkWithComparator(root, s); } } }
public class class_name { private void consolidate() { if (decreasePoolSize == 0) { return; // depends on control dependency: [if], data = [none] } // lazily initialize comparator if (decreasePoolComparator == null) { if (comparator == null) { decreasePoolComparator = new Comparator<Node<K, V>>() { @Override @SuppressWarnings("unchecked") public int compare(Node<K, V> o1, Node<K, V> o2) { return ((Comparable<? super K>) o1.key).compareTo(o2.key); } }; // depends on control dependency: [if], data = [none] } else { decreasePoolComparator = new Comparator<Node<K, V>>() { @Override public int compare(Node<K, V> o1, Node<K, V> o2) { return CostlessMeldPairingHeap.this.comparator.compare(o1.key, o2.key); } }; // depends on control dependency: [if], data = [none] } } // sort Arrays.sort(decreasePool, 0, decreasePoolSize, decreasePoolComparator); int i = decreasePoolSize - 1; Node<K, V> s = decreasePool[i]; s.poolIndex = Node.NO_INDEX; while (i > 0) { Node<K, V> f = decreasePool[i - 1]; f.poolIndex = Node.NO_INDEX; // depends on control dependency: [while], data = [none] decreasePool[i] = null; // depends on control dependency: [while], data = [none] // link (no comparison, due to sort) s.y_s = f.o_c; // depends on control dependency: [while], data = [none] s.o_s = f; // depends on control dependency: [while], data = [none] if (f.o_c != null) { f.o_c.o_s = s; // depends on control dependency: [if], data = [none] } f.o_c = s; // depends on control dependency: [while], data = [none] // advance s = f; // depends on control dependency: [while], data = [none] i--; // depends on control dependency: [while], data = [none] } // empty decrease pool decreasePool[0] = null; decreasePoolSize = 0; decreasePoolMinPos = 0; // merge tree with root if (comparator == null) { root = link(root, s); // depends on control dependency: [if], data = [none] } else { root = linkWithComparator(root, s); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static double dotProductWithAddition(double[] pointA1, double[] pointA2, double[] pointB) { assert (pointA1.length == pointA2.length && pointA1.length == pointB.length); double product = 0.0; for (int i = 0; i < pointA1.length; i++) { product += (pointA1[i] + pointA2[i]) * pointB[i]; } return product; } }
public class class_name { public static double dotProductWithAddition(double[] pointA1, double[] pointA2, double[] pointB) { assert (pointA1.length == pointA2.length && pointA1.length == pointB.length); double product = 0.0; for (int i = 0; i < pointA1.length; i++) { product += (pointA1[i] + pointA2[i]) * pointB[i]; // depends on control dependency: [for], data = [i] } return product; } }
public class class_name { @Override public String toUrl() { List<NameValuePair> params = new ArrayList<NameValuePair>(getParams()); params.add(new BasicNameValuePair("start", Integer.toString(getStart()))); params.add(new BasicNameValuePair("pagesize", Integer.toString(getPageSize()))); params.add(new BasicNameValuePair("fetch", fetch.toString())); String order = getOrder(); if (!order.contains("ObjectID")) { order += ",ObjectID"; } params.add(new BasicNameValuePair("order", order)); if (getQueryFilter() != null) { params.add(new BasicNameValuePair("query", getQueryFilter().toString())); } if (getWorkspace() != null && getWorkspace().length() > 0) { params.add(new BasicNameValuePair("workspace", Ref.getRelativeRef(getWorkspace()))); } if (getProject() == null) { params.add(new BasicNameValuePair("project", "null")); } else if (getProject().length() > 0) { params.add(new BasicNameValuePair("project", getProject())); params.add(new BasicNameValuePair("projectScopeUp", Boolean.toString(isScopedUp()))); params.add(new BasicNameValuePair("projectScopeDown", Boolean.toString(isScopedDown()))); } return (this.type != null ? getTypeEndpoint() : Ref.getRelativeRef(collection.get("_ref").getAsString())) + "?" + URLEncodedUtils.format(params, "utf-8"); } }
public class class_name { @Override public String toUrl() { List<NameValuePair> params = new ArrayList<NameValuePair>(getParams()); params.add(new BasicNameValuePair("start", Integer.toString(getStart()))); params.add(new BasicNameValuePair("pagesize", Integer.toString(getPageSize()))); params.add(new BasicNameValuePair("fetch", fetch.toString())); String order = getOrder(); if (!order.contains("ObjectID")) { order += ",ObjectID"; // depends on control dependency: [if], data = [none] } params.add(new BasicNameValuePair("order", order)); if (getQueryFilter() != null) { params.add(new BasicNameValuePair("query", getQueryFilter().toString())); // depends on control dependency: [if], data = [none] } if (getWorkspace() != null && getWorkspace().length() > 0) { params.add(new BasicNameValuePair("workspace", Ref.getRelativeRef(getWorkspace()))); // depends on control dependency: [if], data = [(getWorkspace()] } if (getProject() == null) { params.add(new BasicNameValuePair("project", "null")); // depends on control dependency: [if], data = [none] } else if (getProject().length() > 0) { params.add(new BasicNameValuePair("project", getProject())); // depends on control dependency: [if], data = [none] params.add(new BasicNameValuePair("projectScopeUp", Boolean.toString(isScopedUp()))); // depends on control dependency: [if], data = [none] params.add(new BasicNameValuePair("projectScopeDown", Boolean.toString(isScopedDown()))); // depends on control dependency: [if], data = [none] } return (this.type != null ? getTypeEndpoint() : Ref.getRelativeRef(collection.get("_ref").getAsString())) + "?" + URLEncodedUtils.format(params, "utf-8"); } }
public class class_name { protected String buildCorePublicanCfgFile(final BuildData buildData, final String publicanCfgTemplate) { final ContentSpec contentSpec = buildData.getContentSpec(); final Map<String, String> overrides = buildData.getBuildOptions().getOverrides(); final String brandOverride = overrides.containsKey(CSConstants.BRAND_OVERRIDE) ? overrides.get( CSConstants.BRAND_OVERRIDE) : (overrides.containsKey(CSConstants.BRAND_ALT_OVERRIDE) ? overrides.get( CSConstants.BRAND_ALT_OVERRIDE) : null); final String brand = brandOverride != null ? brandOverride : (contentSpec.getBrand() == null ? getDefaultBrand( buildData) : contentSpec.getBrand()); // Setup publican.cfg String publicanCfg = publicanCfgTemplate.replaceAll(BuilderConstants.BRAND_REGEX, brand); publicanCfg = publicanCfg.replaceFirst("type\\s*:\\s*.*($|\\r\\n|\\n)", "type: " + contentSpec.getBookType().toString().replaceAll("-Draft", "") + "\n"); publicanCfg = publicanCfg.replaceAll("xml_lang\\s*:\\s*.*?($|\\r\\n|\\n)", "xml_lang: " + buildData.getOutputLocale() + "\n"); // Remove the image width publicanCfg = publicanCfg.replaceFirst("max_image_width\\s*:\\s*\\d+\\s*(\\r)?\\n", ""); publicanCfg = publicanCfg.replaceFirst("toc_section_depth\\s*:\\s*\\d+\\s*(\\r)?\\n", ""); // Minor formatting cleanup publicanCfg = publicanCfg.trim() + "\n"; // Add the dtdver property if (buildData.getDocBookVersion() == DocBookVersion.DOCBOOK_50) { publicanCfg += "dtdver: \"5.0\"\n"; } if (contentSpec.getPublicanCfg() != null) { // If the user publican.cfg doesn't contain a chunk_section_depth, then add a calculated one if (buildData.getBuildOptions().getCalculateChunkDepth() && !contentSpec.getPublicanCfg().contains("chunk_section_depth")) { publicanCfg += "chunk_section_depth: " + calcChunkSectionDepth(buildData) + "\n"; } // Remove the git_branch if the content spec contains a git_branch if (contentSpec.getPublicanCfg().contains("git_branch")) { publicanCfg = publicanCfg.replaceFirst("git_branch\\s*:\\s*.*(\\r)?(\\n)?", ""); } publicanCfg += DocBookBuildUtilities.cleanUserPublicanCfg(contentSpec.getPublicanCfg()); } else if (buildData.getBuildOptions().getCalculateChunkDepth()) { publicanCfg += "chunk_section_depth: " + calcChunkSectionDepth(buildData) + "\n"; } if (buildData.getBuildOptions().getPublicanShowRemarks()) { // Remove any current show_remarks definitions if (publicanCfg.contains("show_remarks")) { publicanCfg = publicanCfg.replaceAll("show_remarks\\s*:\\s*\\d+\\s*(\\r)?(\\n)?", ""); } publicanCfg += "show_remarks: 1\n"; } // Add docname if it wasn't specified and the escaped title is valid Matcher m = null; if (BuilderConstants.VALID_PUBLICAN_DOCNAME_PATTERN.matcher(buildData.getEscapedBookTitle()).matches()) { m = DOCNAME_PATTERN.matcher(publicanCfg); if (!m.find()) { publicanCfg += "docname: " + buildData.getEscapedBookTitle().replaceAll("_", " ") + "\n"; } } // Add product if it wasn't specified m = PRODUCT_PATTERN.matcher(publicanCfg); if (!m.find()) { publicanCfg += "product: " + escapeProduct(buildData.getOriginalBookProduct()) + "\n"; } // Add the mainfile attribute publicanCfg += "mainfile: " + buildData.getRootBookFileName() + "\n"; // Add a version if one wasn't specified m = VERSION_PATTERN.matcher(publicanCfg); if (!m.find()) { String version = contentSpec.getBookVersion(); if (isNullOrEmpty(version)) { version = DocBookBuildUtilities.getKeyValueNodeText(buildData, contentSpec.getVersionNode()); } if (isNullOrEmpty(version)) { version = BuilderConstants.DEFAULT_VERSION; } publicanCfg += "version: " + escapeVersion(version) + "\n"; } return applyPublicanCfgOverrides(buildData, publicanCfg); } }
public class class_name { protected String buildCorePublicanCfgFile(final BuildData buildData, final String publicanCfgTemplate) { final ContentSpec contentSpec = buildData.getContentSpec(); final Map<String, String> overrides = buildData.getBuildOptions().getOverrides(); final String brandOverride = overrides.containsKey(CSConstants.BRAND_OVERRIDE) ? overrides.get( CSConstants.BRAND_OVERRIDE) : (overrides.containsKey(CSConstants.BRAND_ALT_OVERRIDE) ? overrides.get( CSConstants.BRAND_ALT_OVERRIDE) : null); final String brand = brandOverride != null ? brandOverride : (contentSpec.getBrand() == null ? getDefaultBrand( buildData) : contentSpec.getBrand()); // Setup publican.cfg String publicanCfg = publicanCfgTemplate.replaceAll(BuilderConstants.BRAND_REGEX, brand); publicanCfg = publicanCfg.replaceFirst("type\\s*:\\s*.*($|\\r\\n|\\n)", "type: " + contentSpec.getBookType().toString().replaceAll("-Draft", "") + "\n"); publicanCfg = publicanCfg.replaceAll("xml_lang\\s*:\\s*.*?($|\\r\\n|\\n)", "xml_lang: " + buildData.getOutputLocale() + "\n"); // Remove the image width publicanCfg = publicanCfg.replaceFirst("max_image_width\\s*:\\s*\\d+\\s*(\\r)?\\n", ""); publicanCfg = publicanCfg.replaceFirst("toc_section_depth\\s*:\\s*\\d+\\s*(\\r)?\\n", ""); // Minor formatting cleanup publicanCfg = publicanCfg.trim() + "\n"; // Add the dtdver property if (buildData.getDocBookVersion() == DocBookVersion.DOCBOOK_50) { publicanCfg += "dtdver: \"5.0\"\n"; // depends on control dependency: [if], data = [none] } if (contentSpec.getPublicanCfg() != null) { // If the user publican.cfg doesn't contain a chunk_section_depth, then add a calculated one if (buildData.getBuildOptions().getCalculateChunkDepth() && !contentSpec.getPublicanCfg().contains("chunk_section_depth")) { publicanCfg += "chunk_section_depth: " + calcChunkSectionDepth(buildData) + "\n"; // depends on control dependency: [if], data = [none] } // Remove the git_branch if the content spec contains a git_branch if (contentSpec.getPublicanCfg().contains("git_branch")) { publicanCfg = publicanCfg.replaceFirst("git_branch\\s*:\\s*.*(\\r)?(\\n)?", ""); } publicanCfg += DocBookBuildUtilities.cleanUserPublicanCfg(contentSpec.getPublicanCfg()); // depends on control dependency: [if], data = [none] } else if (buildData.getBuildOptions().getCalculateChunkDepth()) { publicanCfg += "chunk_section_depth: " + calcChunkSectionDepth(buildData) + "\n"; // depends on control dependency: [if], data = [none] } if (buildData.getBuildOptions().getPublicanShowRemarks()) { // Remove any current show_remarks definitions if (publicanCfg.contains("show_remarks")) { publicanCfg = publicanCfg.replaceAll("show_remarks\\s*:\\s*\\d+\\s*(\\r)?(\\n)?", ""); } publicanCfg += "show_remarks: 1\n"; } // Add docname if it wasn't specified and the escaped title is valid Matcher m = null; if (BuilderConstants.VALID_PUBLICAN_DOCNAME_PATTERN.matcher(buildData.getEscapedBookTitle()).matches()) { m = DOCNAME_PATTERN.matcher(publicanCfg); // depends on control dependency: [if], data = [none] if (!m.find()) { publicanCfg += "docname: " + buildData.getEscapedBookTitle().replaceAll("_", " ") + "\n"; // depends on control dependency: [if], data = [none] } } // Add product if it wasn't specified m = PRODUCT_PATTERN.matcher(publicanCfg); // depends on control dependency: [if], data = [none] if (!m.find()) { publicanCfg += "product: " + escapeProduct(buildData.getOriginalBookProduct()) + "\n"; // depends on control dependency: [if], data = [none] } // Add the mainfile attribute publicanCfg += "mainfile: " + buildData.getRootBookFileName() + "\n"; // depends on control dependency: [if], data = [none] // Add a version if one wasn't specified m = VERSION_PATTERN.matcher(publicanCfg); // depends on control dependency: [if], data = [none] if (!m.find()) { String version = contentSpec.getBookVersion(); if (isNullOrEmpty(version)) { version = DocBookBuildUtilities.getKeyValueNodeText(buildData, contentSpec.getVersionNode()); // depends on control dependency: [if], data = [none] } if (isNullOrEmpty(version)) { version = BuilderConstants.DEFAULT_VERSION; // depends on control dependency: [if], data = [none] } publicanCfg += "version: " + escapeVersion(version) + "\n"; // depends on control dependency: [if], data = [none] } return applyPublicanCfgOverrides(buildData, publicanCfg); // depends on control dependency: [if], data = [none] } }
public class class_name { public Item getFieldItem(String name) { if (xfa.isXfaPresent()) { name = xfa.findFieldName(name, this); if (name == null) return null; } return (Item)fields.get(name); } }
public class class_name { public Item getFieldItem(String name) { if (xfa.isXfaPresent()) { name = xfa.findFieldName(name, this); // depends on control dependency: [if], data = [none] if (name == null) return null; } return (Item)fields.get(name); } }
public class class_name { public static List<IItem> delete(final FastAdapter fastAdapter, final ExpandableExtension expandableExtension, Collection<Long> identifiersToDelete, boolean notifyParent, boolean deleteEmptyHeaders) { List<IItem> deleted = new ArrayList<>(); if (identifiersToDelete == null || identifiersToDelete.size() == 0) { return deleted; } // we use a LinkedList, because this has performance advantages when modifying the listIterator during iteration! // Modifying list is O(1) LinkedList<Long> identifiers = new LinkedList<>(identifiersToDelete); // we delete item per item from the adapter directly or from the parent // if keepEmptyHeaders is false, we add empty headers to the selected items set via the iterator, so that they are processed in the loop as well IItem item, parent; int pos, parentPos; boolean expanded; Long identifier; ListIterator<Long> it = identifiers.listIterator(); while (it.hasNext()) { identifier = it.next(); pos = fastAdapter.getPosition(identifier); item = fastAdapter.getItem(pos); // search for parent - if we find one, we remove the item from the parent's subitems directly parent = getParent(item); if (parent != null) { parentPos = fastAdapter.getPosition(parent); boolean success = ((IExpandable) parent).getSubItems().remove(item); // Log.d("DELETE", "success=" + success + " | deletedId=" + item.getIdentifier() + " | parentId=" + parent.getIdentifier() + " (sub items: " + ((IExpandable) parent).getSubItems().size() + ") | parentPos=" + parentPos); // check if parent is expanded and notify the adapter about the removed item, if necessary (only if parent is visible) if (parentPos != -1 && ((IExpandable) parent).isExpanded()) { expandableExtension.notifyAdapterSubItemsChanged(parentPos, ((IExpandable) parent).getSubItems().size() + 1); } // if desired, notify the parent about it's changed items (only if parent is visible!) if (parentPos != -1 && notifyParent) { expanded = ((IExpandable) parent).isExpanded(); fastAdapter.notifyAdapterItemChanged(parentPos); // expand the item again if it was expanded before calling notifyAdapterItemChanged if (expanded) { expandableExtension.expand(parentPos); } } deleted.add(item); if (deleteEmptyHeaders && ((IExpandable) parent).getSubItems().size() == 0) { it.add(parent.getIdentifier()); it.previous(); } } else if (pos != -1) { // if we did not find a parent, we remove the item from the adapter IAdapter adapter = fastAdapter.getAdapter(pos); boolean success = false; if (adapter instanceof IItemAdapter) { success = ((IItemAdapter) adapter).remove(pos) != null; if (success) { fastAdapter.notifyAdapterItemRemoved(pos); } } boolean isHeader = item instanceof IExpandable && ((IExpandable) item).getSubItems() != null; // Log.d("DELETE", "success=" + success + " | deletedId=" + item.getIdentifier() + "(" + (isHeader ? "EMPTY HEADER" : "ITEM WITHOUT HEADER") + ")"); deleted.add(item); } } // Log.d("DELETE", "deleted (incl. empty headers): " + deleted.size()); return deleted; } }
public class class_name { public static List<IItem> delete(final FastAdapter fastAdapter, final ExpandableExtension expandableExtension, Collection<Long> identifiersToDelete, boolean notifyParent, boolean deleteEmptyHeaders) { List<IItem> deleted = new ArrayList<>(); if (identifiersToDelete == null || identifiersToDelete.size() == 0) { return deleted; // depends on control dependency: [if], data = [none] } // we use a LinkedList, because this has performance advantages when modifying the listIterator during iteration! // Modifying list is O(1) LinkedList<Long> identifiers = new LinkedList<>(identifiersToDelete); // we delete item per item from the adapter directly or from the parent // if keepEmptyHeaders is false, we add empty headers to the selected items set via the iterator, so that they are processed in the loop as well IItem item, parent; int pos, parentPos; boolean expanded; Long identifier; ListIterator<Long> it = identifiers.listIterator(); while (it.hasNext()) { identifier = it.next(); // depends on control dependency: [while], data = [none] pos = fastAdapter.getPosition(identifier); // depends on control dependency: [while], data = [none] item = fastAdapter.getItem(pos); // depends on control dependency: [while], data = [none] // search for parent - if we find one, we remove the item from the parent's subitems directly parent = getParent(item); // depends on control dependency: [while], data = [none] if (parent != null) { parentPos = fastAdapter.getPosition(parent); // depends on control dependency: [if], data = [(parent] boolean success = ((IExpandable) parent).getSubItems().remove(item); // Log.d("DELETE", "success=" + success + " | deletedId=" + item.getIdentifier() + " | parentId=" + parent.getIdentifier() + " (sub items: " + ((IExpandable) parent).getSubItems().size() + ") | parentPos=" + parentPos); // check if parent is expanded and notify the adapter about the removed item, if necessary (only if parent is visible) if (parentPos != -1 && ((IExpandable) parent).isExpanded()) { expandableExtension.notifyAdapterSubItemsChanged(parentPos, ((IExpandable) parent).getSubItems().size() + 1); // depends on control dependency: [if], data = [(parentPos] } // if desired, notify the parent about it's changed items (only if parent is visible!) if (parentPos != -1 && notifyParent) { expanded = ((IExpandable) parent).isExpanded(); // depends on control dependency: [if], data = [none] fastAdapter.notifyAdapterItemChanged(parentPos); // depends on control dependency: [if], data = [(parentPos] // expand the item again if it was expanded before calling notifyAdapterItemChanged if (expanded) { expandableExtension.expand(parentPos); // depends on control dependency: [if], data = [none] } } deleted.add(item); // depends on control dependency: [if], data = [none] if (deleteEmptyHeaders && ((IExpandable) parent).getSubItems().size() == 0) { it.add(parent.getIdentifier()); // depends on control dependency: [if], data = [none] it.previous(); // depends on control dependency: [if], data = [none] } } else if (pos != -1) { // if we did not find a parent, we remove the item from the adapter IAdapter adapter = fastAdapter.getAdapter(pos); boolean success = false; if (adapter instanceof IItemAdapter) { success = ((IItemAdapter) adapter).remove(pos) != null; // depends on control dependency: [if], data = [none] if (success) { fastAdapter.notifyAdapterItemRemoved(pos); // depends on control dependency: [if], data = [none] } } boolean isHeader = item instanceof IExpandable && ((IExpandable) item).getSubItems() != null; // Log.d("DELETE", "success=" + success + " | deletedId=" + item.getIdentifier() + "(" + (isHeader ? "EMPTY HEADER" : "ITEM WITHOUT HEADER") + ")"); deleted.add(item); // depends on control dependency: [if], data = [none] } } // Log.d("DELETE", "deleted (incl. empty headers): " + deleted.size()); return deleted; } }
public class class_name { public List<String> getFiles(GerritQueryHandler gerritQueryHandler) { if (files == null) { files = FileHelper.getFilesByChange(gerritQueryHandler, id); } return files; } }
public class class_name { public List<String> getFiles(GerritQueryHandler gerritQueryHandler) { if (files == null) { files = FileHelper.getFilesByChange(gerritQueryHandler, id); // depends on control dependency: [if], data = [none] } return files; } }
public class class_name { public HttpServerExchange addRequestWrapper(final ConduitWrapper<StreamSourceConduit> wrapper) { ConduitWrapper<StreamSourceConduit>[] wrappers = requestWrappers; if (requestChannel != null) { throw UndertowMessages.MESSAGES.requestChannelAlreadyProvided(); } if (wrappers == null) { wrappers = requestWrappers = new ConduitWrapper[2]; } else if (wrappers.length == requestWrapperCount) { requestWrappers = new ConduitWrapper[wrappers.length + 2]; System.arraycopy(wrappers, 0, requestWrappers, 0, wrappers.length); wrappers = requestWrappers; } wrappers[requestWrapperCount++] = wrapper; return this; } }
public class class_name { public HttpServerExchange addRequestWrapper(final ConduitWrapper<StreamSourceConduit> wrapper) { ConduitWrapper<StreamSourceConduit>[] wrappers = requestWrappers; if (requestChannel != null) { throw UndertowMessages.MESSAGES.requestChannelAlreadyProvided(); } if (wrappers == null) { wrappers = requestWrappers = new ConduitWrapper[2]; // depends on control dependency: [if], data = [none] } else if (wrappers.length == requestWrapperCount) { requestWrappers = new ConduitWrapper[wrappers.length + 2]; // depends on control dependency: [if], data = [none] System.arraycopy(wrappers, 0, requestWrappers, 0, wrappers.length); // depends on control dependency: [if], data = [none] wrappers = requestWrappers; // depends on control dependency: [if], data = [none] } wrappers[requestWrapperCount++] = wrapper; return this; } }
public class class_name { public CommandLineProgramGroup getCommandLineProgramGroup() { if (commandLineProperties != null) { try { return commandLineProperties.programGroup().newInstance(); } catch (IllegalAccessException | InstantiationException e) { logger.warn( String.format("Can't instantiate program group class to retrieve summary for group %s for class %s", commandLineProperties.programGroup().getName(), clazz.getName())); } } return null; } }
public class class_name { public CommandLineProgramGroup getCommandLineProgramGroup() { if (commandLineProperties != null) { try { return commandLineProperties.programGroup().newInstance(); // depends on control dependency: [try], data = [none] } catch (IllegalAccessException | InstantiationException e) { logger.warn( String.format("Can't instantiate program group class to retrieve summary for group %s for class %s", commandLineProperties.programGroup().getName(), clazz.getName())); } // depends on control dependency: [catch], data = [none] } return null; } }
public class class_name { @Deprecated public GeographyValue add(GeographyPointValue offset) { List<List<GeographyPointValue>> newLoops = new ArrayList<>(); for (List<XYZPoint> oneLoop : m_loops) { List<GeographyPointValue> loop = new ArrayList<>(); for (XYZPoint p : oneLoop) { loop.add(p.toGeographyPointValue().add(offset)); } loop.add(oneLoop.get(0).toGeographyPointValue().add(offset)); newLoops.add(loop); } return new GeographyValue(newLoops, true); } }
public class class_name { @Deprecated public GeographyValue add(GeographyPointValue offset) { List<List<GeographyPointValue>> newLoops = new ArrayList<>(); for (List<XYZPoint> oneLoop : m_loops) { List<GeographyPointValue> loop = new ArrayList<>(); for (XYZPoint p : oneLoop) { loop.add(p.toGeographyPointValue().add(offset)); // depends on control dependency: [for], data = [p] } loop.add(oneLoop.get(0).toGeographyPointValue().add(offset)); // depends on control dependency: [for], data = [oneLoop] newLoops.add(loop); // depends on control dependency: [for], data = [none] } return new GeographyValue(newLoops, true); } }
public class class_name { private void startSpan(ActivityRuntimeContext context) { Tracing tracing = TraceHelper.getTracing("mdw-activity"); Tracer tracer = tracing.tracer(); Span span = tracer.currentSpan(); if (span == null) { // async brave server if b3 requestHeaders populated (subspan) Object requestHeaders = context.getValue("requestHeaders"); if (requestHeaders instanceof Map) { Map<?, ?> headers = (Map<?, ?>) requestHeaders; if (headers.containsKey("x-b3-traceid")) { TraceContext.Extractor<Map<?, ?>> extractor = tracing.propagation().extractor((map, key) -> { Object val = map.get(key.toLowerCase()); return val == null ? null : val.toString(); }); TraceContextOrSamplingFlags extracted = extractor.extract(headers); span = extracted.context() != null ? tracer.joinSpan(extracted.context()) : tracer.nextSpan(extracted); span.name("m" + context.getMasterRequestId()).kind(Span.Kind.SERVER); span = tracer.newChild(span.context()).name("p" + context.getProcessInstanceId()); } } } if (span == null) { // create a new root span for async start span = tracer.nextSpan().name("a" + context.getActivityInstanceId()); } span.start().flush(); // async Tracer.SpanInScope spanInScope = tracer.withSpanInScope(span); context.getRuntimeAttributes().put(Tracer.SpanInScope.class, spanInScope); } }
public class class_name { private void startSpan(ActivityRuntimeContext context) { Tracing tracing = TraceHelper.getTracing("mdw-activity"); Tracer tracer = tracing.tracer(); Span span = tracer.currentSpan(); if (span == null) { // async brave server if b3 requestHeaders populated (subspan) Object requestHeaders = context.getValue("requestHeaders"); if (requestHeaders instanceof Map) { Map<?, ?> headers = (Map<?, ?>) requestHeaders; // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none] if (headers.containsKey("x-b3-traceid")) { TraceContext.Extractor<Map<?, ?>> extractor = tracing.propagation().extractor((map, key) -> { Object val = map.get(key.toLowerCase()); // depends on control dependency: [if], data = [none] return val == null ? null : val.toString(); // depends on control dependency: [if], data = [none] }); TraceContextOrSamplingFlags extracted = extractor.extract(headers); span = extracted.context() != null ? tracer.joinSpan(extracted.context()) : tracer.nextSpan(extracted); // depends on control dependency: [if], data = [none] span.name("m" + context.getMasterRequestId()).kind(Span.Kind.SERVER); // depends on control dependency: [if], data = [none] span = tracer.newChild(span.context()).name("p" + context.getProcessInstanceId()); // depends on control dependency: [if], data = [none] } } } if (span == null) { // create a new root span for async start span = tracer.nextSpan().name("a" + context.getActivityInstanceId()); } span.start().flush(); // async Tracer.SpanInScope spanInScope = tracer.withSpanInScope(span); context.getRuntimeAttributes().put(Tracer.SpanInScope.class, spanInScope); } }
public class class_name { private String toStringImpl() { StringBuffer result = new StringBuffer(128); result.append('@'); result.append(type.getName()); result.append('('); boolean firstMember = true; for (Map.Entry<String, Object> e : memberValues.entrySet()) { if (firstMember) firstMember = false; else result.append(", "); result.append(e.getKey()); result.append('='); result.append(memberValueToString(e.getValue())); } result.append(')'); return result.toString(); } }
public class class_name { private String toStringImpl() { StringBuffer result = new StringBuffer(128); result.append('@'); result.append(type.getName()); result.append('('); boolean firstMember = true; for (Map.Entry<String, Object> e : memberValues.entrySet()) { if (firstMember) firstMember = false; else result.append(", "); result.append(e.getKey()); // depends on control dependency: [for], data = [e] result.append('='); // depends on control dependency: [for], data = [e] result.append(memberValueToString(e.getValue())); // depends on control dependency: [for], data = [e] } result.append(')'); return result.toString(); } }
public class class_name { public int systemSize() { int count = 0; ListIterator<IonValue> iterator = systemIterator(); while (iterator.hasNext()) { @SuppressWarnings("unused") IonValue value = iterator.next(); count++; } return count; } }
public class class_name { public int systemSize() { int count = 0; ListIterator<IonValue> iterator = systemIterator(); while (iterator.hasNext()) { @SuppressWarnings("unused") IonValue value = iterator.next(); count++; // depends on control dependency: [while], data = [none] } return count; } }
public class class_name { private static FactorComparator<Executor> getNumberOfAssignedFlowComparator(final int weight) { return FactorComparator .create(NUMOFASSIGNEDFLOW_COMPARATOR_NAME, weight, new Comparator<Executor>() { @Override public int compare(final Executor o1, final Executor o2) { final ExecutorInfo stat1 = o1.getExecutorInfo(); final ExecutorInfo stat2 = o2.getExecutorInfo(); final Integer result = 0; if (statisticsObjectCheck(stat1, stat2, NUMOFASSIGNEDFLOW_COMPARATOR_NAME)) { return result; } return ((Integer) stat1.getRemainingFlowCapacity()) .compareTo(stat2.getRemainingFlowCapacity()); } }); } }
public class class_name { private static FactorComparator<Executor> getNumberOfAssignedFlowComparator(final int weight) { return FactorComparator .create(NUMOFASSIGNEDFLOW_COMPARATOR_NAME, weight, new Comparator<Executor>() { @Override public int compare(final Executor o1, final Executor o2) { final ExecutorInfo stat1 = o1.getExecutorInfo(); final ExecutorInfo stat2 = o2.getExecutorInfo(); final Integer result = 0; if (statisticsObjectCheck(stat1, stat2, NUMOFASSIGNEDFLOW_COMPARATOR_NAME)) { return result; // depends on control dependency: [if], data = [none] } return ((Integer) stat1.getRemainingFlowCapacity()) .compareTo(stat2.getRemainingFlowCapacity()); } }); } }
public class class_name { @Override protected Split ltSplit(int col, Data d, int[] dist, int distWeight, Random rand) { final int[] distL = new int[d.classes()], distR = dist.clone(); final double upperBoundReduction = upperBoundReduction(d.classes()); double maxReduction = -1; int bestSplit = -1; int totL = 0, totR = 0; // Totals in the distribution int classL = 0, classR = 0; // Count of non-zero classes in the left/right distributions for (int e: distR) { // All zeros for the left, but need to compute for the right totR += e; if( e != 0 ) classR++; } // For this one column, look at all his split points and find the one with the best gain. for (int i = 0; i < _columnDists[col].length - 1; ++i) { int [] cdis = _columnDists[col][i]; for (int j = 0; j < distL.length; ++j) { int v = cdis[j]; if( v == 0 ) continue; // No rows with this class totL += v; totR -= v; if( distL[j]== 0 ) classL++; // One-time transit from zero to non-zero for class j distL[j] += v; distR[j] -= v; if( distR[j]== 0 ) classR--; // One-time transit from non-zero to zero for class j } if (totL == 0) continue; // Totals are zero ==> this will not actually split anything if (totR == 0) continue; // Totals are zero ==> this will not actually split anything // Compute gain. // If the distribution has only 1 class, the gain will be zero. double eL = 0, eR = 0; if( classL > 1 ) for (int e: distL) eL += gain(e,totL); if( classR > 1 ) for (int e: distR) eR += gain(e,totR); double eReduction = upperBoundReduction - ( (eL * totL + eR * totR) / (totL + totR) ); if (eReduction == maxReduction) { // For now, don't break ties. Most ties are because we have several // splits with NO GAIN. This happens *billions* of times in a standard // covtype RF, because we have >100K leaves per tree (and 50 trees and // 54 columns per leave and however many bins per column), and most // leaves have no gain at most split points. //if (rand.nextInt(10)<2) bestSplit=i; } else if (eReduction > maxReduction) { bestSplit = i; maxReduction = eReduction; } } return bestSplit == -1 ? Split.impossible(Utils.maxIndex(dist,_random)) : Split.split(col,bestSplit,maxReduction); } }
public class class_name { @Override protected Split ltSplit(int col, Data d, int[] dist, int distWeight, Random rand) { final int[] distL = new int[d.classes()], distR = dist.clone(); final double upperBoundReduction = upperBoundReduction(d.classes()); double maxReduction = -1; int bestSplit = -1; int totL = 0, totR = 0; // Totals in the distribution int classL = 0, classR = 0; // Count of non-zero classes in the left/right distributions for (int e: distR) { // All zeros for the left, but need to compute for the right totR += e; // depends on control dependency: [for], data = [e] if( e != 0 ) classR++; } // For this one column, look at all his split points and find the one with the best gain. for (int i = 0; i < _columnDists[col].length - 1; ++i) { int [] cdis = _columnDists[col][i]; for (int j = 0; j < distL.length; ++j) { int v = cdis[j]; if( v == 0 ) continue; // No rows with this class totL += v; totR -= v; // depends on control dependency: [for], data = [none] // depends on control dependency: [for], data = [none] if( distL[j]== 0 ) classL++; // One-time transit from zero to non-zero for class j distL[j] += v; distR[j] -= v; // depends on control dependency: [for], data = [j] // depends on control dependency: [for], data = [j] if( distR[j]== 0 ) classR--; // One-time transit from non-zero to zero for class j } if (totL == 0) continue; // Totals are zero ==> this will not actually split anything if (totR == 0) continue; // Totals are zero ==> this will not actually split anything // Compute gain. // If the distribution has only 1 class, the gain will be zero. double eL = 0, eR = 0; if( classL > 1 ) for (int e: distL) eL += gain(e,totL); if( classR > 1 ) for (int e: distR) eR += gain(e,totR); double eReduction = upperBoundReduction - ( (eL * totL + eR * totR) / (totL + totR) ); if (eReduction == maxReduction) { // For now, don't break ties. Most ties are because we have several // splits with NO GAIN. This happens *billions* of times in a standard // covtype RF, because we have >100K leaves per tree (and 50 trees and // 54 columns per leave and however many bins per column), and most // leaves have no gain at most split points. //if (rand.nextInt(10)<2) bestSplit=i; } else if (eReduction > maxReduction) { bestSplit = i; maxReduction = eReduction; // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none] } } return bestSplit == -1 ? Split.impossible(Utils.maxIndex(dist,_random)) : Split.split(col,bestSplit,maxReduction); } }
public class class_name { private ByteBuffer fetchBlockByteRangeScatterGather(LocatedBlock block, long start, long len) throws IOException { // // Connect to best DataNode for desired Block, with potential offset // Socket dn = null; // cached block locations may have been updated by chooseDatNode() // or fetchBlockAt(). Always get the latest list of locations before the // start of the loop. BlockSeekContext seekContext = new BlockSeekContext(getBlockAt( block.getStartOffset(), false, true)); while (true) { DNAddrPair retval = chooseDataNode(seekContext); DatanodeInfo chosenNode = retval.info; InetSocketAddress targetAddr = retval.addr; ByteBuffer result = null; BlockReaderLocalBase localReader = null; BlockReaderAccelerator remoteReader = null; try { if (DFSClient.LOG.isDebugEnabled()) { DFSClient.LOG.debug("fetchBlockByteRangeScatterGather " + " localhst " + dfsClient.localHost + " targetAddr " + targetAddr); } // first try reading the block locally. if (dfsClient.shortCircuitLocalReads && NetUtils.isLocalAddressWithCaching(targetAddr.getAddress())) { localReader = BlockReaderLocalBase.newBlockReader(dfsClient.conf, src, dfsClient.namespaceId, block.getBlock(), chosenNode, start, len, dfsClient.metrics, verifyChecksum, this.clearOsBuffer, false); if (localReader != null) { localReader.setReadLocal(true); localReader.setFsStats(dfsClient.stats); result = localReader.readAll(); } else if (!dfsClient.shortcircuitDisableWhenFail) { throw new IOException( "Short circuit local read not supported for this scase"); } } if (localReader == null) { // go to the datanode dn = dfsClient.socketFactory.createSocket(); NetUtils.connect(dn, targetAddr, dfsClient.socketTimeout, dfsClient.ipTosValue); dn.setSoTimeout(dfsClient.socketTimeout); remoteReader = new BlockReaderAccelerator(dfsClient.conf, targetAddr, chosenNode, dfsClient.getDataTransferProtocolVersion(), dfsClient.namespaceId, dfsClient.clientName, dn, src, block, start, len, verifyChecksum, dfsClient.metrics); result = remoteReader.readAll(); } if (result.remaining() != len) { throw new IOException("truncated return from reader.read(): " + "expected " + len + ", got " + result.remaining()); } if (NetUtils.isLocalAddressWithCaching(targetAddr.getAddress())) { dfsClient.stats.incrementLocalBytesRead(len); dfsClient.stats.incrementRackLocalBytesRead(len); } else if (dfsClient.isInLocalRack(targetAddr)) { dfsClient.stats.incrementRackLocalBytesRead(len); } return result; } catch (ChecksumException e) { DFSClient.LOG.warn("fetchBlockByteRangeScatterGather(). Got a checksum exception for " + src + " at " + block.getBlock() + ":" + e.getPos() + " from " + chosenNode.getName()); dfsClient.reportChecksumFailure(src, block.getBlock(), chosenNode); } catch (IOException e) { DFSClient.LOG.warn("Failed to connect to " + targetAddr + " for file " + src + " for block " + block.getBlock().getBlockId() + ":" + StringUtils.stringifyException(e)); } finally { IOUtils.closeStream(localReader); IOUtils.closeStream(remoteReader); IOUtils.closeSocket(dn); } dfsClient.incReadExpCntToStats(); // Put chosen node into dead list, continue addToDeadNodes(chosenNode); } } }
public class class_name { private ByteBuffer fetchBlockByteRangeScatterGather(LocatedBlock block, long start, long len) throws IOException { // // Connect to best DataNode for desired Block, with potential offset // Socket dn = null; // cached block locations may have been updated by chooseDatNode() // or fetchBlockAt(). Always get the latest list of locations before the // start of the loop. BlockSeekContext seekContext = new BlockSeekContext(getBlockAt( block.getStartOffset(), false, true)); while (true) { DNAddrPair retval = chooseDataNode(seekContext); DatanodeInfo chosenNode = retval.info; InetSocketAddress targetAddr = retval.addr; ByteBuffer result = null; BlockReaderLocalBase localReader = null; BlockReaderAccelerator remoteReader = null; try { if (DFSClient.LOG.isDebugEnabled()) { DFSClient.LOG.debug("fetchBlockByteRangeScatterGather " + " localhst " + dfsClient.localHost + " targetAddr " + targetAddr); // depends on control dependency: [if], data = [none] } // first try reading the block locally. if (dfsClient.shortCircuitLocalReads && NetUtils.isLocalAddressWithCaching(targetAddr.getAddress())) { localReader = BlockReaderLocalBase.newBlockReader(dfsClient.conf, src, dfsClient.namespaceId, block.getBlock(), chosenNode, start, len, dfsClient.metrics, verifyChecksum, this.clearOsBuffer, false); // depends on control dependency: [if], data = [none] if (localReader != null) { localReader.setReadLocal(true); // depends on control dependency: [if], data = [none] localReader.setFsStats(dfsClient.stats); // depends on control dependency: [if], data = [none] result = localReader.readAll(); // depends on control dependency: [if], data = [none] } else if (!dfsClient.shortcircuitDisableWhenFail) { throw new IOException( "Short circuit local read not supported for this scase"); } } if (localReader == null) { // go to the datanode dn = dfsClient.socketFactory.createSocket(); // depends on control dependency: [if], data = [none] NetUtils.connect(dn, targetAddr, dfsClient.socketTimeout, dfsClient.ipTosValue); // depends on control dependency: [if], data = [none] dn.setSoTimeout(dfsClient.socketTimeout); // depends on control dependency: [if], data = [none] remoteReader = new BlockReaderAccelerator(dfsClient.conf, targetAddr, chosenNode, dfsClient.getDataTransferProtocolVersion(), dfsClient.namespaceId, dfsClient.clientName, dn, src, block, start, len, verifyChecksum, dfsClient.metrics); // depends on control dependency: [if], data = [none] result = remoteReader.readAll(); // depends on control dependency: [if], data = [none] } if (result.remaining() != len) { throw new IOException("truncated return from reader.read(): " + "expected " + len + ", got " + result.remaining()); } if (NetUtils.isLocalAddressWithCaching(targetAddr.getAddress())) { dfsClient.stats.incrementLocalBytesRead(len); // depends on control dependency: [if], data = [none] dfsClient.stats.incrementRackLocalBytesRead(len); // depends on control dependency: [if], data = [none] } else if (dfsClient.isInLocalRack(targetAddr)) { dfsClient.stats.incrementRackLocalBytesRead(len); // depends on control dependency: [if], data = [none] } return result; // depends on control dependency: [try], data = [none] } catch (ChecksumException e) { DFSClient.LOG.warn("fetchBlockByteRangeScatterGather(). Got a checksum exception for " + src + " at " + block.getBlock() + ":" + e.getPos() + " from " + chosenNode.getName()); dfsClient.reportChecksumFailure(src, block.getBlock(), chosenNode); } catch (IOException e) { // depends on control dependency: [catch], data = [none] DFSClient.LOG.warn("Failed to connect to " + targetAddr + " for file " + src + " for block " + block.getBlock().getBlockId() + ":" + StringUtils.stringifyException(e)); } finally { // depends on control dependency: [catch], data = [none] IOUtils.closeStream(localReader); IOUtils.closeStream(remoteReader); IOUtils.closeSocket(dn); } dfsClient.incReadExpCntToStats(); // Put chosen node into dead list, continue addToDeadNodes(chosenNode); } } }
public class class_name { public Image createImageWithBarcode(PdfContentByte cb, Color barColor, Color textColor) { try { return Image.getInstance(createTemplateWithBarcode(cb, barColor, textColor)); } catch (Exception e) { throw new ExceptionConverter(e); } } }
public class class_name { public Image createImageWithBarcode(PdfContentByte cb, Color barColor, Color textColor) { try { return Image.getInstance(createTemplateWithBarcode(cb, barColor, textColor)); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new ExceptionConverter(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static String getMapFieldGenericParameterString(FieldInfo field) { FieldType fieldType = ProtobufProxyUtils.TYPE_MAPPING.get(field.getGenericKeyType()); String keyClass; String defaultKeyValue; if (fieldType == null) { // may be object or enum if (Enum.class.isAssignableFrom(field.getGenericKeyType())) { keyClass = WIREFORMAT_CLSNAME + ".ENUM"; Class<?> declaringClass = field.getGenericKeyType(); Field[] fields = declaringClass.getFields(); if (fields != null && fields.length > 0) { defaultKeyValue = ClassHelper.getInternalName(field.getGenericKeyType().getCanonicalName()) + "." + fields[0].getName(); } else { defaultKeyValue = "0"; } } else { keyClass = WIREFORMAT_CLSNAME + ".MESSAGE"; // check constructor boolean hasDefaultConstructor = ClassHelper.hasDefaultConstructor(field.getGenericKeyType()); if (!hasDefaultConstructor) { throw new IllegalArgumentException("Class '" + field.getGenericKeyType().getCanonicalName() + "' must has default constructor method with no parameters."); } defaultKeyValue = "new " + ClassHelper.getInternalName(field.getGenericKeyType().getCanonicalName()) + "()"; } } else { keyClass = WIREFORMAT_CLSNAME + "." + fieldType.toString(); defaultKeyValue = fieldType.getDefaultValue(); } fieldType = ProtobufProxyUtils.TYPE_MAPPING.get(field.getGenericeValueType()); String valueClass; String defaultValueValue; if (fieldType == null) { // may be object or enum if (Enum.class.isAssignableFrom(field.getGenericeValueType())) { valueClass = WIREFORMAT_CLSNAME + ".ENUM"; Class<?> declaringClass = field.getGenericeValueType(); Field[] fields = declaringClass.getFields(); if (fields != null && fields.length > 0) { defaultValueValue = ClassHelper.getInternalName(field.getGenericeValueType().getCanonicalName()) + "." + fields[0].getName(); } else { defaultValueValue = "0"; } } else { valueClass = WIREFORMAT_CLSNAME + ".MESSAGE"; // check constructor boolean hasDefaultConstructor = ClassHelper.hasDefaultConstructor(field.getGenericeValueType()); if (!hasDefaultConstructor) { throw new IllegalArgumentException("Class '" + field.getGenericeValueType().getCanonicalName() + "' must has default constructor method with no parameters."); } defaultValueValue = "new " + ClassHelper.getInternalName(field.getGenericeValueType().getCanonicalName()) + "()"; } } else { valueClass = WIREFORMAT_CLSNAME + "." + fieldType.toString(); defaultValueValue = fieldType.getDefaultValue(); } String joinedSentence = keyClass + "," + defaultKeyValue + "," + valueClass + "," + defaultValueValue; return joinedSentence; } }
public class class_name { public static String getMapFieldGenericParameterString(FieldInfo field) { FieldType fieldType = ProtobufProxyUtils.TYPE_MAPPING.get(field.getGenericKeyType()); String keyClass; String defaultKeyValue; if (fieldType == null) { // may be object or enum if (Enum.class.isAssignableFrom(field.getGenericKeyType())) { keyClass = WIREFORMAT_CLSNAME + ".ENUM"; // depends on control dependency: [if], data = [none] Class<?> declaringClass = field.getGenericKeyType(); Field[] fields = declaringClass.getFields(); if (fields != null && fields.length > 0) { defaultKeyValue = ClassHelper.getInternalName(field.getGenericKeyType().getCanonicalName()) + "." + fields[0].getName(); // depends on control dependency: [if], data = [none] } else { defaultKeyValue = "0"; // depends on control dependency: [if], data = [none] } } else { keyClass = WIREFORMAT_CLSNAME + ".MESSAGE"; // depends on control dependency: [if], data = [none] // check constructor boolean hasDefaultConstructor = ClassHelper.hasDefaultConstructor(field.getGenericKeyType()); if (!hasDefaultConstructor) { throw new IllegalArgumentException("Class '" + field.getGenericKeyType().getCanonicalName() + "' must has default constructor method with no parameters."); } defaultKeyValue = "new " + ClassHelper.getInternalName(field.getGenericKeyType().getCanonicalName()) + "()"; // depends on control dependency: [if], data = [none] } } else { keyClass = WIREFORMAT_CLSNAME + "." + fieldType.toString(); // depends on control dependency: [if], data = [none] defaultKeyValue = fieldType.getDefaultValue(); // depends on control dependency: [if], data = [none] } fieldType = ProtobufProxyUtils.TYPE_MAPPING.get(field.getGenericeValueType()); String valueClass; String defaultValueValue; if (fieldType == null) { // may be object or enum if (Enum.class.isAssignableFrom(field.getGenericeValueType())) { valueClass = WIREFORMAT_CLSNAME + ".ENUM"; // depends on control dependency: [if], data = [none] Class<?> declaringClass = field.getGenericeValueType(); Field[] fields = declaringClass.getFields(); if (fields != null && fields.length > 0) { defaultValueValue = ClassHelper.getInternalName(field.getGenericeValueType().getCanonicalName()) + "." + fields[0].getName(); // depends on control dependency: [if], data = [none] } else { defaultValueValue = "0"; // depends on control dependency: [if], data = [none] } } else { valueClass = WIREFORMAT_CLSNAME + ".MESSAGE"; // depends on control dependency: [if], data = [none] // check constructor boolean hasDefaultConstructor = ClassHelper.hasDefaultConstructor(field.getGenericeValueType()); if (!hasDefaultConstructor) { throw new IllegalArgumentException("Class '" + field.getGenericeValueType().getCanonicalName() + "' must has default constructor method with no parameters."); } defaultValueValue = "new " + ClassHelper.getInternalName(field.getGenericeValueType().getCanonicalName()) + "()"; // depends on control dependency: [if], data = [none] } } else { valueClass = WIREFORMAT_CLSNAME + "." + fieldType.toString(); // depends on control dependency: [if], data = [none] defaultValueValue = fieldType.getDefaultValue(); // depends on control dependency: [if], data = [none] } String joinedSentence = keyClass + "," + defaultKeyValue + "," + valueClass + "," + defaultValueValue; return joinedSentence; } }
public class class_name { public static DMatrixRMaj createMatrixD(EigenDecomposition_F64 eig ) { int N = eig.getNumberOfEigenvalues(); DMatrixRMaj D = new DMatrixRMaj( N , N ); for( int i = 0; i < N; i++ ) { Complex_F64 c = eig.getEigenvalue(i); if( c.isReal() ) { D.set(i,i,c.real); } } return D; } }
public class class_name { public static DMatrixRMaj createMatrixD(EigenDecomposition_F64 eig ) { int N = eig.getNumberOfEigenvalues(); DMatrixRMaj D = new DMatrixRMaj( N , N ); for( int i = 0; i < N; i++ ) { Complex_F64 c = eig.getEigenvalue(i); if( c.isReal() ) { D.set(i,i,c.real); // depends on control dependency: [if], data = [none] } } return D; } }
public class class_name { @Override public Resource fetchResourceById(String type, String uri) { synchronized (lock) { String[] parts = uri.split("\\/"); if (!Utilities.noString(type) && parts.length == 1) return allResourcesById.get(type).get(parts[0]); if (parts.length >= 2) { if (!Utilities.noString(type)) if (!type.equals(parts[parts.length-2])) throw new Error("Resource type mismatch for "+type+" / "+uri); return allResourcesById.get(parts[parts.length-2]).get(parts[parts.length-1]); } else throw new Error("Unable to process request for resource for "+type+" / "+uri); } } }
public class class_name { @Override public Resource fetchResourceById(String type, String uri) { synchronized (lock) { String[] parts = uri.split("\\/"); if (!Utilities.noString(type) && parts.length == 1) return allResourcesById.get(type).get(parts[0]); if (parts.length >= 2) { if (!Utilities.noString(type)) if (!type.equals(parts[parts.length-2])) throw new Error("Resource type mismatch for "+type+" / "+uri); return allResourcesById.get(parts[parts.length-2]).get(parts[parts.length-1]); // depends on control dependency: [if], data = [none] } else throw new Error("Unable to process request for resource for "+type+" / "+uri); } } }
public class class_name { private final State onInitialLine(final Buffer buffer) { try { buffer.markReaderIndex(); final Buffer part1 = buffer.readUntilSafe(config.getMaxAllowedInitialLineSize(), SipParser.SP); final Buffer part2 = buffer.readUntilSafe(config.getMaxAllowedInitialLineSize(), SipParser.SP); final Buffer part3 = buffer.readUntilSingleCRLF(); if (part1 == null || part2 == null || part3 == null) { buffer.resetReaderIndex(); return State.GET_INITIAL_LINE; } sipInitialLine = SipInitialLine.parse(part1, part2, part3); } catch (final IOException e) { throw new RuntimeException("Unable to read from stream due to IOException", e); } return State.GET_HEADER_NAME; } }
public class class_name { private final State onInitialLine(final Buffer buffer) { try { buffer.markReaderIndex(); // depends on control dependency: [try], data = [none] final Buffer part1 = buffer.readUntilSafe(config.getMaxAllowedInitialLineSize(), SipParser.SP); final Buffer part2 = buffer.readUntilSafe(config.getMaxAllowedInitialLineSize(), SipParser.SP); final Buffer part3 = buffer.readUntilSingleCRLF(); if (part1 == null || part2 == null || part3 == null) { buffer.resetReaderIndex(); // depends on control dependency: [if], data = [none] return State.GET_INITIAL_LINE; // depends on control dependency: [if], data = [none] } sipInitialLine = SipInitialLine.parse(part1, part2, part3); // depends on control dependency: [try], data = [none] } catch (final IOException e) { throw new RuntimeException("Unable to read from stream due to IOException", e); } // depends on control dependency: [catch], data = [none] return State.GET_HEADER_NAME; } }
public class class_name { public static boolean isInlineModeAllowed(Element img, InlineMode mode) { // if already inlined => reject (do not inline twice) if (!img.attr(INLINED_ATTR).isEmpty()) { return false; } // if inline mode defined but not the wanted mode => reject if (!img.attr(INLINE_MODE_ATTR).isEmpty() && !img.attr(INLINE_MODE_ATTR).equals(mode.mode())) { return false; } // if inline mode defined and matches the wanted mode => allow // if no inline mode defined => allow (any mode allowed) return true; } }
public class class_name { public static boolean isInlineModeAllowed(Element img, InlineMode mode) { // if already inlined => reject (do not inline twice) if (!img.attr(INLINED_ATTR).isEmpty()) { return false; // depends on control dependency: [if], data = [none] } // if inline mode defined but not the wanted mode => reject if (!img.attr(INLINE_MODE_ATTR).isEmpty() && !img.attr(INLINE_MODE_ATTR).equals(mode.mode())) { return false; // depends on control dependency: [if], data = [none] } // if inline mode defined and matches the wanted mode => allow // if no inline mode defined => allow (any mode allowed) return true; } }
public class class_name { public static TimeZone getGmtTimeZone(final String pattern) { if ("Z".equals(pattern) || "UTC".equals(pattern)) { return GREENWICH; } final Matcher m = GMT_PATTERN.matcher(pattern); if (m.matches()) { final int hours = parseInt(m.group(2)); final int minutes = parseInt(m.group(4)); if (hours == 0 && minutes == 0) { return GREENWICH; } return new GmtTimeZone(parseSign(m.group(1)), hours, minutes); } return null; } }
public class class_name { public static TimeZone getGmtTimeZone(final String pattern) { if ("Z".equals(pattern) || "UTC".equals(pattern)) { return GREENWICH; // depends on control dependency: [if], data = [none] } final Matcher m = GMT_PATTERN.matcher(pattern); if (m.matches()) { final int hours = parseInt(m.group(2)); final int minutes = parseInt(m.group(4)); if (hours == 0 && minutes == 0) { return GREENWICH; // depends on control dependency: [if], data = [none] } return new GmtTimeZone(parseSign(m.group(1)), hours, minutes); // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { public UntagResourceRequest withTagKeys(String... tagKeys) { if (this.tagKeys == null) { setTagKeys(new java.util.ArrayList<String>(tagKeys.length)); } for (String ele : tagKeys) { this.tagKeys.add(ele); } return this; } }
public class class_name { public UntagResourceRequest withTagKeys(String... tagKeys) { if (this.tagKeys == null) { setTagKeys(new java.util.ArrayList<String>(tagKeys.length)); // depends on control dependency: [if], data = [none] } for (String ele : tagKeys) { this.tagKeys.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { private byte[] decrypt(byte[] in, int inOff, int inLen) { // 获取曲线点 final byte[] c1 = new byte[this.curveLength * 2 + 1]; System.arraycopy(in, inOff, c1, 0, c1.length); ECPoint c1P = this.ecParams.getCurve().decodePoint(c1); if (c1P.multiply(this.ecParams.getH()).isInfinity()) { throw new CryptoException("[h]C1 at infinity"); } c1P = c1P.multiply(((ECPrivateKeyParameters) ecKey).getD()).normalize(); final int digestSize = this.digest.getDigestSize(); // 解密C2数据 final byte[] c2 = new byte[inLen - c1.length - digestSize]; if (SM2Mode.C1C3C2 == this.mode) { // C2位于第三部分 System.arraycopy(in, inOff + c1.length + digestSize, c2, 0, c2.length); } else { // C2位于第二部分 System.arraycopy(in, inOff + c1.length, c2, 0, c2.length); } kdf(c1P, c2); // 使用摘要验证C2数据 final byte[] c3 = new byte[digestSize]; addFieldElement(c1P.getAffineXCoord()); this.digest.update(c2, 0, c2.length); addFieldElement(c1P.getAffineYCoord()); this.digest.doFinal(c3, 0); int check = 0; for (int i = 0; i != c3.length; i++) { check |= c3[i] ^ in[inOff + c1.length + ((SM2Mode.C1C3C2 == this.mode) ? 0 : c2.length) + i]; } Arrays.fill(c1, (byte) 0); Arrays.fill(c3, (byte) 0); if (check != 0) { Arrays.fill(c2, (byte) 0); throw new CryptoException("invalid cipher text"); } return c2; } }
public class class_name { private byte[] decrypt(byte[] in, int inOff, int inLen) { // 获取曲线点 final byte[] c1 = new byte[this.curveLength * 2 + 1]; System.arraycopy(in, inOff, c1, 0, c1.length); ECPoint c1P = this.ecParams.getCurve().decodePoint(c1); if (c1P.multiply(this.ecParams.getH()).isInfinity()) { throw new CryptoException("[h]C1 at infinity"); } c1P = c1P.multiply(((ECPrivateKeyParameters) ecKey).getD()).normalize(); final int digestSize = this.digest.getDigestSize(); // 解密C2数据 final byte[] c2 = new byte[inLen - c1.length - digestSize]; if (SM2Mode.C1C3C2 == this.mode) { // C2位于第三部分 System.arraycopy(in, inOff + c1.length + digestSize, c2, 0, c2.length); // depends on control dependency: [if], data = [none] } else { // C2位于第二部分 System.arraycopy(in, inOff + c1.length, c2, 0, c2.length); // depends on control dependency: [if], data = [none] } kdf(c1P, c2); // 使用摘要验证C2数据 final byte[] c3 = new byte[digestSize]; addFieldElement(c1P.getAffineXCoord()); this.digest.update(c2, 0, c2.length); addFieldElement(c1P.getAffineYCoord()); this.digest.doFinal(c3, 0); int check = 0; for (int i = 0; i != c3.length; i++) { check |= c3[i] ^ in[inOff + c1.length + ((SM2Mode.C1C3C2 == this.mode) ? 0 : c2.length) + i]; // depends on control dependency: [for], data = [i] } Arrays.fill(c1, (byte) 0); Arrays.fill(c3, (byte) 0); if (check != 0) { Arrays.fill(c2, (byte) 0); throw new CryptoException("invalid cipher text"); } return c2; } }
public class class_name { @Override public SocketAddress getRemoteSocketAddress() { if(session != null && session.isOpen()){ return session.getRemoteAddress(); } return null; } }
public class class_name { @Override public SocketAddress getRemoteSocketAddress() { if(session != null && session.isOpen()){ return session.getRemoteAddress(); // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { private void setSubjectPrincipals() { if (null != userPrincipal) { this.subject.getPrincipals().add(userPrincipal); } if (null != rolePrincipals) { for (Principal rolePrincipal : rolePrincipals) { this.subject.getPrincipals().add(rolePrincipal); } } } }
public class class_name { private void setSubjectPrincipals() { if (null != userPrincipal) { this.subject.getPrincipals().add(userPrincipal); // depends on control dependency: [if], data = [userPrincipal)] } if (null != rolePrincipals) { for (Principal rolePrincipal : rolePrincipals) { this.subject.getPrincipals().add(rolePrincipal); // depends on control dependency: [for], data = [rolePrincipal] } } } }
public class class_name { public int getCloseButtonState(JComponent c, int tabIndex, boolean tabIsMousedOver) { if (!c.isEnabled()) { return DISABLED; } else if (tabIndex == closeButtonArmedIndex) { return PRESSED; } else if (tabIndex == closeButtonHoverIndex) { return FOCUSED; } else if (tabIsMousedOver) { return MOUSE_OVER; } return ENABLED; } }
public class class_name { public int getCloseButtonState(JComponent c, int tabIndex, boolean tabIsMousedOver) { if (!c.isEnabled()) { return DISABLED; // depends on control dependency: [if], data = [none] } else if (tabIndex == closeButtonArmedIndex) { return PRESSED; // depends on control dependency: [if], data = [none] } else if (tabIndex == closeButtonHoverIndex) { return FOCUSED; // depends on control dependency: [if], data = [none] } else if (tabIsMousedOver) { return MOUSE_OVER; // depends on control dependency: [if], data = [none] } return ENABLED; } }
public class class_name { static synchronized String getTimeZoneDisplay(TimeZone tz, boolean daylight, int style, Locale locale) { Object key = new TimeZoneDisplayKey(tz, daylight, style, locale); String value = (String) cTimeZoneDisplayCache.get(key); if (value == null) { // This is a very slow call, so cache the results. value = tz.getDisplayName(daylight, style, locale); cTimeZoneDisplayCache.put(key, value); } return value; } }
public class class_name { static synchronized String getTimeZoneDisplay(TimeZone tz, boolean daylight, int style, Locale locale) { Object key = new TimeZoneDisplayKey(tz, daylight, style, locale); String value = (String) cTimeZoneDisplayCache.get(key); if (value == null) { // This is a very slow call, so cache the results. value = tz.getDisplayName(daylight, style, locale); // depends on control dependency: [if], data = [none] cTimeZoneDisplayCache.put(key, value); // depends on control dependency: [if], data = [none] } return value; } }
public class class_name { private void encodeScript(final FacesContext context, final Social social) throws IOException { final WidgetBuilder wb = getWidgetBuilder(context); final String clientId = social.getClientId(context); wb.init("ExtSocial", social.resolveWidgetVar(), clientId); wb.attr("showLabel", social.isShowLabel()); wb.attr("shareIn", social.getShareIn()); if (!LangUtils.isValueBlank(social.getUrl())) { wb.attr("url", social.getUrl()); } if (!LangUtils.isValueBlank(social.getText())) { wb.attr("text", social.getText()); } final boolean showCount = BooleanUtils.toBoolean(social.getShowCount()); if (showCount) { wb.attr("showCount", showCount); } else { if (social.getShowCount().equalsIgnoreCase("inside")) { wb.attr("showCount", social.getShowCount()); } else { wb.attr("showCount", showCount); } } // shares array wb.append(",shares: ["); final String[] shares = StringUtils.split(social.getShares(), ','); for (int i = 0; i < shares.length; i++) { // { share: "pinterest", media: "http://mysite.com" }, final String share = StringUtils.lowerCase(shares[i]); if (LangUtils.isValueBlank(share)) { continue; } if (i != 0) { wb.append(","); } wb.append("{"); addShareProperty(wb, "share", share); if (share.equalsIgnoreCase("twitter")) { wb.attr("via", social.getTwitterUsername()); wb.attr("hashtags", social.getTwitterHashtags()); } if (share.equalsIgnoreCase("email")) { wb.attr("to", social.getEmailTo()); } if (share.equalsIgnoreCase("pinterest")) { wb.attr("media", social.getPinterestMedia()); } wb.append("}"); } wb.append("]"); // javascript wb.append(",on: {"); if (social.getOnclick() != null) { addCallback(wb, "click", "function(e)", social.getOnclick()); } if (social.getOnmouseenter() != null) { addCallback(wb, "mouseenter", "function(e)", social.getOnmouseenter()); } if (social.getOnmouseleave() != null) { addCallback(wb, "mouseleave", "function(e)", social.getOnmouseleave()); } wb.append("}"); encodeClientBehaviors(context, social); wb.finish(); } }
public class class_name { private void encodeScript(final FacesContext context, final Social social) throws IOException { final WidgetBuilder wb = getWidgetBuilder(context); final String clientId = social.getClientId(context); wb.init("ExtSocial", social.resolveWidgetVar(), clientId); wb.attr("showLabel", social.isShowLabel()); wb.attr("shareIn", social.getShareIn()); if (!LangUtils.isValueBlank(social.getUrl())) { wb.attr("url", social.getUrl()); } if (!LangUtils.isValueBlank(social.getText())) { wb.attr("text", social.getText()); } final boolean showCount = BooleanUtils.toBoolean(social.getShowCount()); if (showCount) { wb.attr("showCount", showCount); } else { if (social.getShowCount().equalsIgnoreCase("inside")) { wb.attr("showCount", social.getShowCount()); // depends on control dependency: [if], data = [none] } else { wb.attr("showCount", showCount); // depends on control dependency: [if], data = [none] } } // shares array wb.append(",shares: ["); final String[] shares = StringUtils.split(social.getShares(), ','); for (int i = 0; i < shares.length; i++) { // { share: "pinterest", media: "http://mysite.com" }, final String share = StringUtils.lowerCase(shares[i]); if (LangUtils.isValueBlank(share)) { continue; } if (i != 0) { wb.append(","); } wb.append("{"); addShareProperty(wb, "share", share); if (share.equalsIgnoreCase("twitter")) { wb.attr("via", social.getTwitterUsername()); wb.attr("hashtags", social.getTwitterHashtags()); } if (share.equalsIgnoreCase("email")) { wb.attr("to", social.getEmailTo()); } if (share.equalsIgnoreCase("pinterest")) { wb.attr("media", social.getPinterestMedia()); } wb.append("}"); } wb.append("]"); // javascript wb.append(",on: {"); if (social.getOnclick() != null) { addCallback(wb, "click", "function(e)", social.getOnclick()); } if (social.getOnmouseenter() != null) { addCallback(wb, "mouseenter", "function(e)", social.getOnmouseenter()); } if (social.getOnmouseleave() != null) { addCallback(wb, "mouseleave", "function(e)", social.getOnmouseleave()); } wb.append("}"); encodeClientBehaviors(context, social); wb.finish(); } }
public class class_name { protected Map<String, String> getElementAttributes() { // Preserve order of attributes Map<String, String> attrs = new HashMap<>(); if (this.getVoice() != null) { attrs.put("voice", this.getVoice().toString()); } if (this.getLoop() != null) { attrs.put("loop", this.getLoop().toString()); } if (this.getLanguage() != null) { attrs.put("language", this.getLanguage().toString()); } return attrs; } }
public class class_name { protected Map<String, String> getElementAttributes() { // Preserve order of attributes Map<String, String> attrs = new HashMap<>(); if (this.getVoice() != null) { attrs.put("voice", this.getVoice().toString()); // depends on control dependency: [if], data = [none] } if (this.getLoop() != null) { attrs.put("loop", this.getLoop().toString()); // depends on control dependency: [if], data = [none] } if (this.getLanguage() != null) { attrs.put("language", this.getLanguage().toString()); // depends on control dependency: [if], data = [none] } return attrs; } }
public class class_name { public static LocalTime of(int hour, int minute) { HOUR_OF_DAY.checkValidValue(hour); if (minute == 0) { return HOURS[hour]; // for performance } MINUTE_OF_HOUR.checkValidValue(minute); return new LocalTime(hour, minute, 0, 0); } }
public class class_name { public static LocalTime of(int hour, int minute) { HOUR_OF_DAY.checkValidValue(hour); if (minute == 0) { return HOURS[hour]; // for performance // depends on control dependency: [if], data = [none] } MINUTE_OF_HOUR.checkValidValue(minute); return new LocalTime(hour, minute, 0, 0); } }
public class class_name { public static final String printDuration(MSPDIWriter writer, Duration duration) { String result = null; if (duration != null && duration.getDuration() != 0) { result = printDurationMandatory(writer, duration); } return (result); } }
public class class_name { public static final String printDuration(MSPDIWriter writer, Duration duration) { String result = null; if (duration != null && duration.getDuration() != 0) { result = printDurationMandatory(writer, duration); // depends on control dependency: [if], data = [none] } return (result); } }
public class class_name { public static SSLSocketFactory getPinnedCertSslSocketFactory(Context context, int keyStoreRawResId, String keyStorePassword) { InputStream in = null; try { // Get an instance of the Bouncy Castle KeyStore format KeyStore trusted = KeyStore.getInstance("BKS"); // Get the keystore from raw resource in = context.getResources().openRawResource(keyStoreRawResId); // Initialize the keystore with the provided trusted certificates // Also provide the password of the keystore trusted.load(in, keyStorePassword.toCharArray()); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(trusted); // Create an SSLContext that uses our TrustManager SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); return sslContext.getSocketFactory(); } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { Logger.e(e.getMessage()); } } } }
public class class_name { public static SSLSocketFactory getPinnedCertSslSocketFactory(Context context, int keyStoreRawResId, String keyStorePassword) { InputStream in = null; try { // Get an instance of the Bouncy Castle KeyStore format KeyStore trusted = KeyStore.getInstance("BKS"); // Get the keystore from raw resource in = context.getResources().openRawResource(keyStoreRawResId); // depends on control dependency: [try], data = [none] // Initialize the keystore with the provided trusted certificates // Also provide the password of the keystore trusted.load(in, keyStorePassword.toCharArray()); // depends on control dependency: [try], data = [none] // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(trusted); // depends on control dependency: [try], data = [none] // Create an SSLContext that uses our TrustManager SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); // depends on control dependency: [try], data = [none] return sslContext.getSocketFactory(); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new RuntimeException(e); } finally { // depends on control dependency: [catch], data = [none] try { if (in != null) { in.close(); // depends on control dependency: [if], data = [none] } } catch (IOException e) { Logger.e(e.getMessage()); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { public ResetDBParameterGroupRequest withParameters(Parameter... parameters) { if (this.parameters == null) { setParameters(new java.util.ArrayList<Parameter>(parameters.length)); } for (Parameter ele : parameters) { this.parameters.add(ele); } return this; } }
public class class_name { public ResetDBParameterGroupRequest withParameters(Parameter... parameters) { if (this.parameters == null) { setParameters(new java.util.ArrayList<Parameter>(parameters.length)); // depends on control dependency: [if], data = [none] } for (Parameter ele : parameters) { this.parameters.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { private VectorClock toVectorClock(List<Entry<String, Long>> replicaLogicalTimestamps) { final VectorClock timestamps = new VectorClock(); for (Entry<String, Long> replicaTimestamp : replicaLogicalTimestamps) { timestamps.setReplicaTimestamp(replicaTimestamp.getKey(), replicaTimestamp.getValue()); } return timestamps; } }
public class class_name { private VectorClock toVectorClock(List<Entry<String, Long>> replicaLogicalTimestamps) { final VectorClock timestamps = new VectorClock(); for (Entry<String, Long> replicaTimestamp : replicaLogicalTimestamps) { timestamps.setReplicaTimestamp(replicaTimestamp.getKey(), replicaTimestamp.getValue()); // depends on control dependency: [for], data = [replicaTimestamp] } return timestamps; } }
public class class_name { public ChangesetInfo unsubscribe(long id) { SingleElementHandler<ChangesetInfo> handler = new SingleElementHandler<>(); ChangesetInfo result; try { String apiCall = CHANGESET + "/" + id + "/unsubscribe"; osm.makeAuthenticatedRequest(apiCall, "POST", new ChangesetParser(handler)); result = handler.get(); } catch(OsmNotFoundException e) { /* the API is inconsistent here when compared to the "subscribe" command: It returns a 404 if the changeset does not exist OR if the user did not subscribe to the changeset. We want to rethrow it only if the changeset really does not exist TODO monitor https://github.com/openstreetmap/openstreetmap-website/issues/1199 */ result = get(id); if(result == null) throw e; } return result; } }
public class class_name { public ChangesetInfo unsubscribe(long id) { SingleElementHandler<ChangesetInfo> handler = new SingleElementHandler<>(); ChangesetInfo result; try { String apiCall = CHANGESET + "/" + id + "/unsubscribe"; osm.makeAuthenticatedRequest(apiCall, "POST", new ChangesetParser(handler)); // depends on control dependency: [try], data = [none] result = handler.get(); // depends on control dependency: [try], data = [none] } catch(OsmNotFoundException e) { /* the API is inconsistent here when compared to the "subscribe" command: It returns a 404 if the changeset does not exist OR if the user did not subscribe to the changeset. We want to rethrow it only if the changeset really does not exist TODO monitor https://github.com/openstreetmap/openstreetmap-website/issues/1199 */ result = get(id); if(result == null) throw e; } // depends on control dependency: [catch], data = [none] return result; } }
public class class_name { private boolean stopRejoiningHost() { // The host failure notification could come before mesh determination, wait for the determination try { m_meshDeterminationLatch.await(); } catch (InterruptedException e) { } if (m_rejoining) { VoltDB.crashLocalVoltDB("Another node failed before this node could finish rejoining. " + "As a result, the rejoin operation has been canceled. Please try again."); return true; } return false; } }
public class class_name { private boolean stopRejoiningHost() { // The host failure notification could come before mesh determination, wait for the determination try { m_meshDeterminationLatch.await(); // depends on control dependency: [try], data = [none] } catch (InterruptedException e) { } // depends on control dependency: [catch], data = [none] if (m_rejoining) { VoltDB.crashLocalVoltDB("Another node failed before this node could finish rejoining. " + "As a result, the rejoin operation has been canceled. Please try again."); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } return false; } }
public class class_name { public String get(final Object key, final boolean process) { String value = propsMap.get(key); if (process) { value = processPropertyValue(value); } return value == null && defaults != null ? defaults.get(key) : value; } }
public class class_name { public String get(final Object key, final boolean process) { String value = propsMap.get(key); if (process) { value = processPropertyValue(value); // depends on control dependency: [if], data = [none] } return value == null && defaults != null ? defaults.get(key) : value; } }
public class class_name { public EClass getIfcCurtainWallType() { if (ifcCurtainWallTypeEClass == null) { ifcCurtainWallTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(134); } return ifcCurtainWallTypeEClass; } }
public class class_name { public EClass getIfcCurtainWallType() { if (ifcCurtainWallTypeEClass == null) { ifcCurtainWallTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(134); // depends on control dependency: [if], data = [none] } return ifcCurtainWallTypeEClass; } }
public class class_name { protected WSPrincipal getWSPrincipal(Subject subject) throws IOException { WSPrincipal wsPrincipal = null; Set<WSPrincipal> principals = (subject != null) ? subject.getPrincipals(WSPrincipal.class) : null; if (principals != null && !principals.isEmpty()) { if (principals.size() > 1) { // Error - too many principals String principalNames = null; for (WSPrincipal principal : principals) { if (principalNames == null) principalNames = principal.getName(); else principalNames = principalNames + ", " + principal.getName(); } throw new IOException(Tr.formatMessage(tc, "SEC_CONTEXT_DESERIALIZE_TOO_MANY_PRINCIPALS", principalNames)); } else { wsPrincipal = principals.iterator().next(); } } return wsPrincipal; } }
public class class_name { protected WSPrincipal getWSPrincipal(Subject subject) throws IOException { WSPrincipal wsPrincipal = null; Set<WSPrincipal> principals = (subject != null) ? subject.getPrincipals(WSPrincipal.class) : null; if (principals != null && !principals.isEmpty()) { if (principals.size() > 1) { // Error - too many principals String principalNames = null; for (WSPrincipal principal : principals) { if (principalNames == null) principalNames = principal.getName(); else principalNames = principalNames + ", " + principal.getName(); } throw new IOException(Tr.formatMessage(tc, "SEC_CONTEXT_DESERIALIZE_TOO_MANY_PRINCIPALS", principalNames)); } else { wsPrincipal = principals.iterator().next(); // depends on control dependency: [if], data = [none] } } return wsPrincipal; } }
public class class_name { @PUT @Path("{asgName}/status") public Response statusUpdate(@PathParam("asgName") String asgName, @QueryParam("value") String newStatus, @HeaderParam(PeerEurekaNode.HEADER_REPLICATION) String isReplication) { if (awsAsgUtil == null) { return Response.status(400).build(); } try { logger.info("Trying to update ASG Status for ASG {} to {}", asgName, newStatus); ASGStatus asgStatus = ASGStatus.valueOf(newStatus.toUpperCase()); awsAsgUtil.setStatus(asgName, (!ASGStatus.DISABLED.equals(asgStatus))); registry.statusUpdate(asgName, asgStatus, Boolean.valueOf(isReplication)); logger.debug("Updated ASG Status for ASG {} to {}", asgName, asgStatus); } catch (Throwable e) { logger.error("Cannot update the status {} for the ASG {}", newStatus, asgName, e); return Response.serverError().build(); } return Response.ok().build(); } }
public class class_name { @PUT @Path("{asgName}/status") public Response statusUpdate(@PathParam("asgName") String asgName, @QueryParam("value") String newStatus, @HeaderParam(PeerEurekaNode.HEADER_REPLICATION) String isReplication) { if (awsAsgUtil == null) { return Response.status(400).build(); // depends on control dependency: [if], data = [none] } try { logger.info("Trying to update ASG Status for ASG {} to {}", asgName, newStatus); // depends on control dependency: [try], data = [none] ASGStatus asgStatus = ASGStatus.valueOf(newStatus.toUpperCase()); awsAsgUtil.setStatus(asgName, (!ASGStatus.DISABLED.equals(asgStatus))); // depends on control dependency: [try], data = [none] registry.statusUpdate(asgName, asgStatus, Boolean.valueOf(isReplication)); // depends on control dependency: [try], data = [none] logger.debug("Updated ASG Status for ASG {} to {}", asgName, asgStatus); // depends on control dependency: [try], data = [none] } catch (Throwable e) { logger.error("Cannot update the status {} for the ASG {}", newStatus, asgName, e); return Response.serverError().build(); } // depends on control dependency: [catch], data = [none] return Response.ok().build(); } }
public class class_name { @Override public String getUserFacingMessage() { final StringBuilder bldr = new StringBuilder(); bldr.append("ERROR "); bldr.append(exitCode); bldr.append("\n"); String msg = getMessage(); if (msg != null) { bldr.append(msg); } final Throwable cause = getCause(); if (cause != null) { bldr.append("\nCaused by: "); msg = cause.getMessage(); if (msg != null) { bldr.append(msg); } StackTraceElement[] stack = cause.getStackTrace(); for (final StackTraceElement ste : stack) { bldr.append("\n\t"); bldr.append(ste); } bldr.append("\n"); } return bldr.toString(); } }
public class class_name { @Override public String getUserFacingMessage() { final StringBuilder bldr = new StringBuilder(); bldr.append("ERROR "); bldr.append(exitCode); bldr.append("\n"); String msg = getMessage(); if (msg != null) { bldr.append(msg); // depends on control dependency: [if], data = [(msg] } final Throwable cause = getCause(); if (cause != null) { bldr.append("\nCaused by: "); // depends on control dependency: [if], data = [none] msg = cause.getMessage(); // depends on control dependency: [if], data = [none] if (msg != null) { bldr.append(msg); // depends on control dependency: [if], data = [(msg] } StackTraceElement[] stack = cause.getStackTrace(); for (final StackTraceElement ste : stack) { bldr.append("\n\t"); // depends on control dependency: [for], data = [none] bldr.append(ste); // depends on control dependency: [for], data = [ste] } bldr.append("\n"); // depends on control dependency: [if], data = [none] } return bldr.toString(); } }
public class class_name { private static CompilerPass createPeepholeOptimizationsPass( AbstractCompiler compiler, String passName) { final boolean late = false; final boolean useTypesForOptimization = compiler.getOptions().useTypesForLocalOptimization; List<AbstractPeepholeOptimization> optimizations = new ArrayList<>(); optimizations.add(new MinimizeExitPoints()); optimizations.add(new PeepholeMinimizeConditions(late)); optimizations.add(new PeepholeSubstituteAlternateSyntax(late)); optimizations.add(new PeepholeReplaceKnownMethods(late, useTypesForOptimization)); optimizations.add(new PeepholeRemoveDeadCode()); if (compiler.getOptions().j2clPassMode.shouldAddJ2clPasses()) { optimizations.add(new J2clEqualitySameRewriterPass(useTypesForOptimization)); optimizations.add(new J2clStringValueOfRewriterPass()); } optimizations.add(new PeepholeFoldConstants(late, useTypesForOptimization)); optimizations.add(new PeepholeCollectPropertyAssignments()); return new PeepholeOptimizationsPass(compiler, passName, optimizations); } }
public class class_name { private static CompilerPass createPeepholeOptimizationsPass( AbstractCompiler compiler, String passName) { final boolean late = false; final boolean useTypesForOptimization = compiler.getOptions().useTypesForLocalOptimization; List<AbstractPeepholeOptimization> optimizations = new ArrayList<>(); optimizations.add(new MinimizeExitPoints()); optimizations.add(new PeepholeMinimizeConditions(late)); optimizations.add(new PeepholeSubstituteAlternateSyntax(late)); optimizations.add(new PeepholeReplaceKnownMethods(late, useTypesForOptimization)); optimizations.add(new PeepholeRemoveDeadCode()); if (compiler.getOptions().j2clPassMode.shouldAddJ2clPasses()) { optimizations.add(new J2clEqualitySameRewriterPass(useTypesForOptimization)); // depends on control dependency: [if], data = [none] optimizations.add(new J2clStringValueOfRewriterPass()); // depends on control dependency: [if], data = [none] } optimizations.add(new PeepholeFoldConstants(late, useTypesForOptimization)); optimizations.add(new PeepholeCollectPropertyAssignments()); return new PeepholeOptimizationsPass(compiler, passName, optimizations); } }
public class class_name { private void check(CryptoMode cryptoMode) { // For modes that use AES/GCM, we prefer using the BouncyCastle provider unless the // user has explicitly overridden us (i.e., with the FIPS-compliant BouncyCastle // implementation). boolean preferBC = (cryptoMode == CryptoMode.AuthenticatedEncryption) || (cryptoMode == CryptoMode.StrictAuthenticatedEncryption); boolean haveOverride = (cryptoProvider != null && alwaysUseCryptoProvider); if (preferBC && !haveOverride) { if (!CryptoRuntime.isBouncyCastleAvailable()) { CryptoRuntime.enableBouncyCastle(); if (!CryptoRuntime.isBouncyCastleAvailable()) { throw new UnsupportedOperationException( "The Bouncy castle library jar is required on the classpath to enable authenticated encryption"); } } if (!CryptoRuntime.isAesGcmAvailable()) throw new UnsupportedOperationException( "More recent version of the Bouncy castle library is required to enable authenticated encryption"); } } }
public class class_name { private void check(CryptoMode cryptoMode) { // For modes that use AES/GCM, we prefer using the BouncyCastle provider unless the // user has explicitly overridden us (i.e., with the FIPS-compliant BouncyCastle // implementation). boolean preferBC = (cryptoMode == CryptoMode.AuthenticatedEncryption) || (cryptoMode == CryptoMode.StrictAuthenticatedEncryption); boolean haveOverride = (cryptoProvider != null && alwaysUseCryptoProvider); if (preferBC && !haveOverride) { if (!CryptoRuntime.isBouncyCastleAvailable()) { CryptoRuntime.enableBouncyCastle(); // depends on control dependency: [if], data = [none] if (!CryptoRuntime.isBouncyCastleAvailable()) { throw new UnsupportedOperationException( "The Bouncy castle library jar is required on the classpath to enable authenticated encryption"); } } if (!CryptoRuntime.isAesGcmAvailable()) throw new UnsupportedOperationException( "More recent version of the Bouncy castle library is required to enable authenticated encryption"); } } }
public class class_name { private Single<SingleInsertionResult> insert(String preparedSql, Object[] sqlParams) { return Single.fromCallable(() -> { PreparedStatement statement = connection0.prepareStatement(preparedSql, PreparedStatement.RETURN_GENERATED_KEYS); for (int i = 0; i < sqlParams.length; i++) { statement.setObject(i + 1, sqlParams[i]); } statement.execute(); ResultSet rs = statement.getGeneratedKeys(); Integer count = statement.getUpdateCount(); Long id; if (rs.next()) { id = rs.getLong(1); } else { //no id is generated id = null; } rs.close(); statement.close(); return new SingleInsertionResult().setCount(count).setId(id).setPreparedSql(preparedSql); }); } }
public class class_name { private Single<SingleInsertionResult> insert(String preparedSql, Object[] sqlParams) { return Single.fromCallable(() -> { PreparedStatement statement = connection0.prepareStatement(preparedSql, PreparedStatement.RETURN_GENERATED_KEYS); for (int i = 0; i < sqlParams.length; i++) { statement.setObject(i + 1, sqlParams[i]); // depends on control dependency: [for], data = [i] } statement.execute(); ResultSet rs = statement.getGeneratedKeys(); Integer count = statement.getUpdateCount(); Long id; if (rs.next()) { id = rs.getLong(1); // depends on control dependency: [if], data = [none] } else { //no id is generated id = null; // depends on control dependency: [if], data = [none] } rs.close(); statement.close(); return new SingleInsertionResult().setCount(count).setId(id).setPreparedSql(preparedSql); }); } }
public class class_name { public List<ServletType<WebFragmentDescriptor>> getAllServlet() { List<ServletType<WebFragmentDescriptor>> list = new ArrayList<ServletType<WebFragmentDescriptor>>(); List<Node> nodeList = model.get("servlet"); for(Node node: nodeList) { ServletType<WebFragmentDescriptor> type = new ServletTypeImpl<WebFragmentDescriptor>(this, "servlet", model, node); list.add(type); } return list; } }
public class class_name { public List<ServletType<WebFragmentDescriptor>> getAllServlet() { List<ServletType<WebFragmentDescriptor>> list = new ArrayList<ServletType<WebFragmentDescriptor>>(); List<Node> nodeList = model.get("servlet"); for(Node node: nodeList) { ServletType<WebFragmentDescriptor> type = new ServletTypeImpl<WebFragmentDescriptor>(this, "servlet", model, node); list.add(type); // depends on control dependency: [for], data = [none] } return list; } }
public class class_name { public static String validateServices(ToolConsumer consumer, JSONObject providerProfile) { // Mostly to catch casting errors from bad JSON try { JSONObject security_contract = (JSONObject) providerProfile.get(LTI2Constants.SECURITY_CONTRACT); if ( security_contract == null ) { return "JSON missing security_contract"; } JSONArray tool_services = (JSONArray) security_contract.get(LTI2Constants.TOOL_SERVICE); List<ServiceOffered> services_offered = consumer.getService_offered(); if ( tool_services != null ) for (Object o : tool_services) { JSONObject tool_service = (JSONObject) o; String json_service = (String) tool_service.get(LTI2Constants.SERVICE); boolean found = false; for (ServiceOffered service : services_offered ) { String service_endpoint = service.getEndpoint(); if ( service_endpoint.equals(json_service) ) { found = true; break; } } if ( ! found ) return "Service not allowed: "+json_service; } return null; } catch (Exception e) { return "Exception:"+ e.getLocalizedMessage(); } } }
public class class_name { public static String validateServices(ToolConsumer consumer, JSONObject providerProfile) { // Mostly to catch casting errors from bad JSON try { JSONObject security_contract = (JSONObject) providerProfile.get(LTI2Constants.SECURITY_CONTRACT); if ( security_contract == null ) { return "JSON missing security_contract"; // depends on control dependency: [if], data = [none] } JSONArray tool_services = (JSONArray) security_contract.get(LTI2Constants.TOOL_SERVICE); List<ServiceOffered> services_offered = consumer.getService_offered(); if ( tool_services != null ) for (Object o : tool_services) { JSONObject tool_service = (JSONObject) o; String json_service = (String) tool_service.get(LTI2Constants.SERVICE); boolean found = false; for (ServiceOffered service : services_offered ) { String service_endpoint = service.getEndpoint(); if ( service_endpoint.equals(json_service) ) { found = true; // depends on control dependency: [if], data = [none] break; } } if ( ! found ) return "Service not allowed: "+json_service; } return null; // depends on control dependency: [try], data = [none] } catch (Exception e) { return "Exception:"+ e.getLocalizedMessage(); } // depends on control dependency: [catch], data = [none] } }
public class class_name { Node createYield(JSType jsType, Node value) { Node result = IR.yield(value); if (isAddingTypes()) { result.setJSType(checkNotNull(jsType)); } return result; } }
public class class_name { Node createYield(JSType jsType, Node value) { Node result = IR.yield(value); if (isAddingTypes()) { result.setJSType(checkNotNull(jsType)); // depends on control dependency: [if], data = [none] } return result; } }
public class class_name { public static byte[] escape(byte[] auth, boolean quote) { int escapeCount = 0; for (int i = 0; i < auth.length; i++) { if (auth[i] == '"' || auth[i] == '\\') { escapeCount++; } } if (escapeCount > 0 || quote) { byte[] escapedAuth = new byte[auth.length + escapeCount + (quote ? 2 : 0)]; int index = quote ? 1 : 0; for (int i = 0; i < auth.length; i++) { if (auth[i] == '"' || auth[i] == '\\') { escapedAuth[index++] = '\\'; } escapedAuth[index++] = auth[i]; } if (quote) { escapedAuth[0] = '"'; escapedAuth[escapedAuth.length - 1] = '"'; } auth = escapedAuth; } return auth; } }
public class class_name { public static byte[] escape(byte[] auth, boolean quote) { int escapeCount = 0; for (int i = 0; i < auth.length; i++) { if (auth[i] == '"' || auth[i] == '\\') { escapeCount++; // depends on control dependency: [if], data = [none] } } if (escapeCount > 0 || quote) { byte[] escapedAuth = new byte[auth.length + escapeCount + (quote ? 2 : 0)]; int index = quote ? 1 : 0; for (int i = 0; i < auth.length; i++) { if (auth[i] == '"' || auth[i] == '\\') { escapedAuth[index++] = '\\'; // depends on control dependency: [if], data = [none] } escapedAuth[index++] = auth[i]; // depends on control dependency: [for], data = [i] } if (quote) { escapedAuth[0] = '"'; // depends on control dependency: [if], data = [none] escapedAuth[escapedAuth.length - 1] = '"'; // depends on control dependency: [if], data = [none] } auth = escapedAuth; // depends on control dependency: [if], data = [none] } return auth; } }
public class class_name { public Filter<S> mergeRemainderFilter(FilteringScore<S> other) { Filter<S> thisRemainderFilter = getRemainderFilter(); if (this == other) { return thisRemainderFilter; } Filter<S> otherRemainderFilter = other.getRemainderFilter(); if (thisRemainderFilter == null) { return otherRemainderFilter; } else if (otherRemainderFilter == null) { return thisRemainderFilter; } else if (thisRemainderFilter.equals(otherRemainderFilter)) { return thisRemainderFilter; } else { return thisRemainderFilter.or(otherRemainderFilter); } } }
public class class_name { public Filter<S> mergeRemainderFilter(FilteringScore<S> other) { Filter<S> thisRemainderFilter = getRemainderFilter(); if (this == other) { return thisRemainderFilter; // depends on control dependency: [if], data = [none] } Filter<S> otherRemainderFilter = other.getRemainderFilter(); if (thisRemainderFilter == null) { return otherRemainderFilter; // depends on control dependency: [if], data = [none] } else if (otherRemainderFilter == null) { return thisRemainderFilter; // depends on control dependency: [if], data = [none] } else if (thisRemainderFilter.equals(otherRemainderFilter)) { return thisRemainderFilter; // depends on control dependency: [if], data = [none] } else { return thisRemainderFilter.or(otherRemainderFilter); // depends on control dependency: [if], data = [none] } } }
public class class_name { public MachineTime<TimeUnit> getSimpleDuration() { Moment tsp = this.getTemporalOfOpenEnd(); boolean max = (tsp == null); if (max) { // max reached tsp = this.getEnd().getTemporal(); } MachineTime<TimeUnit> result = MachineTime.ON_POSIX_SCALE.between( this.getTemporalOfClosedStart(), tsp); if (max) { return result.plus(1, TimeUnit.NANOSECONDS); } return result; } }
public class class_name { public MachineTime<TimeUnit> getSimpleDuration() { Moment tsp = this.getTemporalOfOpenEnd(); boolean max = (tsp == null); if (max) { // max reached tsp = this.getEnd().getTemporal(); // depends on control dependency: [if], data = [none] } MachineTime<TimeUnit> result = MachineTime.ON_POSIX_SCALE.between( this.getTemporalOfClosedStart(), tsp); if (max) { return result.plus(1, TimeUnit.NANOSECONDS); // depends on control dependency: [if], data = [none] } return result; } }
public class class_name { public String ref(final Object dummy) { if (dummy != null) { if (dummy instanceof String) { return (String) dummy; } throw new MethrefException("Target method not collected"); } return ref(); } }
public class class_name { public String ref(final Object dummy) { if (dummy != null) { if (dummy instanceof String) { return (String) dummy; // depends on control dependency: [if], data = [none] } throw new MethrefException("Target method not collected"); } return ref(); } }
public class class_name { @Override public Iterable<JavaFileObject> list(JavaFileManager.Location location, String packageName, Set<JavaFileObject.Kind> kinds, boolean recurse) throws IOException { Iterable<JavaFileObject> stdList = stdFileManager.list(location, packageName, kinds, recurse); if (location==CLASS_PATH && packageName.equals("REPL")) { // if the desired list is for our JShell package, lazily iterate over // first the standard list then any generated classes. return () -> new Iterator<JavaFileObject>() { boolean stdDone = false; Iterator<? extends JavaFileObject> it; @Override public boolean hasNext() { if (it == null) { it = stdList.iterator(); } if (it.hasNext()) { return true; } if (stdDone) { return false; } else { stdDone = true; it = generatedClasses().iterator(); return it.hasNext(); } } @Override public JavaFileObject next() { if (!hasNext()) { throw new NoSuchElementException(); } return it.next(); } }; } else { return stdList; } } }
public class class_name { @Override public Iterable<JavaFileObject> list(JavaFileManager.Location location, String packageName, Set<JavaFileObject.Kind> kinds, boolean recurse) throws IOException { Iterable<JavaFileObject> stdList = stdFileManager.list(location, packageName, kinds, recurse); if (location==CLASS_PATH && packageName.equals("REPL")) { // if the desired list is for our JShell package, lazily iterate over // first the standard list then any generated classes. return () -> new Iterator<JavaFileObject>() { boolean stdDone = false; Iterator<? extends JavaFileObject> it; @Override public boolean hasNext() { if (it == null) { it = stdList.iterator(); // depends on control dependency: [if], data = [none] } if (it.hasNext()) { return true; // depends on control dependency: [if], data = [none] } if (stdDone) { return false; // depends on control dependency: [if], data = [none] } else { stdDone = true; // depends on control dependency: [if], data = [none] it = generatedClasses().iterator(); // depends on control dependency: [if], data = [none] return it.hasNext(); // depends on control dependency: [if], data = [none] } } @Override public JavaFileObject next() { if (!hasNext()) { throw new NoSuchElementException(); } return it.next(); } }; } else { return stdList; } } }
public class class_name { private CompletableFuture<Channel> bootstrapClient(Address address) { CompletableFuture<Channel> future = new OrderedFuture<>(); Bootstrap bootstrap = new Bootstrap(); bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(10 * 32 * 1024, 10 * 64 * 1024)); bootstrap.option(ChannelOption.SO_RCVBUF, 1024 * 1024); bootstrap.option(ChannelOption.SO_SNDBUF, 1024 * 1024); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.TCP_NODELAY, true); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000); bootstrap.group(clientGroup); // TODO: Make this faster: // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0 bootstrap.channel(clientChannelClass); bootstrap.remoteAddress(address.address(true), address.port()); if (enableNettyTls) { try { bootstrap.handler(new SslClientChannelInitializer(future, address)); } catch (SSLException e) { return Futures.exceptionalFuture(e); } } else { bootstrap.handler(new BasicClientChannelInitializer(future)); } bootstrap.connect().addListener(f -> { if (!f.isSuccess()) { future.completeExceptionally(f.cause()); } }); return future; } }
public class class_name { private CompletableFuture<Channel> bootstrapClient(Address address) { CompletableFuture<Channel> future = new OrderedFuture<>(); Bootstrap bootstrap = new Bootstrap(); bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(10 * 32 * 1024, 10 * 64 * 1024)); bootstrap.option(ChannelOption.SO_RCVBUF, 1024 * 1024); bootstrap.option(ChannelOption.SO_SNDBUF, 1024 * 1024); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.TCP_NODELAY, true); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000); bootstrap.group(clientGroup); // TODO: Make this faster: // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0 bootstrap.channel(clientChannelClass); bootstrap.remoteAddress(address.address(true), address.port()); if (enableNettyTls) { try { bootstrap.handler(new SslClientChannelInitializer(future, address)); // depends on control dependency: [try], data = [none] } catch (SSLException e) { return Futures.exceptionalFuture(e); } // depends on control dependency: [catch], data = [none] } else { bootstrap.handler(new BasicClientChannelInitializer(future)); // depends on control dependency: [if], data = [none] } bootstrap.connect().addListener(f -> { if (!f.isSuccess()) { future.completeExceptionally(f.cause()); } }); return future; } }
public class class_name { public boolean remove(String key, CacheEntry value) { final String sourceMethod = "remove"; //$NON-NLS-1$ boolean removed = false; SignalUtil.lock(cloneLock.readLock(), sourceClass, sourceMethod); try { if (key != null && value != null) { removed = map.remove(keyPrefix + key, value); } if (removed) { evictionLatch.decrement(); value.delete(cacheMgr); } else { evictionLatch.latchIfZero(); } } finally { cloneLock.readLock().unlock(); } return removed; } }
public class class_name { public boolean remove(String key, CacheEntry value) { final String sourceMethod = "remove"; //$NON-NLS-1$ boolean removed = false; SignalUtil.lock(cloneLock.readLock(), sourceClass, sourceMethod); try { if (key != null && value != null) { removed = map.remove(keyPrefix + key, value); // depends on control dependency: [if], data = [(key] } if (removed) { evictionLatch.decrement(); // depends on control dependency: [if], data = [none] value.delete(cacheMgr); // depends on control dependency: [if], data = [none] } else { evictionLatch.latchIfZero(); // depends on control dependency: [if], data = [none] } } finally { cloneLock.readLock().unlock(); } return removed; } }
public class class_name { @Override public List<Object> getTable(final Object table) { List<Object> data = new ArrayList<>(); String tableName; if (table instanceof TableWithNullOption) { // Get source table name tableName = ((TableWithNullOption) table).getTableName(); // Insert null option data.add(null); } else { tableName = (String) table; } for (String[] row : TABLE_DATA) { if (row[0].equals(tableName)) { data.add(new TableEntry(row[1], row[2])); } } return data; } }
public class class_name { @Override public List<Object> getTable(final Object table) { List<Object> data = new ArrayList<>(); String tableName; if (table instanceof TableWithNullOption) { // Get source table name tableName = ((TableWithNullOption) table).getTableName(); // depends on control dependency: [if], data = [none] // Insert null option data.add(null); // depends on control dependency: [if], data = [none] } else { tableName = (String) table; // depends on control dependency: [if], data = [none] } for (String[] row : TABLE_DATA) { if (row[0].equals(tableName)) { data.add(new TableEntry(row[1], row[2])); // depends on control dependency: [if], data = [none] } } return data; } }
public class class_name { protected PojoPathState createState(Object initialPojo, String pojoPath, PojoPathMode mode, PojoPathContext context) { if (mode == null) { throw new NlsNullPointerException("mode"); } Map<Object, Object> rawCache = context.getCache(); if (rawCache == null) { CachingPojoPath rootPath = new CachingPojoPath(initialPojo, initialPojo.getClass()); return new PojoPathState(rootPath, mode, pojoPath); } HashKey<Object> hashKey = new HashKey<>(initialPojo); PojoPathCache masterCache = (PojoPathCache) rawCache.get(hashKey); if (masterCache == null) { masterCache = new PojoPathCache(initialPojo); rawCache.put(hashKey, masterCache); } return masterCache.createState(mode, pojoPath); } }
public class class_name { protected PojoPathState createState(Object initialPojo, String pojoPath, PojoPathMode mode, PojoPathContext context) { if (mode == null) { throw new NlsNullPointerException("mode"); } Map<Object, Object> rawCache = context.getCache(); if (rawCache == null) { CachingPojoPath rootPath = new CachingPojoPath(initialPojo, initialPojo.getClass()); return new PojoPathState(rootPath, mode, pojoPath); // depends on control dependency: [if], data = [none] } HashKey<Object> hashKey = new HashKey<>(initialPojo); PojoPathCache masterCache = (PojoPathCache) rawCache.get(hashKey); if (masterCache == null) { masterCache = new PojoPathCache(initialPojo); // depends on control dependency: [if], data = [none] rawCache.put(hashKey, masterCache); // depends on control dependency: [if], data = [none] } return masterCache.createState(mode, pojoPath); } }
public class class_name { public void marshall(GetLayerVersionPolicyRequest getLayerVersionPolicyRequest, ProtocolMarshaller protocolMarshaller) { if (getLayerVersionPolicyRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getLayerVersionPolicyRequest.getLayerName(), LAYERNAME_BINDING); protocolMarshaller.marshall(getLayerVersionPolicyRequest.getVersionNumber(), VERSIONNUMBER_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(GetLayerVersionPolicyRequest getLayerVersionPolicyRequest, ProtocolMarshaller protocolMarshaller) { if (getLayerVersionPolicyRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getLayerVersionPolicyRequest.getLayerName(), LAYERNAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(getLayerVersionPolicyRequest.getVersionNumber(), VERSIONNUMBER_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private static String convertFifteenToEighteen(String idNumber) { if (15 != idNumber.length()) { return idNumber; } idNumber = idNumber.substring(0, 6) + "19" + idNumber.substring(6, 15); idNumber = idNumber + getVerifyCode(idNumber); return idNumber; } }
public class class_name { private static String convertFifteenToEighteen(String idNumber) { if (15 != idNumber.length()) { return idNumber; // depends on control dependency: [if], data = [none] } idNumber = idNumber.substring(0, 6) + "19" + idNumber.substring(6, 15); idNumber = idNumber + getVerifyCode(idNumber); return idNumber; } }
public class class_name { public static void loadedPlugin(AbstractPlugin plugin) { if (!isPluginLoadedImpl(plugin)) { checkPluginId(plugin); getLoadedPlugins().add(plugin); mapLoadedPlugins.put(plugin.getId(), plugin); Collections.sort(loadedPlugins, riskComparator); } } }
public class class_name { public static void loadedPlugin(AbstractPlugin plugin) { if (!isPluginLoadedImpl(plugin)) { checkPluginId(plugin); // depends on control dependency: [if], data = [none] getLoadedPlugins().add(plugin); // depends on control dependency: [if], data = [none] mapLoadedPlugins.put(plugin.getId(), plugin); // depends on control dependency: [if], data = [none] Collections.sort(loadedPlugins, riskComparator); // depends on control dependency: [if], data = [none] } } }
public class class_name { public ScreenModel doServletCommand(ScreenModel screenParent) { ScreenModel screen = super.doServletCommand(screenParent); // Process params from previous screen if (MenuConstants.SUBMIT.equalsIgnoreCase(this.getProperty(DBParams.COMMAND))) { if (this.getTask().getStatusText(DBConstants.WARNING_MESSAGE) == null) { // Normal return = logged in, go to main menu. this.free(); return null; // This will cause the main menu to display } else { this.getScreenRecord().getField(UserScreenRecord.CURRENT_PASSWORD).setData(null, DBConstants.DISPLAY, DBConstants.INIT_MOVE); this.getScreenRecord().getField(UserScreenRecord.NEW_PASSWORD_1).setData(null, DBConstants.DISPLAY, DBConstants.INIT_MOVE); this.getScreenRecord().getField(UserScreenRecord.NEW_PASSWORD_2).setData(null, DBConstants.DISPLAY, DBConstants.INIT_MOVE); } } return screen; // By default, don't do anything } }
public class class_name { public ScreenModel doServletCommand(ScreenModel screenParent) { ScreenModel screen = super.doServletCommand(screenParent); // Process params from previous screen if (MenuConstants.SUBMIT.equalsIgnoreCase(this.getProperty(DBParams.COMMAND))) { if (this.getTask().getStatusText(DBConstants.WARNING_MESSAGE) == null) { // Normal return = logged in, go to main menu. this.free(); // depends on control dependency: [if], data = [none] return null; // This will cause the main menu to display // depends on control dependency: [if], data = [none] } else { this.getScreenRecord().getField(UserScreenRecord.CURRENT_PASSWORD).setData(null, DBConstants.DISPLAY, DBConstants.INIT_MOVE); // depends on control dependency: [if], data = [none] this.getScreenRecord().getField(UserScreenRecord.NEW_PASSWORD_1).setData(null, DBConstants.DISPLAY, DBConstants.INIT_MOVE); // depends on control dependency: [if], data = [none] this.getScreenRecord().getField(UserScreenRecord.NEW_PASSWORD_2).setData(null, DBConstants.DISPLAY, DBConstants.INIT_MOVE); // depends on control dependency: [if], data = [none] } } return screen; // By default, don't do anything } }
public class class_name { public void removeLockedObjectOwner(String owner) { try { if (_owner != null) { int size = _owner.length; for (int i = 0; i < size; i++) { // check every owner if it is the requested one if (_owner[i].equals(owner)) { // remove the owner String[] newLockedObjectOwner = new String[size - 1]; for (int j = 0; j < (size - 1); j++) { if (j < i) { newLockedObjectOwner[j] = _owner[j]; } else { newLockedObjectOwner[j] = _owner[j + 1]; } } _owner = newLockedObjectOwner; } } if (_owner.length == 0) { _owner = null; } } } catch (ArrayIndexOutOfBoundsException e) { System.out.println("LockedObject.removeLockedObjectOwner()"); System.out.println(e.toString()); } } }
public class class_name { public void removeLockedObjectOwner(String owner) { try { if (_owner != null) { int size = _owner.length; for (int i = 0; i < size; i++) { // check every owner if it is the requested one if (_owner[i].equals(owner)) { // remove the owner String[] newLockedObjectOwner = new String[size - 1]; for (int j = 0; j < (size - 1); j++) { if (j < i) { newLockedObjectOwner[j] = _owner[j]; // depends on control dependency: [if], data = [none] } else { newLockedObjectOwner[j] = _owner[j + 1]; // depends on control dependency: [if], data = [none] } } _owner = newLockedObjectOwner; // depends on control dependency: [if], data = [none] } } if (_owner.length == 0) { _owner = null; // depends on control dependency: [if], data = [none] } } } catch (ArrayIndexOutOfBoundsException e) { System.out.println("LockedObject.removeLockedObjectOwner()"); System.out.println(e.toString()); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private PdfPTable buildPdfTable(int type) throws QueryException { List<Band> bands = new ArrayList<Band>(); if (type == PRINT_PAGE_HEADER) { bands.add(getReportLayout().getPageHeaderBand()); } else if (type == PRINT_PAGE_FOOTER) { bands.add(getReportLayout().getPageFooterBand()); } else { bands = getReportLayout().getDocumentBands(); } int totalRows = 0; int totalColumns = 0; for (Band band : bands) { totalRows += band.getRowCount(); int cols = band.getColumnCount(); if (cols > totalColumns) { totalColumns = cols; } } // no page header or no page footer if (totalColumns == 0) { return null; } PdfPTable datatable = new PdfPTable(totalColumns); // !Important: when a cell is bigger than a page it won't show // we could use datatable.setSplitLate(false)and in this case we can see // some content but it is very ugly. headerwidths = new int[totalColumns]; // % int size = 100 / totalColumns; int totalWidth = 0; for (int i = 0; i < totalColumns; i++) { if (bean.getReportLayout().isUseSize()) { headerwidths[i] = bean.getReportLayout().getColumnsWidth().get(i); } else { headerwidths[i] = size; } totalWidth += headerwidths[i]; } try { if (bean.getReportLayout().isUseSize()) { float pixels = A4_PORTRAIT_PIXELS; if (bean.getReportLayout().getOrientation() == LANDSCAPE) { pixels = A4_LANDSCAPE_PIXELS; } percentage = totalWidth * 100 / pixels; // do not allow to go outside an A4 frame if (percentage > 100) { percentage = 100; } if (!ReportLayout.CUSTOM.equals(bean.getReportLayout().getPageFormat())) { datatable.setWidthPercentage(percentage); } datatable.setWidths(headerwidths); } else { datatable.setWidthPercentage(100); } } catch (DocumentException e) { throw new QueryException(e); } if (type == PRINT_DOCUMENT) { writeHeader(datatable); } // this is used in correlation with sepSplitRows(true) which is the default inside PdfPTable; // by default splitLate is true and in case a subreport is bigger than a page, the subreport // will be written starting from next page, leaving first page empty datatable.setSplitLate(false); return datatable; } }
public class class_name { private PdfPTable buildPdfTable(int type) throws QueryException { List<Band> bands = new ArrayList<Band>(); if (type == PRINT_PAGE_HEADER) { bands.add(getReportLayout().getPageHeaderBand()); } else if (type == PRINT_PAGE_FOOTER) { bands.add(getReportLayout().getPageFooterBand()); } else { bands = getReportLayout().getDocumentBands(); } int totalRows = 0; int totalColumns = 0; for (Band band : bands) { totalRows += band.getRowCount(); int cols = band.getColumnCount(); if (cols > totalColumns) { totalColumns = cols; // depends on control dependency: [if], data = [none] } } // no page header or no page footer if (totalColumns == 0) { return null; } PdfPTable datatable = new PdfPTable(totalColumns); // !Important: when a cell is bigger than a page it won't show // we could use datatable.setSplitLate(false)and in this case we can see // some content but it is very ugly. headerwidths = new int[totalColumns]; // % int size = 100 / totalColumns; int totalWidth = 0; for (int i = 0; i < totalColumns; i++) { if (bean.getReportLayout().isUseSize()) { headerwidths[i] = bean.getReportLayout().getColumnsWidth().get(i); } else { headerwidths[i] = size; } totalWidth += headerwidths[i]; } try { if (bean.getReportLayout().isUseSize()) { float pixels = A4_PORTRAIT_PIXELS; if (bean.getReportLayout().getOrientation() == LANDSCAPE) { pixels = A4_LANDSCAPE_PIXELS; } percentage = totalWidth * 100 / pixels; // do not allow to go outside an A4 frame if (percentage > 100) { percentage = 100; } if (!ReportLayout.CUSTOM.equals(bean.getReportLayout().getPageFormat())) { datatable.setWidthPercentage(percentage); } datatable.setWidths(headerwidths); } else { datatable.setWidthPercentage(100); } } catch (DocumentException e) { throw new QueryException(e); } if (type == PRINT_DOCUMENT) { writeHeader(datatable); } // this is used in correlation with sepSplitRows(true) which is the default inside PdfPTable; // by default splitLate is true and in case a subreport is bigger than a page, the subreport // will be written starting from next page, leaving first page empty datatable.setSplitLate(false); return datatable; } }
public class class_name { private FPTree buildFPTree(final Relation<BitVector> relation, int[] iidx, final int items) { FPTree tree = new FPTree(items); FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Building FP-tree", relation.size(), LOG) : null; int[] buf = new int[items]; for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) { // Convert item to index representation: int l = 0; SparseFeatureVector<?> bv = relation.get(iditer); for(int it = bv.iter(); bv.iterValid(it); it = bv.iterAdvance(it)) { int i = iidx[bv.iterDim(it)]; if(i < 0) { continue; // Skip non-frequent items } buf[l++] = i; } // Skip too short entries if(l >= minlength) { Arrays.sort(buf, 0, l); // Sort ascending tree.insert(buf, 0, l, 1); } LOG.incrementProcessed(prog); } LOG.ensureCompleted(prog); return tree; } }
public class class_name { private FPTree buildFPTree(final Relation<BitVector> relation, int[] iidx, final int items) { FPTree tree = new FPTree(items); FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Building FP-tree", relation.size(), LOG) : null; int[] buf = new int[items]; for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) { // Convert item to index representation: int l = 0; SparseFeatureVector<?> bv = relation.get(iditer); for(int it = bv.iter(); bv.iterValid(it); it = bv.iterAdvance(it)) { int i = iidx[bv.iterDim(it)]; if(i < 0) { continue; // Skip non-frequent items } buf[l++] = i; // depends on control dependency: [for], data = [none] } // Skip too short entries if(l >= minlength) { Arrays.sort(buf, 0, l); // Sort ascending // depends on control dependency: [if], data = [none] tree.insert(buf, 0, l, 1); // depends on control dependency: [if], data = [none] } LOG.incrementProcessed(prog); // depends on control dependency: [for], data = [none] } LOG.ensureCompleted(prog); return tree; } }
public class class_name { void remove(RowCursor cursor) { boolean isValid; do { isValid = true; try (JournalOutputStream os = openItem()) { os.write(CODE_REMOVE); cursor.getKey(_buffer, 0); os.write(_buffer, 0, getKeyLength()); try { BitsUtil.writeLong(os, cursor.getVersion()); } catch (IOException e) { throw new RuntimeException(e); } isValid = os.complete(); } } while (! isValid); } }
public class class_name { void remove(RowCursor cursor) { boolean isValid; do { isValid = true; try (JournalOutputStream os = openItem()) { os.write(CODE_REMOVE); cursor.getKey(_buffer, 0); os.write(_buffer, 0, getKeyLength()); try { BitsUtil.writeLong(os, cursor.getVersion()); // depends on control dependency: [try], data = [none] } catch (IOException e) { throw new RuntimeException(e); } // depends on control dependency: [catch], data = [none] isValid = os.complete(); } } while (! isValid); } }
public class class_name { public void marshall(TagResourceRequest tagResourceRequest, ProtocolMarshaller protocolMarshaller) { if (tagResourceRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(tagResourceRequest.getResourceArn(), RESOURCEARN_BINDING); protocolMarshaller.marshall(tagResourceRequest.getTagsToAdd(), TAGSTOADD_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(TagResourceRequest tagResourceRequest, ProtocolMarshaller protocolMarshaller) { if (tagResourceRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(tagResourceRequest.getResourceArn(), RESOURCEARN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(tagResourceRequest.getTagsToAdd(), TAGSTOADD_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { protected void validateAttachmentContentId(SoapAttachment receivedAttachment, SoapAttachment controlAttachment) { //in case contentId was not set in test case, skip validation if (!StringUtils.hasText(controlAttachment.getContentId())) { return; } if (receivedAttachment.getContentId() != null) { Assert.isTrue(controlAttachment.getContentId() != null, buildValidationErrorMessage("Values not equal for attachment contentId", null, receivedAttachment.getContentId())); Assert.isTrue(receivedAttachment.getContentId().equals(controlAttachment.getContentId()), buildValidationErrorMessage("Values not equal for attachment contentId", controlAttachment.getContentId(), receivedAttachment.getContentId())); } else { Assert.isTrue(controlAttachment.getContentId() == null || controlAttachment.getContentId().length() == 0, buildValidationErrorMessage("Values not equal for attachment contentId", controlAttachment.getContentId(), null)); } if (log.isDebugEnabled()) { log.debug("Validating attachment contentId: " + receivedAttachment.getContentId() + "='" + controlAttachment.getContentId() + "': OK."); } } }
public class class_name { protected void validateAttachmentContentId(SoapAttachment receivedAttachment, SoapAttachment controlAttachment) { //in case contentId was not set in test case, skip validation if (!StringUtils.hasText(controlAttachment.getContentId())) { return; } // depends on control dependency: [if], data = [none] if (receivedAttachment.getContentId() != null) { Assert.isTrue(controlAttachment.getContentId() != null, buildValidationErrorMessage("Values not equal for attachment contentId", null, receivedAttachment.getContentId())); // depends on control dependency: [if], data = [none] Assert.isTrue(receivedAttachment.getContentId().equals(controlAttachment.getContentId()), buildValidationErrorMessage("Values not equal for attachment contentId", controlAttachment.getContentId(), receivedAttachment.getContentId())); // depends on control dependency: [if], data = [(receivedAttachment.getContentId()] } else { Assert.isTrue(controlAttachment.getContentId() == null || controlAttachment.getContentId().length() == 0, buildValidationErrorMessage("Values not equal for attachment contentId", controlAttachment.getContentId(), null)); // depends on control dependency: [if], data = [none] } if (log.isDebugEnabled()) { log.debug("Validating attachment contentId: " + receivedAttachment.getContentId() + "='" + controlAttachment.getContentId() + "': OK."); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void inMemoryWeightGraphGenerator() { for (TopologySpec topologySpec : topologySpecMap.values()) { weightGraphGenerateHelper(topologySpec); } // Filter out connection appearing in servicePolicy. // This is where servicePolicy is enforced. servicePolicy.populateBlackListedEdges(this.weightedGraph); if (servicePolicy.getBlacklistedEdges().size() > 0) { for (FlowEdge toDeletedEdge : servicePolicy.getBlacklistedEdges()) { weightedGraph.removeEdge(toDeletedEdge); } } } }
public class class_name { private void inMemoryWeightGraphGenerator() { for (TopologySpec topologySpec : topologySpecMap.values()) { weightGraphGenerateHelper(topologySpec); // depends on control dependency: [for], data = [topologySpec] } // Filter out connection appearing in servicePolicy. // This is where servicePolicy is enforced. servicePolicy.populateBlackListedEdges(this.weightedGraph); if (servicePolicy.getBlacklistedEdges().size() > 0) { for (FlowEdge toDeletedEdge : servicePolicy.getBlacklistedEdges()) { weightedGraph.removeEdge(toDeletedEdge); // depends on control dependency: [for], data = [toDeletedEdge] } } } }
public class class_name { public String getScaleParam() { if (!isScaled() && !isCropped()) { // the image is not cropped nor scaled, return an empty parameter return ""; } StringBuffer result = new StringBuffer(); if ((m_targetHeight > -1) || (m_targetWidth > -1)) { result.append(SCALE_PARAM_TARGETHEIGHT).append(SCALE_PARAM_COLON).append(getResultingTargetHeight()).append( SCALE_PARAM_DELIMITER); result.append(SCALE_PARAM_TARGETWIDTH).append(SCALE_PARAM_COLON).append(getResultingTargetWidth()).append( SCALE_PARAM_DELIMITER); } if (m_cropX > -1) { result.append(SCALE_PARAM_CROP_X).append(SCALE_PARAM_COLON).append(m_cropX).append(SCALE_PARAM_DELIMITER); } if (m_cropY > -1) { result.append(SCALE_PARAM_CROP_Y).append(SCALE_PARAM_COLON).append(m_cropY).append(SCALE_PARAM_DELIMITER); } if (m_cropHeight > -1) { result.append(SCALE_PARAM_CROP_HEIGHT).append(SCALE_PARAM_COLON).append(m_cropHeight).append( SCALE_PARAM_DELIMITER); } if (m_cropWidth > -1) { result.append(SCALE_PARAM_CROP_WIDTH).append(SCALE_PARAM_COLON).append(m_cropWidth).append( SCALE_PARAM_DELIMITER); } if (result.length() > 0) { result.deleteCharAt(result.length() - 1); } return result.toString(); } }
public class class_name { public String getScaleParam() { if (!isScaled() && !isCropped()) { // the image is not cropped nor scaled, return an empty parameter return ""; // depends on control dependency: [if], data = [none] } StringBuffer result = new StringBuffer(); if ((m_targetHeight > -1) || (m_targetWidth > -1)) { result.append(SCALE_PARAM_TARGETHEIGHT).append(SCALE_PARAM_COLON).append(getResultingTargetHeight()).append( SCALE_PARAM_DELIMITER); // depends on control dependency: [if], data = [none] result.append(SCALE_PARAM_TARGETWIDTH).append(SCALE_PARAM_COLON).append(getResultingTargetWidth()).append( SCALE_PARAM_DELIMITER); // depends on control dependency: [if], data = [none] } if (m_cropX > -1) { result.append(SCALE_PARAM_CROP_X).append(SCALE_PARAM_COLON).append(m_cropX).append(SCALE_PARAM_DELIMITER); // depends on control dependency: [if], data = [(m_cropX] } if (m_cropY > -1) { result.append(SCALE_PARAM_CROP_Y).append(SCALE_PARAM_COLON).append(m_cropY).append(SCALE_PARAM_DELIMITER); // depends on control dependency: [if], data = [(m_cropY] } if (m_cropHeight > -1) { result.append(SCALE_PARAM_CROP_HEIGHT).append(SCALE_PARAM_COLON).append(m_cropHeight).append( SCALE_PARAM_DELIMITER); // depends on control dependency: [if], data = [none] } if (m_cropWidth > -1) { result.append(SCALE_PARAM_CROP_WIDTH).append(SCALE_PARAM_COLON).append(m_cropWidth).append( SCALE_PARAM_DELIMITER); // depends on control dependency: [if], data = [none] } if (result.length() > 0) { result.deleteCharAt(result.length() - 1); // depends on control dependency: [if], data = [(result.length()] } return result.toString(); } }
public class class_name { public static void closeQuietly(final InputStream aInputStream) { if (aInputStream != null) { try { aInputStream.close(); } catch (final IOException details) { LOGGER.error(details.getMessage(), details); } } } }
public class class_name { public static void closeQuietly(final InputStream aInputStream) { if (aInputStream != null) { try { aInputStream.close(); // depends on control dependency: [try], data = [none] } catch (final IOException details) { LOGGER.error(details.getMessage(), details); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { @VisibleForTesting public final Print getJasperPrint( final String jobId, final PJsonObject requestData, final Configuration config, final File configDir, final File taskDirectory) throws JRException, SQLException, ExecutionException { final String templateName = requestData.getString(Constants.JSON_LAYOUT_KEY); final Template template = config.getTemplate(templateName); final File jasperTemplateFile = new File(configDir, template.getReportTemplate()); final File jasperTemplateBuild = this.workingDirectories.getBuildFileFor( config, jasperTemplateFile, JasperReportBuilder.JASPER_REPORT_COMPILED_FILE_EXT, LOGGER); final Values values = new Values(jobId, requestData, template, taskDirectory, this.httpRequestFactory, jasperTemplateBuild.getParentFile()); double maxDpi = maxDpi(values); final ProcessorDependencyGraph.ProcessorGraphForkJoinTask task = template.getProcessorGraph().createTask(values); final ForkJoinTask<Values> taskFuture = this.forkJoinPool.submit( task); try { taskFuture.get(); } catch (InterruptedException exc) { // if cancel() is called on the current thread, this exception will be thrown. // in this case, also properly cancel the task future. taskFuture.cancel(true); Thread.currentThread().interrupt(); throw new CancellationException(); } // Fill the resource bundle String resourceBundle = config.getResourceBundle(); if (resourceBundle != null) { values.put("REPORT_RESOURCE_BUNDLE", ResourceBundle.getBundle( resourceBundle, values.getObject(Values.LOCALE_KEY, Locale.class), new ResourceBundleClassLoader(configDir))); } ValuesLogger.log(templateName, template, values); JasperFillManager fillManager = getJasperFillManager( values.getObject( Values.CLIENT_HTTP_REQUEST_FACTORY_KEY, MfClientHttpRequestFactoryProvider.class)); checkRequiredValues(config, values, template.getReportTemplate()); final JasperPrint print; if (template.getJdbcUrl() != null) { Connection connection; if (template.getJdbcUser() != null) { connection = DriverManager.getConnection( template.getJdbcUrl(), template.getJdbcUser(), template.getJdbcPassword()); } else { connection = DriverManager.getConnection(template.getJdbcUrl()); } print = fillManager.fill( jasperTemplateBuild.getAbsolutePath(), values.asMap(), connection); } else { JRDataSource dataSource; if (template.getTableDataKey() != null) { final Object dataSourceObj = values.getObject(template.getTableDataKey(), Object.class); if (dataSourceObj instanceof JRDataSource) { dataSource = (JRDataSource) dataSourceObj; } else if (dataSourceObj instanceof Iterable) { Iterable sourceObj = (Iterable) dataSourceObj; dataSource = toJRDataSource(sourceObj.iterator()); } else if (dataSourceObj instanceof Iterator) { Iterator sourceObj = (Iterator) dataSourceObj; dataSource = toJRDataSource(sourceObj); } else if (dataSourceObj.getClass().isArray()) { Object[] sourceObj = (Object[]) dataSourceObj; dataSource = toJRDataSource(Arrays.asList(sourceObj).iterator()); } else { throw new AssertionError( String.format("Objects of type: %s cannot be converted to a row in a " + "JRDataSource", dataSourceObj.getClass())); } } else { dataSource = new JREmptyDataSource(); } checkRequiredFields(config, dataSource, template.getReportTemplate()); print = fillManager.fill( jasperTemplateBuild.getAbsolutePath(), values.asMap(), dataSource); } print.setProperty(Renderable.PROPERTY_IMAGE_DPI, String.valueOf(Math.round(maxDpi))); return new Print(getJasperReportsContext( values.getObject( Values.CLIENT_HTTP_REQUEST_FACTORY_KEY, MfClientHttpRequestFactoryProvider.class)), print, values, maxDpi, task.getExecutionContext()); } }
public class class_name { @VisibleForTesting public final Print getJasperPrint( final String jobId, final PJsonObject requestData, final Configuration config, final File configDir, final File taskDirectory) throws JRException, SQLException, ExecutionException { final String templateName = requestData.getString(Constants.JSON_LAYOUT_KEY); final Template template = config.getTemplate(templateName); final File jasperTemplateFile = new File(configDir, template.getReportTemplate()); final File jasperTemplateBuild = this.workingDirectories.getBuildFileFor( config, jasperTemplateFile, JasperReportBuilder.JASPER_REPORT_COMPILED_FILE_EXT, LOGGER); final Values values = new Values(jobId, requestData, template, taskDirectory, this.httpRequestFactory, jasperTemplateBuild.getParentFile()); double maxDpi = maxDpi(values); final ProcessorDependencyGraph.ProcessorGraphForkJoinTask task = template.getProcessorGraph().createTask(values); final ForkJoinTask<Values> taskFuture = this.forkJoinPool.submit( task); try { taskFuture.get(); } catch (InterruptedException exc) { // if cancel() is called on the current thread, this exception will be thrown. // in this case, also properly cancel the task future. taskFuture.cancel(true); Thread.currentThread().interrupt(); throw new CancellationException(); } // Fill the resource bundle String resourceBundle = config.getResourceBundle(); if (resourceBundle != null) { values.put("REPORT_RESOURCE_BUNDLE", ResourceBundle.getBundle( resourceBundle, values.getObject(Values.LOCALE_KEY, Locale.class), new ResourceBundleClassLoader(configDir))); } ValuesLogger.log(templateName, template, values); JasperFillManager fillManager = getJasperFillManager( values.getObject( Values.CLIENT_HTTP_REQUEST_FACTORY_KEY, MfClientHttpRequestFactoryProvider.class)); checkRequiredValues(config, values, template.getReportTemplate()); final JasperPrint print; if (template.getJdbcUrl() != null) { Connection connection; if (template.getJdbcUser() != null) { connection = DriverManager.getConnection( template.getJdbcUrl(), template.getJdbcUser(), template.getJdbcPassword()); // depends on control dependency: [if], data = [none] } else { connection = DriverManager.getConnection(template.getJdbcUrl()); // depends on control dependency: [if], data = [none] } print = fillManager.fill( jasperTemplateBuild.getAbsolutePath(), values.asMap(), connection); } else { JRDataSource dataSource; if (template.getTableDataKey() != null) { final Object dataSourceObj = values.getObject(template.getTableDataKey(), Object.class); if (dataSourceObj instanceof JRDataSource) { dataSource = (JRDataSource) dataSourceObj; // depends on control dependency: [if], data = [none] } else if (dataSourceObj instanceof Iterable) { Iterable sourceObj = (Iterable) dataSourceObj; dataSource = toJRDataSource(sourceObj.iterator()); // depends on control dependency: [if], data = [none] } else if (dataSourceObj instanceof Iterator) { Iterator sourceObj = (Iterator) dataSourceObj; dataSource = toJRDataSource(sourceObj); // depends on control dependency: [if], data = [none] } else if (dataSourceObj.getClass().isArray()) { Object[] sourceObj = (Object[]) dataSourceObj; dataSource = toJRDataSource(Arrays.asList(sourceObj).iterator()); // depends on control dependency: [if], data = [none] } else { throw new AssertionError( String.format("Objects of type: %s cannot be converted to a row in a " + "JRDataSource", dataSourceObj.getClass())); } } else { dataSource = new JREmptyDataSource(); // depends on control dependency: [if], data = [none] } checkRequiredFields(config, dataSource, template.getReportTemplate()); print = fillManager.fill( jasperTemplateBuild.getAbsolutePath(), values.asMap(), dataSource); } print.setProperty(Renderable.PROPERTY_IMAGE_DPI, String.valueOf(Math.round(maxDpi))); return new Print(getJasperReportsContext( values.getObject( Values.CLIENT_HTTP_REQUEST_FACTORY_KEY, MfClientHttpRequestFactoryProvider.class)), print, values, maxDpi, task.getExecutionContext()); } }
public class class_name { @SuppressWarnings("unchecked") public <C extends SecurityConfigurer<O, B>> List<C> getConfigurers(Class<C> clazz) { List<C> configs = (List<C>) this.configurers.get(clazz); if (configs == null) { return new ArrayList<>(); } return new ArrayList<>(configs); } }
public class class_name { @SuppressWarnings("unchecked") public <C extends SecurityConfigurer<O, B>> List<C> getConfigurers(Class<C> clazz) { List<C> configs = (List<C>) this.configurers.get(clazz); if (configs == null) { return new ArrayList<>(); // depends on control dependency: [if], data = [none] } return new ArrayList<>(configs); } }
public class class_name { private Set<Comparable> prepareKeys(OIndex<?> index, Object keys) { final OIndexDefinition indexDefinition = index.getDefinition(); if (keys instanceof Collection) { final Set<Comparable> newKeys = new TreeSet<Comparable>(); for (Object o : ((Collection) keys)) { newKeys.add((Comparable) indexDefinition.createValue(o)); } return newKeys; } else { return Collections.singleton((Comparable) indexDefinition.createValue(keys)); } } }
public class class_name { private Set<Comparable> prepareKeys(OIndex<?> index, Object keys) { final OIndexDefinition indexDefinition = index.getDefinition(); if (keys instanceof Collection) { final Set<Comparable> newKeys = new TreeSet<Comparable>(); for (Object o : ((Collection) keys)) { newKeys.add((Comparable) indexDefinition.createValue(o)); // depends on control dependency: [for], data = [o] } return newKeys; // depends on control dependency: [if], data = [none] } else { return Collections.singleton((Comparable) indexDefinition.createValue(keys)); // depends on control dependency: [if], data = [none] } } }
public class class_name { public NGram createNGram(List words) { int[] nums = new int[words.size()]; //ngram needs it own copy of this array so keep making a unique one for each instance. for (int wi=0;wi<nums.length;wi++) { nums[wi] = wordMap.getIndex(words.get(wi)); if (nums[wi] == -1) { return null; } } return new NGram(nums); } }
public class class_name { public NGram createNGram(List words) { int[] nums = new int[words.size()]; //ngram needs it own copy of this array so keep making a unique one for each instance. for (int wi=0;wi<nums.length;wi++) { nums[wi] = wordMap.getIndex(words.get(wi)); // depends on control dependency: [for], data = [wi] if (nums[wi] == -1) { return null; // depends on control dependency: [if], data = [none] } } return new NGram(nums); } }
public class class_name { @GET @Path("{id}/guaranteestatus") @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_XML) public Response getStatusAgreementXML(@PathParam("id") String agreement_id) { logger.debug("StartOf getStatusAgreementXML - REQUEST for /agreements/" + agreement_id + "/guaranteestatus"); Response result; try{ AgreementHelper agreementRestService = getAgreementHelper(); String serializedAgreement = agreementRestService.getAgreementStatus(agreement_id, MediaType.APPLICATION_XML); if (serializedAgreement!=null){ result = buildResponse(200, serializedAgreement); }else{ result = buildResponse(404, printError(404, "No agreement with "+agreement_id)); } } catch (HelperException e) { logger.info("getStatusAgreementXML exception:"+e.getMessage()); return buildResponse(e); } logger.debug("EndOf getStatusAgreementXML"); return result; } }
public class class_name { @GET @Path("{id}/guaranteestatus") @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_XML) public Response getStatusAgreementXML(@PathParam("id") String agreement_id) { logger.debug("StartOf getStatusAgreementXML - REQUEST for /agreements/" + agreement_id + "/guaranteestatus"); Response result; try{ AgreementHelper agreementRestService = getAgreementHelper(); String serializedAgreement = agreementRestService.getAgreementStatus(agreement_id, MediaType.APPLICATION_XML); if (serializedAgreement!=null){ result = buildResponse(200, serializedAgreement); // depends on control dependency: [if], data = [none] }else{ result = buildResponse(404, printError(404, "No agreement with "+agreement_id)); // depends on control dependency: [if], data = [none] } } catch (HelperException e) { logger.info("getStatusAgreementXML exception:"+e.getMessage()); return buildResponse(e); } // depends on control dependency: [catch], data = [none] logger.debug("EndOf getStatusAgreementXML"); return result; } }
public class class_name { public int filterObject(CaptureSearchResult r) { if(!notifiedSeen) { if(filterGroup != null) { filterGroup.setSawAdministrative(); } notifiedSeen = true; } String url = r.getUrlKey(); if(lastChecked != null) { if(lastChecked.equals(url)) { if(lastCheckedExcluded) { return ObjectFilter.FILTER_EXCLUDE; } else { // don't need to: already did last time... //filterGroup.setPassedAdministrative(); return ObjectFilter.FILTER_INCLUDE; } } } lastChecked = url; lastCheckedExcluded = isExcluded(url); if(lastCheckedExcluded) { return ObjectFilter.FILTER_EXCLUDE; } else { if(!notifiedPassed) { if(filterGroup != null) { filterGroup.setPassedAdministrative(); } notifiedPassed = true; } return ObjectFilter.FILTER_INCLUDE; } } }
public class class_name { public int filterObject(CaptureSearchResult r) { if(!notifiedSeen) { if(filterGroup != null) { filterGroup.setSawAdministrative(); // depends on control dependency: [if], data = [none] } notifiedSeen = true; // depends on control dependency: [if], data = [none] } String url = r.getUrlKey(); if(lastChecked != null) { if(lastChecked.equals(url)) { if(lastCheckedExcluded) { return ObjectFilter.FILTER_EXCLUDE; // depends on control dependency: [if], data = [none] } else { // don't need to: already did last time... //filterGroup.setPassedAdministrative(); return ObjectFilter.FILTER_INCLUDE; // depends on control dependency: [if], data = [none] } } } lastChecked = url; lastCheckedExcluded = isExcluded(url); if(lastCheckedExcluded) { return ObjectFilter.FILTER_EXCLUDE; // depends on control dependency: [if], data = [none] } else { if(!notifiedPassed) { if(filterGroup != null) { filterGroup.setPassedAdministrative(); // depends on control dependency: [if], data = [none] } notifiedPassed = true; // depends on control dependency: [if], data = [none] } return ObjectFilter.FILTER_INCLUDE; // depends on control dependency: [if], data = [none] } } }
public class class_name { protected void parseProcessEngine(Element element, List<ProcessEngineXml> parsedProcessEngines) { ProcessEngineXmlImpl processEngine = new ProcessEngineXmlImpl(); // set name processEngine.setName(element.attribute(NAME)); // set default String defaultValue = element.attribute(DEFAULT); if(defaultValue == null || defaultValue.isEmpty()) { processEngine.setDefault(false); } else { processEngine.setDefault(Boolean.parseBoolean(defaultValue)); } Map<String, String> properties = new HashMap<String, String>(); List<ProcessEnginePluginXml> plugins = new ArrayList<ProcessEnginePluginXml>(); for (Element childElement : element.elements()) { if(CONFIGURATION.equals(childElement.getTagName())) { processEngine.setConfigurationClass(childElement.getText()); } else if(DATASOURCE.equals(childElement.getTagName())) { processEngine.setDatasource(childElement.getText()); } else if(JOB_ACQUISITION.equals(childElement.getTagName())) { processEngine.setJobAcquisitionName(childElement.getText()); } else if(PROPERTIES.equals(childElement.getTagName())) { parseProperties(childElement, properties); } else if(PLUGINS.equals(childElement.getTagName())) { parseProcessEnginePlugins(childElement, plugins); } } // set collected properties processEngine.setProperties(properties); // set plugins processEngine.setPlugins(plugins); // add the process engine to the list of parsed engines. parsedProcessEngines.add(processEngine); } }
public class class_name { protected void parseProcessEngine(Element element, List<ProcessEngineXml> parsedProcessEngines) { ProcessEngineXmlImpl processEngine = new ProcessEngineXmlImpl(); // set name processEngine.setName(element.attribute(NAME)); // set default String defaultValue = element.attribute(DEFAULT); if(defaultValue == null || defaultValue.isEmpty()) { processEngine.setDefault(false); // depends on control dependency: [if], data = [none] } else { processEngine.setDefault(Boolean.parseBoolean(defaultValue)); // depends on control dependency: [if], data = [(defaultValue] } Map<String, String> properties = new HashMap<String, String>(); List<ProcessEnginePluginXml> plugins = new ArrayList<ProcessEnginePluginXml>(); for (Element childElement : element.elements()) { if(CONFIGURATION.equals(childElement.getTagName())) { processEngine.setConfigurationClass(childElement.getText()); // depends on control dependency: [if], data = [none] } else if(DATASOURCE.equals(childElement.getTagName())) { processEngine.setDatasource(childElement.getText()); // depends on control dependency: [if], data = [none] } else if(JOB_ACQUISITION.equals(childElement.getTagName())) { processEngine.setJobAcquisitionName(childElement.getText()); // depends on control dependency: [if], data = [none] } else if(PROPERTIES.equals(childElement.getTagName())) { parseProperties(childElement, properties); // depends on control dependency: [if], data = [none] } else if(PLUGINS.equals(childElement.getTagName())) { parseProcessEnginePlugins(childElement, plugins); // depends on control dependency: [if], data = [none] } } // set collected properties processEngine.setProperties(properties); // set plugins processEngine.setPlugins(plugins); // add the process engine to the list of parsed engines. parsedProcessEngines.add(processEngine); } }