code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { public void addHole( Polygon poly ) { if( _holes == null ) { _holes = new ArrayList<Polygon>(); } _holes.add( poly ); // XXX: tests could be made here to be sure it is fully inside // addSubtraction( poly.getPoints() ); } }
public class class_name { public void addHole( Polygon poly ) { if( _holes == null ) { _holes = new ArrayList<Polygon>(); // depends on control dependency: [if], data = [none] } _holes.add( poly ); // XXX: tests could be made here to be sure it is fully inside // addSubtraction( poly.getPoints() ); } }
public class class_name { private List<PropertyChangeEvent> delta(WAMMemoryLayout oldRegisters, WAMMemoryLayout newRegisters) { List<PropertyChangeEvent> result = new LinkedList<PropertyChangeEvent>(); if (oldRegisters.regBase != newRegisters.regBase) { result.add(new PropertyChangeEvent(this, "regBase", oldRegisters.regBase, newRegisters.regBase)); } if (oldRegisters.regSize != newRegisters.regSize) { result.add(new PropertyChangeEvent(this, "regSize", oldRegisters.regSize, newRegisters.regSize)); } if (oldRegisters.heapBase != newRegisters.heapBase) { result.add(new PropertyChangeEvent(this, "heapBase", oldRegisters.heapBase, newRegisters.heapBase)); } if (oldRegisters.heapSize != newRegisters.heapSize) { result.add(new PropertyChangeEvent(this, "heapSize", oldRegisters.heapSize, newRegisters.heapSize)); } if (oldRegisters.stackBase != newRegisters.stackBase) { result.add(new PropertyChangeEvent(this, "stackBase", oldRegisters.stackBase, newRegisters.stackBase)); } if (oldRegisters.stackSize != newRegisters.stackSize) { result.add(new PropertyChangeEvent(this, "stackSize", oldRegisters.stackSize, newRegisters.stackSize)); } if (oldRegisters.trailBase != newRegisters.trailBase) { result.add(new PropertyChangeEvent(this, "trailBase", oldRegisters.trailBase, newRegisters.trailBase)); } if (oldRegisters.trailSize != newRegisters.trailSize) { result.add(new PropertyChangeEvent(this, "trailSize", oldRegisters.trailSize, newRegisters.trailSize)); } if (oldRegisters.pdlBase != newRegisters.pdlBase) { result.add(new PropertyChangeEvent(this, "pdlBase", oldRegisters.pdlBase, newRegisters.pdlBase)); } if (oldRegisters.pdlSize != newRegisters.pdlSize) { result.add(new PropertyChangeEvent(this, "pdlSize", oldRegisters.pdlSize, newRegisters.pdlSize)); } return result; } }
public class class_name { private List<PropertyChangeEvent> delta(WAMMemoryLayout oldRegisters, WAMMemoryLayout newRegisters) { List<PropertyChangeEvent> result = new LinkedList<PropertyChangeEvent>(); if (oldRegisters.regBase != newRegisters.regBase) { result.add(new PropertyChangeEvent(this, "regBase", oldRegisters.regBase, newRegisters.regBase)); // depends on control dependency: [if], data = [newRegisters.regBase)] } if (oldRegisters.regSize != newRegisters.regSize) { result.add(new PropertyChangeEvent(this, "regSize", oldRegisters.regSize, newRegisters.regSize)); // depends on control dependency: [if], data = [newRegisters.regSize)] } if (oldRegisters.heapBase != newRegisters.heapBase) { result.add(new PropertyChangeEvent(this, "heapBase", oldRegisters.heapBase, newRegisters.heapBase)); // depends on control dependency: [if], data = [newRegisters.heapBase)] } if (oldRegisters.heapSize != newRegisters.heapSize) { result.add(new PropertyChangeEvent(this, "heapSize", oldRegisters.heapSize, newRegisters.heapSize)); // depends on control dependency: [if], data = [newRegisters.heapSize)] } if (oldRegisters.stackBase != newRegisters.stackBase) { result.add(new PropertyChangeEvent(this, "stackBase", oldRegisters.stackBase, newRegisters.stackBase)); // depends on control dependency: [if], data = [newRegisters.stackBase)] } if (oldRegisters.stackSize != newRegisters.stackSize) { result.add(new PropertyChangeEvent(this, "stackSize", oldRegisters.stackSize, newRegisters.stackSize)); // depends on control dependency: [if], data = [newRegisters.stackSize)] } if (oldRegisters.trailBase != newRegisters.trailBase) { result.add(new PropertyChangeEvent(this, "trailBase", oldRegisters.trailBase, newRegisters.trailBase)); // depends on control dependency: [if], data = [newRegisters.trailBase)] } if (oldRegisters.trailSize != newRegisters.trailSize) { result.add(new PropertyChangeEvent(this, "trailSize", oldRegisters.trailSize, newRegisters.trailSize)); // depends on control dependency: [if], data = [newRegisters.trailSize)] } if (oldRegisters.pdlBase != newRegisters.pdlBase) { result.add(new PropertyChangeEvent(this, "pdlBase", oldRegisters.pdlBase, newRegisters.pdlBase)); // depends on control dependency: [if], data = [newRegisters.pdlBase)] } if (oldRegisters.pdlSize != newRegisters.pdlSize) { result.add(new PropertyChangeEvent(this, "pdlSize", oldRegisters.pdlSize, newRegisters.pdlSize)); // depends on control dependency: [if], data = [newRegisters.pdlSize)] } return result; } }
public class class_name { @SuppressWarnings({ "rawtypes", "unchecked" }) public Map<Class<?>, List<Object>> execSelectTableWithJoin(String preparedSql, Object[] searchKeys, Class<? extends D6Model>... modelClazz) { log("#execSelectTableWithJoin preparedSql=" + preparedSql + " searchKeys=" + searchKeys + " modelClazz=" + modelClazz); final Map<Class<?>, List<Object>> resultMap = new HashMap<Class<?>, List<Object>>(); final List<ModelWrapper> modelList = new ArrayList<ModelWrapper>(); for (int i = 0; i < modelClazz.length; i++) { @SuppressWarnings("unchecked") final ModelWrapper model = new ModelWrapper(modelClazz[i]); modelList.add(model); } PreparedStatement preparedStmt = null; ResultSet rs = null; final Connection conn = createConnection(); try { preparedStmt = conn.prepareStatement(preparedSql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); final StringBuilder logSb = new StringBuilder(); if (searchKeys != null) { logSb.append("/ "); for (int i = 0; i < searchKeys.length; i++) { // Object object = searchKeys[i]; setObject((i + 1), preparedStmt, object); logSb.append("key(" + (i + 1) + ")=" + searchKeys[i]); logSb.append(" "); } } log("#execSelectTableWithJoin SQL=" + preparedSql + " " + logSb.toString()); // execute SQL rs = preparedStmt.executeQuery(); final ResultSetMetaData rsMetaData = rs.getMetaData(); final int numberOfColumns = rsMetaData.getColumnCount(); final List<String> columnNameList = new ArrayList<String>(); // cache column names of this result set for (int i = 0; i < numberOfColumns; i++) { String columnName = rsMetaData.getColumnName(i + 1); columnNameList.add(columnName); } while (rs.next()) { // Processing of a single resultset[begin]============= for (int i = 0; i < numberOfColumns; i++) { // Get from the current resultSet final String columnName = columnNameList.get(i); final Object value = rs.getObject(i + 1); // Set the values to all the properties of model class (You // know property is corresponding to each column of the DB) // via modelWrapper for (ModelWrapper model : modelList) { // set value to model wrapper model.setValue(columnName, value); } } // Processing of a single resultset[end]============= for (ModelWrapper model : modelList) { final Class<?> modelClazzName = model.getClazz(); List<Object> modelObjectList = resultMap.get(modelClazzName); // Generate the result list corresponding to a certain model // class if the list have not been generated. if (modelObjectList == null) { modelObjectList = new ArrayList<Object>(); resultMap.put(modelClazzName, modelObjectList); } // Generates a model object having a property value held in // the model wrapper, and stores the model object in the // modelObjectList final Object resultModelObject = model.getAsObject(); modelObjectList.add(resultModelObject); model.initializeFieldMap(); } } } catch (Exception e) { loge("#execSelectTableWithJoin General ", e); } finally { try { if (rs != null) { rs.close(); } if (preparedStmt != null) { preparedStmt.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { loge("#execSelectTableWithJoin SQLException ", e); } } return resultMap; } }
public class class_name { @SuppressWarnings({ "rawtypes", "unchecked" }) public Map<Class<?>, List<Object>> execSelectTableWithJoin(String preparedSql, Object[] searchKeys, Class<? extends D6Model>... modelClazz) { log("#execSelectTableWithJoin preparedSql=" + preparedSql + " searchKeys=" + searchKeys + " modelClazz=" + modelClazz); final Map<Class<?>, List<Object>> resultMap = new HashMap<Class<?>, List<Object>>(); final List<ModelWrapper> modelList = new ArrayList<ModelWrapper>(); for (int i = 0; i < modelClazz.length; i++) { @SuppressWarnings("unchecked") final ModelWrapper model = new ModelWrapper(modelClazz[i]); modelList.add(model); // depends on control dependency: [for], data = [none] } PreparedStatement preparedStmt = null; ResultSet rs = null; final Connection conn = createConnection(); try { preparedStmt = conn.prepareStatement(preparedSql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // depends on control dependency: [try], data = [none] final StringBuilder logSb = new StringBuilder(); if (searchKeys != null) { logSb.append("/ "); // depends on control dependency: [if], data = [none] for (int i = 0; i < searchKeys.length; i++) { // Object object = searchKeys[i]; setObject((i + 1), preparedStmt, object); // depends on control dependency: [for], data = [i] logSb.append("key(" + (i + 1) + ")=" + searchKeys[i]); logSb.append(" "); // depends on control dependency: [for], data = [none] } } log("#execSelectTableWithJoin SQL=" + preparedSql + " " + logSb.toString()); // depends on control dependency: [try], data = [none] // execute SQL rs = preparedStmt.executeQuery(); // depends on control dependency: [try], data = [none] final ResultSetMetaData rsMetaData = rs.getMetaData(); final int numberOfColumns = rsMetaData.getColumnCount(); final List<String> columnNameList = new ArrayList<String>(); // cache column names of this result set for (int i = 0; i < numberOfColumns; i++) { String columnName = rsMetaData.getColumnName(i + 1); columnNameList.add(columnName); // depends on control dependency: [for], data = [none] } while (rs.next()) { // Processing of a single resultset[begin]============= for (int i = 0; i < numberOfColumns; i++) { // Get from the current resultSet final String columnName = columnNameList.get(i); final Object value = rs.getObject(i + 1); // Set the values to all the properties of model class (You // know property is corresponding to each column of the DB) // via modelWrapper for (ModelWrapper model : modelList) { // set value to model wrapper model.setValue(columnName, value); // depends on control dependency: [for], data = [model] } } // Processing of a single resultset[end]============= for (ModelWrapper model : modelList) { final Class<?> modelClazzName = model.getClazz(); List<Object> modelObjectList = resultMap.get(modelClazzName); // Generate the result list corresponding to a certain model // class if the list have not been generated. if (modelObjectList == null) { modelObjectList = new ArrayList<Object>(); // depends on control dependency: [if], data = [none] resultMap.put(modelClazzName, modelObjectList); // depends on control dependency: [if], data = [none] } // Generates a model object having a property value held in // the model wrapper, and stores the model object in the // modelObjectList final Object resultModelObject = model.getAsObject(); modelObjectList.add(resultModelObject); // depends on control dependency: [for], data = [model] model.initializeFieldMap(); // depends on control dependency: [for], data = [model] } } } catch (Exception e) { loge("#execSelectTableWithJoin General ", e); } finally { // depends on control dependency: [catch], data = [none] try { if (rs != null) { rs.close(); // depends on control dependency: [if], data = [none] } if (preparedStmt != null) { preparedStmt.close(); // depends on control dependency: [if], data = [none] } if (conn != null) { conn.close(); // depends on control dependency: [if], data = [none] } } catch (SQLException e) { loge("#execSelectTableWithJoin SQLException ", e); } // depends on control dependency: [catch], data = [none] } return resultMap; } }
public class class_name { @Override public IRxSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) { if (clazz.equals(ClientRxSession.class)) { ClientRxSessionDataReplicatedImpl data = new ClientRxSessionDataReplicatedImpl(sessionId, this.mobicentsCluster, this.replicatedSessionDataSource.getContainer()); return data; } else if (clazz.equals(ServerRxSession.class)) { ServerRxSessionDataReplicatedImpl data = new ServerRxSessionDataReplicatedImpl(sessionId, this.mobicentsCluster); return data; } throw new IllegalArgumentException(); } }
public class class_name { @Override public IRxSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) { if (clazz.equals(ClientRxSession.class)) { ClientRxSessionDataReplicatedImpl data = new ClientRxSessionDataReplicatedImpl(sessionId, this.mobicentsCluster, this.replicatedSessionDataSource.getContainer()); return data; // depends on control dependency: [if], data = [none] } else if (clazz.equals(ServerRxSession.class)) { ServerRxSessionDataReplicatedImpl data = new ServerRxSessionDataReplicatedImpl(sessionId, this.mobicentsCluster); return data; // depends on control dependency: [if], data = [none] } throw new IllegalArgumentException(); } }
public class class_name { private static String addToProperties(String key,String value ) { if(!value.contains(PLACEHOLDER_PREFIX)){ allProperties.put(key, value); return value; } String[] segments = value.split("\\$\\{"); String seg; StringBuilder finalValue = new StringBuilder(); for (int i = 0; i < segments.length; i++) { seg = StringUtils.trimToNull(segments[i]); if(StringUtils.isBlank(seg))continue; if(seg.contains(PLACEHOLDER_SUFFIX)){ String refKey = seg.substring(0, seg.indexOf(PLACEHOLDER_SUFFIX)).trim(); //其他非${}的占位符如:{{host}} String withBraceString = null; if(seg.contains("{")){ withBraceString = seg.substring(seg.indexOf(PLACEHOLDER_SUFFIX)+1); } //如果包含默认值,如:${host:127.0.0.1} String defaultValue = null; if(refKey.contains(":")){ String[] tmpArray = refKey.split(":"); refKey = tmpArray[0]; defaultValue = tmpArray[1]; } String refValue = getProperty(refKey); if(StringUtils.isBlank(refValue)){ refValue = defaultValue; } finalValue.append(refValue); if(withBraceString != null){ finalValue.append(withBraceString); }else{ String[] segments2 = seg.split("\\}"); if(segments2.length == 2){ finalValue.append(segments2[1]); } } }else{ finalValue.append(seg); } } allProperties.put(key, finalValue.toString()); return finalValue.toString(); } }
public class class_name { private static String addToProperties(String key,String value ) { if(!value.contains(PLACEHOLDER_PREFIX)){ allProperties.put(key, value); // depends on control dependency: [if], data = [none] return value; // depends on control dependency: [if], data = [none] } String[] segments = value.split("\\$\\{"); String seg; StringBuilder finalValue = new StringBuilder(); for (int i = 0; i < segments.length; i++) { seg = StringUtils.trimToNull(segments[i]); // depends on control dependency: [for], data = [i] if(StringUtils.isBlank(seg))continue; if(seg.contains(PLACEHOLDER_SUFFIX)){ String refKey = seg.substring(0, seg.indexOf(PLACEHOLDER_SUFFIX)).trim(); //其他非${}的占位符如:{{host}} String withBraceString = null; if(seg.contains("{")){ withBraceString = seg.substring(seg.indexOf(PLACEHOLDER_SUFFIX)+1); // depends on control dependency: [if], data = [none] } //如果包含默认值,如:${host:127.0.0.1} String defaultValue = null; if(refKey.contains(":")){ String[] tmpArray = refKey.split(":"); refKey = tmpArray[0]; // depends on control dependency: [if], data = [none] defaultValue = tmpArray[1]; // depends on control dependency: [if], data = [none] } String refValue = getProperty(refKey); if(StringUtils.isBlank(refValue)){ refValue = defaultValue; // depends on control dependency: [if], data = [none] } finalValue.append(refValue); // depends on control dependency: [if], data = [none] if(withBraceString != null){ finalValue.append(withBraceString); // depends on control dependency: [if], data = [(withBraceString] }else{ String[] segments2 = seg.split("\\}"); if(segments2.length == 2){ finalValue.append(segments2[1]); // depends on control dependency: [if], data = [none] } } }else{ finalValue.append(seg); // depends on control dependency: [if], data = [none] } } allProperties.put(key, finalValue.toString()); return finalValue.toString(); } }
public class class_name { boolean isPreferredAddress(InetAddress address) { if (this.properties.isUseOnlySiteLocalInterfaces()) { final boolean siteLocalAddress = address.isSiteLocalAddress(); if (!siteLocalAddress) { this.log.trace("Ignoring address: " + address.getHostAddress()); } return siteLocalAddress; } final List<String> preferredNetworks = this.properties.getPreferredNetworks(); if (preferredNetworks.isEmpty()) { return true; } for (String regex : preferredNetworks) { final String hostAddress = address.getHostAddress(); if (hostAddress.matches(regex) || hostAddress.startsWith(regex)) { return true; } } this.log.trace("Ignoring address: " + address.getHostAddress()); return false; } }
public class class_name { boolean isPreferredAddress(InetAddress address) { if (this.properties.isUseOnlySiteLocalInterfaces()) { final boolean siteLocalAddress = address.isSiteLocalAddress(); if (!siteLocalAddress) { this.log.trace("Ignoring address: " + address.getHostAddress()); // depends on control dependency: [if], data = [none] } return siteLocalAddress; // depends on control dependency: [if], data = [none] } final List<String> preferredNetworks = this.properties.getPreferredNetworks(); if (preferredNetworks.isEmpty()) { return true; // depends on control dependency: [if], data = [none] } for (String regex : preferredNetworks) { final String hostAddress = address.getHostAddress(); if (hostAddress.matches(regex) || hostAddress.startsWith(regex)) { return true; // depends on control dependency: [if], data = [none] } } this.log.trace("Ignoring address: " + address.getHostAddress()); return false; } }
public class class_name { public void clearButtonsLeft() { m_itemsLeft.removeAllComponents(); m_leftButtons.removeAllComponents(); // in case the app title is set, make sure to keep the label in the button bar if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_appIndicator.getValue())) { m_itemsLeft.addComponent(m_appIndicator); } updateFoldingThreshhold(); } }
public class class_name { public void clearButtonsLeft() { m_itemsLeft.removeAllComponents(); m_leftButtons.removeAllComponents(); // in case the app title is set, make sure to keep the label in the button bar if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_appIndicator.getValue())) { m_itemsLeft.addComponent(m_appIndicator); // depends on control dependency: [if], data = [none] } updateFoldingThreshhold(); } }
public class class_name { public static void main(String[] args) { try { if (args.length == 8 || args.length == 9) { String host = args[0]; int port = Integer.parseInt(args[1]); String user = args[2]; String password = args[3]; String pid = args[4]; String dsid = args[5]; File outfile = new File(args[6]); String asOfDateTime = args.length == 8 ? args[7] : null; String context = args.length == 9 ? args[8] : null; FileOutputStream outStream = new FileOutputStream(outfile); Downloader downloader = new Downloader(host, port, context, user, password); downloader.getDatastreamContent(pid, dsid, asOfDateTime, outStream); } else { System.err .println("Usage: Downloader host port user password pid dsid outfile [MMDDYYTHH:MM:SS] [context]"); } } catch (Exception e) { e.printStackTrace(); System.err.println("ERROR: " + e.getMessage()); } } }
public class class_name { public static void main(String[] args) { try { if (args.length == 8 || args.length == 9) { String host = args[0]; int port = Integer.parseInt(args[1]); String user = args[2]; String password = args[3]; String pid = args[4]; String dsid = args[5]; File outfile = new File(args[6]); String asOfDateTime = args.length == 8 ? args[7] : null; String context = args.length == 9 ? args[8] : null; FileOutputStream outStream = new FileOutputStream(outfile); Downloader downloader = new Downloader(host, port, context, user, password); downloader.getDatastreamContent(pid, dsid, asOfDateTime, outStream); // depends on control dependency: [if], data = [none] } else { System.err .println("Usage: Downloader host port user password pid dsid outfile [MMDDYYTHH:MM:SS] [context]"); // depends on control dependency: [if], data = [none] } } catch (Exception e) { e.printStackTrace(); System.err.println("ERROR: " + e.getMessage()); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public EClass getIfcLocalPlacement() { if (ifcLocalPlacementEClass == null) { ifcLocalPlacementEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(301); } return ifcLocalPlacementEClass; } }
public class class_name { public EClass getIfcLocalPlacement() { if (ifcLocalPlacementEClass == null) { ifcLocalPlacementEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(301); // depends on control dependency: [if], data = [none] } return ifcLocalPlacementEClass; } }
public class class_name { public static double jaccardIndex(IntegerVector a, IntegerVector b) { Set<Integer> intersection = new HashSet<Integer>(); Set<Integer> union = new HashSet<Integer>(); for (int i = 0; i < a.length(); ++i) { int d = a.get(i); intersection.add(d); union.add(d); } Set<Integer> tmp = new HashSet<Integer>(); for (int i = 0; i < b.length(); ++i) { int d = b.get(i); tmp.add(d); union.add(d); } intersection.retainAll(tmp); return ((double)(intersection.size())) / union.size(); } }
public class class_name { public static double jaccardIndex(IntegerVector a, IntegerVector b) { Set<Integer> intersection = new HashSet<Integer>(); Set<Integer> union = new HashSet<Integer>(); for (int i = 0; i < a.length(); ++i) { int d = a.get(i); intersection.add(d); // depends on control dependency: [for], data = [none] union.add(d); // depends on control dependency: [for], data = [none] } Set<Integer> tmp = new HashSet<Integer>(); for (int i = 0; i < b.length(); ++i) { int d = b.get(i); tmp.add(d); // depends on control dependency: [for], data = [none] union.add(d); // depends on control dependency: [for], data = [none] } intersection.retainAll(tmp); return ((double)(intersection.size())) / union.size(); } }
public class class_name { public static String stripQuotes( String input ) { if( input.length() < 2 ){ return input; }else if( input.startsWith( SINGLE_QUOTE ) && input.endsWith( SINGLE_QUOTE ) ){ return input.substring( 1, input.length() - 1 ); }else if( input.startsWith( DOUBLE_QUOTE ) && input.endsWith( DOUBLE_QUOTE ) ){ return input.substring( 1, input.length() - 1 ); }else{ return input; } } }
public class class_name { public static String stripQuotes( String input ) { if( input.length() < 2 ){ return input; // depends on control dependency: [if], data = [none] }else if( input.startsWith( SINGLE_QUOTE ) && input.endsWith( SINGLE_QUOTE ) ){ return input.substring( 1, input.length() - 1 ); // depends on control dependency: [if], data = [none] }else if( input.startsWith( DOUBLE_QUOTE ) && input.endsWith( DOUBLE_QUOTE ) ){ return input.substring( 1, input.length() - 1 ); // depends on control dependency: [if], data = [none] }else{ return input; // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override public void saveTo(final OutputStream out) { try { Util.copy(getInputStream(), out); } catch (IOException e) { throw new MechanizeException(e); } } }
public class class_name { @Override public void saveTo(final OutputStream out) { try { Util.copy(getInputStream(), out); // depends on control dependency: [try], data = [none] } catch (IOException e) { throw new MechanizeException(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { void configureEndpoints(Reflections reflections) { // [Re]initialise the api: api = new HashMap<>(); log.info("Scanning for endpoint classes.."); Set<Class<?>> endpoints = reflections.getTypesAnnotatedWith(Api.class); // log.info(reflections.getConfiguration().getUrls()); log.info("Found {} endpoint classes.", endpoints.size()); log.info("Examining endpoint class methods:"); // Configure the classes: for (Class<?> endpointClass : endpoints) { Route route = getEndpoint(endpointClass); route.endpointClass = endpointClass; for (Method method : endpointClass.getMethods()) { // Skip Object methods if (method.getDeclaringClass() == Object.class) { continue; } // Find public methods: if (Modifier.isPublic(method.getModifiers())) { // Which HTTP method(s) will this method respond to? annotation: for (Annotation annotation : method.getAnnotations()) { HttpMethod httpMethod = HttpMethod.method(annotation); if (httpMethod != null) { log.info("Http method: {}", httpMethod); RequestHandler requestHandler = new RequestHandler(); requestHandler.handlerMethod = method; log.info("Java method: {}", method.getName()); // Look for an optional Json message type parameter: for (Class<?> parameterType : method.getParameterTypes()) { if (!HttpServletRequest.class.isAssignableFrom(parameterType) && !HttpServletResponse.class.isAssignableFrom(parameterType)) { if (requestHandler.requestMessageType != null) { log.error("Too many parameters on {} method {}. " + "Message type already set to {} but also found a {} parameter.", httpMethod, method.getName(), requestHandler.requestMessageType.getSimpleName(), parameterType.getSimpleName()); break annotation; } requestHandler.requestMessageType = parameterType; log.info("request Json: {}", requestHandler.requestMessageType.getSimpleName()); } } // Check the response Json message type: if (method.getReturnType() != void.class) { requestHandler.responseMessageType = method.getReturnType(); log.info("Response Json: {}", requestHandler.responseMessageType.getSimpleName()); } route.requestHandlers.put(httpMethod, requestHandler); } } } } } } }
public class class_name { void configureEndpoints(Reflections reflections) { // [Re]initialise the api: api = new HashMap<>(); log.info("Scanning for endpoint classes.."); Set<Class<?>> endpoints = reflections.getTypesAnnotatedWith(Api.class); // log.info(reflections.getConfiguration().getUrls()); log.info("Found {} endpoint classes.", endpoints.size()); log.info("Examining endpoint class methods:"); // Configure the classes: for (Class<?> endpointClass : endpoints) { Route route = getEndpoint(endpointClass); route.endpointClass = endpointClass; // depends on control dependency: [for], data = [endpointClass] for (Method method : endpointClass.getMethods()) { // Skip Object methods if (method.getDeclaringClass() == Object.class) { continue; } // Find public methods: if (Modifier.isPublic(method.getModifiers())) { // Which HTTP method(s) will this method respond to? annotation: for (Annotation annotation : method.getAnnotations()) { HttpMethod httpMethod = HttpMethod.method(annotation); if (httpMethod != null) { log.info("Http method: {}", httpMethod); // depends on control dependency: [if], data = [none] RequestHandler requestHandler = new RequestHandler(); requestHandler.handlerMethod = method; // depends on control dependency: [if], data = [none] log.info("Java method: {}", method.getName()); // depends on control dependency: [if], data = [none] // Look for an optional Json message type parameter: for (Class<?> parameterType : method.getParameterTypes()) { if (!HttpServletRequest.class.isAssignableFrom(parameterType) && !HttpServletResponse.class.isAssignableFrom(parameterType)) { if (requestHandler.requestMessageType != null) { log.error("Too many parameters on {} method {}. " + "Message type already set to {} but also found a {} parameter.", httpMethod, method.getName(), requestHandler.requestMessageType.getSimpleName(), parameterType.getSimpleName()); // depends on control dependency: [if], data = [none] break annotation; } requestHandler.requestMessageType = parameterType; // depends on control dependency: [if], data = [none] log.info("request Json: {}", requestHandler.requestMessageType.getSimpleName()); // depends on control dependency: [if], data = [none] } } // Check the response Json message type: if (method.getReturnType() != void.class) { requestHandler.responseMessageType = method.getReturnType(); // depends on control dependency: [if], data = [none] log.info("Response Json: {}", requestHandler.responseMessageType.getSimpleName()); // depends on control dependency: [if], data = [none] } route.requestHandlers.put(httpMethod, requestHandler); // depends on control dependency: [if], data = [(httpMethod] } } } } } } }
public class class_name { public static String prepareArrayClassnameForLoading(String className) { int bracketCount = StringUtil.count(className, '['); if (bracketCount == 0) { // not an array return null; } String brackets = StringUtil.repeat('[', bracketCount); int bracketIndex = className.indexOf('['); className = className.substring(0, bracketIndex); int primitiveNdx = getPrimitiveClassNameIndex(className); if (primitiveNdx >= 0) { className = String.valueOf(PRIMITIVE_BYTECODE_NAME[primitiveNdx]); return brackets + className; } else { return brackets + 'L' + className + ';'; } } }
public class class_name { public static String prepareArrayClassnameForLoading(String className) { int bracketCount = StringUtil.count(className, '['); if (bracketCount == 0) { // not an array return null; // depends on control dependency: [if], data = [none] } String brackets = StringUtil.repeat('[', bracketCount); int bracketIndex = className.indexOf('['); className = className.substring(0, bracketIndex); int primitiveNdx = getPrimitiveClassNameIndex(className); if (primitiveNdx >= 0) { className = String.valueOf(PRIMITIVE_BYTECODE_NAME[primitiveNdx]); // depends on control dependency: [if], data = [none] return brackets + className; // depends on control dependency: [if], data = [none] } else { return brackets + 'L' + className + ';'; // depends on control dependency: [if], data = [none] } } }
public class class_name { public List<Destination> getDestinations() { List<Destination> destinations = new ArrayList<Destination>(); Iterator<JMSDestination> destinationIterator = jmsDestinations.values().iterator(); while(destinationIterator.hasNext()) { destinations.add(destinationIterator.next().destination); } return destinations; } }
public class class_name { public List<Destination> getDestinations() { List<Destination> destinations = new ArrayList<Destination>(); Iterator<JMSDestination> destinationIterator = jmsDestinations.values().iterator(); while(destinationIterator.hasNext()) { destinations.add(destinationIterator.next().destination); // depends on control dependency: [while], data = [none] } return destinations; } }
public class class_name { public void timeout(ServletTimer timer) { SipApplicationSession sipApplicationSession = timer.getApplicationSession(); Map<String, Object> attributes = (Map<String, Object>)timer.getInfo(); try { String callerAddress = (String)attributes.get("caller"); String callerDomain = (String)attributes.get("callerDomain"); SipURI fromURI = sipFactory.createSipURI(callerAddress, callerDomain); Address fromAddress = sipFactory.createAddress(fromURI); String customerName = (String) attributes.get("customerName"); BigDecimal amount = (BigDecimal) attributes.get("amountOrder"); String customerPhone = (String) attributes.get("customerPhone"); String customerContact = (String) attributes.get("customerContact"); Address toAddress = sipFactory.createAddress(customerPhone); logger.info("preparing to call : "+ toAddress); SipServletRequest sipServletRequest = sipFactory.createRequest(sipApplicationSession, "INVITE", fromAddress, toAddress); if(attributes.get("adminApproval") != null) { logger.info("preparing speech for admin approval"); customerContact = (String) attributes.get("adminContactAddress"); //TTS file creation StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(customerName); stringBuffer.append(" has placed an order of $"); stringBuffer.append(amount); stringBuffer.append(". Press 1 to approve and 2 to reject."); sipServletRequest.getSession().setAttribute("speechUri", java.net.URI.create("data:" + URLEncoder.encode("ts("+ stringBuffer +")", "UTF-8"))); } URI requestURI = sipFactory.createURI(customerContact); sipServletRequest.setRequestURI(requestURI); //copying the attributes in the sip session since the media listener depends on it Iterator<Entry<String,Object>> attrIterator = attributes.entrySet().iterator(); while (attrIterator.hasNext()) { Map.Entry<java.lang.String, java.lang.Object> entry = (Map.Entry<java.lang.String, java.lang.Object>) attrIterator .next(); sipServletRequest.getSession().setAttribute(entry.getKey(), entry.getValue()); } SipSession sipSession = sipServletRequest.getSession(); if (sipSession.getAttribute("deliveryDate") != null) { String announcementFile = MMSUtil.audioFilePath + "/OrderDeliveryDate.wav"; sipServletRequest.getSession().setAttribute("speechUri", java.net.URI.create(announcementFile)); logger.info("Preparing to play Delivery Date Announcement : " + announcementFile); } //Media Server Control Creation MediaSession mediaSession = MMSUtil.getMsControl().createMediaSession(); NetworkConnection conn = mediaSession .createNetworkConnection(NetworkConnection.BASIC); SdpPortManager sdpManag = conn.getSdpPortManager(); sdpManag.generateSdpOffer(); byte[] sdpOffer = null; int numTimes = 0; while(sdpOffer == null && numTimes<10) { sdpOffer = sdpManag.getMediaServerSessionDescription(); Thread.sleep(500); numTimes++; } MediaGroup mg = mediaSession.createMediaGroup(MediaGroup.PLAYER_SIGNALDETECTOR); sipServletRequest.getSession().setAttribute("mediaGroup", mg); sipServletRequest.getSession().setAttribute("mediaSession", mediaSession); sipServletRequest.setContentLength(sdpOffer.length); sipServletRequest.setContent(sdpOffer, "application/sdp"); MediaConnectionListener listener = new MediaConnectionListener(); listener.setInviteRequest(sipServletRequest); // provider.addConnectionListener(listener); sipServletRequest.getSession().setAttribute("connection", conn); sipServletRequest.send(); mg.getSignalDetector().addListener(new DTMFListener(mg, sipServletRequest.getSession(), MMSUtil.audioFilePath)); conn.join(Direction.DUPLEX, mg); logger.info("waiting to get the SDP from Media Server before sending the INVITE to " + callerAddress + "@" + callerDomain); } catch (Exception e) { logger.error("An unexpected exception occured while creating the request for delivery date", e); } } }
public class class_name { public void timeout(ServletTimer timer) { SipApplicationSession sipApplicationSession = timer.getApplicationSession(); Map<String, Object> attributes = (Map<String, Object>)timer.getInfo(); try { String callerAddress = (String)attributes.get("caller"); String callerDomain = (String)attributes.get("callerDomain"); SipURI fromURI = sipFactory.createSipURI(callerAddress, callerDomain); Address fromAddress = sipFactory.createAddress(fromURI); String customerName = (String) attributes.get("customerName"); BigDecimal amount = (BigDecimal) attributes.get("amountOrder"); String customerPhone = (String) attributes.get("customerPhone"); String customerContact = (String) attributes.get("customerContact"); Address toAddress = sipFactory.createAddress(customerPhone); logger.info("preparing to call : "+ toAddress); // depends on control dependency: [try], data = [none] SipServletRequest sipServletRequest = sipFactory.createRequest(sipApplicationSession, "INVITE", fromAddress, toAddress); if(attributes.get("adminApproval") != null) { logger.info("preparing speech for admin approval"); // depends on control dependency: [if], data = [none] customerContact = (String) attributes.get("adminContactAddress"); // depends on control dependency: [if], data = [none] //TTS file creation StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(customerName); // depends on control dependency: [if], data = [none] stringBuffer.append(" has placed an order of $"); // depends on control dependency: [if], data = [none] stringBuffer.append(amount); // depends on control dependency: [if], data = [none] stringBuffer.append(". Press 1 to approve and 2 to reject."); // depends on control dependency: [if], data = [none] sipServletRequest.getSession().setAttribute("speechUri", java.net.URI.create("data:" + URLEncoder.encode("ts("+ stringBuffer +")", "UTF-8"))); // depends on control dependency: [if], data = [none] } URI requestURI = sipFactory.createURI(customerContact); sipServletRequest.setRequestURI(requestURI); // depends on control dependency: [try], data = [none] //copying the attributes in the sip session since the media listener depends on it Iterator<Entry<String,Object>> attrIterator = attributes.entrySet().iterator(); while (attrIterator.hasNext()) { Map.Entry<java.lang.String, java.lang.Object> entry = (Map.Entry<java.lang.String, java.lang.Object>) attrIterator .next(); sipServletRequest.getSession().setAttribute(entry.getKey(), entry.getValue()); // depends on control dependency: [while], data = [none] } SipSession sipSession = sipServletRequest.getSession(); if (sipSession.getAttribute("deliveryDate") != null) { String announcementFile = MMSUtil.audioFilePath + "/OrderDeliveryDate.wav"; sipServletRequest.getSession().setAttribute("speechUri", java.net.URI.create(announcementFile)); // depends on control dependency: [if], data = [none] logger.info("Preparing to play Delivery Date Announcement : " + announcementFile); // depends on control dependency: [if], data = [none] } //Media Server Control Creation MediaSession mediaSession = MMSUtil.getMsControl().createMediaSession(); NetworkConnection conn = mediaSession .createNetworkConnection(NetworkConnection.BASIC); SdpPortManager sdpManag = conn.getSdpPortManager(); sdpManag.generateSdpOffer(); // depends on control dependency: [try], data = [none] byte[] sdpOffer = null; int numTimes = 0; while(sdpOffer == null && numTimes<10) { sdpOffer = sdpManag.getMediaServerSessionDescription(); // depends on control dependency: [while], data = [none] Thread.sleep(500); // depends on control dependency: [while], data = [none] numTimes++; // depends on control dependency: [while], data = [none] } MediaGroup mg = mediaSession.createMediaGroup(MediaGroup.PLAYER_SIGNALDETECTOR); sipServletRequest.getSession().setAttribute("mediaGroup", mg); // depends on control dependency: [try], data = [none] sipServletRequest.getSession().setAttribute("mediaSession", mediaSession); // depends on control dependency: [try], data = [none] sipServletRequest.setContentLength(sdpOffer.length); // depends on control dependency: [try], data = [none] sipServletRequest.setContent(sdpOffer, "application/sdp"); // depends on control dependency: [try], data = [none] MediaConnectionListener listener = new MediaConnectionListener(); listener.setInviteRequest(sipServletRequest); // depends on control dependency: [try], data = [none] // provider.addConnectionListener(listener); sipServletRequest.getSession().setAttribute("connection", conn); // depends on control dependency: [try], data = [none] sipServletRequest.send(); // depends on control dependency: [try], data = [none] mg.getSignalDetector().addListener(new DTMFListener(mg, sipServletRequest.getSession(), MMSUtil.audioFilePath)); // depends on control dependency: [try], data = [none] conn.join(Direction.DUPLEX, mg); // depends on control dependency: [try], data = [none] logger.info("waiting to get the SDP from Media Server before sending the INVITE to " + callerAddress + "@" + callerDomain); // depends on control dependency: [try], data = [none] } catch (Exception e) { logger.error("An unexpected exception occured while creating the request for delivery date", e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public long reservePermission(Duration timeoutDuration) { long timeoutInNanos = timeoutDuration.toNanos(); State modifiedState = updateStateWithBackOff(timeoutInNanos); boolean canAcquireImmediately = modifiedState.nanosToWait <= 0; if (canAcquireImmediately) { publishRateLimiterEvent(true); return 0; } boolean canAcquireInTime = timeoutInNanos >= modifiedState.nanosToWait; if (canAcquireInTime) { publishRateLimiterEvent(true); return modifiedState.nanosToWait; } publishRateLimiterEvent(false); return -1; } }
public class class_name { @Override public long reservePermission(Duration timeoutDuration) { long timeoutInNanos = timeoutDuration.toNanos(); State modifiedState = updateStateWithBackOff(timeoutInNanos); boolean canAcquireImmediately = modifiedState.nanosToWait <= 0; if (canAcquireImmediately) { publishRateLimiterEvent(true); // depends on control dependency: [if], data = [none] return 0; // depends on control dependency: [if], data = [none] } boolean canAcquireInTime = timeoutInNanos >= modifiedState.nanosToWait; if (canAcquireInTime) { publishRateLimiterEvent(true); // depends on control dependency: [if], data = [none] return modifiedState.nanosToWait; // depends on control dependency: [if], data = [none] } publishRateLimiterEvent(false); return -1; } }
public class class_name { public ListDeploymentInstancesRequest withInstanceStatusFilter(InstanceStatus... instanceStatusFilter) { com.amazonaws.internal.SdkInternalList<String> instanceStatusFilterCopy = new com.amazonaws.internal.SdkInternalList<String>( instanceStatusFilter.length); for (InstanceStatus value : instanceStatusFilter) { instanceStatusFilterCopy.add(value.toString()); } if (getInstanceStatusFilter() == null) { setInstanceStatusFilter(instanceStatusFilterCopy); } else { getInstanceStatusFilter().addAll(instanceStatusFilterCopy); } return this; } }
public class class_name { public ListDeploymentInstancesRequest withInstanceStatusFilter(InstanceStatus... instanceStatusFilter) { com.amazonaws.internal.SdkInternalList<String> instanceStatusFilterCopy = new com.amazonaws.internal.SdkInternalList<String>( instanceStatusFilter.length); for (InstanceStatus value : instanceStatusFilter) { instanceStatusFilterCopy.add(value.toString()); // depends on control dependency: [for], data = [value] } if (getInstanceStatusFilter() == null) { setInstanceStatusFilter(instanceStatusFilterCopy); // depends on control dependency: [if], data = [none] } else { getInstanceStatusFilter().addAll(instanceStatusFilterCopy); // depends on control dependency: [if], data = [none] } return this; } }
public class class_name { public static MapPro duplicateDataMember(ComponentImpl c, MapPro map, MapPro newMap, boolean deepCopy) { Iterator it = map.entrySet().iterator(); Map.Entry entry; Object value; while (it.hasNext()) { entry = (Entry) it.next(); value = entry.getValue(); if (!(value instanceof UDF)) { if (deepCopy) value = Duplicator.duplicate(value, deepCopy); newMap.put(entry.getKey(), value); } } return newMap; } }
public class class_name { public static MapPro duplicateDataMember(ComponentImpl c, MapPro map, MapPro newMap, boolean deepCopy) { Iterator it = map.entrySet().iterator(); Map.Entry entry; Object value; while (it.hasNext()) { entry = (Entry) it.next(); // depends on control dependency: [while], data = [none] value = entry.getValue(); // depends on control dependency: [while], data = [none] if (!(value instanceof UDF)) { if (deepCopy) value = Duplicator.duplicate(value, deepCopy); newMap.put(entry.getKey(), value); // depends on control dependency: [if], data = [none] } } return newMap; } }
public class class_name { @RequestMapping(value = "/download/{configId}", method = RequestMethod.GET) public HttpEntity<byte[]> downloadDspBill(@PathVariable long configId) { // 业务校验 configValidator.valideConfigExist(configId); ConfListVo config = configMgr.getConfVo(configId); HttpHeaders header = new HttpHeaders(); byte[] res = config.getValue().getBytes(); if (res == null) { throw new DocumentNotFoundException(config.getKey()); } String name = null; try { name = URLEncoder.encode(config.getKey(), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } header.set("Content-Disposition", "attachment; filename=" + name); header.setContentLength(res.length); return new HttpEntity<byte[]>(res, header); } }
public class class_name { @RequestMapping(value = "/download/{configId}", method = RequestMethod.GET) public HttpEntity<byte[]> downloadDspBill(@PathVariable long configId) { // 业务校验 configValidator.valideConfigExist(configId); ConfListVo config = configMgr.getConfVo(configId); HttpHeaders header = new HttpHeaders(); byte[] res = config.getValue().getBytes(); if (res == null) { throw new DocumentNotFoundException(config.getKey()); } String name = null; try { name = URLEncoder.encode(config.getKey(), "UTF-8"); // depends on control dependency: [try], data = [none] } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // depends on control dependency: [catch], data = [none] header.set("Content-Disposition", "attachment; filename=" + name); header.setContentLength(res.length); return new HttpEntity<byte[]>(res, header); } }
public class class_name { public static ApiBodyMetadata mapTypeToPojo(JCodeModel pojoCodeModel, RamlRoot document, TypeDeclaration type) { RamlInterpretationResult interpret = RamlInterpreterFactory.getInterpreterForType(type).interpret(document, type, pojoCodeModel, false); // here we expect that a new object is created i guess... we'd need to // see how primitive arrays fit in JClass pojo = null; if (interpret.getBuilder() != null) { pojo = interpret.getBuilder().getPojo(); } else if (interpret.getResolvedClass() != null) { pojo = interpret.getResolvedClass(); } if (pojo == null) { throw new IllegalStateException("No Pojo created or resolved for type " + type.getClass().getSimpleName() + ":" + type.name()); } if (pojo.name().equals("Void")) { return null; } boolean array = false; String pojoName = pojo.name(); if (pojo.name().contains("List<") || pojo.name().contains("Set<")) { array = true; pojoName = pojo.getTypeParameters().get(0).name(); } return new ApiBodyMetadata(pojoName, type, array, pojoCodeModel); } }
public class class_name { public static ApiBodyMetadata mapTypeToPojo(JCodeModel pojoCodeModel, RamlRoot document, TypeDeclaration type) { RamlInterpretationResult interpret = RamlInterpreterFactory.getInterpreterForType(type).interpret(document, type, pojoCodeModel, false); // here we expect that a new object is created i guess... we'd need to // see how primitive arrays fit in JClass pojo = null; if (interpret.getBuilder() != null) { pojo = interpret.getBuilder().getPojo(); // depends on control dependency: [if], data = [none] } else if (interpret.getResolvedClass() != null) { pojo = interpret.getResolvedClass(); // depends on control dependency: [if], data = [none] } if (pojo == null) { throw new IllegalStateException("No Pojo created or resolved for type " + type.getClass().getSimpleName() + ":" + type.name()); } if (pojo.name().equals("Void")) { return null; // depends on control dependency: [if], data = [none] } boolean array = false; String pojoName = pojo.name(); if (pojo.name().contains("List<") || pojo.name().contains("Set<")) { array = true; // depends on control dependency: [if], data = [none] pojoName = pojo.getTypeParameters().get(0).name(); // depends on control dependency: [if], data = [none] } return new ApiBodyMetadata(pojoName, type, array, pojoCodeModel); } }
public class class_name { private boolean startChannelInChain(Channel targetChannel, Chain chain) throws ChannelException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "startChannelInChain"); } // No need to check parameters since this is called from internal only. String channelName = targetChannel.getName(); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "channelName=" + channelName + " chainName=" + chain.getName()); } boolean channelStarted = false; ChannelContainer channelContainer = channelRunningMap.get(channelName); // No need to check returned channelContainer since this is called from // internal only. RuntimeState channelState = channelContainer.getState(); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Found channel, state: " + channelState.ordinal); } Channel channel = channelContainer.getChannel(); if ((RuntimeState.INITIALIZED == channelState) || (RuntimeState.QUIESCED == channelState)) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Starting channel"); } try { channel.start(); } catch (ChannelException ce) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Channel " + channel + " threw ChannelException " + ce.getMessage()); } throw ce; } catch (Throwable e) { FFDCFilter.processException(e, getClass().getName() + ".startChannelInChain", "1228", this, new Object[] { channel }); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Channel " + channel + " threw non-ChannelException " + e.getMessage()); } throw new ChannelException(e); } channelStarted = true; channelContainer.setState(RuntimeState.STARTED); } else { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Skip channel start, invalid former state: " + channelState.ordinal); } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "startChannelInChain"); } return channelStarted; } }
public class class_name { private boolean startChannelInChain(Channel targetChannel, Chain chain) throws ChannelException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "startChannelInChain"); } // No need to check parameters since this is called from internal only. String channelName = targetChannel.getName(); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "channelName=" + channelName + " chainName=" + chain.getName()); } boolean channelStarted = false; ChannelContainer channelContainer = channelRunningMap.get(channelName); // No need to check returned channelContainer since this is called from // internal only. RuntimeState channelState = channelContainer.getState(); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Found channel, state: " + channelState.ordinal); } Channel channel = channelContainer.getChannel(); if ((RuntimeState.INITIALIZED == channelState) || (RuntimeState.QUIESCED == channelState)) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Starting channel"); // depends on control dependency: [if], data = [none] } try { channel.start(); // depends on control dependency: [try], data = [none] } catch (ChannelException ce) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Channel " + channel + " threw ChannelException " + ce.getMessage()); // depends on control dependency: [if], data = [none] } throw ce; } catch (Throwable e) { // depends on control dependency: [catch], data = [none] FFDCFilter.processException(e, getClass().getName() + ".startChannelInChain", "1228", this, new Object[] { channel }); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Channel " + channel + " threw non-ChannelException " + e.getMessage()); // depends on control dependency: [if], data = [none] } throw new ChannelException(e); } // depends on control dependency: [catch], data = [none] channelStarted = true; channelContainer.setState(RuntimeState.STARTED); } else { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Skip channel start, invalid former state: " + channelState.ordinal); // depends on control dependency: [if], data = [none] } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "startChannelInChain"); } return channelStarted; } }
public class class_name { public static Iterable<BoxWebHook.Info> all(final BoxAPIConnection api, String ... fields) { QueryStringBuilder builder = new QueryStringBuilder(); if (fields.length > 0) { builder.appendParam("fields", fields); } return new BoxResourceIterable<BoxWebHook.Info>( api, WEBHOOKS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()), 64) { @Override protected BoxWebHook.Info factory(JsonObject jsonObject) { BoxWebHook webHook = new BoxWebHook(api, jsonObject.get("id").asString()); return webHook.new Info(jsonObject); } }; } }
public class class_name { public static Iterable<BoxWebHook.Info> all(final BoxAPIConnection api, String ... fields) { QueryStringBuilder builder = new QueryStringBuilder(); if (fields.length > 0) { builder.appendParam("fields", fields); // depends on control dependency: [if], data = [none] } return new BoxResourceIterable<BoxWebHook.Info>( api, WEBHOOKS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), builder.toString()), 64) { @Override protected BoxWebHook.Info factory(JsonObject jsonObject) { BoxWebHook webHook = new BoxWebHook(api, jsonObject.get("id").asString()); return webHook.new Info(jsonObject); } }; } }
public class class_name { public long getWorkspaceDataSize() throws RepositoryException { long dataSize = 0; ResultSet result = null; try { result = findWorkspaceDataSize(); try { if (result.next()) { dataSize += result.getLong(1); } } finally { JDBCUtils.freeResources(result, null, null); } result = findWorkspacePropertiesOnValueStorage(); try { while (result.next()) { String storageDesc = result.getString(DBConstants.COLUMN_VSTORAGE_DESC); String propertyId = result.getString(DBConstants.COLUMN_VPROPERTY_ID); int orderNum = result.getInt(DBConstants.COLUMN_VORDERNUM); ValueIOChannel channel = containerConfig.valueStorageProvider.getChannel(storageDesc); dataSize += channel.getValueSize(getIdentifier(propertyId), orderNum); } } finally { JDBCUtils.freeResources(result, null, null); } } catch (IOException e) { throw new RepositoryException(e); } catch (SQLException e) { throw new RepositoryException(e.getMessage(), e); } return dataSize; } }
public class class_name { public long getWorkspaceDataSize() throws RepositoryException { long dataSize = 0; ResultSet result = null; try { result = findWorkspaceDataSize(); try { if (result.next()) { dataSize += result.getLong(1); // depends on control dependency: [if], data = [none] } } finally { JDBCUtils.freeResources(result, null, null); } result = findWorkspacePropertiesOnValueStorage(); try { while (result.next()) { String storageDesc = result.getString(DBConstants.COLUMN_VSTORAGE_DESC); String propertyId = result.getString(DBConstants.COLUMN_VPROPERTY_ID); int orderNum = result.getInt(DBConstants.COLUMN_VORDERNUM); ValueIOChannel channel = containerConfig.valueStorageProvider.getChannel(storageDesc); dataSize += channel.getValueSize(getIdentifier(propertyId), orderNum); // depends on control dependency: [while], data = [none] } } finally { JDBCUtils.freeResources(result, null, null); } } catch (IOException e) { throw new RepositoryException(e); } catch (SQLException e) { throw new RepositoryException(e.getMessage(), e); } return dataSize; } }
public class class_name { public void setTitleAlignment(final TextAlignment ALIGNMENT) { if (null == titleAlignment) { _titleAlignment = ALIGNMENT; fireTileEvent(RESIZE_EVENT); } else { titleAlignment.set(ALIGNMENT); } } }
public class class_name { public void setTitleAlignment(final TextAlignment ALIGNMENT) { if (null == titleAlignment) { _titleAlignment = ALIGNMENT; // depends on control dependency: [if], data = [none] fireTileEvent(RESIZE_EVENT); // depends on control dependency: [if], data = [none] } else { titleAlignment.set(ALIGNMENT); // depends on control dependency: [if], data = [none] } } }
public class class_name { public <T> Response<T> postFile(Endpoint endpoint, InputStream input, Class<T> responseClass, NameValuePair... fields) throws IOException { // Create the request HttpPost post = new HttpPost(endpoint.url()); post.setHeaders(combineHeaders()); // Add fields as text pairs MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); for (NameValuePair field : fields) { multipartEntityBuilder.addTextBody(field.getName(), field.getValue()); } // Add file as binary Path tempFile = Files.createTempFile("upload", ".dat"); try (OutputStream output = Files.newOutputStream(tempFile)) { IOUtils.copy(input, output); } FileBody bin = new FileBody(tempFile.toFile()); multipartEntityBuilder.addPart("file", bin); // Set the body post.setEntity(multipartEntityBuilder.build()); // Send the request and process the response try (CloseableHttpResponse response = httpClient().execute(post)) { T body = deserialiseResponseMessage(response, responseClass); return new Response<>(response.getStatusLine(), body); } } }
public class class_name { public <T> Response<T> postFile(Endpoint endpoint, InputStream input, Class<T> responseClass, NameValuePair... fields) throws IOException { // Create the request HttpPost post = new HttpPost(endpoint.url()); post.setHeaders(combineHeaders()); // Add fields as text pairs MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); for (NameValuePair field : fields) { multipartEntityBuilder.addTextBody(field.getName(), field.getValue()); // depends on control dependency: [for], data = [field] } // Add file as binary Path tempFile = Files.createTempFile("upload", ".dat"); try (OutputStream output = Files.newOutputStream(tempFile)) { IOUtils.copy(input, output); } FileBody bin = new FileBody(tempFile.toFile()); multipartEntityBuilder.addPart("file", bin); // Set the body post.setEntity(multipartEntityBuilder.build()); // Send the request and process the response try (CloseableHttpResponse response = httpClient().execute(post)) { T body = deserialiseResponseMessage(response, responseClass); return new Response<>(response.getStatusLine(), body); } } }
public class class_name { @Override int[] contribution(IAtomContainer container, RingSearch ringSearch) { final int nAtoms = container.getAtomCount(); final int[] electrons = new int[nAtoms]; Arrays.fill(electrons, -1); final Map<IAtom, Integer> indexMap = Maps.newHashMapWithExpectedSize(nAtoms); for (int i = 0; i < nAtoms; i++) { IAtom atom = container.getAtom(i); indexMap.put(atom, i); // acyclic atom skipped if (!ringSearch.cyclic(i)) continue; Hybridization hyb = atom.getHybridization(); checkNotNull(atom.getAtomTypeName(), "atom has unset atom type"); // atom has been assigned an atom type but we don't know the hybrid state, // typically for atom type 'X' (unknown) if (hyb == null) continue; switch (hyb) { case SP2: case PLANAR3: electrons[i] = electronsForAtomType(atom); break; case SP3: electrons[i] = lonePairCount(atom) > 0 ? 2 : -1; break; } } // exocyclic double bonds are allowed no further processing if (exocyclic) return electrons; // check for exocyclic double/triple bonds and disallow their contribution for (IBond bond : container.bonds()) { if (bond.getOrder() == IBond.Order.DOUBLE || bond.getOrder() == IBond.Order.TRIPLE) { IAtom a1 = bond.getBegin(); IAtom a2 = bond.getEnd(); String a1Type = a1.getAtomTypeName(); String a2Type = a2.getAtomTypeName(); int u = indexMap.get(a1); int v = indexMap.get(a2); if (!ringSearch.cyclic(u, v)) { // XXX: single exception - we could make this more general but // for now this mirrors the existing behavior if (a1Type.equals("N.sp2.3") && a2Type.equals("O.sp2") || a1Type.equals("O.sp2") && a2Type.equals("N.sp2.3")) continue; electrons[u] = electrons[v] = -1; } } } return electrons; } }
public class class_name { @Override int[] contribution(IAtomContainer container, RingSearch ringSearch) { final int nAtoms = container.getAtomCount(); final int[] electrons = new int[nAtoms]; Arrays.fill(electrons, -1); final Map<IAtom, Integer> indexMap = Maps.newHashMapWithExpectedSize(nAtoms); for (int i = 0; i < nAtoms; i++) { IAtom atom = container.getAtom(i); indexMap.put(atom, i); // depends on control dependency: [for], data = [i] // acyclic atom skipped if (!ringSearch.cyclic(i)) continue; Hybridization hyb = atom.getHybridization(); checkNotNull(atom.getAtomTypeName(), "atom has unset atom type"); // depends on control dependency: [for], data = [none] // atom has been assigned an atom type but we don't know the hybrid state, // typically for atom type 'X' (unknown) if (hyb == null) continue; switch (hyb) { case SP2: case PLANAR3: electrons[i] = electronsForAtomType(atom); break; case SP3: electrons[i] = lonePairCount(atom) > 0 ? 2 : -1; break; } } // exocyclic double bonds are allowed no further processing if (exocyclic) return electrons; // check for exocyclic double/triple bonds and disallow their contribution for (IBond bond : container.bonds()) { if (bond.getOrder() == IBond.Order.DOUBLE || bond.getOrder() == IBond.Order.TRIPLE) { IAtom a1 = bond.getBegin(); IAtom a2 = bond.getEnd(); String a1Type = a1.getAtomTypeName(); String a2Type = a2.getAtomTypeName(); int u = indexMap.get(a1); int v = indexMap.get(a2); if (!ringSearch.cyclic(u, v)) { // XXX: single exception - we could make this more general but // for now this mirrors the existing behavior if (a1Type.equals("N.sp2.3") && a2Type.equals("O.sp2") || a1Type.equals("O.sp2") && a2Type.equals("N.sp2.3")) continue; electrons[u] = electrons[v] = -1; } } } return electrons; } }
public class class_name { public TypeIntoStep into(By into) { if (getKeysVariable() != null) { return new TypeIntoStep(getKeysVariable(), into); } else { return new TypeIntoStep(getKeys(), into); } } }
public class class_name { public TypeIntoStep into(By into) { if (getKeysVariable() != null) { return new TypeIntoStep(getKeysVariable(), into); // depends on control dependency: [if], data = [(getKeysVariable()] } else { return new TypeIntoStep(getKeys(), into); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void updateMemberRole(final String memberId, final ConversationMemberRole role, final AVIMConversationCallback callback) { AVIMConversationMemberInfo info = new AVIMConversationMemberInfo(this.conversationId, memberId, role); Map<String, Object> params = new HashMap<String, Object>(); params.put(Conversation.PARAM_CONVERSATION_MEMBER_DETAILS, info.getUpdateAttrs()); boolean ret = InternalConfiguration.getOperationTube().processMembers(this.client.getClientId(), this.conversationId, getType(), JSON.toJSONString(params), Conversation.AVIMOperation.CONVERSATION_PROMOTE_MEMBER, callback); if (!ret && null != callback) { callback.internalDone(new AVException(AVException.OPERATION_FORBIDDEN, "couldn't start service in background.")); } } }
public class class_name { public void updateMemberRole(final String memberId, final ConversationMemberRole role, final AVIMConversationCallback callback) { AVIMConversationMemberInfo info = new AVIMConversationMemberInfo(this.conversationId, memberId, role); Map<String, Object> params = new HashMap<String, Object>(); params.put(Conversation.PARAM_CONVERSATION_MEMBER_DETAILS, info.getUpdateAttrs()); boolean ret = InternalConfiguration.getOperationTube().processMembers(this.client.getClientId(), this.conversationId, getType(), JSON.toJSONString(params), Conversation.AVIMOperation.CONVERSATION_PROMOTE_MEMBER, callback); if (!ret && null != callback) { callback.internalDone(new AVException(AVException.OPERATION_FORBIDDEN, "couldn't start service in background.")); // depends on control dependency: [if], data = [none] } } }
public class class_name { public Long rpush(Object key, Object... values) { Jedis jedis = getJedis(); try { return jedis.rpush(keyToBytes(key), valuesToBytesArray(values)); } finally {close(jedis);} } }
public class class_name { public Long rpush(Object key, Object... values) { Jedis jedis = getJedis(); try { return jedis.rpush(keyToBytes(key), valuesToBytesArray(values)); // depends on control dependency: [try], data = [none] } finally {close(jedis);} } }
public class class_name { public synchronized void setMaxCacheSizeInBytes(final int newsize) { if (validState) { log.info(this.getClass().getName() + "::setMaxCacheSizeInBytes newsize=" + newsize + " flushing write-cache"); privateSync(true, false); clearReadCaches(); } if (newsize >= 1024) { // 1KB minimal maxCacheSizeInBytes = newsize; createReadCaches(); } } }
public class class_name { public synchronized void setMaxCacheSizeInBytes(final int newsize) { if (validState) { log.info(this.getClass().getName() + "::setMaxCacheSizeInBytes newsize=" + newsize + " flushing write-cache"); // depends on control dependency: [if], data = [none] privateSync(true, false); // depends on control dependency: [if], data = [none] clearReadCaches(); // depends on control dependency: [if], data = [none] } if (newsize >= 1024) { // 1KB minimal maxCacheSizeInBytes = newsize; // depends on control dependency: [if], data = [none] createReadCaches(); // depends on control dependency: [if], data = [none] } } }
public class class_name { ReservoirItemsSketch<T> downsampledCopy(final int maxK) { final ReservoirItemsSketch<T> ris = new ReservoirItemsSketch<>(maxK, rf_); for (final T item : getSamples()) { // Pretending old implicit weights are all 1. Not true in general, but they're all // equal so update should work properly as long as we update itemsSeen_ at the end. ris.update(item); } // need to adjust number seen to get correct new implicit weights if (ris.getN() < itemsSeen_) { ris.forceIncrementItemsSeen(itemsSeen_ - ris.getN()); } return ris; } }
public class class_name { ReservoirItemsSketch<T> downsampledCopy(final int maxK) { final ReservoirItemsSketch<T> ris = new ReservoirItemsSketch<>(maxK, rf_); for (final T item : getSamples()) { // Pretending old implicit weights are all 1. Not true in general, but they're all // equal so update should work properly as long as we update itemsSeen_ at the end. ris.update(item); // depends on control dependency: [for], data = [item] } // need to adjust number seen to get correct new implicit weights if (ris.getN() < itemsSeen_) { ris.forceIncrementItemsSeen(itemsSeen_ - ris.getN()); // depends on control dependency: [if], data = [none] } return ris; } }
public class class_name { @Reference(name = "sslSupport", service = ChannelFactoryProvider.class, policy = ReferencePolicy.DYNAMIC, policyOption = ReferencePolicyOption.GREEDY, cardinality = ReferenceCardinality.OPTIONAL, target = "(type=SSLChannel)") protected void setSslSupport(ServiceReference<ChannelFactoryProvider> ref) { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(this, tc, "enable ssl support " + ref.getProperty("type"), this); } sslFactoryProvider.setReference(ref); httpSecureChain.enable(); if (endpointConfig != null) { // If this is post-activate, drive the update action performAction(updateAction); } } }
public class class_name { @Reference(name = "sslSupport", service = ChannelFactoryProvider.class, policy = ReferencePolicy.DYNAMIC, policyOption = ReferencePolicyOption.GREEDY, cardinality = ReferenceCardinality.OPTIONAL, target = "(type=SSLChannel)") protected void setSslSupport(ServiceReference<ChannelFactoryProvider> ref) { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(this, tc, "enable ssl support " + ref.getProperty("type"), this); // depends on control dependency: [if], data = [none] } sslFactoryProvider.setReference(ref); httpSecureChain.enable(); if (endpointConfig != null) { // If this is post-activate, drive the update action performAction(updateAction); // depends on control dependency: [if], data = [none] } } }
public class class_name { protected CmsContainerPageBean cleanupContainersContainers(CmsObject cms, CmsContainerPageBean cntPage) { // get the used containers first Map<String, CmsContainerBean> currentContainers = cntPage.getContainers(); List<CmsContainerBean> containers = new ArrayList<CmsContainerBean>(); for (String cntName : cntPage.getNames()) { CmsContainerBean container = currentContainers.get(cntName); if (!container.getElements().isEmpty()) { containers.add(container); } } // now get the unused containers CmsContainerPageBean currentContainerPage = getContainerPage(cms); if (currentContainerPage != null) { for (String cntName : currentContainerPage.getNames()) { if (!currentContainers.containsKey(cntName)) { CmsContainerBean container = currentContainerPage.getContainers().get(cntName); if (!container.getElements().isEmpty()) { containers.add(container); } } } } // check if any nested containers have lost their parent element // first collect all present elements Map<String, CmsContainerElementBean> pageElements = new HashMap<String, CmsContainerElementBean>(); Map<String, String> parentContainers = new HashMap<String, String>(); for (CmsContainerBean container : containers) { for (CmsContainerElementBean element : container.getElements()) { try { element.initResource(cms); if (!CmsModelGroupHelper.isModelGroupResource(element.getResource())) { pageElements.put(element.getInstanceId(), element); parentContainers.put(element.getInstanceId(), container.getName()); } } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); } } } Iterator<CmsContainerBean> cntIt = containers.iterator(); while (cntIt.hasNext()) { CmsContainerBean container = cntIt.next(); // check all unused nested containers if their parent element is still part of the page if (!currentContainers.containsKey(container.getName()) && (container.isNestedContainer() && !container.isRootContainer())) { boolean remove = !pageElements.containsKey(container.getParentInstanceId()) || container.getElements().isEmpty(); if (!remove) { // check if the parent element formatter is set to strictly render all nested containers CmsContainerElementBean element = pageElements.get(container.getParentInstanceId()); String settingsKey = CmsFormatterConfig.getSettingsKeyForContainer( parentContainers.get(element.getInstanceId())); String formatterId = element.getIndividualSettings().get(settingsKey); if (CmsUUID.isValidUUID(formatterId)) { I_CmsFormatterBean formatterBean = OpenCms.getADEManager().getCachedFormatters( false).getFormatters().get(new CmsUUID(formatterId)); remove = (formatterBean instanceof CmsFormatterBean) && ((CmsFormatterBean)formatterBean).isStrictContainers(); } } if (remove) { // remove the sub elements from the page list for (CmsContainerElementBean element : container.getElements()) { pageElements.remove(element.getInstanceId()); } // remove the container cntIt.remove(); } } } return new CmsContainerPageBean(containers); } }
public class class_name { protected CmsContainerPageBean cleanupContainersContainers(CmsObject cms, CmsContainerPageBean cntPage) { // get the used containers first Map<String, CmsContainerBean> currentContainers = cntPage.getContainers(); List<CmsContainerBean> containers = new ArrayList<CmsContainerBean>(); for (String cntName : cntPage.getNames()) { CmsContainerBean container = currentContainers.get(cntName); if (!container.getElements().isEmpty()) { containers.add(container); // depends on control dependency: [if], data = [none] } } // now get the unused containers CmsContainerPageBean currentContainerPage = getContainerPage(cms); if (currentContainerPage != null) { for (String cntName : currentContainerPage.getNames()) { if (!currentContainers.containsKey(cntName)) { CmsContainerBean container = currentContainerPage.getContainers().get(cntName); if (!container.getElements().isEmpty()) { containers.add(container); // depends on control dependency: [if], data = [none] } } } } // check if any nested containers have lost their parent element // first collect all present elements Map<String, CmsContainerElementBean> pageElements = new HashMap<String, CmsContainerElementBean>(); Map<String, String> parentContainers = new HashMap<String, String>(); for (CmsContainerBean container : containers) { for (CmsContainerElementBean element : container.getElements()) { try { element.initResource(cms); // depends on control dependency: [try], data = [none] if (!CmsModelGroupHelper.isModelGroupResource(element.getResource())) { pageElements.put(element.getInstanceId(), element); // depends on control dependency: [if], data = [none] parentContainers.put(element.getInstanceId(), container.getName()); // depends on control dependency: [if], data = [none] } } catch (CmsException e) { LOG.warn(e.getLocalizedMessage(), e); } // depends on control dependency: [catch], data = [none] } } Iterator<CmsContainerBean> cntIt = containers.iterator(); while (cntIt.hasNext()) { CmsContainerBean container = cntIt.next(); // check all unused nested containers if their parent element is still part of the page if (!currentContainers.containsKey(container.getName()) && (container.isNestedContainer() && !container.isRootContainer())) { boolean remove = !pageElements.containsKey(container.getParentInstanceId()) || container.getElements().isEmpty(); if (!remove) { // check if the parent element formatter is set to strictly render all nested containers CmsContainerElementBean element = pageElements.get(container.getParentInstanceId()); String settingsKey = CmsFormatterConfig.getSettingsKeyForContainer( parentContainers.get(element.getInstanceId())); String formatterId = element.getIndividualSettings().get(settingsKey); if (CmsUUID.isValidUUID(formatterId)) { I_CmsFormatterBean formatterBean = OpenCms.getADEManager().getCachedFormatters( false).getFormatters().get(new CmsUUID(formatterId)); remove = (formatterBean instanceof CmsFormatterBean) && ((CmsFormatterBean)formatterBean).isStrictContainers(); // depends on control dependency: [if], data = [none] } } if (remove) { // remove the sub elements from the page list for (CmsContainerElementBean element : container.getElements()) { pageElements.remove(element.getInstanceId()); // depends on control dependency: [for], data = [element] } // remove the container cntIt.remove(); // depends on control dependency: [if], data = [none] } } } return new CmsContainerPageBean(containers); } }
public class class_name { public double[][] getSummedMarginals() { double[][] results = new double[neighborIndices.length][]; for (int i = 0; i < neighborIndices.length; i++) { results[i] = new double[getDimensions()[i]]; } double[][] maxValues = new double[neighborIndices.length][]; for (int i = 0; i < neighborIndices.length; i++) { maxValues[i] = new double[getDimensions()[i]]; for (int j = 0; j < maxValues[i].length; j++) maxValues[i][j] = Double.NEGATIVE_INFINITY; } // Get max values // OPTIMIZATION: // Rather than use the standard iterator, which creates lots of int[] arrays on the heap, which need to be GC'd, // we use the fast version that just mutates one array. Since this is read once for us here, this is ideal. Iterator<int[]> fastPassByReferenceIterator = fastPassByReferenceIterator(); int[] assignment = fastPassByReferenceIterator.next(); while (true) { double v = getAssignmentLogValue(assignment); for (int i = 0; i < neighborIndices.length; i++) { if (maxValues[i][assignment[i]] < v) maxValues[i][assignment[i]] = v; } // This mutates the resultAssignment[] array, rather than creating a new one if (fastPassByReferenceIterator.hasNext()) { fastPassByReferenceIterator.next(); } else break; } // Do the summation // OPTIMIZATION: // Rather than use the standard iterator, which creates lots of int[] arrays on the heap, which need to be GC'd, // we use the fast version that just mutates one array. Since this is read once for us here, this is ideal. Iterator<int[]> secondFastPassByReferenceIterator = fastPassByReferenceIterator(); assignment = secondFastPassByReferenceIterator.next(); while (true) { double v = getAssignmentLogValue(assignment); for (int i = 0; i < neighborIndices.length; i++) { if (USE_EXP_APPROX) { results[i][assignment[i]] += exp(v - maxValues[i][assignment[i]]); } else { results[i][assignment[i]] += Math.exp(v - maxValues[i][assignment[i]]); } } // This mutates the resultAssignment[] array, rather than creating a new one if (secondFastPassByReferenceIterator.hasNext()) { secondFastPassByReferenceIterator.next(); } else break; } // normalize results, and move to linear space for (int i = 0; i < neighborIndices.length; i++) { double sum = 0.0; for (int j = 0; j < results[i].length; j++) { if (USE_EXP_APPROX) { results[i][j] = exp(maxValues[i][j]) * results[i][j]; } else { results[i][j] = Math.exp(maxValues[i][j]) * results[i][j]; } sum += results[i][j]; } if (Double.isInfinite(sum)) { for (int j = 0; j < results[i].length; j++) { results[i][j] = 1.0 / results[i].length; } } else { for (int j = 0; j < results[i].length; j++) { results[i][j] /= sum; } } } return results; } }
public class class_name { public double[][] getSummedMarginals() { double[][] results = new double[neighborIndices.length][]; for (int i = 0; i < neighborIndices.length; i++) { results[i] = new double[getDimensions()[i]]; // depends on control dependency: [for], data = [i] } double[][] maxValues = new double[neighborIndices.length][]; for (int i = 0; i < neighborIndices.length; i++) { maxValues[i] = new double[getDimensions()[i]]; // depends on control dependency: [for], data = [i] for (int j = 0; j < maxValues[i].length; j++) maxValues[i][j] = Double.NEGATIVE_INFINITY; } // Get max values // OPTIMIZATION: // Rather than use the standard iterator, which creates lots of int[] arrays on the heap, which need to be GC'd, // we use the fast version that just mutates one array. Since this is read once for us here, this is ideal. Iterator<int[]> fastPassByReferenceIterator = fastPassByReferenceIterator(); int[] assignment = fastPassByReferenceIterator.next(); while (true) { double v = getAssignmentLogValue(assignment); for (int i = 0; i < neighborIndices.length; i++) { if (maxValues[i][assignment[i]] < v) maxValues[i][assignment[i]] = v; } // This mutates the resultAssignment[] array, rather than creating a new one if (fastPassByReferenceIterator.hasNext()) { fastPassByReferenceIterator.next(); // depends on control dependency: [if], data = [none] } else break; } // Do the summation // OPTIMIZATION: // Rather than use the standard iterator, which creates lots of int[] arrays on the heap, which need to be GC'd, // we use the fast version that just mutates one array. Since this is read once for us here, this is ideal. Iterator<int[]> secondFastPassByReferenceIterator = fastPassByReferenceIterator(); assignment = secondFastPassByReferenceIterator.next(); while (true) { double v = getAssignmentLogValue(assignment); for (int i = 0; i < neighborIndices.length; i++) { if (USE_EXP_APPROX) { results[i][assignment[i]] += exp(v - maxValues[i][assignment[i]]); // depends on control dependency: [if], data = [none] } else { results[i][assignment[i]] += Math.exp(v - maxValues[i][assignment[i]]); // depends on control dependency: [if], data = [none] } } // This mutates the resultAssignment[] array, rather than creating a new one if (secondFastPassByReferenceIterator.hasNext()) { secondFastPassByReferenceIterator.next(); // depends on control dependency: [if], data = [none] } else break; } // normalize results, and move to linear space for (int i = 0; i < neighborIndices.length; i++) { double sum = 0.0; for (int j = 0; j < results[i].length; j++) { if (USE_EXP_APPROX) { results[i][j] = exp(maxValues[i][j]) * results[i][j]; // depends on control dependency: [if], data = [none] } else { results[i][j] = Math.exp(maxValues[i][j]) * results[i][j]; // depends on control dependency: [if], data = [none] } sum += results[i][j]; // depends on control dependency: [for], data = [j] } if (Double.isInfinite(sum)) { for (int j = 0; j < results[i].length; j++) { results[i][j] = 1.0 / results[i].length; // depends on control dependency: [for], data = [j] } } else { for (int j = 0; j < results[i].length; j++) { results[i][j] /= sum; // depends on control dependency: [for], data = [j] } } } return results; } }
public class class_name { protected String getWffPrintStructure() { final String attributeValue = this.attributeValue; String result = ""; beforeWffPrintStructure(); final StringBuilder attrBuilder = new StringBuilder(); attrBuilder.append(attributeName); if (attributeValue != null) { attrBuilder.append(new char[] { '=' }).append(attributeValue); result = StringBuilderUtil.getTrimmedString(attrBuilder); } else if (attributeValueMap != null && attributeValueMap.size() > 0) { attrBuilder.append(new char[] { '=' }); final Set<Entry<String, String>> entrySet = getAttributeValueMap() .entrySet(); for (final Entry<String, String> entry : entrySet) { attrBuilder.append(entry.getKey()).append(':') .append(entry.getValue()).append(';'); } result = StringBuilderUtil.getTrimmedString(attrBuilder); } else if (attributeValueSet != null && attributeValueSet.size() > 0) { attrBuilder.append(new char[] { '=' }); for (final String each : getAttributeValueSet()) { attrBuilder.append(each).append(' '); } result = StringBuilderUtil.getTrimmedString(attrBuilder); } else { result = attrBuilder.toString(); } return result; } }
public class class_name { protected String getWffPrintStructure() { final String attributeValue = this.attributeValue; String result = ""; beforeWffPrintStructure(); final StringBuilder attrBuilder = new StringBuilder(); attrBuilder.append(attributeName); if (attributeValue != null) { attrBuilder.append(new char[] { '=' }).append(attributeValue); // depends on control dependency: [if], data = [(attributeValue] result = StringBuilderUtil.getTrimmedString(attrBuilder); // depends on control dependency: [if], data = [none] } else if (attributeValueMap != null && attributeValueMap.size() > 0) { attrBuilder.append(new char[] { '=' }); // depends on control dependency: [if], data = [none] final Set<Entry<String, String>> entrySet = getAttributeValueMap() .entrySet(); for (final Entry<String, String> entry : entrySet) { attrBuilder.append(entry.getKey()).append(':') .append(entry.getValue()).append(';'); // depends on control dependency: [for], data = [entry] } result = StringBuilderUtil.getTrimmedString(attrBuilder); // depends on control dependency: [if], data = [none] } else if (attributeValueSet != null && attributeValueSet.size() > 0) { attrBuilder.append(new char[] { '=' }); // depends on control dependency: [if], data = [none] for (final String each : getAttributeValueSet()) { attrBuilder.append(each).append(' '); // depends on control dependency: [for], data = [each] } result = StringBuilderUtil.getTrimmedString(attrBuilder); // depends on control dependency: [if], data = [none] } else { result = attrBuilder.toString(); // depends on control dependency: [if], data = [none] } return result; } }
public class class_name { public boolean isRunning() { try { client.get("/"); return true; } catch (IOException e) { LOGGER.debug("isRunning()", e); return false; } } }
public class class_name { public boolean isRunning() { try { client.get("/"); // depends on control dependency: [try], data = [none] return true; // depends on control dependency: [try], data = [none] } catch (IOException e) { LOGGER.debug("isRunning()", e); return false; } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void marshall(AttachTypedLinkRequest attachTypedLinkRequest, ProtocolMarshaller protocolMarshaller) { if (attachTypedLinkRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(attachTypedLinkRequest.getDirectoryArn(), DIRECTORYARN_BINDING); protocolMarshaller.marshall(attachTypedLinkRequest.getSourceObjectReference(), SOURCEOBJECTREFERENCE_BINDING); protocolMarshaller.marshall(attachTypedLinkRequest.getTargetObjectReference(), TARGETOBJECTREFERENCE_BINDING); protocolMarshaller.marshall(attachTypedLinkRequest.getTypedLinkFacet(), TYPEDLINKFACET_BINDING); protocolMarshaller.marshall(attachTypedLinkRequest.getAttributes(), ATTRIBUTES_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(AttachTypedLinkRequest attachTypedLinkRequest, ProtocolMarshaller protocolMarshaller) { if (attachTypedLinkRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(attachTypedLinkRequest.getDirectoryArn(), DIRECTORYARN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(attachTypedLinkRequest.getSourceObjectReference(), SOURCEOBJECTREFERENCE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(attachTypedLinkRequest.getTargetObjectReference(), TARGETOBJECTREFERENCE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(attachTypedLinkRequest.getTypedLinkFacet(), TYPEDLINKFACET_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(attachTypedLinkRequest.getAttributes(), ATTRIBUTES_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 DrawerBuilder withStickyHeader(@LayoutRes int stickyHeaderRes) { if (mActivity == null) { throw new RuntimeException("please pass an activity first to use this call"); } if (stickyHeaderRes != -1) { //i know there should be a root, bit i got none here this.mStickyHeaderView = mActivity.getLayoutInflater().inflate(stickyHeaderRes, null, false); } return this; } }
public class class_name { public DrawerBuilder withStickyHeader(@LayoutRes int stickyHeaderRes) { if (mActivity == null) { throw new RuntimeException("please pass an activity first to use this call"); } if (stickyHeaderRes != -1) { //i know there should be a root, bit i got none here this.mStickyHeaderView = mActivity.getLayoutInflater().inflate(stickyHeaderRes, null, false); // depends on control dependency: [if], data = [(stickyHeaderRes] } return this; } }
public class class_name { public CmsSite matchSite(CmsSiteMatcher matcher) { CmsSite site = m_siteMatcherSites.get(matcher); if (site == null) { // return the default site (might be null as well) site = m_defaultSite; } return site; } }
public class class_name { public CmsSite matchSite(CmsSiteMatcher matcher) { CmsSite site = m_siteMatcherSites.get(matcher); if (site == null) { // return the default site (might be null as well) site = m_defaultSite; // depends on control dependency: [if], data = [none] } return site; } }
public class class_name { public void moveAttributeValue(CmsAttributeValueView valueView, int currentPosition, int targetPosition) { if (currentPosition == targetPosition) { return; } FlowPanel parent = (FlowPanel)valueView.getParent(); m_widgetService.addChangedOrderPath(getSimplePath(-1)); valueView.removeFromParent(); m_attributeValueViews.remove(valueView); CmsAttributeValueView valueWidget = null; if (isChoiceHandler()) { removeHandlers(currentPosition); CmsEntity value = m_entity.getAttribute(m_attributeName).getComplexValues().get(currentPosition); m_entity.removeAttributeValue(m_attributeName, currentPosition); m_entity.insertAttributeValue(m_attributeName, value, targetPosition); String attributeChoice = getChoiceName(targetPosition); CmsType optionType = getAttributeType().getAttributeType(attributeChoice); valueWidget = new CmsAttributeValueView( this, m_widgetService.getAttributeLabel(attributeChoice), m_widgetService.getAttributeHelp(attributeChoice)); if (optionType.isSimpleType() && m_widgetService.isDisplaySingleLine(attributeChoice)) { valueWidget.setCompactMode(CmsAttributeValueView.COMPACT_MODE_SINGLE_LINE); } parent.insert(valueWidget, targetPosition); insertHandlers(targetPosition); if (optionType.isSimpleType()) { valueWidget.setValueWidget( m_widgetService.getAttributeFormWidget(attributeChoice), value.getAttribute(attributeChoice).getSimpleValue(), m_widgetService.getDefaultAttributeValue(attributeChoice, getSimplePath(targetPosition)), true); } else { valueWidget.setValueEntity( m_widgetService.getRendererForAttribute(attributeChoice, getAttributeType()), value.getAttribute(attributeChoice).getComplexValue()); } List<CmsChoiceMenuEntryBean> menuEntries = CmsRenderer.getChoiceEntries(getAttributeType(), true); for (CmsChoiceMenuEntryBean menuEntry : menuEntries) { valueWidget.addChoice(m_widgetService, menuEntry); } } else if (getAttributeType().isSimpleType()) { String value = m_entity.getAttribute(m_attributeName).getSimpleValues().get(currentPosition); m_entity.removeAttributeValue(m_attributeName, currentPosition); m_entity.insertAttributeValue(m_attributeName, value, targetPosition); valueWidget = new CmsAttributeValueView( this, m_widgetService.getAttributeLabel(m_attributeName), m_widgetService.getAttributeHelp(m_attributeName)); if (m_widgetService.isDisplaySingleLine(m_attributeName)) { valueWidget.setCompactMode(CmsAttributeValueView.COMPACT_MODE_SINGLE_LINE); } parent.insert(valueWidget, targetPosition); valueWidget.setValueWidget( m_widgetService.getAttributeFormWidget(m_attributeName), value, m_widgetService.getDefaultAttributeValue(m_attributeName, getSimplePath(targetPosition)), true); } else { removeHandlers(currentPosition); CmsEntity value = m_entity.getAttribute(m_attributeName).getComplexValues().get(currentPosition); m_entity.removeAttributeValue(m_attributeName, currentPosition); m_entity.insertAttributeValue(m_attributeName, value, targetPosition); valueWidget = new CmsAttributeValueView( this, m_widgetService.getAttributeLabel(m_attributeName), m_widgetService.getAttributeHelp(m_attributeName)); parent.insert(valueWidget, targetPosition); insertHandlers(targetPosition); valueWidget.setValueEntity( m_widgetService.getRendererForAttribute(m_attributeName, getAttributeType()), value); if (getAttributeType().getAttributeType(CmsType.CHOICE_ATTRIBUTE_NAME) != null) { List<CmsChoiceMenuEntryBean> menuEntries = CmsRenderer.getChoiceEntries(getAttributeType(), false); for (CmsChoiceMenuEntryBean entry : menuEntries) { valueWidget.addChoice(m_widgetService, entry); } } } m_attributeValueViews.remove(valueWidget); m_attributeValueViews.add(targetPosition, valueWidget); updateButtonVisisbility(); CmsUndoRedoHandler handler = CmsUndoRedoHandler.getInstance(); if (handler.isIntitalized()) { handler.addChange(m_entity.getId(), m_attributeName, 0, ChangeType.sort); } } }
public class class_name { public void moveAttributeValue(CmsAttributeValueView valueView, int currentPosition, int targetPosition) { if (currentPosition == targetPosition) { return; // depends on control dependency: [if], data = [none] } FlowPanel parent = (FlowPanel)valueView.getParent(); m_widgetService.addChangedOrderPath(getSimplePath(-1)); valueView.removeFromParent(); m_attributeValueViews.remove(valueView); CmsAttributeValueView valueWidget = null; if (isChoiceHandler()) { removeHandlers(currentPosition); // depends on control dependency: [if], data = [none] CmsEntity value = m_entity.getAttribute(m_attributeName).getComplexValues().get(currentPosition); m_entity.removeAttributeValue(m_attributeName, currentPosition); // depends on control dependency: [if], data = [none] m_entity.insertAttributeValue(m_attributeName, value, targetPosition); // depends on control dependency: [if], data = [none] String attributeChoice = getChoiceName(targetPosition); CmsType optionType = getAttributeType().getAttributeType(attributeChoice); valueWidget = new CmsAttributeValueView( this, m_widgetService.getAttributeLabel(attributeChoice), m_widgetService.getAttributeHelp(attributeChoice)); // depends on control dependency: [if], data = [none] if (optionType.isSimpleType() && m_widgetService.isDisplaySingleLine(attributeChoice)) { valueWidget.setCompactMode(CmsAttributeValueView.COMPACT_MODE_SINGLE_LINE); // depends on control dependency: [if], data = [none] } parent.insert(valueWidget, targetPosition); // depends on control dependency: [if], data = [none] insertHandlers(targetPosition); // depends on control dependency: [if], data = [none] if (optionType.isSimpleType()) { valueWidget.setValueWidget( m_widgetService.getAttributeFormWidget(attributeChoice), value.getAttribute(attributeChoice).getSimpleValue(), m_widgetService.getDefaultAttributeValue(attributeChoice, getSimplePath(targetPosition)), true); // depends on control dependency: [if], data = [none] } else { valueWidget.setValueEntity( m_widgetService.getRendererForAttribute(attributeChoice, getAttributeType()), value.getAttribute(attributeChoice).getComplexValue()); // depends on control dependency: [if], data = [none] } List<CmsChoiceMenuEntryBean> menuEntries = CmsRenderer.getChoiceEntries(getAttributeType(), true); for (CmsChoiceMenuEntryBean menuEntry : menuEntries) { valueWidget.addChoice(m_widgetService, menuEntry); // depends on control dependency: [for], data = [menuEntry] } } else if (getAttributeType().isSimpleType()) { String value = m_entity.getAttribute(m_attributeName).getSimpleValues().get(currentPosition); m_entity.removeAttributeValue(m_attributeName, currentPosition); // depends on control dependency: [if], data = [none] m_entity.insertAttributeValue(m_attributeName, value, targetPosition); // depends on control dependency: [if], data = [none] valueWidget = new CmsAttributeValueView( this, m_widgetService.getAttributeLabel(m_attributeName), m_widgetService.getAttributeHelp(m_attributeName)); // depends on control dependency: [if], data = [none] if (m_widgetService.isDisplaySingleLine(m_attributeName)) { valueWidget.setCompactMode(CmsAttributeValueView.COMPACT_MODE_SINGLE_LINE); // depends on control dependency: [if], data = [none] } parent.insert(valueWidget, targetPosition); // depends on control dependency: [if], data = [none] valueWidget.setValueWidget( m_widgetService.getAttributeFormWidget(m_attributeName), value, m_widgetService.getDefaultAttributeValue(m_attributeName, getSimplePath(targetPosition)), true); // depends on control dependency: [if], data = [none] } else { removeHandlers(currentPosition); // depends on control dependency: [if], data = [none] CmsEntity value = m_entity.getAttribute(m_attributeName).getComplexValues().get(currentPosition); m_entity.removeAttributeValue(m_attributeName, currentPosition); // depends on control dependency: [if], data = [none] m_entity.insertAttributeValue(m_attributeName, value, targetPosition); // depends on control dependency: [if], data = [none] valueWidget = new CmsAttributeValueView( this, m_widgetService.getAttributeLabel(m_attributeName), m_widgetService.getAttributeHelp(m_attributeName)); // depends on control dependency: [if], data = [none] parent.insert(valueWidget, targetPosition); // depends on control dependency: [if], data = [none] insertHandlers(targetPosition); // depends on control dependency: [if], data = [none] valueWidget.setValueEntity( m_widgetService.getRendererForAttribute(m_attributeName, getAttributeType()), value); // depends on control dependency: [if], data = [none] if (getAttributeType().getAttributeType(CmsType.CHOICE_ATTRIBUTE_NAME) != null) { List<CmsChoiceMenuEntryBean> menuEntries = CmsRenderer.getChoiceEntries(getAttributeType(), false); for (CmsChoiceMenuEntryBean entry : menuEntries) { valueWidget.addChoice(m_widgetService, entry); // depends on control dependency: [for], data = [entry] } } } m_attributeValueViews.remove(valueWidget); m_attributeValueViews.add(targetPosition, valueWidget); updateButtonVisisbility(); CmsUndoRedoHandler handler = CmsUndoRedoHandler.getInstance(); if (handler.isIntitalized()) { handler.addChange(m_entity.getId(), m_attributeName, 0, ChangeType.sort); // depends on control dependency: [if], data = [none] } } }
public class class_name { public String getRawPropertyValue(String key) { String value = super.getProperty(key); if (value != null) { return value; } for (Properties properties : defaults) { value = properties.getProperty(key); if (value != null) { return value; } } return null; } }
public class class_name { public String getRawPropertyValue(String key) { String value = super.getProperty(key); if (value != null) { return value; // depends on control dependency: [if], data = [none] } for (Properties properties : defaults) { value = properties.getProperty(key); // depends on control dependency: [for], data = [properties] if (value != null) { return value; // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { public void marshall(StopApplicationRequest stopApplicationRequest, ProtocolMarshaller protocolMarshaller) { if (stopApplicationRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(stopApplicationRequest.getApplicationName(), APPLICATIONNAME_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(StopApplicationRequest stopApplicationRequest, ProtocolMarshaller protocolMarshaller) { if (stopApplicationRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(stopApplicationRequest.getApplicationName(), APPLICATIONNAME_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 revokeService(Class serviceClass, BeanContextServiceProvider serviceProvider, boolean revokeCurrentServicesNow) { if (serviceClass == null || serviceProvider == null) { throw new NullPointerException(); } synchronized (globalHierarchyLock) { synchronized (services) { BCSSServiceProvider bcssProvider = (BCSSServiceProvider) services.get(serviceClass); if (bcssProvider == null) { // non-exist service return; } if (bcssProvider.getServiceProvider() != serviceProvider) { throw new IllegalArgumentException(Messages.getString("beans.66")); } services.remove(serviceClass); if (serviceProvider instanceof Serializable) { serializable--; } } } // notify listeners fireServiceRevoked(serviceClass, revokeCurrentServicesNow); // notify service users notifyServiceRevokedToServiceUsers(serviceClass, serviceProvider, revokeCurrentServicesNow); } }
public class class_name { public void revokeService(Class serviceClass, BeanContextServiceProvider serviceProvider, boolean revokeCurrentServicesNow) { if (serviceClass == null || serviceProvider == null) { throw new NullPointerException(); } synchronized (globalHierarchyLock) { synchronized (services) { BCSSServiceProvider bcssProvider = (BCSSServiceProvider) services.get(serviceClass); if (bcssProvider == null) { // non-exist service return; // depends on control dependency: [if], data = [none] } if (bcssProvider.getServiceProvider() != serviceProvider) { throw new IllegalArgumentException(Messages.getString("beans.66")); } services.remove(serviceClass); if (serviceProvider instanceof Serializable) { serializable--; // depends on control dependency: [if], data = [none] } } } // notify listeners fireServiceRevoked(serviceClass, revokeCurrentServicesNow); // notify service users notifyServiceRevokedToServiceUsers(serviceClass, serviceProvider, revokeCurrentServicesNow); } }
public class class_name { public ServiceCall<ListModelsResults> listModels(ListModelsOptions listModelsOptions) { String[] pathSegments = { "v1/models" }; RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments)); builder.query("version", versionDate); Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("natural-language-understanding", "v1", "listModels"); for (Entry<String, String> header : sdkHeaders.entrySet()) { builder.header(header.getKey(), header.getValue()); } builder.header("Accept", "application/json"); if (listModelsOptions != null) { } return createServiceCall(builder.build(), ResponseConverterUtils.getObject(ListModelsResults.class)); } }
public class class_name { public ServiceCall<ListModelsResults> listModels(ListModelsOptions listModelsOptions) { String[] pathSegments = { "v1/models" }; RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments)); builder.query("version", versionDate); Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("natural-language-understanding", "v1", "listModels"); for (Entry<String, String> header : sdkHeaders.entrySet()) { builder.header(header.getKey(), header.getValue()); // depends on control dependency: [for], data = [header] } builder.header("Accept", "application/json"); if (listModelsOptions != null) { } return createServiceCall(builder.build(), ResponseConverterUtils.getObject(ListModelsResults.class)); } }
public class class_name { public Observable<ServiceResponse<IssuerBundle>> deleteCertificateIssuerWithServiceResponseAsync(String vaultBaseUrl, String issuerName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } if (issuerName == null) { throw new IllegalArgumentException("Parameter issuerName is required and cannot be null."); } if (this.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); return service.deleteCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<IssuerBundle>>>() { @Override public Observable<ServiceResponse<IssuerBundle>> call(Response<ResponseBody> response) { try { ServiceResponse<IssuerBundle> clientResponse = deleteCertificateIssuerDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } }
public class class_name { public Observable<ServiceResponse<IssuerBundle>> deleteCertificateIssuerWithServiceResponseAsync(String vaultBaseUrl, String issuerName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } if (issuerName == null) { throw new IllegalArgumentException("Parameter issuerName is required and cannot be null."); } if (this.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl); return service.deleteCertificateIssuer(issuerName, this.apiVersion(), this.acceptLanguage(), parameterizedHost, this.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<IssuerBundle>>>() { @Override public Observable<ServiceResponse<IssuerBundle>> call(Response<ResponseBody> response) { try { ServiceResponse<IssuerBundle> clientResponse = deleteCertificateIssuerDelegate(response); return Observable.just(clientResponse); // depends on control dependency: [try], data = [none] } catch (Throwable t) { return Observable.error(t); } // depends on control dependency: [catch], data = [none] } }); } }
public class class_name { public int last() { for (int ii=array.length-1;ii>=0;ii--) { if (array[ii] != 0) { for (int jj=Math.min(bits,(ii+1)*8)-1;jj>=0;jj--) { if (isSet(jj)) { return jj; } } } } return -1; } }
public class class_name { public int last() { for (int ii=array.length-1;ii>=0;ii--) { if (array[ii] != 0) { for (int jj=Math.min(bits,(ii+1)*8)-1;jj>=0;jj--) { if (isSet(jj)) { return jj; // depends on control dependency: [if], data = [none] } } } } return -1; } }
public class class_name { private void initLocalTable() { String tableName = config.getPath(); ClassLoader cl = this.getClass().getClassLoader(); try (InputStream is = cl.getResourceAsStream(tableName)) { if (is == null) { throw new IllegalStateException("Cant find " + tableName); } try (BufferedReader br = new BufferedReader(new InputStreamReader(is, CDM.utf8Charset))) { while (true) { String line = br.readLine(); if (line == null) { break; } if ((line.length() == 0) || line.startsWith("#")) { continue; } String[] flds = StringUtil2.splitString(line); int p1 = Integer.parseInt(flds[0].trim()); // must have a number int p2 = Integer.parseInt(flds[1].trim()); // must have a number int p3 = Integer.parseInt(flds[2].trim()); // must have a number StringBuilder b = new StringBuilder(); int count = 3; while (count < flds.length && !flds[count].equals(".")) { b.append(flds[count++]).append(' '); } String abbrev = b.toString().trim(); b.setLength(0); count++; while (count < flds.length && !flds[count].equals(".")) { b.append(flds[count++]).append(' '); } String name = b.toString().trim(); b.setLength(0); count++; while (count < flds.length && !flds[count].equals(".")) { b.append(flds[count++]).append(' '); } String unit = b.toString().trim(); Grib2Parameter s = new Grib2Parameter(p1, p2, p3, name, unit, abbrev, null); local.put(makeParamId(p1, p2, p3), s); } } } catch (IOException ioe) { throw new RuntimeException(ioe); } } }
public class class_name { private void initLocalTable() { String tableName = config.getPath(); ClassLoader cl = this.getClass().getClassLoader(); try (InputStream is = cl.getResourceAsStream(tableName)) { if (is == null) { throw new IllegalStateException("Cant find " + tableName); } try (BufferedReader br = new BufferedReader(new InputStreamReader(is, CDM.utf8Charset))) { while (true) { String line = br.readLine(); if (line == null) { break; } if ((line.length() == 0) || line.startsWith("#")) { continue; } String[] flds = StringUtil2.splitString(line); int p1 = Integer.parseInt(flds[0].trim()); // must have a number int p2 = Integer.parseInt(flds[1].trim()); // must have a number int p3 = Integer.parseInt(flds[2].trim()); // must have a number StringBuilder b = new StringBuilder(); int count = 3; while (count < flds.length && !flds[count].equals(".")) { b.append(flds[count++]).append(' '); // depends on control dependency: [while], data = [none] } String abbrev = b.toString().trim(); b.setLength(0); // depends on control dependency: [while], data = [none] count++; // depends on control dependency: [while], data = [none] while (count < flds.length && !flds[count].equals(".")) { b.append(flds[count++]).append(' '); // depends on control dependency: [while], data = [none] } String name = b.toString().trim(); b.setLength(0); // depends on control dependency: [while], data = [none] count++; // depends on control dependency: [while], data = [none] while (count < flds.length && !flds[count].equals(".")) { b.append(flds[count++]).append(' '); // depends on control dependency: [while], data = [none] } String unit = b.toString().trim(); Grib2Parameter s = new Grib2Parameter(p1, p2, p3, name, unit, abbrev, null); local.put(makeParamId(p1, p2, p3), s); // depends on control dependency: [while], data = [none] } } } catch (IOException ioe) { throw new RuntimeException(ioe); } } }
public class class_name { protected final void resolveProxies() { final List<String> unresolved = new ArrayList<String>(); if (!resolvedAllProxies(unresolved, 0)) { LOG.warn("Could not resolve the following proxies ({}):", unresolved.size()); for (final String ref : unresolved) { LOG.warn("Not found: {}", ref); } final Iterator<Notifier> it = resourceSet.getAllContents(); while (it.hasNext()) { final Notifier next = it.next(); if (next instanceof EObject) { final EObject obj = (EObject) next; if (obj.eIsProxy()) { try { it.remove(); } catch (final UnsupportedOperationException ex) { LOG.error("Could not remove proxy: " + obj, ex); } } } } } } }
public class class_name { protected final void resolveProxies() { final List<String> unresolved = new ArrayList<String>(); if (!resolvedAllProxies(unresolved, 0)) { LOG.warn("Could not resolve the following proxies ({}):", unresolved.size()); // depends on control dependency: [if], data = [none] for (final String ref : unresolved) { LOG.warn("Not found: {}", ref); // depends on control dependency: [for], data = [ref] } final Iterator<Notifier> it = resourceSet.getAllContents(); while (it.hasNext()) { final Notifier next = it.next(); if (next instanceof EObject) { final EObject obj = (EObject) next; if (obj.eIsProxy()) { try { it.remove(); // depends on control dependency: [try], data = [none] } catch (final UnsupportedOperationException ex) { LOG.error("Could not remove proxy: " + obj, ex); } // depends on control dependency: [catch], data = [none] } } } } } }
public class class_name { private ProcTemplate createTemplate(Template template) { if (!template.isEmpty()) { return new ProcTemplate(templateElementFactory.createTemplateList(template.getElements())); } else { return ProcTemplate.EMPTY; } } }
public class class_name { private ProcTemplate createTemplate(Template template) { if (!template.isEmpty()) { return new ProcTemplate(templateElementFactory.createTemplateList(template.getElements())); // depends on control dependency: [if], data = [none] } else { return ProcTemplate.EMPTY; // depends on control dependency: [if], data = [none] } } }
public class class_name { private static final String urlEncode(String s) { try { return URLEncoder.encode(s, "UTF-8"); } catch (Exception e) { logger.warn("Failed to encode '" + s + "'", e); return s; } } }
public class class_name { private static final String urlEncode(String s) { try { return URLEncoder.encode(s, "UTF-8"); // depends on control dependency: [try], data = [none] } catch (Exception e) { logger.warn("Failed to encode '" + s + "'", e); return s; } // depends on control dependency: [catch], data = [none] } }
public class class_name { @SuppressWarnings("unchecked") @Override public void run(Class<? extends Object> toRun, JobManager handler, Map<String, String> handlerParameters) { // initialize the spring context with all requested classes on first boot - // and only on first boot: the Spring context cannot be refreshed multiple times. if (!refreshed) { synchronized (AnnotationSpringContextBootstrapHandler.class) { if (!refreshed) { // Add the different elements to the context path if (handlerParameters.containsKey("beanNameGenerator")) { Class<? extends BeanNameGenerator> clazz; try { clazz = (Class<? extends BeanNameGenerator>) AnnotationSpringContextBootstrapHandler.class.getClassLoader() .loadClass(handlerParameters.get("beanNameGenerator")); } catch (ClassNotFoundException e) { throw new RuntimeException("The handler beanNameGenerator class [" + handlerParameters.get("beanNameGenerator") + "] cannot be found.", e); } BeanNameGenerator generator; try { generator = clazz.newInstance(); } catch (Exception e) { throw new RuntimeException("The handler beanNameGenerator class [" + handlerParameters.get("beanNameGenerator") + "] was found but cannot be instantiated. Check it has a no-arguments constructor.", e); } ctx.setBeanNameGenerator(generator); } if (handlerParameters.containsKey("contextDisplayName")) { ctx.setDisplayName(handlerParameters.get("contextDisplayName")); } if (handlerParameters.containsKey("contextId")) { ctx.setId(handlerParameters.get("contextId")); } if (handlerParameters.containsKey("allowCircularReferences")) { boolean allow = Boolean.parseBoolean(handlerParameters.get("allowCircularReferences")); ctx.setAllowCircularReferences(allow); } if (handlerParameters.containsKey("additionalScan")) { ctx.scan(handlerParameters.get("additionalScan").split(",")); } else { ctx.register(toRun); } // Create a holder for the parameters. BeanDefinition def = new RootBeanDefinition(HashMap.class); def.setScope(THREAD_SCOPE_NAME); ctx.registerBeanDefinition("runtimeParameters", def); // This is a factory to retrieve the JobManager. We cannot just inject the JM, as it is created at runtime, long after // the context has been created! def = new RootBeanDefinition(JobManagerProvider.class); def.setScope(BeanDefinition.SCOPE_SINGLETON); ctx.registerBeanDefinition("jobManagerProvider", def); // It would however be possible to use a lazy bean injection. But this would require the user to put @Lazy everywhere, // or else the result is null... Too fragile. The provider/factory pattern above does the same thing and forces the user // to do a lazy call. // def = new RootBeanDefinition(JobManager.class); // def.setScope(RootBeanDefinition.SCOPE_PROTOTYPE); // def.setLazyInit(true); // def.setFactoryBeanName("jobManagerProvider"); // def.setFactoryMethodName("getObject"); // ctx.registerBeanDefinition("jobManager", def); // Go: this initializes the context ctx.refresh(); refreshed = true; } } } } }
public class class_name { @SuppressWarnings("unchecked") @Override public void run(Class<? extends Object> toRun, JobManager handler, Map<String, String> handlerParameters) { // initialize the spring context with all requested classes on first boot - // and only on first boot: the Spring context cannot be refreshed multiple times. if (!refreshed) { synchronized (AnnotationSpringContextBootstrapHandler.class) // depends on control dependency: [if], data = [none] { if (!refreshed) { // Add the different elements to the context path if (handlerParameters.containsKey("beanNameGenerator")) { Class<? extends BeanNameGenerator> clazz; try { clazz = (Class<? extends BeanNameGenerator>) AnnotationSpringContextBootstrapHandler.class.getClassLoader() .loadClass(handlerParameters.get("beanNameGenerator")); // depends on control dependency: [try], data = [none] } catch (ClassNotFoundException e) { throw new RuntimeException("The handler beanNameGenerator class [" + handlerParameters.get("beanNameGenerator") + "] cannot be found.", e); } // depends on control dependency: [catch], data = [none] BeanNameGenerator generator; try { generator = clazz.newInstance(); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new RuntimeException("The handler beanNameGenerator class [" + handlerParameters.get("beanNameGenerator") + "] was found but cannot be instantiated. Check it has a no-arguments constructor.", e); } // depends on control dependency: [catch], data = [none] ctx.setBeanNameGenerator(generator); // depends on control dependency: [if], data = [none] } if (handlerParameters.containsKey("contextDisplayName")) { ctx.setDisplayName(handlerParameters.get("contextDisplayName")); // depends on control dependency: [if], data = [none] } if (handlerParameters.containsKey("contextId")) { ctx.setId(handlerParameters.get("contextId")); // depends on control dependency: [if], data = [none] } if (handlerParameters.containsKey("allowCircularReferences")) { boolean allow = Boolean.parseBoolean(handlerParameters.get("allowCircularReferences")); ctx.setAllowCircularReferences(allow); // depends on control dependency: [if], data = [none] } if (handlerParameters.containsKey("additionalScan")) { ctx.scan(handlerParameters.get("additionalScan").split(",")); // depends on control dependency: [if], data = [none] } else { ctx.register(toRun); // depends on control dependency: [if], data = [none] } // Create a holder for the parameters. BeanDefinition def = new RootBeanDefinition(HashMap.class); def.setScope(THREAD_SCOPE_NAME); // depends on control dependency: [if], data = [none] ctx.registerBeanDefinition("runtimeParameters", def); // depends on control dependency: [if], data = [none] // This is a factory to retrieve the JobManager. We cannot just inject the JM, as it is created at runtime, long after // the context has been created! def = new RootBeanDefinition(JobManagerProvider.class); // depends on control dependency: [if], data = [none] def.setScope(BeanDefinition.SCOPE_SINGLETON); // depends on control dependency: [if], data = [none] ctx.registerBeanDefinition("jobManagerProvider", def); // depends on control dependency: [if], data = [none] // It would however be possible to use a lazy bean injection. But this would require the user to put @Lazy everywhere, // or else the result is null... Too fragile. The provider/factory pattern above does the same thing and forces the user // to do a lazy call. // def = new RootBeanDefinition(JobManager.class); // def.setScope(RootBeanDefinition.SCOPE_PROTOTYPE); // def.setLazyInit(true); // def.setFactoryBeanName("jobManagerProvider"); // def.setFactoryMethodName("getObject"); // ctx.registerBeanDefinition("jobManager", def); // Go: this initializes the context ctx.refresh(); // depends on control dependency: [if], data = [none] refreshed = true; // depends on control dependency: [if], data = [none] } } } } }
public class class_name { public void addFinalConstructState(String infix, State finalConstructState) { for (String property : finalConstructState.getPropertyNames()) { if (Strings.isNullOrEmpty(infix)) { setProp(FINAL_CONSTRUCT_STATE_PREFIX + property, finalConstructState.getProp(property)); } else { setProp(FINAL_CONSTRUCT_STATE_PREFIX + infix + "." + property, finalConstructState.getProp(property)); } } } }
public class class_name { public void addFinalConstructState(String infix, State finalConstructState) { for (String property : finalConstructState.getPropertyNames()) { if (Strings.isNullOrEmpty(infix)) { setProp(FINAL_CONSTRUCT_STATE_PREFIX + property, finalConstructState.getProp(property)); // depends on control dependency: [if], data = [none] } else { setProp(FINAL_CONSTRUCT_STATE_PREFIX + infix + "." + property, finalConstructState.getProp(property)); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public void setCommand(java.util.Collection<String> command) { if (command == null) { this.command = null; return; } this.command = new com.amazonaws.internal.SdkInternalList<String>(command); } }
public class class_name { public void setCommand(java.util.Collection<String> command) { if (command == null) { this.command = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.command = new com.amazonaws.internal.SdkInternalList<String>(command); } }
public class class_name { public static void main(String... args) { CommandLineRunner runner = new CommandLineRunner(); try { runner.run(args); } catch (Exception t) { System.err.println(t.getMessage()); System.err.println("Try '--help' for more information."); t.printStackTrace(System.err); System.exit(1); } System.exit(0); } }
public class class_name { public static void main(String... args) { CommandLineRunner runner = new CommandLineRunner(); try { runner.run(args); // depends on control dependency: [try], data = [none] } catch (Exception t) { System.err.println(t.getMessage()); System.err.println("Try '--help' for more information."); t.printStackTrace(System.err); System.exit(1); } // depends on control dependency: [catch], data = [none] System.exit(0); } }
public class class_name { public static List<Integer> parseStringToIntegerList(String source, String token) { if (StringUtils.isBlank(source) || StringUtils.isEmpty(token)) { return null; } List<Integer> result = new ArrayList<Integer>(); String[] units = source.split(token); for (String unit : units) { result.add(Integer.valueOf(unit)); } return result; } }
public class class_name { public static List<Integer> parseStringToIntegerList(String source, String token) { if (StringUtils.isBlank(source) || StringUtils.isEmpty(token)) { return null; // depends on control dependency: [if], data = [none] } List<Integer> result = new ArrayList<Integer>(); String[] units = source.split(token); for (String unit : units) { result.add(Integer.valueOf(unit)); // depends on control dependency: [for], data = [unit] } return result; } }
public class class_name { public static boolean isExtensionWellFormated(File file, String prefix) { String path = file.getAbsolutePath(); String extension = ""; int i = path.lastIndexOf('.'); if (i >= 0) { extension = path.substring(i + 1); } return extension.equalsIgnoreCase(prefix); } }
public class class_name { public static boolean isExtensionWellFormated(File file, String prefix) { String path = file.getAbsolutePath(); String extension = ""; int i = path.lastIndexOf('.'); if (i >= 0) { extension = path.substring(i + 1); // depends on control dependency: [if], data = [(i] } return extension.equalsIgnoreCase(prefix); } }
public class class_name { public void marshall(ProductionVariant productionVariant, ProtocolMarshaller protocolMarshaller) { if (productionVariant == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(productionVariant.getVariantName(), VARIANTNAME_BINDING); protocolMarshaller.marshall(productionVariant.getModelName(), MODELNAME_BINDING); protocolMarshaller.marshall(productionVariant.getInitialInstanceCount(), INITIALINSTANCECOUNT_BINDING); protocolMarshaller.marshall(productionVariant.getInstanceType(), INSTANCETYPE_BINDING); protocolMarshaller.marshall(productionVariant.getInitialVariantWeight(), INITIALVARIANTWEIGHT_BINDING); protocolMarshaller.marshall(productionVariant.getAcceleratorType(), ACCELERATORTYPE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(ProductionVariant productionVariant, ProtocolMarshaller protocolMarshaller) { if (productionVariant == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(productionVariant.getVariantName(), VARIANTNAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(productionVariant.getModelName(), MODELNAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(productionVariant.getInitialInstanceCount(), INITIALINSTANCECOUNT_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(productionVariant.getInstanceType(), INSTANCETYPE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(productionVariant.getInitialVariantWeight(), INITIALVARIANTWEIGHT_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(productionVariant.getAcceleratorType(), ACCELERATORTYPE_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static void tryAddPropertyChangeListenerUnchecked( Object target, PropertyChangeListener propertyChangeListener) { Objects.requireNonNull(target, "The target may not be null"); Objects.requireNonNull(propertyChangeListener, "The propertyChangeListener may not be null"); if (maintainsPropertyChangeListeners(target.getClass())) { PropertyChangeUtils.addPropertyChangeListenerUnchecked( target, propertyChangeListener); } } }
public class class_name { public static void tryAddPropertyChangeListenerUnchecked( Object target, PropertyChangeListener propertyChangeListener) { Objects.requireNonNull(target, "The target may not be null"); Objects.requireNonNull(propertyChangeListener, "The propertyChangeListener may not be null"); if (maintainsPropertyChangeListeners(target.getClass())) { PropertyChangeUtils.addPropertyChangeListenerUnchecked( target, propertyChangeListener); // depends on control dependency: [if], data = [none] } } }
public class class_name { private boolean isProductExtensionInstalled(String inputString, String productExtension) { if ((productExtension == null) || (inputString == null)) { return false; } int msgIndex = inputString.indexOf("CWWKF0012I: The server installed the following features:"); if (msgIndex == -1) { return false; } String msgString = inputString.substring(msgIndex); int leftBracketIndex = msgString.indexOf("["); int rightBracketIndex = msgString.indexOf("]"); if ((leftBracketIndex == -1) || (rightBracketIndex == -1) || (rightBracketIndex < leftBracketIndex)) { return false; } String features = msgString.substring(leftBracketIndex, rightBracketIndex); Log.info(c, "isProductExtensionInstalled", features); if (features.indexOf(productExtension) == -1) { return false; } return true; } }
public class class_name { private boolean isProductExtensionInstalled(String inputString, String productExtension) { if ((productExtension == null) || (inputString == null)) { return false; // depends on control dependency: [if], data = [none] } int msgIndex = inputString.indexOf("CWWKF0012I: The server installed the following features:"); if (msgIndex == -1) { return false; // depends on control dependency: [if], data = [none] } String msgString = inputString.substring(msgIndex); int leftBracketIndex = msgString.indexOf("["); int rightBracketIndex = msgString.indexOf("]"); if ((leftBracketIndex == -1) || (rightBracketIndex == -1) || (rightBracketIndex < leftBracketIndex)) { return false; // depends on control dependency: [if], data = [none] } String features = msgString.substring(leftBracketIndex, rightBracketIndex); Log.info(c, "isProductExtensionInstalled", features); if (features.indexOf(productExtension) == -1) { return false; // depends on control dependency: [if], data = [none] } return true; } }
public class class_name { public void marshall(DeleteFleetRequest deleteFleetRequest, ProtocolMarshaller protocolMarshaller) { if (deleteFleetRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deleteFleetRequest.getFleetArn(), FLEETARN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(DeleteFleetRequest deleteFleetRequest, ProtocolMarshaller protocolMarshaller) { if (deleteFleetRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deleteFleetRequest.getFleetArn(), FLEETARN_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 notifyRCDReceiveExclusiveChange(boolean isReceiveExclusive) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "notifyRCDReceiveExclusiveChange", new Object[] {Boolean.valueOf(isReceiveExclusive)}); // Only do this for ptp as it does not seem to make sense for p/s synchronized (_anycastInputHandlers) { for(Iterator i=_anycastInputHandlers.keySet().iterator(); i.hasNext();) { AnycastInputHandler aih = _anycastInputHandlers.get(i.next()); if (aih != null) { RemoteConsumerDispatcher rcd = aih.getRCD(); rcd.notifyReceiveExclusiveChange(isReceiveExclusive); } } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "notifyRCDReceiveExclusiveChange"); } }
public class class_name { public void notifyRCDReceiveExclusiveChange(boolean isReceiveExclusive) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "notifyRCDReceiveExclusiveChange", new Object[] {Boolean.valueOf(isReceiveExclusive)}); // Only do this for ptp as it does not seem to make sense for p/s synchronized (_anycastInputHandlers) { for(Iterator i=_anycastInputHandlers.keySet().iterator(); i.hasNext();) { AnycastInputHandler aih = _anycastInputHandlers.get(i.next()); if (aih != null) { RemoteConsumerDispatcher rcd = aih.getRCD(); rcd.notifyReceiveExclusiveChange(isReceiveExclusive); // depends on control dependency: [if], data = [none] } } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "notifyRCDReceiveExclusiveChange"); } }
public class class_name { protected void drawWeeks() { Calendar tmpCalendar = (Calendar) calendar.clone(); for (int i = 1; i < 7; i++) { tmpCalendar.set(Calendar.DAY_OF_MONTH, (i * 7) - 6); int week = tmpCalendar.get(Calendar.WEEK_OF_YEAR); String buttonText = Integer.toString(week); if (week < 10) { buttonText = "0" + buttonText; } weeks[i].setText(buttonText); if ((i == 5) || (i == 6)) { weeks[i].setVisible(days[i * 7].isVisible()); } } } }
public class class_name { protected void drawWeeks() { Calendar tmpCalendar = (Calendar) calendar.clone(); for (int i = 1; i < 7; i++) { tmpCalendar.set(Calendar.DAY_OF_MONTH, (i * 7) - 6); // depends on control dependency: [for], data = [i] int week = tmpCalendar.get(Calendar.WEEK_OF_YEAR); String buttonText = Integer.toString(week); if (week < 10) { buttonText = "0" + buttonText; // depends on control dependency: [if], data = [none] } weeks[i].setText(buttonText); // depends on control dependency: [for], data = [i] if ((i == 5) || (i == 6)) { weeks[i].setVisible(days[i * 7].isVisible()); // depends on control dependency: [if], data = [none] } } } }
public class class_name { @Override public MessageContext getMessageContext() throws IllegalStateException { boolean isEndpointMethod = false; // LI2281.07 // Get the method context for the current thread, and check to see if // the current method is from WebService Endpoint interface. d174057 Object context = EJSContainer.getMethodContext(); // d646139.1 if (context instanceof EJSDeployedSupport) { EJSDeployedSupport s = (EJSDeployedSupport) context; if (s.methodInfo.ivInterface == MethodInterface.SERVICE_ENDPOINT) { isEndpointMethod = true; } } // getMessageContext is allowed only from within Web Service Endpoint // interface methods. StatefulSessionBeanO overrides this method and // throws an exception for that spec restriction. if (!isEndpointMethod) { IllegalStateException ise; // Not an allowed method for Stateful beans per EJB Specification. ise = new IllegalStateException("SessionBean: getMessageContext not " + "allowed from Non-WebService " + "Endpoint method"); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "getMessageContext: " + ise); throw ise; } if (messageContextMethod == null) { try { messageContextMethod = Class.forName("com.ibm.ws.webservices.engine.MessageContext") .getMethod("getCurrentThreadsContext", (Class[]) null); } catch (SecurityException e) { FFDCFilter.processException( e, CLASS_NAME + ".getMessageContext", "348", this); } catch (NoSuchMethodException e) { FFDCFilter.processException( e, CLASS_NAME + ".getMessageContext", "354", this); } catch (ClassNotFoundException e) { FFDCFilter.processException( e, CLASS_NAME + ".getMessageContext", "360", this); } } MessageContext theMessageContext = null; try { theMessageContext = (MessageContext) messageContextMethod.invoke(null, (Object[]) null); } catch (IllegalArgumentException e) { FFDCFilter.processException( e, CLASS_NAME + ".getMessageContext", "372", this); } catch (IllegalAccessException e) { FFDCFilter.processException( e, CLASS_NAME + ".getMessageContext", "378", this); } catch (InvocationTargetException e) { FFDCFilter.processException( e, CLASS_NAME + ".getMessageContext", "384", this); } return theMessageContext; } }
public class class_name { @Override public MessageContext getMessageContext() throws IllegalStateException { boolean isEndpointMethod = false; // LI2281.07 // Get the method context for the current thread, and check to see if // the current method is from WebService Endpoint interface. d174057 Object context = EJSContainer.getMethodContext(); // d646139.1 if (context instanceof EJSDeployedSupport) { EJSDeployedSupport s = (EJSDeployedSupport) context; if (s.methodInfo.ivInterface == MethodInterface.SERVICE_ENDPOINT) { isEndpointMethod = true; // depends on control dependency: [if], data = [none] } } // getMessageContext is allowed only from within Web Service Endpoint // interface methods. StatefulSessionBeanO overrides this method and // throws an exception for that spec restriction. if (!isEndpointMethod) { IllegalStateException ise; // Not an allowed method for Stateful beans per EJB Specification. ise = new IllegalStateException("SessionBean: getMessageContext not " + "allowed from Non-WebService " + "Endpoint method"); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "getMessageContext: " + ise); throw ise; } if (messageContextMethod == null) { try { messageContextMethod = Class.forName("com.ibm.ws.webservices.engine.MessageContext") .getMethod("getCurrentThreadsContext", (Class[]) null); } catch (SecurityException e) { FFDCFilter.processException( e, CLASS_NAME + ".getMessageContext", "348", this); } catch (NoSuchMethodException e) { FFDCFilter.processException( e, CLASS_NAME + ".getMessageContext", "354", this); } catch (ClassNotFoundException e) { FFDCFilter.processException( e, CLASS_NAME + ".getMessageContext", "360", this); } } MessageContext theMessageContext = null; try { theMessageContext = (MessageContext) messageContextMethod.invoke(null, (Object[]) null); } catch (IllegalArgumentException e) { FFDCFilter.processException( e, CLASS_NAME + ".getMessageContext", "372", this); } catch (IllegalAccessException e) { FFDCFilter.processException( e, CLASS_NAME + ".getMessageContext", "378", this); } catch (InvocationTargetException e) { FFDCFilter.processException( e, CLASS_NAME + ".getMessageContext", "384", this); } return theMessageContext; } }
public class class_name { public void setState(int state) throws RepositoryException { if (getState() != ONLINE && !(state == ONLINE || state == OFFLINE)) { throw new RepositoryException("First switch repository to ONLINE and then to needed state.\n" + toString()); } String[] workspaces = getWorkspaceNames(); if (workspaces.length > 0) { // set state for all workspaces for (String workspaceName : workspaces) { if (!workspaceName.equals(systemWorkspaceName)) { getWorkspaceContainer(workspaceName).setState(state); } } getWorkspaceContainer(systemWorkspaceName).setState(state); } isOffline = state == OFFLINE; } }
public class class_name { public void setState(int state) throws RepositoryException { if (getState() != ONLINE && !(state == ONLINE || state == OFFLINE)) { throw new RepositoryException("First switch repository to ONLINE and then to needed state.\n" + toString()); } String[] workspaces = getWorkspaceNames(); if (workspaces.length > 0) { // set state for all workspaces for (String workspaceName : workspaces) { if (!workspaceName.equals(systemWorkspaceName)) { getWorkspaceContainer(workspaceName).setState(state); // depends on control dependency: [if], data = [none] } } getWorkspaceContainer(systemWorkspaceName).setState(state); } isOffline = state == OFFLINE; } }
public class class_name { public static boolean matchProduces(InternalRoute route, InternalRequest<?> request) { if (nonEmpty(request.getAccept())) { List<MediaType> matchedAcceptTypes = getAcceptedMediaTypes(route.getProduces(), request.getAccept()); if (nonEmpty(matchedAcceptTypes)) { request.setMatchedAccept(matchedAcceptTypes.get(0)); return true; } } return false; } }
public class class_name { public static boolean matchProduces(InternalRoute route, InternalRequest<?> request) { if (nonEmpty(request.getAccept())) { List<MediaType> matchedAcceptTypes = getAcceptedMediaTypes(route.getProduces(), request.getAccept()); if (nonEmpty(matchedAcceptTypes)) { request.setMatchedAccept(matchedAcceptTypes.get(0)); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { private void sendKeepAliveBridgeMessage(int appId, String bridgeId, String token, final CallStatsHttp2Client httpClient) { long apiTS = System.currentTimeMillis(); BridgeKeepAliveMessage message = new BridgeKeepAliveMessage(bridgeId, apiTS); String requestMessageString = gson.toJson(message); httpClient.sendBridgeAlive(keepAliveEventUrl, token, requestMessageString, new CallStatsHttp2ResponseListener() { public void onResponse(Response response) { int responseStatus = response.code(); BridgeKeepAliveResponse keepAliveResponse; try { String responseString = response.body().string(); keepAliveResponse = gson.fromJson(responseString, BridgeKeepAliveResponse.class); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (JsonSyntaxException e) { logger.error("Json Syntax Exception " + e.getMessage(), e); e.printStackTrace(); throw new RuntimeException(e); } httpClient.setDisrupted(false); if (responseStatus == CallStatsResponseStatus.RESPONSE_STATUS_SUCCESS) { keepAliveStatusListener.onSuccess(); } else if (responseStatus == CallStatsResponseStatus.INVALID_AUTHENTICATION_TOKEN) { stopKeepAliveSender(); keepAliveStatusListener.onKeepAliveError(CallStatsErrors.AUTH_ERROR, keepAliveResponse.getMsg()); } else { httpClient.setDisrupted(true); } } public void onFailure(Exception e) { logger.info("Response exception " + e.toString()); httpClient.setDisrupted(true); } }); } }
public class class_name { private void sendKeepAliveBridgeMessage(int appId, String bridgeId, String token, final CallStatsHttp2Client httpClient) { long apiTS = System.currentTimeMillis(); BridgeKeepAliveMessage message = new BridgeKeepAliveMessage(bridgeId, apiTS); String requestMessageString = gson.toJson(message); httpClient.sendBridgeAlive(keepAliveEventUrl, token, requestMessageString, new CallStatsHttp2ResponseListener() { public void onResponse(Response response) { int responseStatus = response.code(); BridgeKeepAliveResponse keepAliveResponse; try { String responseString = response.body().string(); keepAliveResponse = gson.fromJson(responseString, BridgeKeepAliveResponse.class); // depends on control dependency: [try], data = [none] } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (JsonSyntaxException e) { // depends on control dependency: [catch], data = [none] logger.error("Json Syntax Exception " + e.getMessage(), e); e.printStackTrace(); throw new RuntimeException(e); } // depends on control dependency: [catch], data = [none] httpClient.setDisrupted(false); if (responseStatus == CallStatsResponseStatus.RESPONSE_STATUS_SUCCESS) { keepAliveStatusListener.onSuccess(); // depends on control dependency: [if], data = [none] } else if (responseStatus == CallStatsResponseStatus.INVALID_AUTHENTICATION_TOKEN) { stopKeepAliveSender(); // depends on control dependency: [if], data = [none] keepAliveStatusListener.onKeepAliveError(CallStatsErrors.AUTH_ERROR, keepAliveResponse.getMsg()); // depends on control dependency: [if], data = [none] } else { httpClient.setDisrupted(true); // depends on control dependency: [if], data = [none] } } public void onFailure(Exception e) { logger.info("Response exception " + e.toString()); httpClient.setDisrupted(true); } }); } }
public class class_name { @Override public int compare(TemporalPropositionDefinition a1, TemporalPropositionDefinition a2) { if (a1 == a2) { return 0; } else { Integer index1 = rule2Index.get(a1.getId()); Integer index2 = rule2Index.get(a2.getId()); return index1.compareTo(index2); } } }
public class class_name { @Override public int compare(TemporalPropositionDefinition a1, TemporalPropositionDefinition a2) { if (a1 == a2) { return 0; // depends on control dependency: [if], data = [none] } else { Integer index1 = rule2Index.get(a1.getId()); Integer index2 = rule2Index.get(a2.getId()); return index1.compareTo(index2); // depends on control dependency: [if], data = [none] } } }
public class class_name { public DescribeDBClusterBacktracksResult withDBClusterBacktracks(DBClusterBacktrack... dBClusterBacktracks) { if (this.dBClusterBacktracks == null) { setDBClusterBacktracks(new com.amazonaws.internal.SdkInternalList<DBClusterBacktrack>(dBClusterBacktracks.length)); } for (DBClusterBacktrack ele : dBClusterBacktracks) { this.dBClusterBacktracks.add(ele); } return this; } }
public class class_name { public DescribeDBClusterBacktracksResult withDBClusterBacktracks(DBClusterBacktrack... dBClusterBacktracks) { if (this.dBClusterBacktracks == null) { setDBClusterBacktracks(new com.amazonaws.internal.SdkInternalList<DBClusterBacktrack>(dBClusterBacktracks.length)); // depends on control dependency: [if], data = [none] } for (DBClusterBacktrack ele : dBClusterBacktracks) { this.dBClusterBacktracks.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { @SuppressWarnings("unchecked") public final V get(String key) { V value = mMemCache.get(key); if (mDiskCache != null && value == null) { Snapshot snapshot = null; InputStream in = null; try { snapshot = mDiskCache.get(key); if (snapshot != null) { in = snapshot.getInputStream(INDEX_VALUE); byte[] bytes = IOUtils.toByteArray(in); value = mConverter.from(bytes); } } catch (IOException e) { System.out.println("Unable to get entry from disk cache. key: " + key); } catch (Exception e) { System.out.println("Unable to get entry from disk cache. key: " + key); } catch (OutOfMemoryError e) { System.out.println("Unable to get entry from disk cache. key: " + key); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(snapshot); } if (value != null) { // write back to mem cache mMemCache.put(key, value); } } return value; } }
public class class_name { @SuppressWarnings("unchecked") public final V get(String key) { V value = mMemCache.get(key); if (mDiskCache != null && value == null) { Snapshot snapshot = null; InputStream in = null; try { snapshot = mDiskCache.get(key); // depends on control dependency: [try], data = [none] if (snapshot != null) { in = snapshot.getInputStream(INDEX_VALUE); // depends on control dependency: [if], data = [none] byte[] bytes = IOUtils.toByteArray(in); value = mConverter.from(bytes); // depends on control dependency: [if], data = [none] } } catch (IOException e) { System.out.println("Unable to get entry from disk cache. key: " + key); } catch (Exception e) { // depends on control dependency: [catch], data = [none] System.out.println("Unable to get entry from disk cache. key: " + key); } catch (OutOfMemoryError e) { // depends on control dependency: [catch], data = [none] System.out.println("Unable to get entry from disk cache. key: " + key); } finally { // depends on control dependency: [catch], data = [none] IOUtils.closeQuietly(in); IOUtils.closeQuietly(snapshot); } if (value != null) { // write back to mem cache mMemCache.put(key, value); // depends on control dependency: [if], data = [none] } } return value; } }
public class class_name { public synchronized void start(GcEventListener listener) { // TODO: this class has a bad mix of static fields used from an instance of the class. For now // this has been changed not to throw to make the dependency injection use-cases work. A // more general refactor of the GcLogger class is needed. if (notifListener != null) { LOGGER.warn("logger already started"); return; } eventListener = listener; notifListener = new GcNotificationListener(); for (GarbageCollectorMXBean mbean : ManagementFactory.getGarbageCollectorMXBeans()) { if (mbean instanceof NotificationEmitter) { final NotificationEmitter emitter = (NotificationEmitter) mbean; emitter.addNotificationListener(notifListener, null, null); } } } }
public class class_name { public synchronized void start(GcEventListener listener) { // TODO: this class has a bad mix of static fields used from an instance of the class. For now // this has been changed not to throw to make the dependency injection use-cases work. A // more general refactor of the GcLogger class is needed. if (notifListener != null) { LOGGER.warn("logger already started"); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } eventListener = listener; notifListener = new GcNotificationListener(); for (GarbageCollectorMXBean mbean : ManagementFactory.getGarbageCollectorMXBeans()) { if (mbean instanceof NotificationEmitter) { final NotificationEmitter emitter = (NotificationEmitter) mbean; emitter.addNotificationListener(notifListener, null, null); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public static boolean isActionableForAccessibility(AccessibilityNodeInfoCompat node) { if (node == null) { return false; } // Nodes that are clickable are always actionable. if (isClickable(node) || isLongClickable(node)) { return true; } if (node.isFocusable()) { return true; } return supportsAnyAction(node, AccessibilityNodeInfoCompat.ACTION_FOCUS, AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT, AccessibilityNodeInfoCompat.ACTION_PREVIOUS_HTML_ELEMENT); } }
public class class_name { public static boolean isActionableForAccessibility(AccessibilityNodeInfoCompat node) { if (node == null) { return false; // depends on control dependency: [if], data = [none] } // Nodes that are clickable are always actionable. if (isClickable(node) || isLongClickable(node)) { return true; // depends on control dependency: [if], data = [none] } if (node.isFocusable()) { return true; // depends on control dependency: [if], data = [none] } return supportsAnyAction(node, AccessibilityNodeInfoCompat.ACTION_FOCUS, AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT, AccessibilityNodeInfoCompat.ACTION_PREVIOUS_HTML_ELEMENT); } }
public class class_name { private int getColorDigit( int idx, CssFormatter formatter ) { Expression expression = get( idx ); double d = expression.doubleValue( formatter ); if( expression.getDataType( formatter ) == PERCENT ) { d *= 2.55; } return colorDigit(d); } }
public class class_name { private int getColorDigit( int idx, CssFormatter formatter ) { Expression expression = get( idx ); double d = expression.doubleValue( formatter ); if( expression.getDataType( formatter ) == PERCENT ) { d *= 2.55; // depends on control dependency: [if], data = [none] } return colorDigit(d); } }
public class class_name { public List getErrors() { if (hasChilds()) { List ret = new ArrayList(0); Iterator it = getChilds().iterator(); while (it.hasNext()) { ret.addAll(((AbcNode) it.next()).getErrors()); } return ret; } else { return errors != null ? errors : new ArrayList(0); } } }
public class class_name { public List getErrors() { if (hasChilds()) { List ret = new ArrayList(0); Iterator it = getChilds().iterator(); while (it.hasNext()) { ret.addAll(((AbcNode) it.next()).getErrors()); // depends on control dependency: [while], data = [none] } return ret; // depends on control dependency: [if], data = [none] } else { return errors != null ? errors : new ArrayList(0); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static Report restoreSubreportsInMaster(Report report) { JasperContent reportContent = (JasperContent) report.getContent(); List<JcrFile> subreportFiles = reportContent.getSubreports(); if (subreportFiles.size() > 0) { JcrFile masterFile = reportContent.getMaster(); try { String masterContent = new String(masterFile.getDataProvider().getBytes(), "UTF-8"); List<String> subreportsContent = new ArrayList<String>(); for (int i = 0, size = subreportFiles.size(); i < size; i++) { subreportsContent.add(new String(subreportFiles.get(i).getDataProvider().getBytes(), "UTF-8")); } for (int i = 0, size = subreportFiles.size(); i < size; i++) { String name = subreportFiles.get(i).getName(); String oldName = getUnique(name, report.getId()) + "." + JASPER_COMPILED_EXT; String newName = name + "." + JASPER_COMPILED_EXT; masterContent = masterContent.replaceAll(oldName, newName); for (int j = 0; j < size; j++) { if (j != i) { subreportsContent.set(j, subreportsContent.get(j).replaceAll(oldName, newName)); } } if (LOG.isDebugEnabled()) { LOG.debug("Subreport " + name + ": " + oldName + " > " + newName); // LOG.debug("master = " + master); } } masterFile.setDataProvider(new JcrDataProviderImpl(masterContent.getBytes("UTF-8"))); for (int i = 0, size = subreportFiles.size(); i < size; i++) { subreportFiles.get(i).setDataProvider(new JcrDataProviderImpl(subreportsContent.get(i).getBytes("UTF-8"))); } } catch (UnsupportedEncodingException e) { LOG.error("Error inside JasperUtil.restoreSubreportsInMaster: " + e.getMessage(), e); e.printStackTrace(); } } return report; } }
public class class_name { public static Report restoreSubreportsInMaster(Report report) { JasperContent reportContent = (JasperContent) report.getContent(); List<JcrFile> subreportFiles = reportContent.getSubreports(); if (subreportFiles.size() > 0) { JcrFile masterFile = reportContent.getMaster(); try { String masterContent = new String(masterFile.getDataProvider().getBytes(), "UTF-8"); List<String> subreportsContent = new ArrayList<String>(); for (int i = 0, size = subreportFiles.size(); i < size; i++) { subreportsContent.add(new String(subreportFiles.get(i).getDataProvider().getBytes(), "UTF-8")); // depends on control dependency: [for], data = [i] } for (int i = 0, size = subreportFiles.size(); i < size; i++) { String name = subreportFiles.get(i).getName(); String oldName = getUnique(name, report.getId()) + "." + JASPER_COMPILED_EXT; String newName = name + "." + JASPER_COMPILED_EXT; masterContent = masterContent.replaceAll(oldName, newName); // depends on control dependency: [for], data = [none] for (int j = 0; j < size; j++) { if (j != i) { subreportsContent.set(j, subreportsContent.get(j).replaceAll(oldName, newName)); // depends on control dependency: [if], data = [(j] } } if (LOG.isDebugEnabled()) { LOG.debug("Subreport " + name + ": " + oldName + " > " + newName); // depends on control dependency: [if], data = [none] // LOG.debug("master = " + master); } } masterFile.setDataProvider(new JcrDataProviderImpl(masterContent.getBytes("UTF-8"))); // depends on control dependency: [try], data = [none] for (int i = 0, size = subreportFiles.size(); i < size; i++) { subreportFiles.get(i).setDataProvider(new JcrDataProviderImpl(subreportsContent.get(i).getBytes("UTF-8"))); // depends on control dependency: [for], data = [i] } } catch (UnsupportedEncodingException e) { LOG.error("Error inside JasperUtil.restoreSubreportsInMaster: " + e.getMessage(), e); e.printStackTrace(); } // depends on control dependency: [catch], data = [none] } return report; } }
public class class_name { protected HttpURLConnection openConnection(URL requestTokenURL) { try { HttpURLConnection connection = (HttpURLConnection) requestTokenURL.openConnection(selectProxy(requestTokenURL)); connection.setConnectTimeout(getConnectionTimeout()); connection.setReadTimeout(getReadTimeout()); return connection; } catch (IOException e) { throw new OAuthRequestFailedException("Failed to open an OAuth connection.", e); } } }
public class class_name { protected HttpURLConnection openConnection(URL requestTokenURL) { try { HttpURLConnection connection = (HttpURLConnection) requestTokenURL.openConnection(selectProxy(requestTokenURL)); connection.setConnectTimeout(getConnectionTimeout()); // depends on control dependency: [try], data = [none] connection.setReadTimeout(getReadTimeout()); // depends on control dependency: [try], data = [none] return connection; // depends on control dependency: [try], data = [none] } catch (IOException e) { throw new OAuthRequestFailedException("Failed to open an OAuth connection.", e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static MimeType getMimeType(Resource resource) { MimeType result = null; if (resource != null) { ResourceHandle handle = ResourceHandle.use(resource); result = getMimeType(handle.getProperty(ResourceUtil.PROP_MIME_TYPE, "")); if (result == null) { String name = resource.getName(); if (ResourceUtil.CONTENT_NODE.equals(name)) { result = getParentMimeType(resource); } else { result = getContentMimeType(resource); if (result == null) { String filename = getResourceName(resource); result = getMimeType(filename); } } } } return result; } }
public class class_name { public static MimeType getMimeType(Resource resource) { MimeType result = null; if (resource != null) { ResourceHandle handle = ResourceHandle.use(resource); result = getMimeType(handle.getProperty(ResourceUtil.PROP_MIME_TYPE, "")); // depends on control dependency: [if], data = [none] if (result == null) { String name = resource.getName(); if (ResourceUtil.CONTENT_NODE.equals(name)) { result = getParentMimeType(resource); // depends on control dependency: [if], data = [none] } else { result = getContentMimeType(resource); // depends on control dependency: [if], data = [none] if (result == null) { String filename = getResourceName(resource); result = getMimeType(filename); // depends on control dependency: [if], data = [none] } } } } return result; } }
public class class_name { protected JSONObject requestServer(AipRequest request) { // 请求API AipResponse response = AipHttpClient.post(request); String resData = response.getBodyStr(); Integer status = response.getStatus(); if (status.equals(200) && !resData.equals("")) { try { JSONObject res = new JSONObject(resData); if (state.getState().equals(EAuthState.STATE_POSSIBLE_CLOUD_USER)) { boolean cloudAuthState = res.isNull("error_code") || res.getInt("error_code") != AipClientConst.IAM_ERROR_CODE; state.transfer(cloudAuthState); if (LOGGER.isDebugEnabled()) { LOGGER.debug("state after cloud auth: " + state.toString()); } if (!cloudAuthState) { return Util.getGeneralError( AipClientConst.OPENAPI_NO_ACCESS_ERROR_CODE, AipClientConst.OPENAPI_NO_ACCESS_ERROR_MSG); } } return res; } catch (JSONException e) { return Util.getGeneralError(-1, resData); } } else { LOGGER.warn(String.format("call failed! response status: %d, data: %s", status, resData)); return AipError.NET_TIMEOUT_ERROR.toJsonResult(); } } }
public class class_name { protected JSONObject requestServer(AipRequest request) { // 请求API AipResponse response = AipHttpClient.post(request); String resData = response.getBodyStr(); Integer status = response.getStatus(); if (status.equals(200) && !resData.equals("")) { try { JSONObject res = new JSONObject(resData); if (state.getState().equals(EAuthState.STATE_POSSIBLE_CLOUD_USER)) { boolean cloudAuthState = res.isNull("error_code") || res.getInt("error_code") != AipClientConst.IAM_ERROR_CODE; state.transfer(cloudAuthState); // depends on control dependency: [if], data = [none] if (LOGGER.isDebugEnabled()) { LOGGER.debug("state after cloud auth: " + state.toString()); // depends on control dependency: [if], data = [none] } if (!cloudAuthState) { return Util.getGeneralError( AipClientConst.OPENAPI_NO_ACCESS_ERROR_CODE, AipClientConst.OPENAPI_NO_ACCESS_ERROR_MSG); // depends on control dependency: [if], data = [none] } } return res; // depends on control dependency: [try], data = [none] } catch (JSONException e) { return Util.getGeneralError(-1, resData); } // depends on control dependency: [catch], data = [none] } else { LOGGER.warn(String.format("call failed! response status: %d, data: %s", status, resData)); // depends on control dependency: [if], data = [none] return AipError.NET_TIMEOUT_ERROR.toJsonResult(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static KNN<double[]> learn(double[][] x, int[] y, int k) { if (x.length != y.length) { throw new IllegalArgumentException(String.format("The sizes of X and Y don't match: %d != %d", x.length, y.length)); } if (k < 1) { throw new IllegalArgumentException("Illegal k = " + k); } KNNSearch<double[], double[]> knn = null; if (x[0].length < 10) { knn = new KDTree<>(x, x); } else { knn = new CoverTree<>(x, new EuclideanDistance()); } return new KNN<>(knn, y, k); } }
public class class_name { public static KNN<double[]> learn(double[][] x, int[] y, int k) { if (x.length != y.length) { throw new IllegalArgumentException(String.format("The sizes of X and Y don't match: %d != %d", x.length, y.length)); } if (k < 1) { throw new IllegalArgumentException("Illegal k = " + k); } KNNSearch<double[], double[]> knn = null; if (x[0].length < 10) { knn = new KDTree<>(x, x); // depends on control dependency: [if], data = [none] } else { knn = new CoverTree<>(x, new EuclideanDistance()); // depends on control dependency: [if], data = [none] } return new KNN<>(knn, y, k); } }
public class class_name { public static void main(String[] args) { // run application from cmd line using Maven: // mvn exec:java -Dexec.mainClass="io.joynr.demo.MyRadioConsumerApplication" -Dexec.args="<arguments>" DiscoveryScope tmpDiscoveryScope = DiscoveryScope.LOCAL_AND_GLOBAL; String host = "localhost"; int port = 4242; String providerDomain = "domain"; String transport = null; CommandLine line; Options options = new Options(); Options helpOptions = new Options(); setupOptions(options, helpOptions); CommandLineParser parser = new DefaultParser(); // check for '-h' option alone first. This is required in order to avoid // reports about missing other args when using only '-h', which should supported // to just get help / usage info. try { line = parser.parse(helpOptions, args); if (line.hasOption('h')) { HelpFormatter formatter = new HelpFormatter(); // use 'options' here to print help about all possible parameters formatter.printHelp(MyRadioConsumerApplication.class.getName(), options, true); System.exit(0); } } catch (ParseException e) { // ignore, since any option except '-h' will cause this exception } try { line = parser.parse(options, args); if (line.hasOption('d')) { providerDomain = line.getOptionValue('d'); LOG.info("found domain = " + providerDomain); } if (line.hasOption('H')) { host = line.getOptionValue('H'); LOG.info("found host = " + host); } if (line.hasOption('l')) { tmpDiscoveryScope = DiscoveryScope.LOCAL_ONLY; LOG.info("found scope local"); } if (line.hasOption('p')) { port = Integer.parseInt(line.getOptionValue('p')); LOG.info("found port = " + port); } if (line.hasOption('t')) { transport = line.getOptionValue('t').toLowerCase(); LOG.info("found transport = " + transport); } } catch (ParseException e) { LOG.error("failed to parse command line: " + e); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(MyRadioConsumerApplication.class.getName(), options, true); System.exit(1); } // joynr config properties are used to set joynr configuration at compile time. They are set on the // JoynInjectorFactory. Properties joynrConfig = new Properties(); Module runtimeModule = getRuntimeModule(transport, host, port, joynrConfig); LOG.debug("Using the following runtime module: " + runtimeModule.getClass().getSimpleName()); LOG.debug("Searching for providers on domain \"{}\"", providerDomain); // Set a custom static persistence file (default is joynr.properties in the working dir) to store // joynr configuration. It allows for changing the joynr configuration at runtime. Custom persistence // files support running the consumer and provider applications from within the same directory. joynrConfig.setProperty(MessagingPropertyKeys.PERSISTENCE_FILE, STATIC_PERSISTENCE_FILE); // How to use custom infrastructure elements: // 1) Set them programmatically at compile time using the joynr configuration properties at the // JoynInjectorFactory. E.g. uncomment the following lines to set a certain joynr server // instance. // joynrConfig.setProperty(MessagingPropertyKeys.BOUNCE_PROXY_URL, "http://localhost:8080/bounceproxy/"); // joynrConfig.setProperty(MessagingPropertyKeys.DISCOVERYDIRECTORYURL, "http://localhost:8080/discovery/channels/discoverydirectory_channelid/"); joynrConfig.setProperty(PROPERTY_JOYNR_DOMAIN_LOCAL, "radioapp_consumer_local_domain"); // 2) Or set them in the static persistence file (default: joynr.properties in working dir) at // runtime. If not available in the working dir, it will be created during the first launch // of the application. Copy the following lines to the custom persistence file to set a // certain joynr server instance. // NOTE: This application uses a custom static persistence file consumer-joynr.properties. // Copy the following lines to the custom persistence file to set a certain joynr server // instance. // joynr.messaging.bounceproxyurl=http://localhost:8080/bounceproxy/ // joynr.messaging.discoverydirectoryurl=http://localhost:8080/discovery/channels/discoverydirectory_channelid/ // 3) Or set them in Java System properties. // -Djoynr.messaging.bounceProxyUrl=http://localhost:8080/bounceproxy/ // -Djoynr.messaging.capabilitiesDirectoryUrl=http://localhost:8080/discovery/channels/discoverydirectory_channelid/ // NOTE: // Programmatically set configuration properties override properties set in the static persistence file. // Java system properties override both // Application-specific configuration properties are injected to the application by setting // them on the JoynApplicationModule. Properties appConfig = new Properties(); appConfig.setProperty(APP_CONFIG_PROVIDER_DOMAIN, providerDomain); final DiscoveryScope discoveryScope = tmpDiscoveryScope; JoynrApplication myRadioConsumerApp = new JoynrInjectorFactory(joynrConfig, runtimeModule).createApplication(new JoynrApplicationModule(MyRadioConsumerApplication.class, appConfig) { @Override protected void configure() { super.configure(); bind(DiscoveryScope.class).toInstance(discoveryScope); } }); myRadioConsumerApp.run(); myRadioConsumerApp.shutdown(); } }
public class class_name { public static void main(String[] args) { // run application from cmd line using Maven: // mvn exec:java -Dexec.mainClass="io.joynr.demo.MyRadioConsumerApplication" -Dexec.args="<arguments>" DiscoveryScope tmpDiscoveryScope = DiscoveryScope.LOCAL_AND_GLOBAL; String host = "localhost"; int port = 4242; String providerDomain = "domain"; String transport = null; CommandLine line; Options options = new Options(); Options helpOptions = new Options(); setupOptions(options, helpOptions); CommandLineParser parser = new DefaultParser(); // check for '-h' option alone first. This is required in order to avoid // reports about missing other args when using only '-h', which should supported // to just get help / usage info. try { line = parser.parse(helpOptions, args); // depends on control dependency: [try], data = [none] if (line.hasOption('h')) { HelpFormatter formatter = new HelpFormatter(); // use 'options' here to print help about all possible parameters formatter.printHelp(MyRadioConsumerApplication.class.getName(), options, true); // depends on control dependency: [if], data = [none] System.exit(0); // depends on control dependency: [if], data = [none] } } catch (ParseException e) { // ignore, since any option except '-h' will cause this exception } // depends on control dependency: [catch], data = [none] try { line = parser.parse(options, args); // depends on control dependency: [try], data = [none] if (line.hasOption('d')) { providerDomain = line.getOptionValue('d'); // depends on control dependency: [if], data = [none] LOG.info("found domain = " + providerDomain); // depends on control dependency: [if], data = [none] } if (line.hasOption('H')) { host = line.getOptionValue('H'); // depends on control dependency: [if], data = [none] LOG.info("found host = " + host); // depends on control dependency: [if], data = [none] } if (line.hasOption('l')) { tmpDiscoveryScope = DiscoveryScope.LOCAL_ONLY; // depends on control dependency: [if], data = [none] LOG.info("found scope local"); // depends on control dependency: [if], data = [none] } if (line.hasOption('p')) { port = Integer.parseInt(line.getOptionValue('p')); // depends on control dependency: [if], data = [none] LOG.info("found port = " + port); // depends on control dependency: [if], data = [none] } if (line.hasOption('t')) { transport = line.getOptionValue('t').toLowerCase(); // depends on control dependency: [if], data = [none] LOG.info("found transport = " + transport); // depends on control dependency: [if], data = [none] } } catch (ParseException e) { LOG.error("failed to parse command line: " + e); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(MyRadioConsumerApplication.class.getName(), options, true); System.exit(1); } // depends on control dependency: [catch], data = [none] // joynr config properties are used to set joynr configuration at compile time. They are set on the // JoynInjectorFactory. Properties joynrConfig = new Properties(); Module runtimeModule = getRuntimeModule(transport, host, port, joynrConfig); LOG.debug("Using the following runtime module: " + runtimeModule.getClass().getSimpleName()); LOG.debug("Searching for providers on domain \"{}\"", providerDomain); // Set a custom static persistence file (default is joynr.properties in the working dir) to store // joynr configuration. It allows for changing the joynr configuration at runtime. Custom persistence // files support running the consumer and provider applications from within the same directory. joynrConfig.setProperty(MessagingPropertyKeys.PERSISTENCE_FILE, STATIC_PERSISTENCE_FILE); // How to use custom infrastructure elements: // 1) Set them programmatically at compile time using the joynr configuration properties at the // JoynInjectorFactory. E.g. uncomment the following lines to set a certain joynr server // instance. // joynrConfig.setProperty(MessagingPropertyKeys.BOUNCE_PROXY_URL, "http://localhost:8080/bounceproxy/"); // joynrConfig.setProperty(MessagingPropertyKeys.DISCOVERYDIRECTORYURL, "http://localhost:8080/discovery/channels/discoverydirectory_channelid/"); joynrConfig.setProperty(PROPERTY_JOYNR_DOMAIN_LOCAL, "radioapp_consumer_local_domain"); // 2) Or set them in the static persistence file (default: joynr.properties in working dir) at // runtime. If not available in the working dir, it will be created during the first launch // of the application. Copy the following lines to the custom persistence file to set a // certain joynr server instance. // NOTE: This application uses a custom static persistence file consumer-joynr.properties. // Copy the following lines to the custom persistence file to set a certain joynr server // instance. // joynr.messaging.bounceproxyurl=http://localhost:8080/bounceproxy/ // joynr.messaging.discoverydirectoryurl=http://localhost:8080/discovery/channels/discoverydirectory_channelid/ // 3) Or set them in Java System properties. // -Djoynr.messaging.bounceProxyUrl=http://localhost:8080/bounceproxy/ // -Djoynr.messaging.capabilitiesDirectoryUrl=http://localhost:8080/discovery/channels/discoverydirectory_channelid/ // NOTE: // Programmatically set configuration properties override properties set in the static persistence file. // Java system properties override both // Application-specific configuration properties are injected to the application by setting // them on the JoynApplicationModule. Properties appConfig = new Properties(); appConfig.setProperty(APP_CONFIG_PROVIDER_DOMAIN, providerDomain); final DiscoveryScope discoveryScope = tmpDiscoveryScope; JoynrApplication myRadioConsumerApp = new JoynrInjectorFactory(joynrConfig, runtimeModule).createApplication(new JoynrApplicationModule(MyRadioConsumerApplication.class, appConfig) { @Override protected void configure() { super.configure(); bind(DiscoveryScope.class).toInstance(discoveryScope); } }); myRadioConsumerApp.run(); myRadioConsumerApp.shutdown(); } }
public class class_name { public Row withPaddedHeader(final HeaderDefinition headerDefinition) { if (_headerDefinition != headerDefinition) { String[] values = new String[headerDefinition.size()]; System.arraycopy(_values, 0, values, 0, _values.length); return Row.of(headerDefinition, values); } else { return this; } } }
public class class_name { public Row withPaddedHeader(final HeaderDefinition headerDefinition) { if (_headerDefinition != headerDefinition) { String[] values = new String[headerDefinition.size()]; System.arraycopy(_values, 0, values, 0, _values.length); // depends on control dependency: [if], data = [none] return Row.of(headerDefinition, values); // depends on control dependency: [if], data = [none] } else { return this; // depends on control dependency: [if], data = [none] } } }
public class class_name { public void addAka(String country, String aka) { if (!isValidString(country) || !isValidString(aka)) { return; } this.akas.add(new CountryDetail(country, aka)); } }
public class class_name { public void addAka(String country, String aka) { if (!isValidString(country) || !isValidString(aka)) { return; // depends on control dependency: [if], data = [none] } this.akas.add(new CountryDetail(country, aka)); } }
public class class_name { public void removeHandlers() { Iterator<HandlerRegistration> it = registrations.iterator(); while (it.hasNext()) { HandlerRegistration r = it.next(); /* * must remove before we call removeHandler. Might have come from nested * ResettableEventBus */ it.remove(); r.removeHandler(); } } }
public class class_name { public void removeHandlers() { Iterator<HandlerRegistration> it = registrations.iterator(); while (it.hasNext()) { HandlerRegistration r = it.next(); /* * must remove before we call removeHandler. Might have come from nested * ResettableEventBus */ it.remove(); // depends on control dependency: [while], data = [none] r.removeHandler(); // depends on control dependency: [while], data = [none] } } }
public class class_name { @Override public OfferRequestPacket parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException { int eventType = parser.getEventType(); String sessionID = null; int timeout = -1; OfferContent content = null; boolean done = false; Map<String, List<String>> metaData = new HashMap<>(); if (eventType != XmlPullParser.START_TAG) { // throw exception } Jid userJID = ParserUtils.getJidAttribute(parser); // Default userID to the JID. Jid userID = userJID; while (!done) { eventType = parser.next(); if (eventType == XmlPullParser.START_TAG) { String elemName = parser.getName(); if ("timeout".equals(elemName)) { timeout = Integer.parseInt(parser.nextText()); } else if (MetaData.ELEMENT_NAME.equals(elemName)) { metaData = MetaDataUtils.parseMetaData(parser); } else if (SessionID.ELEMENT_NAME.equals(elemName)) { sessionID = parser.getAttributeValue("", "id"); } else if (UserID.ELEMENT_NAME.equals(elemName)) { userID = ParserUtils.getJidAttribute(parser, "id"); } else if ("user-request".equals(elemName)) { content = UserRequest.getInstance(); } else if (RoomInvitation.ELEMENT_NAME.equals(elemName)) { RoomInvitation invitation = (RoomInvitation) PacketParserUtils .parseExtensionElement(RoomInvitation.ELEMENT_NAME, RoomInvitation.NAMESPACE, parser, xmlEnvironment); content = new InvitationRequest(invitation.getInviter(), invitation.getRoom(), invitation.getReason()); } else if (RoomTransfer.ELEMENT_NAME.equals(elemName)) { RoomTransfer transfer = (RoomTransfer) PacketParserUtils .parseExtensionElement(RoomTransfer.ELEMENT_NAME, RoomTransfer.NAMESPACE, parser, xmlEnvironment); content = new TransferRequest(transfer.getInviter(), transfer.getRoom(), transfer.getReason()); } } else if (eventType == XmlPullParser.END_TAG) { if ("offer".equals(parser.getName())) { done = true; } } } OfferRequestPacket offerRequest = new OfferRequestPacket(userJID, userID, timeout, metaData, sessionID, content); offerRequest.setType(IQ.Type.set); return offerRequest; } }
public class class_name { @Override public OfferRequestPacket parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException { int eventType = parser.getEventType(); String sessionID = null; int timeout = -1; OfferContent content = null; boolean done = false; Map<String, List<String>> metaData = new HashMap<>(); if (eventType != XmlPullParser.START_TAG) { // throw exception } Jid userJID = ParserUtils.getJidAttribute(parser); // Default userID to the JID. Jid userID = userJID; while (!done) { eventType = parser.next(); if (eventType == XmlPullParser.START_TAG) { String elemName = parser.getName(); if ("timeout".equals(elemName)) { timeout = Integer.parseInt(parser.nextText()); // depends on control dependency: [if], data = [none] } else if (MetaData.ELEMENT_NAME.equals(elemName)) { metaData = MetaDataUtils.parseMetaData(parser); // depends on control dependency: [if], data = [none] } else if (SessionID.ELEMENT_NAME.equals(elemName)) { sessionID = parser.getAttributeValue("", "id"); // depends on control dependency: [if], data = [none] } else if (UserID.ELEMENT_NAME.equals(elemName)) { userID = ParserUtils.getJidAttribute(parser, "id"); // depends on control dependency: [if], data = [none] } else if ("user-request".equals(elemName)) { content = UserRequest.getInstance(); // depends on control dependency: [if], data = [none] } else if (RoomInvitation.ELEMENT_NAME.equals(elemName)) { RoomInvitation invitation = (RoomInvitation) PacketParserUtils .parseExtensionElement(RoomInvitation.ELEMENT_NAME, RoomInvitation.NAMESPACE, parser, xmlEnvironment); content = new InvitationRequest(invitation.getInviter(), invitation.getRoom(), invitation.getReason()); // depends on control dependency: [if], data = [none] } else if (RoomTransfer.ELEMENT_NAME.equals(elemName)) { RoomTransfer transfer = (RoomTransfer) PacketParserUtils .parseExtensionElement(RoomTransfer.ELEMENT_NAME, RoomTransfer.NAMESPACE, parser, xmlEnvironment); content = new TransferRequest(transfer.getInviter(), transfer.getRoom(), transfer.getReason()); // depends on control dependency: [if], data = [none] } } else if (eventType == XmlPullParser.END_TAG) { if ("offer".equals(parser.getName())) { done = true; // depends on control dependency: [if], data = [none] } } } OfferRequestPacket offerRequest = new OfferRequestPacket(userJID, userID, timeout, metaData, sessionID, content); offerRequest.setType(IQ.Type.set); return offerRequest; } }
public class class_name { public void setNote(String note) { try { staticTableHistory.updateNote(historyId, note); httpMessageCachedData.setNote(note != null && note.length() > 0); notifyEvent(HistoryReferenceEventPublisher.EVENT_NOTE_SET); } catch (DatabaseException e) { log.error(e.getMessage(), e); } } }
public class class_name { public void setNote(String note) { try { staticTableHistory.updateNote(historyId, note); // depends on control dependency: [try], data = [none] httpMessageCachedData.setNote(note != null && note.length() > 0); // depends on control dependency: [try], data = [none] notifyEvent(HistoryReferenceEventPublisher.EVENT_NOTE_SET); // depends on control dependency: [try], data = [none] } catch (DatabaseException e) { log.error(e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private Map<String, Object> buildThriftCounterSuperColumn(String tableName, String superColumnName, EmbeddableType superColumn, Object counterSuperColumnObject) { Map<String, Object> thriftCounterSuperColumns = new HashMap<String, Object>(); Iterator<Attribute> iter = superColumn.getAttributes().iterator(); List<CounterColumn> thriftColumns = new ArrayList<CounterColumn>(); while (iter.hasNext()) { Attribute column = iter.next(); Field field = (Field) column.getJavaMember(); String name = ((AbstractAttribute) column).getJPAColumnName(); String value = null; try { value = PropertyAccessorHelper.getString(counterSuperColumnObject, field); } catch (PropertyAccessException exp) { // This is an entity column to be persisted in a super column // family. It will be stored as a super column that would // have just one column with the same name if (log.isInfoEnabled()) { log.info(exp.getMessage() + ". Possible case of entity column in a super column family. Will be treated as a super column."); } value = counterSuperColumnObject.toString(); } if (null != value) { try { CounterColumn thriftColumn = new CounterColumn(); thriftColumn.setName(PropertyAccessorFactory.STRING.toBytes(name)); thriftColumn.setValue(Long.parseLong(value)); thriftColumns.add(thriftColumn); tableName = ((AbstractAttribute) column).getTableName() != null ? ((AbstractAttribute) column) .getTableName() : tableName; CounterSuperColumn thriftSuperColumn = (CounterSuperColumn) thriftCounterSuperColumns .get(tableName); if (thriftSuperColumn == null) { thriftSuperColumn = new CounterSuperColumn(); thriftSuperColumn.setName(PropertyAccessorFactory.STRING.toBytes(superColumnName)); thriftCounterSuperColumns.put(tableName, thriftSuperColumn); } thriftSuperColumn.addToColumns(thriftColumn); } catch (NumberFormatException nfe) { log.error("For counter column arguments should be numeric type, Caused by: .", nfe); throw new KunderaException(nfe); } } } return thriftCounterSuperColumns; } }
public class class_name { private Map<String, Object> buildThriftCounterSuperColumn(String tableName, String superColumnName, EmbeddableType superColumn, Object counterSuperColumnObject) { Map<String, Object> thriftCounterSuperColumns = new HashMap<String, Object>(); Iterator<Attribute> iter = superColumn.getAttributes().iterator(); List<CounterColumn> thriftColumns = new ArrayList<CounterColumn>(); while (iter.hasNext()) { Attribute column = iter.next(); Field field = (Field) column.getJavaMember(); String name = ((AbstractAttribute) column).getJPAColumnName(); String value = null; try { value = PropertyAccessorHelper.getString(counterSuperColumnObject, field); // depends on control dependency: [try], data = [none] } catch (PropertyAccessException exp) { // This is an entity column to be persisted in a super column // family. It will be stored as a super column that would // have just one column with the same name if (log.isInfoEnabled()) { log.info(exp.getMessage() + ". Possible case of entity column in a super column family. Will be treated as a super column."); // depends on control dependency: [if], data = [none] } value = counterSuperColumnObject.toString(); } // depends on control dependency: [catch], data = [none] if (null != value) { try { CounterColumn thriftColumn = new CounterColumn(); thriftColumn.setName(PropertyAccessorFactory.STRING.toBytes(name)); // depends on control dependency: [try], data = [none] thriftColumn.setValue(Long.parseLong(value)); // depends on control dependency: [try], data = [none] thriftColumns.add(thriftColumn); // depends on control dependency: [try], data = [none] tableName = ((AbstractAttribute) column).getTableName() != null ? ((AbstractAttribute) column) .getTableName() : tableName; // depends on control dependency: [try], data = [none] CounterSuperColumn thriftSuperColumn = (CounterSuperColumn) thriftCounterSuperColumns .get(tableName); if (thriftSuperColumn == null) { thriftSuperColumn = new CounterSuperColumn(); // depends on control dependency: [if], data = [none] thriftSuperColumn.setName(PropertyAccessorFactory.STRING.toBytes(superColumnName)); // depends on control dependency: [if], data = [none] thriftCounterSuperColumns.put(tableName, thriftSuperColumn); // depends on control dependency: [if], data = [none] } thriftSuperColumn.addToColumns(thriftColumn); // depends on control dependency: [try], data = [none] } catch (NumberFormatException nfe) { log.error("For counter column arguments should be numeric type, Caused by: .", nfe); throw new KunderaException(nfe); } // depends on control dependency: [catch], data = [none] } } return thriftCounterSuperColumns; } }
public class class_name { public ListEndpointsResult withEndpoints(EndpointSummary... endpoints) { if (this.endpoints == null) { setEndpoints(new java.util.ArrayList<EndpointSummary>(endpoints.length)); } for (EndpointSummary ele : endpoints) { this.endpoints.add(ele); } return this; } }
public class class_name { public ListEndpointsResult withEndpoints(EndpointSummary... endpoints) { if (this.endpoints == null) { setEndpoints(new java.util.ArrayList<EndpointSummary>(endpoints.length)); // depends on control dependency: [if], data = [none] } for (EndpointSummary ele : endpoints) { this.endpoints.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { @Override public void visitLabel(Label label) { if (enabled && handlers.containsKey(label)) { handlerPendingInstruction = label; } super.visitLabel(label); } }
public class class_name { @Override public void visitLabel(Label label) { if (enabled && handlers.containsKey(label)) { handlerPendingInstruction = label; // depends on control dependency: [if], data = [none] } super.visitLabel(label); } }
public class class_name { protected void _writeBinary(Base64Variant b64variant, byte[] input, int inputPtr, final int inputEnd) throws IOException, JsonGenerationException { // Encoding is by chunks of 3 input, 4 output chars, so: int safeInputEnd = inputEnd - 3; // Let's also reserve room for possible lf char each round int safeOutputEnd = _outputEnd - 6; int chunksBeforeLF = b64variant.getMaxLineLength() >> 2; // Ok, first we loop through all full triplets of data: while (inputPtr <= safeInputEnd) { if (_outputTail > safeOutputEnd) { // need to flush _flushBuffer(); } // First, mash 3 bytes into lsb of 32-bit int int b24 = ((int) input[inputPtr++]) << 8; b24 |= ((int) input[inputPtr++]) & 0xFF; b24 = (b24 << 8) | (((int) input[inputPtr++]) & 0xFF); _outputTail = b64variant.encodeBase64Chunk(b24, _outputBuffer, _outputTail); if (--chunksBeforeLF <= 0) { // note: RISON does not escape newlines _outputBuffer[_outputTail++] = '\n'; chunksBeforeLF = b64variant.getMaxLineLength() >> 2; } } // And then we may have 1 or 2 leftover bytes to encode int inputLeft = inputEnd - inputPtr; // 0, 1 or 2 if (inputLeft > 0) { // yes, but do we have room for output? if (_outputTail > safeOutputEnd) { // don't really need 6 bytes but... _flushBuffer(); } int b24 = ((int) input[inputPtr++]) << 16; if (inputLeft == 2) { b24 |= (((int) input[inputPtr]) & 0xFF) << 8; } _outputTail = b64variant.encodeBase64Partial(b24, inputLeft, _outputBuffer, _outputTail); } } }
public class class_name { protected void _writeBinary(Base64Variant b64variant, byte[] input, int inputPtr, final int inputEnd) throws IOException, JsonGenerationException { // Encoding is by chunks of 3 input, 4 output chars, so: int safeInputEnd = inputEnd - 3; // Let's also reserve room for possible lf char each round int safeOutputEnd = _outputEnd - 6; int chunksBeforeLF = b64variant.getMaxLineLength() >> 2; // Ok, first we loop through all full triplets of data: while (inputPtr <= safeInputEnd) { if (_outputTail > safeOutputEnd) { // need to flush _flushBuffer(); } // First, mash 3 bytes into lsb of 32-bit int int b24 = ((int) input[inputPtr++]) << 8; b24 |= ((int) input[inputPtr++]) & 0xFF; b24 = (b24 << 8) | (((int) input[inputPtr++]) & 0xFF); _outputTail = b64variant.encodeBase64Chunk(b24, _outputBuffer, _outputTail); if (--chunksBeforeLF <= 0) { // note: RISON does not escape newlines _outputBuffer[_outputTail++] = '\n'; chunksBeforeLF = b64variant.getMaxLineLength() >> 2; } } // And then we may have 1 or 2 leftover bytes to encode int inputLeft = inputEnd - inputPtr; // 0, 1 or 2 if (inputLeft > 0) { // yes, but do we have room for output? if (_outputTail > safeOutputEnd) { // don't really need 6 bytes but... _flushBuffer(); // depends on control dependency: [if], data = [none] } int b24 = ((int) input[inputPtr++]) << 16; if (inputLeft == 2) { b24 |= (((int) input[inputPtr]) & 0xFF) << 8; // depends on control dependency: [if], data = [none] } _outputTail = b64variant.encodeBase64Partial(b24, inputLeft, _outputBuffer, _outputTail); } } }
public class class_name { private void parseConfig(String config) { if (isValidConfig(config)) { String[] conf = config.split("x"); if (conf[0].trim().equals("?")) { m_width = I_CmsFormatRestriction.DIMENSION_NOT_SET; } else { m_width = CmsClientStringUtil.parseInt(conf[0]); m_width = (m_width == 0) ? I_CmsFormatRestriction.DIMENSION_NOT_SET : m_width; } if (conf[1].trim().equals("?")) { m_height = I_CmsFormatRestriction.DIMENSION_NOT_SET; } else { m_height = CmsClientStringUtil.parseInt(conf[1]); m_height = (m_height == 0) ? I_CmsFormatRestriction.DIMENSION_NOT_SET : m_height; } } } }
public class class_name { private void parseConfig(String config) { if (isValidConfig(config)) { String[] conf = config.split("x"); if (conf[0].trim().equals("?")) { m_width = I_CmsFormatRestriction.DIMENSION_NOT_SET; // depends on control dependency: [if], data = [none] } else { m_width = CmsClientStringUtil.parseInt(conf[0]); // depends on control dependency: [if], data = [none] m_width = (m_width == 0) ? I_CmsFormatRestriction.DIMENSION_NOT_SET : m_width; // depends on control dependency: [if], data = [none] } if (conf[1].trim().equals("?")) { m_height = I_CmsFormatRestriction.DIMENSION_NOT_SET; // depends on control dependency: [if], data = [none] } else { m_height = CmsClientStringUtil.parseInt(conf[1]); // depends on control dependency: [if], data = [none] m_height = (m_height == 0) ? I_CmsFormatRestriction.DIMENSION_NOT_SET : m_height; // depends on control dependency: [if], data = [none] } } } }
public class class_name { private static Map<URI, String> getOrAdd(Map<String, Map<URI, String>> map, String key) { Map<URI, String> value = map.get(key); if (value == null) { map.put(key, value = new HashMap<>()); } return value; } }
public class class_name { private static Map<URI, String> getOrAdd(Map<String, Map<URI, String>> map, String key) { Map<URI, String> value = map.get(key); if (value == null) { map.put(key, value = new HashMap<>()); // depends on control dependency: [if], data = [none] } return value; } }
public class class_name { protected Map<String, List<Object>> getReleasedByDefaultAttributes(final Principal p, final Map<String, List<Object>> attributes) { val ctx = ApplicationContextProvider.getApplicationContext(); if (ctx != null) { LOGGER.trace("Located application context. Retrieving default attributes for release, if any"); val props = ctx.getAutowireCapableBeanFactory().getBean(CasConfigurationProperties.class); val defaultAttrs = props.getAuthn().getAttributeRepository().getDefaultAttributesToRelease(); LOGGER.debug("Default attributes for release are: [{}]", defaultAttrs); val defaultAttributesToRelease = new TreeMap<String, List<Object>>(String.CASE_INSENSITIVE_ORDER); defaultAttrs.forEach(key -> { if (attributes.containsKey(key)) { LOGGER.debug("Found and added default attribute for release: [{}]", key); defaultAttributesToRelease.put(key, attributes.get(key)); } }); return defaultAttributesToRelease; } return new TreeMap<>(); } }
public class class_name { protected Map<String, List<Object>> getReleasedByDefaultAttributes(final Principal p, final Map<String, List<Object>> attributes) { val ctx = ApplicationContextProvider.getApplicationContext(); if (ctx != null) { LOGGER.trace("Located application context. Retrieving default attributes for release, if any"); // depends on control dependency: [if], data = [none] val props = ctx.getAutowireCapableBeanFactory().getBean(CasConfigurationProperties.class); val defaultAttrs = props.getAuthn().getAttributeRepository().getDefaultAttributesToRelease(); LOGGER.debug("Default attributes for release are: [{}]", defaultAttrs); val defaultAttributesToRelease = new TreeMap<String, List<Object>>(String.CASE_INSENSITIVE_ORDER); defaultAttrs.forEach(key -> { if (attributes.containsKey(key)) { LOGGER.debug("Found and added default attribute for release: [{}]", key); defaultAttributesToRelease.put(key, attributes.get(key)); } }); // depends on control dependency: [if], data = [none] return defaultAttributesToRelease; // depends on control dependency: [if], data = [none] } return new TreeMap<>(); } }
public class class_name { @POST @Produces({"script/groovy"}) @Path("src/{repository}/{workspace}/{path:.*}") public Response getScript(@PathParam("repository") String repository, @PathParam("workspace") String workspace, @PathParam("path") String path) { Session ses = null; try { ses = sessionProviderService.getSessionProvider(null).getSession(workspace, repositoryService.getRepository(repository)); Node scriptFile = (Node)ses.getItem("/" + path); return Response.status(Response.Status.OK).entity( scriptFile.getNode("jcr:content").getProperty("jcr:data").getStream()).type("script/groovy").build(); } catch (PathNotFoundException e) { String msg = "Path " + path + " does not exists"; LOG.error(msg); return Response.status(Response.Status.NOT_FOUND).entity(msg).entity(MediaType.TEXT_PLAIN).build(); } catch (Exception e) { LOG.error(e.getMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()) .type(MediaType.TEXT_PLAIN).build(); } finally { if (ses != null) { ses.logout(); } } } }
public class class_name { @POST @Produces({"script/groovy"}) @Path("src/{repository}/{workspace}/{path:.*}") public Response getScript(@PathParam("repository") String repository, @PathParam("workspace") String workspace, @PathParam("path") String path) { Session ses = null; try { ses = sessionProviderService.getSessionProvider(null).getSession(workspace, repositoryService.getRepository(repository)); // depends on control dependency: [try], data = [none] Node scriptFile = (Node)ses.getItem("/" + path); return Response.status(Response.Status.OK).entity( scriptFile.getNode("jcr:content").getProperty("jcr:data").getStream()).type("script/groovy").build(); // depends on control dependency: [try], data = [none] } catch (PathNotFoundException e) { String msg = "Path " + path + " does not exists"; LOG.error(msg); return Response.status(Response.Status.NOT_FOUND).entity(msg).entity(MediaType.TEXT_PLAIN).build(); } // depends on control dependency: [catch], data = [none] catch (Exception e) { LOG.error(e.getMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()) .type(MediaType.TEXT_PLAIN).build(); } // depends on control dependency: [catch], data = [none] finally { if (ses != null) { ses.logout(); // depends on control dependency: [if], data = [none] } } } }
public class class_name { @SuppressWarnings("unchecked") public void setSettings(Object presets) { if (presets == null) { m_settingPresets = null; } else if (!(presets instanceof Map)) { throw new IllegalArgumentException( "cms:container -- value of 'settings' attribute should be a map, but is " + ClassUtils.getCanonicalName(presets)); } else { m_settingPresets = new HashMap<>((Map<String, String>)presets); } } }
public class class_name { @SuppressWarnings("unchecked") public void setSettings(Object presets) { if (presets == null) { m_settingPresets = null; // depends on control dependency: [if], data = [none] } else if (!(presets instanceof Map)) { throw new IllegalArgumentException( "cms:container -- value of 'settings' attribute should be a map, but is " + ClassUtils.getCanonicalName(presets)); } else { m_settingPresets = new HashMap<>((Map<String, String>)presets); // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override public boolean onInterceptTouchEvent(MotionEvent event) { try { if (event == null || getAdapter() == null || getAdapter().getCount() == 0) { return false; } return super.onInterceptTouchEvent(event); } catch (RuntimeException e) { Log.e(TAG, "Exception during WrapContentViewPager onTouchEvent: " + "index out of bound, or nullpointer even if we check the adapter before " + e.toString()); return false; } } }
public class class_name { @Override public boolean onInterceptTouchEvent(MotionEvent event) { try { if (event == null || getAdapter() == null || getAdapter().getCount() == 0) { return false; // depends on control dependency: [if], data = [none] } return super.onInterceptTouchEvent(event); // depends on control dependency: [try], data = [none] } catch (RuntimeException e) { Log.e(TAG, "Exception during WrapContentViewPager onTouchEvent: " + "index out of bound, or nullpointer even if we check the adapter before " + e.toString()); return false; } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static int getVIntSize(long i) { if (i >= -112 && i <= 127) { return 1; } if (i < 0) { i ^= -1L; // take one's complement' } // find the number of bytes with non-leading zeros int dataBits = Long.SIZE - Long.numberOfLeadingZeros(i); // find the number of data bytes + length byte return (dataBits + 7) / 8 + 1; } }
public class class_name { public static int getVIntSize(long i) { if (i >= -112 && i <= 127) { return 1; // depends on control dependency: [if], data = [none] } if (i < 0) { i ^= -1L; // take one's complement' // depends on control dependency: [if], data = [none] } // find the number of bytes with non-leading zeros int dataBits = Long.SIZE - Long.numberOfLeadingZeros(i); // find the number of data bytes + length byte return (dataBits + 7) / 8 + 1; } }
public class class_name { public void discardConnection(Connection realConnection) { JdbcUtils.close(realConnection); lock.lock(); try { activeCount--; discardCount++; if (activeCount <= 0) { emptySignal(); } } finally { lock.unlock(); } } }
public class class_name { public void discardConnection(Connection realConnection) { JdbcUtils.close(realConnection); lock.lock(); try { activeCount--; // depends on control dependency: [try], data = [none] discardCount++; // depends on control dependency: [try], data = [none] if (activeCount <= 0) { emptySignal(); // depends on control dependency: [if], data = [none] } } finally { lock.unlock(); } } }
public class class_name { public static <T> T invokeUnchecked(Constructor<T> constructor, Object... arguments) { try { return constructor.newInstance(arguments); } catch (IllegalAccessException ex) { // This cannot happen if the constructor is public. throw new IllegalArgumentException("Constructor is not publicly accessible.", ex); } catch (InstantiationException ex) { // This can only happen if the constructor belongs to an // abstract class. throw new IllegalArgumentException("Constructor is part of an abstract class.", ex); } catch (InvocationTargetException ex) { // If the method is not declared to throw any checked exceptions, // the worst that can happen is a RuntimeException or an Error (we can, // and should, re-throw both). if (ex.getCause() instanceof Error) { throw (Error) ex.getCause(); } else { throw (RuntimeException) ex.getCause(); } } } }
public class class_name { public static <T> T invokeUnchecked(Constructor<T> constructor, Object... arguments) { try { return constructor.newInstance(arguments); // depends on control dependency: [try], data = [none] } catch (IllegalAccessException ex) { // This cannot happen if the constructor is public. throw new IllegalArgumentException("Constructor is not publicly accessible.", ex); } // depends on control dependency: [catch], data = [none] catch (InstantiationException ex) { // This can only happen if the constructor belongs to an // abstract class. throw new IllegalArgumentException("Constructor is part of an abstract class.", ex); } // depends on control dependency: [catch], data = [none] catch (InvocationTargetException ex) { // If the method is not declared to throw any checked exceptions, // the worst that can happen is a RuntimeException or an Error (we can, // and should, re-throw both). if (ex.getCause() instanceof Error) { throw (Error) ex.getCause(); } else { throw (RuntimeException) ex.getCause(); } } // depends on control dependency: [catch], data = [none] } }
public class class_name { protected String getBaseUri() { if (mSession != null && mSession.getAuthInfo() != null && mSession.getAuthInfo().getBaseDomain() != null){ return String.format(BoxConstants.BASE_URI_TEMPLATE,mSession.getAuthInfo().getBaseDomain()); } return mBaseUri; } }
public class class_name { protected String getBaseUri() { if (mSession != null && mSession.getAuthInfo() != null && mSession.getAuthInfo().getBaseDomain() != null){ return String.format(BoxConstants.BASE_URI_TEMPLATE,mSession.getAuthInfo().getBaseDomain()); // depends on control dependency: [if], data = [none] } return mBaseUri; } }
public class class_name { private void setupRelationshipRepositories(Class<?> resourceClass, boolean mapped) { MetaLookup metaLookup = mapped ? resourceMetaLookup : jpaMetaLookup; Class<? extends MetaDataObject> metaClass = mapped ? MetaJsonObject.class : MetaJpaDataObject.class; MetaDataObject meta = metaLookup.getMeta(resourceClass, metaClass); for (MetaAttribute attr : meta.getAttributes()) { if (!attr.isAssociation()) { continue; } MetaType attrType = attr.getType().getElementType(); if (attrType instanceof MetaEntity) { // normal entity association Class<?> attrImplClass = attrType.getImplementationClass(); JpaRepositoryConfig<?> attrConfig = getRepositoryConfig(attrImplClass); // only include relations that are exposed as repositories if (attrConfig != null) { RelationshipRepositoryV2<?, ?, ?, ?> relationshipRepository = filterRelationshipCreation(attrImplClass, repositoryFactory.createRelationshipRepository(this, resourceClass, attrConfig)); context.addRepository(relationshipRepository); } } else if (attrType instanceof MetaResource) { Class<?> attrImplClass = attrType.getImplementationClass(); JpaRepositoryConfig<?> attrConfig = getRepositoryConfig(attrImplClass); if (attrConfig == null || attrConfig.getMapper() == null) { throw new IllegalStateException("no mapped entity for " + attrType.getName() + " reference by " + attr.getId() + " registered"); } JpaRepositoryConfig<?> targetConfig = getRepositoryConfig(attrImplClass); Class<?> targetResourceClass = targetConfig.getResourceClass(); RelationshipRepositoryV2<?, ?, ?, ?> relationshipRepository = filterRelationshipCreation(targetResourceClass, repositoryFactory.createRelationshipRepository(this, resourceClass, attrConfig)); context.addRepository(relationshipRepository); } else { throw new IllegalStateException("unable to process relation: " + attr.getId() + ", neither a entity nor a mapped entity is referenced"); } } } }
public class class_name { private void setupRelationshipRepositories(Class<?> resourceClass, boolean mapped) { MetaLookup metaLookup = mapped ? resourceMetaLookup : jpaMetaLookup; Class<? extends MetaDataObject> metaClass = mapped ? MetaJsonObject.class : MetaJpaDataObject.class; MetaDataObject meta = metaLookup.getMeta(resourceClass, metaClass); for (MetaAttribute attr : meta.getAttributes()) { if (!attr.isAssociation()) { continue; } MetaType attrType = attr.getType().getElementType(); if (attrType instanceof MetaEntity) { // normal entity association Class<?> attrImplClass = attrType.getImplementationClass(); JpaRepositoryConfig<?> attrConfig = getRepositoryConfig(attrImplClass); // only include relations that are exposed as repositories if (attrConfig != null) { RelationshipRepositoryV2<?, ?, ?, ?> relationshipRepository = filterRelationshipCreation(attrImplClass, repositoryFactory.createRelationshipRepository(this, resourceClass, attrConfig)); // depends on control dependency: [if], data = [none] context.addRepository(relationshipRepository); // depends on control dependency: [if], data = [none] } } else if (attrType instanceof MetaResource) { Class<?> attrImplClass = attrType.getImplementationClass(); JpaRepositoryConfig<?> attrConfig = getRepositoryConfig(attrImplClass); if (attrConfig == null || attrConfig.getMapper() == null) { throw new IllegalStateException("no mapped entity for " + attrType.getName() + " reference by " + attr.getId() + " registered"); } JpaRepositoryConfig<?> targetConfig = getRepositoryConfig(attrImplClass); Class<?> targetResourceClass = targetConfig.getResourceClass(); RelationshipRepositoryV2<?, ?, ?, ?> relationshipRepository = filterRelationshipCreation(targetResourceClass, repositoryFactory.createRelationshipRepository(this, resourceClass, attrConfig)); context.addRepository(relationshipRepository); } else { throw new IllegalStateException("unable to process relation: " + attr.getId() + ", neither a entity nor a mapped entity is referenced"); } } } }