code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { public void config(final OServer oServer, final OServerConfigurationManager serverCfg, final ODocument jsonConfig) { server = oServer; serverConfig = serverCfg; if (jsonConfig.containsField("name")) { name = jsonConfig.field("name"); } if (jsonConfig.containsField("debug")) { debug = jsonConfig.field("debug"); } if (jsonConfig.containsField("enabled")) { enabled = jsonConfig.field("enabled"); } if (jsonConfig.containsField("caseSensitive")) { caseSensitive = jsonConfig.field("caseSensitive"); } } }
public class class_name { public void config(final OServer oServer, final OServerConfigurationManager serverCfg, final ODocument jsonConfig) { server = oServer; serverConfig = serverCfg; if (jsonConfig.containsField("name")) { name = jsonConfig.field("name"); // depends on control dependency: [if], data = [none] } if (jsonConfig.containsField("debug")) { debug = jsonConfig.field("debug"); // depends on control dependency: [if], data = [none] } if (jsonConfig.containsField("enabled")) { enabled = jsonConfig.field("enabled"); // depends on control dependency: [if], data = [none] } if (jsonConfig.containsField("caseSensitive")) { caseSensitive = jsonConfig.field("caseSensitive"); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static boolean check(Tile tile1, Tile tile2, Tile tile3) { //Typeが違う場合false if (tile1.getType() != tile2.getType() || tile2.getType() != tile3.getType()) { return false; } //字牌だった場合false if (tile1.getNumber() == 0 || tile2.getNumber() == 0 || tile3.getNumber() == 0) { return false; } //ソートする Tile s; if (tile1.getNumber() > tile2.getNumber()) { s = tile1; tile1 = tile2; tile2 = s; } if (tile1.getNumber() > tile3.getNumber()) { s = tile1; tile1 = tile3; tile3 = s; } if (tile2.getNumber() > tile3.getNumber()) { s = tile2; tile2 = tile3; tile3 = s; } //判定 return tile1.getNumber() + 1 == tile2.getNumber() && tile2.getNumber() + 1 == tile3.getNumber(); } }
public class class_name { public static boolean check(Tile tile1, Tile tile2, Tile tile3) { //Typeが違う場合false if (tile1.getType() != tile2.getType() || tile2.getType() != tile3.getType()) { return false; // depends on control dependency: [if], data = [none] } //字牌だった場合false if (tile1.getNumber() == 0 || tile2.getNumber() == 0 || tile3.getNumber() == 0) { return false; // depends on control dependency: [if], data = [none] } //ソートする Tile s; if (tile1.getNumber() > tile2.getNumber()) { s = tile1; // depends on control dependency: [if], data = [none] tile1 = tile2; // depends on control dependency: [if], data = [none] tile2 = s; // depends on control dependency: [if], data = [none] } if (tile1.getNumber() > tile3.getNumber()) { s = tile1; // depends on control dependency: [if], data = [none] tile1 = tile3; // depends on control dependency: [if], data = [none] tile3 = s; // depends on control dependency: [if], data = [none] } if (tile2.getNumber() > tile3.getNumber()) { s = tile2; // depends on control dependency: [if], data = [none] tile2 = tile3; // depends on control dependency: [if], data = [none] tile3 = s; // depends on control dependency: [if], data = [none] } //判定 return tile1.getNumber() + 1 == tile2.getNumber() && tile2.getNumber() + 1 == tile3.getNumber(); } }
public class class_name { protected List<ServletDefinition> initServlets( List<ServletDefinition> servletDefinitions) throws Exception { // Sort the list taking in account the load-on-startup attribute Collections.sort(servletDefinitions); // Sets the Jawr context at "bundle processing at build time" ThreadLocalJawrContext.setBundleProcessingAtBuildTime(true); List<ServletDefinition> jawrServletDefinitions = new ArrayList<ServletDefinition>(); for (Iterator<ServletDefinition> iterator = servletDefinitions .iterator(); iterator.hasNext();) { ServletDefinition servletDefinition = (ServletDefinition) iterator .next(); servletDefinition.initServlet(); if (servletDefinition.isJawrServletDefinition()) { jawrServletDefinitions.add(servletDefinition); } } return jawrServletDefinitions; } }
public class class_name { protected List<ServletDefinition> initServlets( List<ServletDefinition> servletDefinitions) throws Exception { // Sort the list taking in account the load-on-startup attribute Collections.sort(servletDefinitions); // Sets the Jawr context at "bundle processing at build time" ThreadLocalJawrContext.setBundleProcessingAtBuildTime(true); List<ServletDefinition> jawrServletDefinitions = new ArrayList<ServletDefinition>(); for (Iterator<ServletDefinition> iterator = servletDefinitions .iterator(); iterator.hasNext();) { ServletDefinition servletDefinition = (ServletDefinition) iterator .next(); servletDefinition.initServlet(); if (servletDefinition.isJawrServletDefinition()) { jawrServletDefinitions.add(servletDefinition); // depends on control dependency: [if], data = [none] } } return jawrServletDefinitions; } }
public class class_name { public V remove(K key) { writeLock.lock(); try { return cache.remove(key); } finally { writeLock.unlock(); } } }
public class class_name { public V remove(K key) { writeLock.lock(); try { return cache.remove(key); // depends on control dependency: [try], data = [none] } finally { writeLock.unlock(); } } }
public class class_name { public Key findKey(String name) { if (keys == null) { return null; } // search rows for (Key key : keys.kkrow) { if (key.name.equals(name)) { return key; } } // search columns for (Key key : keys.kkcol) { if (key.name.equals(name)) { return key; } } return null; } }
public class class_name { public Key findKey(String name) { if (keys == null) { return null; // depends on control dependency: [if], data = [none] } // search rows for (Key key : keys.kkrow) { if (key.name.equals(name)) { return key; // depends on control dependency: [if], data = [none] } } // search columns for (Key key : keys.kkcol) { if (key.name.equals(name)) { return key; // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { @Override public boolean registerReadAhead(InterChannelCallback cb, int timeout) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Read-ahead requested (timeout=" + timeout + ") " + getVC()); } if (-1 > timeout) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Invalid timeout used by caller."); } return false; } int state; int myState; // grab the read-ahead states in a sync block to avoid timing windows // with the callback kicking in at the same time synchronized (this.stateSyncObject) { state = getCallbackState(); myState = getReadState(); setCallbackState(CALLBACK_STATE_PENDING, null); } if (CALLBACK_STATE_IDLE != state) { // invalid state to start this read-ahead from if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Callback state is invalid: " + state); } return false; } if (READ_STATE_IDLE != myState) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Read for response state is invalid: " + myState); } return false; } // start the read now this.bReadAheadEnabled = true; int time = (-1 == timeout) ? getReadTimeout() : timeout; setAppReadCallback(cb); setupJITRead(getHttpConfig().getIncomingHdrBufferSize()); getTSC().getReadInterface().read(1, HttpOSCReadAhead.getRef(), true, time); return true; } }
public class class_name { @Override public boolean registerReadAhead(InterChannelCallback cb, int timeout) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Read-ahead requested (timeout=" + timeout + ") " + getVC()); // depends on control dependency: [if], data = [none] } if (-1 > timeout) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Invalid timeout used by caller."); // depends on control dependency: [if], data = [none] } return false; // depends on control dependency: [if], data = [none] } int state; int myState; // grab the read-ahead states in a sync block to avoid timing windows // with the callback kicking in at the same time synchronized (this.stateSyncObject) { state = getCallbackState(); myState = getReadState(); setCallbackState(CALLBACK_STATE_PENDING, null); } if (CALLBACK_STATE_IDLE != state) { // invalid state to start this read-ahead from if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Callback state is invalid: " + state); // depends on control dependency: [if], data = [none] } return false; // depends on control dependency: [if], data = [none] } if (READ_STATE_IDLE != myState) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Read for response state is invalid: " + myState); // depends on control dependency: [if], data = [none] } return false; // depends on control dependency: [if], data = [none] } // start the read now this.bReadAheadEnabled = true; int time = (-1 == timeout) ? getReadTimeout() : timeout; setAppReadCallback(cb); setupJITRead(getHttpConfig().getIncomingHdrBufferSize()); getTSC().getReadInterface().read(1, HttpOSCReadAhead.getRef(), true, time); return true; } }
public class class_name { private void parseLine(final String line, final TemporalDataModelIF<Long, Long> dataset) { String[] toks; if (line.contains("::")) { toks = line.split("::"); } else { toks = line.split("\t"); } // user long userId = Long.parseLong(toks[USER_TOK]); // item long itemId = Long.parseLong(toks[ITEM_TOK]); // timestamp long timestamp = Long.parseLong(toks[TIME_TOK]); // preference double preference = Double.parseDouble(toks[RATING_TOK]); ////// // update information ////// dataset.addPreference(userId, itemId, preference); dataset.addTimestamp(userId, itemId, timestamp); } }
public class class_name { private void parseLine(final String line, final TemporalDataModelIF<Long, Long> dataset) { String[] toks; if (line.contains("::")) { toks = line.split("::"); // depends on control dependency: [if], data = [none] } else { toks = line.split("\t"); // depends on control dependency: [if], data = [none] } // user long userId = Long.parseLong(toks[USER_TOK]); // item long itemId = Long.parseLong(toks[ITEM_TOK]); // timestamp long timestamp = Long.parseLong(toks[TIME_TOK]); // preference double preference = Double.parseDouble(toks[RATING_TOK]); ////// // update information ////// dataset.addPreference(userId, itemId, preference); dataset.addTimestamp(userId, itemId, timestamp); } }
public class class_name { public String getDialogCopyFolderModeString() { if (getDialogCopyFolderMode() == CmsResource.COPY_AS_NEW) { return COPYMODE_RESOURCE; } else if (getDialogCopyFolderMode() == CmsResource.COPY_AS_SIBLING) { return COPYMODE_SIBLING; } else { return COPYMODE_PRESERVE; } } }
public class class_name { public String getDialogCopyFolderModeString() { if (getDialogCopyFolderMode() == CmsResource.COPY_AS_NEW) { return COPYMODE_RESOURCE; // depends on control dependency: [if], data = [none] } else if (getDialogCopyFolderMode() == CmsResource.COPY_AS_SIBLING) { return COPYMODE_SIBLING; // depends on control dependency: [if], data = [none] } else { return COPYMODE_PRESERVE; // depends on control dependency: [if], data = [none] } } }
public class class_name { private static boolean durationIsValid(long seconds, int nanos) { if (seconds < DURATION_SECONDS_MIN || seconds > DURATION_SECONDS_MAX) { return false; } if (nanos < -999999999L || nanos >= NANOS_PER_SECOND) { return false; } if (seconds < 0 || nanos < 0) { if (seconds > 0 || nanos > 0) { return false; } } return true; } }
public class class_name { private static boolean durationIsValid(long seconds, int nanos) { if (seconds < DURATION_SECONDS_MIN || seconds > DURATION_SECONDS_MAX) { return false; // depends on control dependency: [if], data = [none] } if (nanos < -999999999L || nanos >= NANOS_PER_SECOND) { return false; // depends on control dependency: [if], data = [none] } if (seconds < 0 || nanos < 0) { if (seconds > 0 || nanos > 0) { return false; // depends on control dependency: [if], data = [none] } } return true; } }
public class class_name { public boolean matchRule(AuditEvent event, String ruleName, String expectedMessage, String expectedSeverity) { if (!ruleName.equals(RuleUtil.getName(event))) { return false; } // check message too, for those that have a specific one. // like GenericIllegalRegexp and Regexp if (expectedMessage != null) { // event.getMessage() uses java.text.MessageFormat in its implementation. // Read MessageFormat Javadoc about single quote: // http://java.sun.com/j2se/1.4.2/docs/api/java/text/MessageFormat.html String msgWithoutSingleQuote = StringUtils.replace(expectedMessage, "'", ""); return expectedMessage.equals(event.getMessage()) || msgWithoutSingleQuote.equals(event.getMessage()); } // Check the severity. This helps to distinguish between // different configurations for the same rule, where each // configuration has a different severity, like JavadocMetod. // See also http://jira.codehaus.org/browse/MCHECKSTYLE-41 if (expectedSeverity != null) { return expectedSeverity.equals(event.getSeverityLevel().getName()); } return true; } }
public class class_name { public boolean matchRule(AuditEvent event, String ruleName, String expectedMessage, String expectedSeverity) { if (!ruleName.equals(RuleUtil.getName(event))) { return false; // depends on control dependency: [if], data = [none] } // check message too, for those that have a specific one. // like GenericIllegalRegexp and Regexp if (expectedMessage != null) { // event.getMessage() uses java.text.MessageFormat in its implementation. // Read MessageFormat Javadoc about single quote: // http://java.sun.com/j2se/1.4.2/docs/api/java/text/MessageFormat.html String msgWithoutSingleQuote = StringUtils.replace(expectedMessage, "'", ""); return expectedMessage.equals(event.getMessage()) || msgWithoutSingleQuote.equals(event.getMessage()); // depends on control dependency: [if], data = [none] } // Check the severity. This helps to distinguish between // different configurations for the same rule, where each // configuration has a different severity, like JavadocMetod. // See also http://jira.codehaus.org/browse/MCHECKSTYLE-41 if (expectedSeverity != null) { return expectedSeverity.equals(event.getSeverityLevel().getName()); // depends on control dependency: [if], data = [none] } return true; } }
public class class_name { public static boolean contains(Iterator<?> iterator, @NullableDecl Object element) { if (element == null) { while (iterator.hasNext()) { if (iterator.next() == null) { return true; } } } else { while (iterator.hasNext()) { if (element.equals(iterator.next())) { return true; } } } return false; } }
public class class_name { public static boolean contains(Iterator<?> iterator, @NullableDecl Object element) { if (element == null) { while (iterator.hasNext()) { if (iterator.next() == null) { return true; // depends on control dependency: [if], data = [none] } } } else { while (iterator.hasNext()) { if (element.equals(iterator.next())) { return true; // depends on control dependency: [if], data = [none] } } } return false; } }
public class class_name { public static DateTime parse(String dateStr) { if (null == dateStr) { return null; } // 去掉两边空格并去掉中文日期中的“日”,以规范长度 dateStr = dateStr.trim().replace("日", ""); int length = dateStr.length(); if (Validator.isNumber(dateStr)) { // 纯数字形式 if (length == DatePattern.PURE_DATETIME_PATTERN.length()) { return parse(dateStr, DatePattern.PURE_DATETIME_FORMAT); } else if (length == DatePattern.PURE_DATETIME_MS_PATTERN.length()) { return parse(dateStr, DatePattern.PURE_DATETIME_MS_FORMAT); } else if (length == DatePattern.PURE_DATE_PATTERN.length()) { return parse(dateStr, DatePattern.PURE_DATE_FORMAT); } else if (length == DatePattern.PURE_TIME_PATTERN.length()) { return parse(dateStr, DatePattern.PURE_TIME_FORMAT); } } if (length == DatePattern.NORM_DATETIME_PATTERN.length() || length == DatePattern.NORM_DATETIME_PATTERN.length() + 1) { if (dateStr.contains("T")) { // UTC时间格式:类似2018-09-13T05:34:31 return parseUTC(dateStr); } return parseDateTime(dateStr); } else if (length == DatePattern.NORM_DATE_PATTERN.length()) { return parseDate(dateStr); } else if (length == DatePattern.NORM_TIME_PATTERN.length() || length == DatePattern.NORM_TIME_PATTERN.length() + 1) { return parseTimeToday(dateStr); } else if (length == DatePattern.NORM_DATETIME_MINUTE_PATTERN.length() || length == DatePattern.NORM_DATETIME_MINUTE_PATTERN.length() + 1) { return parse(normalize(dateStr), DatePattern.NORM_DATETIME_MINUTE_FORMAT); } else if (length >= DatePattern.NORM_DATETIME_MS_PATTERN.length() - 2) { return parse(normalize(dateStr), DatePattern.NORM_DATETIME_MS_FORMAT); } // 没有更多匹配的时间格式 throw new DateException("No format fit for date String [{}] !", dateStr); } }
public class class_name { public static DateTime parse(String dateStr) { if (null == dateStr) { return null; // depends on control dependency: [if], data = [none] } // 去掉两边空格并去掉中文日期中的“日”,以规范长度 dateStr = dateStr.trim().replace("日", ""); int length = dateStr.length(); if (Validator.isNumber(dateStr)) { // 纯数字形式 if (length == DatePattern.PURE_DATETIME_PATTERN.length()) { return parse(dateStr, DatePattern.PURE_DATETIME_FORMAT); // depends on control dependency: [if], data = [none] } else if (length == DatePattern.PURE_DATETIME_MS_PATTERN.length()) { return parse(dateStr, DatePattern.PURE_DATETIME_MS_FORMAT); // depends on control dependency: [if], data = [none] } else if (length == DatePattern.PURE_DATE_PATTERN.length()) { return parse(dateStr, DatePattern.PURE_DATE_FORMAT); // depends on control dependency: [if], data = [none] } else if (length == DatePattern.PURE_TIME_PATTERN.length()) { return parse(dateStr, DatePattern.PURE_TIME_FORMAT); // depends on control dependency: [if], data = [none] } } if (length == DatePattern.NORM_DATETIME_PATTERN.length() || length == DatePattern.NORM_DATETIME_PATTERN.length() + 1) { if (dateStr.contains("T")) { // UTC时间格式:类似2018-09-13T05:34:31 return parseUTC(dateStr); // depends on control dependency: [if], data = [none] } return parseDateTime(dateStr); // depends on control dependency: [if], data = [none] } else if (length == DatePattern.NORM_DATE_PATTERN.length()) { return parseDate(dateStr); // depends on control dependency: [if], data = [none] } else if (length == DatePattern.NORM_TIME_PATTERN.length() || length == DatePattern.NORM_TIME_PATTERN.length() + 1) { return parseTimeToday(dateStr); // depends on control dependency: [if], data = [none] } else if (length == DatePattern.NORM_DATETIME_MINUTE_PATTERN.length() || length == DatePattern.NORM_DATETIME_MINUTE_PATTERN.length() + 1) { return parse(normalize(dateStr), DatePattern.NORM_DATETIME_MINUTE_FORMAT); // depends on control dependency: [if], data = [none] } else if (length >= DatePattern.NORM_DATETIME_MS_PATTERN.length() - 2) { return parse(normalize(dateStr), DatePattern.NORM_DATETIME_MS_FORMAT); // depends on control dependency: [if], data = [none] } // 没有更多匹配的时间格式 throw new DateException("No format fit for date String [{}] !", dateStr); } }
public class class_name { public static String join(String start, String linePrefix, Collection<?> lines) { if (lines.isEmpty()) { return ""; } StringBuilder out = new StringBuilder(start); for (Object line : lines) { out.append(linePrefix).append(line).append("\n"); } return out.substring(0, out.length() - 1); //lose last EOL } }
public class class_name { public static String join(String start, String linePrefix, Collection<?> lines) { if (lines.isEmpty()) { return ""; // depends on control dependency: [if], data = [none] } StringBuilder out = new StringBuilder(start); for (Object line : lines) { out.append(linePrefix).append(line).append("\n"); // depends on control dependency: [for], data = [line] } return out.substring(0, out.length() - 1); //lose last EOL } }
public class class_name { @When("^I query the database with '(.+?)'$") public void selectData(String query) throws Exception { Statement myStatement = null; //postgres table List<String> sqlTable = new ArrayList<String>(); List<String> sqlTableAux = new ArrayList<String>(); Connection myConnection = this.commonspec.getConnection(); java.sql.ResultSet rs = null; try { myStatement = myConnection.createStatement(); rs = myStatement.executeQuery(query); //column names ResultSetMetaData resultSetMetaData = rs.getMetaData(); int count = resultSetMetaData.getColumnCount(); for (int i = 1; i <= count; i++) { sqlTable.add(resultSetMetaData.getColumnName(i).toString()); } //takes column names and column count while (rs.next()) { for (int i = 1; i <= count; i++) { //aux list without column names sqlTableAux.add(rs.getObject(i).toString()); } } sqlTable.addAll(sqlTableAux); //sends raws to environment variable for (int i = 0; i < sqlTable.size(); i++) { ThreadProperty.set("queryresponse" + i, sqlTable.get(i)); } ThreadProperty.remove("queryresponse" + sqlTable.size()); rs.close(); myStatement.close(); } catch (Exception e) { e.printStackTrace(); Assertions.assertThat(rs).as("There are no response from SELECT").isNotNull(); } } }
public class class_name { @When("^I query the database with '(.+?)'$") public void selectData(String query) throws Exception { Statement myStatement = null; //postgres table List<String> sqlTable = new ArrayList<String>(); List<String> sqlTableAux = new ArrayList<String>(); Connection myConnection = this.commonspec.getConnection(); java.sql.ResultSet rs = null; try { myStatement = myConnection.createStatement(); rs = myStatement.executeQuery(query); //column names ResultSetMetaData resultSetMetaData = rs.getMetaData(); int count = resultSetMetaData.getColumnCount(); for (int i = 1; i <= count; i++) { sqlTable.add(resultSetMetaData.getColumnName(i).toString()); // depends on control dependency: [for], data = [i] } //takes column names and column count while (rs.next()) { for (int i = 1; i <= count; i++) { //aux list without column names sqlTableAux.add(rs.getObject(i).toString()); // depends on control dependency: [for], data = [i] } } sqlTable.addAll(sqlTableAux); //sends raws to environment variable for (int i = 0; i < sqlTable.size(); i++) { ThreadProperty.set("queryresponse" + i, sqlTable.get(i)); // depends on control dependency: [for], data = [i] } ThreadProperty.remove("queryresponse" + sqlTable.size()); rs.close(); myStatement.close(); } catch (Exception e) { e.printStackTrace(); Assertions.assertThat(rs).as("There are no response from SELECT").isNotNull(); } } }
public class class_name { @Override public boolean launch(Activity context, Bundle data) { if(entityLoaderUtils != null) { entityLoaderUtils.initEntityLoader(); } Class<?>[] activityClasses = getActivityClasses(); Class<?> activityClass = null; for (Class<?> cls : activityClasses) { if(appUtils.isActivityAvailable(context, cls)) { activityClass = cls; break; } } if(activityClass != null) { Intent intent = newIntent(context, activityClass); intent.putExtras(data); handleIntent(context, intent, data); context.startActivity(intent); return true; } return false; } }
public class class_name { @Override public boolean launch(Activity context, Bundle data) { if(entityLoaderUtils != null) { entityLoaderUtils.initEntityLoader(); // depends on control dependency: [if], data = [none] } Class<?>[] activityClasses = getActivityClasses(); Class<?> activityClass = null; for (Class<?> cls : activityClasses) { if(appUtils.isActivityAvailable(context, cls)) { activityClass = cls; // depends on control dependency: [if], data = [none] break; } } if(activityClass != null) { Intent intent = newIntent(context, activityClass); intent.putExtras(data); // depends on control dependency: [if], data = [none] handleIntent(context, intent, data); // depends on control dependency: [if], data = [none] context.startActivity(intent); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } return false; } }
public class class_name { public static List<Dashboard> findSharedDashboards(EntityManager em, PrincipalUser owner, Integer limit, String version) { requireArgument(em != null, "Entity manager can not be null."); TypedQuery<Dashboard> query; if(owner == null){ if (version==null) { query = em.createNamedQuery("Dashboard.getSharedDashboards", Dashboard.class); } else { query = em.createNamedQuery("Dashboard.getSharedDashboardsByVersion", Dashboard.class); query.setParameter("version",version); } } else { if(version==null) { query = em.createNamedQuery("Dashboard.getSharedDashboardsByOwner", Dashboard.class); query.setParameter("owner", owner); } else { query = em.createNamedQuery("Dashboard.getSharedDashboardsByOwnerAndByVersion", Dashboard.class); query.setParameter("owner", owner); query.setParameter("version",version); } } query.setHint("javax.persistence.cache.storeMode", "REFRESH"); if(limit!= null){ query.setMaxResults(limit); } try { return query.getResultList(); } catch (NoResultException ex) { return new ArrayList<>(0); } } }
public class class_name { public static List<Dashboard> findSharedDashboards(EntityManager em, PrincipalUser owner, Integer limit, String version) { requireArgument(em != null, "Entity manager can not be null."); TypedQuery<Dashboard> query; if(owner == null){ if (version==null) { query = em.createNamedQuery("Dashboard.getSharedDashboards", Dashboard.class); // depends on control dependency: [if], data = [none] } else { query = em.createNamedQuery("Dashboard.getSharedDashboardsByVersion", Dashboard.class); // depends on control dependency: [if], data = [none] query.setParameter("version",version); // depends on control dependency: [if], data = [none] } } else { if(version==null) { query = em.createNamedQuery("Dashboard.getSharedDashboardsByOwner", Dashboard.class); // depends on control dependency: [if], data = [none] query.setParameter("owner", owner); // depends on control dependency: [if], data = [none] } else { query = em.createNamedQuery("Dashboard.getSharedDashboardsByOwnerAndByVersion", Dashboard.class); // depends on control dependency: [if], data = [none] query.setParameter("owner", owner); // depends on control dependency: [if], data = [none] query.setParameter("version",version); // depends on control dependency: [if], data = [none] } } query.setHint("javax.persistence.cache.storeMode", "REFRESH"); if(limit!= null){ query.setMaxResults(limit); // depends on control dependency: [if], data = [(limit] } try { return query.getResultList(); // depends on control dependency: [try], data = [none] } catch (NoResultException ex) { return new ArrayList<>(0); } // depends on control dependency: [catch], data = [none] } }
public class class_name { protected void addWebApp(DeployedModule dm) throws WebAppNotLoadedException { try { String virtualHost = dm.getVirtualHostName(); if ((virtualHost == null) || (virtualHost.equals(""))) virtualHost = DEFAULT_HOST; VirtualHost vHost = getVirtualHost(virtualHost); if (vHost == null) { logger.logp(Level.INFO, CLASS_NAME, "addWebApp", "host.has.not.been.defined", new String[] { virtualHost }); throw new WebAppNotLoadedException("Virtual Host " + virtualHost + " not found"); } //need to parse the ibm-web-ext before mapping the context root com.ibm.wsspi.adaptable.module.Container mc = dm.getWebApp().getModuleContainer(); WebExt ext = null; if (mc != null) { try { ext = mc.adapt(WebExt.class); } catch (UnableToAdaptException e) { if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE)) { logger.logp(Level.FINE, CLASS_NAME, "commonInitializationFinally", "Unable to parse the WebExt file", e); } ext = null; } } if (ext != null) { dm.getWebAppConfig().setInitializeWebExtProps(ext); } //done parsing the ibm-web-ext file vHost.addWebApplication(dm, extensionFactories); } catch (WebAppNotLoadedException wahnf) { com.ibm.ws.ffdc.FFDCFilter.processException(wahnf, "com.ibm.ws.webcontainer.Webcontainer", "732", this); throw wahnf; } catch (Throwable th) { com.ibm.wsspi.webcontainer.util.FFDCWrapper.processException(th, CLASS_NAME, "736", this); throw new WebAppNotLoadedException(th.getMessage(), th); } } }
public class class_name { protected void addWebApp(DeployedModule dm) throws WebAppNotLoadedException { try { String virtualHost = dm.getVirtualHostName(); if ((virtualHost == null) || (virtualHost.equals(""))) virtualHost = DEFAULT_HOST; VirtualHost vHost = getVirtualHost(virtualHost); if (vHost == null) { logger.logp(Level.INFO, CLASS_NAME, "addWebApp", "host.has.not.been.defined", new String[] { virtualHost }); throw new WebAppNotLoadedException("Virtual Host " + virtualHost + " not found"); } //need to parse the ibm-web-ext before mapping the context root com.ibm.wsspi.adaptable.module.Container mc = dm.getWebApp().getModuleContainer(); WebExt ext = null; if (mc != null) { try { ext = mc.adapt(WebExt.class); } catch (UnableToAdaptException e) { if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE)) { logger.logp(Level.FINE, CLASS_NAME, "commonInitializationFinally", "Unable to parse the WebExt file", e); // depends on control dependency: [if], data = [none] } ext = null; } } if (ext != null) { dm.getWebAppConfig().setInitializeWebExtProps(ext); } //done parsing the ibm-web-ext file vHost.addWebApplication(dm, extensionFactories); } catch (WebAppNotLoadedException wahnf) { com.ibm.ws.ffdc.FFDCFilter.processException(wahnf, "com.ibm.ws.webcontainer.Webcontainer", "732", this); throw wahnf; } catch (Throwable th) { com.ibm.wsspi.webcontainer.util.FFDCWrapper.processException(th, CLASS_NAME, "736", this); throw new WebAppNotLoadedException(th.getMessage(), th); } } }
public class class_name { public Vector getConnectedSocketDetails() { Vector details = new Vector(socketList.size()); for (Enumeration enumeration = socketList.elements(); enumeration.hasMoreElements(); ) { Socket socket = (Socket) enumeration.nextElement(); details.add( new SocketDetail(socket, (SocketNode13) socketMap.get(socket))); } return details; } }
public class class_name { public Vector getConnectedSocketDetails() { Vector details = new Vector(socketList.size()); for (Enumeration enumeration = socketList.elements(); enumeration.hasMoreElements(); ) { Socket socket = (Socket) enumeration.nextElement(); details.add( new SocketDetail(socket, (SocketNode13) socketMap.get(socket))); // depends on control dependency: [for], data = [none] } return details; } }
public class class_name { public void fakeDragBy(float yOffset) { if (!mFakeDragging) { throw new IllegalStateException("No fake drag in progress. Call beginFakeDrag first."); } mLastMotionY += yOffset; float oldScrollY = getScrollY(); float scrollY = oldScrollY - yOffset; final int height = getClientHeight(); float topBound = height * mFirstOffset; float bottomBound = height * mLastOffset; final ItemInfo firstItem = mItems.get(0); final ItemInfo lastItem = mItems.get(mItems.size() - 1); if (firstItem.position != 0) { topBound = firstItem.offset * height; } if (lastItem.position != mAdapter.getCount() - 1) { bottomBound = lastItem.offset * height; } if (scrollY < topBound) { scrollY = topBound; } else if (scrollY > bottomBound) { scrollY = bottomBound; } // Don't lose the rounded component mLastMotionY += scrollY - (int) scrollY; scrollTo(getScrollX(), (int) scrollY); pageScrolled((int) scrollY); // Synthesize an event for the VelocityTracker. final long time = SystemClock.uptimeMillis(); final MotionEvent ev = MotionEvent.obtain(mFakeDragBeginTime, time, MotionEvent.ACTION_MOVE, 0, mLastMotionY, 0); mVelocityTracker.addMovement(ev); ev.recycle(); } }
public class class_name { public void fakeDragBy(float yOffset) { if (!mFakeDragging) { throw new IllegalStateException("No fake drag in progress. Call beginFakeDrag first."); } mLastMotionY += yOffset; float oldScrollY = getScrollY(); float scrollY = oldScrollY - yOffset; final int height = getClientHeight(); float topBound = height * mFirstOffset; float bottomBound = height * mLastOffset; final ItemInfo firstItem = mItems.get(0); final ItemInfo lastItem = mItems.get(mItems.size() - 1); if (firstItem.position != 0) { topBound = firstItem.offset * height; // depends on control dependency: [if], data = [none] } if (lastItem.position != mAdapter.getCount() - 1) { bottomBound = lastItem.offset * height; // depends on control dependency: [if], data = [none] } if (scrollY < topBound) { scrollY = topBound; // depends on control dependency: [if], data = [none] } else if (scrollY > bottomBound) { scrollY = bottomBound; // depends on control dependency: [if], data = [none] } // Don't lose the rounded component mLastMotionY += scrollY - (int) scrollY; scrollTo(getScrollX(), (int) scrollY); pageScrolled((int) scrollY); // Synthesize an event for the VelocityTracker. final long time = SystemClock.uptimeMillis(); final MotionEvent ev = MotionEvent.obtain(mFakeDragBeginTime, time, MotionEvent.ACTION_MOVE, 0, mLastMotionY, 0); mVelocityTracker.addMovement(ev); ev.recycle(); } }
public class class_name { public void setAnchors(int[] anchors) { super.anchors = new ArrayList<Anchor>(); if (anchors != null) { for (int i = 0; i < anchors.length; i++) { if (anchors[i] >= 0) { addAnchor(i, anchors[i]); } } } } }
public class class_name { public void setAnchors(int[] anchors) { super.anchors = new ArrayList<Anchor>(); if (anchors != null) { for (int i = 0; i < anchors.length; i++) { if (anchors[i] >= 0) { addAnchor(i, anchors[i]); // depends on control dependency: [if], data = [none] } } } } }
public class class_name { protected boolean hasTimeStampHeader() { String originTime = request.getHeader(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS); boolean result = false; if(originTime != null) { try { // TODO: remove the originTime field from request header, // because coordinator should not accept the request origin time // from the client.. In this commit, we only changed // "this.parsedRequestOriginTimeInMs" from // "Long.parseLong(originTime)" to current system time, // The reason that we did not remove the field from request // header right now, is because this commit is a quick fix for // internal performance test to be available as soon as // possible. this.parsedRequestOriginTimeInMs = System.currentTimeMillis(); if(this.parsedRequestOriginTimeInMs < 0) { RestErrorHandler.writeErrorResponse(messageEvent, HttpResponseStatus.BAD_REQUEST, "Origin time cannot be negative "); } else { result = true; } } catch(NumberFormatException nfe) { logger.error("Exception when validating request. Incorrect origin time parameter. Cannot parse this to long: " + originTime, nfe); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Incorrect origin time parameter. Cannot parse this to long: " + originTime); } } else { logger.error("Error when validating request. Missing origin time parameter."); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Missing origin time parameter."); } return result; } }
public class class_name { protected boolean hasTimeStampHeader() { String originTime = request.getHeader(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS); boolean result = false; if(originTime != null) { try { // TODO: remove the originTime field from request header, // because coordinator should not accept the request origin time // from the client.. In this commit, we only changed // "this.parsedRequestOriginTimeInMs" from // "Long.parseLong(originTime)" to current system time, // The reason that we did not remove the field from request // header right now, is because this commit is a quick fix for // internal performance test to be available as soon as // possible. this.parsedRequestOriginTimeInMs = System.currentTimeMillis(); // depends on control dependency: [try], data = [none] if(this.parsedRequestOriginTimeInMs < 0) { RestErrorHandler.writeErrorResponse(messageEvent, HttpResponseStatus.BAD_REQUEST, "Origin time cannot be negative "); // depends on control dependency: [if], data = [none] } else { result = true; // depends on control dependency: [if], data = [none] } } catch(NumberFormatException nfe) { logger.error("Exception when validating request. Incorrect origin time parameter. Cannot parse this to long: " + originTime, nfe); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Incorrect origin time parameter. Cannot parse this to long: " + originTime); } // depends on control dependency: [catch], data = [none] } else { logger.error("Error when validating request. Missing origin time parameter."); // depends on control dependency: [if], data = [none] RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Missing origin time parameter."); // depends on control dependency: [if], data = [none] } return result; } }
public class class_name { public boolean removeValue(Object value) { try { boolean result = false; if (isCluster(groupName)) { result = getBinaryJedisClusterCommands(groupName).lrem(keyBytes, 0, valueSerialize(value)) >= 1; } else { result = getBinaryJedisCommands(groupName).lrem(keyBytes, 0, valueSerialize(value)) >= 1; } return result; } finally { getJedisProvider(groupName).release(); } } }
public class class_name { public boolean removeValue(Object value) { try { boolean result = false; if (isCluster(groupName)) { result = getBinaryJedisClusterCommands(groupName).lrem(keyBytes, 0, valueSerialize(value)) >= 1; // depends on control dependency: [if], data = [none] } else { result = getBinaryJedisCommands(groupName).lrem(keyBytes, 0, valueSerialize(value)) >= 1; // depends on control dependency: [if], data = [none] } return result; // depends on control dependency: [try], data = [none] } finally { getJedisProvider(groupName).release(); } } }
public class class_name { private RegistrationEntryList getRegistrationEntryList(String subject, RelatedFinder finder) { RegistrationEntryList registrationEntryList; RegistrationKey key = new RegistrationKey(subject, finder.getFinderClassName()); if (logger.isDebugEnabled()) { logger.debug("**************Adding application notification registration with key: " + key.toString()); } registrationEntryList = mithraApplicationNotificationSubscriber.get(key); if (registrationEntryList == null) { registrationEntryList = new RegistrationEntryList(); mithraApplicationNotificationSubscriber.put(key, registrationEntryList); } return registrationEntryList; } }
public class class_name { private RegistrationEntryList getRegistrationEntryList(String subject, RelatedFinder finder) { RegistrationEntryList registrationEntryList; RegistrationKey key = new RegistrationKey(subject, finder.getFinderClassName()); if (logger.isDebugEnabled()) { logger.debug("**************Adding application notification registration with key: " + key.toString()); // depends on control dependency: [if], data = [none] } registrationEntryList = mithraApplicationNotificationSubscriber.get(key); if (registrationEntryList == null) { registrationEntryList = new RegistrationEntryList(); // depends on control dependency: [if], data = [none] mithraApplicationNotificationSubscriber.put(key, registrationEntryList); // depends on control dependency: [if], data = [none] } return registrationEntryList; } }
public class class_name { static String choppedStatementNoLineChange(String statement) { // \r\n needs to be the first element in the pipe. statement = statement.replaceAll("\\r\\n|\\r|\\n", " "); if (statement.length() <= MAX_OUTPUT_STMT_LENGTH) { return statement; } return statement.substring(0, MAX_OUTPUT_STMT_LENGTH) + "...... (" + (statement.length() - MAX_OUTPUT_STMT_LENGTH) + " characters omitted)"; } }
public class class_name { static String choppedStatementNoLineChange(String statement) { // \r\n needs to be the first element in the pipe. statement = statement.replaceAll("\\r\\n|\\r|\\n", " "); if (statement.length() <= MAX_OUTPUT_STMT_LENGTH) { return statement; // depends on control dependency: [if], data = [none] } return statement.substring(0, MAX_OUTPUT_STMT_LENGTH) + "...... (" + (statement.length() - MAX_OUTPUT_STMT_LENGTH) + " characters omitted)"; } }
public class class_name { public static void setupMenuButton(ButtonBase button, RadialMenuParams params, Node graphic, String tooltip, boolean addStyle) { button.minWidthProperty().bind(params.buttonSizeProperty()); button.minHeightProperty().bind(params.buttonSizeProperty()); button.prefWidthProperty().bind(params.buttonSizeProperty()); button.prefHeightProperty().bind(params.buttonSizeProperty()); button.maxWidthProperty().bind(params.buttonSizeProperty()); button.maxHeightProperty().bind(params.buttonSizeProperty()); if (addStyle) { button.getStylesheets().addAll(params.getStyleSheets()); } button.setId(params.getStyleId()); button.getStyleClass().addAll(params.getStyleClasses()); button.setGraphic(graphic); button.setTooltip(new Tooltip(tooltip)); } }
public class class_name { public static void setupMenuButton(ButtonBase button, RadialMenuParams params, Node graphic, String tooltip, boolean addStyle) { button.minWidthProperty().bind(params.buttonSizeProperty()); button.minHeightProperty().bind(params.buttonSizeProperty()); button.prefWidthProperty().bind(params.buttonSizeProperty()); button.prefHeightProperty().bind(params.buttonSizeProperty()); button.maxWidthProperty().bind(params.buttonSizeProperty()); button.maxHeightProperty().bind(params.buttonSizeProperty()); if (addStyle) { button.getStylesheets().addAll(params.getStyleSheets()); // depends on control dependency: [if], data = [none] } button.setId(params.getStyleId()); button.getStyleClass().addAll(params.getStyleClasses()); button.setGraphic(graphic); button.setTooltip(new Tooltip(tooltip)); } }
public class class_name { public String getPrincipal() { String principal = target.getPrincipal(); if (StringUtils.hasText(principal)) { return principal; } else { return defaultUser; } } }
public class class_name { public String getPrincipal() { String principal = target.getPrincipal(); if (StringUtils.hasText(principal)) { return principal; // depends on control dependency: [if], data = [none] } else { return defaultUser; // depends on control dependency: [if], data = [none] } } }
public class class_name { private void onFlushBatch(Map<String, BulkWriteOperation> bulkWriteOperationMap) { if (!bulkWriteOperationMap.isEmpty()) { for (BulkWriteOperation builder : bulkWriteOperationMap.values()) { try { builder.execute(getWriteConcern()); } catch (BulkWriteException bwex) { log.error("Batch insertion is not performed due to error in write command. Caused By: ", bwex); throw new KunderaException( "Batch insertion is not performed due to error in write command. Caused By: ", bwex); } catch (MongoException mex) { log.error("Batch insertion is not performed. Caused By: ", mex); throw new KunderaException("Batch insertion is not performed. Caused By: ", mex); } } } } }
public class class_name { private void onFlushBatch(Map<String, BulkWriteOperation> bulkWriteOperationMap) { if (!bulkWriteOperationMap.isEmpty()) { for (BulkWriteOperation builder : bulkWriteOperationMap.values()) { try { builder.execute(getWriteConcern()); // depends on control dependency: [try], data = [none] } catch (BulkWriteException bwex) { log.error("Batch insertion is not performed due to error in write command. Caused By: ", bwex); throw new KunderaException( "Batch insertion is not performed due to error in write command. Caused By: ", bwex); } // depends on control dependency: [catch], data = [none] catch (MongoException mex) { log.error("Batch insertion is not performed. Caused By: ", mex); throw new KunderaException("Batch insertion is not performed. Caused By: ", mex); } // depends on control dependency: [catch], data = [none] } } } }
public class class_name { public void createCluster() { AmazonElasticMapReduce emr = sparkEmrClientBuilder.build(); Optional<ClusterSummary> csr = findClusterWithName(emr, sparkClusterName); if (csr.isPresent()) { String msg = String.format("A cluster with name %s and id %s is already deployed", sparkClusterName, csr.get().getId()); log.error(msg); throw new IllegalStateException(msg); } else { RunJobFlowResult res = emr.runJobFlow(sparkRunJobFlowRequest); String msg = String.format("Your cluster is launched with name %s and id %s.", sparkClusterName, res.getJobFlowId()); log.info(msg); } } }
public class class_name { public void createCluster() { AmazonElasticMapReduce emr = sparkEmrClientBuilder.build(); Optional<ClusterSummary> csr = findClusterWithName(emr, sparkClusterName); if (csr.isPresent()) { String msg = String.format("A cluster with name %s and id %s is already deployed", sparkClusterName, csr.get().getId()); log.error(msg); // depends on control dependency: [if], data = [none] throw new IllegalStateException(msg); } else { RunJobFlowResult res = emr.runJobFlow(sparkRunJobFlowRequest); String msg = String.format("Your cluster is launched with name %s and id %s.", sparkClusterName, res.getJobFlowId()); log.info(msg); // depends on control dependency: [if], data = [none] } } }
public class class_name { public JarClassLoader addJar(File jarFileOrDir) { if(isJarFile(jarFileOrDir)) { return addURL(jarFileOrDir); } final List<File> jars = loopJar(jarFileOrDir); for (File jar : jars) { addURL(jar); } return this; } }
public class class_name { public JarClassLoader addJar(File jarFileOrDir) { if(isJarFile(jarFileOrDir)) { return addURL(jarFileOrDir); // depends on control dependency: [if], data = [none] } final List<File> jars = loopJar(jarFileOrDir); for (File jar : jars) { addURL(jar); // depends on control dependency: [for], data = [jar] } return this; } }
public class class_name { public void addEntryState(PortletRequest req, String entryId, NotificationState state) { if (usernameFinder.isAuthenticated(req)) { final String username = usernameFinder.findUsername(req); String idStr = entryId.replaceAll(ID_PREFIX, ""); // remove the prefix JpaEntry jpaEntry = notificationDao.getEntry(Long.parseLong(idStr)); if (jpaEntry != null) { JpaEvent event = new JpaEvent(); event.setEntry(jpaEntry); event.setState(state); event.setTimestamp(new Timestamp(new Date().getTime())); event.setUsername(username); notificationDao.createOrUpdateEvent(event); } else { throw new IllegalArgumentException("JpaEntry not found"); } } } }
public class class_name { public void addEntryState(PortletRequest req, String entryId, NotificationState state) { if (usernameFinder.isAuthenticated(req)) { final String username = usernameFinder.findUsername(req); String idStr = entryId.replaceAll(ID_PREFIX, ""); // remove the prefix JpaEntry jpaEntry = notificationDao.getEntry(Long.parseLong(idStr)); if (jpaEntry != null) { JpaEvent event = new JpaEvent(); event.setEntry(jpaEntry); // depends on control dependency: [if], data = [(jpaEntry] event.setState(state); // depends on control dependency: [if], data = [none] event.setTimestamp(new Timestamp(new Date().getTime())); // depends on control dependency: [if], data = [none] event.setUsername(username); // depends on control dependency: [if], data = [none] notificationDao.createOrUpdateEvent(event); // depends on control dependency: [if], data = [none] } else { throw new IllegalArgumentException("JpaEntry not found"); } } } }
public class class_name { private static String encodeFileNameToContentDisposition(HttpServletRequest httpRequest, String fileName) { assert fileName != null; final String userAgent = httpRequest.getHeader("user-agent"); if (userAgent != null && userAgent.contains("MSIE")) { return "attachment;filename=" + fileName; } return encodeFileNameToStandardContentDisposition(fileName); } }
public class class_name { private static String encodeFileNameToContentDisposition(HttpServletRequest httpRequest, String fileName) { assert fileName != null; final String userAgent = httpRequest.getHeader("user-agent"); if (userAgent != null && userAgent.contains("MSIE")) { return "attachment;filename=" + fileName; // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none] } return encodeFileNameToStandardContentDisposition(fileName); } }
public class class_name { public static int getAtomCount(IChemModel chemModel) { int count = 0; ICrystal crystal = chemModel.getCrystal(); if (crystal != null) { count += crystal.getAtomCount(); } IAtomContainerSet moleculeSet = chemModel.getMoleculeSet(); if (moleculeSet != null) { count += MoleculeSetManipulator.getAtomCount(moleculeSet); } IReactionSet reactionSet = chemModel.getReactionSet(); if (reactionSet != null) { count += ReactionSetManipulator.getAtomCount(reactionSet); } return count; } }
public class class_name { public static int getAtomCount(IChemModel chemModel) { int count = 0; ICrystal crystal = chemModel.getCrystal(); if (crystal != null) { count += crystal.getAtomCount(); // depends on control dependency: [if], data = [none] } IAtomContainerSet moleculeSet = chemModel.getMoleculeSet(); if (moleculeSet != null) { count += MoleculeSetManipulator.getAtomCount(moleculeSet); // depends on control dependency: [if], data = [(moleculeSet] } IReactionSet reactionSet = chemModel.getReactionSet(); if (reactionSet != null) { count += ReactionSetManipulator.getAtomCount(reactionSet); // depends on control dependency: [if], data = [(reactionSet] } return count; } }
public class class_name { public static void setStaticField(Class<?> clazz, String fieldName, Object fieldNewValue) { try { setStaticField(clazz.getDeclaredField(fieldName), fieldNewValue); } catch (Exception e) { throw new RuntimeException(e); } } }
public class class_name { public static void setStaticField(Class<?> clazz, String fieldName, Object fieldNewValue) { try { setStaticField(clazz.getDeclaredField(fieldName), fieldNewValue); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new RuntimeException(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private static void addDependency(List<Dependency> dependencies, MavenCoordinates requiredArtifact, Constants.ArtifactType type, String scope) { Dependency dependency = new Dependency(); dependency.setGroupId(requiredArtifact.getGroupId()); dependency.setArtifactId(requiredArtifact.getArtifactId()); dependency.setVersion(requiredArtifact.getVersion()); if(scope!=null){ dependency.setScope(scope); } if (type != null) { dependency.setType(type.getType()); } dependencies.add(dependency); } }
public class class_name { private static void addDependency(List<Dependency> dependencies, MavenCoordinates requiredArtifact, Constants.ArtifactType type, String scope) { Dependency dependency = new Dependency(); dependency.setGroupId(requiredArtifact.getGroupId()); dependency.setArtifactId(requiredArtifact.getArtifactId()); dependency.setVersion(requiredArtifact.getVersion()); if(scope!=null){ dependency.setScope(scope); // depends on control dependency: [if], data = [(scope] } if (type != null) { dependency.setType(type.getType()); // depends on control dependency: [if], data = [(type] } dependencies.add(dependency); } }
public class class_name { public void addPoint(double x, double y) { if (npoints >= xpoints.length) { final int newLength = npoints * 2; xpoints = Arrays.copyOf(xpoints, newLength); ypoints = Arrays.copyOf(ypoints, newLength); } xpoints[npoints] = x; ypoints[npoints] = y; npoints++; updateBounds(); } }
public class class_name { public void addPoint(double x, double y) { if (npoints >= xpoints.length) { final int newLength = npoints * 2; xpoints = Arrays.copyOf(xpoints, newLength); // depends on control dependency: [if], data = [none] ypoints = Arrays.copyOf(ypoints, newLength); // depends on control dependency: [if], data = [none] } xpoints[npoints] = x; ypoints[npoints] = y; npoints++; updateBounds(); } }
public class class_name { private static int getAbsoluteLevelOffset(@NotNull String path, @NotNull ResourceResolver resourceResolver) { Matcher versionHistoryMatcher = VERSION_HISTORY_PATTERN.matcher(path); if (versionHistoryMatcher.matches()) { return 3; } Matcher legacyVersionHistoryMatcher = LEGACY_VERSION_HISTORY_PATTERN.matcher(path); if (legacyVersionHistoryMatcher.matches()) { if (isTenant(resourceResolver)) { legacyVersionHistoryMatcher = LEGACY_VERSION_HISTORY_TENANT_PATTERN.matcher(path); if (legacyVersionHistoryMatcher.matches()) { return 3; } } return 2; } Matcher launchesMatcher = LAUNCHES_PATTERN.matcher(path); if (launchesMatcher.matches()) { return 6; } return 0; } }
public class class_name { private static int getAbsoluteLevelOffset(@NotNull String path, @NotNull ResourceResolver resourceResolver) { Matcher versionHistoryMatcher = VERSION_HISTORY_PATTERN.matcher(path); if (versionHistoryMatcher.matches()) { return 3; // depends on control dependency: [if], data = [none] } Matcher legacyVersionHistoryMatcher = LEGACY_VERSION_HISTORY_PATTERN.matcher(path); if (legacyVersionHistoryMatcher.matches()) { if (isTenant(resourceResolver)) { legacyVersionHistoryMatcher = LEGACY_VERSION_HISTORY_TENANT_PATTERN.matcher(path); // depends on control dependency: [if], data = [none] if (legacyVersionHistoryMatcher.matches()) { return 3; // depends on control dependency: [if], data = [none] } } return 2; // depends on control dependency: [if], data = [none] } Matcher launchesMatcher = LAUNCHES_PATTERN.matcher(path); if (launchesMatcher.matches()) { return 6; // depends on control dependency: [if], data = [none] } return 0; } }
public class class_name { CssFormatter startBlock( String[] selectors ) { final List<CssOutput> results = state.results; if( blockDeep == 0 ) { output = null; CssOutput nextOutput = null; if( results.size() > 0 && !"@font-face".equals( selectors[0] ) ) { CssOutput cssOutput = results.get( results.size() - 1 ); if( Arrays.equals( selectors, cssOutput.getSelectors() ) ) { nextOutput = cssOutput; } } CssFormatter block; if( nextOutput == null ) { block = copy( null ); if( selectors[0].startsWith( "@media" ) ) { block.lessExtends = new LessExtendMap( state.lessExtends ); nextOutput = new CssMediaOutput( selectors, block.output, state.isReference, block.lessExtends ); } else { nextOutput = new CssRuleOutput( selectors, block.output, state.isReference ); } results.add( nextOutput ); } else { block = copy( nextOutput.getOutput() ); } block.currentOutput = nextOutput; block.incInsets(); block.blockDeep++; return block; } else { if( selectors[0].startsWith( "@media" ) ) { CssFormatter block = copy( null ); block.lessExtends = new LessExtendMap( state.lessExtends ); String[] sel = new String[]{ this.currentOutput.getSelectors()[0] + " and " + selectors[0].substring( 6 ).trim() }; block.currentOutput = new CssMediaOutput( sel, block.output, state.isReference, block.lessExtends ); results.add( block.currentOutput ); block.insets.setLength( 2 ); block.blockDeep = 1; return block; } else { if( blockDeep == 1 && this.currentOutput.getClass() == CssMediaOutput.class ) { CssFormatter block = copy( null ); block.incInsets(); block.currentOutput = this.currentOutput; ((CssMediaOutput)this.currentOutput).startBlock( selectors, block.output ); block.blockDeep++; return block; } else { blockDeep++; startBlockImpl( selectors ); return this; } } } } }
public class class_name { CssFormatter startBlock( String[] selectors ) { final List<CssOutput> results = state.results; if( blockDeep == 0 ) { output = null; // depends on control dependency: [if], data = [none] CssOutput nextOutput = null; if( results.size() > 0 && !"@font-face".equals( selectors[0] ) ) { CssOutput cssOutput = results.get( results.size() - 1 ); if( Arrays.equals( selectors, cssOutput.getSelectors() ) ) { nextOutput = cssOutput; // depends on control dependency: [if], data = [none] } } CssFormatter block; if( nextOutput == null ) { block = copy( null ); // depends on control dependency: [if], data = [null )] if( selectors[0].startsWith( "@media" ) ) { block.lessExtends = new LessExtendMap( state.lessExtends ); // depends on control dependency: [if], data = [none] nextOutput = new CssMediaOutput( selectors, block.output, state.isReference, block.lessExtends ); // depends on control dependency: [if], data = [none] } else { nextOutput = new CssRuleOutput( selectors, block.output, state.isReference ); // depends on control dependency: [if], data = [none] } results.add( nextOutput ); // depends on control dependency: [if], data = [( nextOutput] } else { block = copy( nextOutput.getOutput() ); // depends on control dependency: [if], data = [( nextOutput] } block.currentOutput = nextOutput; // depends on control dependency: [if], data = [none] block.incInsets(); // depends on control dependency: [if], data = [none] block.blockDeep++; // depends on control dependency: [if], data = [none] return block; // depends on control dependency: [if], data = [none] } else { if( selectors[0].startsWith( "@media" ) ) { CssFormatter block = copy( null ); block.lessExtends = new LessExtendMap( state.lessExtends ); // depends on control dependency: [if], data = [none] String[] sel = new String[]{ this.currentOutput.getSelectors()[0] + " and " + selectors[0].substring( 6 ).trim() }; block.currentOutput = new CssMediaOutput( sel, block.output, state.isReference, block.lessExtends ); // depends on control dependency: [if], data = [none] results.add( block.currentOutput ); // depends on control dependency: [if], data = [none] block.insets.setLength( 2 ); // depends on control dependency: [if], data = [none] block.blockDeep = 1; // depends on control dependency: [if], data = [none] return block; // depends on control dependency: [if], data = [none] } else { if( blockDeep == 1 && this.currentOutput.getClass() == CssMediaOutput.class ) { CssFormatter block = copy( null ); block.incInsets(); // depends on control dependency: [if], data = [none] block.currentOutput = this.currentOutput; // depends on control dependency: [if], data = [none] ((CssMediaOutput)this.currentOutput).startBlock( selectors, block.output ); // depends on control dependency: [if], data = [none] block.blockDeep++; // depends on control dependency: [if], data = [none] return block; // depends on control dependency: [if], data = [none] } else { blockDeep++; // depends on control dependency: [if], data = [none] startBlockImpl( selectors ); // depends on control dependency: [if], data = [none] return this; // depends on control dependency: [if], data = [none] } } } } }
public class class_name { public String translate(K k) { final Object o = k.getConstant(); String result; if (o != null) { if (!k.isQuote()) { result = o.toString(); } else if (o instanceof String) { result = singleQuotize(escapeSql((String) o)); } else if (o instanceof Boolean) { result = (Boolean) o ? translateTrue() : translateFalse(); } else { result = o.toString(); } } else { result = "NULL"; } return k.isEnclosed() ? ("(" + result + ")") : result; } }
public class class_name { public String translate(K k) { final Object o = k.getConstant(); String result; if (o != null) { if (!k.isQuote()) { result = o.toString(); // depends on control dependency: [if], data = [none] } else if (o instanceof String) { result = singleQuotize(escapeSql((String) o)); // depends on control dependency: [if], data = [none] } else if (o instanceof Boolean) { result = (Boolean) o ? translateTrue() : translateFalse(); // depends on control dependency: [if], data = [none] } else { result = o.toString(); // depends on control dependency: [if], data = [none] } } else { result = "NULL"; // depends on control dependency: [if], data = [none] } return k.isEnclosed() ? ("(" + result + ")") : result; } }
public class class_name { public void actionDeleteElementLocale() throws JspException { try { Locale loc = getElementLocale(); m_page.removeLocale(loc); //write the modified xml content m_file.setContents(m_page.marshal()); m_file = getCms().writeFile(m_file); List<Locale> locales = m_page.getLocales(); if (locales.size() > 0) { // set first locale as new display locale Locale newLoc = locales.get(0); setParamElementlanguage(newLoc.toString()); m_elementLocale = newLoc; } else { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.LOG_GET_LOCALES_1, getParamResource())); } } initContent(); } catch (CmsXmlException e) { // an error occurred while trying to delete the locale, stop action showErrorPage(e); } catch (CmsException e) { // should usually never happen if (LOG.isInfoEnabled()) { LOG.info(e.getLocalizedMessage(), e); } } } }
public class class_name { public void actionDeleteElementLocale() throws JspException { try { Locale loc = getElementLocale(); m_page.removeLocale(loc); //write the modified xml content m_file.setContents(m_page.marshal()); m_file = getCms().writeFile(m_file); List<Locale> locales = m_page.getLocales(); if (locales.size() > 0) { // set first locale as new display locale Locale newLoc = locales.get(0); setParamElementlanguage(newLoc.toString()); m_elementLocale = newLoc; } else { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.LOG_GET_LOCALES_1, getParamResource())); // depends on control dependency: [if], data = [none] } } initContent(); } catch (CmsXmlException e) { // an error occurred while trying to delete the locale, stop action showErrorPage(e); } catch (CmsException e) { // should usually never happen if (LOG.isInfoEnabled()) { LOG.info(e.getLocalizedMessage(), e); } } } }
public class class_name { private int getDependencies(JSONObject npmLsJson, List<String> linesOfNpmLs, int currentLineNumber, Collection<DependencyInfo> dependencies) { if (npmLsJson.has(Constants.DEPENDENCIES)) { JSONObject dependenciesJsonObject = npmLsJson.getJSONObject(Constants.DEPENDENCIES); if (dependenciesJsonObject != null) { for (int i = 0; i < dependenciesJsonObject.keySet().size(); i++) { String currentLine = linesOfNpmLs.get(currentLineNumber); // Examples: // +-- UNMET DEPENDENCY @material-ui/core@1.5.0 // | +-- UNMET DEPENDENCY @babel/runtime@7.0.0-beta.42 // | | `-- UNMET DEPENDENCY regenerator-runtime@0.11.1 // | | +-- UNMET OPTIONAL DEPENDENCY are-we-there-yet@1.1.4 // | | | +-- UNMET OPTIONAL DEPENDENCY delegates@1.0.0 // | | | `-- UNMET OPTIONAL DEPENDENCY readable-stream@2.3.6 if (currentLine.endsWith(DEDUPED) || currentLine.contains(UNMET_DEPENDENCY)) { currentLineNumber++; continue; } String dependencyAlias = getTheNextPackageNameFromNpmLs(currentLine); try { JSONObject dependencyJsonObject = dependenciesJsonObject.getJSONObject(dependencyAlias); DependencyInfo dependency = getDependency(dependencyAlias, dependencyJsonObject); if (dependency != null) { dependencies.add(dependency); logger.debug("Collect child dependencies of {}", dependencyAlias); // collect child dependencies Collection<DependencyInfo> childDependencies = new ArrayList<>(); currentLineNumber = getDependencies(dependencyJsonObject, linesOfNpmLs, currentLineNumber + 1, childDependencies); dependency.getChildren().addAll(childDependencies); } else { // it can be only if was an error in 'npm ls' if (dependencyJsonObject.has(REQUIRED)) { Object requiredObject = dependencyJsonObject.get(REQUIRED); if (requiredObject instanceof JSONObject) { currentLineNumber = getDependencies((JSONObject) requiredObject, linesOfNpmLs, currentLineNumber + 1, new ArrayList<>()); } else { currentLineNumber++; } } else { currentLineNumber++; } } } catch (JSONException e){ if (ignoreNpmLsErrors) { logger.error(e.getMessage()); logger.debug("{}", e.getStackTrace()); currentLineNumber++; } else { throw e; } } } } } return currentLineNumber; } }
public class class_name { private int getDependencies(JSONObject npmLsJson, List<String> linesOfNpmLs, int currentLineNumber, Collection<DependencyInfo> dependencies) { if (npmLsJson.has(Constants.DEPENDENCIES)) { JSONObject dependenciesJsonObject = npmLsJson.getJSONObject(Constants.DEPENDENCIES); if (dependenciesJsonObject != null) { for (int i = 0; i < dependenciesJsonObject.keySet().size(); i++) { String currentLine = linesOfNpmLs.get(currentLineNumber); // Examples: // +-- UNMET DEPENDENCY @material-ui/core@1.5.0 // | +-- UNMET DEPENDENCY @babel/runtime@7.0.0-beta.42 // | | `-- UNMET DEPENDENCY regenerator-runtime@0.11.1 // | | +-- UNMET OPTIONAL DEPENDENCY are-we-there-yet@1.1.4 // | | | +-- UNMET OPTIONAL DEPENDENCY delegates@1.0.0 // | | | `-- UNMET OPTIONAL DEPENDENCY readable-stream@2.3.6 if (currentLine.endsWith(DEDUPED) || currentLine.contains(UNMET_DEPENDENCY)) { currentLineNumber++; // depends on control dependency: [if], data = [none] continue; } String dependencyAlias = getTheNextPackageNameFromNpmLs(currentLine); try { JSONObject dependencyJsonObject = dependenciesJsonObject.getJSONObject(dependencyAlias); DependencyInfo dependency = getDependency(dependencyAlias, dependencyJsonObject); if (dependency != null) { dependencies.add(dependency); // depends on control dependency: [if], data = [(dependency] logger.debug("Collect child dependencies of {}", dependencyAlias); // depends on control dependency: [if], data = [none] // collect child dependencies Collection<DependencyInfo> childDependencies = new ArrayList<>(); currentLineNumber = getDependencies(dependencyJsonObject, linesOfNpmLs, currentLineNumber + 1, childDependencies); // depends on control dependency: [if], data = [(dependency] dependency.getChildren().addAll(childDependencies); // depends on control dependency: [if], data = [none] } else { // it can be only if was an error in 'npm ls' if (dependencyJsonObject.has(REQUIRED)) { Object requiredObject = dependencyJsonObject.get(REQUIRED); if (requiredObject instanceof JSONObject) { currentLineNumber = getDependencies((JSONObject) requiredObject, linesOfNpmLs, currentLineNumber + 1, new ArrayList<>()); // depends on control dependency: [if], data = [none] } else { currentLineNumber++; // depends on control dependency: [if], data = [none] } } else { currentLineNumber++; // depends on control dependency: [if], data = [none] } } } catch (JSONException e){ if (ignoreNpmLsErrors) { logger.error(e.getMessage()); // depends on control dependency: [if], data = [none] logger.debug("{}", e.getStackTrace()); // depends on control dependency: [if], data = [none] currentLineNumber++; // depends on control dependency: [if], data = [none] } else { throw e; } } // depends on control dependency: [catch], data = [none] } } } return currentLineNumber; } }
public class class_name { public void marshall(ElasticIp elasticIp, ProtocolMarshaller protocolMarshaller) { if (elasticIp == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(elasticIp.getIp(), IP_BINDING); protocolMarshaller.marshall(elasticIp.getName(), NAME_BINDING); protocolMarshaller.marshall(elasticIp.getDomain(), DOMAIN_BINDING); protocolMarshaller.marshall(elasticIp.getRegion(), REGION_BINDING); protocolMarshaller.marshall(elasticIp.getInstanceId(), INSTANCEID_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(ElasticIp elasticIp, ProtocolMarshaller protocolMarshaller) { if (elasticIp == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(elasticIp.getIp(), IP_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(elasticIp.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(elasticIp.getDomain(), DOMAIN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(elasticIp.getRegion(), REGION_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(elasticIp.getInstanceId(), INSTANCEID_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public SqlInfo buildSqlInfo(BuildSource source) { Node node = source.getNode(); /* 获取field和match属性,如果匹配中'match'属性没有值或者值为真,则认为是必然生成项. */ String fieldText = XmlNodeHelper.getAndCheckNodeText(node, ZealotConst.ATTR_FIELD); String matchText = XmlNodeHelper.getNodeAttrText(node, ZealotConst.ATTR_MATCH); Boolean matchValue = (Boolean) ParseHelper.parseExpressWithException(matchText, source.getParamObj()); if (StringHelper.isBlank(matchText) || Boolean.TRUE.equals(matchValue)) { return XmlSqlInfoBuilder.newInstace(source).buildIsNullSql(fieldText); } return source.getSqlInfo(); } }
public class class_name { @Override public SqlInfo buildSqlInfo(BuildSource source) { Node node = source.getNode(); /* 获取field和match属性,如果匹配中'match'属性没有值或者值为真,则认为是必然生成项. */ String fieldText = XmlNodeHelper.getAndCheckNodeText(node, ZealotConst.ATTR_FIELD); String matchText = XmlNodeHelper.getNodeAttrText(node, ZealotConst.ATTR_MATCH); Boolean matchValue = (Boolean) ParseHelper.parseExpressWithException(matchText, source.getParamObj()); if (StringHelper.isBlank(matchText) || Boolean.TRUE.equals(matchValue)) { return XmlSqlInfoBuilder.newInstace(source).buildIsNullSql(fieldText); // depends on control dependency: [if], data = [none] } return source.getSqlInfo(); } }
public class class_name { public static base_responses unset(nitro_service client, aaakcdaccount resources[], String[] args) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { aaakcdaccount unsetresources[] = new aaakcdaccount[resources.length]; for (int i=0;i<resources.length;i++){ unsetresources[i] = new aaakcdaccount(); unsetresources[i].kcdaccount = resources[i].kcdaccount; unsetresources[i].keytab = resources[i].keytab; unsetresources[i].usercert = resources[i].usercert; unsetresources[i].cacert = resources[i].cacert; } result = unset_bulk_request(client, unsetresources,args); } return result; } }
public class class_name { public static base_responses unset(nitro_service client, aaakcdaccount resources[], String[] args) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { aaakcdaccount unsetresources[] = new aaakcdaccount[resources.length]; for (int i=0;i<resources.length;i++){ unsetresources[i] = new aaakcdaccount(); // depends on control dependency: [for], data = [i] unsetresources[i].kcdaccount = resources[i].kcdaccount; // depends on control dependency: [for], data = [i] unsetresources[i].keytab = resources[i].keytab; // depends on control dependency: [for], data = [i] unsetresources[i].usercert = resources[i].usercert; // depends on control dependency: [for], data = [i] unsetresources[i].cacert = resources[i].cacert; // depends on control dependency: [for], data = [i] } result = unset_bulk_request(client, unsetresources,args); } return result; } }
public class class_name { private Stack<String> truncatePathStack(int pLevel) { if (pathStack.size() < pLevel) { return new Stack<String>(); } else { // Trim of domain and MBean properties // pathStack gets cloned here since the processing will eat it up Stack<String> ret = (Stack<String>) pathStack.clone(); for (int i = 0;i < pLevel;i++) { ret.pop(); } return ret; } } }
public class class_name { private Stack<String> truncatePathStack(int pLevel) { if (pathStack.size() < pLevel) { return new Stack<String>(); // depends on control dependency: [if], data = [none] } else { // Trim of domain and MBean properties // pathStack gets cloned here since the processing will eat it up Stack<String> ret = (Stack<String>) pathStack.clone(); for (int i = 0;i < pLevel;i++) { ret.pop(); // depends on control dependency: [for], data = [none] } return ret; // depends on control dependency: [if], data = [none] } } }
public class class_name { protected void init(String domain){ // get list of public fields java.lang.reflect.Field[] fields = this.getClass().getDeclaredFields(); if(fields.length > 0){ if(domain == null) domain = fields[0].getDeclaringClass().getName(); // Fix our debugging to use the child classname logger = Logging.getLogger(fields[0].getDeclaringClass().getName()); } logger.debug("Beginning initialization from PropertyManager using domain='" + domain + "'"); PropertyManager.ManagedProperties properties = PropertyManager.getProperties(domain); PropertyManager.ManagedProperties secureProperties = PropertyManager.getProperties("_" + domain); // Go through all the public fields in this class, and try to fill them from // our property class logger.debug("field count = " + fields.length); for(int i = 0; i < fields.length; i++){ String fieldName = fields[i].getName(); Class<?> type = fields[i].getType(); String value = secureProperties.getProperty(fieldName); boolean doSecurely = value != null; if(value == null) value = properties.getProperty(fieldName); boolean isArray = fields[i].getType().isArray(); try{ if(isArray){ if(value == null){ // We need to grab all the values for the array (.0,.1,.2, etc) List<String> values = new ArrayList<String>(); for(int j = 0; true; j++){ if(doSecurely) value = secureProperties.getProperty(fieldName + "." + j); else value = properties.getProperty(fieldName + "." + j); if(value == null) break; if(doSecurely) logger.info("Setting field '" + fieldName + ":" + type.getComponentType().getName() + "' [" + j + "] to ***PROTECTED***"); else logger.info("Setting field '" + fieldName + ":" + type.getComponentType().getName() + "' [" + j + "] to " + value); values.add(value); } if(values.size() == 0) continue; fields[i].setAccessible(true); fields[i].set(null, getObjectForString(type, values.toArray(new String[values.size()]))); }else{ // We have a single property value, try to deserialize gson fields[i].setAccessible(true); fields[i].set(null, getObjectForString(type, value)); } }else if(value != null){ if(doSecurely) logger.info("Setting field '" + fieldName + ":" + type.getName() + "' to ***PROTECTED***"); else logger.info("Setting field '" + fieldName + ":" + type.getName() + "' to " + value); fields[i].setAccessible(true); fields[i].set(null, getObjectForString(type, value)); }else{ // debug.debug("'" + fieldName + "' does not exist in the properties // file. (Domain='" + domain + "') Leaving alone."); } }catch(Exception ex){ logger.error("Error setting field '" + fieldName + "'. Check properties file.", ex); } } logger.debug("Init complete"); } }
public class class_name { protected void init(String domain){ // get list of public fields java.lang.reflect.Field[] fields = this.getClass().getDeclaredFields(); if(fields.length > 0){ if(domain == null) domain = fields[0].getDeclaringClass().getName(); // Fix our debugging to use the child classname logger = Logging.getLogger(fields[0].getDeclaringClass().getName()); // depends on control dependency: [if], data = [none] } logger.debug("Beginning initialization from PropertyManager using domain='" + domain + "'"); PropertyManager.ManagedProperties properties = PropertyManager.getProperties(domain); PropertyManager.ManagedProperties secureProperties = PropertyManager.getProperties("_" + domain); // Go through all the public fields in this class, and try to fill them from // our property class logger.debug("field count = " + fields.length); for(int i = 0; i < fields.length; i++){ String fieldName = fields[i].getName(); Class<?> type = fields[i].getType(); String value = secureProperties.getProperty(fieldName); boolean doSecurely = value != null; if(value == null) value = properties.getProperty(fieldName); boolean isArray = fields[i].getType().isArray(); try{ if(isArray){ if(value == null){ // We need to grab all the values for the array (.0,.1,.2, etc) List<String> values = new ArrayList<String>(); for(int j = 0; true; j++){ if(doSecurely) value = secureProperties.getProperty(fieldName + "." + j); else value = properties.getProperty(fieldName + "." + j); if(value == null) break; if(doSecurely) logger.info("Setting field '" + fieldName + ":" + type.getComponentType().getName() + "' [" + j + "] to ***PROTECTED***"); else logger.info("Setting field '" + fieldName + ":" + type.getComponentType().getName() + "' [" + j + "] to " + value); values.add(value); // depends on control dependency: [for], data = [none] } if(values.size() == 0) continue; fields[i].setAccessible(true); // depends on control dependency: [if], data = [none] fields[i].set(null, getObjectForString(type, values.toArray(new String[values.size()]))); // depends on control dependency: [if], data = [none] }else{ // We have a single property value, try to deserialize gson fields[i].setAccessible(true); // depends on control dependency: [if], data = [none] fields[i].set(null, getObjectForString(type, value)); // depends on control dependency: [if], data = [none] } }else if(value != null){ if(doSecurely) logger.info("Setting field '" + fieldName + ":" + type.getName() + "' to ***PROTECTED***"); else logger.info("Setting field '" + fieldName + ":" + type.getName() + "' to " + value); fields[i].setAccessible(true); // depends on control dependency: [if], data = [none] fields[i].set(null, getObjectForString(type, value)); // depends on control dependency: [if], data = [none] }else{ // debug.debug("'" + fieldName + "' does not exist in the properties // file. (Domain='" + domain + "') Leaving alone."); } }catch(Exception ex){ logger.error("Error setting field '" + fieldName + "'. Check properties file.", ex); } // depends on control dependency: [catch], data = [none] } logger.debug("Init complete"); } }
public class class_name { public CmsMenuItemVisibilityMode getVisibility(I_CmsContextMenuItem item) { CmsMenuItemVisibilityMode result = m_visiblities.get(item); if (result == null) { result = item.getVisibility(m_context); m_visiblities.put(item, result); } return result; } }
public class class_name { public CmsMenuItemVisibilityMode getVisibility(I_CmsContextMenuItem item) { CmsMenuItemVisibilityMode result = m_visiblities.get(item); if (result == null) { result = item.getVisibility(m_context); // depends on control dependency: [if], data = [none] m_visiblities.put(item, result); // depends on control dependency: [if], data = [none] } return result; } }
public class class_name { long get(final long key) { final int probe = hashProbe(key); if (states[probe] > 0) { assert (keys[probe] == key); return values[probe]; } return 0; } }
public class class_name { long get(final long key) { final int probe = hashProbe(key); if (states[probe] > 0) { assert (keys[probe] == key); // depends on control dependency: [if], data = [none] return values[probe]; // depends on control dependency: [if], data = [none] } return 0; } }
public class class_name { public MultipleRuleContext<DPO, RI, RO> check(Rule<RI, RO> rule) { if (rule != null) { addedRules.add(rule); } // Stay in the same context and re-use the same instance because no type has changed return this; } }
public class class_name { public MultipleRuleContext<DPO, RI, RO> check(Rule<RI, RO> rule) { if (rule != null) { addedRules.add(rule); // depends on control dependency: [if], data = [(rule] } // Stay in the same context and re-use the same instance because no type has changed return this; } }
public class class_name { @CanIgnoreReturnValue @Override public int setCount(E element, int count) { checkIsE(element); checkNonnegative(count, "count"); int index = element.ordinal(); int oldCount = counts[index]; counts[index] = count; size += count - oldCount; if (oldCount == 0 && count > 0) { distinctElements++; } else if (oldCount > 0 && count == 0) { distinctElements--; } return oldCount; } }
public class class_name { @CanIgnoreReturnValue @Override public int setCount(E element, int count) { checkIsE(element); checkNonnegative(count, "count"); int index = element.ordinal(); int oldCount = counts[index]; counts[index] = count; size += count - oldCount; if (oldCount == 0 && count > 0) { distinctElements++; // depends on control dependency: [if], data = [none] } else if (oldCount > 0 && count == 0) { distinctElements--; // depends on control dependency: [if], data = [none] } return oldCount; } }
public class class_name { private Object readResponse(Type returnType, InputStream input, String id) throws Throwable { ReadContext context = ReadContext.getReadContext(input, mapper); ObjectNode jsonObject = getValidResponse(id, context); notifyAnswerListener(jsonObject); handleErrorResponse(jsonObject); if (hasResult(jsonObject)) { if (isReturnTypeInvalid(returnType)) { return null; } return constructResponseObject(returnType, jsonObject); } // no return type return null; } }
public class class_name { private Object readResponse(Type returnType, InputStream input, String id) throws Throwable { ReadContext context = ReadContext.getReadContext(input, mapper); ObjectNode jsonObject = getValidResponse(id, context); notifyAnswerListener(jsonObject); handleErrorResponse(jsonObject); if (hasResult(jsonObject)) { if (isReturnTypeInvalid(returnType)) { return null; // depends on control dependency: [if], data = [none] } return constructResponseObject(returnType, jsonObject); } // no return type return null; } }
public class class_name { public void setColumns(java.util.Collection<Column> columns) { if (columns == null) { this.columns = null; return; } this.columns = new java.util.ArrayList<Column>(columns); } }
public class class_name { public void setColumns(java.util.Collection<Column> columns) { if (columns == null) { this.columns = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.columns = new java.util.ArrayList<Column>(columns); } }
public class class_name { public static double[][] times(final double[][] m1, final double[][] m2) { final int rowdim1 = m1.length, coldim1 = getColumnDimensionality(m1); final int coldim2 = getColumnDimensionality(m2); // Optimized implementation, exploiting the storage layout assert m2.length == coldim1 : ERR_MATRIX_INNERDIM; final double[][] r2 = new double[rowdim1][coldim2]; // Optimized ala Jama. jik order. final double[] Bcolj = new double[coldim1]; for(int j = 0; j < coldim2; j++) { // Make a linear copy of column j from B for(int k = 0; k < coldim1; k++) { Bcolj[k] = m2[k][j]; } // multiply it with each row from A for(int i = 0; i < rowdim1; i++) { final double[] Arowi = m1[i]; double s = 0; for(int k = 0; k < coldim1; k++) { s += Arowi[k] * Bcolj[k]; } r2[i][j] = s; } } return r2; } }
public class class_name { public static double[][] times(final double[][] m1, final double[][] m2) { final int rowdim1 = m1.length, coldim1 = getColumnDimensionality(m1); final int coldim2 = getColumnDimensionality(m2); // Optimized implementation, exploiting the storage layout assert m2.length == coldim1 : ERR_MATRIX_INNERDIM; final double[][] r2 = new double[rowdim1][coldim2]; // Optimized ala Jama. jik order. final double[] Bcolj = new double[coldim1]; for(int j = 0; j < coldim2; j++) { // Make a linear copy of column j from B for(int k = 0; k < coldim1; k++) { Bcolj[k] = m2[k][j]; // depends on control dependency: [for], data = [k] } // multiply it with each row from A for(int i = 0; i < rowdim1; i++) { final double[] Arowi = m1[i]; double s = 0; for(int k = 0; k < coldim1; k++) { s += Arowi[k] * Bcolj[k]; // depends on control dependency: [for], data = [k] } r2[i][j] = s; // depends on control dependency: [for], data = [i] } } return r2; } }
public class class_name { protected void restoreValue( Object defValue) { if (storeData != null) { validValue = getStoreValue( defValue); setEditValue( validValue); } } }
public class class_name { protected void restoreValue( Object defValue) { if (storeData != null) { validValue = getStoreValue( defValue); // depends on control dependency: [if], data = [none] setEditValue( validValue); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void setSkillSummaries(java.util.Collection<SkillSummary> skillSummaries) { if (skillSummaries == null) { this.skillSummaries = null; return; } this.skillSummaries = new java.util.ArrayList<SkillSummary>(skillSummaries); } }
public class class_name { public void setSkillSummaries(java.util.Collection<SkillSummary> skillSummaries) { if (skillSummaries == null) { this.skillSummaries = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.skillSummaries = new java.util.ArrayList<SkillSummary>(skillSummaries); } }
public class class_name { public static void setScopeAttribute(final String name, final Object value, final String scope, final PageContext pageContext) { HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); String scopeValue = scope != null ? scope.toLowerCase() : SCOPE_PAGE; if (scopeValue.equals(SCOPE_PAGE)) { pageContext.setAttribute(name, value); } else if (scopeValue.equals(SCOPE_REQUEST)) { request.setAttribute(name, value); } else if (scopeValue.equals(SCOPE_SESSION)) { request.getSession().setAttribute(name, value); } else if (scopeValue.equals(SCOPE_APPLICATION)) { request.getServletContext().setAttribute(name, value); } else { throw new IllegalArgumentException("Invalid scope: " + scope); } } }
public class class_name { public static void setScopeAttribute(final String name, final Object value, final String scope, final PageContext pageContext) { HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); String scopeValue = scope != null ? scope.toLowerCase() : SCOPE_PAGE; if (scopeValue.equals(SCOPE_PAGE)) { pageContext.setAttribute(name, value); // depends on control dependency: [if], data = [none] } else if (scopeValue.equals(SCOPE_REQUEST)) { request.setAttribute(name, value); // depends on control dependency: [if], data = [none] } else if (scopeValue.equals(SCOPE_SESSION)) { request.getSession().setAttribute(name, value); // depends on control dependency: [if], data = [none] } else if (scopeValue.equals(SCOPE_APPLICATION)) { request.getServletContext().setAttribute(name, value); // depends on control dependency: [if], data = [none] } else { throw new IllegalArgumentException("Invalid scope: " + scope); } } }
public class class_name { public GetSecurityConfigurationsResult withSecurityConfigurations(SecurityConfiguration... securityConfigurations) { if (this.securityConfigurations == null) { setSecurityConfigurations(new java.util.ArrayList<SecurityConfiguration>(securityConfigurations.length)); } for (SecurityConfiguration ele : securityConfigurations) { this.securityConfigurations.add(ele); } return this; } }
public class class_name { public GetSecurityConfigurationsResult withSecurityConfigurations(SecurityConfiguration... securityConfigurations) { if (this.securityConfigurations == null) { setSecurityConfigurations(new java.util.ArrayList<SecurityConfiguration>(securityConfigurations.length)); // depends on control dependency: [if], data = [none] } for (SecurityConfiguration ele : securityConfigurations) { this.securityConfigurations.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { public final StringProperty locationProperty() { if (location == null) { location = new SimpleStringProperty(null, "location") { //$NON-NLS-1$ @Override public void set(String newLocation) { String oldLocation = get(); if (!Util.equals(oldLocation, newLocation)) { super.set(newLocation); Calendar calendar = getCalendar(); if (calendar != null) { calendar.fireEvent(new CalendarEvent(CalendarEvent.ENTRY_LOCATION_CHANGED, calendar, Entry.this, oldLocation)); } } } }; } return location; } }
public class class_name { public final StringProperty locationProperty() { if (location == null) { location = new SimpleStringProperty(null, "location") { //$NON-NLS-1$ @Override public void set(String newLocation) { String oldLocation = get(); if (!Util.equals(oldLocation, newLocation)) { super.set(newLocation); // depends on control dependency: [if], data = [none] Calendar calendar = getCalendar(); if (calendar != null) { calendar.fireEvent(new CalendarEvent(CalendarEvent.ENTRY_LOCATION_CHANGED, calendar, Entry.this, oldLocation)); // depends on control dependency: [if], data = [none] } } } }; // depends on control dependency: [if], data = [none] } return location; } }
public class class_name { public static void getSuperTypeParameterMap(JvmDeclaredType type, Map<String, JvmTypeReference> mapping) { for (final JvmTypeReference superTypeReference : type.getSuperTypes()) { if (superTypeReference instanceof JvmParameterizedTypeReference) { final JvmParameterizedTypeReference parameterizedTypeReference = (JvmParameterizedTypeReference) superTypeReference; final JvmType st = superTypeReference.getType(); if (st instanceof JvmTypeParameterDeclarator) { final JvmTypeParameterDeclarator superType = (JvmTypeParameterDeclarator) st; int i = 0; for (final JvmTypeParameter typeParameter : superType.getTypeParameters()) { mapping.put(typeParameter.getIdentifier(), parameterizedTypeReference.getArguments().get(i)); ++i; } } } } } }
public class class_name { public static void getSuperTypeParameterMap(JvmDeclaredType type, Map<String, JvmTypeReference> mapping) { for (final JvmTypeReference superTypeReference : type.getSuperTypes()) { if (superTypeReference instanceof JvmParameterizedTypeReference) { final JvmParameterizedTypeReference parameterizedTypeReference = (JvmParameterizedTypeReference) superTypeReference; final JvmType st = superTypeReference.getType(); if (st instanceof JvmTypeParameterDeclarator) { final JvmTypeParameterDeclarator superType = (JvmTypeParameterDeclarator) st; int i = 0; for (final JvmTypeParameter typeParameter : superType.getTypeParameters()) { mapping.put(typeParameter.getIdentifier(), parameterizedTypeReference.getArguments().get(i)); // depends on control dependency: [for], data = [typeParameter] ++i; // depends on control dependency: [for], data = [none] } } } } } }
public class class_name { InjectionPoint getInternalConstructor() { if (factory.constructorInjector != null) { return factory.constructorInjector.getConstructionProxy().getInjectionPoint(); } else { return constructorInjectionPoint; } } }
public class class_name { InjectionPoint getInternalConstructor() { if (factory.constructorInjector != null) { return factory.constructorInjector.getConstructionProxy().getInjectionPoint(); // depends on control dependency: [if], data = [none] } else { return constructorInjectionPoint; // depends on control dependency: [if], data = [none] } } }
public class class_name { public void sendMessage(Severity severity, String className, String elementName, String eventName, String message, int severityLevel, boolean srActionable, long lastNotified, Metric triggeredOnMetric) { requireArgument(elementName != null && !elementName.isEmpty(), "ElementName cannot be null or empty."); requireArgument(eventName != null && !eventName.isEmpty(), "EventName cannot be null or empty."); if (Boolean.valueOf(_config.getValue(com.salesforce.dva.argus.system.SystemConfiguration.Property.GOC_ENABLED))) { try { GOCDataBuilder builder = new GOCDataBuilder(); className = _truncateIfSizeGreaterThan(className, 50); elementName = _truncateIfSizeGreaterThan(elementName, 100); eventName = _truncateIfSizeGreaterThan(eventName, 100); builder.withClassName(className).withElementName(elementName).withEventName(eventName). withSeverity(severityLevel).withSRActionable(srActionable).withEventText(message); if (severity == Severity.OK) { builder.withActive(false).withClearedAt(lastNotified); } else { builder.withActive(true).withCreatedAt(lastNotified); } builder.withLastNotifiedAt(lastNotified); if (srActionable == true) { builder.withUserdefined2(_config.getValue(AuditNotifier.Property.AUDIT_PRODOUTAGE_EMAIL_TEMPLATE.getName(), AuditNotifier.Property.AUDIT_PRODOUTAGE_EMAIL_TEMPLATE.getDefaultValue())); } GOCData gocData = builder.build(); boolean refresh = false; GOCTransport gocTransport = new GOCTransport(); HttpClient httpclient = gocTransport.getHttpClient(_config); for (int i = 0; i < 1; i++) { PostMethod post = null; try { post=getRequestMethod(refresh, triggeredOnMetric.hashCode() + " " + gocData.getsm_Alert_Id__c()); post.setRequestEntity(new StringRequestEntity(gocData.toJSON(), "application/json", null)); int respCode = httpclient.executeMethod(post); // Check for success if (respCode == 201 || respCode == 204) { _logger.info("Success - send GOC++ having element '{}' event '{}' severity {}.", elementName, eventName, severity.name()); break; } else if (respCode == 401) { // Indication that the session timedout, Need to refresh and retry refresh = true; } else { _logger.error("Failure - send GOC++ having element '{}' event '{}' severity {}. Response code '{}' response '{}'", elementName, eventName, severity.name(), respCode, post.getResponseBodyAsString()); } } catch (Exception e) { _logger.error("Failure - send GOC++ having element '{}' event '{}' severity {}. Exception '{}'", elementName, eventName, severity.name(), e); } finally { if(post != null){ post.releaseConnection(); } } } } catch (RuntimeException ex) { throw new SystemException("Failed to send an GOC++ notification.", ex); } } else { _logger.info("Sending GOC++ notification is disabled. Not sending message for element '{}' event '{}' severity {}.", elementName, eventName, severity.name()); } } }
public class class_name { public void sendMessage(Severity severity, String className, String elementName, String eventName, String message, int severityLevel, boolean srActionable, long lastNotified, Metric triggeredOnMetric) { requireArgument(elementName != null && !elementName.isEmpty(), "ElementName cannot be null or empty."); requireArgument(eventName != null && !eventName.isEmpty(), "EventName cannot be null or empty."); if (Boolean.valueOf(_config.getValue(com.salesforce.dva.argus.system.SystemConfiguration.Property.GOC_ENABLED))) { try { GOCDataBuilder builder = new GOCDataBuilder(); className = _truncateIfSizeGreaterThan(className, 50); // depends on control dependency: [try], data = [none] elementName = _truncateIfSizeGreaterThan(elementName, 100); // depends on control dependency: [try], data = [none] eventName = _truncateIfSizeGreaterThan(eventName, 100); // depends on control dependency: [try], data = [none] builder.withClassName(className).withElementName(elementName).withEventName(eventName). withSeverity(severityLevel).withSRActionable(srActionable).withEventText(message); // depends on control dependency: [try], data = [none] if (severity == Severity.OK) { builder.withActive(false).withClearedAt(lastNotified); // depends on control dependency: [if], data = [none] } else { builder.withActive(true).withCreatedAt(lastNotified); // depends on control dependency: [if], data = [none] } builder.withLastNotifiedAt(lastNotified); // depends on control dependency: [try], data = [none] if (srActionable == true) { builder.withUserdefined2(_config.getValue(AuditNotifier.Property.AUDIT_PRODOUTAGE_EMAIL_TEMPLATE.getName(), AuditNotifier.Property.AUDIT_PRODOUTAGE_EMAIL_TEMPLATE.getDefaultValue())); // depends on control dependency: [if], data = [none] } GOCData gocData = builder.build(); boolean refresh = false; GOCTransport gocTransport = new GOCTransport(); HttpClient httpclient = gocTransport.getHttpClient(_config); for (int i = 0; i < 1; i++) { PostMethod post = null; try { post=getRequestMethod(refresh, triggeredOnMetric.hashCode() + " " + gocData.getsm_Alert_Id__c()); // depends on control dependency: [try], data = [none] post.setRequestEntity(new StringRequestEntity(gocData.toJSON(), "application/json", null)); // depends on control dependency: [try], data = [none] int respCode = httpclient.executeMethod(post); // Check for success if (respCode == 201 || respCode == 204) { _logger.info("Success - send GOC++ having element '{}' event '{}' severity {}.", elementName, eventName, severity.name()); // depends on control dependency: [if], data = [none] break; } else if (respCode == 401) { // Indication that the session timedout, Need to refresh and retry refresh = true; // depends on control dependency: [if], data = [none] } else { _logger.error("Failure - send GOC++ having element '{}' event '{}' severity {}. Response code '{}' response '{}'", elementName, eventName, severity.name(), respCode, post.getResponseBodyAsString()); // depends on control dependency: [if], data = [none] } } catch (Exception e) { _logger.error("Failure - send GOC++ having element '{}' event '{}' severity {}. Exception '{}'", elementName, eventName, severity.name(), e); } finally { // depends on control dependency: [catch], data = [none] if(post != null){ post.releaseConnection(); // depends on control dependency: [if], data = [none] } } } } catch (RuntimeException ex) { throw new SystemException("Failed to send an GOC++ notification.", ex); } // depends on control dependency: [catch], data = [none] } else { _logger.info("Sending GOC++ notification is disabled. Not sending message for element '{}' event '{}' severity {}.", elementName, eventName, severity.name()); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void registerDefaults() { typeToEditor.clear(); propertyToEditor.clear(); //switch to service loader and use of custom annotation ServiceLoader<PropertyEditor> propertyLoader = ServiceLoader.load(PropertyEditor.class); Iterator<PropertyEditor> controllersIt = propertyLoader.iterator(); while (controllersIt.hasNext()) { try { PropertyEditor c = controllersIt.next(); EditorRegistry annotation = c.getClass().getAnnotation(EditorRegistry.class); if (annotation != null) { for (Class<?> clazz : annotation.type()) { registerEditor(clazz, c.getClass()); } } } catch (ServiceConfigurationError serviceError) { Logger.getLogger(getClass().getName()).log(Level.WARNING, serviceError.getMessage(), serviceError); } } } }
public class class_name { public void registerDefaults() { typeToEditor.clear(); propertyToEditor.clear(); //switch to service loader and use of custom annotation ServiceLoader<PropertyEditor> propertyLoader = ServiceLoader.load(PropertyEditor.class); Iterator<PropertyEditor> controllersIt = propertyLoader.iterator(); while (controllersIt.hasNext()) { try { PropertyEditor c = controllersIt.next(); EditorRegistry annotation = c.getClass().getAnnotation(EditorRegistry.class); if (annotation != null) { for (Class<?> clazz : annotation.type()) { registerEditor(clazz, c.getClass()); // depends on control dependency: [for], data = [clazz] } } } catch (ServiceConfigurationError serviceError) { Logger.getLogger(getClass().getName()).log(Level.WARNING, serviceError.getMessage(), serviceError); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { private Expression readCaseWhen(final Expression l) { readThis(Tokens.WHEN); Expression condition = null; if (l == null) { condition = XreadBooleanValueExpression(); } else { while (true) { Expression newCondition = XreadPredicateRightPart(l); if (l == newCondition) { newCondition = new ExpressionLogical(l, XreadRowValuePredicand()); } if (condition == null) { condition = newCondition; } else { condition = new ExpressionLogical(OpTypes.OR, condition, newCondition); } if (token.tokenType == Tokens.COMMA) { read(); } else { break; } } } readThis(Tokens.THEN); Expression current = XreadValueExpression(); Expression elseExpr = null; if (token.tokenType == Tokens.WHEN) { elseExpr = readCaseWhen(l); } else if (token.tokenType == Tokens.ELSE) { read(); elseExpr = XreadValueExpression(); readThis(Tokens.END); readIfThis(Tokens.CASE); } else { elseExpr = new ExpressionValue((Object) null, Type.SQL_ALL_TYPES); readThis(Tokens.END); readIfThis(Tokens.CASE); } Expression alternatives = new ExpressionOp(OpTypes.ALTERNATIVE, current, elseExpr); Expression casewhen = new ExpressionOp(OpTypes.CASEWHEN, condition, alternatives); return casewhen; } }
public class class_name { private Expression readCaseWhen(final Expression l) { readThis(Tokens.WHEN); Expression condition = null; if (l == null) { condition = XreadBooleanValueExpression(); // depends on control dependency: [if], data = [none] } else { while (true) { Expression newCondition = XreadPredicateRightPart(l); if (l == newCondition) { newCondition = new ExpressionLogical(l, XreadRowValuePredicand()); // depends on control dependency: [if], data = [none] } if (condition == null) { condition = newCondition; // depends on control dependency: [if], data = [none] } else { condition = new ExpressionLogical(OpTypes.OR, condition, newCondition); // depends on control dependency: [if], data = [none] } if (token.tokenType == Tokens.COMMA) { read(); // depends on control dependency: [if], data = [none] } else { break; } } } readThis(Tokens.THEN); Expression current = XreadValueExpression(); Expression elseExpr = null; if (token.tokenType == Tokens.WHEN) { elseExpr = readCaseWhen(l); // depends on control dependency: [if], data = [none] } else if (token.tokenType == Tokens.ELSE) { read(); // depends on control dependency: [if], data = [none] elseExpr = XreadValueExpression(); // depends on control dependency: [if], data = [none] readThis(Tokens.END); // depends on control dependency: [if], data = [none] readIfThis(Tokens.CASE); // depends on control dependency: [if], data = [none] } else { elseExpr = new ExpressionValue((Object) null, Type.SQL_ALL_TYPES); // depends on control dependency: [if], data = [none] readThis(Tokens.END); // depends on control dependency: [if], data = [none] readIfThis(Tokens.CASE); // depends on control dependency: [if], data = [none] } Expression alternatives = new ExpressionOp(OpTypes.ALTERNATIVE, current, elseExpr); Expression casewhen = new ExpressionOp(OpTypes.CASEWHEN, condition, alternatives); return casewhen; } }
public class class_name { public <T extends Object, O extends Object> List<T> findBySQL(String sql, List<O> params, RowMapper<T> mapper) { if (sql == null) { recordLog(" param sql is null!"); } // 构造参数 Object[] args = null; if (params == null) { args = new Object[0]; } else { args = params.toArray(new Object[params.size()]); } // 查询 if (params != null) { recordLog(sql + "\t" + params.toString()); } else { recordLog(sql); } return (List<T>) jdbcTemplate.query(sql, args, mapper); } }
public class class_name { public <T extends Object, O extends Object> List<T> findBySQL(String sql, List<O> params, RowMapper<T> mapper) { if (sql == null) { recordLog(" param sql is null!"); // depends on control dependency: [if], data = [none] } // 构造参数 Object[] args = null; if (params == null) { args = new Object[0]; // depends on control dependency: [if], data = [none] } else { args = params.toArray(new Object[params.size()]); // depends on control dependency: [if], data = [none] } // 查询 if (params != null) { recordLog(sql + "\t" + params.toString()); // depends on control dependency: [if], data = [none] } else { recordLog(sql); // depends on control dependency: [if], data = [none] } return (List<T>) jdbcTemplate.query(sql, args, mapper); } }
public class class_name { public void marshall(DomainSummary domainSummary, ProtocolMarshaller protocolMarshaller) { if (domainSummary == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(domainSummary.getDomainName(), DOMAINNAME_BINDING); protocolMarshaller.marshall(domainSummary.getAutoRenew(), AUTORENEW_BINDING); protocolMarshaller.marshall(domainSummary.getTransferLock(), TRANSFERLOCK_BINDING); protocolMarshaller.marshall(domainSummary.getExpiry(), EXPIRY_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(DomainSummary domainSummary, ProtocolMarshaller protocolMarshaller) { if (domainSummary == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(domainSummary.getDomainName(), DOMAINNAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(domainSummary.getAutoRenew(), AUTORENEW_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(domainSummary.getTransferLock(), TRANSFERLOCK_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(domainSummary.getExpiry(), EXPIRY_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 void marshall(StartDeviceSyncRequest startDeviceSyncRequest, ProtocolMarshaller protocolMarshaller) { if (startDeviceSyncRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(startDeviceSyncRequest.getRoomArn(), ROOMARN_BINDING); protocolMarshaller.marshall(startDeviceSyncRequest.getDeviceArn(), DEVICEARN_BINDING); protocolMarshaller.marshall(startDeviceSyncRequest.getFeatures(), FEATURES_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(StartDeviceSyncRequest startDeviceSyncRequest, ProtocolMarshaller protocolMarshaller) { if (startDeviceSyncRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(startDeviceSyncRequest.getRoomArn(), ROOMARN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(startDeviceSyncRequest.getDeviceArn(), DEVICEARN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(startDeviceSyncRequest.getFeatures(), FEATURES_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 Collection<Set<E>> allNonTrivialEquivalenceClasses() { Relation<E,E> relRepr2Elems = new MapSetRelation<E,E>(); for (E elem : elmap.keySet()) { E repr = find(elem); relRepr2Elems.add(repr, elem); } List<Set<E>> result = new LinkedList<Set<E>>(); for(E repr : relRepr2Elems.keys()) { Set<E> equivClass = relRepr2Elems.getValues(repr); // skip the trivial, 1-element equivalence classes if(equivClass.size() > 1) { result.add(relRepr2Elems.getValues(repr)); } } return Collections.unmodifiableList(result); } }
public class class_name { public Collection<Set<E>> allNonTrivialEquivalenceClasses() { Relation<E,E> relRepr2Elems = new MapSetRelation<E,E>(); for (E elem : elmap.keySet()) { E repr = find(elem); relRepr2Elems.add(repr, elem); // depends on control dependency: [for], data = [elem] } List<Set<E>> result = new LinkedList<Set<E>>(); for(E repr : relRepr2Elems.keys()) { Set<E> equivClass = relRepr2Elems.getValues(repr); // skip the trivial, 1-element equivalence classes if(equivClass.size() > 1) { result.add(relRepr2Elems.getValues(repr)); // depends on control dependency: [if], data = [none] } } return Collections.unmodifiableList(result); } }
public class class_name { protected final void notifyStarted() { monitor.enter(); try { // We have to examine the internal state of the snapshot here to properly handle the stop // while starting case. if (snapshot.state != STARTING) { IllegalStateException failure = new IllegalStateException( "Cannot notifyStarted() when the service is " + snapshot.state); notifyFailed(failure); throw failure; } if (snapshot.shutdownWhenStartupFinishes) { snapshot = new StateSnapshot(STOPPING); // We don't call listeners here because we already did that when we set the // shutdownWhenStartupFinishes flag. doStop(); } else { snapshot = new StateSnapshot(RUNNING); enqueueRunningEvent(); } } finally { monitor.leave(); dispatchListenerEvents(); } } }
public class class_name { protected final void notifyStarted() { monitor.enter(); try { // We have to examine the internal state of the snapshot here to properly handle the stop // while starting case. if (snapshot.state != STARTING) { IllegalStateException failure = new IllegalStateException( "Cannot notifyStarted() when the service is " + snapshot.state); notifyFailed(failure); // depends on control dependency: [if], data = [none] throw failure; } if (snapshot.shutdownWhenStartupFinishes) { snapshot = new StateSnapshot(STOPPING); // depends on control dependency: [if], data = [none] // We don't call listeners here because we already did that when we set the // shutdownWhenStartupFinishes flag. doStop(); // depends on control dependency: [if], data = [none] } else { snapshot = new StateSnapshot(RUNNING); // depends on control dependency: [if], data = [none] enqueueRunningEvent(); // depends on control dependency: [if], data = [none] } } finally { monitor.leave(); dispatchListenerEvents(); } } }
public class class_name { @Bind(id = "importDeclarations", specification = ImportDeclaration.class, aggregate = true, optional = true) void bindImportDeclaration(ServiceReference<ImportDeclaration> importDeclarationSRef) { synchronized (lock) { declarationsManager.add(importDeclarationSRef); if (!declarationsManager.matched(importDeclarationSRef)) { LOG.debug("No service matching was found, ignoring service reference."); return; } LOG.debug(linkerName + " : Bind the ImportDeclaration " + declarationsManager.getDeclaration(importDeclarationSRef)); declarationsManager.createLinks(importDeclarationSRef); } } }
public class class_name { @Bind(id = "importDeclarations", specification = ImportDeclaration.class, aggregate = true, optional = true) void bindImportDeclaration(ServiceReference<ImportDeclaration> importDeclarationSRef) { synchronized (lock) { declarationsManager.add(importDeclarationSRef); if (!declarationsManager.matched(importDeclarationSRef)) { LOG.debug("No service matching was found, ignoring service reference."); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } LOG.debug(linkerName + " : Bind the ImportDeclaration " + declarationsManager.getDeclaration(importDeclarationSRef)); declarationsManager.createLinks(importDeclarationSRef); } } }
public class class_name { public static String getBaseMessage(Throwable exception) { String message = null; // ----------------------------------------------------------------------- // RemoteException contains a 'detail' field that holds the 'cause', // instead of the normal cause defined by Throwable. When detail is // set, getMessage() will include the text and stack of the detail, // which may ends up duplicating the message text. // // To avoid this, 'detail' is temporarily cleared, resulting in // getMessage() returning only the message text specified when the // RemoteException was created. d366807 // ----------------------------------------------------------------------- if (exception instanceof RemoteException) { RemoteException rex = (RemoteException) exception; Throwable detail = rex.detail; rex.detail = null; message = rex.getMessage(); rex.detail = detail; // We frequently create remote exceptions with an empty message // to avoid redundant messages being printed in stack traces. If the // remote exception has an empty message, use the detail. d739198 if ("".equals(message) && detail != null) { message = getBaseMessage(detail); } } // ----------------------------------------------------------------------- // Other exceptions, like EJBException, do not contain a public field // that holds the 'cause'. So for these exceptions, the returned // message text is just parsed for the beginning of the nested // exceptions... and then truncated. // ----------------------------------------------------------------------- else if (exception != null) { message = exception.getMessage(); if (message != null) { if (message.startsWith("nested exception is:")) { message = null; } else { int nestIndex = message.indexOf("; nested exception is:"); if (nestIndex > -1) message = message.substring(0, nestIndex); } } } return message; } }
public class class_name { public static String getBaseMessage(Throwable exception) { String message = null; // ----------------------------------------------------------------------- // RemoteException contains a 'detail' field that holds the 'cause', // instead of the normal cause defined by Throwable. When detail is // set, getMessage() will include the text and stack of the detail, // which may ends up duplicating the message text. // // To avoid this, 'detail' is temporarily cleared, resulting in // getMessage() returning only the message text specified when the // RemoteException was created. d366807 // ----------------------------------------------------------------------- if (exception instanceof RemoteException) { RemoteException rex = (RemoteException) exception; Throwable detail = rex.detail; rex.detail = null; // depends on control dependency: [if], data = [none] message = rex.getMessage(); // depends on control dependency: [if], data = [none] rex.detail = detail; // depends on control dependency: [if], data = [none] // We frequently create remote exceptions with an empty message // to avoid redundant messages being printed in stack traces. If the // remote exception has an empty message, use the detail. d739198 if ("".equals(message) && detail != null) { message = getBaseMessage(detail); // depends on control dependency: [if], data = [none] } } // ----------------------------------------------------------------------- // Other exceptions, like EJBException, do not contain a public field // that holds the 'cause'. So for these exceptions, the returned // message text is just parsed for the beginning of the nested // exceptions... and then truncated. // ----------------------------------------------------------------------- else if (exception != null) { message = exception.getMessage(); // depends on control dependency: [if], data = [none] if (message != null) { if (message.startsWith("nested exception is:")) { message = null; // depends on control dependency: [if], data = [none] } else { int nestIndex = message.indexOf("; nested exception is:"); if (nestIndex > -1) message = message.substring(0, nestIndex); } } } return message; } }
public class class_name { static void initDefaultHandlers() { if (config != null && config.getDefaultHandlers() != null) { defaultHandlers = getHandlersFromExecList(config.getDefaultHandlers()); handlerListById.put("defaultHandlers", defaultHandlers); } } }
public class class_name { static void initDefaultHandlers() { if (config != null && config.getDefaultHandlers() != null) { defaultHandlers = getHandlersFromExecList(config.getDefaultHandlers()); // depends on control dependency: [if], data = [(config] handlerListById.put("defaultHandlers", defaultHandlers); // depends on control dependency: [if], data = [none] } } }
public class class_name { private <I, V, O extends Option<I, V>> OptionsContainer getMostSpecificContainer(Class<O> optionType) { OptionsContainer container; if ( propertyName != null ) { for ( Class<?> clazz : hierarchy ) { for ( OptionValueSource source : sources ) { container = source.getPropertyOptions( clazz, propertyName ); if ( !container.getAll( optionType ).isEmpty() ) { return container; } } } } if ( entityType != null ) { for ( Class<?> clazz : hierarchy ) { for ( OptionValueSource source : sources ) { container = source.getEntityOptions( clazz ); if ( !container.getAll( optionType ).isEmpty() ) { return container; } } } } for ( OptionValueSource source : sources ) { container = source.getGlobalOptions(); if ( !container.getAll( optionType ).isEmpty() ) { return container; } } return OptionsContainer.EMPTY; } }
public class class_name { private <I, V, O extends Option<I, V>> OptionsContainer getMostSpecificContainer(Class<O> optionType) { OptionsContainer container; if ( propertyName != null ) { for ( Class<?> clazz : hierarchy ) { for ( OptionValueSource source : sources ) { container = source.getPropertyOptions( clazz, propertyName ); // depends on control dependency: [for], data = [source] if ( !container.getAll( optionType ).isEmpty() ) { return container; // depends on control dependency: [if], data = [none] } } } } if ( entityType != null ) { for ( Class<?> clazz : hierarchy ) { for ( OptionValueSource source : sources ) { container = source.getEntityOptions( clazz ); // depends on control dependency: [for], data = [source] if ( !container.getAll( optionType ).isEmpty() ) { return container; // depends on control dependency: [if], data = [none] } } } } for ( OptionValueSource source : sources ) { container = source.getGlobalOptions(); // depends on control dependency: [for], data = [source] if ( !container.getAll( optionType ).isEmpty() ) { return container; // depends on control dependency: [if], data = [none] } } return OptionsContainer.EMPTY; } }
public class class_name { @Nullable private Integer waitFor(Process process) { try { return process.waitFor(); } catch (InterruptedException e) { log.info("interrupted in Process.waitFor"); return null; } } }
public class class_name { @Nullable private Integer waitFor(Process process) { try { return process.waitFor(); // depends on control dependency: [try], data = [none] } catch (InterruptedException e) { log.info("interrupted in Process.waitFor"); return null; } // depends on control dependency: [catch], data = [none] } }
public class class_name { public TemporalAccessor parse(CharSequence text, ParsePosition position) { Objects.requireNonNull(text, "text"); Objects.requireNonNull(position, "position"); try { return parseResolved0(text, position); } catch (DateTimeParseException | IndexOutOfBoundsException ex) { throw ex; } catch (RuntimeException ex) { throw createError(text, ex); } } }
public class class_name { public TemporalAccessor parse(CharSequence text, ParsePosition position) { Objects.requireNonNull(text, "text"); Objects.requireNonNull(position, "position"); try { return parseResolved0(text, position); // depends on control dependency: [try], data = [none] } catch (DateTimeParseException | IndexOutOfBoundsException ex) { throw ex; } catch (RuntimeException ex) { // depends on control dependency: [catch], data = [none] throw createError(text, ex); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private void transitiveDeps(int depth) throws IOException { Stream<Location> deps = archives.stream() .flatMap(Archive::getDependencies); Deque<Location> unresolved = deps.collect(Collectors.toCollection(LinkedList::new)); ConcurrentLinkedDeque<Location> deque = new ConcurrentLinkedDeque<>(); do { Location target; while ((target = unresolved.poll()) != null) { if (finder.isParsed(target)) continue; Archive archive = configuration.findClass(target).orElse(null); if (archive != null) { archives.add(archive); String name = target.getName(); Set<Location> targets = apiOnly ? finder.parseExportedAPIs(archive, name) : finder.parse(archive, name); // build unresolved dependencies targets.stream() .filter(t -> !finder.isParsed(t)) .forEach(deque::add); } } unresolved = deque; deque = new ConcurrentLinkedDeque<>(); } while (!unresolved.isEmpty() && depth-- > 0); } }
public class class_name { private void transitiveDeps(int depth) throws IOException { Stream<Location> deps = archives.stream() .flatMap(Archive::getDependencies); Deque<Location> unresolved = deps.collect(Collectors.toCollection(LinkedList::new)); ConcurrentLinkedDeque<Location> deque = new ConcurrentLinkedDeque<>(); do { Location target; while ((target = unresolved.poll()) != null) { if (finder.isParsed(target)) continue; Archive archive = configuration.findClass(target).orElse(null); if (archive != null) { archives.add(archive); // depends on control dependency: [if], data = [(archive] String name = target.getName(); Set<Location> targets = apiOnly ? finder.parseExportedAPIs(archive, name) : finder.parse(archive, name); // build unresolved dependencies targets.stream() .filter(t -> !finder.isParsed(t)) .forEach(deque::add); // depends on control dependency: [if], data = [none] } } unresolved = deque; deque = new ConcurrentLinkedDeque<>(); } while (!unresolved.isEmpty() && depth-- > 0); } }
public class class_name { public static void setFollowRedirects(boolean set) { SecurityManager sec = System.getSecurityManager(); if (sec != null) { // seems to be the best check here... sec.checkSetFactory(); } followRedirects = set; } }
public class class_name { public static void setFollowRedirects(boolean set) { SecurityManager sec = System.getSecurityManager(); if (sec != null) { // seems to be the best check here... sec.checkSetFactory(); // depends on control dependency: [if], data = [none] } followRedirects = set; } }
public class class_name { @Restricted(NoExternalUse.class) public List<DisplayExecutor> getDisplayExecutors() { // The size may change while we are populating, but let's start with a reasonable guess to minimize resizing List<DisplayExecutor> result = new ArrayList<>(executors.size() + oneOffExecutors.size()); int index = 0; for (Executor e: executors) { if (e.isDisplayCell()) { result.add(new DisplayExecutor(Integer.toString(index + 1), String.format("executors/%d", index), e)); } index++; } index = 0; for (OneOffExecutor e: oneOffExecutors) { if (e.isDisplayCell()) { result.add(new DisplayExecutor("", String.format("oneOffExecutors/%d", index), e)); } index++; } return result; } }
public class class_name { @Restricted(NoExternalUse.class) public List<DisplayExecutor> getDisplayExecutors() { // The size may change while we are populating, but let's start with a reasonable guess to minimize resizing List<DisplayExecutor> result = new ArrayList<>(executors.size() + oneOffExecutors.size()); int index = 0; for (Executor e: executors) { if (e.isDisplayCell()) { result.add(new DisplayExecutor(Integer.toString(index + 1), String.format("executors/%d", index), e)); // depends on control dependency: [if], data = [none] } index++; // depends on control dependency: [for], data = [e] } index = 0; for (OneOffExecutor e: oneOffExecutors) { if (e.isDisplayCell()) { result.add(new DisplayExecutor("", String.format("oneOffExecutors/%d", index), e)); // depends on control dependency: [if], data = [none] } index++; // depends on control dependency: [for], data = [e] } return result; } }
public class class_name { public List<EventData> parse(Long pipelineId, List<Entry> datas) throws SelectException { List<EventData> eventDatas = new ArrayList<EventData>(); Pipeline pipeline = configClientService.findPipeline(pipelineId); List<Entry> transactionDataBuffer = new ArrayList<Entry>(); // hz为主站点,us->hz的数据,需要回环同步会us。并且需要开启回环补救算法 PipelineParameter pipelineParameter = pipeline.getParameters(); boolean enableLoopbackRemedy = pipelineParameter.isEnableRemedy() && pipelineParameter.isHome() && pipelineParameter.getRemedyAlgorithm().isLoopback(); boolean isLoopback = false; boolean needLoopback = false; // 判断是否属于需要loopback处理的类型,只处理正常otter同步产生的回环数据,因为会有业务方手工屏蔽同步的接口,避免回环 long now = new Date().getTime(); try { for (Entry entry : datas) { switch (entry.getEntryType()) { case TRANSACTIONBEGIN: isLoopback = false; break; case ROWDATA: String tableName = entry.getHeader().getTableName(); // 判断是否是回环表retl_mark boolean isMarkTable = tableName.equalsIgnoreCase(pipeline.getParameters().getSystemMarkTable()); if (isMarkTable) { RowChange rowChange = RowChange.parseFrom(entry.getStoreValue()); if (!rowChange.getIsDdl()) { int loopback = 0; if (rowChange.getRowDatasCount() > 0) { loopback = checkLoopback(pipeline, rowChange.getRowDatas(0)); } if (loopback == 2) { needLoopback |= true; // 只处理正常同步产生的回环数据 } isLoopback |= loopback > 0; } } // 检查下otter3.0的回环表,对应的schmea会比较随意,所以不做比较 boolean isCompatibleLoopback = tableName.equalsIgnoreCase(compatibleMarkTable); if (isCompatibleLoopback) { RowChange rowChange = RowChange.parseFrom(entry.getStoreValue()); if (!rowChange.getIsDdl()) { int loopback = 0; if (rowChange.getRowDatasCount() > 0) { loopback = checkCompatibleLoopback(pipeline, rowChange.getRowDatas(0)); } if (loopback == 2) { needLoopback |= true; // 只处理正常同步产生的回环数据 } isLoopback |= loopback > 0; } } if ((!isLoopback || (enableLoopbackRemedy && needLoopback)) && !isMarkTable && !isCompatibleLoopback) { transactionDataBuffer.add(entry); } break; case TRANSACTIONEND: if (!isLoopback || (enableLoopbackRemedy && needLoopback)) { // 添加数据解析 for (Entry bufferEntry : transactionDataBuffer) { List<EventData> parseDatas = internParse(pipeline, bufferEntry); if (CollectionUtils.isEmpty(parseDatas)) {// 可能为空,针对ddl返回时就为null continue; } // 初步计算一下事件大小 long totalSize = bufferEntry.getHeader().getEventLength(); long eachSize = totalSize / parseDatas.size(); for (EventData eventData : parseDatas) { if (eventData == null) { continue; } eventData.setSize(eachSize);// 记录一下大小 if (needLoopback) {// 针对需要回环同步的 // 如果延迟超过指定的阀值,则设置为需要反查db if (now - eventData.getExecuteTime() > 1000 * pipeline.getParameters() .getRemedyDelayThresoldForMedia()) { eventData.setSyncConsistency(SyncConsistency.MEDIA); } else { eventData.setSyncConsistency(SyncConsistency.BASE); } eventData.setRemedy(true); } eventDatas.add(eventData); } } } isLoopback = false; needLoopback = false; transactionDataBuffer.clear(); break; default: break; } } // 添加最后一次的数据,可能没有TRANSACTIONEND if (!isLoopback || (enableLoopbackRemedy && needLoopback)) { // 添加数据解析 for (Entry bufferEntry : transactionDataBuffer) { List<EventData> parseDatas = internParse(pipeline, bufferEntry); if (CollectionUtils.isEmpty(parseDatas)) {// 可能为空,针对ddl返回时就为null continue; } // 初步计算一下事件大小 long totalSize = bufferEntry.getHeader().getEventLength(); long eachSize = totalSize / parseDatas.size(); for (EventData eventData : parseDatas) { if (eventData == null) { continue; } eventData.setSize(eachSize);// 记录一下大小 if (needLoopback) {// 针对需要回环同步的 // 如果延迟超过指定的阀值,则设置为需要反查db if (now - eventData.getExecuteTime() > 1000 * pipeline.getParameters() .getRemedyDelayThresoldForMedia()) { eventData.setSyncConsistency(SyncConsistency.MEDIA); } else { eventData.setSyncConsistency(SyncConsistency.BASE); } } eventDatas.add(eventData); } } } } catch (Exception e) { throw new SelectException(e); } return eventDatas; } }
public class class_name { public List<EventData> parse(Long pipelineId, List<Entry> datas) throws SelectException { List<EventData> eventDatas = new ArrayList<EventData>(); Pipeline pipeline = configClientService.findPipeline(pipelineId); List<Entry> transactionDataBuffer = new ArrayList<Entry>(); // hz为主站点,us->hz的数据,需要回环同步会us。并且需要开启回环补救算法 PipelineParameter pipelineParameter = pipeline.getParameters(); boolean enableLoopbackRemedy = pipelineParameter.isEnableRemedy() && pipelineParameter.isHome() && pipelineParameter.getRemedyAlgorithm().isLoopback(); boolean isLoopback = false; boolean needLoopback = false; // 判断是否属于需要loopback处理的类型,只处理正常otter同步产生的回环数据,因为会有业务方手工屏蔽同步的接口,避免回环 long now = new Date().getTime(); try { for (Entry entry : datas) { switch (entry.getEntryType()) { case TRANSACTIONBEGIN: isLoopback = false; break; case ROWDATA: String tableName = entry.getHeader().getTableName(); // 判断是否是回环表retl_mark boolean isMarkTable = tableName.equalsIgnoreCase(pipeline.getParameters().getSystemMarkTable()); if (isMarkTable) { RowChange rowChange = RowChange.parseFrom(entry.getStoreValue()); if (!rowChange.getIsDdl()) { int loopback = 0; if (rowChange.getRowDatasCount() > 0) { loopback = checkLoopback(pipeline, rowChange.getRowDatas(0)); // depends on control dependency: [if], data = [0)] } if (loopback == 2) { needLoopback |= true; // 只处理正常同步产生的回环数据 // depends on control dependency: [if], data = [none] } isLoopback |= loopback > 0; // depends on control dependency: [if], data = [none] } } // 检查下otter3.0的回环表,对应的schmea会比较随意,所以不做比较 boolean isCompatibleLoopback = tableName.equalsIgnoreCase(compatibleMarkTable); if (isCompatibleLoopback) { RowChange rowChange = RowChange.parseFrom(entry.getStoreValue()); if (!rowChange.getIsDdl()) { int loopback = 0; if (rowChange.getRowDatasCount() > 0) { loopback = checkCompatibleLoopback(pipeline, rowChange.getRowDatas(0)); // depends on control dependency: [if], data = [0)] } if (loopback == 2) { needLoopback |= true; // 只处理正常同步产生的回环数据 // depends on control dependency: [if], data = [none] } isLoopback |= loopback > 0; // depends on control dependency: [if], data = [none] } } if ((!isLoopback || (enableLoopbackRemedy && needLoopback)) && !isMarkTable && !isCompatibleLoopback) { transactionDataBuffer.add(entry); // depends on control dependency: [if], data = [none] } break; case TRANSACTIONEND: if (!isLoopback || (enableLoopbackRemedy && needLoopback)) { // 添加数据解析 for (Entry bufferEntry : transactionDataBuffer) { List<EventData> parseDatas = internParse(pipeline, bufferEntry); if (CollectionUtils.isEmpty(parseDatas)) {// 可能为空,针对ddl返回时就为null continue; } // 初步计算一下事件大小 long totalSize = bufferEntry.getHeader().getEventLength(); long eachSize = totalSize / parseDatas.size(); for (EventData eventData : parseDatas) { if (eventData == null) { continue; } eventData.setSize(eachSize);// 记录一下大小 // depends on control dependency: [for], data = [eventData] if (needLoopback) {// 针对需要回环同步的 // 如果延迟超过指定的阀值,则设置为需要反查db if (now - eventData.getExecuteTime() > 1000 * pipeline.getParameters() .getRemedyDelayThresoldForMedia()) { eventData.setSyncConsistency(SyncConsistency.MEDIA); // depends on control dependency: [if], data = [none] } else { eventData.setSyncConsistency(SyncConsistency.BASE); // depends on control dependency: [if], data = [none] } eventData.setRemedy(true); // depends on control dependency: [if], data = [none] } eventDatas.add(eventData); // depends on control dependency: [for], data = [eventData] } } } isLoopback = false; needLoopback = false; transactionDataBuffer.clear(); break; default: break; } } // 添加最后一次的数据,可能没有TRANSACTIONEND if (!isLoopback || (enableLoopbackRemedy && needLoopback)) { // 添加数据解析 for (Entry bufferEntry : transactionDataBuffer) { List<EventData> parseDatas = internParse(pipeline, bufferEntry); if (CollectionUtils.isEmpty(parseDatas)) {// 可能为空,针对ddl返回时就为null continue; } // 初步计算一下事件大小 long totalSize = bufferEntry.getHeader().getEventLength(); long eachSize = totalSize / parseDatas.size(); for (EventData eventData : parseDatas) { if (eventData == null) { continue; } eventData.setSize(eachSize);// 记录一下大小 // depends on control dependency: [for], data = [eventData] if (needLoopback) {// 针对需要回环同步的 // 如果延迟超过指定的阀值,则设置为需要反查db if (now - eventData.getExecuteTime() > 1000 * pipeline.getParameters() .getRemedyDelayThresoldForMedia()) { eventData.setSyncConsistency(SyncConsistency.MEDIA); // depends on control dependency: [if], data = [none] } else { eventData.setSyncConsistency(SyncConsistency.BASE); // depends on control dependency: [if], data = [none] } } eventDatas.add(eventData); // depends on control dependency: [for], data = [eventData] } } } } catch (Exception e) { throw new SelectException(e); } return eventDatas; } }
public class class_name { public String convertToJavaString(String input, boolean useUnicode) { int length = input.length(); StringBuilder result = new StringBuilder(length + 4); for (int i = 0; i < length; i++) { escapeAndAppendTo(input.charAt(i), useUnicode, result); } return result.toString(); } }
public class class_name { public String convertToJavaString(String input, boolean useUnicode) { int length = input.length(); StringBuilder result = new StringBuilder(length + 4); for (int i = 0; i < length; i++) { escapeAndAppendTo(input.charAt(i), useUnicode, result); // depends on control dependency: [for], data = [i] } return result.toString(); } }
public class class_name { public void write() { root.accept(visitor); try { Backup.backup(root.getFilename()); } catch (IOException e) { logger.error("Problem backing up old copy of GEDCOM file", e); } final String filename = root.getFilename(); final String charset = new CharsetScanner().charset(root); try (FileOutputStream fstream = new FileOutputStream(filename); BufferedOutputStream bstream = new BufferedOutputStream( fstream)) { writeTheLines(bstream, charset); } catch (IOException e) { logger.error("Problem writing GEDCOM file", e); } } }
public class class_name { public void write() { root.accept(visitor); try { Backup.backup(root.getFilename()); // depends on control dependency: [try], data = [none] } catch (IOException e) { logger.error("Problem backing up old copy of GEDCOM file", e); } // depends on control dependency: [catch], data = [none] final String filename = root.getFilename(); final String charset = new CharsetScanner().charset(root); try (FileOutputStream fstream = new FileOutputStream(filename); BufferedOutputStream bstream = new BufferedOutputStream( fstream)) { writeTheLines(bstream, charset); } catch (IOException e) { logger.error("Problem writing GEDCOM file", e); } } }
public class class_name { public GobblinMetrics getOrDefault(String id, Callable<? extends GobblinMetrics> valueLoader) { try { return this.metricsCache.get(id, valueLoader); } catch (ExecutionException ee) { throw Throwables.propagate(ee); } } }
public class class_name { public GobblinMetrics getOrDefault(String id, Callable<? extends GobblinMetrics> valueLoader) { try { return this.metricsCache.get(id, valueLoader); // depends on control dependency: [try], data = [none] } catch (ExecutionException ee) { throw Throwables.propagate(ee); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static boolean isPositiveInteger(String s) { if (isEmpty(s)) return defaultEmptyOK; try { long temp = Long.parseLong(s); if (temp > 0) return true; return false; } catch (Exception e) { return false; } // return(isSignedInteger(s, secondArg) // &&((isEmpty(s) && secondArg) ||(parseInt(s) > 0) ) ); } }
public class class_name { public static boolean isPositiveInteger(String s) { if (isEmpty(s)) return defaultEmptyOK; try { long temp = Long.parseLong(s); if (temp > 0) return true; return false; // depends on control dependency: [try], data = [none] } catch (Exception e) { return false; } // depends on control dependency: [catch], data = [none] // return(isSignedInteger(s, secondArg) // &&((isEmpty(s) && secondArg) ||(parseInt(s) > 0) ) ); } }
public class class_name { private Expression convertWithoutParens(ExpressionTree condition, TreePath parent) { Expression result = (Expression) convert(condition, parent); if (result.getKind() == TreeNode.Kind.PARENTHESIZED_EXPRESSION) { result = TreeUtil.remove(((ParenthesizedExpression) result).getExpression()); } return result; } }
public class class_name { private Expression convertWithoutParens(ExpressionTree condition, TreePath parent) { Expression result = (Expression) convert(condition, parent); if (result.getKind() == TreeNode.Kind.PARENTHESIZED_EXPRESSION) { result = TreeUtil.remove(((ParenthesizedExpression) result).getExpression()); // depends on control dependency: [if], data = [none] } return result; } }
public class class_name { public static Object typeConvert(Object val, String esType) { if (val == null) { return null; } if (esType == null) { return val; } Object res = null; if ("integer".equals(esType)) { if (val instanceof Number) { res = ((Number) val).intValue(); } else { res = Integer.parseInt(val.toString()); } } else if ("long".equals(esType)) { if (val instanceof Number) { res = ((Number) val).longValue(); } else { res = Long.parseLong(val.toString()); } } else if ("short".equals(esType)) { if (val instanceof Number) { res = ((Number) val).shortValue(); } else { res = Short.parseShort(val.toString()); } } else if ("byte".equals(esType)) { if (val instanceof Number) { res = ((Number) val).byteValue(); } else { res = Byte.parseByte(val.toString()); } } else if ("double".equals(esType)) { if (val instanceof Number) { res = ((Number) val).doubleValue(); } else { res = Double.parseDouble(val.toString()); } } else if ("float".equals(esType) || "half_float".equals(esType) || "scaled_float".equals(esType)) { if (val instanceof Number) { res = ((Number) val).floatValue(); } else { res = Float.parseFloat(val.toString()); } } else if ("boolean".equals(esType)) { if (val instanceof Boolean) { res = val; } else if (val instanceof Number) { int v = ((Number) val).intValue(); res = v != 0; } else { res = Boolean.parseBoolean(val.toString()); } } else if ("date".equals(esType)) { if (val instanceof java.sql.Time) { DateTime dateTime = new DateTime(((java.sql.Time) val).getTime()); if (dateTime.getMillisOfSecond() != 0) { res = dateTime.toString("HH:mm:ss.SSS"); } else { res = dateTime.toString("HH:mm:ss"); } } else if (val instanceof java.sql.Timestamp) { DateTime dateTime = new DateTime(((java.sql.Timestamp) val).getTime()); if (dateTime.getMillisOfSecond() != 0) { res = dateTime.toString("yyyy-MM-dd'T'HH:mm:ss.SSS" + Util.timeZone); } else { res = dateTime.toString("yyyy-MM-dd'T'HH:mm:ss" + Util.timeZone); } } else if (val instanceof java.sql.Date || val instanceof Date) { DateTime dateTime; if (val instanceof java.sql.Date) { dateTime = new DateTime(((java.sql.Date) val).getTime()); } else { dateTime = new DateTime(((Date) val).getTime()); } if (dateTime.getHourOfDay() == 0 && dateTime.getMinuteOfHour() == 0 && dateTime.getSecondOfMinute() == 0 && dateTime.getMillisOfSecond() == 0) { res = dateTime.toString("yyyy-MM-dd"); } else { if (dateTime.getMillisOfSecond() != 0) { res = dateTime.toString("yyyy-MM-dd'T'HH:mm:ss.SSS" + Util.timeZone); } else { res = dateTime.toString("yyyy-MM-dd'T'HH:mm:ss" + Util.timeZone); } } } else if (val instanceof Long) { DateTime dateTime = new DateTime(((Long) val).longValue()); if (dateTime.getHourOfDay() == 0 && dateTime.getMinuteOfHour() == 0 && dateTime.getSecondOfMinute() == 0 && dateTime.getMillisOfSecond() == 0) { res = dateTime.toString("yyyy-MM-dd"); } else if (dateTime.getMillisOfSecond() != 0) { res = dateTime.toString("yyyy-MM-dd'T'HH:mm:ss.SSS" + Util.timeZone); } else { res = dateTime.toString("yyyy-MM-dd'T'HH:mm:ss" + Util.timeZone); } } else if (val instanceof String) { String v = ((String) val).trim(); if (v.length() > 18 && v.charAt(4) == '-' && v.charAt(7) == '-' && v.charAt(10) == ' ' && v.charAt(13) == ':' && v.charAt(16) == ':') { String dt = v.substring(0, 10) + "T" + v.substring(11); Date date = Util.parseDate(dt); if (date != null) { DateTime dateTime = new DateTime(date); if (dateTime.getMillisOfSecond() != 0) { res = dateTime.toString("yyyy-MM-dd'T'HH:mm:ss.SSS" + Util.timeZone); } else { res = dateTime.toString("yyyy-MM-dd'T'HH:mm:ss" + Util.timeZone); } } } else if (v.length() == 10 && v.charAt(4) == '-' && v.charAt(7) == '-') { Date date = Util.parseDate(v); if (date != null) { DateTime dateTime = new DateTime(date); res = dateTime.toString("yyyy-MM-dd"); } } } } else if ("binary".equals(esType)) { if (val instanceof byte[]) { Base64 base64 = new Base64(); res = base64.encodeAsString((byte[]) val); } else if (val instanceof Blob) { byte[] b = blobToBytes((Blob) val); Base64 base64 = new Base64(); res = base64.encodeAsString(b); } else if (val instanceof String) { // 对应canal中的单字节编码 byte[] b = ((String) val).getBytes(StandardCharsets.ISO_8859_1); Base64 base64 = new Base64(); res = base64.encodeAsString(b); } } else if ("geo_point".equals(esType)) { if (!(val instanceof String)) { logger.error("es type is geo_point, but source type is not String"); return val; } if (!((String) val).contains(",")) { logger.error("es type is geo_point, source value not contains ',' separator"); return val; } String[] point = ((String) val).split(","); Map<String, Double> location = new HashMap<>(); location.put("lat", Double.valueOf(point[0].trim())); location.put("lon", Double.valueOf(point[1].trim())); return location; } else if ("array".equals(esType)) { if ("".equals(val.toString().trim())) { res = new ArrayList<>(); } else { String value = val.toString(); String separator = ","; if (!value.contains(",")) { if (value.contains(";")) { separator = ";"; } else if (value.contains("|")) { separator = "\\|"; } else if (value.contains("-")) { separator = "-"; } } String[] values = value.split(separator); return Arrays.asList(values); } } else if ("object".equals(esType)) { if ("".equals(val.toString().trim())) { res = new HashMap<>(); } else { res = JSON.parseObject(val.toString(), Map.class); } } else { // 其他类全以字符串处理 res = val.toString(); } return res; } }
public class class_name { public static Object typeConvert(Object val, String esType) { if (val == null) { return null; // depends on control dependency: [if], data = [none] } if (esType == null) { return val; // depends on control dependency: [if], data = [none] } Object res = null; if ("integer".equals(esType)) { if (val instanceof Number) { res = ((Number) val).intValue(); // depends on control dependency: [if], data = [none] } else { res = Integer.parseInt(val.toString()); // depends on control dependency: [if], data = [none] } } else if ("long".equals(esType)) { if (val instanceof Number) { res = ((Number) val).longValue(); // depends on control dependency: [if], data = [none] } else { res = Long.parseLong(val.toString()); // depends on control dependency: [if], data = [none] } } else if ("short".equals(esType)) { if (val instanceof Number) { res = ((Number) val).shortValue(); // depends on control dependency: [if], data = [none] } else { res = Short.parseShort(val.toString()); // depends on control dependency: [if], data = [none] } } else if ("byte".equals(esType)) { if (val instanceof Number) { res = ((Number) val).byteValue(); // depends on control dependency: [if], data = [none] } else { res = Byte.parseByte(val.toString()); // depends on control dependency: [if], data = [none] } } else if ("double".equals(esType)) { if (val instanceof Number) { res = ((Number) val).doubleValue(); // depends on control dependency: [if], data = [none] } else { res = Double.parseDouble(val.toString()); // depends on control dependency: [if], data = [none] } } else if ("float".equals(esType) || "half_float".equals(esType) || "scaled_float".equals(esType)) { if (val instanceof Number) { res = ((Number) val).floatValue(); // depends on control dependency: [if], data = [none] } else { res = Float.parseFloat(val.toString()); // depends on control dependency: [if], data = [none] } } else if ("boolean".equals(esType)) { if (val instanceof Boolean) { res = val; // depends on control dependency: [if], data = [none] } else if (val instanceof Number) { int v = ((Number) val).intValue(); res = v != 0; // depends on control dependency: [if], data = [none] } else { res = Boolean.parseBoolean(val.toString()); // depends on control dependency: [if], data = [none] } } else if ("date".equals(esType)) { if (val instanceof java.sql.Time) { DateTime dateTime = new DateTime(((java.sql.Time) val).getTime()); if (dateTime.getMillisOfSecond() != 0) { res = dateTime.toString("HH:mm:ss.SSS"); // depends on control dependency: [if], data = [none] } else { res = dateTime.toString("HH:mm:ss"); // depends on control dependency: [if], data = [none] } } else if (val instanceof java.sql.Timestamp) { DateTime dateTime = new DateTime(((java.sql.Timestamp) val).getTime()); if (dateTime.getMillisOfSecond() != 0) { res = dateTime.toString("yyyy-MM-dd'T'HH:mm:ss.SSS" + Util.timeZone); // depends on control dependency: [if], data = [none] } else { res = dateTime.toString("yyyy-MM-dd'T'HH:mm:ss" + Util.timeZone); // depends on control dependency: [if], data = [none] } } else if (val instanceof java.sql.Date || val instanceof Date) { DateTime dateTime; if (val instanceof java.sql.Date) { dateTime = new DateTime(((java.sql.Date) val).getTime()); // depends on control dependency: [if], data = [none] } else { dateTime = new DateTime(((Date) val).getTime()); // depends on control dependency: [if], data = [none] } if (dateTime.getHourOfDay() == 0 && dateTime.getMinuteOfHour() == 0 && dateTime.getSecondOfMinute() == 0 && dateTime.getMillisOfSecond() == 0) { res = dateTime.toString("yyyy-MM-dd"); // depends on control dependency: [if], data = [none] } else { if (dateTime.getMillisOfSecond() != 0) { res = dateTime.toString("yyyy-MM-dd'T'HH:mm:ss.SSS" + Util.timeZone); // depends on control dependency: [if], data = [none] } else { res = dateTime.toString("yyyy-MM-dd'T'HH:mm:ss" + Util.timeZone); // depends on control dependency: [if], data = [none] } } } else if (val instanceof Long) { DateTime dateTime = new DateTime(((Long) val).longValue()); if (dateTime.getHourOfDay() == 0 && dateTime.getMinuteOfHour() == 0 && dateTime.getSecondOfMinute() == 0 && dateTime.getMillisOfSecond() == 0) { res = dateTime.toString("yyyy-MM-dd"); // depends on control dependency: [if], data = [none] } else if (dateTime.getMillisOfSecond() != 0) { res = dateTime.toString("yyyy-MM-dd'T'HH:mm:ss.SSS" + Util.timeZone); // depends on control dependency: [if], data = [none] } else { res = dateTime.toString("yyyy-MM-dd'T'HH:mm:ss" + Util.timeZone); // depends on control dependency: [if], data = [none] } } else if (val instanceof String) { String v = ((String) val).trim(); if (v.length() > 18 && v.charAt(4) == '-' && v.charAt(7) == '-' && v.charAt(10) == ' ' && v.charAt(13) == ':' && v.charAt(16) == ':') { String dt = v.substring(0, 10) + "T" + v.substring(11); Date date = Util.parseDate(dt); if (date != null) { DateTime dateTime = new DateTime(date); if (dateTime.getMillisOfSecond() != 0) { res = dateTime.toString("yyyy-MM-dd'T'HH:mm:ss.SSS" + Util.timeZone); // depends on control dependency: [if], data = [none] } else { res = dateTime.toString("yyyy-MM-dd'T'HH:mm:ss" + Util.timeZone); // depends on control dependency: [if], data = [none] } } } else if (v.length() == 10 && v.charAt(4) == '-' && v.charAt(7) == '-') { Date date = Util.parseDate(v); if (date != null) { DateTime dateTime = new DateTime(date); res = dateTime.toString("yyyy-MM-dd"); // depends on control dependency: [if], data = [none] } } } } else if ("binary".equals(esType)) { if (val instanceof byte[]) { Base64 base64 = new Base64(); res = base64.encodeAsString((byte[]) val); // depends on control dependency: [if], data = [none] } else if (val instanceof Blob) { byte[] b = blobToBytes((Blob) val); Base64 base64 = new Base64(); res = base64.encodeAsString(b); // depends on control dependency: [if], data = [none] } else if (val instanceof String) { // 对应canal中的单字节编码 byte[] b = ((String) val).getBytes(StandardCharsets.ISO_8859_1); Base64 base64 = new Base64(); res = base64.encodeAsString(b); // depends on control dependency: [if], data = [none] } } else if ("geo_point".equals(esType)) { if (!(val instanceof String)) { logger.error("es type is geo_point, but source type is not String"); // depends on control dependency: [if], data = [none] return val; // depends on control dependency: [if], data = [none] } if (!((String) val).contains(",")) { logger.error("es type is geo_point, source value not contains ',' separator"); // depends on control dependency: [if], data = [none] return val; // depends on control dependency: [if], data = [none] } String[] point = ((String) val).split(","); Map<String, Double> location = new HashMap<>(); location.put("lat", Double.valueOf(point[0].trim())); // depends on control dependency: [if], data = [none] location.put("lon", Double.valueOf(point[1].trim())); // depends on control dependency: [if], data = [none] return location; // depends on control dependency: [if], data = [none] } else if ("array".equals(esType)) { if ("".equals(val.toString().trim())) { res = new ArrayList<>(); // depends on control dependency: [if], data = [none] } else { String value = val.toString(); String separator = ","; if (!value.contains(",")) { if (value.contains(";")) { separator = ";"; // depends on control dependency: [if], data = [none] } else if (value.contains("|")) { separator = "\\|"; // depends on control dependency: [if], data = [none] } else if (value.contains("-")) { separator = "-"; // depends on control dependency: [if], data = [none] } } String[] values = value.split(separator); return Arrays.asList(values); // depends on control dependency: [if], data = [none] } } else if ("object".equals(esType)) { if ("".equals(val.toString().trim())) { res = new HashMap<>(); // depends on control dependency: [if], data = [none] } else { res = JSON.parseObject(val.toString(), Map.class); // depends on control dependency: [if], data = [none] } } else { // 其他类全以字符串处理 res = val.toString(); // depends on control dependency: [if], data = [none] } return res; } }
public class class_name { public String fuzzyOutputValue() { StringBuilder sb = new StringBuilder(); Iterator<Term> it = getTerms().iterator(); if (it.hasNext()) { Term term = it.next(); double degree = fuzzyOutput.activationDegree(term); sb.append(Op.str(degree)).append("/").append(term.getName()); while (it.hasNext()) { term = it.next(); degree = fuzzyOutput.activationDegree(term); if (Double.isNaN(degree) || Op.isGE(degree, 0.0)) { sb.append(" + ").append(Op.str(degree)); } else { sb.append(" - ").append(Op.str(Math.abs(degree))); } sb.append("/").append(term.getName()); } } return sb.toString(); } }
public class class_name { public String fuzzyOutputValue() { StringBuilder sb = new StringBuilder(); Iterator<Term> it = getTerms().iterator(); if (it.hasNext()) { Term term = it.next(); double degree = fuzzyOutput.activationDegree(term); sb.append(Op.str(degree)).append("/").append(term.getName()); // depends on control dependency: [if], data = [none] while (it.hasNext()) { term = it.next(); // depends on control dependency: [while], data = [none] degree = fuzzyOutput.activationDegree(term); // depends on control dependency: [while], data = [none] if (Double.isNaN(degree) || Op.isGE(degree, 0.0)) { sb.append(" + ").append(Op.str(degree)); // depends on control dependency: [if], data = [none] } else { sb.append(" - ").append(Op.str(Math.abs(degree))); // depends on control dependency: [if], data = [none] } sb.append("/").append(term.getName()); // depends on control dependency: [while], data = [none] } } return sb.toString(); } }
public class class_name { public static boolean fixSalt(Document doc) { Element root = doc.getDocumentElement(); String salt = root.getAttribute("salt"); if (StringUtil.isEmpty(salt, true) || !Decision.isUUId(salt)) { // create salt root.setAttribute("salt", CreateUUID.invoke()); return true; } return false; } }
public class class_name { public static boolean fixSalt(Document doc) { Element root = doc.getDocumentElement(); String salt = root.getAttribute("salt"); if (StringUtil.isEmpty(salt, true) || !Decision.isUUId(salt)) { // create salt root.setAttribute("salt", CreateUUID.invoke()); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } return false; } }
public class class_name { protected void addSorting(CmsSelectQuery select, TableAlias users, CmsUserSearchParameters searchParams) { boolean ascending = searchParams.isAscending(); String ordering = getSortExpression(users, searchParams); if (ascending) { ordering += " ASC"; } else { ordering += " DESC"; } select.setOrdering(ordering); } }
public class class_name { protected void addSorting(CmsSelectQuery select, TableAlias users, CmsUserSearchParameters searchParams) { boolean ascending = searchParams.isAscending(); String ordering = getSortExpression(users, searchParams); if (ascending) { ordering += " ASC"; // depends on control dependency: [if], data = [none] } else { ordering += " DESC"; // depends on control dependency: [if], data = [none] } select.setOrdering(ordering); } }
public class class_name { public QueryFind buildFind(IAssetType assetType) { String searchString = find.getSearchString(); if ((searchString != null) && (searchString.trim().length() != 0)) { AttributeSelection attributes = new AttributeSelection(); if (find.fields.size() > 0) { for (String field : find.fields) { attributes .add(assetType .getAttributeDefinition(resolvePropertyName(field))); } } else { if (assetType.getShortNameAttribute() != null) { attributes.add(assetType.getShortNameAttribute()); } if (assetType.getNameAttribute() != null) { attributes.add(assetType.getNameAttribute()); } if (assetType.getDescriptionAttribute() != null) { attributes.add(assetType.getDescriptionAttribute()); } } return new QueryFind(find.getSearchString(), attributes); } return null; } }
public class class_name { public QueryFind buildFind(IAssetType assetType) { String searchString = find.getSearchString(); if ((searchString != null) && (searchString.trim().length() != 0)) { AttributeSelection attributes = new AttributeSelection(); if (find.fields.size() > 0) { for (String field : find.fields) { attributes .add(assetType .getAttributeDefinition(resolvePropertyName(field))); // depends on control dependency: [for], data = [none] } } else { if (assetType.getShortNameAttribute() != null) { attributes.add(assetType.getShortNameAttribute()); // depends on control dependency: [if], data = [(assetType.getShortNameAttribute()] } if (assetType.getNameAttribute() != null) { attributes.add(assetType.getNameAttribute()); // depends on control dependency: [if], data = [(assetType.getNameAttribute()] } if (assetType.getDescriptionAttribute() != null) { attributes.add(assetType.getDescriptionAttribute()); // depends on control dependency: [if], data = [(assetType.getDescriptionAttribute()] } } return new QueryFind(find.getSearchString(), attributes); // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { @Override public void announceMPStopping() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "announceMPStopping"); if (isPubSub()) { if (null != _pubSubRealization) { //doing a sanity check with checking for not null //signal to _pubSubRealization to gracefully exit from deleteMsgsWithNoReferences() _pubSubRealization.stopDeletingMsgsWihoutReferencesTask(true); } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "announceMPStopping"); } }
public class class_name { @Override public void announceMPStopping() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "announceMPStopping"); if (isPubSub()) { if (null != _pubSubRealization) { //doing a sanity check with checking for not null //signal to _pubSubRealization to gracefully exit from deleteMsgsWithNoReferences() _pubSubRealization.stopDeletingMsgsWihoutReferencesTask(true); // depends on control dependency: [if], data = [none] } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "announceMPStopping"); } }
public class class_name { private List<IAtomContainer> constructTautomers(IAtomContainer inputMolecule, List<Integer> mobHydrAttachPositions, int totalMobHydrCount) throws CloneNotSupportedException { List<IAtomContainer> tautomers = new ArrayList<IAtomContainer>(); //Tautomeric skeleton generation IAtomContainer skeleton = (IAtomContainer) inputMolecule.clone(); boolean atomsToRemove = true; List<IAtom> removedAtoms = new ArrayList<IAtom>(); boolean atomRemoved = false; while (atomsToRemove) { ATOMS: for (IAtom atom : skeleton.atoms()) { atomRemoved = false; int position = Integer.valueOf(atom.getID()); if (!mobHydrAttachPositions.contains(position) && atom.getHybridization().equals(IAtomType.Hybridization.SP3)) { skeleton.removeAtomOnly(atom); removedAtoms.add(atom); atomRemoved = true; break ATOMS; } else { for (IBond bond : skeleton.bonds()) { if (bond.contains(atom) && bond.getOrder().equals(IBond.Order.TRIPLE)) { skeleton.removeAtomOnly(atom); removedAtoms.add(atom); atomRemoved = true; break ATOMS; } } } } if (!atomRemoved) atomsToRemove = false; } boolean bondsToRemove = true; boolean bondRemoved = false; while (bondsToRemove) { BONDS: for (IBond bond : skeleton.bonds()) { bondRemoved = false; for (IAtom removedAtom : removedAtoms) { if (bond.contains(removedAtom)) { IAtom other = bond.getOther(removedAtom); int decValence = 0; switch (bond.getOrder()) { case SINGLE: decValence = 1; break; case DOUBLE: decValence = 2; break; case TRIPLE: decValence = 3; break; case QUADRUPLE: decValence = 4; break; } other.setValency(other.getValency() - decValence); skeleton.removeBond(bond); bondRemoved = true; break BONDS; } } } if (!bondRemoved) bondsToRemove = false; } int doubleBondCount = 0; for (IBond bond : skeleton.bonds()) { if (bond.getOrder().equals(IBond.Order.DOUBLE)) { bond.setOrder(IBond.Order.SINGLE); doubleBondCount++; } } for (int hPosition : mobHydrAttachPositions) { IAtom atom = findAtomByPosition(skeleton, hPosition); atom.setImplicitHydrogenCount(0); } // Make combinations for mobile Hydrogen attachments List<List<Integer>> combinations = new ArrayList<List<Integer>>(); combineHydrogenPositions(new ArrayList<Integer>(), combinations, skeleton, totalMobHydrCount, mobHydrAttachPositions); Stack<Object> solutions = new Stack<Object>(); for (List<Integer> hPositions : combinations) { IAtomContainer tautomerSkeleton = (IAtomContainer) skeleton.clone(); for (Integer hPos : hPositions) { IAtom atom = findAtomByPosition(tautomerSkeleton, hPos); atom.setImplicitHydrogenCount(atom.getImplicitHydrogenCount() + 1); } List<IAtom> atomsInNeedOfFix = new ArrayList<IAtom>(); for (IAtom atom : tautomerSkeleton.atoms()) { if (atom.getValency() - atom.getFormalCharge() != atom.getImplicitHydrogenCount() + getConnectivity(atom, tautomerSkeleton)) atomsInNeedOfFix.add(atom); } List<Integer> dblBondPositions = tryDoubleBondCombinations(tautomerSkeleton, 0, 0, doubleBondCount, atomsInNeedOfFix); if (dblBondPositions != null) { //Found a valid double bond combination for this mobile hydrogen configuration.. solutions.push(dblBondPositions); solutions.push(tautomerSkeleton); } } LOGGER.debug("#possible solutions : ", solutions.size()); if (solutions.size() == 0) { LOGGER.error("Could not generate any tautomers for the input. Is input in Kekule form? "); tautomers.add(inputMolecule); } else { while (solutions.size() != 0) { IAtomContainer tautomerSkeleton = (IAtomContainer) solutions.pop(); List<Integer> dblBondPositions = (List<Integer>) solutions.pop(); IAtomContainer tautomer = (IAtomContainer) inputMolecule.clone(); for (IAtom skAtom1 : tautomerSkeleton.atoms()) { for (IAtom atom1 : tautomer.atoms()) { if (atom1.getID().equals(skAtom1.getID())) { atom1.setImplicitHydrogenCount(skAtom1.getImplicitHydrogenCount()); for (int bondIdx = 0; bondIdx < tautomerSkeleton.getBondCount(); bondIdx++) { IBond skBond = tautomerSkeleton.getBond(bondIdx); if (skBond.contains(skAtom1)) { IAtom skAtom2 = skBond.getOther(skAtom1); for (IAtom atom2 : tautomer.atoms()) { if (atom2.getID().equals(skAtom2.getID())) { IBond tautBond = tautomer.getBond(atom1, atom2); if (dblBondPositions.contains(bondIdx)) tautBond.setOrder(IBond.Order.DOUBLE); else tautBond.setOrder(IBond.Order.SINGLE); } } } } } } } for (IAtom atom : tautomer.atoms()) { atom.setFlag(CDKConstants.ISAROMATIC, false); atom.setValency(null); } for (IBond bond : tautomer.bonds()) bond.setFlag(CDKConstants.ISAROMATIC, false); tautomers.add(tautomer); } } LOGGER.debug("# initial tautomers generated : ", tautomers.size()); return tautomers; } }
public class class_name { private List<IAtomContainer> constructTautomers(IAtomContainer inputMolecule, List<Integer> mobHydrAttachPositions, int totalMobHydrCount) throws CloneNotSupportedException { List<IAtomContainer> tautomers = new ArrayList<IAtomContainer>(); //Tautomeric skeleton generation IAtomContainer skeleton = (IAtomContainer) inputMolecule.clone(); boolean atomsToRemove = true; List<IAtom> removedAtoms = new ArrayList<IAtom>(); boolean atomRemoved = false; while (atomsToRemove) { ATOMS: for (IAtom atom : skeleton.atoms()) { atomRemoved = false; // depends on control dependency: [for], data = [atom] int position = Integer.valueOf(atom.getID()); if (!mobHydrAttachPositions.contains(position) && atom.getHybridization().equals(IAtomType.Hybridization.SP3)) { skeleton.removeAtomOnly(atom); // depends on control dependency: [if], data = [none] removedAtoms.add(atom); // depends on control dependency: [if], data = [none] atomRemoved = true; // depends on control dependency: [if], data = [none] break ATOMS; } else { for (IBond bond : skeleton.bonds()) { if (bond.contains(atom) && bond.getOrder().equals(IBond.Order.TRIPLE)) { skeleton.removeAtomOnly(atom); // depends on control dependency: [if], data = [none] removedAtoms.add(atom); // depends on control dependency: [if], data = [none] atomRemoved = true; // depends on control dependency: [if], data = [none] break ATOMS; } } } } if (!atomRemoved) atomsToRemove = false; } boolean bondsToRemove = true; boolean bondRemoved = false; while (bondsToRemove) { BONDS: for (IBond bond : skeleton.bonds()) { bondRemoved = false; // depends on control dependency: [for], data = [bond] for (IAtom removedAtom : removedAtoms) { if (bond.contains(removedAtom)) { IAtom other = bond.getOther(removedAtom); int decValence = 0; switch (bond.getOrder()) { case SINGLE: decValence = 1; break; case DOUBLE: decValence = 2; break; case TRIPLE: decValence = 3; break; case QUADRUPLE: decValence = 4; break; } other.setValency(other.getValency() - decValence); // depends on control dependency: [for], data = [none] skeleton.removeBond(bond); // depends on control dependency: [for], data = [none] bondRemoved = true; // depends on control dependency: [for], data = [none] break BONDS; } } } if (!bondRemoved) bondsToRemove = false; } int doubleBondCount = 0; for (IBond bond : skeleton.bonds()) { if (bond.getOrder().equals(IBond.Order.DOUBLE)) { bond.setOrder(IBond.Order.SINGLE); doubleBondCount++; } } for (int hPosition : mobHydrAttachPositions) { IAtom atom = findAtomByPosition(skeleton, hPosition); atom.setImplicitHydrogenCount(0); } // Make combinations for mobile Hydrogen attachments List<List<Integer>> combinations = new ArrayList<List<Integer>>(); combineHydrogenPositions(new ArrayList<Integer>(), combinations, skeleton, totalMobHydrCount, mobHydrAttachPositions); Stack<Object> solutions = new Stack<Object>(); for (List<Integer> hPositions : combinations) { IAtomContainer tautomerSkeleton = (IAtomContainer) skeleton.clone(); for (Integer hPos : hPositions) { IAtom atom = findAtomByPosition(tautomerSkeleton, hPos); atom.setImplicitHydrogenCount(atom.getImplicitHydrogenCount() + 1); } List<IAtom> atomsInNeedOfFix = new ArrayList<IAtom>(); for (IAtom atom : tautomerSkeleton.atoms()) { if (atom.getValency() - atom.getFormalCharge() != atom.getImplicitHydrogenCount() + getConnectivity(atom, tautomerSkeleton)) atomsInNeedOfFix.add(atom); } List<Integer> dblBondPositions = tryDoubleBondCombinations(tautomerSkeleton, 0, 0, doubleBondCount, atomsInNeedOfFix); if (dblBondPositions != null) { //Found a valid double bond combination for this mobile hydrogen configuration.. solutions.push(dblBondPositions); solutions.push(tautomerSkeleton); } } LOGGER.debug("#possible solutions : ", solutions.size()); if (solutions.size() == 0) { LOGGER.error("Could not generate any tautomers for the input. Is input in Kekule form? "); tautomers.add(inputMolecule); } else { while (solutions.size() != 0) { IAtomContainer tautomerSkeleton = (IAtomContainer) solutions.pop(); List<Integer> dblBondPositions = (List<Integer>) solutions.pop(); IAtomContainer tautomer = (IAtomContainer) inputMolecule.clone(); for (IAtom skAtom1 : tautomerSkeleton.atoms()) { for (IAtom atom1 : tautomer.atoms()) { if (atom1.getID().equals(skAtom1.getID())) { atom1.setImplicitHydrogenCount(skAtom1.getImplicitHydrogenCount()); for (int bondIdx = 0; bondIdx < tautomerSkeleton.getBondCount(); bondIdx++) { IBond skBond = tautomerSkeleton.getBond(bondIdx); if (skBond.contains(skAtom1)) { IAtom skAtom2 = skBond.getOther(skAtom1); for (IAtom atom2 : tautomer.atoms()) { if (atom2.getID().equals(skAtom2.getID())) { IBond tautBond = tautomer.getBond(atom1, atom2); if (dblBondPositions.contains(bondIdx)) tautBond.setOrder(IBond.Order.DOUBLE); else tautBond.setOrder(IBond.Order.SINGLE); } } } } } } } for (IAtom atom : tautomer.atoms()) { atom.setFlag(CDKConstants.ISAROMATIC, false); atom.setValency(null); } for (IBond bond : tautomer.bonds()) bond.setFlag(CDKConstants.ISAROMATIC, false); tautomers.add(tautomer); } } LOGGER.debug("# initial tautomers generated : ", tautomers.size()); return tautomers; } }
public class class_name { public Object nextValue() throws JSONException { char c = nextClean(); String s; switch (c) { case '"': case '\'': return nextString(c); case '{': back(); return new JSONObject(this, m_ordered); case '[': case '(': back(); return new JSONArray(this); default: } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuffer sb = new StringBuffer(); char b = c; while ((c >= ' ') && (",:]}/\\\"[{;=#".indexOf(c) < 0)) { sb.append(c); c = next(); } back(); /* * If it is true, false, or null, return the proper value. */ s = sb.toString().trim(); if (s.equals("")) { throw syntaxError("Missing value"); } if (s.equalsIgnoreCase("true")) { return Boolean.TRUE; } if (s.equalsIgnoreCase("false")) { return Boolean.FALSE; } if (s.equalsIgnoreCase("null")) { return JSONObject.NULL; } /* * If it might be a number, try converting it. We support the 0- and 0x- * conventions. If a number cannot be produced, then the value will just * be a string. Note that the 0-, 0x-, plus, and implied string * conventions are non-standard. A JSON parser is free to accept * non-JSON forms as long as it accepts all correct JSON forms. */ if (((b >= '0') && (b <= '9')) || (b == '.') || (b == '-') || (b == '+')) { if (b == '0') { if ((s.length() > 2) && ((s.charAt(1) == 'x') || (s.charAt(1) == 'X'))) { try { return new Integer(Integer.parseInt(s.substring(2), 16)); } catch (Exception e) { /* Ignore the error */ } } else { try { return new Integer(Integer.parseInt(s, 8)); } catch (Exception e) { /* Ignore the error */ } } } try { return new Integer(s); } catch (Exception e) { try { return new Long(s); } catch (Exception f) { try { return new Double(s); } catch (Exception g) { return s; } } } } return s; } }
public class class_name { public Object nextValue() throws JSONException { char c = nextClean(); String s; switch (c) { case '"': case '\'': return nextString(c); case '{': back(); return new JSONObject(this, m_ordered); case '[': case '(': back(); return new JSONArray(this); default: } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuffer sb = new StringBuffer(); char b = c; while ((c >= ' ') && (",:]}/\\\"[{;=#".indexOf(c) < 0)) { sb.append(c); c = next(); } back(); /* * If it is true, false, or null, return the proper value. */ s = sb.toString().trim(); if (s.equals("")) { throw syntaxError("Missing value"); } if (s.equalsIgnoreCase("true")) { return Boolean.TRUE; // depends on control dependency: [if], data = [none] } if (s.equalsIgnoreCase("false")) { return Boolean.FALSE; // depends on control dependency: [if], data = [none] } if (s.equalsIgnoreCase("null")) { return JSONObject.NULL; // depends on control dependency: [if], data = [none] } /* * If it might be a number, try converting it. We support the 0- and 0x- * conventions. If a number cannot be produced, then the value will just * be a string. Note that the 0-, 0x-, plus, and implied string * conventions are non-standard. A JSON parser is free to accept * non-JSON forms as long as it accepts all correct JSON forms. */ if (((b >= '0') && (b <= '9')) || (b == '.') || (b == '-') || (b == '+')) { if (b == '0') { if ((s.length() > 2) && ((s.charAt(1) == 'x') || (s.charAt(1) == 'X'))) { try { return new Integer(Integer.parseInt(s.substring(2), 16)); // depends on control dependency: [try], data = [none] } catch (Exception e) { /* Ignore the error */ } // depends on control dependency: [catch], data = [none] } else { try { return new Integer(Integer.parseInt(s, 8)); // depends on control dependency: [try], data = [none] } catch (Exception e) { /* Ignore the error */ } // depends on control dependency: [catch], data = [none] } } try { return new Integer(s); // depends on control dependency: [try], data = [none] } catch (Exception e) { try { return new Long(s); // depends on control dependency: [try], data = [none] } catch (Exception f) { try { return new Double(s); // depends on control dependency: [try], data = [none] } catch (Exception g) { return s; } // depends on control dependency: [catch], data = [none] } // depends on control dependency: [catch], data = [none] } // depends on control dependency: [catch], data = [none] } return s; } }
public class class_name { public static String resourceFileToString(final String location, final String fileName) { if (location == null || fileName == null) return null; final InputStream in = ResourceUtilities.class.getResourceAsStream(location + fileName); if (in == null) return null; final BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; final StringBuilder output = new StringBuilder(""); try { while ((line = br.readLine()) != null) { output.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { in.close(); } catch (IOException e) { LOG.error("Failed to close the InputStream", e); } try { br.close(); } catch (IOException e) { LOG.error("Failed to close the BufferedReader", e); } } return output.toString(); } }
public class class_name { public static String resourceFileToString(final String location, final String fileName) { if (location == null || fileName == null) return null; final InputStream in = ResourceUtilities.class.getResourceAsStream(location + fileName); if (in == null) return null; final BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; final StringBuilder output = new StringBuilder(""); try { while ((line = br.readLine()) != null) { output.append(line + "\n"); // depends on control dependency: [while], data = [none] } } catch (IOException e) { e.printStackTrace(); } finally { // depends on control dependency: [catch], data = [none] try { in.close(); // depends on control dependency: [try], data = [none] } catch (IOException e) { LOG.error("Failed to close the InputStream", e); } // depends on control dependency: [catch], data = [none] try { br.close(); // depends on control dependency: [try], data = [none] } catch (IOException e) { LOG.error("Failed to close the BufferedReader", e); } // depends on control dependency: [catch], data = [none] } return output.toString(); } }
public class class_name { private JSONObject getJsonRequestContent(J4pRequest pRequest) { JSONObject requestContent = pRequest.toJson(); if (defaultTargetConfig != null && pRequest.getTargetConfig() == null) { requestContent.put("target", defaultTargetConfig.toJson()); } return requestContent; } }
public class class_name { private JSONObject getJsonRequestContent(J4pRequest pRequest) { JSONObject requestContent = pRequest.toJson(); if (defaultTargetConfig != null && pRequest.getTargetConfig() == null) { requestContent.put("target", defaultTargetConfig.toJson()); // depends on control dependency: [if], data = [none] } return requestContent; } }
public class class_name { private void removeStateItemStreams(Transaction transaction) throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "removeStateItemStreams", transaction ); try { // Clean up mqlink state stream. This is a raw itemstream so // we do this "by hand". if( _mqLinkStateItemStream != null && _mqLinkStateItemStream.isInStore()) { Item item = null; while (null != (item = _mqLinkStateItemStream.findFirstMatchingItem(null))) { item.remove(transaction, NO_LOCK_ID); } // Now remove the itemstream itself _mqLinkStateItemStream.remove(transaction, NO_LOCK_ID); } // Clean up pubsub bridge state itemstream. // Note that pubsub bridge should already have tidied up contained // itemstreams. This does a final tidy and removes the state itemstream // itself. Must check that this is not in store as we may have the item stream // from a previous failed delete if( _mqLinkPubSubBridgeItemStream != null && _mqLinkPubSubBridgeItemStream.isInStore()) { _mqLinkPubSubBridgeItemStream.removeAll(transaction); } // Set refs to null removed as we may fail the delete later. // _mqLinkStateItemStream = null; // _mqLinkPubSubBridgeItemStream = null; } catch (MessageStoreException e) { // FFDC FFDCFilter.processException( e, "com.ibm.ws.sib.processor.impl.MQLinkHandler.removeStateItemStreams", "1:910:1.71", this); SibTr.exception(tc, e); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "removeStateItemStreams", e); throw new SIResourceException(e); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "removeStateItemStreams"); } }
public class class_name { private void removeStateItemStreams(Transaction transaction) throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "removeStateItemStreams", transaction ); try { // Clean up mqlink state stream. This is a raw itemstream so // we do this "by hand". if( _mqLinkStateItemStream != null && _mqLinkStateItemStream.isInStore()) { Item item = null; while (null != (item = _mqLinkStateItemStream.findFirstMatchingItem(null))) { item.remove(transaction, NO_LOCK_ID); // depends on control dependency: [while], data = [none] } // Now remove the itemstream itself _mqLinkStateItemStream.remove(transaction, NO_LOCK_ID); // depends on control dependency: [if], data = [none] } // Clean up pubsub bridge state itemstream. // Note that pubsub bridge should already have tidied up contained // itemstreams. This does a final tidy and removes the state itemstream // itself. Must check that this is not in store as we may have the item stream // from a previous failed delete if( _mqLinkPubSubBridgeItemStream != null && _mqLinkPubSubBridgeItemStream.isInStore()) { _mqLinkPubSubBridgeItemStream.removeAll(transaction); // depends on control dependency: [if], data = [none] } // Set refs to null removed as we may fail the delete later. // _mqLinkStateItemStream = null; // _mqLinkPubSubBridgeItemStream = null; } catch (MessageStoreException e) { // FFDC FFDCFilter.processException( e, "com.ibm.ws.sib.processor.impl.MQLinkHandler.removeStateItemStreams", "1:910:1.71", this); SibTr.exception(tc, e); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "removeStateItemStreams", e); throw new SIResourceException(e); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "removeStateItemStreams"); } }
public class class_name { public EClass getIfcTimeSeriesSchedule() { if (ifcTimeSeriesScheduleEClass == null) { ifcTimeSeriesScheduleEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(615); } return ifcTimeSeriesScheduleEClass; } }
public class class_name { public EClass getIfcTimeSeriesSchedule() { if (ifcTimeSeriesScheduleEClass == null) { ifcTimeSeriesScheduleEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(615); // depends on control dependency: [if], data = [none] } return ifcTimeSeriesScheduleEClass; } }
public class class_name { private void scanJarManifestForClassPathEntries(LinkedList<WorkListItem> workList, ICodeBase codeBase) throws IOException { // See if this codebase has a jar manifest ICodeBaseEntry manifestEntry = codeBase.lookupResource("META-INF/MANIFEST.MF"); if (manifestEntry == null) { // Do nothing - no Jar manifest found return; } // Try to read the manifest InputStream in = null; try { in = manifestEntry.openResource(); Manifest manifest = new Manifest(in); Attributes mainAttrs = manifest.getMainAttributes(); String classPath = mainAttrs.getValue("Class-Path"); if (classPath != null) { String[] pathList = classPath.split("\\s+"); for (String path : pathList) { // Create a codebase locator for the classpath entry // relative to the codebase in which we discovered the Jar // manifest ICodeBaseLocator relativeCodeBaseLocator = codeBase.getCodeBaseLocator().createRelativeCodeBaseLocator(path); // Codebases found in Class-Path entries are always // added to the aux classpath, not the application. addToWorkList(workList, new WorkListItem(relativeCodeBaseLocator, false, ICodeBase.Discovered.IN_JAR_MANIFEST)); } } } finally { if (in != null) { IO.close(in); } } } }
public class class_name { private void scanJarManifestForClassPathEntries(LinkedList<WorkListItem> workList, ICodeBase codeBase) throws IOException { // See if this codebase has a jar manifest ICodeBaseEntry manifestEntry = codeBase.lookupResource("META-INF/MANIFEST.MF"); if (manifestEntry == null) { // Do nothing - no Jar manifest found return; } // Try to read the manifest InputStream in = null; try { in = manifestEntry.openResource(); Manifest manifest = new Manifest(in); Attributes mainAttrs = manifest.getMainAttributes(); String classPath = mainAttrs.getValue("Class-Path"); if (classPath != null) { String[] pathList = classPath.split("\\s+"); for (String path : pathList) { // Create a codebase locator for the classpath entry // relative to the codebase in which we discovered the Jar // manifest ICodeBaseLocator relativeCodeBaseLocator = codeBase.getCodeBaseLocator().createRelativeCodeBaseLocator(path); // Codebases found in Class-Path entries are always // added to the aux classpath, not the application. addToWorkList(workList, new WorkListItem(relativeCodeBaseLocator, false, ICodeBase.Discovered.IN_JAR_MANIFEST)); // depends on control dependency: [for], data = [none] } } } finally { if (in != null) { IO.close(in); // depends on control dependency: [if], data = [(in] } } } }
public class class_name { public BagObject put (String key, Object object) { // convert the element to internal storage format, and don't bother with the rest if that's // a null value (per the docs above) object = objectify (object); if (object != null) { // separate the key into path components, the "local" key value is the first component, // so use that to conduct the search. If there is an element there, we want to get it, // otherwise we want to create it. String[] path = Key.split (key); Pair pair = getOrAddPair (path[0]); if (path.length == 1) { // this was the only key in the path, so it's the end of the line, store the value pair.value = object; } else { // this is not the leaf key, so we set the pair value to be a new BagObject if // necessary, then traverse via recursion, BagObject bagObject = (BagObject) pair.value; if (bagObject == null) { pair.value = (bagObject = new BagObject ()); } bagObject.put (path[1], object); } } return this; } }
public class class_name { public BagObject put (String key, Object object) { // convert the element to internal storage format, and don't bother with the rest if that's // a null value (per the docs above) object = objectify (object); if (object != null) { // separate the key into path components, the "local" key value is the first component, // so use that to conduct the search. If there is an element there, we want to get it, // otherwise we want to create it. String[] path = Key.split (key); Pair pair = getOrAddPair (path[0]); if (path.length == 1) { // this was the only key in the path, so it's the end of the line, store the value pair.value = object; // depends on control dependency: [if], data = [none] } else { // this is not the leaf key, so we set the pair value to be a new BagObject if // necessary, then traverse via recursion, BagObject bagObject = (BagObject) pair.value; if (bagObject == null) { pair.value = (bagObject = new BagObject ()); // depends on control dependency: [if], data = [(bagObject] } bagObject.put (path[1], object); // depends on control dependency: [if], data = [none] } } return this; } }
public class class_name { public static long saturatedPow(long b, int k) { checkNonNegative("exponent", k); if (b >= -2 & b <= 2) { switch ((int) b) { case 0: return (k == 0) ? 1 : 0; case 1: return 1; case (-1): return ((k & 1) == 0) ? 1 : -1; case 2: if (k >= Long.SIZE - 1) { return Long.MAX_VALUE; } return 1L << k; case (-2): if (k >= Long.SIZE) { return Long.MAX_VALUE + (k & 1); } return ((k & 1) == 0) ? (1L << k) : (-1L << k); default: throw new AssertionError(); } } long accum = 1; // if b is negative and k is odd then the limit is MIN otherwise the limit is MAX long limit = Long.MAX_VALUE + ((b >>> Long.SIZE - 1) & (k & 1)); while (true) { switch (k) { case 0: return accum; case 1: return saturatedMultiply(accum, b); default: if ((k & 1) != 0) { accum = saturatedMultiply(accum, b); } k >>= 1; if (k > 0) { if (-FLOOR_SQRT_MAX_LONG > b | b > FLOOR_SQRT_MAX_LONG) { return limit; } b *= b; } } } } }
public class class_name { public static long saturatedPow(long b, int k) { checkNonNegative("exponent", k); if (b >= -2 & b <= 2) { switch ((int) b) { // depends on control dependency: [if], data = [none] case 0: return (k == 0) ? 1 : 0; case 1: return 1; case (-1): return ((k & 1) == 0) ? 1 : -1; case 2: if (k >= Long.SIZE - 1) { return Long.MAX_VALUE; // depends on control dependency: [if], data = [none] } return 1L << k; case (-2): if (k >= Long.SIZE) { return Long.MAX_VALUE + (k & 1); // depends on control dependency: [if], data = [(k] } return ((k & 1) == 0) ? (1L << k) : (-1L << k); default: throw new AssertionError(); } } long accum = 1; // if b is negative and k is odd then the limit is MIN otherwise the limit is MAX long limit = Long.MAX_VALUE + ((b >>> Long.SIZE - 1) & (k & 1)); while (true) { switch (k) { case 0: return accum; case 1: return saturatedMultiply(accum, b); default: if ((k & 1) != 0) { accum = saturatedMultiply(accum, b); // depends on control dependency: [if], data = [none] } k >>= 1; if (k > 0) { if (-FLOOR_SQRT_MAX_LONG > b | b > FLOOR_SQRT_MAX_LONG) { return limit; // depends on control dependency: [if], data = [none] } b *= b; // depends on control dependency: [if], data = [none] } } } } }
public class class_name { @Override public WebDriverBrowser<?> create(Object obj) { try { WebDriverProperties webDriverProperties; if (obj instanceof Scriptable && "String".equals(((Scriptable) obj).getClassName())) { obj = obj.toString(); } if (obj instanceof String) { webDriverProperties = new WebDriverProperties(); webDriverProperties.getDesiredCapabilities().put("browserName", obj); } else if (obj instanceof Scriptable) { final Scriptable scriptable = (Scriptable) obj; String json = engine.runWithContext(engine.new RhinoCallable<String, RuntimeException>() { @Override protected String doCall(Context cx, Scriptable scope) throws RuntimeException { return (String) cx.evaluateString(scriptable, "JSON.stringify(this)", "<expression>", 1, null); } }); webDriverProperties = mapper.readValue(json, WebDriverProperties.class); } else { throw new IllegalArgumentException("Only strings or maps are accepted"); } WebDriver wd = webDriverFactory.create(webDriverProperties); WebModule webModule = combine(defaultModule(wd), WebModules.debugModule(), RhinoWebModules.rhinoModule()); return new WebDriverBrowser<DefaultWebElements>(wd, DefaultWebElements.class, webModule); } catch (IOException e) { throw Throwables.propagate(e); } } }
public class class_name { @Override public WebDriverBrowser<?> create(Object obj) { try { WebDriverProperties webDriverProperties; if (obj instanceof Scriptable && "String".equals(((Scriptable) obj).getClassName())) { obj = obj.toString(); // depends on control dependency: [if], data = [none] } if (obj instanceof String) { webDriverProperties = new WebDriverProperties(); // depends on control dependency: [if], data = [none] webDriverProperties.getDesiredCapabilities().put("browserName", obj); // depends on control dependency: [if], data = [none] } else if (obj instanceof Scriptable) { final Scriptable scriptable = (Scriptable) obj; String json = engine.runWithContext(engine.new RhinoCallable<String, RuntimeException>() { @Override protected String doCall(Context cx, Scriptable scope) throws RuntimeException { return (String) cx.evaluateString(scriptable, "JSON.stringify(this)", "<expression>", 1, null); } }); webDriverProperties = mapper.readValue(json, WebDriverProperties.class); // depends on control dependency: [if], data = [none] } else { throw new IllegalArgumentException("Only strings or maps are accepted"); } WebDriver wd = webDriverFactory.create(webDriverProperties); WebModule webModule = combine(defaultModule(wd), WebModules.debugModule(), RhinoWebModules.rhinoModule()); return new WebDriverBrowser<DefaultWebElements>(wd, DefaultWebElements.class, webModule); // depends on control dependency: [try], data = [none] } catch (IOException e) { throw Throwables.propagate(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public EClass getIfcSpatialStructureElementType() { if (ifcSpatialStructureElementTypeEClass == null) { ifcSpatialStructureElementTypeEClass = (EClass) EPackage.Registry.INSTANCE .getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(528); } return ifcSpatialStructureElementTypeEClass; } }
public class class_name { public EClass getIfcSpatialStructureElementType() { if (ifcSpatialStructureElementTypeEClass == null) { ifcSpatialStructureElementTypeEClass = (EClass) EPackage.Registry.INSTANCE .getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(528); // depends on control dependency: [if], data = [none] } return ifcSpatialStructureElementTypeEClass; } }
public class class_name { public void addQuad(final String subject, final String predicate, final String object, String graph) { if (graph == null) { graph = "@default"; } if (!containsKey(graph)) { put(graph, new ArrayList<Quad>()); } ((ArrayList<Quad>) get(graph)).add(new Quad(subject, predicate, object, graph)); } }
public class class_name { public void addQuad(final String subject, final String predicate, final String object, String graph) { if (graph == null) { graph = "@default"; // depends on control dependency: [if], data = [none] } if (!containsKey(graph)) { put(graph, new ArrayList<Quad>()); // depends on control dependency: [if], data = [none] } ((ArrayList<Quad>) get(graph)).add(new Quad(subject, predicate, object, graph)); } }