code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { private final Connection getConnectionUsingDriver(String userN, String password) throws ResourceException { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(this, tc, "getConnectionUsingDriver", AdapterUtil.toString(dataSourceOrDriver), userN); final String user = userN == null ? null : userN.trim(); final String pwd = password == null ? null : password.trim(); Connection conn = null; boolean isConnectionSetupComplete = false; try { conn = AccessController.doPrivileged(new PrivilegedExceptionAction<Connection>() { public Connection run() throws Exception { Hashtable<?, ?> vProps = dsConfig.get().vendorProps; Properties conProps = new Properties(); String url = null; // convert property values to String and decode passwords for (Map.Entry<?, ?> prop : vProps.entrySet()) { String name = (String) prop.getKey(); Object value = prop.getValue(); if (value instanceof String) { String str = (String) value; if ("URL".equals(name) || "url".equals(name)) { url = str; if (isTraceOn && tc.isDebugEnabled()) Tr.debug(this, tc, name + '=' + PropertyService.filterURL(str)); } else if ((user == null || !"user".equals(name)) && (pwd == null || !"password".equals(name))) { // Decode passwords if (PropertyService.isPassword(name)) { if (isTraceOn && tc.isDebugEnabled()) Tr.debug(this, tc, "prop " + name + '=' + (str == null ? null : "***")); if (PasswordUtil.getCryptoAlgorithm(str) != null) { str = PasswordUtil.decode(str); } } else { if (isTraceOn && tc.isDebugEnabled()) Tr.debug(this, tc, "prop " + name + '=' + str); } conProps.setProperty(name, str); } } else { if (isTraceOn && tc.isDebugEnabled()) Tr.debug(this, tc, "prop " + name + '=' + value); // Convert to String value conProps.setProperty(name, value.toString()); } } if (user != null) { conProps.setProperty("user", user); conProps.setProperty("password", pwd); if (isTraceOn && tc.isDebugEnabled()) { Tr.debug(this, tc, "prop user=" + user); Tr.debug(this, tc, "prop password=" + (pwd == null ? null : "***")); } } Connection conn = ((Driver) dataSourceOrDriver).connect(url, conProps); //Although possible, this shouldn't happen since the JDBC Driver has indicated it can accept the URL if(conn == null) { //return beginning on JDBC url (ex jdbc:db2: String urlPrefix = ""; int first = url.indexOf(":"); int second = url.indexOf(":", first+1); if(first < 0 || second < 0) { urlPrefix = url.substring(0, 10); } else { urlPrefix = url.substring(0, second); } throw new ResourceException(AdapterUtil.getNLSMessage("DSRA4006.null.connection", dsConfig.get().id, vendorImplClass.getName(), urlPrefix)); } return conn; } }); try { postGetConnectionHandling(conn); } catch (SQLException se) { FFDCFilter.processException(se, getClass().getName(), "871", this); if (isTraceOn && tc.isEntryEnabled()) Tr.exit(this, tc, "getConnectionUsingDriver", se); throw AdapterUtil.translateSQLException(se, this, false, getClass()); } isConnectionSetupComplete = true; } catch (PrivilegedActionException pae) { FFDCFilter.processException(pae.getException(), getClass().getName(), "879"); ResourceException resX = new DataStoreAdapterException("JAVAX_CONN_ERR", pae.getException(), getClass(), "Connection"); if (isTraceOn && tc.isEntryEnabled()) Tr.exit(this, tc, "getConnectionUsingDriver", pae.getException()); throw resX; } catch (ClassCastException castX) { // There's a possibility this occurred because of an error in the JDBC driver // itself. The trace should allow us to determine this. FFDCFilter.processException(castX, getClass().getName(), "887"); ResourceException resX = new DataStoreAdapterException("NOT_A_1_PHASE_DS", null, getClass(), castX.getMessage()); if (isTraceOn && tc.isEntryEnabled()) Tr.exit(this, tc, "getConnectionUsingDriver", castX); throw resX; } finally { // Destroy the connection if we weren't able to successfully complete the setup. if (conn != null && !isConnectionSetupComplete) try { conn.close(); } catch (Throwable x) { } } if (isTraceOn && tc.isEntryEnabled()) Tr.exit(this, tc, "getConnectionUsingDriver", AdapterUtil.toString(conn)); return conn; } }
public class class_name { private final Connection getConnectionUsingDriver(String userN, String password) throws ResourceException { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(this, tc, "getConnectionUsingDriver", AdapterUtil.toString(dataSourceOrDriver), userN); final String user = userN == null ? null : userN.trim(); final String pwd = password == null ? null : password.trim(); Connection conn = null; boolean isConnectionSetupComplete = false; try { conn = AccessController.doPrivileged(new PrivilegedExceptionAction<Connection>() { public Connection run() throws Exception { Hashtable<?, ?> vProps = dsConfig.get().vendorProps; Properties conProps = new Properties(); String url = null; // convert property values to String and decode passwords for (Map.Entry<?, ?> prop : vProps.entrySet()) { String name = (String) prop.getKey(); Object value = prop.getValue(); if (value instanceof String) { String str = (String) value; if ("URL".equals(name) || "url".equals(name)) { url = str; // depends on control dependency: [if], data = [none] if (isTraceOn && tc.isDebugEnabled()) Tr.debug(this, tc, name + '=' + PropertyService.filterURL(str)); } else if ((user == null || !"user".equals(name)) && (pwd == null || !"password".equals(name))) { // Decode passwords if (PropertyService.isPassword(name)) { if (isTraceOn && tc.isDebugEnabled()) Tr.debug(this, tc, "prop " + name + '=' + (str == null ? null : "***")); if (PasswordUtil.getCryptoAlgorithm(str) != null) { str = PasswordUtil.decode(str); // depends on control dependency: [if], data = [none] } } else { if (isTraceOn && tc.isDebugEnabled()) Tr.debug(this, tc, "prop " + name + '=' + str); } conProps.setProperty(name, str); // depends on control dependency: [if], data = [none] } } else { if (isTraceOn && tc.isDebugEnabled()) Tr.debug(this, tc, "prop " + name + '=' + value); // Convert to String value conProps.setProperty(name, value.toString()); } } if (user != null) { conProps.setProperty("user", user); conProps.setProperty("password", pwd); if (isTraceOn && tc.isDebugEnabled()) { Tr.debug(this, tc, "prop user=" + user); Tr.debug(this, tc, "prop password=" + (pwd == null ? null : "***")); } } Connection conn = ((Driver) dataSourceOrDriver).connect(url, conProps); //Although possible, this shouldn't happen since the JDBC Driver has indicated it can accept the URL if(conn == null) { //return beginning on JDBC url (ex jdbc:db2: String urlPrefix = ""; int first = url.indexOf(":"); int second = url.indexOf(":", first+1); if(first < 0 || second < 0) { urlPrefix = url.substring(0, 10); } else { urlPrefix = url.substring(0, second); } throw new ResourceException(AdapterUtil.getNLSMessage("DSRA4006.null.connection", dsConfig.get().id, vendorImplClass.getName(), urlPrefix)); } return conn; } }); try { postGetConnectionHandling(conn); } catch (SQLException se) { FFDCFilter.processException(se, getClass().getName(), "871", this); if (isTraceOn && tc.isEntryEnabled()) Tr.exit(this, tc, "getConnectionUsingDriver", se); throw AdapterUtil.translateSQLException(se, this, false, getClass()); } isConnectionSetupComplete = true; } catch (PrivilegedActionException pae) { FFDCFilter.processException(pae.getException(), getClass().getName(), "879"); ResourceException resX = new DataStoreAdapterException("JAVAX_CONN_ERR", pae.getException(), getClass(), "Connection"); if (isTraceOn && tc.isEntryEnabled()) Tr.exit(this, tc, "getConnectionUsingDriver", pae.getException()); throw resX; } catch (ClassCastException castX) { // There's a possibility this occurred because of an error in the JDBC driver // itself. The trace should allow us to determine this. FFDCFilter.processException(castX, getClass().getName(), "887"); ResourceException resX = new DataStoreAdapterException("NOT_A_1_PHASE_DS", null, getClass(), castX.getMessage()); if (isTraceOn && tc.isEntryEnabled()) Tr.exit(this, tc, "getConnectionUsingDriver", castX); throw resX; } finally { // Destroy the connection if we weren't able to successfully complete the setup. if (conn != null && !isConnectionSetupComplete) try { conn.close(); } catch (Throwable x) { } } if (isTraceOn && tc.isEntryEnabled()) Tr.exit(this, tc, "getConnectionUsingDriver", AdapterUtil.toString(conn)); return conn; } }
public class class_name { public static CryptonitGenericOrder adaptOrder( String orderId, CryptonitOrderStatusResponse cryptonitOrderStatusResponse) { CryptonitOrderTransaction[] cryptonitTransactions = cryptonitOrderStatusResponse.getTransactions(); CurrencyPair currencyPair = null; Date date = null; BigDecimal averagePrice = null; BigDecimal cumulativeAmount = null; BigDecimal totalFee = null; // Use only the first transaction, because we assume that for a single order id all transactions // will // be of the same currency pair if (cryptonitTransactions.length > 0) { currencyPair = adaptCurrencyPair(cryptonitTransactions[0]); date = cryptonitTransactions[0].getDatetime(); averagePrice = Arrays.stream(cryptonitTransactions) .map(t -> t.getPrice()) .reduce((x, y) -> x.add(y)) .get() .divide(BigDecimal.valueOf(cryptonitTransactions.length), 2); cumulativeAmount = Arrays.stream(cryptonitTransactions) .map(t -> getBaseCurrencyAmountFromCryptonitTransaction(t)) .reduce((x, y) -> x.add(y)) .get(); totalFee = Arrays.stream(cryptonitTransactions) .map(t -> t.getFee()) .reduce((x, y) -> x.add(y)) .get(); } OrderStatus orderStatus = adaptOrderStatus(cryptonitOrderStatusResponse.getStatus(), cryptonitTransactions.length); CryptonitGenericOrder cryptonitGenericOrder = new CryptonitGenericOrder( null, // not discernable from response data null, // not discernable from the data currencyPair, orderId, date, averagePrice, cumulativeAmount, totalFee, orderStatus); return cryptonitGenericOrder; } }
public class class_name { public static CryptonitGenericOrder adaptOrder( String orderId, CryptonitOrderStatusResponse cryptonitOrderStatusResponse) { CryptonitOrderTransaction[] cryptonitTransactions = cryptonitOrderStatusResponse.getTransactions(); CurrencyPair currencyPair = null; Date date = null; BigDecimal averagePrice = null; BigDecimal cumulativeAmount = null; BigDecimal totalFee = null; // Use only the first transaction, because we assume that for a single order id all transactions // will // be of the same currency pair if (cryptonitTransactions.length > 0) { currencyPair = adaptCurrencyPair(cryptonitTransactions[0]); // depends on control dependency: [if], data = [none] date = cryptonitTransactions[0].getDatetime(); // depends on control dependency: [if], data = [none] averagePrice = Arrays.stream(cryptonitTransactions) .map(t -> t.getPrice()) .reduce((x, y) -> x.add(y)) .get() .divide(BigDecimal.valueOf(cryptonitTransactions.length), 2); // depends on control dependency: [if], data = [(cryptonitTransactions.length] cumulativeAmount = Arrays.stream(cryptonitTransactions) .map(t -> getBaseCurrencyAmountFromCryptonitTransaction(t)) .reduce((x, y) -> x.add(y)) .get(); // depends on control dependency: [if], data = [none] totalFee = Arrays.stream(cryptonitTransactions) .map(t -> t.getFee()) .reduce((x, y) -> x.add(y)) .get(); // depends on control dependency: [if], data = [none] } OrderStatus orderStatus = adaptOrderStatus(cryptonitOrderStatusResponse.getStatus(), cryptonitTransactions.length); CryptonitGenericOrder cryptonitGenericOrder = new CryptonitGenericOrder( null, // not discernable from response data null, // not discernable from the data currencyPair, orderId, date, averagePrice, cumulativeAmount, totalFee, orderStatus); return cryptonitGenericOrder; } }
public class class_name { public static final SupportFragment shadow(Object fragment, IckleSupportManager.Builder supportManagerBuilder) { boolean hasIllegalArguments = false; StringBuilder errorContext = new StringBuilder(); if(fragment == null) { errorContext .append("Either an instance of ") .append(android.app.Fragment.class.getName()) .append(" or ") .append(android.support.v4.app.Fragment.class.getName()) .append(" must be supplied. "); hasIllegalArguments = true; } if(supportManagerBuilder == null) { errorContext .append("An instance of ") .append(IckleSupportManager.Builder.class.getName()) .append(" must be supplied. "); hasIllegalArguments = true; } if(hasIllegalArguments) throw new IckleBotRuntimeException(new IllegalArgumentException(errorContext.toString())); if(supportManagerBuilder != null && supportManagerBuilder.isBuilt()) { errorContext .append("The provided ") .append(IckleSupportManager.Builder.class.getName()) .append(" has already been built. These builders are non-reusable"); throw new IckleBotRuntimeException(new IllegalStateException(errorContext.toString())); } return new IckleSupportFragment(fragment, supportManagerBuilder); } }
public class class_name { public static final SupportFragment shadow(Object fragment, IckleSupportManager.Builder supportManagerBuilder) { boolean hasIllegalArguments = false; StringBuilder errorContext = new StringBuilder(); if(fragment == null) { errorContext .append("Either an instance of ") .append(android.app.Fragment.class.getName()) .append(" or ") .append(android.support.v4.app.Fragment.class.getName()) .append(" must be supplied. "); // depends on control dependency: [if], data = [none] hasIllegalArguments = true; // depends on control dependency: [if], data = [none] } if(supportManagerBuilder == null) { errorContext .append("An instance of ") .append(IckleSupportManager.Builder.class.getName()) .append(" must be supplied. "); // depends on control dependency: [if], data = [none] hasIllegalArguments = true; // depends on control dependency: [if], data = [none] } if(hasIllegalArguments) throw new IckleBotRuntimeException(new IllegalArgumentException(errorContext.toString())); if(supportManagerBuilder != null && supportManagerBuilder.isBuilt()) { errorContext .append("The provided ") .append(IckleSupportManager.Builder.class.getName()) .append(" has already been built. These builders are non-reusable"); // depends on control dependency: [if], data = [none] throw new IckleBotRuntimeException(new IllegalStateException(errorContext.toString())); } return new IckleSupportFragment(fragment, supportManagerBuilder); } }
public class class_name { public String getStrippedSubstring() { // TODO: detect Java <6 and make sure we only return the substring? // With java 7, String.substring will arraycopy the characters. int sstart = start, send = end; while(sstart < send) { char c = input.charAt(sstart); if(c != ' ' || c != '\n' || c != '\r' || c != '\t') { break; } ++sstart; } while(--send >= sstart) { char c = input.charAt(send); if(c != ' ' || c != '\n' || c != '\r' || c != '\t') { break; } } ++send; return (sstart < send) ? input.subSequence(sstart, send).toString() : ""; } }
public class class_name { public String getStrippedSubstring() { // TODO: detect Java <6 and make sure we only return the substring? // With java 7, String.substring will arraycopy the characters. int sstart = start, send = end; while(sstart < send) { char c = input.charAt(sstart); if(c != ' ' || c != '\n' || c != '\r' || c != '\t') { break; } ++sstart; // depends on control dependency: [while], data = [none] } while(--send >= sstart) { char c = input.charAt(send); if(c != ' ' || c != '\n' || c != '\r' || c != '\t') { break; } } ++send; return (sstart < send) ? input.subSequence(sstart, send).toString() : ""; } }
public class class_name { public void setInitialSequence(int[] sequence) { if(models != null){ for(int i = 0; i < models.length; i++) models[i].setInitialSequence(sequence); return; } model1.setInitialSequence(sequence); model2.setInitialSequence(sequence); } }
public class class_name { public void setInitialSequence(int[] sequence) { if(models != null){ for(int i = 0; i < models.length; i++) models[i].setInitialSequence(sequence); return; // depends on control dependency: [if], data = [none] } model1.setInitialSequence(sequence); model2.setInitialSequence(sequence); } }
public class class_name { private Future<?> flushDataFrom(List<CommitLogSegment> segments, boolean force) { if (segments.isEmpty()) return Futures.immediateFuture(null); final ReplayPosition maxReplayPosition = segments.get(segments.size() - 1).getContext(); // a map of CfId -> forceFlush() to ensure we only queue one flush per cf final Map<UUID, ListenableFuture<?>> flushes = new LinkedHashMap<>(); for (CommitLogSegment segment : segments) { for (UUID dirtyCFId : segment.getDirtyCFIDs()) { Pair<String,String> pair = Schema.instance.getCF(dirtyCFId); if (pair == null) { // even though we remove the schema entry before a final flush when dropping a CF, // it's still possible for a writer to race and finish his append after the flush. logger.debug("Marking clean CF {} that doesn't exist anymore", dirtyCFId); segment.markClean(dirtyCFId, segment.getContext()); } else if (!flushes.containsKey(dirtyCFId)) { String keyspace = pair.left; final ColumnFamilyStore cfs = Keyspace.open(keyspace).getColumnFamilyStore(dirtyCFId); // can safely call forceFlush here as we will only ever block (briefly) for other attempts to flush, // no deadlock possibility since switchLock removal flushes.put(dirtyCFId, force ? cfs.forceFlush() : cfs.forceFlush(maxReplayPosition)); } } } return Futures.allAsList(flushes.values()); } }
public class class_name { private Future<?> flushDataFrom(List<CommitLogSegment> segments, boolean force) { if (segments.isEmpty()) return Futures.immediateFuture(null); final ReplayPosition maxReplayPosition = segments.get(segments.size() - 1).getContext(); // a map of CfId -> forceFlush() to ensure we only queue one flush per cf final Map<UUID, ListenableFuture<?>> flushes = new LinkedHashMap<>(); for (CommitLogSegment segment : segments) { for (UUID dirtyCFId : segment.getDirtyCFIDs()) { Pair<String,String> pair = Schema.instance.getCF(dirtyCFId); if (pair == null) { // even though we remove the schema entry before a final flush when dropping a CF, // it's still possible for a writer to race and finish his append after the flush. logger.debug("Marking clean CF {} that doesn't exist anymore", dirtyCFId); // depends on control dependency: [if], data = [none] segment.markClean(dirtyCFId, segment.getContext()); // depends on control dependency: [if], data = [none] } else if (!flushes.containsKey(dirtyCFId)) { String keyspace = pair.left; final ColumnFamilyStore cfs = Keyspace.open(keyspace).getColumnFamilyStore(dirtyCFId); // can safely call forceFlush here as we will only ever block (briefly) for other attempts to flush, // no deadlock possibility since switchLock removal flushes.put(dirtyCFId, force ? cfs.forceFlush() : cfs.forceFlush(maxReplayPosition)); // depends on control dependency: [if], data = [none] } } } return Futures.allAsList(flushes.values()); } }
public class class_name { public java.util.List<java.util.Date> getTimestamps() { if (timestamps == null) { timestamps = new com.amazonaws.internal.SdkInternalList<java.util.Date>(); } return timestamps; } }
public class class_name { public java.util.List<java.util.Date> getTimestamps() { if (timestamps == null) { timestamps = new com.amazonaws.internal.SdkInternalList<java.util.Date>(); // depends on control dependency: [if], data = [none] } return timestamps; } }
public class class_name { public void setDirectoryUser(String userName, String password){ this.authData = generateDirectoryAuthData(userName, password); if(getStatus().isConnected()){ ErrorCode ec = sendConnectProtocol(this.getConnectTimeOut()); if(ErrorCode.SESSION_EXPIRED.equals(ec)){ LOGGER.info("Session Expired, cleanup the client session."); closeSession(); } else if(! ErrorCode.OK.equals(ec)){ reopenSession(); } } } }
public class class_name { public void setDirectoryUser(String userName, String password){ this.authData = generateDirectoryAuthData(userName, password); if(getStatus().isConnected()){ ErrorCode ec = sendConnectProtocol(this.getConnectTimeOut()); if(ErrorCode.SESSION_EXPIRED.equals(ec)){ LOGGER.info("Session Expired, cleanup the client session."); // depends on control dependency: [if], data = [none] closeSession(); // depends on control dependency: [if], data = [none] } else if(! ErrorCode.OK.equals(ec)){ reopenSession(); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public static String getVariantKey(Map<String, String> curVariants, Set<String> variantTypes) { String variantKey = ""; if (curVariants != null && variantTypes != null) { Map<String, String> tempVariants = new TreeMap<>(curVariants); StringBuilder variantKeyBuf = new StringBuilder(); for (Entry<String, String> entry : tempVariants.entrySet()) { if (variantTypes.contains(entry.getKey())) { String value = entry.getValue(); if (value == null) { value = ""; } variantKeyBuf.append(value + JawrConstant.VARIANT_SEPARATOR_CHAR); } } variantKey = variantKeyBuf.toString(); if (StringUtils.isNotEmpty(variantKey) && variantKey.charAt(variantKey.length() - 1) == JawrConstant.VARIANT_SEPARATOR_CHAR) { variantKey = variantKey.substring(0, variantKey.length() - 1); } } return variantKey; } }
public class class_name { public static String getVariantKey(Map<String, String> curVariants, Set<String> variantTypes) { String variantKey = ""; if (curVariants != null && variantTypes != null) { Map<String, String> tempVariants = new TreeMap<>(curVariants); StringBuilder variantKeyBuf = new StringBuilder(); for (Entry<String, String> entry : tempVariants.entrySet()) { if (variantTypes.contains(entry.getKey())) { String value = entry.getValue(); if (value == null) { value = ""; // depends on control dependency: [if], data = [none] } variantKeyBuf.append(value + JawrConstant.VARIANT_SEPARATOR_CHAR); // depends on control dependency: [if], data = [none] } } variantKey = variantKeyBuf.toString(); // depends on control dependency: [if], data = [none] if (StringUtils.isNotEmpty(variantKey) && variantKey.charAt(variantKey.length() - 1) == JawrConstant.VARIANT_SEPARATOR_CHAR) { variantKey = variantKey.substring(0, variantKey.length() - 1); // depends on control dependency: [if], data = [none] } } return variantKey; } }
public class class_name { public int nextNode() { if (m_foundLast) return DTM.NULL; int next; m_lastFetched = next = (DTM.NULL == m_lastFetched) ? m_context : DTM.NULL; // m_lastFetched = next; if (DTM.NULL != next) { m_pos++; return next; } else { m_foundLast = true; return DTM.NULL; } } }
public class class_name { public int nextNode() { if (m_foundLast) return DTM.NULL; int next; m_lastFetched = next = (DTM.NULL == m_lastFetched) ? m_context : DTM.NULL; // m_lastFetched = next; if (DTM.NULL != next) { m_pos++; // depends on control dependency: [if], data = [none] return next; // depends on control dependency: [if], data = [none] } else { m_foundLast = true; // depends on control dependency: [if], data = [none] return DTM.NULL; // depends on control dependency: [if], data = [none] } } }
public class class_name { private void record(long offset) { if (config.recorder == null || offset == 0) { return; } String data = format(Locale.ENGLISH, "{\"size\":%d,\"offset\":%d, \"modify_time\":%d, \"contexts\":[%s]}", totalSize, offset, modifyTime, StringUtils.jsonJoin(contexts)); config.recorder.set(recorderKey, data.getBytes()); } }
public class class_name { private void record(long offset) { if (config.recorder == null || offset == 0) { return; // depends on control dependency: [if], data = [none] } String data = format(Locale.ENGLISH, "{\"size\":%d,\"offset\":%d, \"modify_time\":%d, \"contexts\":[%s]}", totalSize, offset, modifyTime, StringUtils.jsonJoin(contexts)); config.recorder.set(recorderKey, data.getBytes()); } }
public class class_name { public int getIdentifier() { if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) { trace.entry(this, cclass , "getIdentifier" ); trace.exit(this, cclass , "getIdentifier" , "returns objectStoreIdentifier=" + objectStoreIdentifier + "(int)" ); } return objectStoreIdentifier; } }
public class class_name { public int getIdentifier() { if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) { trace.entry(this, cclass , "getIdentifier" ); // depends on control dependency: [if], data = [none] trace.exit(this, cclass , "getIdentifier" , "returns objectStoreIdentifier=" + objectStoreIdentifier + "(int)" ); } return objectStoreIdentifier; // depends on control dependency: [if], data = [none] } }
public class class_name { public void addRosterEntry(RosterEntry rosterEntry) { // Obtain a String[] from the roster entry groups name List<String> groupNamesList = new ArrayList<>(); String[] groupNames; for (RosterGroup group : rosterEntry.getGroups()) { groupNamesList.add(group.getName()); } groupNames = groupNamesList.toArray(new String[groupNamesList.size()]); // Create a new Entry based on the rosterEntry and add it to the packet RemoteRosterEntry remoteRosterEntry = new RemoteRosterEntry(rosterEntry.getJid(), rosterEntry.getName(), groupNames); addRosterEntry(remoteRosterEntry); } }
public class class_name { public void addRosterEntry(RosterEntry rosterEntry) { // Obtain a String[] from the roster entry groups name List<String> groupNamesList = new ArrayList<>(); String[] groupNames; for (RosterGroup group : rosterEntry.getGroups()) { groupNamesList.add(group.getName()); // depends on control dependency: [for], data = [group] } groupNames = groupNamesList.toArray(new String[groupNamesList.size()]); // Create a new Entry based on the rosterEntry and add it to the packet RemoteRosterEntry remoteRosterEntry = new RemoteRosterEntry(rosterEntry.getJid(), rosterEntry.getName(), groupNames); addRosterEntry(remoteRosterEntry); } }
public class class_name { static public String allow(String x, String allowChars, char replaceChar) { boolean ok = true; for (int pos = 0; pos < x.length(); pos++) { char c = x.charAt(pos); if (!(Character.isLetterOrDigit(c) || (0 <= allowChars.indexOf(c)))) { ok = false; break; } } if (ok) return x; // gotta do it StringBuilder sb = new StringBuilder(x); for (int pos = 0; pos < sb.length(); pos++) { char c = sb.charAt(pos); if (Character.isLetterOrDigit(c) || (0 <= allowChars.indexOf(c))) { continue; } sb.setCharAt(pos, replaceChar); } return sb.toString(); } }
public class class_name { static public String allow(String x, String allowChars, char replaceChar) { boolean ok = true; for (int pos = 0; pos < x.length(); pos++) { char c = x.charAt(pos); if (!(Character.isLetterOrDigit(c) || (0 <= allowChars.indexOf(c)))) { ok = false; // depends on control dependency: [if], data = [none] break; } } if (ok) return x; // gotta do it StringBuilder sb = new StringBuilder(x); for (int pos = 0; pos < sb.length(); pos++) { char c = sb.charAt(pos); if (Character.isLetterOrDigit(c) || (0 <= allowChars.indexOf(c))) { continue; } sb.setCharAt(pos, replaceChar); // depends on control dependency: [for], data = [pos] } return sb.toString(); } }
public class class_name { private void plantCookie(HttpServletRequest request, HttpServletResponse response) { String xId = CookieUtils.getCookieValue(request, LoginConstant.XONE_COOKIE_NAME_STRING); // 没有Cookie 则生成一个随机的Cookie if (xId == null) { String cookieString = TokenUtil.generateToken(); CookieUtils .setCookie(response, LoginConstant.XONE_COOKIE_NAME_STRING, cookieString, XONE_COOKIE_DOMAIN_STRING, LoginConstant.XONE_COOKIE_AGE); } else { } } }
public class class_name { private void plantCookie(HttpServletRequest request, HttpServletResponse response) { String xId = CookieUtils.getCookieValue(request, LoginConstant.XONE_COOKIE_NAME_STRING); // 没有Cookie 则生成一个随机的Cookie if (xId == null) { String cookieString = TokenUtil.generateToken(); CookieUtils .setCookie(response, LoginConstant.XONE_COOKIE_NAME_STRING, cookieString, XONE_COOKIE_DOMAIN_STRING, LoginConstant.XONE_COOKIE_AGE); // depends on control dependency: [if], data = [none] } else { } } }
public class class_name { public void writeMethodInterface(String strProtection, String strMethodName, String strReturns, String strParams, String strThrows, String strDescription, String strCodeBody) { if ((strProtection == null) || (strProtection.length() == 0)) strProtection = "public"; String strInterfaceEnd = "\n"; if (strCodeBody == null) strCodeBody = "{\n"; if (";\n".equals(strCodeBody)) { strInterfaceEnd = strCodeBody; strCodeBody = null; } String strDesc = strDescription; if (strDesc.length() == 0) { strDesc = strMethodName + " Method"; strDesc = new Character(Character.toUpperCase(strDesc.charAt(0))) + strDesc.substring(1); } strDesc = this.convertDescToJavaDoc(strDesc); if (strThrows.length() > 0) strThrows = " throws " + strThrows; m_StreamOut.writeit("/**\n" + strDesc + "\n */\n"); if (strParams.equalsIgnoreCase("void")) strParams = DBConstants.BLANK; if (strReturns.length() == 0) { m_StreamOut.writeit("public " + strMethodName + "(" + strParams + ")" + strThrows + "\n"); m_strParams = strParams; // Also default params for Init() call! } else m_StreamOut.writeit(strProtection + " " + strReturns + " " + strMethodName + "(" + strParams + ")" + strThrows + strInterfaceEnd); if (strCodeBody != null) m_StreamOut.writeit(strCodeBody); } }
public class class_name { public void writeMethodInterface(String strProtection, String strMethodName, String strReturns, String strParams, String strThrows, String strDescription, String strCodeBody) { if ((strProtection == null) || (strProtection.length() == 0)) strProtection = "public"; String strInterfaceEnd = "\n"; if (strCodeBody == null) strCodeBody = "{\n"; if (";\n".equals(strCodeBody)) { strInterfaceEnd = strCodeBody; // depends on control dependency: [if], data = [none] strCodeBody = null; // depends on control dependency: [if], data = [none] } String strDesc = strDescription; if (strDesc.length() == 0) { strDesc = strMethodName + " Method"; // depends on control dependency: [if], data = [none] strDesc = new Character(Character.toUpperCase(strDesc.charAt(0))) + strDesc.substring(1); // depends on control dependency: [if], data = [0)] } strDesc = this.convertDescToJavaDoc(strDesc); if (strThrows.length() > 0) strThrows = " throws " + strThrows; m_StreamOut.writeit("/**\n" + strDesc + "\n */\n"); if (strParams.equalsIgnoreCase("void")) strParams = DBConstants.BLANK; if (strReturns.length() == 0) { m_StreamOut.writeit("public " + strMethodName + "(" + strParams + ")" + strThrows + "\n"); m_strParams = strParams; // Also default params for Init() call! // depends on control dependency: [if], data = [none] } else m_StreamOut.writeit(strProtection + " " + strReturns + " " + strMethodName + "(" + strParams + ")" + strThrows + strInterfaceEnd); if (strCodeBody != null) m_StreamOut.writeit(strCodeBody); } }
public class class_name { protected void traverseMap(Deque<JsonObject<String, Object>> stack, JsonObject<String, Object> jsonObj) { // Convert @keys to a Collection of Java objects. convertMapToKeysItems(jsonObj); final Object[] keys = (Object[]) jsonObj.get("@keys"); final Object[] items = jsonObj.getArray(); if (keys == null || items == null) { if (keys != items) { throw new JsonIoException("Map written where one of @keys or @items is empty"); } return; } final int size = keys.length; if (size != items.length) { throw new JsonIoException("Map written with @keys and @items entries of different sizes"); } Object[] mapKeys = buildCollection(stack, keys, size); Object[] mapValues = buildCollection(stack, items, size); // Save these for later so that unresolved references inside keys or values // get patched first, and then build the Maps. prettyMaps.add(new Object[]{jsonObj, mapKeys, mapValues}); } }
public class class_name { protected void traverseMap(Deque<JsonObject<String, Object>> stack, JsonObject<String, Object> jsonObj) { // Convert @keys to a Collection of Java objects. convertMapToKeysItems(jsonObj); final Object[] keys = (Object[]) jsonObj.get("@keys"); final Object[] items = jsonObj.getArray(); if (keys == null || items == null) { if (keys != items) { throw new JsonIoException("Map written where one of @keys or @items is empty"); } return; // depends on control dependency: [if], data = [none] } final int size = keys.length; if (size != items.length) { throw new JsonIoException("Map written with @keys and @items entries of different sizes"); } Object[] mapKeys = buildCollection(stack, keys, size); Object[] mapValues = buildCollection(stack, items, size); // Save these for later so that unresolved references inside keys or values // get patched first, and then build the Maps. prettyMaps.add(new Object[]{jsonObj, mapKeys, mapValues}); } }
public class class_name { public static void assertFalse(boolean condition, String message) { if (imp != null && condition) { imp.assertFailed(message); } } }
public class class_name { public static void assertFalse(boolean condition, String message) { if (imp != null && condition) { imp.assertFailed(message); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void setComment(String comment) { this.comment = comment; if (!Strings.isEmpty(comment)) { this.name = MessageFormat.format("{0} [{1}]", getClass().getName(), comment); //$NON-NLS-1$ } else { this.name = getClass().getName(); } } }
public class class_name { public void setComment(String comment) { this.comment = comment; if (!Strings.isEmpty(comment)) { this.name = MessageFormat.format("{0} [{1}]", getClass().getName(), comment); //$NON-NLS-1$ // depends on control dependency: [if], data = [none] } else { this.name = getClass().getName(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void visit( DependencyNode node, boolean collecting ) { if ( collecting ) { dependencies.add( node.getArtifact() ); } if ( matchesTarget( node.getArtifact() ) ) { collecting = true; log.debug( "Found target. Collecting dependencies after " + node.getArtifact() ); } for ( final DependencyNode child : node.getChildren() ) { visit( child, collecting ); } } }
public class class_name { public void visit( DependencyNode node, boolean collecting ) { if ( collecting ) { dependencies.add( node.getArtifact() ); // depends on control dependency: [if], data = [none] } if ( matchesTarget( node.getArtifact() ) ) { collecting = true; // depends on control dependency: [if], data = [none] log.debug( "Found target. Collecting dependencies after " + node.getArtifact() ); // depends on control dependency: [if], data = [none] } for ( final DependencyNode child : node.getChildren() ) { visit( child, collecting ); // depends on control dependency: [for], data = [child] } } }
public class class_name { protected PlanNode createCanonicalPlan( QueryContext context, SetQuery query ) { // Process the left and right parts of the query ... PlanNode left = createPlan(context, query.getLeft()); PlanNode right = createPlan(context, query.getRight()); // Wrap in a set operation node ... PlanNode plan = new PlanNode(Type.SET_OPERATION); plan.addChildren(left, right); plan.setProperty(Property.SET_OPERATION, query.operation()); plan.setProperty(Property.SET_USE_ALL, query.isAll()); // Process the orderings and limits ... plan = attachSorting(context, plan, query.orderings()); plan = attachLimits(context, plan, query.getLimits()); // Capture if we're limiting the results to 1 row and no offset and no sorting ... if (query.getLimits().isLimitedToSingleRowWithNoOffset() && query.orderings().isEmpty()) { context.getHints().isExistsQuery = true; } return plan; } }
public class class_name { protected PlanNode createCanonicalPlan( QueryContext context, SetQuery query ) { // Process the left and right parts of the query ... PlanNode left = createPlan(context, query.getLeft()); PlanNode right = createPlan(context, query.getRight()); // Wrap in a set operation node ... PlanNode plan = new PlanNode(Type.SET_OPERATION); plan.addChildren(left, right); plan.setProperty(Property.SET_OPERATION, query.operation()); plan.setProperty(Property.SET_USE_ALL, query.isAll()); // Process the orderings and limits ... plan = attachSorting(context, plan, query.orderings()); plan = attachLimits(context, plan, query.getLimits()); // Capture if we're limiting the results to 1 row and no offset and no sorting ... if (query.getLimits().isLimitedToSingleRowWithNoOffset() && query.orderings().isEmpty()) { context.getHints().isExistsQuery = true; // depends on control dependency: [if], data = [none] } return plan; } }
public class class_name { @Override public final IEntityFileReporter lazyGet( final Map<String, Object> pAddParam, final String pBeanName) throws Exception { IEntityFileReporter proc = this.reportersMap.get(pBeanName); if (proc == null) { // locking: synchronized (this) { // make sure again whether it's null after locking: proc = this.reportersMap.get(pBeanName); if (proc == null && pBeanName.equals(InvoiceReportPdf.class.getSimpleName())) { proc = lazyGetInvoiceReportPdf(pAddParam); } } } if (proc == null) { throw new ExceptionWithCode(ExceptionWithCode.CONFIGURATION_MISTAKE, "There is no entity processor with name " + pBeanName); } return proc; } }
public class class_name { @Override public final IEntityFileReporter lazyGet( final Map<String, Object> pAddParam, final String pBeanName) throws Exception { IEntityFileReporter proc = this.reportersMap.get(pBeanName); if (proc == null) { // locking: synchronized (this) { // make sure again whether it's null after locking: proc = this.reportersMap.get(pBeanName); if (proc == null && pBeanName.equals(InvoiceReportPdf.class.getSimpleName())) { proc = lazyGetInvoiceReportPdf(pAddParam); // depends on control dependency: [if], data = [none] } } } if (proc == null) { throw new ExceptionWithCode(ExceptionWithCode.CONFIGURATION_MISTAKE, "There is no entity processor with name " + pBeanName); } return proc; } }
public class class_name { public java.util.List<AccountModification> getAccountModifications() { if (accountModifications == null) { accountModifications = new com.amazonaws.internal.SdkInternalList<AccountModification>(); } return accountModifications; } }
public class class_name { public java.util.List<AccountModification> getAccountModifications() { if (accountModifications == null) { accountModifications = new com.amazonaws.internal.SdkInternalList<AccountModification>(); // depends on control dependency: [if], data = [none] } return accountModifications; } }
public class class_name { private ConsoleReaderWrapper initConsole() { ConsoleReaderWrapper consoleReaderWrapper = new ConsoleReaderWrapper(); consoleReaderWrapper.print(""); consoleReaderWrapper.print(question); consoleReaderWrapper.setCompleters(completers); if (history.isPresent()) { consoleReaderWrapper.enableHistoryFrom(history.get()); } else { consoleReaderWrapper.disableHistory(); } return consoleReaderWrapper; } }
public class class_name { private ConsoleReaderWrapper initConsole() { ConsoleReaderWrapper consoleReaderWrapper = new ConsoleReaderWrapper(); consoleReaderWrapper.print(""); consoleReaderWrapper.print(question); consoleReaderWrapper.setCompleters(completers); if (history.isPresent()) { consoleReaderWrapper.enableHistoryFrom(history.get()); // depends on control dependency: [if], data = [none] } else { consoleReaderWrapper.disableHistory(); // depends on control dependency: [if], data = [none] } return consoleReaderWrapper; } }
public class class_name { public EList<Triplet> getCS() { if (cs == null) { cs = new EObjectContainmentEList.Resolving<Triplet>(Triplet.class, this, AfplibPackage.PTX__CS); } return cs; } }
public class class_name { public EList<Triplet> getCS() { if (cs == null) { cs = new EObjectContainmentEList.Resolving<Triplet>(Triplet.class, this, AfplibPackage.PTX__CS); // depends on control dependency: [if], data = [none] } return cs; } }
public class class_name { public int executeTask(final TransactionalProtocolClient.TransactionalOperationListener<ServerOperation> listener, final ServerUpdateTask task) { try { return execute(listener, task.getServerIdentity(), task.getOperation()); } catch (OperationFailedException e) { // Handle failures operation transformation failures final ServerIdentity identity = task.getServerIdentity(); final ServerOperation serverOperation = new ServerOperation(identity, task.getOperation(), null, null, OperationResultTransformer.ORIGINAL_RESULT); final TransactionalProtocolClient.PreparedOperation<ServerOperation> result = BlockingQueueOperationListener.FailedOperation.create(serverOperation, e); listener.operationPrepared(result); recordExecutedRequest(new ExecutedServerRequest(identity, result.getFinalResult(), OperationResultTransformer.ORIGINAL_RESULT)); return 1; // 1 ms timeout since there is no reason to wait for the locally stored result } } }
public class class_name { public int executeTask(final TransactionalProtocolClient.TransactionalOperationListener<ServerOperation> listener, final ServerUpdateTask task) { try { return execute(listener, task.getServerIdentity(), task.getOperation()); // depends on control dependency: [try], data = [none] } catch (OperationFailedException e) { // Handle failures operation transformation failures final ServerIdentity identity = task.getServerIdentity(); final ServerOperation serverOperation = new ServerOperation(identity, task.getOperation(), null, null, OperationResultTransformer.ORIGINAL_RESULT); final TransactionalProtocolClient.PreparedOperation<ServerOperation> result = BlockingQueueOperationListener.FailedOperation.create(serverOperation, e); listener.operationPrepared(result); recordExecutedRequest(new ExecutedServerRequest(identity, result.getFinalResult(), OperationResultTransformer.ORIGINAL_RESULT)); return 1; // 1 ms timeout since there is no reason to wait for the locally stored result } // depends on control dependency: [catch], data = [none] } }
public class class_name { public <T extends Extension> T getExtension(Class<T> clazz) { if (clazz != null) { Extension extension = extensionsMap.get(clazz); if (extension != null) { return clazz.cast(extension); } } return null; } }
public class class_name { public <T extends Extension> T getExtension(Class<T> clazz) { if (clazz != null) { Extension extension = extensionsMap.get(clazz); if (extension != null) { return clazz.cast(extension); // depends on control dependency: [if], data = [(extension] } } return null; } }
public class class_name { public Map<String, String> getLanguageNames() { Map<String, String> languageNames = new HashMap<String, String>(); // For each language key/resource pair for (Map.Entry<String, Resource> entry : resources.entrySet()) { // Get language key and resource String languageKey = entry.getKey(); Resource resource = entry.getValue(); // Get stream for resource InputStream resourceStream = resource.asStream(); if (resourceStream == null) { logger.warn("Expected language resource does not exist: \"{}\".", languageKey); continue; } // Get name node of language try { JsonNode tree = mapper.readTree(resourceStream); JsonNode nameNode = tree.get(LANGUAGE_DISPLAY_NAME_KEY); // Attempt to read language name from node String languageName; if (nameNode == null || (languageName = nameNode.getTextValue()) == null) { logger.warn("Root-level \"" + LANGUAGE_DISPLAY_NAME_KEY + "\" string missing or invalid in language \"{}\"", languageKey); languageName = languageKey; } // Add language key/name pair to map languageNames.put(languageKey, languageName); } // Continue with next language if unable to read catch (IOException e) { logger.warn("Unable to read language resource \"{}\".", languageKey); logger.debug("Error reading language resource.", e); } } return Collections.unmodifiableMap(languageNames); } }
public class class_name { public Map<String, String> getLanguageNames() { Map<String, String> languageNames = new HashMap<String, String>(); // For each language key/resource pair for (Map.Entry<String, Resource> entry : resources.entrySet()) { // Get language key and resource String languageKey = entry.getKey(); Resource resource = entry.getValue(); // Get stream for resource InputStream resourceStream = resource.asStream(); if (resourceStream == null) { logger.warn("Expected language resource does not exist: \"{}\".", languageKey); // depends on control dependency: [if], data = [none] continue; } // Get name node of language try { JsonNode tree = mapper.readTree(resourceStream); JsonNode nameNode = tree.get(LANGUAGE_DISPLAY_NAME_KEY); // Attempt to read language name from node String languageName; if (nameNode == null || (languageName = nameNode.getTextValue()) == null) { logger.warn("Root-level \"" + LANGUAGE_DISPLAY_NAME_KEY + "\" string missing or invalid in language \"{}\"", languageKey); // depends on control dependency: [if], data = [none] languageName = languageKey; // depends on control dependency: [if], data = [none] } // Add language key/name pair to map languageNames.put(languageKey, languageName); } // Continue with next language if unable to read catch (IOException e) { logger.warn("Unable to read language resource \"{}\".", languageKey); logger.debug("Error reading language resource.", e); } } return Collections.unmodifiableMap(languageNames); } }
public class class_name { public static List<String> getWords(int count, boolean startLorem) { LinkedList<String> wordList = new LinkedList<String>(); if (startLorem) { if (count > COMMON_WORDS.length) { wordList.addAll(Arrays.asList(COMMON_WORDS)); } else { // add first "count" words for (int i = 0; i < count; i++) { wordList.add(COMMON_WORDS[i]); } } } // add remaining words (random) for (int i = wordList.size(); i < count; i++) { wordList.add(QuickUtils.math.getRandomPosition(DICTIONARY)); } return wordList; } }
public class class_name { public static List<String> getWords(int count, boolean startLorem) { LinkedList<String> wordList = new LinkedList<String>(); if (startLorem) { if (count > COMMON_WORDS.length) { wordList.addAll(Arrays.asList(COMMON_WORDS)); // depends on control dependency: [if], data = [none] } else { // add first "count" words for (int i = 0; i < count; i++) { wordList.add(COMMON_WORDS[i]); // depends on control dependency: [for], data = [i] } } } // add remaining words (random) for (int i = wordList.size(); i < count; i++) { wordList.add(QuickUtils.math.getRandomPosition(DICTIONARY)); // depends on control dependency: [for], data = [none] } return wordList; } }
public class class_name { public LookUpStrategy determineLookUpStrategy(Object object) { Class<?> objectClass = object.getClass(); return decisionCache.computeIfAbsent(objectClass, key -> { if (object.getClass().isEnum()) { return new ImmutableLookUpStrategy(); } switch (lookUpStrategyType) { case PLANNING_ID_OR_NONE: MemberAccessor memberAccessor1 = ConfigUtils.findPlanningIdMemberAccessor(objectClass); if (memberAccessor1 == null) { return new NoneLookUpStrategy(); } return new PlanningIdLookUpStrategy(memberAccessor1); case PLANNING_ID_OR_FAIL_FAST: MemberAccessor memberAccessor2 = ConfigUtils.findPlanningIdMemberAccessor(objectClass); if (memberAccessor2 == null) { throw new IllegalArgumentException("The class (" + objectClass + ") does not have a " + PlanningId.class.getSimpleName() + " annotation," + " but the lookUpStrategyType (" + lookUpStrategyType + ") requires it.\n" + "Maybe add the " + PlanningId.class.getSimpleName() + " annotation" + " or change the " + PlanningSolution.class.getSimpleName() + " annotation's " + LookUpStrategyType.class.getSimpleName() + "."); } return new PlanningIdLookUpStrategy(memberAccessor2); case EQUALITY: Method equalsMethod; Method hashCodeMethod; try { equalsMethod = object.getClass().getMethod("equals", Object.class); hashCodeMethod = object.getClass().getMethod("hashCode"); } catch (NoSuchMethodException e) { throw new IllegalStateException( "Impossible state because equals() and hashCode() always exist.", e); } if (equalsMethod.getDeclaringClass().equals(Object.class)) { throw new IllegalArgumentException("The class (" + object.getClass().getSimpleName() + ") doesn't override the equals() method, neither does any superclass."); } if (hashCodeMethod.getDeclaringClass().equals(Object.class)) { throw new IllegalArgumentException("The class (" + object.getClass().getSimpleName() + ") overrides equals() but neither it nor any superclass" + " overrides the hashCode() method."); } return new EqualsLookUpStrategy(); case NONE: return new NoneLookUpStrategy(); default: throw new IllegalStateException("The lookUpStrategyType (" + lookUpStrategyType + ") is not implemented."); } }); } }
public class class_name { public LookUpStrategy determineLookUpStrategy(Object object) { Class<?> objectClass = object.getClass(); return decisionCache.computeIfAbsent(objectClass, key -> { if (object.getClass().isEnum()) { return new ImmutableLookUpStrategy(); } switch (lookUpStrategyType) { case PLANNING_ID_OR_NONE: MemberAccessor memberAccessor1 = ConfigUtils.findPlanningIdMemberAccessor(objectClass); if (memberAccessor1 == null) { return new NoneLookUpStrategy(); // depends on control dependency: [if], data = [none] } return new PlanningIdLookUpStrategy(memberAccessor1); case PLANNING_ID_OR_FAIL_FAST: MemberAccessor memberAccessor2 = ConfigUtils.findPlanningIdMemberAccessor(objectClass); if (memberAccessor2 == null) { throw new IllegalArgumentException("The class (" + objectClass + ") does not have a " + PlanningId.class.getSimpleName() + " annotation," + " but the lookUpStrategyType (" + lookUpStrategyType + ") requires it.\n" + "Maybe add the " + PlanningId.class.getSimpleName() + " annotation" + " or change the " + PlanningSolution.class.getSimpleName() + " annotation's " + LookUpStrategyType.class.getSimpleName() + "."); } return new PlanningIdLookUpStrategy(memberAccessor2); case EQUALITY: Method equalsMethod; Method hashCodeMethod; try { equalsMethod = object.getClass().getMethod("equals", Object.class); hashCodeMethod = object.getClass().getMethod("hashCode"); } catch (NoSuchMethodException e) { throw new IllegalStateException( "Impossible state because equals() and hashCode() always exist.", e); } if (equalsMethod.getDeclaringClass().equals(Object.class)) { throw new IllegalArgumentException("The class (" + object.getClass().getSimpleName() + ") doesn't override the equals() method, neither does any superclass."); } if (hashCodeMethod.getDeclaringClass().equals(Object.class)) { throw new IllegalArgumentException("The class (" + object.getClass().getSimpleName() + ") overrides equals() but neither it nor any superclass" + " overrides the hashCode() method."); } return new EqualsLookUpStrategy(); case NONE: return new NoneLookUpStrategy(); default: throw new IllegalStateException("The lookUpStrategyType (" + lookUpStrategyType + ") is not implemented."); } }); } }
public class class_name { private void executeWffBMTask(final byte[] message) throws UnsupportedEncodingException { final List<NameValue> nameValues = WffBinaryMessageUtil.VERSION_1 .parse(message); final NameValue task = nameValues.get(0); final byte taskValue = task.getValues()[0][0]; if (Task.TASK.getValueByte() == task.getName()[0]) { // IM stands for Invoke Method if (taskValue == Task.INVOKE_ASYNC_METHOD.getValueByte()) { invokeAsychMethod(nameValues); } else if (taskValue == Task.INVOKE_CUSTOM_SERVER_METHOD .getValueByte()) { invokeCustomServerMethod(nameValues); } else if (taskValue == Task.REMOVE_BROWSER_PAGE.getValueByte()) { removeBrowserPageFromContext(nameValues); } } } }
public class class_name { private void executeWffBMTask(final byte[] message) throws UnsupportedEncodingException { final List<NameValue> nameValues = WffBinaryMessageUtil.VERSION_1 .parse(message); final NameValue task = nameValues.get(0); final byte taskValue = task.getValues()[0][0]; if (Task.TASK.getValueByte() == task.getName()[0]) { // IM stands for Invoke Method if (taskValue == Task.INVOKE_ASYNC_METHOD.getValueByte()) { invokeAsychMethod(nameValues); // depends on control dependency: [if], data = [none] } else if (taskValue == Task.INVOKE_CUSTOM_SERVER_METHOD .getValueByte()) { invokeCustomServerMethod(nameValues); // depends on control dependency: [if], data = [none] } else if (taskValue == Task.REMOVE_BROWSER_PAGE.getValueByte()) { removeBrowserPageFromContext(nameValues); // depends on control dependency: [if], data = [none] } } } }
public class class_name { protected void processIdent( DetailAST aAST ) { final int parentType = aAST.getParent().getType(); if (((parentType != TokenTypes.DOT) && (parentType != TokenTypes.METHOD_DEF)) || ((parentType == TokenTypes.DOT) && (aAST.getNextSibling() != null))) { referenced.add(aAST.getText()); } } }
public class class_name { protected void processIdent( DetailAST aAST ) { final int parentType = aAST.getParent().getType(); if (((parentType != TokenTypes.DOT) && (parentType != TokenTypes.METHOD_DEF)) || ((parentType == TokenTypes.DOT) && (aAST.getNextSibling() != null))) { referenced.add(aAST.getText()); // depends on control dependency: [if], data = [none] } } }
public class class_name { public boolean printData(PrintWriter out, int iPrintOptions) { boolean bFieldsFound = false; int iNumCols = this.getSFieldCount(); for (int iIndex = 0; iIndex < iNumCols; iIndex++) { ScreenField sField = this.getSField(iIndex); boolean bPrintControl = this.isPrintableControl(sField, iPrintOptions); if (this.isToolbar()) if (sField.getConverter() == null) bPrintControl = false; if (this instanceof BaseGridScreen) if (iIndex < ((BaseGridScreen)this).getNavCount()) bPrintControl = true; // Move to isPrintable. if (bPrintControl) { if (!bFieldsFound) this.printDataStartForm(out, iPrintOptions); // First time this.printDataStartField(out, iPrintOptions); this.printScreenFieldData(sField, out, iPrintOptions); this.printDataEndField(out, iPrintOptions); bFieldsFound = true; } } if (bFieldsFound) this.printDataEndForm(out, iPrintOptions); return bFieldsFound; } }
public class class_name { public boolean printData(PrintWriter out, int iPrintOptions) { boolean bFieldsFound = false; int iNumCols = this.getSFieldCount(); for (int iIndex = 0; iIndex < iNumCols; iIndex++) { ScreenField sField = this.getSField(iIndex); boolean bPrintControl = this.isPrintableControl(sField, iPrintOptions); if (this.isToolbar()) if (sField.getConverter() == null) bPrintControl = false; if (this instanceof BaseGridScreen) if (iIndex < ((BaseGridScreen)this).getNavCount()) bPrintControl = true; // Move to isPrintable. if (bPrintControl) { if (!bFieldsFound) this.printDataStartForm(out, iPrintOptions); // First time this.printDataStartField(out, iPrintOptions); // depends on control dependency: [if], data = [none] this.printScreenFieldData(sField, out, iPrintOptions); // depends on control dependency: [if], data = [none] this.printDataEndField(out, iPrintOptions); // depends on control dependency: [if], data = [none] bFieldsFound = true; // depends on control dependency: [if], data = [none] } } if (bFieldsFound) this.printDataEndForm(out, iPrintOptions); return bFieldsFound; } }
public class class_name { @Override public final AnalyzedSentence disambiguate(AnalyzedSentence input) { lazyInit(); AnalyzedTokenReadings[] anTokens = input.getTokens(); AnalyzedTokenReadings[] output = anTokens; for (int i = 0; i < anTokens.length; i++) { String tok = output[i].getToken(); if (tok.length()<1) { continue; } // If the second token is not whitespace, concatenate it if (i + 1 < anTokens.length && !anTokens[i+1].isWhitespace()) { tok = tok + output[i + 1].getToken(); } // If it is a capitalized word, the second time try with lowercase word. int myCount = 0; while (myCount < 2) { StringBuilder tokens = new StringBuilder(); int finalLen = 0; if (mStartSpace.containsKey(tok)) { int len = mStartSpace.get(tok); int j = i; int lenCounter = 0; while (j < anTokens.length) { if (!anTokens[j].isWhitespace()) { if (j == i && myCount == 1) { tokens.append(anTokens[j].getToken().toLowerCase()); } else { tokens.append(anTokens[j].getToken()); } String toks = tokens.toString(); if (mFull.containsKey(toks)) { output[i] = prepareNewReading(toks, output[i].getToken(), output[i], false); output[finalLen] = prepareNewReading(toks, anTokens[finalLen].getToken(), output[finalLen], true); } } else { if (j > 1 && !anTokens[j-1].isWhitespace()) { //avoid multiple whitespaces tokens.append(' '); lenCounter++; } if (lenCounter == len) { break; } } j++; finalLen = j; } } if (mStartNoSpace.containsKey(tok.substring(0, 1))) { int j = i; while (j < anTokens.length && !anTokens[j].isWhitespace()) { if (j == i && myCount == 1) { tokens.append(anTokens[j].getToken().toLowerCase()); } else { tokens.append(anTokens[j].getToken()); } String toks = tokens.toString(); if (mFull.containsKey(toks)) { output[i] = prepareNewReading(toks, anTokens[i].getToken(), output[i], false); output[j] = prepareNewReading(toks, anTokens[j].getToken(), output[j], true); } j++; } } // If it is a capitalized word, try with lowercase word. myCount++; if (allowFirstCapitalized && StringTools.isCapitalizedWord(tok) && myCount == 1) { tok = tok.toLowerCase(); } else { myCount = 2; } } } return new AnalyzedSentence(output); } }
public class class_name { @Override public final AnalyzedSentence disambiguate(AnalyzedSentence input) { lazyInit(); AnalyzedTokenReadings[] anTokens = input.getTokens(); AnalyzedTokenReadings[] output = anTokens; for (int i = 0; i < anTokens.length; i++) { String tok = output[i].getToken(); if (tok.length()<1) { continue; } // If the second token is not whitespace, concatenate it if (i + 1 < anTokens.length && !anTokens[i+1].isWhitespace()) { tok = tok + output[i + 1].getToken(); // depends on control dependency: [if], data = [none] } // If it is a capitalized word, the second time try with lowercase word. int myCount = 0; while (myCount < 2) { StringBuilder tokens = new StringBuilder(); int finalLen = 0; if (mStartSpace.containsKey(tok)) { int len = mStartSpace.get(tok); int j = i; int lenCounter = 0; while (j < anTokens.length) { if (!anTokens[j].isWhitespace()) { if (j == i && myCount == 1) { tokens.append(anTokens[j].getToken().toLowerCase()); // depends on control dependency: [if], data = [none] } else { tokens.append(anTokens[j].getToken()); // depends on control dependency: [if], data = [none] } String toks = tokens.toString(); if (mFull.containsKey(toks)) { output[i] = prepareNewReading(toks, output[i].getToken(), output[i], false); // depends on control dependency: [if], data = [none] output[finalLen] = prepareNewReading(toks, anTokens[finalLen].getToken(), output[finalLen], true); // depends on control dependency: [if], data = [none] } } else { if (j > 1 && !anTokens[j-1].isWhitespace()) { //avoid multiple whitespaces tokens.append(' '); // depends on control dependency: [if], data = [none] lenCounter++; // depends on control dependency: [if], data = [none] } if (lenCounter == len) { break; } } j++; // depends on control dependency: [while], data = [none] finalLen = j; // depends on control dependency: [while], data = [none] } } if (mStartNoSpace.containsKey(tok.substring(0, 1))) { int j = i; while (j < anTokens.length && !anTokens[j].isWhitespace()) { if (j == i && myCount == 1) { tokens.append(anTokens[j].getToken().toLowerCase()); // depends on control dependency: [if], data = [none] } else { tokens.append(anTokens[j].getToken()); // depends on control dependency: [if], data = [none] } String toks = tokens.toString(); if (mFull.containsKey(toks)) { output[i] = prepareNewReading(toks, anTokens[i].getToken(), output[i], false); // depends on control dependency: [if], data = [none] output[j] = prepareNewReading(toks, anTokens[j].getToken(), output[j], true); // depends on control dependency: [if], data = [none] } j++; // depends on control dependency: [while], data = [none] } } // If it is a capitalized word, try with lowercase word. myCount++; // depends on control dependency: [while], data = [none] if (allowFirstCapitalized && StringTools.isCapitalizedWord(tok) && myCount == 1) { tok = tok.toLowerCase(); // depends on control dependency: [if], data = [none] } else { myCount = 2; // depends on control dependency: [if], data = [none] } } } return new AnalyzedSentence(output); } }
public class class_name { private TypeRef resultType() { Type[] parameters = _method.getGenericParameterTypes(); for (Type parameter : parameters) { TypeRef type = TypeRef.of(parameter); if (Result.class.equals(type.rawClass())) { TypeRef resultTypeRef = type.param(0); return resultTypeRef; } } return null; } }
public class class_name { private TypeRef resultType() { Type[] parameters = _method.getGenericParameterTypes(); for (Type parameter : parameters) { TypeRef type = TypeRef.of(parameter); if (Result.class.equals(type.rawClass())) { TypeRef resultTypeRef = type.param(0); return resultTypeRef; // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { protected void scanEntry(final ClassPathEntry classPathEntry) { if (!acceptEntry(classPathEntry.name())) { return; } try { onEntry(classPathEntry); } catch (Exception ex) { throw new FindFileException("Scan entry error: " + classPathEntry, ex); } } }
public class class_name { protected void scanEntry(final ClassPathEntry classPathEntry) { if (!acceptEntry(classPathEntry.name())) { return; // depends on control dependency: [if], data = [none] } try { onEntry(classPathEntry); // depends on control dependency: [try], data = [none] } catch (Exception ex) { throw new FindFileException("Scan entry error: " + classPathEntry, ex); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public DoubleVector buildVector(BufferedReader document, DoubleVector documentVector) { // Tokenize and determine what words exist in the document, along with // the requested meta information, such as a term frequency. Map<String, Integer> termCounts = new HashMap<String, Integer>(); Iterator<String> articleTokens = IteratorFactory.tokenize(document); while (articleTokens.hasNext()) { String term = articleTokens.next(); Integer count = termCounts.get(term); termCounts.put(term, (count == null || !useTermFreq) ? 1 : count.intValue() + 1); } // Iterate through each term in the document and sum the term Vectors // found in the provided SemanticSpace. // If the underlying BasisMapping of the sspace is not read-only, then // the getVector method would try to access a non-existing element. // We therefore check here if the word is in the mapping and // skip the word if it is not. Set<String> knownWords = sspace.getWords(); for (Map.Entry<String, Integer> entry : termCounts.entrySet()) { if(knownWords.contains(entry.getKey())) { Vector termVector = sspace.getVector(entry.getKey()); if (termVector == null) continue; add(documentVector, termVector, entry.getValue()); } } return documentVector; } }
public class class_name { public DoubleVector buildVector(BufferedReader document, DoubleVector documentVector) { // Tokenize and determine what words exist in the document, along with // the requested meta information, such as a term frequency. Map<String, Integer> termCounts = new HashMap<String, Integer>(); Iterator<String> articleTokens = IteratorFactory.tokenize(document); while (articleTokens.hasNext()) { String term = articleTokens.next(); Integer count = termCounts.get(term); termCounts.put(term, (count == null || !useTermFreq) ? 1 : count.intValue() + 1); // depends on control dependency: [while], data = [none] } // Iterate through each term in the document and sum the term Vectors // found in the provided SemanticSpace. // If the underlying BasisMapping of the sspace is not read-only, then // the getVector method would try to access a non-existing element. // We therefore check here if the word is in the mapping and // skip the word if it is not. Set<String> knownWords = sspace.getWords(); for (Map.Entry<String, Integer> entry : termCounts.entrySet()) { if(knownWords.contains(entry.getKey())) { Vector termVector = sspace.getVector(entry.getKey()); if (termVector == null) continue; add(documentVector, termVector, entry.getValue()); // depends on control dependency: [if], data = [none] } } return documentVector; } }
public class class_name { public static DirLock takeOwnershipIfStale(FileSystem fs, Path dirToLock, int lockTimeoutSec) { Path dirLockFile = getDirLockFile(dirToLock); long now = System.currentTimeMillis(); long expiryTime = now - (lockTimeoutSec*1000); try { long modTime = fs.getFileStatus(dirLockFile).getModificationTime(); if(modTime <= expiryTime) { return takeOwnership(fs, dirLockFile); } return null; } catch (IOException e) { return null; } } }
public class class_name { public static DirLock takeOwnershipIfStale(FileSystem fs, Path dirToLock, int lockTimeoutSec) { Path dirLockFile = getDirLockFile(dirToLock); long now = System.currentTimeMillis(); long expiryTime = now - (lockTimeoutSec*1000); try { long modTime = fs.getFileStatus(dirLockFile).getModificationTime(); if(modTime <= expiryTime) { return takeOwnership(fs, dirLockFile); // depends on control dependency: [if], data = [none] } return null; // depends on control dependency: [try], data = [none] } catch (IOException e) { return null; } // depends on control dependency: [catch], data = [none] } }
public class class_name { public byte[] decrypt(final String encodedJSON) { byte[] result = null; if (encodedJSON == null) throw new OSecurityException("OSymmetricKey.decrypt(String) encodedJSON is null"); try { byte[] decoded = convertFromBase64(encodedJSON); if (decoded == null) throw new OSecurityException("OSymmetricKey.decrypt(String) encodedJSON could not be decoded"); String json = new String(decoded, "UTF8"); // Convert the JSON content to an ODocument to make parsing it easier. final ODocument doc = new ODocument().fromJSON(json, "noMap"); // Set a default in case the JSON document does not contain an "algorithm" property. String algorithm = secretKeyAlgorithm; if (doc.containsField("algorithm")) algorithm = doc.field("algorithm"); // Set a default in case the JSON document does not contain a "transform" property. String transform = defaultCipherTransformation; if (doc.containsField("transform")) transform = doc.field("transform"); String payloadBase64 = doc.field("payload"); String ivBase64 = doc.field("iv"); byte[] payload = null; byte[] iv = null; if (payloadBase64 != null) payload = convertFromBase64(payloadBase64); if (ivBase64 != null) iv = convertFromBase64(ivBase64); // Throws NoSuchAlgorithmException and NoSuchPaddingException. Cipher cipher = Cipher.getInstance(transform); if (iv != null) cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv)); else cipher.init(Cipher.DECRYPT_MODE, secretKey); result = cipher.doFinal(payload); } catch (Exception ex) { throw OException.wrapException(new OSecurityException("OSymmetricKey.decrypt(String) Exception: " + ex.getMessage()), ex); } return result; } }
public class class_name { public byte[] decrypt(final String encodedJSON) { byte[] result = null; if (encodedJSON == null) throw new OSecurityException("OSymmetricKey.decrypt(String) encodedJSON is null"); try { byte[] decoded = convertFromBase64(encodedJSON); if (decoded == null) throw new OSecurityException("OSymmetricKey.decrypt(String) encodedJSON could not be decoded"); String json = new String(decoded, "UTF8"); // Convert the JSON content to an ODocument to make parsing it easier. final ODocument doc = new ODocument().fromJSON(json, "noMap"); // Set a default in case the JSON document does not contain an "algorithm" property. String algorithm = secretKeyAlgorithm; if (doc.containsField("algorithm")) algorithm = doc.field("algorithm"); // Set a default in case the JSON document does not contain a "transform" property. String transform = defaultCipherTransformation; if (doc.containsField("transform")) transform = doc.field("transform"); String payloadBase64 = doc.field("payload"); String ivBase64 = doc.field("iv"); byte[] payload = null; byte[] iv = null; if (payloadBase64 != null) payload = convertFromBase64(payloadBase64); if (ivBase64 != null) iv = convertFromBase64(ivBase64); // Throws NoSuchAlgorithmException and NoSuchPaddingException. Cipher cipher = Cipher.getInstance(transform); if (iv != null) cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv)); else cipher.init(Cipher.DECRYPT_MODE, secretKey); result = cipher.doFinal(payload); // depends on control dependency: [try], data = [none] } catch (Exception ex) { throw OException.wrapException(new OSecurityException("OSymmetricKey.decrypt(String) Exception: " + ex.getMessage()), ex); } // depends on control dependency: [catch], data = [none] return result; } }
public class class_name { public static void copyStream( StreamMonitor monitor, URL sourceURL, int expected, InputStream source, OutputStream destination, boolean closeStreams ) throws IOException, NullArgumentException { NullArgumentException.validateNotNull( source, "source" ); NullArgumentException.validateNotNull( destination, "destination" ); int length; int count = 0; // cumulative total read byte[] buffer = new byte[BUFFER_SIZE]; BufferedOutputStream dest; if( destination instanceof BufferedOutputStream ) { dest = (BufferedOutputStream) destination; } else { dest = new BufferedOutputStream( destination ); } BufferedInputStream src; if( source instanceof BufferedInputStream ) { src = (BufferedInputStream) source; } else { src = new BufferedInputStream( source ); } try { while( ( length = src.read( buffer ) ) >= 0 ) { count = count + length; dest.write( buffer, 0, length ); if( null != monitor ) { monitor.notifyUpdate( sourceURL, expected, count ); } } dest.flush(); } finally { if( closeStreams ) { closeStreams( src, dest ); } if( null != monitor ) { monitor.notifyCompletion( sourceURL ); } } } }
public class class_name { public static void copyStream( StreamMonitor monitor, URL sourceURL, int expected, InputStream source, OutputStream destination, boolean closeStreams ) throws IOException, NullArgumentException { NullArgumentException.validateNotNull( source, "source" ); NullArgumentException.validateNotNull( destination, "destination" ); int length; int count = 0; // cumulative total read byte[] buffer = new byte[BUFFER_SIZE]; BufferedOutputStream dest; if( destination instanceof BufferedOutputStream ) { dest = (BufferedOutputStream) destination; } else { dest = new BufferedOutputStream( destination ); } BufferedInputStream src; if( source instanceof BufferedInputStream ) { src = (BufferedInputStream) source; } else { src = new BufferedInputStream( source ); } try { while( ( length = src.read( buffer ) ) >= 0 ) { count = count + length; // depends on control dependency: [while], data = [none] dest.write( buffer, 0, length ); // depends on control dependency: [while], data = [none] if( null != monitor ) { monitor.notifyUpdate( sourceURL, expected, count ); // depends on control dependency: [if], data = [none] } } dest.flush(); } finally { if( closeStreams ) { closeStreams( src, dest ); // depends on control dependency: [if], data = [none] } if( null != monitor ) { monitor.notifyCompletion( sourceURL ); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public static Node findNodeByName(Document doc, String pathExpression) { final StringTokenizer tok = new StringTokenizer(pathExpression, "."); final int numToks = tok.countTokens(); NodeList elements; if (numToks == 1) { elements = doc.getElementsByTagNameNS("*", pathExpression); return elements.item(0); } String element = pathExpression.substring(pathExpression.lastIndexOf('.')+1); elements = doc.getElementsByTagNameNS("*", element); String attributeName = null; if (elements.getLength() == 0) { //No element found, but maybe we are searching for an attribute attributeName = element; //cut off attributeName and set element to next token and continue Node found = findNodeByName(doc, pathExpression.substring(0, pathExpression.length() - attributeName.length() - 1)); if (found != null) { return found.getAttributes().getNamedItem(attributeName); } else { return null; } } StringBuffer pathName; Node parent; for (int j=0; j<elements.getLength(); j++) { int cnt = numToks-1; pathName = new StringBuffer(element); parent = elements.item(j).getParentNode(); do { if (parent != null) { pathName.insert(0, '.'); pathName.insert(0, parent.getLocalName());//getNodeName()); parent = parent.getParentNode(); } } while (parent != null && --cnt > 0); if (pathName.toString().equals(pathExpression)) {return elements.item(j);} } return null; } }
public class class_name { public static Node findNodeByName(Document doc, String pathExpression) { final StringTokenizer tok = new StringTokenizer(pathExpression, "."); final int numToks = tok.countTokens(); NodeList elements; if (numToks == 1) { elements = doc.getElementsByTagNameNS("*", pathExpression); // depends on control dependency: [if], data = [none] return elements.item(0); // depends on control dependency: [if], data = [none] } String element = pathExpression.substring(pathExpression.lastIndexOf('.')+1); elements = doc.getElementsByTagNameNS("*", element); String attributeName = null; if (elements.getLength() == 0) { //No element found, but maybe we are searching for an attribute attributeName = element; // depends on control dependency: [if], data = [none] //cut off attributeName and set element to next token and continue Node found = findNodeByName(doc, pathExpression.substring(0, pathExpression.length() - attributeName.length() - 1)); if (found != null) { return found.getAttributes().getNamedItem(attributeName); // depends on control dependency: [if], data = [none] } else { return null; // depends on control dependency: [if], data = [none] } } StringBuffer pathName; Node parent; for (int j=0; j<elements.getLength(); j++) { int cnt = numToks-1; pathName = new StringBuffer(element); // depends on control dependency: [for], data = [none] parent = elements.item(j).getParentNode(); // depends on control dependency: [for], data = [j] do { if (parent != null) { pathName.insert(0, '.'); // depends on control dependency: [if], data = [none] pathName.insert(0, parent.getLocalName());//getNodeName()); // depends on control dependency: [if], data = [none] parent = parent.getParentNode(); // depends on control dependency: [if], data = [none] } } while (parent != null && --cnt > 0); if (pathName.toString().equals(pathExpression)) {return elements.item(j);} // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { private static String encode(String str, boolean fullUri) { byte[] utf8buf = null; StringBuilder sb = null; for (int k = 0, length = str.length(); k != length; ++k) { char C = str.charAt(k); if (encodeUnescaped(C, fullUri)) { if (sb != null) { sb.append(C); } } else { if (sb == null) { sb = new StringBuilder(length + 3); sb.append(str); sb.setLength(k); utf8buf = new byte[6]; } if (0xDC00 <= C && C <= 0xDFFF) { throw uriError(); } int V; if (C < 0xD800 || 0xDBFF < C) { V = C; } else { k++; if (k == length) { throw uriError(); } char C2 = str.charAt(k); if (!(0xDC00 <= C2 && C2 <= 0xDFFF)) { throw uriError(); } V = ((C - 0xD800) << 10) + (C2 - 0xDC00) + 0x10000; } int L = oneUcs4ToUtf8Char(utf8buf, V); for (int j = 0; j < L; j++) { int d = 0xff & utf8buf[j]; sb.append('%'); sb.append(toHexChar(d >>> 4)); sb.append(toHexChar(d & 0xf)); } } } return (sb == null) ? str : sb.toString(); } }
public class class_name { private static String encode(String str, boolean fullUri) { byte[] utf8buf = null; StringBuilder sb = null; for (int k = 0, length = str.length(); k != length; ++k) { char C = str.charAt(k); if (encodeUnescaped(C, fullUri)) { if (sb != null) { sb.append(C); // depends on control dependency: [if], data = [none] } } else { if (sb == null) { sb = new StringBuilder(length + 3); // depends on control dependency: [if], data = [none] sb.append(str); // depends on control dependency: [if], data = [none] sb.setLength(k); // depends on control dependency: [if], data = [none] utf8buf = new byte[6]; // depends on control dependency: [if], data = [none] } if (0xDC00 <= C && C <= 0xDFFF) { throw uriError(); } int V; if (C < 0xD800 || 0xDBFF < C) { V = C; // depends on control dependency: [if], data = [none] } else { k++; // depends on control dependency: [if], data = [none] if (k == length) { throw uriError(); } char C2 = str.charAt(k); if (!(0xDC00 <= C2 && C2 <= 0xDFFF)) { throw uriError(); } V = ((C - 0xD800) << 10) + (C2 - 0xDC00) + 0x10000; // depends on control dependency: [if], data = [(C] } int L = oneUcs4ToUtf8Char(utf8buf, V); for (int j = 0; j < L; j++) { int d = 0xff & utf8buf[j]; sb.append('%'); // depends on control dependency: [for], data = [none] sb.append(toHexChar(d >>> 4)); // depends on control dependency: [for], data = [none] sb.append(toHexChar(d & 0xf)); // depends on control dependency: [for], data = [none] } } } return (sb == null) ? str : sb.toString(); } }
public class class_name { @Override public void setVisible(boolean visible) { if (polygon != null) { polygon.setVisible(visible); } for (Marker marker : markers) { marker.setVisible(visible); } for (PolygonHoleMarkers hole : holes) { hole.setVisible(visible); } } }
public class class_name { @Override public void setVisible(boolean visible) { if (polygon != null) { polygon.setVisible(visible); // depends on control dependency: [if], data = [none] } for (Marker marker : markers) { marker.setVisible(visible); // depends on control dependency: [for], data = [marker] } for (PolygonHoleMarkers hole : holes) { hole.setVisible(visible); // depends on control dependency: [for], data = [hole] } } }
public class class_name { public static Collection<RDFNode> getListItemsOrEmpty(RDFNode node) { ImmutableList.Builder<RDFNode> items = ImmutableList.builder(); if (isList(node)) { RDFList rdfList = node.as(RDFList.class); rdfList.iterator().forEachRemaining(items::add); } return items.build(); } }
public class class_name { public static Collection<RDFNode> getListItemsOrEmpty(RDFNode node) { ImmutableList.Builder<RDFNode> items = ImmutableList.builder(); if (isList(node)) { RDFList rdfList = node.as(RDFList.class); rdfList.iterator().forEachRemaining(items::add); // depends on control dependency: [if], data = [none] } return items.build(); } }
public class class_name { @Deprecated public static void permute(String source, boolean skipZeros, Set<String> output) { // TODO: optimize //if (PROGRESS) System.out.println("Permute: " + source); // optimization: // if zero or one character, just return a set with it // we check for length < 2 to keep from counting code points all the time if (source.length() <= 2 && UTF16.countCodePoint(source) <= 1) { output.add(source); return; } // otherwise iterate through the string, and recursively permute all the other characters Set<String> subpermute = new HashSet<String>(); int cp; for (int i = 0; i < source.length(); i += UTF16.getCharCount(cp)) { cp = UTF16.charAt(source, i); // optimization: // if the character is canonical combining class zero, // don't permute it if (skipZeros && i != 0 && UCharacter.getCombiningClass(cp) == 0) { //System.out.println("Skipping " + Utility.hex(UTF16.valueOf(source, i))); continue; } // see what the permutations of the characters before and after this one are subpermute.clear(); permute(source.substring(0,i) + source.substring(i + UTF16.getCharCount(cp)), skipZeros, subpermute); // prefix this character to all of them String chStr = UTF16.valueOf(source, i); for (String s : subpermute) { String piece = chStr + s; //if (PROGRESS) System.out.println(" Piece: " + piece); output.add(piece); } } } }
public class class_name { @Deprecated public static void permute(String source, boolean skipZeros, Set<String> output) { // TODO: optimize //if (PROGRESS) System.out.println("Permute: " + source); // optimization: // if zero or one character, just return a set with it // we check for length < 2 to keep from counting code points all the time if (source.length() <= 2 && UTF16.countCodePoint(source) <= 1) { output.add(source); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } // otherwise iterate through the string, and recursively permute all the other characters Set<String> subpermute = new HashSet<String>(); int cp; for (int i = 0; i < source.length(); i += UTF16.getCharCount(cp)) { cp = UTF16.charAt(source, i); // depends on control dependency: [for], data = [i] // optimization: // if the character is canonical combining class zero, // don't permute it if (skipZeros && i != 0 && UCharacter.getCombiningClass(cp) == 0) { //System.out.println("Skipping " + Utility.hex(UTF16.valueOf(source, i))); continue; } // see what the permutations of the characters before and after this one are subpermute.clear(); // depends on control dependency: [for], data = [none] permute(source.substring(0,i) + source.substring(i + UTF16.getCharCount(cp)), skipZeros, subpermute); // depends on control dependency: [for], data = [i] // prefix this character to all of them String chStr = UTF16.valueOf(source, i); for (String s : subpermute) { String piece = chStr + s; //if (PROGRESS) System.out.println(" Piece: " + piece); output.add(piece); // depends on control dependency: [for], data = [none] } } } }
public class class_name { public static File print(final UIGrid _uiGrid) { File ret = null; final String clazzName = Configuration.getAttribute(ConfigAttribute.GRIDPRINTESJP); try { UIGrid.LOG.debug("Print method executed for {}", _uiGrid); final Class<?> clazz = Class.forName(clazzName, false, EFapsClassLoader.getInstance()); final EventExecution event = (EventExecution) clazz.newInstance(); final Parameter param = new Parameter(); param.put(ParameterValues.PARAMETERS, Context.getThreadContext().getParameters()); param.put(ParameterValues.CLASS, _uiGrid); final Return retu = event.execute(param); if (retu != null) { ret = (File) retu.get(ReturnValues.VALUES); } } catch (final ClassNotFoundException | InstantiationException | IllegalAccessException e) { UIGrid.LOG.error("Catched", e); } catch (final EFapsException e) { UIGrid.LOG.error("Catched", e); } return ret; } }
public class class_name { public static File print(final UIGrid _uiGrid) { File ret = null; final String clazzName = Configuration.getAttribute(ConfigAttribute.GRIDPRINTESJP); try { UIGrid.LOG.debug("Print method executed for {}", _uiGrid); // depends on control dependency: [try], data = [none] final Class<?> clazz = Class.forName(clazzName, false, EFapsClassLoader.getInstance()); final EventExecution event = (EventExecution) clazz.newInstance(); final Parameter param = new Parameter(); param.put(ParameterValues.PARAMETERS, Context.getThreadContext().getParameters()); // depends on control dependency: [try], data = [none] param.put(ParameterValues.CLASS, _uiGrid); // depends on control dependency: [try], data = [none] final Return retu = event.execute(param); if (retu != null) { ret = (File) retu.get(ReturnValues.VALUES); // depends on control dependency: [if], data = [none] } } catch (final ClassNotFoundException | InstantiationException | IllegalAccessException e) { UIGrid.LOG.error("Catched", e); } catch (final EFapsException e) { // depends on control dependency: [catch], data = [none] UIGrid.LOG.error("Catched", e); } // depends on control dependency: [catch], data = [none] return ret; } }
public class class_name { private String getParameterName(AnnotatedParameter<?> parameter) { try { Method method = Method.class.getMethod("getParameters"); Object[] parameters = (Object[]) method.invoke(parameter.getDeclaringCallable().getJavaMember()); Object param = parameters[parameter.getPosition()]; Class<?> Parameter = Class.forName("java.lang.reflect.Parameter"); if ((Boolean) Parameter.getMethod("isNamePresent").invoke(param)) return (String) Parameter.getMethod("getName").invoke(param); else throw new UnsupportedOperationException("Unable to retrieve name for parameter [" + parameter + "], activate the -parameters compiler argument or annotate the injected parameter with the @Metric annotation"); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | ClassNotFoundException cause) { throw new UnsupportedOperationException("Unable to retrieve name for parameter [" + parameter + "], @Metric annotation on injected parameter is required before Java 8"); } } }
public class class_name { private String getParameterName(AnnotatedParameter<?> parameter) { try { Method method = Method.class.getMethod("getParameters"); Object[] parameters = (Object[]) method.invoke(parameter.getDeclaringCallable().getJavaMember()); Object param = parameters[parameter.getPosition()]; Class<?> Parameter = Class.forName("java.lang.reflect.Parameter"); if ((Boolean) Parameter.getMethod("isNamePresent").invoke(param)) return (String) Parameter.getMethod("getName").invoke(param); else throw new UnsupportedOperationException("Unable to retrieve name for parameter [" + parameter + "], activate the -parameters compiler argument or annotate the injected parameter with the @Metric annotation"); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | ClassNotFoundException cause) { throw new UnsupportedOperationException("Unable to retrieve name for parameter [" + parameter + "], @Metric annotation on injected parameter is required before Java 8"); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override protected void defineWidgets() { List selectOptions = getModulesFromServer(); if (selectOptions.isEmpty()) { // no import modules available, display message addWidget( new CmsWidgetDialogParameter( this, "moduleupload", PAGES[0], new CmsDisplayWidget(key(Messages.GUI_MODULES_IMPORT_NOT_AVAILABLE_0)))); } else { // add the file select box widget addWidget(new CmsWidgetDialogParameter(this, "moduleupload", PAGES[0], new CmsSelectWidget(selectOptions))); } } }
public class class_name { @Override protected void defineWidgets() { List selectOptions = getModulesFromServer(); if (selectOptions.isEmpty()) { // no import modules available, display message addWidget( new CmsWidgetDialogParameter( this, "moduleupload", PAGES[0], new CmsDisplayWidget(key(Messages.GUI_MODULES_IMPORT_NOT_AVAILABLE_0)))); // depends on control dependency: [if], data = [none] } else { // add the file select box widget addWidget(new CmsWidgetDialogParameter(this, "moduleupload", PAGES[0], new CmsSelectWidget(selectOptions))); // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override public void evaluate(BinarySolution solution) { int counterOnes; int counterZeroes; counterOnes = 0; counterZeroes = 0; BitSet bitset = solution.getVariableValue(0) ; for (int i = 0; i < bitset.length(); i++) { if (bitset.get(i)) { counterOnes++; } else { counterZeroes++; } } // OneZeroMax is a maximization problem: multiply by -1 to minimize solution.setObjective(0, -1.0 * counterOnes); solution.setObjective(1, -1.0 * counterZeroes); } }
public class class_name { @Override public void evaluate(BinarySolution solution) { int counterOnes; int counterZeroes; counterOnes = 0; counterZeroes = 0; BitSet bitset = solution.getVariableValue(0) ; for (int i = 0; i < bitset.length(); i++) { if (bitset.get(i)) { counterOnes++; // depends on control dependency: [if], data = [none] } else { counterZeroes++; // depends on control dependency: [if], data = [none] } } // OneZeroMax is a maximization problem: multiply by -1 to minimize solution.setObjective(0, -1.0 * counterOnes); solution.setObjective(1, -1.0 * counterZeroes); } }
public class class_name { public static EncodedElement getStreamInfo(StreamConfiguration sc, int minFrameSize, int maxFrameSize, long samplesInStream, byte[] md5Hash) { int bytes = getByteSize(); EncodedElement ele = new EncodedElement(bytes, 0); int encodedBitsPerSample = sc.getBitsPerSample()-1; ele.addInt(sc.getMinBlockSize(), 16); ele.addInt(sc.getMaxBlockSize(), 16); ele.addInt(minFrameSize, 24); ele.addInt(maxFrameSize, 24); ele.addInt(sc.getSampleRate(), 20); ele.addInt(sc.getChannelCount()-1, 3); ele.addInt(encodedBitsPerSample, 5); ele.addLong(samplesInStream, 36); for(int i = 0; i < 16; i++) { ele.addInt(md5Hash[i], 8); } return ele; } }
public class class_name { public static EncodedElement getStreamInfo(StreamConfiguration sc, int minFrameSize, int maxFrameSize, long samplesInStream, byte[] md5Hash) { int bytes = getByteSize(); EncodedElement ele = new EncodedElement(bytes, 0); int encodedBitsPerSample = sc.getBitsPerSample()-1; ele.addInt(sc.getMinBlockSize(), 16); ele.addInt(sc.getMaxBlockSize(), 16); ele.addInt(minFrameSize, 24); ele.addInt(maxFrameSize, 24); ele.addInt(sc.getSampleRate(), 20); ele.addInt(sc.getChannelCount()-1, 3); ele.addInt(encodedBitsPerSample, 5); ele.addLong(samplesInStream, 36); for(int i = 0; i < 16; i++) { ele.addInt(md5Hash[i], 8); // depends on control dependency: [for], data = [i] } return ele; } }
public class class_name { public void processFile(File zipFile, File destDir) throws IOException { if (!destDir.exists()) { throw new IOException("Destionation directory '" + destDir + "' does not exists, or can't be read!"); } ZipFile f = null; try { f = new ZipFile(zipFile); Map<String, ZipEntry> fEntries = getEntries(f); String[] names = fEntries.keySet().toArray(new String[] {}); if (sortNames) { Arrays.sort(names); } // copy all files for (int i = 0; i < names.length; i++) { String name = names[i]; ZipEntry e = fEntries.get(name); copyFileEntry(destDir, f, e); } } catch (IOException ioe) { String msg = ioe.getMessage(); if (msg.indexOf(zipFile.toString()) < 0) { msg += " - " + zipFile.toString(); } throw new IOException(msg); } finally { if (f != null) { try { f.close(); } catch (IOException ioe) { } } } } }
public class class_name { public void processFile(File zipFile, File destDir) throws IOException { if (!destDir.exists()) { throw new IOException("Destionation directory '" + destDir + "' does not exists, or can't be read!"); } ZipFile f = null; try { f = new ZipFile(zipFile); Map<String, ZipEntry> fEntries = getEntries(f); String[] names = fEntries.keySet().toArray(new String[] {}); if (sortNames) { Arrays.sort(names); // depends on control dependency: [if], data = [none] } // copy all files for (int i = 0; i < names.length; i++) { String name = names[i]; ZipEntry e = fEntries.get(name); copyFileEntry(destDir, f, e); // depends on control dependency: [for], data = [none] } } catch (IOException ioe) { String msg = ioe.getMessage(); if (msg.indexOf(zipFile.toString()) < 0) { msg += " - " + zipFile.toString(); // depends on control dependency: [if], data = [none] } throw new IOException(msg); } finally { if (f != null) { try { f.close(); // depends on control dependency: [try], data = [none] } catch (IOException ioe) { } // depends on control dependency: [catch], data = [none] } } } }
public class class_name { public static <T> DataSet<Tuple2<Long, T>> zipWithUniqueId (DataSet <T> input) { return input.mapPartition(new RichMapPartitionFunction<T, Tuple2<Long, T>>() { long maxBitSize = getBitSize(Long.MAX_VALUE); long shifter = 0; long start = 0; long taskId = 0; long label = 0; @Override public void open(Configuration parameters) throws Exception { super.open(parameters); shifter = getBitSize(getRuntimeContext().getNumberOfParallelSubtasks() - 1); taskId = getRuntimeContext().getIndexOfThisSubtask(); } @Override public void mapPartition(Iterable<T> values, Collector<Tuple2<Long, T>> out) throws Exception { for (T value : values) { label = (start << shifter) + taskId; if (getBitSize(start) + shifter < maxBitSize) { out.collect(new Tuple2<>(label, value)); start++; } else { throw new Exception("Exceeded Long value range while generating labels"); } } } }); } }
public class class_name { public static <T> DataSet<Tuple2<Long, T>> zipWithUniqueId (DataSet <T> input) { return input.mapPartition(new RichMapPartitionFunction<T, Tuple2<Long, T>>() { long maxBitSize = getBitSize(Long.MAX_VALUE); long shifter = 0; long start = 0; long taskId = 0; long label = 0; @Override public void open(Configuration parameters) throws Exception { super.open(parameters); shifter = getBitSize(getRuntimeContext().getNumberOfParallelSubtasks() - 1); taskId = getRuntimeContext().getIndexOfThisSubtask(); } @Override public void mapPartition(Iterable<T> values, Collector<Tuple2<Long, T>> out) throws Exception { for (T value : values) { label = (start << shifter) + taskId; // depends on control dependency: [for], data = [none] if (getBitSize(start) + shifter < maxBitSize) { out.collect(new Tuple2<>(label, value)); // depends on control dependency: [if], data = [none] start++; // depends on control dependency: [if], data = [none] } else { throw new Exception("Exceeded Long value range while generating labels"); } } } }); } }
public class class_name { private void trimNode(final Node node) { NodeList children = node.getChildNodes(); for (int i = children.getLength() - 1; i >= 0; i--) { trimChild(node, children.item(i)); } } }
public class class_name { private void trimNode(final Node node) { NodeList children = node.getChildNodes(); for (int i = children.getLength() - 1; i >= 0; i--) { trimChild(node, children.item(i)); // depends on control dependency: [for], data = [i] } } }
public class class_name { public StateVertex crawlIndex() { LOG.debug("Setting up vertex of the index page"); if (basicAuthUrl != null) { browser.goToUrl(basicAuthUrl); } browser.goToUrl(url); // Run url first load plugin to clear the application state plugins.runOnUrlFirstLoadPlugins(context); plugins.runOnUrlLoadPlugins(context); StateVertex index = vertexFactory.createIndex(url.toString(), browser.getStrippedDom(), stateComparator.getStrippedDom(browser), browser); Preconditions.checkArgument(index.getId() == StateVertex.INDEX_ID, "It seems some the index state is crawled more than once."); LOG.debug("Parsing the index for candidate elements"); ImmutableList<CandidateElement> extract = candidateExtractor.extract(index); plugins.runPreStateCrawlingPlugins(context, extract, index); candidateActionCache.addActions(extract, index); return index; } }
public class class_name { public StateVertex crawlIndex() { LOG.debug("Setting up vertex of the index page"); if (basicAuthUrl != null) { browser.goToUrl(basicAuthUrl); // depends on control dependency: [if], data = [(basicAuthUrl] } browser.goToUrl(url); // Run url first load plugin to clear the application state plugins.runOnUrlFirstLoadPlugins(context); plugins.runOnUrlLoadPlugins(context); StateVertex index = vertexFactory.createIndex(url.toString(), browser.getStrippedDom(), stateComparator.getStrippedDom(browser), browser); Preconditions.checkArgument(index.getId() == StateVertex.INDEX_ID, "It seems some the index state is crawled more than once."); LOG.debug("Parsing the index for candidate elements"); ImmutableList<CandidateElement> extract = candidateExtractor.extract(index); plugins.runPreStateCrawlingPlugins(context, extract, index); candidateActionCache.addActions(extract, index); return index; } }
public class class_name { public void init(String ownName, Iterable<String> options, Iterable<String> classNames, Iterable<? extends JavaFileObject> files) { this.ownName = ownName; this.classNames = toSet(classNames); this.fileObjects = toSet(files); this.files = null; errorMode = ErrorMode.ILLEGAL_ARGUMENT; if (options != null) { processArgs(toList(options), Option.getJavacToolOptions(), apiHelper, false, true); } errorMode = ErrorMode.ILLEGAL_STATE; } }
public class class_name { public void init(String ownName, Iterable<String> options, Iterable<String> classNames, Iterable<? extends JavaFileObject> files) { this.ownName = ownName; this.classNames = toSet(classNames); this.fileObjects = toSet(files); this.files = null; errorMode = ErrorMode.ILLEGAL_ARGUMENT; if (options != null) { processArgs(toList(options), Option.getJavacToolOptions(), apiHelper, false, true); // depends on control dependency: [if], data = [(options] } errorMode = ErrorMode.ILLEGAL_STATE; } }
public class class_name { protected void undo() { try { boolean recursive = Boolean.parseBoolean(m_modifySubresourcesField.getValue().toString()); boolean undoMove = m_undoMoveField.getValue().booleanValue(); CmsObject cms = m_context.getCms(); Set<CmsUUID> updateResources = new HashSet<CmsUUID>(); for (CmsResource resource : m_context.getResources()) { updateResources.add(resource.getStructureId()); if (undoMove) { // in case a move is undone, add the former parent folder updateResources.add(cms.readParentFolder(resource.getStructureId()).getStructureId()); } CmsLockActionRecord actionRecord = null; try { actionRecord = CmsLockUtil.ensureLock(m_context.getCms(), resource); CmsResourceUndoMode mode = CmsResourceUndoMode.getUndoMode(undoMove, recursive); cms.undoChanges(cms.getSitePath(resource), mode); if (undoMove) { // in case a move is undone, also add the new parent folder updateResources.add(cms.readParentFolder(resource.getStructureId()).getStructureId()); } } finally { if ((actionRecord != null) && (actionRecord.getChange() == LockChange.locked)) { try { m_context.getCms().unlockResource(cms.readResource(resource.getStructureId())); } catch (CmsLockException e) { LOG.warn(e.getLocalizedMessage(), e); } } } } m_context.finish(updateResources); } catch (Exception e) { m_context.error(e); } } }
public class class_name { protected void undo() { try { boolean recursive = Boolean.parseBoolean(m_modifySubresourcesField.getValue().toString()); boolean undoMove = m_undoMoveField.getValue().booleanValue(); CmsObject cms = m_context.getCms(); Set<CmsUUID> updateResources = new HashSet<CmsUUID>(); for (CmsResource resource : m_context.getResources()) { updateResources.add(resource.getStructureId()); // depends on control dependency: [for], data = [resource] if (undoMove) { // in case a move is undone, add the former parent folder updateResources.add(cms.readParentFolder(resource.getStructureId()).getStructureId()); // depends on control dependency: [if], data = [none] } CmsLockActionRecord actionRecord = null; try { actionRecord = CmsLockUtil.ensureLock(m_context.getCms(), resource); // depends on control dependency: [try], data = [none] CmsResourceUndoMode mode = CmsResourceUndoMode.getUndoMode(undoMove, recursive); cms.undoChanges(cms.getSitePath(resource), mode); // depends on control dependency: [try], data = [none] if (undoMove) { // in case a move is undone, also add the new parent folder updateResources.add(cms.readParentFolder(resource.getStructureId()).getStructureId()); // depends on control dependency: [if], data = [none] } } finally { if ((actionRecord != null) && (actionRecord.getChange() == LockChange.locked)) { try { m_context.getCms().unlockResource(cms.readResource(resource.getStructureId())); // depends on control dependency: [try], data = [none] } catch (CmsLockException e) { LOG.warn(e.getLocalizedMessage(), e); } // depends on control dependency: [catch], data = [none] } } } m_context.finish(updateResources); // depends on control dependency: [try], data = [none] } catch (Exception e) { m_context.error(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public Period plusDays(long daysToAdd) { if (daysToAdd == 0) { return this; } return create(years, months, Math.toIntExact(Math.addExact(days, daysToAdd))); } }
public class class_name { public Period plusDays(long daysToAdd) { if (daysToAdd == 0) { return this; // depends on control dependency: [if], data = [none] } return create(years, months, Math.toIntExact(Math.addExact(days, daysToAdd))); } }
public class class_name { public String getTopLines(int num) { stopCollecting(); CountMap<String> ls = new CountMap<String>(lines); StringBuilder buff = new StringBuilder(); buff.append("Top lines over ").append(time).append(" ms (").append(pauseTime).append(" ms paused), with ") .append(total).append(" counts:").append(LINE_SEPARATOR); for (int i = 0, n = 0; ls.size() > 0 && n < num; i++) { int highest = 0; List<Map.Entry<String, Integer>> bests = new ArrayList<Map.Entry<String, Integer>>(); for (Map.Entry<String, Integer> el : ls.entrySet()) { if (el.getValue() > highest) { bests.clear(); bests.add(el); highest = el.getValue(); } else if (el.getValue() == highest) { bests.add(el); } } for (Map.Entry<String, Integer> e : bests) { ls.remove(e.getKey()); int percent = 100 * highest / Math.max(total, 1); buff.append("Rank: ").append(i + 1).append(", Self: ").append(percent).append("%, Trace: ") .append(LINE_SEPARATOR).append(e.getKey()).append(LINE_SEPARATOR); n++; } } return buff.toString(); } }
public class class_name { public String getTopLines(int num) { stopCollecting(); CountMap<String> ls = new CountMap<String>(lines); StringBuilder buff = new StringBuilder(); buff.append("Top lines over ").append(time).append(" ms (").append(pauseTime).append(" ms paused), with ") .append(total).append(" counts:").append(LINE_SEPARATOR); for (int i = 0, n = 0; ls.size() > 0 && n < num; i++) { int highest = 0; List<Map.Entry<String, Integer>> bests = new ArrayList<Map.Entry<String, Integer>>(); for (Map.Entry<String, Integer> el : ls.entrySet()) { if (el.getValue() > highest) { bests.clear(); // depends on control dependency: [if], data = [none] bests.add(el); // depends on control dependency: [if], data = [none] highest = el.getValue(); // depends on control dependency: [if], data = [none] } else if (el.getValue() == highest) { bests.add(el); // depends on control dependency: [if], data = [none] } } for (Map.Entry<String, Integer> e : bests) { ls.remove(e.getKey()); // depends on control dependency: [for], data = [e] int percent = 100 * highest / Math.max(total, 1); buff.append("Rank: ").append(i + 1).append(", Self: ").append(percent).append("%, Trace: ") .append(LINE_SEPARATOR).append(e.getKey()).append(LINE_SEPARATOR); // depends on control dependency: [for], data = [e] n++; // depends on control dependency: [for], data = [none] } } return buff.toString(); } }
public class class_name { public void afterSuite(String suiteName, String ... testGroups) { testSuiteListener.onFinish(); if (!CollectionUtils.isEmpty(afterSuite)) { for (SequenceAfterSuite sequenceAfterSuite : afterSuite) { try { if (sequenceAfterSuite.shouldExecute(suiteName, testGroups)) { sequenceAfterSuite.execute(createTestContext()); } } catch (Exception e) { testSuiteListener.onFinishFailure(e); throw new AssertionError("After suite failed with errors", e); } } testSuiteListener.onFinishSuccess(); } else { testSuiteListener.onFinishSuccess(); } } }
public class class_name { public void afterSuite(String suiteName, String ... testGroups) { testSuiteListener.onFinish(); if (!CollectionUtils.isEmpty(afterSuite)) { for (SequenceAfterSuite sequenceAfterSuite : afterSuite) { try { if (sequenceAfterSuite.shouldExecute(suiteName, testGroups)) { sequenceAfterSuite.execute(createTestContext()); // depends on control dependency: [if], data = [none] } } catch (Exception e) { testSuiteListener.onFinishFailure(e); throw new AssertionError("After suite failed with errors", e); } // depends on control dependency: [catch], data = [none] } testSuiteListener.onFinishSuccess(); // depends on control dependency: [if], data = [none] } else { testSuiteListener.onFinishSuccess(); // depends on control dependency: [if], data = [none] } } }
public class class_name { Map<K, V> variableSnapshot(boolean ascending, int limit, Function<V, V> transformer) { evictionLock.lock(); try { maintenance(/* ignored */ null); return timerWheel().snapshot(ascending, limit, transformer); } finally { evictionLock.unlock(); } } }
public class class_name { Map<K, V> variableSnapshot(boolean ascending, int limit, Function<V, V> transformer) { evictionLock.lock(); try { maintenance(/* ignored */ null); // depends on control dependency: [try], data = [none] return timerWheel().snapshot(ascending, limit, transformer); // depends on control dependency: [try], data = [none] } finally { evictionLock.unlock(); } } }
public class class_name { void handleLeaveEvent(LeaveEvent event) { final AsteriskQueueImpl queue = getInternalQueueByName(event.getQueue()); final AsteriskChannelImpl channel = channelManager.getChannelImplByName(event.getChannel()); if (queue == null) { logger.error("Ignored LeaveEvent for unknown queue " + event.getQueue()); return; } if (channel == null) { logger.error("Ignored LeaveEvent for unknown channel " + event.getChannel()); return; } final AsteriskQueueEntryImpl existingQueueEntry = queue.getEntry(event.getChannel()); if (existingQueueEntry == null) { logger.error("Ignored leave event for non existing queue entry in queue " + event.getQueue() + " for channel " + event.getChannel()); return; } queue.removeEntry(existingQueueEntry, event.getDateReceived()); } }
public class class_name { void handleLeaveEvent(LeaveEvent event) { final AsteriskQueueImpl queue = getInternalQueueByName(event.getQueue()); final AsteriskChannelImpl channel = channelManager.getChannelImplByName(event.getChannel()); if (queue == null) { logger.error("Ignored LeaveEvent for unknown queue " + event.getQueue()); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } if (channel == null) { logger.error("Ignored LeaveEvent for unknown channel " + event.getChannel()); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } final AsteriskQueueEntryImpl existingQueueEntry = queue.getEntry(event.getChannel()); if (existingQueueEntry == null) { logger.error("Ignored leave event for non existing queue entry in queue " + event.getQueue() + " for channel " + event.getChannel()); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } queue.removeEntry(existingQueueEntry, event.getDateReceived()); } }
public class class_name { public static Expression transformInlineConstants(final Expression exp, final ClassNode attrType) { if (exp instanceof PropertyExpression) { PropertyExpression pe = (PropertyExpression) exp; if (pe.getObjectExpression() instanceof ClassExpression) { ClassExpression ce = (ClassExpression) pe.getObjectExpression(); ClassNode type = ce.getType(); if (type.isEnum() || !(type.isResolved() || type.isPrimaryClassNode())) return exp; if (type.isPrimaryClassNode()) { FieldNode fn = type.redirect().getField(pe.getPropertyAsString()); if (fn != null && fn.isStatic() && fn.isFinal()) { Expression ce2 = transformInlineConstants(fn.getInitialValueExpression(), attrType); if (ce2 != null) { return ce2; } } } else { try { Field field = type.redirect().getTypeClass().getField(pe.getPropertyAsString()); if (field != null && Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers())) { ConstantExpression ce3 = new ConstantExpression(field.get(null), true); ce3.setSourcePosition(exp); return ce3; } } catch(Exception e) { // ignore, leave property expression in place and we'll report later } } } } else if (exp instanceof BinaryExpression) { ConstantExpression ce = transformBinaryConstantExpression((BinaryExpression) exp, attrType); if (ce != null) { return ce; } } else if (exp instanceof VariableExpression) { VariableExpression ve = (VariableExpression) exp; if (ve.getAccessedVariable() instanceof FieldNode) { FieldNode fn = (FieldNode) ve.getAccessedVariable(); if (fn.isStatic() && fn.isFinal()) { Expression ce = transformInlineConstants(fn.getInitialValueExpression(), attrType); if (ce != null) { return ce; } } } } else if (exp instanceof ListExpression) { return transformListOfConstants((ListExpression) exp, attrType); } return exp; } }
public class class_name { public static Expression transformInlineConstants(final Expression exp, final ClassNode attrType) { if (exp instanceof PropertyExpression) { PropertyExpression pe = (PropertyExpression) exp; if (pe.getObjectExpression() instanceof ClassExpression) { ClassExpression ce = (ClassExpression) pe.getObjectExpression(); ClassNode type = ce.getType(); if (type.isEnum() || !(type.isResolved() || type.isPrimaryClassNode())) return exp; if (type.isPrimaryClassNode()) { FieldNode fn = type.redirect().getField(pe.getPropertyAsString()); if (fn != null && fn.isStatic() && fn.isFinal()) { Expression ce2 = transformInlineConstants(fn.getInitialValueExpression(), attrType); if (ce2 != null) { return ce2; // depends on control dependency: [if], data = [none] } } } else { try { Field field = type.redirect().getTypeClass().getField(pe.getPropertyAsString()); if (field != null && Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers())) { ConstantExpression ce3 = new ConstantExpression(field.get(null), true); ce3.setSourcePosition(exp); // depends on control dependency: [if], data = [none] return ce3; // depends on control dependency: [if], data = [none] } } catch(Exception e) { // ignore, leave property expression in place and we'll report later } // depends on control dependency: [catch], data = [none] } } } else if (exp instanceof BinaryExpression) { ConstantExpression ce = transformBinaryConstantExpression((BinaryExpression) exp, attrType); if (ce != null) { return ce; // depends on control dependency: [if], data = [none] } } else if (exp instanceof VariableExpression) { VariableExpression ve = (VariableExpression) exp; if (ve.getAccessedVariable() instanceof FieldNode) { FieldNode fn = (FieldNode) ve.getAccessedVariable(); if (fn.isStatic() && fn.isFinal()) { Expression ce = transformInlineConstants(fn.getInitialValueExpression(), attrType); if (ce != null) { return ce; // depends on control dependency: [if], data = [none] } } } } else if (exp instanceof ListExpression) { return transformListOfConstants((ListExpression) exp, attrType); // depends on control dependency: [if], data = [none] } return exp; } }
public class class_name { @CheckReturnValue @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final T blockingFirst() { BlockingFirstSubscriber<T> s = new BlockingFirstSubscriber<T>(); subscribe(s); T v = s.blockingGet(); if (v != null) { return v; } throw new NoSuchElementException(); } }
public class class_name { @CheckReturnValue @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) public final T blockingFirst() { BlockingFirstSubscriber<T> s = new BlockingFirstSubscriber<T>(); subscribe(s); T v = s.blockingGet(); if (v != null) { return v; // depends on control dependency: [if], data = [none] } throw new NoSuchElementException(); } }
public class class_name { private byte[] getRequestStatsJson(String requestId) { RequestStats requestStats = cache.get(requestId); if (null != requestStats) { StringBuilder sb = new StringBuilder(); sb. append("{"). append("\"timeToFirstByte\":"). append(requestStats.getTimeToFirstByte()). append(","). append("\"time\":"). append(requestStats.getElapsedTime()); if (null != requestStats.getExecutedStatements()) { sb.append(",\"executedQueries\":["); Set<Map.Entry<StatementMetaData, SqlStats>> entries = requestStats.getExecutedStatements().entrySet(); Iterator<Map.Entry<StatementMetaData, SqlStats>> statementsIt = entries.iterator(); while (statementsIt.hasNext()) { Map.Entry<StatementMetaData, SqlStats> entry = statementsIt.next(); StatementMetaData statement = entry.getKey(); SqlStats sqlStats = entry.getValue(); sb. append("{"). append("\"query\":"). append(StringUtil.escapeJsonString(statement.sql)). append(","). append("\"stackTrace\":"). append(StringUtil.escapeJsonString(statement.stackTrace)). append(","). append("\"time\":"). append(sqlStats.elapsedTime.longValue()). append(","). append("\"invocations\":"). append(sqlStats.queries.longValue()). append(","). append("\"rows\":"). append(sqlStats.rows.longValue()). append(","). append("\"type\":\""). append(statement.query.name()). append("\","). append("\"bytesDown\":"). append(sqlStats.bytesDown.longValue()). append(","). append("\"bytesUp\":"). append(sqlStats.bytesUp.longValue()). append("}"); if (statementsIt.hasNext()) { sb.append(","); } } sb.append("]"); } if (null != requestStats.getSocketOperations()) { sb.append(",\"networkConnections\":["); Iterator<Map.Entry<SocketMetaData, SocketStats>> statementsIt = requestStats.getSocketOperations().entrySet().iterator(); while (statementsIt.hasNext()) { Map.Entry<SocketMetaData, SocketStats> entry = statementsIt.next(); SocketMetaData socketMetaData = entry.getKey(); SocketStats socketStats = entry.getValue(); sb. append("{"). append("\"host\":"). append(StringUtil.escapeJsonString(socketMetaData.address.toString())). append(","). append("\"stackTrace\":"). append(StringUtil.escapeJsonString(socketMetaData.stackTrace)). append(","). append("\"time\":"). append(socketStats.elapsedTime.longValue()). append(","). append("\"bytesDown\":"). append(socketStats.bytesDown.longValue()). append(","). append("\"bytesUp\":"). append(socketStats.bytesUp.longValue()). append("}"); if (statementsIt.hasNext()) { sb.append(","); } } sb.append("]"); } if (null != requestStats.getExceptions() && !requestStats.getExceptions().isEmpty()) { sb.append(",\"exceptions\":["); Iterator<Throwable> exceptionsIt = requestStats.getExceptions().iterator(); while (exceptionsIt.hasNext()) { Throwable exception = exceptionsIt.next(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exception.printStackTrace(pw); sb. append("{"). append("\"class\":"). append(StringUtil.escapeJsonString(exception.getClass().getName())). append(",\"message\":"). append(StringUtil.escapeJsonString(exception.getMessage())). append(",\"stackTrace\":"). append(StringUtil.escapeJsonString(sw.toString())). append("}"); if (exceptionsIt.hasNext()) { sb.append(","); } } sb.append("]"); } sb.append("}"); return sb.toString().getBytes(); } else { return null; } } }
public class class_name { private byte[] getRequestStatsJson(String requestId) { RequestStats requestStats = cache.get(requestId); if (null != requestStats) { StringBuilder sb = new StringBuilder(); sb. append("{"). append("\"timeToFirstByte\":"). append(requestStats.getTimeToFirstByte()). append(","). append("\"time\":"). append(requestStats.getElapsedTime()); // depends on control dependency: [if], data = [none] if (null != requestStats.getExecutedStatements()) { sb.append(",\"executedQueries\":["); // depends on control dependency: [if], data = [none] Set<Map.Entry<StatementMetaData, SqlStats>> entries = requestStats.getExecutedStatements().entrySet(); Iterator<Map.Entry<StatementMetaData, SqlStats>> statementsIt = entries.iterator(); while (statementsIt.hasNext()) { Map.Entry<StatementMetaData, SqlStats> entry = statementsIt.next(); StatementMetaData statement = entry.getKey(); SqlStats sqlStats = entry.getValue(); sb. append("{"). append("\"query\":"). append(StringUtil.escapeJsonString(statement.sql)). append(","). append("\"stackTrace\":"). append(StringUtil.escapeJsonString(statement.stackTrace)). append(","). append("\"time\":"). append(sqlStats.elapsedTime.longValue()). append(","). append("\"invocations\":"). append(sqlStats.queries.longValue()). append(","). append("\"rows\":"). append(sqlStats.rows.longValue()). append(","). append("\"type\":\""). append(statement.query.name()). append("\","). append("\"bytesDown\":"). append(sqlStats.bytesDown.longValue()). append(","). append("\"bytesUp\":"). append(sqlStats.bytesUp.longValue()). append("}"); // depends on control dependency: [while], data = [none] if (statementsIt.hasNext()) { sb.append(","); // depends on control dependency: [if], data = [none] } } sb.append("]"); // depends on control dependency: [if], data = [none] } if (null != requestStats.getSocketOperations()) { sb.append(",\"networkConnections\":["); // depends on control dependency: [if], data = [none] Iterator<Map.Entry<SocketMetaData, SocketStats>> statementsIt = requestStats.getSocketOperations().entrySet().iterator(); while (statementsIt.hasNext()) { Map.Entry<SocketMetaData, SocketStats> entry = statementsIt.next(); SocketMetaData socketMetaData = entry.getKey(); SocketStats socketStats = entry.getValue(); sb. append("{"). append("\"host\":"). append(StringUtil.escapeJsonString(socketMetaData.address.toString())). append(","). append("\"stackTrace\":"). append(StringUtil.escapeJsonString(socketMetaData.stackTrace)). append(","). append("\"time\":"). append(socketStats.elapsedTime.longValue()). append(","). append("\"bytesDown\":"). append(socketStats.bytesDown.longValue()). append(","). append("\"bytesUp\":"). append(socketStats.bytesUp.longValue()). append("}"); // depends on control dependency: [while], data = [none] if (statementsIt.hasNext()) { sb.append(","); // depends on control dependency: [if], data = [none] } } sb.append("]"); // depends on control dependency: [if], data = [none] } if (null != requestStats.getExceptions() && !requestStats.getExceptions().isEmpty()) { sb.append(",\"exceptions\":["); // depends on control dependency: [if], data = [none] Iterator<Throwable> exceptionsIt = requestStats.getExceptions().iterator(); while (exceptionsIt.hasNext()) { Throwable exception = exceptionsIt.next(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exception.printStackTrace(pw); // depends on control dependency: [while], data = [none] sb. append("{"). append("\"class\":"). append(StringUtil.escapeJsonString(exception.getClass().getName())). append(",\"message\":"). append(StringUtil.escapeJsonString(exception.getMessage())). append(",\"stackTrace\":"). append(StringUtil.escapeJsonString(sw.toString())). append("}"); // depends on control dependency: [while], data = [none] if (exceptionsIt.hasNext()) { sb.append(","); // depends on control dependency: [if], data = [none] } } sb.append("]"); // depends on control dependency: [if], data = [none] } sb.append("}"); // depends on control dependency: [if], data = [none] return sb.toString().getBytes(); // depends on control dependency: [if], data = [none] } else { return null; // depends on control dependency: [if], data = [none] } } }
public class class_name { public MasterSlaveServersConfig setMasterAddress(String masterAddress) { if (masterAddress != null) { this.masterAddress = URIBuilder.create(masterAddress); } return this; } }
public class class_name { public MasterSlaveServersConfig setMasterAddress(String masterAddress) { if (masterAddress != null) { this.masterAddress = URIBuilder.create(masterAddress); // depends on control dependency: [if], data = [(masterAddress] } return this; } }
public class class_name { @Override public PollResult startPoll(PollController conn) { if (! _lifecycle.isActive()) { log.warning(this + " select disabled"); return PollResult.CLOSED; } else if (_selectMax <= _connectionCount.get()) { log.warning(this + " keepalive overflow " + _connectionCount + " max=" + _selectMax); System.out.println("OVERFLOW:"); return PollResult.CLOSED; } if (! conn.toKeepaliveStart()) { return PollResult.CLOSED; } // XXX: check for full _executor.execute(new PollTask(conn)); return PollResult.START; } }
public class class_name { @Override public PollResult startPoll(PollController conn) { if (! _lifecycle.isActive()) { log.warning(this + " select disabled"); // depends on control dependency: [if], data = [none] return PollResult.CLOSED; // depends on control dependency: [if], data = [none] } else if (_selectMax <= _connectionCount.get()) { log.warning(this + " keepalive overflow " + _connectionCount + " max=" + _selectMax); // depends on control dependency: [if], data = [none] System.out.println("OVERFLOW:"); // depends on control dependency: [if], data = [none] return PollResult.CLOSED; // depends on control dependency: [if], data = [none] } if (! conn.toKeepaliveStart()) { return PollResult.CLOSED; // depends on control dependency: [if], data = [none] } // XXX: check for full _executor.execute(new PollTask(conn)); return PollResult.START; } }
public class class_name { @UiThread int getChildPosition(int flatPosition) { if (flatPosition == 0) { return 0; } int childCount = 0; for (int i = 0; i < flatPosition; i++) { ExpandableWrapper<P, C> listItem = mFlatItemList.get(i); if (listItem.isParent()) { childCount = 0; } else { childCount++; } } return childCount; } }
public class class_name { @UiThread int getChildPosition(int flatPosition) { if (flatPosition == 0) { return 0; // depends on control dependency: [if], data = [none] } int childCount = 0; for (int i = 0; i < flatPosition; i++) { ExpandableWrapper<P, C> listItem = mFlatItemList.get(i); if (listItem.isParent()) { childCount = 0; // depends on control dependency: [if], data = [none] } else { childCount++; // depends on control dependency: [if], data = [none] } } return childCount; } }
public class class_name { private void estimateNextExecution() { synchronized (TIMER_LOCK) { if (fixedDelay) { scheduledExecutionTime = period + System.currentTimeMillis(); } else { if (firstExecution == 0) { // save timestamp of first execution firstExecution = scheduledExecutionTime; } long now = System.currentTimeMillis(); long executedTime = (numInvocations++ * period); scheduledExecutionTime = firstExecution + executedTime; if(logger.isDebugEnabled()) { logger.debug("next execution estimated to run at " + scheduledExecutionTime); } if(logger.isDebugEnabled()) { logger.debug("current time is " + now); } } } } }
public class class_name { private void estimateNextExecution() { synchronized (TIMER_LOCK) { if (fixedDelay) { scheduledExecutionTime = period + System.currentTimeMillis(); // depends on control dependency: [if], data = [none] } else { if (firstExecution == 0) { // save timestamp of first execution firstExecution = scheduledExecutionTime; // depends on control dependency: [if], data = [none] } long now = System.currentTimeMillis(); long executedTime = (numInvocations++ * period); scheduledExecutionTime = firstExecution + executedTime; // depends on control dependency: [if], data = [none] if(logger.isDebugEnabled()) { logger.debug("next execution estimated to run at " + scheduledExecutionTime); // depends on control dependency: [if], data = [none] } if(logger.isDebugEnabled()) { logger.debug("current time is " + now); // depends on control dependency: [if], data = [none] } } } } }
public class class_name { public void marshall(ParametersFilter parametersFilter, ProtocolMarshaller protocolMarshaller) { if (parametersFilter == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(parametersFilter.getKey(), KEY_BINDING); protocolMarshaller.marshall(parametersFilter.getValues(), VALUES_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(ParametersFilter parametersFilter, ProtocolMarshaller protocolMarshaller) { if (parametersFilter == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(parametersFilter.getKey(), KEY_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(parametersFilter.getValues(), VALUES_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 long getChunkSize() throws IOException { final int st = this.state; switch (st) { case CHUNK_CRLF: this.buffer.clear(); final int bytesRead1 = this.in.readLine(this.buffer); if (bytesRead1 == -1) { throw new MalformedChunkCodingException( "CRLF expected at end of chunk"); } if (!this.buffer.isEmpty()) { throw new MalformedChunkCodingException( "Unexpected content at the end of chunk"); } state = CHUNK_LEN; //$FALL-THROUGH$ case CHUNK_LEN: this.buffer.clear(); final int bytesRead2 = this.in.readLine(this.buffer); if (bytesRead2 == -1) { throw new ConnectionClosedException("Premature end of chunk coded message body: " + "closing chunk expected"); } int separator = this.buffer.indexOf(';'); if (separator < 0) { separator = this.buffer.length(); } final String s = this.buffer.substringTrimmed(0, separator); try { return Long.parseLong(s, 16); } catch (final NumberFormatException e) { throw new MalformedChunkCodingException("Bad chunk header: " + s); } default: throw new IllegalStateException("Inconsistent codec state"); } } }
public class class_name { private long getChunkSize() throws IOException { final int st = this.state; switch (st) { case CHUNK_CRLF: this.buffer.clear(); final int bytesRead1 = this.in.readLine(this.buffer); if (bytesRead1 == -1) { throw new MalformedChunkCodingException( "CRLF expected at end of chunk"); } if (!this.buffer.isEmpty()) { throw new MalformedChunkCodingException( "Unexpected content at the end of chunk"); } state = CHUNK_LEN; //$FALL-THROUGH$ case CHUNK_LEN: this.buffer.clear(); final int bytesRead2 = this.in.readLine(this.buffer); if (bytesRead2 == -1) { throw new ConnectionClosedException("Premature end of chunk coded message body: " + "closing chunk expected"); } int separator = this.buffer.indexOf(';'); if (separator < 0) { separator = this.buffer.length(); // depends on control dependency: [if], data = [none] } final String s = this.buffer.substringTrimmed(0, separator); try { return Long.parseLong(s, 16); // depends on control dependency: [try], data = [none] } catch (final NumberFormatException e) { throw new MalformedChunkCodingException("Bad chunk header: " + s); } // depends on control dependency: [catch], data = [none] default: throw new IllegalStateException("Inconsistent codec state"); } } }
public class class_name { public static TreeSet<Integer> getUsableLocalPorts(int numRequested, int minPort, int maxPort) { final TreeSet<Integer> availablePorts = new TreeSet<>(); int attemptCount = 0; while ((++attemptCount <= numRequested + 100) && availablePorts.size() < numRequested) { availablePorts.add(getUsableLocalPort(minPort, maxPort)); } if (availablePorts.size() != numRequested) { throw new UtilException("Could not find {} available ports in the range [{}, {}]", numRequested, minPort, maxPort); } return availablePorts; } }
public class class_name { public static TreeSet<Integer> getUsableLocalPorts(int numRequested, int minPort, int maxPort) { final TreeSet<Integer> availablePorts = new TreeSet<>(); int attemptCount = 0; while ((++attemptCount <= numRequested + 100) && availablePorts.size() < numRequested) { availablePorts.add(getUsableLocalPort(minPort, maxPort)); // depends on control dependency: [while], data = [none] } if (availablePorts.size() != numRequested) { throw new UtilException("Could not find {} available ports in the range [{}, {}]", numRequested, minPort, maxPort); } return availablePorts; } }
public class class_name { void toStringParamValueOnly(final StringBuilder buf) { if (value == null) { buf.append("null"); } else { final Object paramVal = value.get(); final Class<?> valClass = paramVal.getClass(); if (valClass.isArray()) { buf.append('['); for (int j = 0, n = Array.getLength(paramVal); j < n; j++) { if (j > 0) { buf.append(", "); } final Object elt = Array.get(paramVal, j); buf.append(elt == null ? "null" : elt.toString()); } buf.append(']'); } else if (paramVal instanceof String) { buf.append('"'); buf.append(paramVal.toString().replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r")); buf.append('"'); } else if (paramVal instanceof Character) { buf.append('\''); buf.append(paramVal.toString().replace("'", "\\'").replace("\n", "\\n").replace("\r", "\\r")); buf.append('\''); } else { buf.append(paramVal.toString()); } } } }
public class class_name { void toStringParamValueOnly(final StringBuilder buf) { if (value == null) { buf.append("null"); // depends on control dependency: [if], data = [none] } else { final Object paramVal = value.get(); final Class<?> valClass = paramVal.getClass(); if (valClass.isArray()) { buf.append('['); // depends on control dependency: [if], data = [none] for (int j = 0, n = Array.getLength(paramVal); j < n; j++) { if (j > 0) { buf.append(", "); // depends on control dependency: [if], data = [none] } final Object elt = Array.get(paramVal, j); buf.append(elt == null ? "null" : elt.toString()); // depends on control dependency: [for], data = [none] } buf.append(']'); // depends on control dependency: [if], data = [none] } else if (paramVal instanceof String) { buf.append('"'); // depends on control dependency: [if], data = [none] buf.append(paramVal.toString().replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r")); // depends on control dependency: [if], data = [none] buf.append('"'); // depends on control dependency: [if], data = [none] } else if (paramVal instanceof Character) { buf.append('\''); // depends on control dependency: [if], data = [none] buf.append(paramVal.toString().replace("'", "\\'").replace("\n", "\\n").replace("\r", "\\r")); // depends on control dependency: [if], data = [none] buf.append('\''); // depends on control dependency: [if], data = [none] } else { buf.append(paramVal.toString()); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public static Map<String, Object> getAttributeMap(ServletRequest req) { if (req instanceof CmsFlexRequest) { return ((CmsFlexRequest)req).getAttributeMap(); } Map<String, Object> attrs = new HashMap<String, Object>(); Enumeration<String> atrrEnum = CmsCollectionsGenericWrapper.enumeration(req.getAttributeNames()); while (atrrEnum.hasMoreElements()) { String key = atrrEnum.nextElement(); Object value = req.getAttribute(key); attrs.put(key, value); } return attrs; } }
public class class_name { public static Map<String, Object> getAttributeMap(ServletRequest req) { if (req instanceof CmsFlexRequest) { return ((CmsFlexRequest)req).getAttributeMap(); // depends on control dependency: [if], data = [none] } Map<String, Object> attrs = new HashMap<String, Object>(); Enumeration<String> atrrEnum = CmsCollectionsGenericWrapper.enumeration(req.getAttributeNames()); while (atrrEnum.hasMoreElements()) { String key = atrrEnum.nextElement(); Object value = req.getAttribute(key); attrs.put(key, value); // depends on control dependency: [while], data = [none] } return attrs; } }
public class class_name { public Blacklist generateBlacklist(Model model) { ChemicalNameNormalizer normalizer = new ChemicalNameNormalizer(model); SIFSearcher searcher = new SIFSearcher(new Fetcher(normalizer), SIFEnum.USED_TO_PRODUCE); Set<SIFInteraction> sifs = searcher.searchSIF(model); // read interactions into maps Map<String, Set<String>> upstrMap = new HashMap<String, Set<String>>(); Map<String, Set<String>> dwstrMap = new HashMap<String, Set<String>>(); Map<String, Set<String>> neighMap = new HashMap<String, Set<String>>(); for (SIFInteraction sif : sifs) { String source = sif.sourceID; String target = sif.targetID; if (!neighMap.containsKey(source)) neighMap.put(source, new HashSet<String>()); if (!neighMap.containsKey(target)) neighMap.put(target, new HashSet<String>()); if (!dwstrMap.containsKey(source)) dwstrMap.put(source, new HashSet<String>()); if (!dwstrMap.containsKey(target)) dwstrMap.put(target, new HashSet<String>()); if (!upstrMap.containsKey(source)) upstrMap.put(source, new HashSet<String>()); if (!upstrMap.containsKey(target)) upstrMap.put(target, new HashSet<String>()); neighMap.get(source).add(target); neighMap.get(target).add(source); dwstrMap.get(source).add(target); upstrMap.get(target).add(source); } // remove intersection of upstream and downstream for (String name : neighMap.keySet()) { if (!upstrMap.containsKey(name) || !dwstrMap.containsKey(name)) continue; Set<String> upstr = upstrMap.get(name); Set<String> dwstr = dwstrMap.get(name); Set<String> temp = new HashSet<String>(upstr); upstr.removeAll(dwstr); dwstr.removeAll(temp); } Blacklist blacklist = new Blacklist(); // populate the blacklist for (SmallMoleculeReference smr : model.getObjects(SmallMoleculeReference.class)) { String name = normalizer.getName(smr); int neighSize = neighMap.containsKey(name) ? neighMap.get(name).size() : 0; int upstrOnly = upstrMap.containsKey(name) ? upstrMap.get(name).size() : 0; int dwstrOnly = dwstrMap.containsKey(name) ? dwstrMap.get(name).size() : 0; // if (neighSize > 30) System.out.println(name + "\t" + neighSize + "\t" + upstrOnly + "\t" + dwstrOnly); if (decider.isUbique(neighSize, upstrOnly, dwstrOnly)) { blacklist.addEntry(smr.getUri(), decider.getScore(neighSize, upstrOnly, dwstrOnly), decider.getContext(neighSize, upstrOnly, dwstrOnly)); } } return blacklist; } }
public class class_name { public Blacklist generateBlacklist(Model model) { ChemicalNameNormalizer normalizer = new ChemicalNameNormalizer(model); SIFSearcher searcher = new SIFSearcher(new Fetcher(normalizer), SIFEnum.USED_TO_PRODUCE); Set<SIFInteraction> sifs = searcher.searchSIF(model); // read interactions into maps Map<String, Set<String>> upstrMap = new HashMap<String, Set<String>>(); Map<String, Set<String>> dwstrMap = new HashMap<String, Set<String>>(); Map<String, Set<String>> neighMap = new HashMap<String, Set<String>>(); for (SIFInteraction sif : sifs) { String source = sif.sourceID; String target = sif.targetID; if (!neighMap.containsKey(source)) neighMap.put(source, new HashSet<String>()); if (!neighMap.containsKey(target)) neighMap.put(target, new HashSet<String>()); if (!dwstrMap.containsKey(source)) dwstrMap.put(source, new HashSet<String>()); if (!dwstrMap.containsKey(target)) dwstrMap.put(target, new HashSet<String>()); if (!upstrMap.containsKey(source)) upstrMap.put(source, new HashSet<String>()); if (!upstrMap.containsKey(target)) upstrMap.put(target, new HashSet<String>()); neighMap.get(source).add(target); // depends on control dependency: [for], data = [none] neighMap.get(target).add(source); // depends on control dependency: [for], data = [none] dwstrMap.get(source).add(target); // depends on control dependency: [for], data = [none] upstrMap.get(target).add(source); // depends on control dependency: [for], data = [none] } // remove intersection of upstream and downstream for (String name : neighMap.keySet()) { if (!upstrMap.containsKey(name) || !dwstrMap.containsKey(name)) continue; Set<String> upstr = upstrMap.get(name); Set<String> dwstr = dwstrMap.get(name); Set<String> temp = new HashSet<String>(upstr); upstr.removeAll(dwstr); // depends on control dependency: [for], data = [none] dwstr.removeAll(temp); // depends on control dependency: [for], data = [none] } Blacklist blacklist = new Blacklist(); // populate the blacklist for (SmallMoleculeReference smr : model.getObjects(SmallMoleculeReference.class)) { String name = normalizer.getName(smr); int neighSize = neighMap.containsKey(name) ? neighMap.get(name).size() : 0; int upstrOnly = upstrMap.containsKey(name) ? upstrMap.get(name).size() : 0; int dwstrOnly = dwstrMap.containsKey(name) ? dwstrMap.get(name).size() : 0; // if (neighSize > 30) System.out.println(name + "\t" + neighSize + "\t" + upstrOnly + "\t" + dwstrOnly); if (decider.isUbique(neighSize, upstrOnly, dwstrOnly)) { blacklist.addEntry(smr.getUri(), decider.getScore(neighSize, upstrOnly, dwstrOnly), decider.getContext(neighSize, upstrOnly, dwstrOnly)); // depends on control dependency: [if], data = [none] } } return blacklist; } }
public class class_name { private Set<AllocationID> computeAllPriorAllocationIds() { HashSet<AllocationID> allPreviousAllocationIds = new HashSet<>(getNumberOfExecutionJobVertices()); for (ExecutionVertex executionVertex : getAllExecutionVertices()) { AllocationID latestPriorAllocation = executionVertex.getLatestPriorAllocation(); if (latestPriorAllocation != null) { allPreviousAllocationIds.add(latestPriorAllocation); } } return allPreviousAllocationIds; } }
public class class_name { private Set<AllocationID> computeAllPriorAllocationIds() { HashSet<AllocationID> allPreviousAllocationIds = new HashSet<>(getNumberOfExecutionJobVertices()); for (ExecutionVertex executionVertex : getAllExecutionVertices()) { AllocationID latestPriorAllocation = executionVertex.getLatestPriorAllocation(); if (latestPriorAllocation != null) { allPreviousAllocationIds.add(latestPriorAllocation); // depends on control dependency: [if], data = [(latestPriorAllocation] } } return allPreviousAllocationIds; } }
public class class_name { public synchronized static void setLogFile(File logfile) { // Add a file logger that will use the compiler's customized // formatter. This formatter provides a terse representation of the // logging information. try { if (logfile != null) { String absolutePath = logfile.getAbsolutePath(); if (initializedLogFile == null || (!initializedLogFile.equals(absolutePath))) { // Remove any existing handlers. initializeLogger(topLogger); // Set the new handler. FileHandler handler = new FileHandler(absolutePath); handler.setFormatter(new LogFormatter()); topLogger.addHandler(handler); // Make sure we save the name of the log file to avoid // inappropriate reinitialization. initializedLogFile = absolutePath; } } } catch (IOException consumed) { StringBuilder sb = new StringBuilder(); sb.append("WARNING: unable to open logging file handler\n"); sb.append("WARNING: logfile = '" + logfile.getAbsolutePath() + "'"); sb.append("\nWARNING: message = "); sb.append(consumed.getMessage()); System.err.println(sb.toString()); } } }
public class class_name { public synchronized static void setLogFile(File logfile) { // Add a file logger that will use the compiler's customized // formatter. This formatter provides a terse representation of the // logging information. try { if (logfile != null) { String absolutePath = logfile.getAbsolutePath(); if (initializedLogFile == null || (!initializedLogFile.equals(absolutePath))) { // Remove any existing handlers. initializeLogger(topLogger); // depends on control dependency: [if], data = [none] // Set the new handler. FileHandler handler = new FileHandler(absolutePath); handler.setFormatter(new LogFormatter()); // depends on control dependency: [if], data = [none] topLogger.addHandler(handler); // depends on control dependency: [if], data = [none] // Make sure we save the name of the log file to avoid // inappropriate reinitialization. initializedLogFile = absolutePath; // depends on control dependency: [if], data = [none] } } } catch (IOException consumed) { StringBuilder sb = new StringBuilder(); sb.append("WARNING: unable to open logging file handler\n"); sb.append("WARNING: logfile = '" + logfile.getAbsolutePath() + "'"); sb.append("\nWARNING: message = "); sb.append(consumed.getMessage()); System.err.println(sb.toString()); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void releaseAndTryRemoveAll() throws Exception { Collection<String> children = getAllPaths(); Exception exception = null; for (String child : children) { try { releaseAndTryRemove('/' + child); } catch (Exception e) { exception = ExceptionUtils.firstOrSuppressed(e, exception); } } if (exception != null) { throw new Exception("Could not properly release and try removing all state nodes.", exception); } } }
public class class_name { public void releaseAndTryRemoveAll() throws Exception { Collection<String> children = getAllPaths(); Exception exception = null; for (String child : children) { try { releaseAndTryRemove('/' + child); // depends on control dependency: [try], data = [none] } catch (Exception e) { exception = ExceptionUtils.firstOrSuppressed(e, exception); } // depends on control dependency: [catch], data = [none] } if (exception != null) { throw new Exception("Could not properly release and try removing all state nodes.", exception); } } }
public class class_name { public OutlierResult run(Database database, Relation<N> spatial, Relation<O> attributes) { if(LOG.isDebugging()) { LOG.debug("Dimensionality: " + RelationUtil.dimensionality(attributes)); } final NeighborSetPredicate npred = getNeighborSetPredicateFactory().instantiate(database, spatial); CovarianceMatrix covmaker = new CovarianceMatrix(RelationUtil.dimensionality(attributes)); WritableDataStore<double[]> deltas = DataStoreUtil.makeStorage(attributes.getDBIDs(), DataStoreFactory.HINT_TEMP, double[].class); for(DBIDIter iditer = attributes.iterDBIDs(); iditer.valid(); iditer.advance()) { final O obj = attributes.get(iditer); final DBIDs neighbors = npred.getNeighborDBIDs(iditer); // TODO: remove object itself from neighbors? // Mean vector "g" double[] mean = Centroid.make(attributes, neighbors).getArrayRef(); // Delta vector "h" double[] delta = minusEquals(obj.toArray(), mean); deltas.put(iditer, delta); covmaker.put(delta); } // Finalize covariance matrix: double[] mean = covmaker.getMeanVector(); double[][] cmati = inverse(covmaker.destroyToSampleMatrix()); DoubleMinMax minmax = new DoubleMinMax(); WritableDoubleDataStore scores = DataStoreUtil.makeDoubleStorage(attributes.getDBIDs(), DataStoreFactory.HINT_STATIC); for(DBIDIter iditer = attributes.iterDBIDs(); iditer.valid(); iditer.advance()) { // Note: we modify deltas here double[] v = minusEquals(deltas.get(iditer), mean); final double score = transposeTimesTimes(v, cmati, v); minmax.put(score); scores.putDouble(iditer, score); } DoubleRelation scoreResult = new MaterializedDoubleRelation("mean multiple attributes spatial outlier", "mean-multipleattributes-outlier", scores, attributes.getDBIDs()); OutlierScoreMeta scoreMeta = new BasicOutlierScoreMeta(minmax.getMin(), minmax.getMax(), 0.0, Double.POSITIVE_INFINITY, 0); OutlierResult or = new OutlierResult(scoreMeta, scoreResult); or.addChildResult(npred); return or; } }
public class class_name { public OutlierResult run(Database database, Relation<N> spatial, Relation<O> attributes) { if(LOG.isDebugging()) { LOG.debug("Dimensionality: " + RelationUtil.dimensionality(attributes)); // depends on control dependency: [if], data = [none] } final NeighborSetPredicate npred = getNeighborSetPredicateFactory().instantiate(database, spatial); CovarianceMatrix covmaker = new CovarianceMatrix(RelationUtil.dimensionality(attributes)); WritableDataStore<double[]> deltas = DataStoreUtil.makeStorage(attributes.getDBIDs(), DataStoreFactory.HINT_TEMP, double[].class); for(DBIDIter iditer = attributes.iterDBIDs(); iditer.valid(); iditer.advance()) { final O obj = attributes.get(iditer); final DBIDs neighbors = npred.getNeighborDBIDs(iditer); // TODO: remove object itself from neighbors? // Mean vector "g" double[] mean = Centroid.make(attributes, neighbors).getArrayRef(); // Delta vector "h" double[] delta = minusEquals(obj.toArray(), mean); deltas.put(iditer, delta); // depends on control dependency: [for], data = [iditer] covmaker.put(delta); // depends on control dependency: [for], data = [none] } // Finalize covariance matrix: double[] mean = covmaker.getMeanVector(); double[][] cmati = inverse(covmaker.destroyToSampleMatrix()); DoubleMinMax minmax = new DoubleMinMax(); WritableDoubleDataStore scores = DataStoreUtil.makeDoubleStorage(attributes.getDBIDs(), DataStoreFactory.HINT_STATIC); for(DBIDIter iditer = attributes.iterDBIDs(); iditer.valid(); iditer.advance()) { // Note: we modify deltas here double[] v = minusEquals(deltas.get(iditer), mean); final double score = transposeTimesTimes(v, cmati, v); minmax.put(score); // depends on control dependency: [for], data = [none] scores.putDouble(iditer, score); // depends on control dependency: [for], data = [iditer] } DoubleRelation scoreResult = new MaterializedDoubleRelation("mean multiple attributes spatial outlier", "mean-multipleattributes-outlier", scores, attributes.getDBIDs()); OutlierScoreMeta scoreMeta = new BasicOutlierScoreMeta(minmax.getMin(), minmax.getMax(), 0.0, Double.POSITIVE_INFINITY, 0); OutlierResult or = new OutlierResult(scoreMeta, scoreResult); or.addChildResult(npred); return or; } }
public class class_name { public void shape(char[] text, int start, int count, Range context) { checkParams(text, start, count); if (context == null) { throw new NullPointerException("context is null"); } if (isContextual()) { if (rangeSet != null) { shapeContextually(text, start, count, context); } else { int key = Range.toRangeIndex(context); if (key >= 0) { shapeContextually(text, start, count, key); } else { shapeContextually(text, start, count, shapingRange); } } } else { shapeNonContextually(text, start, count); } } }
public class class_name { public void shape(char[] text, int start, int count, Range context) { checkParams(text, start, count); if (context == null) { throw new NullPointerException("context is null"); } if (isContextual()) { if (rangeSet != null) { shapeContextually(text, start, count, context); // depends on control dependency: [if], data = [none] } else { int key = Range.toRangeIndex(context); if (key >= 0) { shapeContextually(text, start, count, key); // depends on control dependency: [if], data = [none] } else { shapeContextually(text, start, count, shapingRange); // depends on control dependency: [if], data = [none] } } } else { shapeNonContextually(text, start, count); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static String durationToFormattedString(final Duration duration) { if (duration == null) { return null; } return LocalTime.ofNanoOfDay(duration.toNanos()).format(DateTimeFormatter.ofPattern(DURATION_FORMAT)); } }
public class class_name { public static String durationToFormattedString(final Duration duration) { if (duration == null) { return null; // depends on control dependency: [if], data = [none] } return LocalTime.ofNanoOfDay(duration.toNanos()).format(DateTimeFormatter.ofPattern(DURATION_FORMAT)); } }
public class class_name { protected Color parseHtml(String value) { if (value.length() != 7) { throw new ConversionException(USAGE); } int colorValue = 0; try { colorValue = Integer.parseInt(value.substring(1), 16); return new Color(colorValue); } catch (NumberFormatException ex) { throw new ConversionException(value + "is not a valid Html color", ex); } } }
public class class_name { protected Color parseHtml(String value) { if (value.length() != 7) { throw new ConversionException(USAGE); } int colorValue = 0; try { colorValue = Integer.parseInt(value.substring(1), 16); // depends on control dependency: [try], data = [none] return new Color(colorValue); // depends on control dependency: [try], data = [none] } catch (NumberFormatException ex) { throw new ConversionException(value + "is not a valid Html color", ex); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private void release() { try { Method release = BoundObjectTable.Table.class.getDeclaredMethod("release", String.class); release.setAccessible(true); release.invoke(boundObjectTable, boundId); } catch (Exception x) { LOG.log(Level.WARNING, "failed to unbind " + boundId, x); } } }
public class class_name { private void release() { try { Method release = BoundObjectTable.Table.class.getDeclaredMethod("release", String.class); release.setAccessible(true); // depends on control dependency: [try], data = [none] release.invoke(boundObjectTable, boundId); // depends on control dependency: [try], data = [none] } catch (Exception x) { LOG.log(Level.WARNING, "failed to unbind " + boundId, x); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static ScopedRequest getScopedRequest( HttpServletRequest realRequest, String overrideURI, ServletContext servletContext, Object scopeKey, boolean seeOuterRequestAttributes ) { assert ! ( realRequest instanceof ScopedRequest ); String requestAttr = getScopedName( OVERRIDE_REQUEST_ATTR, scopeKey ); ScopedRequest scopedRequest = ( ScopedRequest ) realRequest.getAttribute( requestAttr ); // // If it doesn't exist, create it and cache it. // if ( scopedRequest == null ) { // // The override URI must start with a slash -- it's webapp-relative. // if ( overrideURI != null && ! overrideURI.startsWith( "/" ) ) overrideURI = '/' + overrideURI; scopedRequest = new ScopedRequestImpl( realRequest, overrideURI, scopeKey, servletContext, seeOuterRequestAttributes ); realRequest.setAttribute( requestAttr, scopedRequest ); } return scopedRequest; } }
public class class_name { public static ScopedRequest getScopedRequest( HttpServletRequest realRequest, String overrideURI, ServletContext servletContext, Object scopeKey, boolean seeOuterRequestAttributes ) { assert ! ( realRequest instanceof ScopedRequest ); String requestAttr = getScopedName( OVERRIDE_REQUEST_ATTR, scopeKey ); ScopedRequest scopedRequest = ( ScopedRequest ) realRequest.getAttribute( requestAttr ); // // If it doesn't exist, create it and cache it. // if ( scopedRequest == null ) { // // The override URI must start with a slash -- it's webapp-relative. // if ( overrideURI != null && ! overrideURI.startsWith( "/" ) ) overrideURI = '/' + overrideURI; scopedRequest = new ScopedRequestImpl( realRequest, overrideURI, scopeKey, servletContext, seeOuterRequestAttributes ); // depends on control dependency: [if], data = [none] realRequest.setAttribute( requestAttr, scopedRequest ); // depends on control dependency: [if], data = [none] } return scopedRequest; } }
public class class_name { public void buildPackageHeader(XMLNode node, Content summariesTree) { String parsedPackageName = parsePackageName(currentPackage.name()); if (! printedPackageHeaders.contains(parsedPackageName)) { writer.addPackageName(currentPackage, parsePackageName(currentPackage.name()), summariesTree); printedPackageHeaders.add(parsedPackageName); } } }
public class class_name { public void buildPackageHeader(XMLNode node, Content summariesTree) { String parsedPackageName = parsePackageName(currentPackage.name()); if (! printedPackageHeaders.contains(parsedPackageName)) { writer.addPackageName(currentPackage, parsePackageName(currentPackage.name()), summariesTree); // depends on control dependency: [if], data = [none] printedPackageHeaders.add(parsedPackageName); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static Callable<Void> getUploadFileCallable( final StageInfo stage, final String srcFilePath, final FileMetadata metadata, final SnowflakeStorageClient client, final SFSession connection, final String command, final InputStream inputStream, final boolean sourceFromStream, final int parallel, final File srcFile, final RemoteStoreFileEncryptionMaterial encMat) { return new Callable<Void>() { public Void call() throws Exception { logger.debug("Entering getUploadFileCallable..."); InputStream uploadStream = inputStream; File fileToUpload = null; if (uploadStream == null) { try { uploadStream = new FileInputStream(srcFilePath); } catch (FileNotFoundException ex) { metadata.resultStatus = ResultStatus.ERROR; metadata.errorDetails = ex.getMessage(); throw ex; } } // this shouldn't happen if (metadata == null) { throw new SnowflakeSQLException(SqlState.INTERNAL_ERROR, ErrorCode.INTERNAL_ERROR.getMessageCode(), "missing file metadata for: " + srcFilePath); } String destFileName = metadata.destFileName; long uploadSize; String digest = null; logger.debug("Dest file name={}"); // Temp file that needs to be cleaned up when upload was successful FileBackedOutputStream fileBackedOutputStream = null; // SNOW-16082: we should catpure exception if we fail to compress or // calcuate digest. try { if (metadata.requireCompress) { InputStreamWithMetadata compressedSizeAndStream = (encMat == null ? compressStreamWithGZIPNoDigest(uploadStream) : compressStreamWithGZIP(uploadStream)); fileBackedOutputStream = compressedSizeAndStream.fileBackedOutputStream; // update the size uploadSize = compressedSizeAndStream.size; digest = compressedSizeAndStream.digest; if (compressedSizeAndStream.fileBackedOutputStream.getFile() != null) { fileToUpload = compressedSizeAndStream.fileBackedOutputStream.getFile(); } logger.debug("New size after compression: {}", uploadSize); } else if (stage.getStageType() != StageInfo.StageType.LOCAL_FS) { // If it's not local_fs, we store our digest in the metadata // In local_fs, we don't need digest, and if we turn it on, we will consume whole uploadStream, which local_fs uses. InputStreamWithMetadata result = computeDigest(uploadStream, sourceFromStream); digest = result.digest; fileBackedOutputStream = result.fileBackedOutputStream; uploadSize = result.size; if (!sourceFromStream) { fileToUpload = srcFile; } else if (result.fileBackedOutputStream.getFile() != null) { fileToUpload = result.fileBackedOutputStream.getFile(); } } else { if (!sourceFromStream && (srcFile != null)) { fileToUpload = srcFile; } // if stage is local_fs and upload source is stream, upload size // does not matter since 1) transfer did not require size 2) no // output from uploadStream api is required uploadSize = sourceFromStream ? 0 : srcFile.length(); } logger.debug("Started copying file from: {} to {}:{} destName: {} " + "auto compressed? {} size={}", srcFilePath, stage.getStageType().name(), stage.getLocation(), destFileName, (metadata.requireCompress ? "yes" : "no"), uploadSize); // Simulated failure code. if (connection.getInjectFileUploadFailure() != null && srcFilePath.endsWith( (connection).getInjectFileUploadFailure())) { throw new SnowflakeSimulatedUploadFailure( srcFile != null ? srcFile.getName() : "Unknown"); } // upload it switch (stage.getStageType()) { case LOCAL_FS: pushFileToLocal(stage.getLocation(), srcFilePath, destFileName, uploadStream, fileBackedOutputStream); break; case S3: case AZURE: pushFileToRemoteStore(stage, destFileName, uploadStream, fileBackedOutputStream, uploadSize, digest, metadata.destCompressionType, client, connection, command, parallel, fileToUpload, (fileToUpload == null), encMat); metadata.isEncrypted = encMat != null; break; } } catch (SnowflakeSimulatedUploadFailure ex) { // This code path is used for Simulated failure code in tests. // Never happen in production metadata.resultStatus = ResultStatus.ERROR; metadata.errorDetails = ex.getMessage(); throw ex; } catch (Throwable ex) { logger.error( "Exception encountered during file upload", ex); metadata.resultStatus = ResultStatus.ERROR; metadata.errorDetails = ex.getMessage(); throw ex; } finally { if (fileBackedOutputStream != null) { try { fileBackedOutputStream.reset(); } catch (IOException ex) { logger.debug("failed to clean up temp file: {}", ex); } } if (inputStream == null) { IOUtils.closeQuietly(uploadStream); } } logger.debug("filePath: {}", srcFilePath); // set dest size metadata.destFileSize = uploadSize; // mark the file as being uploaded metadata.resultStatus = ResultStatus.UPLOADED; return null; } }; } }
public class class_name { public static Callable<Void> getUploadFileCallable( final StageInfo stage, final String srcFilePath, final FileMetadata metadata, final SnowflakeStorageClient client, final SFSession connection, final String command, final InputStream inputStream, final boolean sourceFromStream, final int parallel, final File srcFile, final RemoteStoreFileEncryptionMaterial encMat) { return new Callable<Void>() { public Void call() throws Exception { logger.debug("Entering getUploadFileCallable..."); InputStream uploadStream = inputStream; File fileToUpload = null; if (uploadStream == null) { try { uploadStream = new FileInputStream(srcFilePath); // depends on control dependency: [try], data = [none] } catch (FileNotFoundException ex) { metadata.resultStatus = ResultStatus.ERROR; metadata.errorDetails = ex.getMessage(); throw ex; } // depends on control dependency: [catch], data = [none] } // this shouldn't happen if (metadata == null) { throw new SnowflakeSQLException(SqlState.INTERNAL_ERROR, ErrorCode.INTERNAL_ERROR.getMessageCode(), "missing file metadata for: " + srcFilePath); } String destFileName = metadata.destFileName; long uploadSize; String digest = null; logger.debug("Dest file name={}"); // Temp file that needs to be cleaned up when upload was successful FileBackedOutputStream fileBackedOutputStream = null; // SNOW-16082: we should catpure exception if we fail to compress or // calcuate digest. try { if (metadata.requireCompress) { InputStreamWithMetadata compressedSizeAndStream = (encMat == null ? compressStreamWithGZIPNoDigest(uploadStream) : compressStreamWithGZIP(uploadStream)); fileBackedOutputStream = compressedSizeAndStream.fileBackedOutputStream; // depends on control dependency: [if], data = [none] // update the size uploadSize = compressedSizeAndStream.size; // depends on control dependency: [if], data = [none] digest = compressedSizeAndStream.digest; // depends on control dependency: [if], data = [none] if (compressedSizeAndStream.fileBackedOutputStream.getFile() != null) { fileToUpload = compressedSizeAndStream.fileBackedOutputStream.getFile(); // depends on control dependency: [if], data = [none] } logger.debug("New size after compression: {}", uploadSize); // depends on control dependency: [if], data = [none] } else if (stage.getStageType() != StageInfo.StageType.LOCAL_FS) { // If it's not local_fs, we store our digest in the metadata // In local_fs, we don't need digest, and if we turn it on, we will consume whole uploadStream, which local_fs uses. InputStreamWithMetadata result = computeDigest(uploadStream, sourceFromStream); digest = result.digest; // depends on control dependency: [if], data = [none] fileBackedOutputStream = result.fileBackedOutputStream; // depends on control dependency: [if], data = [none] uploadSize = result.size; // depends on control dependency: [if], data = [none] if (!sourceFromStream) { fileToUpload = srcFile; // depends on control dependency: [if], data = [none] } else if (result.fileBackedOutputStream.getFile() != null) { fileToUpload = result.fileBackedOutputStream.getFile(); // depends on control dependency: [if], data = [none] } } else { if (!sourceFromStream && (srcFile != null)) { fileToUpload = srcFile; // depends on control dependency: [if], data = [none] } // if stage is local_fs and upload source is stream, upload size // does not matter since 1) transfer did not require size 2) no // output from uploadStream api is required uploadSize = sourceFromStream ? 0 : srcFile.length(); // depends on control dependency: [if], data = [none] } logger.debug("Started copying file from: {} to {}:{} destName: {} " + "auto compressed? {} size={}", srcFilePath, stage.getStageType().name(), stage.getLocation(), destFileName, (metadata.requireCompress ? "yes" : "no"), uploadSize); // Simulated failure code. if (connection.getInjectFileUploadFailure() != null && srcFilePath.endsWith( (connection).getInjectFileUploadFailure())) { throw new SnowflakeSimulatedUploadFailure( srcFile != null ? srcFile.getName() : "Unknown"); } // upload it switch (stage.getStageType()) { case LOCAL_FS: pushFileToLocal(stage.getLocation(), srcFilePath, destFileName, uploadStream, fileBackedOutputStream); break; case S3: case AZURE: pushFileToRemoteStore(stage, destFileName, uploadStream, fileBackedOutputStream, uploadSize, digest, metadata.destCompressionType, client, connection, command, parallel, fileToUpload, (fileToUpload == null), encMat); metadata.isEncrypted = encMat != null; break; } } catch (SnowflakeSimulatedUploadFailure ex) { // This code path is used for Simulated failure code in tests. // Never happen in production metadata.resultStatus = ResultStatus.ERROR; metadata.errorDetails = ex.getMessage(); throw ex; } catch (Throwable ex) { logger.error( "Exception encountered during file upload", ex); metadata.resultStatus = ResultStatus.ERROR; metadata.errorDetails = ex.getMessage(); throw ex; } finally { if (fileBackedOutputStream != null) { try { fileBackedOutputStream.reset(); // depends on control dependency: [try], data = [none] } catch (IOException ex) { logger.debug("failed to clean up temp file: {}", ex); } // depends on control dependency: [catch], data = [none] } if (inputStream == null) { IOUtils.closeQuietly(uploadStream); // depends on control dependency: [if], data = [none] } } logger.debug("filePath: {}", srcFilePath); // set dest size metadata.destFileSize = uploadSize; // mark the file as being uploaded metadata.resultStatus = ResultStatus.UPLOADED; return null; } }; } }
public class class_name { public boolean canRemoveRepository(String name) throws RepositoryException { RepositoryImpl repo = (RepositoryImpl)getRepository(name); try { RepositoryEntry repconfig = config.getRepositoryConfiguration(name); for (WorkspaceEntry wsEntry : repconfig.getWorkspaceEntries()) { // Check non system workspaces if (!repo.getSystemWorkspaceName().equals(wsEntry.getName()) && !repo.canRemoveWorkspace(wsEntry.getName())) { return false; } } // check system workspace RepositoryContainer repositoryContainer = repositoryContainers.get(name); SessionRegistry sessionRegistry = (SessionRegistry)repositoryContainer.getComponentInstance(SessionRegistry.class); if (sessionRegistry == null || sessionRegistry.isInUse(repo.getSystemWorkspaceName())) { return false; } } catch (RepositoryConfigurationException e) { throw new RepositoryException(e); } return true; } }
public class class_name { public boolean canRemoveRepository(String name) throws RepositoryException { RepositoryImpl repo = (RepositoryImpl)getRepository(name); try { RepositoryEntry repconfig = config.getRepositoryConfiguration(name); for (WorkspaceEntry wsEntry : repconfig.getWorkspaceEntries()) { // Check non system workspaces if (!repo.getSystemWorkspaceName().equals(wsEntry.getName()) && !repo.canRemoveWorkspace(wsEntry.getName())) { return false; // depends on control dependency: [if], data = [none] } } // check system workspace RepositoryContainer repositoryContainer = repositoryContainers.get(name); SessionRegistry sessionRegistry = (SessionRegistry)repositoryContainer.getComponentInstance(SessionRegistry.class); if (sessionRegistry == null || sessionRegistry.isInUse(repo.getSystemWorkspaceName())) { return false; // depends on control dependency: [if], data = [none] } } catch (RepositoryConfigurationException e) { throw new RepositoryException(e); } return true; } }
public class class_name { public ThreadPoolBuilder withName(String name) { // ensure we've got a spot to put the thread id. if (!name.contains("%d")) { name = name + "-%d"; } nameMap.putIfAbsent(name, new AtomicInteger(0)); int id = nameMap.get(name).incrementAndGet(); this.poolName = String.format(name, id); if (id > 1) { this.threadNameFormat = name.replace("%d", id + "-%d"); } else { this.threadNameFormat = name; } return this; } }
public class class_name { public ThreadPoolBuilder withName(String name) { // ensure we've got a spot to put the thread id. if (!name.contains("%d")) { name = name + "-%d"; // depends on control dependency: [if], data = [none] } nameMap.putIfAbsent(name, new AtomicInteger(0)); int id = nameMap.get(name).incrementAndGet(); this.poolName = String.format(name, id); if (id > 1) { this.threadNameFormat = name.replace("%d", id + "-%d"); // depends on control dependency: [if], data = [none] } else { this.threadNameFormat = name; // depends on control dependency: [if], data = [none] } return this; } }
public class class_name { @Override public void encodeBegin(FacesContext context, UIComponent component) throws IOException { if (!component.isRendered()) { return; } Accordion accordion = (Accordion) component; ResponseWriter rw = context.getResponseWriter(); String clientId = accordion.getClientId(); String accordionClientId = clientId.replace(":", "_"); List<String> expandedIds = (null != accordion.getExpandedPanels()) ? Arrays.asList(accordion.getExpandedPanels().split(",")) : null; rw.startElement("div", accordion); String styleClass = accordion.getStyleClass(); if (null == styleClass) { styleClass="panel-group"; } else { styleClass += " panel-group"; } rw.writeAttribute("class", (styleClass + Responsive.getResponsiveStyleClass(accordion, false)).trim(), null); writeAttribute(rw, "style", accordion.getStyle()); rw.writeAttribute("id", accordionClientId, "id"); Tooltip.generateTooltip(context, component, rw); beginDisabledFieldset(accordion, rw); if (accordion.getChildren() != null && accordion.getChildren().size() > 0) { for (UIComponent _child : accordion.getChildren()) { if (_child instanceof Panel && ((Panel) _child).isCollapsible()) { Panel _childPane = (Panel) _child; _childPane.setAccordionParent(accordionClientId); String childPaneClientId = _childPane.getClientId(); if (_childPane.getClientId().contains(":")) { String[] parts = _childPane.getClientId().split(":"); if (parts.length == 2) childPaneClientId = parts[1]; } if (null != expandedIds && expandedIds.contains(_childPane.getClientId())) _childPane.setCollapsed(false); else _childPane.setCollapsed(true); _childPane.encodeAll(context); } else { throw new FacesException("Accordion must contain only collapsible panel components", null); } } } endDisabledFieldset(accordion, rw); } }
public class class_name { @Override public void encodeBegin(FacesContext context, UIComponent component) throws IOException { if (!component.isRendered()) { return; } Accordion accordion = (Accordion) component; ResponseWriter rw = context.getResponseWriter(); String clientId = accordion.getClientId(); String accordionClientId = clientId.replace(":", "_"); List<String> expandedIds = (null != accordion.getExpandedPanels()) ? Arrays.asList(accordion.getExpandedPanels().split(",")) : null; rw.startElement("div", accordion); String styleClass = accordion.getStyleClass(); if (null == styleClass) { styleClass="panel-group"; } else { styleClass += " panel-group"; } rw.writeAttribute("class", (styleClass + Responsive.getResponsiveStyleClass(accordion, false)).trim(), null); writeAttribute(rw, "style", accordion.getStyle()); rw.writeAttribute("id", accordionClientId, "id"); Tooltip.generateTooltip(context, component, rw); beginDisabledFieldset(accordion, rw); if (accordion.getChildren() != null && accordion.getChildren().size() > 0) { for (UIComponent _child : accordion.getChildren()) { if (_child instanceof Panel && ((Panel) _child).isCollapsible()) { Panel _childPane = (Panel) _child; _childPane.setAccordionParent(accordionClientId); // depends on control dependency: [if], data = [none] String childPaneClientId = _childPane.getClientId(); if (_childPane.getClientId().contains(":")) { String[] parts = _childPane.getClientId().split(":"); if (parts.length == 2) childPaneClientId = parts[1]; } if (null != expandedIds && expandedIds.contains(_childPane.getClientId())) _childPane.setCollapsed(false); else _childPane.setCollapsed(true); _childPane.encodeAll(context); // depends on control dependency: [if], data = [none] } else { throw new FacesException("Accordion must contain only collapsible panel components", null); } } } endDisabledFieldset(accordion, rw); } }
public class class_name { public static synchronized void printPortsInUse(VoltLogger log) { try { /* * Don't do DNS resolution, don't use names for port numbers */ ProcessBuilder pb = new ProcessBuilder("lsof", "-i", "-n", "-P"); pb.redirectErrorStream(true); Process p = pb.start(); java.io.InputStreamReader reader = new java.io.InputStreamReader(p.getInputStream()); java.io.BufferedReader br = new java.io.BufferedReader(reader); String str = br.readLine(); log.fatal("Logging ports that are bound for listening, " + "this doesn't include ports bound by outgoing connections " + "which can also cause a failure to bind"); log.fatal("The PID of this process is " + getPID()); if (str != null) { log.fatal(str); } while((str = br.readLine()) != null) { if (str.contains("LISTEN")) { log.fatal(str); } } } catch (Exception e) { log.fatal("Unable to list ports in use at this time."); } } }
public class class_name { public static synchronized void printPortsInUse(VoltLogger log) { try { /* * Don't do DNS resolution, don't use names for port numbers */ ProcessBuilder pb = new ProcessBuilder("lsof", "-i", "-n", "-P"); pb.redirectErrorStream(true); // depends on control dependency: [try], data = [none] Process p = pb.start(); java.io.InputStreamReader reader = new java.io.InputStreamReader(p.getInputStream()); java.io.BufferedReader br = new java.io.BufferedReader(reader); String str = br.readLine(); log.fatal("Logging ports that are bound for listening, " + "this doesn't include ports bound by outgoing connections " + "which can also cause a failure to bind"); // depends on control dependency: [try], data = [none] log.fatal("The PID of this process is " + getPID()); // depends on control dependency: [try], data = [none] if (str != null) { log.fatal(str); // depends on control dependency: [if], data = [(str] } while((str = br.readLine()) != null) { if (str.contains("LISTEN")) { log.fatal(str); // depends on control dependency: [if], data = [none] } } } catch (Exception e) { log.fatal("Unable to list ports in use at this time."); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static char[] addToCharArray(char[] a, char value) { if(a == null || a.length == 0) { return new char[] {value}; } char[] array = new char[a.length + 1]; array[a.length] = value; return array; } }
public class class_name { public static char[] addToCharArray(char[] a, char value) { if(a == null || a.length == 0) { return new char[] {value}; // depends on control dependency: [if], data = [none] } char[] array = new char[a.length + 1]; array[a.length] = value; return array; } }
public class class_name { public void cleanWatchers(String name){ synchronized(watchers){ if(watchers.containsKey(name)){ watchers.get(name).clear(); } } } }
public class class_name { public void cleanWatchers(String name){ synchronized(watchers){ if(watchers.containsKey(name)){ watchers.get(name).clear(); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public void marshall(BuiltinIntentMetadata builtinIntentMetadata, ProtocolMarshaller protocolMarshaller) { if (builtinIntentMetadata == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(builtinIntentMetadata.getSignature(), SIGNATURE_BINDING); protocolMarshaller.marshall(builtinIntentMetadata.getSupportedLocales(), SUPPORTEDLOCALES_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(BuiltinIntentMetadata builtinIntentMetadata, ProtocolMarshaller protocolMarshaller) { if (builtinIntentMetadata == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(builtinIntentMetadata.getSignature(), SIGNATURE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(builtinIntentMetadata.getSupportedLocales(), SUPPORTEDLOCALES_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public Map<String, String> getSubmissionType(ProposalDevelopmentDocumentContract pdDoc) { Map<String, String> submissionInfo = new HashMap<>(); S2sOpportunityContract opportunity = pdDoc.getDevelopmentProposal().getS2sOpportunity(); if (opportunity != null) { if (opportunity.getS2sSubmissionType() != null) { String submissionTypeCode = opportunity.getS2sSubmissionType().getCode(); String submissionTypeDescription = opportunity.getS2sSubmissionType().getDescription(); submissionInfo.put(SUBMISSION_TYPE_CODE, submissionTypeCode); submissionInfo.put(SUBMISSION_TYPE_DESCRIPTION, submissionTypeDescription); } if (opportunity.getS2sRevisionType() != null) { String revisionCode = opportunity.getS2sRevisionType().getCode(); submissionInfo.put(KEY_REVISION_CODE, revisionCode); } if (opportunity.getRevisionOtherDescription() != null) { submissionInfo.put(KEY_REVISION_OTHER_DESCRIPTION, opportunity.getRevisionOtherDescription()); } } return submissionInfo; } }
public class class_name { public Map<String, String> getSubmissionType(ProposalDevelopmentDocumentContract pdDoc) { Map<String, String> submissionInfo = new HashMap<>(); S2sOpportunityContract opportunity = pdDoc.getDevelopmentProposal().getS2sOpportunity(); if (opportunity != null) { if (opportunity.getS2sSubmissionType() != null) { String submissionTypeCode = opportunity.getS2sSubmissionType().getCode(); String submissionTypeDescription = opportunity.getS2sSubmissionType().getDescription(); submissionInfo.put(SUBMISSION_TYPE_CODE, submissionTypeCode); // depends on control dependency: [if], data = [none] submissionInfo.put(SUBMISSION_TYPE_DESCRIPTION, submissionTypeDescription); // depends on control dependency: [if], data = [none] } if (opportunity.getS2sRevisionType() != null) { String revisionCode = opportunity.getS2sRevisionType().getCode(); submissionInfo.put(KEY_REVISION_CODE, revisionCode); // depends on control dependency: [if], data = [none] } if (opportunity.getRevisionOtherDescription() != null) { submissionInfo.put(KEY_REVISION_OTHER_DESCRIPTION, opportunity.getRevisionOtherDescription()); // depends on control dependency: [if], data = [none] } } return submissionInfo; } }
public class class_name { private static boolean isRequestRewriteNeeded(HttpMessage message) { int statusCode = message.getResponseHeader().getStatusCode(); String method = message.getRequestHeader().getMethod(); if (statusCode == 301 || statusCode == 302) { return HttpRequestHeader.POST.equalsIgnoreCase(method); } return statusCode == 303 && !(HttpRequestHeader.GET.equalsIgnoreCase(method) || HttpRequestHeader.HEAD.equalsIgnoreCase(method)); } }
public class class_name { private static boolean isRequestRewriteNeeded(HttpMessage message) { int statusCode = message.getResponseHeader().getStatusCode(); String method = message.getRequestHeader().getMethod(); if (statusCode == 301 || statusCode == 302) { return HttpRequestHeader.POST.equalsIgnoreCase(method); // depends on control dependency: [if], data = [none] } return statusCode == 303 && !(HttpRequestHeader.GET.equalsIgnoreCase(method) || HttpRequestHeader.HEAD.equalsIgnoreCase(method)); } }
public class class_name { public void removeQuery(String id) { int index = getElementPosition(id); QueryControllerEntity element = entities.get(index); if (element instanceof QueryControllerQuery) { entities.remove(index); fireElementRemoved(element); return; } else { QueryControllerGroup group = (QueryControllerGroup) element; Vector<QueryControllerQuery> queries_ingroup = group.getQueries(); for (QueryControllerQuery query : queries_ingroup) { if (query.getID().equals(id)) { fireElementRemoved(group.removeQuery(query.getID()), group); return; } } } } }
public class class_name { public void removeQuery(String id) { int index = getElementPosition(id); QueryControllerEntity element = entities.get(index); if (element instanceof QueryControllerQuery) { entities.remove(index); // depends on control dependency: [if], data = [none] fireElementRemoved(element); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } else { QueryControllerGroup group = (QueryControllerGroup) element; Vector<QueryControllerQuery> queries_ingroup = group.getQueries(); for (QueryControllerQuery query : queries_ingroup) { if (query.getID().equals(id)) { fireElementRemoved(group.removeQuery(query.getID()), group); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } } } } }
public class class_name { public String getScript(ClientBehaviorContext behaviorContext) { if (behaviorContext == null) { throw new NullPointerException("behaviorContext"); } ClientBehaviorRenderer renderer = getRenderer(behaviorContext.getFacesContext()); if (renderer != null) { // If a BehaviorRenderer is available for the specified behavior renderer type, this method delegates // to the BehaviorRenderer.getScript method. try { setCachedFacesContext(behaviorContext.getFacesContext()); return renderer.getScript(behaviorContext, this); } finally { setCachedFacesContext(null); } } // Otherwise, this method returns null. return null; } }
public class class_name { public String getScript(ClientBehaviorContext behaviorContext) { if (behaviorContext == null) { throw new NullPointerException("behaviorContext"); } ClientBehaviorRenderer renderer = getRenderer(behaviorContext.getFacesContext()); if (renderer != null) { // If a BehaviorRenderer is available for the specified behavior renderer type, this method delegates // to the BehaviorRenderer.getScript method. try { setCachedFacesContext(behaviorContext.getFacesContext()); // depends on control dependency: [try], data = [none] return renderer.getScript(behaviorContext, this); // depends on control dependency: [try], data = [none] } finally { setCachedFacesContext(null); } } // Otherwise, this method returns null. return null; } }
public class class_name { public static int[] validate2(int[] data, boolean allowSz1, String paramName){ if(data == null) { return null; } if(allowSz1){ Preconditions.checkArgument(data.length == 1 || data.length == 2, "Need either 1 or 2 %s values, got %s values: %s", paramName, data.length, data); } else { Preconditions.checkArgument(data.length == 2,"Need 2 %s values, got %s values: %s", paramName, data.length, data); } if(data.length == 1){ return new int[]{data[0], data[0]}; } else { return data; } } }
public class class_name { public static int[] validate2(int[] data, boolean allowSz1, String paramName){ if(data == null) { return null; // depends on control dependency: [if], data = [none] } if(allowSz1){ Preconditions.checkArgument(data.length == 1 || data.length == 2, "Need either 1 or 2 %s values, got %s values: %s", paramName, data.length, data); // depends on control dependency: [if], data = [none] } else { Preconditions.checkArgument(data.length == 2,"Need 2 %s values, got %s values: %s", paramName, data.length, data); // depends on control dependency: [if], data = [none] } if(data.length == 1){ return new int[]{data[0], data[0]}; // depends on control dependency: [if], data = [none] } else { return data; // depends on control dependency: [if], data = [none] } } }
public class class_name { public static double getRuntimeDoubleProperty(String property, String defaultValue) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getRuntimeDoubleProperty", new Object[] {property, defaultValue}); // Note that we parse the default value outside of the try / catch so that if we muck // up then we blow up. Customer settable properties however, we do not want to blow if they // screw up. double runtimeProp = Double.parseDouble(defaultValue); try { runtimeProp = Double.parseDouble(RuntimeInfo.getPropertyWithMsg(property, defaultValue)); } catch (NumberFormatException e) { FFDCFilter.processException(e, CLASS_NAME + ".getRuntimeDoubleProperty", CommsConstants.COMMSUTILS_GETRUNTIMEDOUBLE_01); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "NumberFormatException: ", e); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "getRuntimeDoubleProperty", ""+runtimeProp); return runtimeProp; } }
public class class_name { public static double getRuntimeDoubleProperty(String property, String defaultValue) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getRuntimeDoubleProperty", new Object[] {property, defaultValue}); // Note that we parse the default value outside of the try / catch so that if we muck // up then we blow up. Customer settable properties however, we do not want to blow if they // screw up. double runtimeProp = Double.parseDouble(defaultValue); try { runtimeProp = Double.parseDouble(RuntimeInfo.getPropertyWithMsg(property, defaultValue)); // depends on control dependency: [try], data = [none] } catch (NumberFormatException e) { FFDCFilter.processException(e, CLASS_NAME + ".getRuntimeDoubleProperty", CommsConstants.COMMSUTILS_GETRUNTIMEDOUBLE_01); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "NumberFormatException: ", e); } // depends on control dependency: [catch], data = [none] if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "getRuntimeDoubleProperty", ""+runtimeProp); return runtimeProp; } }
public class class_name { @Override public ContainerResponse filter(ContainerRequest cres, ContainerResponse response) { initLazily(servletRequest); String requestOrigin = cres.getHeaderValue("Origin"); if (requestOrigin != null) { // is this is a cors request (ajax request that targets a different domain than the one the page was loaded from) if (allowedOrigin != null && allowedOrigin.startsWith(requestOrigin)) { // no cors allowances make are applied if allowedOrigins == null // only return the origin the client informed response.getHttpHeaders().add("Access-Control-Allow-Origin", requestOrigin); response.getHttpHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization"); response.getHttpHeaders().add("Access-Control-Allow-Credentials", "true"); response.getHttpHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD"); response.getHttpHeaders().add("Access-Control-Max-Age", "1209600"); } } return response; } }
public class class_name { @Override public ContainerResponse filter(ContainerRequest cres, ContainerResponse response) { initLazily(servletRequest); String requestOrigin = cres.getHeaderValue("Origin"); if (requestOrigin != null) { // is this is a cors request (ajax request that targets a different domain than the one the page was loaded from) if (allowedOrigin != null && allowedOrigin.startsWith(requestOrigin)) { // no cors allowances make are applied if allowedOrigins == null // only return the origin the client informed response.getHttpHeaders().add("Access-Control-Allow-Origin", requestOrigin); // depends on control dependency: [if], data = [none] response.getHttpHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization"); // depends on control dependency: [if], data = [none] response.getHttpHeaders().add("Access-Control-Allow-Credentials", "true"); // depends on control dependency: [if], data = [none] response.getHttpHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD"); // depends on control dependency: [if], data = [none] response.getHttpHeaders().add("Access-Control-Max-Age", "1209600"); // depends on control dependency: [if], data = [none] } } return response; } }
public class class_name { public static Long convertVarNumberToLong(RLPElement rpe) { Long result=0L; if (rpe.getRawData()!=null) { if (rpe.getRawData().length==0) { result=0L; } else if (rpe.getRawData().length<2) { result=(long) EthereumUtil.convertToByte(rpe); } else if (rpe.getRawData().length<3) { result = (long) EthereumUtil.convertToShort(rpe); } else if (rpe.getRawData().length<5) { result=(long) EthereumUtil.convertToInt(rpe); } else if (rpe.getRawData().length<9) { result=EthereumUtil.convertToLong(rpe); } } return result; } }
public class class_name { public static Long convertVarNumberToLong(RLPElement rpe) { Long result=0L; if (rpe.getRawData()!=null) { if (rpe.getRawData().length==0) { result=0L; // depends on control dependency: [if], data = [none] } else if (rpe.getRawData().length<2) { result=(long) EthereumUtil.convertToByte(rpe); // depends on control dependency: [if], data = [none] } else if (rpe.getRawData().length<3) { result = (long) EthereumUtil.convertToShort(rpe); // depends on control dependency: [if], data = [none] } else if (rpe.getRawData().length<5) { result=(long) EthereumUtil.convertToInt(rpe); // depends on control dependency: [if], data = [none] } else if (rpe.getRawData().length<9) { result=EthereumUtil.convertToLong(rpe); // depends on control dependency: [if], data = [none] } } return result; } }