code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { private List<String> sortIds(Set<String> docIdSet, List<FieldSort> sortDocument, List<Index> indexes, SQLDatabase db) throws QueryException { boolean smallResultSet = (docIdSet.size() < SMALL_RESULT_SET_SIZE_THRESHOLD); SqlParts orderBy = sqlToSortIds(docIdSet, sortDocument, indexes); List<String> sortedIds = null; // The query will iterate through a sorted list of docIds. // This means that if we create a new array and add entries // to that array as we iterate through the result set which // are part of the query's results, we'll end up with an // ordered set of results. Cursor cursor = null; try { cursor = db.rawQuery(orderBy.sqlWithPlaceHolders, orderBy.placeHolderValues); while (cursor.moveToNext()) { if (sortedIds == null) { sortedIds = new ArrayList<String>(); } String candidateId = cursor.getString(0); if (smallResultSet) { sortedIds.add(candidateId); } else { if (docIdSet.contains(candidateId)) { sortedIds.add(candidateId); } } } } catch (SQLException e) { logger.log(Level.SEVERE, "Failed to sort doc ids.", e); return null; } finally { DatabaseUtils.closeCursorQuietly(cursor); } return sortedIds; } }
public class class_name { private List<String> sortIds(Set<String> docIdSet, List<FieldSort> sortDocument, List<Index> indexes, SQLDatabase db) throws QueryException { boolean smallResultSet = (docIdSet.size() < SMALL_RESULT_SET_SIZE_THRESHOLD); SqlParts orderBy = sqlToSortIds(docIdSet, sortDocument, indexes); List<String> sortedIds = null; // The query will iterate through a sorted list of docIds. // This means that if we create a new array and add entries // to that array as we iterate through the result set which // are part of the query's results, we'll end up with an // ordered set of results. Cursor cursor = null; try { cursor = db.rawQuery(orderBy.sqlWithPlaceHolders, orderBy.placeHolderValues); while (cursor.moveToNext()) { if (sortedIds == null) { sortedIds = new ArrayList<String>(); // depends on control dependency: [if], data = [none] } String candidateId = cursor.getString(0); if (smallResultSet) { sortedIds.add(candidateId); // depends on control dependency: [if], data = [none] } else { if (docIdSet.contains(candidateId)) { sortedIds.add(candidateId); // depends on control dependency: [if], data = [none] } } } } catch (SQLException e) { logger.log(Level.SEVERE, "Failed to sort doc ids.", e); return null; } finally { DatabaseUtils.closeCursorQuietly(cursor); } return sortedIds; } }
public class class_name { private String rdNumber(int base) throws LexException { StringBuilder v = new StringBuilder(); int n = value(ch); // long v = n; v.append(ch); if (n < 0 || n >= base) { throwMessage(1001, "Invalid char [" + ch + "] in base " + base + " number"); } while (true) { rdCh(); n = value(ch); if (n < 0 || n >= base) { return v.toString(); } // v = (v * base) + n; v.append(ch); } } }
public class class_name { private String rdNumber(int base) throws LexException { StringBuilder v = new StringBuilder(); int n = value(ch); // long v = n; v.append(ch); if (n < 0 || n >= base) { throwMessage(1001, "Invalid char [" + ch + "] in base " + base + " number"); } while (true) { rdCh(); n = value(ch); if (n < 0 || n >= base) { return v.toString(); // depends on control dependency: [if], data = [none] } // v = (v * base) + n; v.append(ch); } } }
public class class_name { @SuppressWarnings("unchecked") public static <T> T contextualize(final OperationalContextRetriver retriver, final T instance, Class<?> interfaze, final Class<?>... contextPropagatingInterfaces) { return (T) Proxy.newProxyInstance(instance.getClass().getClassLoader(), new Class<?>[] {interfaze}, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { OperationalContext context = retriver.retrieve(); context.activate(); try { Object result = method.invoke(instance, args); Class<?> type = method.getReturnType(); if (result != null && type != null && type.isInterface() && Arrays.asList( contextPropagatingInterfaces).contains(type)) { return contextualize(retriver, result, type, contextPropagatingInterfaces); } else { return result; } } catch (InvocationTargetException e) { throw e.getTargetException(); } finally { context.deactivate(); } } }); } }
public class class_name { @SuppressWarnings("unchecked") public static <T> T contextualize(final OperationalContextRetriver retriver, final T instance, Class<?> interfaze, final Class<?>... contextPropagatingInterfaces) { return (T) Proxy.newProxyInstance(instance.getClass().getClassLoader(), new Class<?>[] {interfaze}, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { OperationalContext context = retriver.retrieve(); context.activate(); try { Object result = method.invoke(instance, args); Class<?> type = method.getReturnType(); if (result != null && type != null && type.isInterface() && Arrays.asList( contextPropagatingInterfaces).contains(type)) { return contextualize(retriver, result, type, contextPropagatingInterfaces); // depends on control dependency: [if], data = [none] } else { return result; // depends on control dependency: [if], data = [none] } } catch (InvocationTargetException e) { throw e.getTargetException(); } finally { context.deactivate(); } } }); } }
public class class_name { private static void removeMethodByName(Method method, List<Method> methods) { if(methods != null) { Iterator<Method> itr = methods.iterator(); Method aMethod = null; while(itr.hasNext()) { aMethod = itr.next(); if(aMethod.getName().equals(method.getName())) { itr.remove(); break; } } if(aMethod != null) { methods.add(aMethod); } } } }
public class class_name { private static void removeMethodByName(Method method, List<Method> methods) { if(methods != null) { Iterator<Method> itr = methods.iterator(); Method aMethod = null; while(itr.hasNext()) { aMethod = itr.next(); // depends on control dependency: [while], data = [none] if(aMethod.getName().equals(method.getName())) { itr.remove(); // depends on control dependency: [if], data = [none] break; } } if(aMethod != null) { methods.add(aMethod); // depends on control dependency: [if], data = [(aMethod] } } } }
public class class_name { public static boolean isIdentical(DMatrix a, DMatrix b , double tol ) { if( a.getNumRows() != b.getNumRows() || a.getNumCols() != b.getNumCols() ) { return false; } if( tol < 0 ) throw new IllegalArgumentException("Tolerance must be greater than or equal to zero."); final int numRows = a.getNumRows(); final int numCols = a.getNumCols(); for (int row = 0; row < numRows; row++) { for (int col = 0; col < numCols; col++) { if( !UtilEjml.isIdentical(a.unsafe_get(row,col),b.unsafe_get(row,col), tol)) return false; } } return true; } }
public class class_name { public static boolean isIdentical(DMatrix a, DMatrix b , double tol ) { if( a.getNumRows() != b.getNumRows() || a.getNumCols() != b.getNumCols() ) { return false; // depends on control dependency: [if], data = [none] } if( tol < 0 ) throw new IllegalArgumentException("Tolerance must be greater than or equal to zero."); final int numRows = a.getNumRows(); final int numCols = a.getNumCols(); for (int row = 0; row < numRows; row++) { for (int col = 0; col < numCols; col++) { if( !UtilEjml.isIdentical(a.unsafe_get(row,col),b.unsafe_get(row,col), tol)) return false; } } return true; } }
public class class_name { private File findFile(File base, String path, boolean cs) { if (FileUtil.isAbsolutePath(path)) { if (base == null) { String[] s = FileUtil.dissect(path); base = new File(s[0]); path = s[1]; } else { File f = FileUtil.normalize(path); String s = FileUtil.removeLeadingPath(base, f); if (s.equals(f.getAbsolutePath())) { //removing base from path yields no change; path not child of base return null; } path = s; } } return findFile(base, SelectorUtils.tokenizePath(path), cs); } }
public class class_name { private File findFile(File base, String path, boolean cs) { if (FileUtil.isAbsolutePath(path)) { if (base == null) { String[] s = FileUtil.dissect(path); base = new File(s[0]); // depends on control dependency: [if], data = [none] path = s[1]; // depends on control dependency: [if], data = [none] } else { File f = FileUtil.normalize(path); String s = FileUtil.removeLeadingPath(base, f); if (s.equals(f.getAbsolutePath())) { //removing base from path yields no change; path not child of base return null; // depends on control dependency: [if], data = [none] } path = s; // depends on control dependency: [if], data = [none] } } return findFile(base, SelectorUtils.tokenizePath(path), cs); } }
public class class_name { public static GEOMTYPE getGeometryType( SimpleFeatureCollection featureCollection ) { GeometryDescriptor geometryDescriptor = featureCollection.getSchema().getGeometryDescriptor(); if (EGeometryType.isPolygon(geometryDescriptor)) { return GEOMTYPE.POLYGON; } else if (EGeometryType.isLine(geometryDescriptor)) { return GEOMTYPE.LINE; } else if (EGeometryType.isPoint(geometryDescriptor)) { return GEOMTYPE.POINT; } else { return GEOMTYPE.UNKNOWN; } } }
public class class_name { public static GEOMTYPE getGeometryType( SimpleFeatureCollection featureCollection ) { GeometryDescriptor geometryDescriptor = featureCollection.getSchema().getGeometryDescriptor(); if (EGeometryType.isPolygon(geometryDescriptor)) { return GEOMTYPE.POLYGON; // depends on control dependency: [if], data = [none] } else if (EGeometryType.isLine(geometryDescriptor)) { return GEOMTYPE.LINE; // depends on control dependency: [if], data = [none] } else if (EGeometryType.isPoint(geometryDescriptor)) { return GEOMTYPE.POINT; // depends on control dependency: [if], data = [none] } else { return GEOMTYPE.UNKNOWN; // depends on control dependency: [if], data = [none] } } }
public class class_name { public void start(){ try { jmsServer.setConfiguration(config); jmsServer.setJmsConfiguration(jmsConfig); jmsServer.start(); ConnectionFactory connectionFactory = (ConnectionFactory) jmsServer.lookup("/cf"); if(connectionFactory == null){ throw new AsyncException("Failed to start EmbeddedJMS server due to previous errors."); } consumerConnection = connectionFactory.createConnection(); receiverSessionPool = new SessionPool("Consumer", consumerConnection); producerConnection = connectionFactory.createConnection(); senderSessionPool = new SessionPool("Producer", producerConnection); configureListeners(injector, queueConfigsList); started = true; } catch (Exception e) { throw new AsyncException(e); } } }
public class class_name { public void start(){ try { jmsServer.setConfiguration(config); // depends on control dependency: [try], data = [none] jmsServer.setJmsConfiguration(jmsConfig); // depends on control dependency: [try], data = [none] jmsServer.start(); // depends on control dependency: [try], data = [none] ConnectionFactory connectionFactory = (ConnectionFactory) jmsServer.lookup("/cf"); if(connectionFactory == null){ throw new AsyncException("Failed to start EmbeddedJMS server due to previous errors."); } consumerConnection = connectionFactory.createConnection(); // depends on control dependency: [try], data = [none] receiverSessionPool = new SessionPool("Consumer", consumerConnection); // depends on control dependency: [try], data = [none] producerConnection = connectionFactory.createConnection(); // depends on control dependency: [try], data = [none] senderSessionPool = new SessionPool("Producer", producerConnection); // depends on control dependency: [try], data = [none] configureListeners(injector, queueConfigsList); // depends on control dependency: [try], data = [none] started = true; // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new AsyncException(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override protected String documentation() { if (documentation == null) { JavaFileObject overviewPath = getOverviewPath(); if (overviewPath == null) { // no doc file to be had documentation = ""; } else { // read from file try { documentation = readHTMLDocumentation( overviewPath.openInputStream(), overviewPath); } catch (IOException exc) { documentation = ""; env.error(null, "javadoc.File_Read_Error", overviewPath.getName()); } } } return documentation; } }
public class class_name { @Override protected String documentation() { if (documentation == null) { JavaFileObject overviewPath = getOverviewPath(); if (overviewPath == null) { // no doc file to be had documentation = ""; // depends on control dependency: [if], data = [none] } else { // read from file try { documentation = readHTMLDocumentation( overviewPath.openInputStream(), overviewPath); // depends on control dependency: [try], data = [none] } catch (IOException exc) { documentation = ""; env.error(null, "javadoc.File_Read_Error", overviewPath.getName()); } // depends on control dependency: [catch], data = [none] } } return documentation; } }
public class class_name { private static void initializeDrawee(Context context, @Nullable DraweeConfig draweeConfig) { if (FrescoSystrace.isTracing()) { FrescoSystrace.beginSection("Fresco.initializeDrawee"); } sDraweeControllerBuilderSupplier = new PipelineDraweeControllerBuilderSupplier(context, draweeConfig); SimpleDraweeView.initialize(sDraweeControllerBuilderSupplier); if (FrescoSystrace.isTracing()) { FrescoSystrace.endSection(); } } }
public class class_name { private static void initializeDrawee(Context context, @Nullable DraweeConfig draweeConfig) { if (FrescoSystrace.isTracing()) { FrescoSystrace.beginSection("Fresco.initializeDrawee"); // depends on control dependency: [if], data = [none] } sDraweeControllerBuilderSupplier = new PipelineDraweeControllerBuilderSupplier(context, draweeConfig); SimpleDraweeView.initialize(sDraweeControllerBuilderSupplier); if (FrescoSystrace.isTracing()) { FrescoSystrace.endSection(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void reset() { final ReentrantLock lock = this.lock; lock.lock(); try { breakBarrier(); // break the current generation nextGeneration(); // start a new generation } finally { lock.unlock(); } } }
public class class_name { public void reset() { final ReentrantLock lock = this.lock; lock.lock(); try { breakBarrier(); // break the current generation // depends on control dependency: [try], data = [none] nextGeneration(); // start a new generation // depends on control dependency: [try], data = [none] } finally { lock.unlock(); } } }
public class class_name { public void marshall(UpdateJobQueueRequest updateJobQueueRequest, ProtocolMarshaller protocolMarshaller) { if (updateJobQueueRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(updateJobQueueRequest.getJobQueue(), JOBQUEUE_BINDING); protocolMarshaller.marshall(updateJobQueueRequest.getState(), STATE_BINDING); protocolMarshaller.marshall(updateJobQueueRequest.getPriority(), PRIORITY_BINDING); protocolMarshaller.marshall(updateJobQueueRequest.getComputeEnvironmentOrder(), COMPUTEENVIRONMENTORDER_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(UpdateJobQueueRequest updateJobQueueRequest, ProtocolMarshaller protocolMarshaller) { if (updateJobQueueRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(updateJobQueueRequest.getJobQueue(), JOBQUEUE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(updateJobQueueRequest.getState(), STATE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(updateJobQueueRequest.getPriority(), PRIORITY_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(updateJobQueueRequest.getComputeEnvironmentOrder(), COMPUTEENVIRONMENTORDER_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 base_responses add(nitro_service client, clusternodegroup resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { clusternodegroup addresources[] = new clusternodegroup[resources.length]; for (int i=0;i<resources.length;i++){ addresources[i] = new clusternodegroup(); addresources[i].name = resources[i].name; addresources[i].strict = resources[i].strict; } result = add_bulk_request(client, addresources); } return result; } }
public class class_name { public static base_responses add(nitro_service client, clusternodegroup resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { clusternodegroup addresources[] = new clusternodegroup[resources.length]; for (int i=0;i<resources.length;i++){ addresources[i] = new clusternodegroup(); // depends on control dependency: [for], data = [i] addresources[i].name = resources[i].name; // depends on control dependency: [for], data = [i] addresources[i].strict = resources[i].strict; // depends on control dependency: [for], data = [i] } result = add_bulk_request(client, addresources); } return result; } }
public class class_name { private com.github.fge.jsonschema.main.JsonSchema getValidator() throws ProcessingException { if (validator == null) { synchronized (this) { if (validator == null) { ValidationConfigurationBuilder cfgBuilder = ValidationConfiguration.newBuilder(); cfgBuilder.addLibrary("http://brutusin.org/json/json-schema-spec", DraftV3Library.get()); validator = JsonSchemaFactory.newBuilder().setValidationConfiguration(cfgBuilder.freeze()).freeze().getJsonSchema(getNode()); } } } return validator; } }
public class class_name { private com.github.fge.jsonschema.main.JsonSchema getValidator() throws ProcessingException { if (validator == null) { synchronized (this) { if (validator == null) { ValidationConfigurationBuilder cfgBuilder = ValidationConfiguration.newBuilder(); cfgBuilder.addLibrary("http://brutusin.org/json/json-schema-spec", DraftV3Library.get()); validator = JsonSchemaFactory.newBuilder().setValidationConfiguration(cfgBuilder.freeze()).freeze().getJsonSchema(getNode()); // depends on control dependency: [if], data = [none] } } } return validator; } }
public class class_name { protected void bindBlobLiteral(int index, byte[] value) { if (blobLiterals == null) { blobLiterals = new LinkedHashMap<>(); } blobLiterals.put(index, value); } }
public class class_name { protected void bindBlobLiteral(int index, byte[] value) { if (blobLiterals == null) { blobLiterals = new LinkedHashMap<>(); // depends on control dependency: [if], data = [none] } blobLiterals.put(index, value); } }
public class class_name { public static String join(Iterable<?> iterable, String separator) { if (iterable != null) { StringBuilder buf = new StringBuilder(); Iterator<?> it = iterable.iterator(); char singleChar = separator.length() == 1 ? separator.charAt(0) : 0; while (it.hasNext()) { buf.append(it.next()); if (it.hasNext()) { if (singleChar != 0) { // More efficient buf.append(singleChar); } else { buf.append(separator); } } } return buf.toString(); } else { return ""; } } }
public class class_name { public static String join(Iterable<?> iterable, String separator) { if (iterable != null) { StringBuilder buf = new StringBuilder(); Iterator<?> it = iterable.iterator(); char singleChar = separator.length() == 1 ? separator.charAt(0) : 0; while (it.hasNext()) { buf.append(it.next()); // depends on control dependency: [while], data = [none] if (it.hasNext()) { if (singleChar != 0) { // More efficient buf.append(singleChar); // depends on control dependency: [if], data = [(singleChar] } else { buf.append(separator); // depends on control dependency: [if], data = [none] } } } return buf.toString(); // depends on control dependency: [if], data = [none] } else { return ""; // depends on control dependency: [if], data = [none] } } }
public class class_name { private void saveLastFetchedId(byte[] lastFetchedId) { if (lastFetchedId != null) { rocksDbWrapper.put(cfNameMetadata, writeOptions, keyLastFetchedId, lastFetchedId); } } }
public class class_name { private void saveLastFetchedId(byte[] lastFetchedId) { if (lastFetchedId != null) { rocksDbWrapper.put(cfNameMetadata, writeOptions, keyLastFetchedId, lastFetchedId); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static String toBase64(byte[] byteArray) { String result = null; if (byteArray != null) { result = Base64.encodeBase64String(byteArray); } return result; } }
public class class_name { public static String toBase64(byte[] byteArray) { String result = null; if (byteArray != null) { result = Base64.encodeBase64String(byteArray); // depends on control dependency: [if], data = [(byteArray] } return result; } }
public class class_name { protected void initializeElements() { final BusLine line = getBusLine(); if (line != null) { int i = 0; for (final BusItinerary itinerary : line.busItineraries()) { onBusItineraryAdded(itinerary, i); ++i; } } } }
public class class_name { protected void initializeElements() { final BusLine line = getBusLine(); if (line != null) { int i = 0; for (final BusItinerary itinerary : line.busItineraries()) { onBusItineraryAdded(itinerary, i); // depends on control dependency: [for], data = [itinerary] ++i; // depends on control dependency: [for], data = [none] } } } }
public class class_name { public Match find(String text) { if (regexp == null) return null; Matcher m = regexp.matcher(text); if (m.find()) { Match match = new Match(); match.setText(text); match.match = m; match.start = m.start(0); match.end = m.end(0); match.line = text; return match; } else { return null; } } }
public class class_name { public Match find(String text) { if (regexp == null) return null; Matcher m = regexp.matcher(text); if (m.find()) { Match match = new Match(); match.setText(text); // depends on control dependency: [if], data = [none] match.match = m; // depends on control dependency: [if], data = [none] match.start = m.start(0); // depends on control dependency: [if], data = [none] match.end = m.end(0); // depends on control dependency: [if], data = [none] match.line = text; // depends on control dependency: [if], data = [none] return match; // depends on control dependency: [if], data = [none] } else { return null; // depends on control dependency: [if], data = [none] } } }
public class class_name { private String getAction(final Annotation[] annotations, final Method method) { for (final Annotation annotation : annotations) { if (annotation instanceof Audit) { final Audit audit = (Audit) annotation; String action = audit.action(); if (ACTION.equals(action)) { return method.getName(); } else { return action; } } } return null; } }
public class class_name { private String getAction(final Annotation[] annotations, final Method method) { for (final Annotation annotation : annotations) { if (annotation instanceof Audit) { final Audit audit = (Audit) annotation; String action = audit.action(); if (ACTION.equals(action)) { return method.getName(); // depends on control dependency: [if], data = [none] } else { return action; // depends on control dependency: [if], data = [none] } } } return null; } }
public class class_name { List<HttpSenderListener> getHttpSenderListeners() { if (httpSenderListeners == null) { return Collections.emptyList(); } return Collections.unmodifiableList(httpSenderListeners); } }
public class class_name { List<HttpSenderListener> getHttpSenderListeners() { if (httpSenderListeners == null) { return Collections.emptyList(); // depends on control dependency: [if], data = [none] } return Collections.unmodifiableList(httpSenderListeners); } }
public class class_name { private IStereoElement newTetrahedral(int u, int[] vs, IAtom[] atoms, Configuration c) { // no way to handle tetrahedral configurations with implicit // hydrogen or lone pair at the moment if (vs.length != 4) { // sanity check if (vs.length != 3) return null; // there is an implicit hydrogen (or lone-pair) we insert the // central atom in sorted position vs = insert(u, vs); } // @TH1/@TH2 = anti-clockwise and clockwise respectively Stereo stereo = c == Configuration.TH1 ? Stereo.ANTI_CLOCKWISE : Stereo.CLOCKWISE; return new TetrahedralChirality(atoms[u], new IAtom[]{atoms[vs[0]], atoms[vs[1]], atoms[vs[2]], atoms[vs[3]]}, stereo); } }
public class class_name { private IStereoElement newTetrahedral(int u, int[] vs, IAtom[] atoms, Configuration c) { // no way to handle tetrahedral configurations with implicit // hydrogen or lone pair at the moment if (vs.length != 4) { // sanity check if (vs.length != 3) return null; // there is an implicit hydrogen (or lone-pair) we insert the // central atom in sorted position vs = insert(u, vs); // depends on control dependency: [if], data = [none] } // @TH1/@TH2 = anti-clockwise and clockwise respectively Stereo stereo = c == Configuration.TH1 ? Stereo.ANTI_CLOCKWISE : Stereo.CLOCKWISE; return new TetrahedralChirality(atoms[u], new IAtom[]{atoms[vs[0]], atoms[vs[1]], atoms[vs[2]], atoms[vs[3]]}, stereo); } }
public class class_name { private static StringBuilder append(Object key, Object value, StringBuilder queryString, String ampersand) { if (queryString.length() > 0) { queryString.append(ampersand); } // Use encodeURL from Struts' RequestUtils class - it's JDK 1.3 and 1.4 // compliant queryString.append(encodeURL(key.toString())); queryString.append("="); queryString.append(encodeURL(value.toString())); return queryString; } }
public class class_name { private static StringBuilder append(Object key, Object value, StringBuilder queryString, String ampersand) { if (queryString.length() > 0) { queryString.append(ampersand); // depends on control dependency: [if], data = [none] } // Use encodeURL from Struts' RequestUtils class - it's JDK 1.3 and 1.4 // compliant queryString.append(encodeURL(key.toString())); queryString.append("="); queryString.append(encodeURL(value.toString())); return queryString; } }
public class class_name { public EnableEnhancedMonitoringResult withDesiredShardLevelMetrics(String... desiredShardLevelMetrics) { if (this.desiredShardLevelMetrics == null) { setDesiredShardLevelMetrics(new com.amazonaws.internal.SdkInternalList<String>(desiredShardLevelMetrics.length)); } for (String ele : desiredShardLevelMetrics) { this.desiredShardLevelMetrics.add(ele); } return this; } }
public class class_name { public EnableEnhancedMonitoringResult withDesiredShardLevelMetrics(String... desiredShardLevelMetrics) { if (this.desiredShardLevelMetrics == null) { setDesiredShardLevelMetrics(new com.amazonaws.internal.SdkInternalList<String>(desiredShardLevelMetrics.length)); // depends on control dependency: [if], data = [none] } for (String ele : desiredShardLevelMetrics) { this.desiredShardLevelMetrics.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { double error(int[] x, int[] y) { int e = 0; for (int i = 0; i < x.length; i++) { if (x[i] != y[i]) { e++; } } return (double) e / x.length; } }
public class class_name { double error(int[] x, int[] y) { int e = 0; for (int i = 0; i < x.length; i++) { if (x[i] != y[i]) { e++; // depends on control dependency: [if], data = [none] } } return (double) e / x.length; } }
public class class_name { public static CounterMap parseCounters(byte[] prefix, Map<byte[], byte[]> keyValues) { CounterMap counterValues = new CounterMap(); byte[] counterPrefix = Bytes.add(prefix, Constants.SEP_BYTES); for (Map.Entry<byte[], byte[]> entry : keyValues.entrySet()) { byte[] key = entry.getKey(); if (Bytes.startsWith(key, counterPrefix) && key.length > counterPrefix.length) { // qualifier should be in the format: g!countergroup!counterkey byte[][] qualifierFields = ByteUtil.split(Bytes.tail(key, key.length - counterPrefix.length), Constants.SEP_BYTES); if (qualifierFields.length != 2) { throw new IllegalArgumentException( "Malformed column qualifier for counter value: " + Bytes.toStringBinary(key)); } Counter c = new Counter(Bytes.toString(qualifierFields[0]), Bytes.toString(qualifierFields[1]), Bytes.toLong(entry.getValue())); counterValues.add(c); } } return counterValues; } }
public class class_name { public static CounterMap parseCounters(byte[] prefix, Map<byte[], byte[]> keyValues) { CounterMap counterValues = new CounterMap(); byte[] counterPrefix = Bytes.add(prefix, Constants.SEP_BYTES); for (Map.Entry<byte[], byte[]> entry : keyValues.entrySet()) { byte[] key = entry.getKey(); if (Bytes.startsWith(key, counterPrefix) && key.length > counterPrefix.length) { // qualifier should be in the format: g!countergroup!counterkey byte[][] qualifierFields = ByteUtil.split(Bytes.tail(key, key.length - counterPrefix.length), Constants.SEP_BYTES); if (qualifierFields.length != 2) { throw new IllegalArgumentException( "Malformed column qualifier for counter value: " + Bytes.toStringBinary(key)); } Counter c = new Counter(Bytes.toString(qualifierFields[0]), Bytes.toString(qualifierFields[1]), Bytes.toLong(entry.getValue())); counterValues.add(c); // depends on control dependency: [if], data = [none] } } return counterValues; } }
public class class_name { public Long peek() throws InterruptedException { lock.lockInterruptibly(); try { while (queue.size() == 0) { notEmpty.await(); } return queue.peek(); } finally { lock.unlock(); } } }
public class class_name { public Long peek() throws InterruptedException { lock.lockInterruptibly(); try { while (queue.size() == 0) { notEmpty.await(); // depends on control dependency: [while], data = [none] } return queue.peek(); } finally { lock.unlock(); } } }
public class class_name { private CoverageDataTileMatrixResults getResults(CoverageDataRequest request, BoundingBox requestProjectedBoundingBox, int overlappingPixels) { // Try to get the coverage data from the current zoom level TileMatrix tileMatrix = getTileMatrix(request); CoverageDataTileMatrixResults results = null; if (tileMatrix != null) { results = getResults(requestProjectedBoundingBox, tileMatrix, overlappingPixels); // Try to zoom in or out to find a matching coverage data if (results == null) { results = getResultsZoom(requestProjectedBoundingBox, tileMatrix, overlappingPixels); } } return results; } }
public class class_name { private CoverageDataTileMatrixResults getResults(CoverageDataRequest request, BoundingBox requestProjectedBoundingBox, int overlappingPixels) { // Try to get the coverage data from the current zoom level TileMatrix tileMatrix = getTileMatrix(request); CoverageDataTileMatrixResults results = null; if (tileMatrix != null) { results = getResults(requestProjectedBoundingBox, tileMatrix, overlappingPixels); // depends on control dependency: [if], data = [none] // Try to zoom in or out to find a matching coverage data if (results == null) { results = getResultsZoom(requestProjectedBoundingBox, tileMatrix, overlappingPixels); // depends on control dependency: [if], data = [none] } } return results; } }
public class class_name { public void pathCompleted (long timestamp) { Path oldpath = _path; _path = null; oldpath.wasRemoved(this); if (_observers != null) { _observers.apply(new CompletedOp(this, oldpath, timestamp)); } } }
public class class_name { public void pathCompleted (long timestamp) { Path oldpath = _path; _path = null; oldpath.wasRemoved(this); if (_observers != null) { _observers.apply(new CompletedOp(this, oldpath, timestamp)); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static DistributedSchedulingLock getDistributedScheduleByType(EntityManager em, long type) { requireArgument(em != null, "Entity manager can not be null."); TypedQuery<DistributedSchedulingLock> query = em.createNamedQuery("DistributedSchedulingLock.GetEntryById", DistributedSchedulingLock.class); query.setHint(QueryHints.REFRESH, HintValues.TRUE); try { query.setParameter("type", type); return query.getSingleResult(); } catch (NoResultException ex) { return null; } } }
public class class_name { public static DistributedSchedulingLock getDistributedScheduleByType(EntityManager em, long type) { requireArgument(em != null, "Entity manager can not be null."); TypedQuery<DistributedSchedulingLock> query = em.createNamedQuery("DistributedSchedulingLock.GetEntryById", DistributedSchedulingLock.class); query.setHint(QueryHints.REFRESH, HintValues.TRUE); try { query.setParameter("type", type); // depends on control dependency: [try], data = [none] return query.getSingleResult(); // depends on control dependency: [try], data = [none] } catch (NoResultException ex) { return null; } // depends on control dependency: [catch], data = [none] } }
public class class_name { private Tuple toTuple( List<VarDef> combinedVars, TupleRef tupleRef) { if( tupleRef.size() != getTupleSize()) { throw new IllegalStateException( String.valueOf( tupleRef) + " does not match combiner tuple size=" + getTupleSize()); } Tuple tuple = new Tuple(); for( Iterator<VarBinding> bindings = tupleRef.getVarBindings(); bindings.hasNext(); ) { VarBinding binding = bindings.next(); VarDef var = findVarPath( combinedVars, binding.getVar()); if( var == null) { throw new IllegalStateException( "Var=" + binding.getVar() + " is not included in this combination"); } VarValueDef value = var.getValue( binding.getValue()); if( value == null) { throw new IllegalStateException( "Value=" + binding.getValue() + " is not defined for var=" + binding.getVar()); } if( !value.isValid()) { throw new IllegalStateException( "Value=" + binding.getValue() + " is a failure value for var=" + binding.getVar()); } tuple.add( new VarBindingDef( var, value)); } return tuple; } }
public class class_name { private Tuple toTuple( List<VarDef> combinedVars, TupleRef tupleRef) { if( tupleRef.size() != getTupleSize()) { throw new IllegalStateException( String.valueOf( tupleRef) + " does not match combiner tuple size=" + getTupleSize()); } Tuple tuple = new Tuple(); for( Iterator<VarBinding> bindings = tupleRef.getVarBindings(); bindings.hasNext(); ) { VarBinding binding = bindings.next(); VarDef var = findVarPath( combinedVars, binding.getVar()); if( var == null) { throw new IllegalStateException( "Var=" + binding.getVar() + " is not included in this combination"); } VarValueDef value = var.getValue( binding.getValue()); if( value == null) { throw new IllegalStateException( "Value=" + binding.getValue() + " is not defined for var=" + binding.getVar()); } if( !value.isValid()) { throw new IllegalStateException( "Value=" + binding.getValue() + " is a failure value for var=" + binding.getVar()); } tuple.add( new VarBindingDef( var, value)); // depends on control dependency: [for], data = [none] } return tuple; } }
public class class_name { public DirContext getInnermostDelegateDirContext() { final DirContext delegateDirContext = this.getDelegateDirContext(); if (delegateDirContext instanceof DelegatingDirContext) { return ((DelegatingDirContext)delegateDirContext).getInnermostDelegateDirContext(); } return delegateDirContext; } }
public class class_name { public DirContext getInnermostDelegateDirContext() { final DirContext delegateDirContext = this.getDelegateDirContext(); if (delegateDirContext instanceof DelegatingDirContext) { return ((DelegatingDirContext)delegateDirContext).getInnermostDelegateDirContext(); // depends on control dependency: [if], data = [none] } return delegateDirContext; } }
public class class_name { public static <P extends ParaObject> List<P> readPageFromSharedTable(String appid, Pager pager) { LinkedList<P> results = new LinkedList<>(); if (StringUtils.isBlank(appid)) { return results; } PageIterable<Item, QueryOutcome> pages = queryGSI(appid, pager); if (pages != null) { for (Page<Item, QueryOutcome> page : pages) { for (Item item : page) { P obj = ParaObjectUtils.setAnnotatedFields(item.asMap()); if (obj != null) { results.add(obj); } } } } if (!results.isEmpty() && pager != null) { pager.setLastKey(results.peekLast().getId()); } return results; } }
public class class_name { public static <P extends ParaObject> List<P> readPageFromSharedTable(String appid, Pager pager) { LinkedList<P> results = new LinkedList<>(); if (StringUtils.isBlank(appid)) { return results; // depends on control dependency: [if], data = [none] } PageIterable<Item, QueryOutcome> pages = queryGSI(appid, pager); if (pages != null) { for (Page<Item, QueryOutcome> page : pages) { for (Item item : page) { P obj = ParaObjectUtils.setAnnotatedFields(item.asMap()); if (obj != null) { results.add(obj); // depends on control dependency: [if], data = [(obj] } } } } if (!results.isEmpty() && pager != null) { pager.setLastKey(results.peekLast().getId()); // depends on control dependency: [if], data = [none] } return results; } }
public class class_name { public void clearMessagesAtSource(IndoubtAction indoubtAction) throws SIMPControllableNotFoundException, SIMPRuntimeOperationFailedException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "clearMessagesAtSource"); assertValidControllable(); synchronized(_streamSet) { boolean foundUncommittedMsgs = false; //we do not reallocate for an individual InternalOutputStreamSet // Next delete all indoubt messages from the Message store // Unless we have been told to leave them there // Since any reallocated messages have been replace by Silence // in the streams we can assume we want to work on all messages which // remain in the stream if( indoubtAction != IndoubtAction.INDOUBT_LEAVE) { // This is an iterator over all messages in all the source streams // in this streamSet. There may be Uncommitted messages in this list // but getSIMPMessage will return null for these as they don't have a // valid ItemStream id so we won't try to delete them Iterator itr = this.getTransmitMessagesIterator(SIMPConstants.SIMPCONTROL_RETURN_ALL_MESSAGES); TransmitMessage xmitMsg = null; String state=null; while(itr != null && itr.hasNext()) { xmitMsg = (TransmitMessage)itr.next(); state = xmitMsg.getState(); if (state.equals( State.COMMITTING.toString() ) ) { foundUncommittedMsgs = true; } else { try { // We can operate on this message SIMPMessage msg = xmitMsg.getSIMPMessage(); if( msg != null) { //this will also check whether the msg should ber emoved //from the store _ioStreamManager.removeMessage(_streamSet, msg); } } catch (SIResourceException e) { FFDCFilter.processException( e, "com.ibm.ws.sib.processor.runtime.InternalOutputStreamSetControl.clearMessagesAtSource", "1:496:1.30", this); SIMPRuntimeOperationFailedException finalE = new SIMPRuntimeOperationFailedException( nls.getFormattedMessage( "INTERNAL_MESSAGING_ERROR_CWSIP0002", new Object[] {"InternalOutputStreamSetControl.clearMessagesAtSource", "1:504:1.30", e}, null), e); SibTr.exception(tc, finalE); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "clearMessagesAtSource", finalE); throw finalE; } } } } // Now send a Flushed message and remove streamSet from ioStreamManager if( foundUncommittedMsgs == false) { _ioStreamManager.forceFlush(_streamSet.getStreamID()); } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "clearMessagesAtSource"); } }
public class class_name { public void clearMessagesAtSource(IndoubtAction indoubtAction) throws SIMPControllableNotFoundException, SIMPRuntimeOperationFailedException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "clearMessagesAtSource"); assertValidControllable(); synchronized(_streamSet) { boolean foundUncommittedMsgs = false; //we do not reallocate for an individual InternalOutputStreamSet // Next delete all indoubt messages from the Message store // Unless we have been told to leave them there // Since any reallocated messages have been replace by Silence // in the streams we can assume we want to work on all messages which // remain in the stream if( indoubtAction != IndoubtAction.INDOUBT_LEAVE) { // This is an iterator over all messages in all the source streams // in this streamSet. There may be Uncommitted messages in this list // but getSIMPMessage will return null for these as they don't have a // valid ItemStream id so we won't try to delete them Iterator itr = this.getTransmitMessagesIterator(SIMPConstants.SIMPCONTROL_RETURN_ALL_MESSAGES); TransmitMessage xmitMsg = null; String state=null; while(itr != null && itr.hasNext()) { xmitMsg = (TransmitMessage)itr.next(); // depends on control dependency: [while], data = [none] state = xmitMsg.getState(); // depends on control dependency: [while], data = [none] if (state.equals( State.COMMITTING.toString() ) ) { foundUncommittedMsgs = true; // depends on control dependency: [if], data = [none] } else { try { // We can operate on this message SIMPMessage msg = xmitMsg.getSIMPMessage(); if( msg != null) { //this will also check whether the msg should ber emoved //from the store _ioStreamManager.removeMessage(_streamSet, msg); // depends on control dependency: [if], data = [none] } } catch (SIResourceException e) { FFDCFilter.processException( e, "com.ibm.ws.sib.processor.runtime.InternalOutputStreamSetControl.clearMessagesAtSource", "1:496:1.30", this); SIMPRuntimeOperationFailedException finalE = new SIMPRuntimeOperationFailedException( nls.getFormattedMessage( "INTERNAL_MESSAGING_ERROR_CWSIP0002", new Object[] {"InternalOutputStreamSetControl.clearMessagesAtSource", "1:504:1.30", e}, null), e); SibTr.exception(tc, finalE); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "clearMessagesAtSource", finalE); throw finalE; } // depends on control dependency: [catch], data = [none] } } } // Now send a Flushed message and remove streamSet from ioStreamManager if( foundUncommittedMsgs == false) { _ioStreamManager.forceFlush(_streamSet.getStreamID()); // depends on control dependency: [if], data = [none] } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "clearMessagesAtSource"); } }
public class class_name { public void marshall(StopAccessLoggingRequest stopAccessLoggingRequest, ProtocolMarshaller protocolMarshaller) { if (stopAccessLoggingRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(stopAccessLoggingRequest.getContainerName(), CONTAINERNAME_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(StopAccessLoggingRequest stopAccessLoggingRequest, ProtocolMarshaller protocolMarshaller) { if (stopAccessLoggingRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(stopAccessLoggingRequest.getContainerName(), CONTAINERNAME_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 unloadAllModuleRevision(String scriptModuleId) { for (ModuleIdentifier revisionId : getAllRevisionIds(scriptModuleId)) { if (revisionId.getName().equals(scriptModuleId)) { unloadModule(revisionId); } } } }
public class class_name { public void unloadAllModuleRevision(String scriptModuleId) { for (ModuleIdentifier revisionId : getAllRevisionIds(scriptModuleId)) { if (revisionId.getName().equals(scriptModuleId)) { unloadModule(revisionId); // depends on control dependency: [if], data = [none] } } } }
public class class_name { @Override public String compareDatastreamChecksum(String pid, String dsID, String versionDate) { assertInitialized(); try { MessageContext ctx = context.getMessageContext(); return m_management.compareDatastreamChecksum(ReadOnlyContext .getSoapContext(ctx), pid, dsID, DateUtility .parseDateOrNull(versionDate)); } catch (Throwable th) { LOG.error("Error comparing datastream checksum", th); throw CXFUtility.getFault(th); } } }
public class class_name { @Override public String compareDatastreamChecksum(String pid, String dsID, String versionDate) { assertInitialized(); try { MessageContext ctx = context.getMessageContext(); return m_management.compareDatastreamChecksum(ReadOnlyContext .getSoapContext(ctx), pid, dsID, DateUtility .parseDateOrNull(versionDate)); // depends on control dependency: [try], data = [none] } catch (Throwable th) { LOG.error("Error comparing datastream checksum", th); throw CXFUtility.getFault(th); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public JoinableResourceBundle resolveBundleForPath(String path) { JoinableResourceBundle theBundle = null; for (Iterator<JoinableResourceBundle> it = bundles.iterator(); it.hasNext();) { JoinableResourceBundle bundle = it.next(); if (bundle.getId().equals(path) || bundle.belongsToBundle(path)) { theBundle = bundle; break; } } return theBundle; } }
public class class_name { @Override public JoinableResourceBundle resolveBundleForPath(String path) { JoinableResourceBundle theBundle = null; for (Iterator<JoinableResourceBundle> it = bundles.iterator(); it.hasNext();) { JoinableResourceBundle bundle = it.next(); if (bundle.getId().equals(path) || bundle.belongsToBundle(path)) { theBundle = bundle; // depends on control dependency: [if], data = [none] break; } } return theBundle; } }
public class class_name { @Override public void free() { try { if(hasCoreConnection()) { this.getCoreConnection().close(); } this.fireConnectionFreed(); this.boundThreadId= Thread.currentThread().getId(); } finally { this.setClosed(true); // state may be important for State-Listener, so its set after the listener did their work setTransactionalData(false); // re-opem is not possible // this.connection=null; this.releaseThreadBinding(); } } }
public class class_name { @Override public void free() { try { if(hasCoreConnection()) { this.getCoreConnection().close(); // depends on control dependency: [if], data = [none] } this.fireConnectionFreed(); // depends on control dependency: [try], data = [none] this.boundThreadId= Thread.currentThread().getId(); // depends on control dependency: [try], data = [none] } finally { this.setClosed(true); // state may be important for State-Listener, so its set after the listener did their work setTransactionalData(false); // re-opem is not possible // this.connection=null; this.releaseThreadBinding(); } } }
public class class_name { protected void loadWaterMarks() throws IOException { // Load source water marks from file if (file != null && file.exists()) { try { loadWaterMarks(file); } catch (IOException e) { if (fileOriginal != null && fileOriginal.exists()) { loadWaterMarks(fileOriginal); } } } } }
public class class_name { protected void loadWaterMarks() throws IOException { // Load source water marks from file if (file != null && file.exists()) { try { loadWaterMarks(file); // depends on control dependency: [try], data = [none] } catch (IOException e) { if (fileOriginal != null && fileOriginal.exists()) { loadWaterMarks(fileOriginal); // depends on control dependency: [if], data = [(fileOriginal] } } // depends on control dependency: [catch], data = [none] } } }
public class class_name { public final EObject entryRuleSarlXLoopFormalParameter() throws RecognitionException { EObject current = null; EObject iv_ruleSarlXLoopFormalParameter = null; try { // InternalSARL.g:8449:65: (iv_ruleSarlXLoopFormalParameter= ruleSarlXLoopFormalParameter EOF ) // InternalSARL.g:8450:2: iv_ruleSarlXLoopFormalParameter= ruleSarlXLoopFormalParameter EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getSarlXLoopFormalParameterRule()); } pushFollow(FOLLOW_1); iv_ruleSarlXLoopFormalParameter=ruleSarlXLoopFormalParameter(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleSarlXLoopFormalParameter; } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } }
public class class_name { public final EObject entryRuleSarlXLoopFormalParameter() throws RecognitionException { EObject current = null; EObject iv_ruleSarlXLoopFormalParameter = null; try { // InternalSARL.g:8449:65: (iv_ruleSarlXLoopFormalParameter= ruleSarlXLoopFormalParameter EOF ) // InternalSARL.g:8450:2: iv_ruleSarlXLoopFormalParameter= ruleSarlXLoopFormalParameter EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getSarlXLoopFormalParameterRule()); // depends on control dependency: [if], data = [none] } pushFollow(FOLLOW_1); iv_ruleSarlXLoopFormalParameter=ruleSarlXLoopFormalParameter(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleSarlXLoopFormalParameter; // depends on control dependency: [if], data = [none] } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } }
public class class_name { public void marshall(BackupDetails backupDetails, ProtocolMarshaller protocolMarshaller) { if (backupDetails == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(backupDetails.getBackupArn(), BACKUPARN_BINDING); protocolMarshaller.marshall(backupDetails.getBackupName(), BACKUPNAME_BINDING); protocolMarshaller.marshall(backupDetails.getBackupSizeBytes(), BACKUPSIZEBYTES_BINDING); protocolMarshaller.marshall(backupDetails.getBackupStatus(), BACKUPSTATUS_BINDING); protocolMarshaller.marshall(backupDetails.getBackupType(), BACKUPTYPE_BINDING); protocolMarshaller.marshall(backupDetails.getBackupCreationDateTime(), BACKUPCREATIONDATETIME_BINDING); protocolMarshaller.marshall(backupDetails.getBackupExpiryDateTime(), BACKUPEXPIRYDATETIME_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(BackupDetails backupDetails, ProtocolMarshaller protocolMarshaller) { if (backupDetails == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(backupDetails.getBackupArn(), BACKUPARN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(backupDetails.getBackupName(), BACKUPNAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(backupDetails.getBackupSizeBytes(), BACKUPSIZEBYTES_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(backupDetails.getBackupStatus(), BACKUPSTATUS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(backupDetails.getBackupType(), BACKUPTYPE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(backupDetails.getBackupCreationDateTime(), BACKUPCREATIONDATETIME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(backupDetails.getBackupExpiryDateTime(), BACKUPEXPIRYDATETIME_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { protected void updateStyles() { DayEntryView view = getSkinnable(); Entry<?> entry = getEntry(); Calendar calendar = entry.getCalendar(); if (entry instanceof DraggedEntry) { calendar = ((DraggedEntry) entry).getOriginalCalendar(); } // when the entry gets removed from its calendar then the calendar can // be null if (calendar == null) { return; } view.getStyleClass().setAll("default-style-entry", calendar.getStyle() + "-entry"); if (entry.isRecurrence()) { view.getStyleClass().add("recurrence"); //$NON-NLS-1$ } startTimeLabel.getStyleClass().setAll("start-time-label", "default-style-entry-time-label", calendar.getStyle() + "-entry-time-label"); titleLabel.getStyleClass().setAll("title-label", "default-style-entry-title-label", calendar.getStyle() + "-entry-title-label"); } }
public class class_name { protected void updateStyles() { DayEntryView view = getSkinnable(); Entry<?> entry = getEntry(); Calendar calendar = entry.getCalendar(); if (entry instanceof DraggedEntry) { calendar = ((DraggedEntry) entry).getOriginalCalendar(); // depends on control dependency: [if], data = [none] } // when the entry gets removed from its calendar then the calendar can // be null if (calendar == null) { return; // depends on control dependency: [if], data = [none] } view.getStyleClass().setAll("default-style-entry", calendar.getStyle() + "-entry"); if (entry.isRecurrence()) { view.getStyleClass().add("recurrence"); //$NON-NLS-1$ // depends on control dependency: [if], data = [none] } startTimeLabel.getStyleClass().setAll("start-time-label", "default-style-entry-time-label", calendar.getStyle() + "-entry-time-label"); titleLabel.getStyleClass().setAll("title-label", "default-style-entry-title-label", calendar.getStyle() + "-entry-title-label"); } }
public class class_name { public void marshall(ItemResponse itemResponse, ProtocolMarshaller protocolMarshaller) { if (itemResponse == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(itemResponse.getEndpointItemResponse(), ENDPOINTITEMRESPONSE_BINDING); protocolMarshaller.marshall(itemResponse.getEventsItemResponse(), EVENTSITEMRESPONSE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(ItemResponse itemResponse, ProtocolMarshaller protocolMarshaller) { if (itemResponse == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(itemResponse.getEndpointItemResponse(), ENDPOINTITEMRESPONSE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(itemResponse.getEventsItemResponse(), EVENTSITEMRESPONSE_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public byte[] toBytes(Object object) { if (object == null) { return null; } BigDecimal b = (BigDecimal) object; final int scale = b.scale(); final BigInteger unscaled = b.unscaledValue(); final byte[] value = unscaled.toByteArray(); final byte[] bytes = new byte[value.length + 4]; bytes[0] = (byte) (scale >>> 24); bytes[1] = (byte) (scale >>> 16); bytes[2] = (byte) (scale >>> 8); bytes[3] = (byte) (scale >>> 0); System.arraycopy(value, 0, bytes, 4, value.length); return bytes; } }
public class class_name { @Override public byte[] toBytes(Object object) { if (object == null) { return null; // depends on control dependency: [if], data = [none] } BigDecimal b = (BigDecimal) object; final int scale = b.scale(); final BigInteger unscaled = b.unscaledValue(); final byte[] value = unscaled.toByteArray(); final byte[] bytes = new byte[value.length + 4]; bytes[0] = (byte) (scale >>> 24); bytes[1] = (byte) (scale >>> 16); bytes[2] = (byte) (scale >>> 8); bytes[3] = (byte) (scale >>> 0); System.arraycopy(value, 0, bytes, 4, value.length); return bytes; } }
public class class_name { protected void validateGroupClause(SqlSelect select) { SqlNodeList groupList = select.getGroup(); if (groupList == null) { return; } final String clause = "GROUP BY"; validateNoAggs(aggOrOverFinder, groupList, clause); final SqlValidatorScope groupScope = getGroupScope(select); inferUnknownTypes(unknownType, groupScope, groupList); // expand the expression in group list. List<SqlNode> expandedList = new ArrayList<>(); for (SqlNode groupItem : groupList) { SqlNode expandedItem = expandGroupByOrHavingExpr(groupItem, groupScope, select, false); expandedList.add(expandedItem); } groupList = new SqlNodeList(expandedList, groupList.getParserPosition()); select.setGroupBy(groupList); for (SqlNode groupItem : expandedList) { validateGroupByItem(select, groupItem); } // Nodes in the GROUP BY clause are expressions except if they are calls // to the GROUPING SETS, ROLLUP or CUBE operators; this operators are not // expressions, because they do not have a type. for (SqlNode node : groupList) { switch (node.getKind()) { case GROUPING_SETS: case ROLLUP: case CUBE: node.validate(this, groupScope); break; default: node.validateExpr(this, groupScope); } } // Derive the type of each GROUP BY item. We don't need the type, but // it resolves functions, and that is necessary for deducing // monotonicity. final SqlValidatorScope selectScope = getSelectScope(select); AggregatingSelectScope aggregatingScope = null; if (selectScope instanceof AggregatingSelectScope) { aggregatingScope = (AggregatingSelectScope) selectScope; } for (SqlNode groupItem : groupList) { if (groupItem instanceof SqlNodeList && ((SqlNodeList) groupItem).size() == 0) { continue; } validateGroupItem(groupScope, aggregatingScope, groupItem); } SqlNode agg = aggFinder.findAgg(groupList); if (agg != null) { throw newValidationError(agg, RESOURCE.aggregateIllegalInClause(clause)); } } }
public class class_name { protected void validateGroupClause(SqlSelect select) { SqlNodeList groupList = select.getGroup(); if (groupList == null) { return; // depends on control dependency: [if], data = [none] } final String clause = "GROUP BY"; validateNoAggs(aggOrOverFinder, groupList, clause); final SqlValidatorScope groupScope = getGroupScope(select); inferUnknownTypes(unknownType, groupScope, groupList); // expand the expression in group list. List<SqlNode> expandedList = new ArrayList<>(); for (SqlNode groupItem : groupList) { SqlNode expandedItem = expandGroupByOrHavingExpr(groupItem, groupScope, select, false); expandedList.add(expandedItem); // depends on control dependency: [for], data = [none] } groupList = new SqlNodeList(expandedList, groupList.getParserPosition()); select.setGroupBy(groupList); for (SqlNode groupItem : expandedList) { validateGroupByItem(select, groupItem); // depends on control dependency: [for], data = [groupItem] } // Nodes in the GROUP BY clause are expressions except if they are calls // to the GROUPING SETS, ROLLUP or CUBE operators; this operators are not // expressions, because they do not have a type. for (SqlNode node : groupList) { switch (node.getKind()) { case GROUPING_SETS: case ROLLUP: case CUBE: node.validate(this, groupScope); break; default: node.validateExpr(this, groupScope); } } // Derive the type of each GROUP BY item. We don't need the type, but // it resolves functions, and that is necessary for deducing // monotonicity. final SqlValidatorScope selectScope = getSelectScope(select); AggregatingSelectScope aggregatingScope = null; if (selectScope instanceof AggregatingSelectScope) { aggregatingScope = (AggregatingSelectScope) selectScope; // depends on control dependency: [if], data = [none] } for (SqlNode groupItem : groupList) { if (groupItem instanceof SqlNodeList && ((SqlNodeList) groupItem).size() == 0) { continue; } validateGroupItem(groupScope, aggregatingScope, groupItem); // depends on control dependency: [for], data = [groupItem] } SqlNode agg = aggFinder.findAgg(groupList); if (agg != null) { throw newValidationError(agg, RESOURCE.aggregateIllegalInClause(clause)); } } }
public class class_name { public static File zip(File zipFile, Charset charset, boolean withSrcDir, File... srcFiles) throws UtilException { validateFiles(zipFile, srcFiles); try (ZipOutputStream out = getZipOutputStream(zipFile, charset)) { String srcRootDir; for (File srcFile : srcFiles) { if(null == srcFile) { continue; } // 如果只是压缩一个文件,则需要截取该文件的父目录 srcRootDir = srcFile.getCanonicalPath(); if (srcFile.isFile() || withSrcDir) { //若是文件,则将父目录完整路径都截取掉;若设置包含目录,则将上级目录全部截取掉,保留本目录名 srcRootDir = srcFile.getCanonicalFile().getParentFile().getCanonicalPath(); } // 调用递归压缩方法进行目录或文件压缩 zip(srcFile, srcRootDir, out); out.flush(); } } catch (IOException e) { throw new UtilException(e); } return zipFile; } }
public class class_name { public static File zip(File zipFile, Charset charset, boolean withSrcDir, File... srcFiles) throws UtilException { validateFiles(zipFile, srcFiles); try (ZipOutputStream out = getZipOutputStream(zipFile, charset)) { String srcRootDir; for (File srcFile : srcFiles) { if(null == srcFile) { continue; } // 如果只是压缩一个文件,则需要截取该文件的父目录 srcRootDir = srcFile.getCanonicalPath(); // depends on control dependency: [for], data = [srcFile] if (srcFile.isFile() || withSrcDir) { //若是文件,则将父目录完整路径都截取掉;若设置包含目录,则将上级目录全部截取掉,保留本目录名 srcRootDir = srcFile.getCanonicalFile().getParentFile().getCanonicalPath(); // depends on control dependency: [if], data = [none] } // 调用递归压缩方法进行目录或文件压缩 zip(srcFile, srcRootDir, out); // depends on control dependency: [for], data = [srcFile] out.flush(); // depends on control dependency: [for], data = [none] } } catch (IOException e) { throw new UtilException(e); } return zipFile; } }
public class class_name { public Result<FindPolysAroundResult> findPolysAroundCircle(long startRef, float[] centerPos, float radius, QueryFilter filter) { // Validate input if (!m_nav.isValidPolyRef(startRef) || Objects.isNull(centerPos) || !vIsFinite(centerPos) || radius < 0 || !Float.isFinite(radius) || Objects.isNull(filter)) { return Result.invalidParam(); } List<Long> resultRef = new ArrayList<>(); List<Long> resultParent = new ArrayList<>(); List<Float> resultCost = new ArrayList<>(); m_nodePool.clear(); m_openList.clear(); Node startNode = m_nodePool.getNode(startRef); vCopy(startNode.pos, centerPos); startNode.pidx = 0; startNode.cost = 0; startNode.total = 0; startNode.id = startRef; startNode.flags = Node.DT_NODE_OPEN; m_openList.push(startNode); float radiusSqr = sqr(radius); while (!m_openList.isEmpty()) { Node bestNode = m_openList.pop(); bestNode.flags &= ~Node.DT_NODE_OPEN; bestNode.flags |= Node.DT_NODE_CLOSED; // Get poly and tile. // The API input has been cheked already, skip checking internal data. long bestRef = bestNode.id; Tupple2<MeshTile, Poly> tileAndPoly = m_nav.getTileAndPolyByRefUnsafe(bestRef); MeshTile bestTile = tileAndPoly.first; Poly bestPoly = tileAndPoly.second; // Get parent poly and tile. long parentRef = 0; MeshTile parentTile = null; Poly parentPoly = null; if (bestNode.pidx != 0) { parentRef = m_nodePool.getNodeAtIdx(bestNode.pidx).id; } if (parentRef != 0) { tileAndPoly = m_nav.getTileAndPolyByRefUnsafe(parentRef); parentTile = tileAndPoly.first; parentPoly = tileAndPoly.second; } resultRef.add(bestRef); resultParent.add(parentRef); resultCost.add(bestNode.total); for (int i = bestPoly.firstLink; i != NavMesh.DT_NULL_LINK; i = bestTile.links.get(i).next) { Link link = bestTile.links.get(i); long neighbourRef = link.ref; // Skip invalid neighbours and do not follow back to parent. if (neighbourRef == 0 || neighbourRef == parentRef) { continue; } // Expand to neighbour tileAndPoly = m_nav.getTileAndPolyByRefUnsafe(neighbourRef); MeshTile neighbourTile = tileAndPoly.first; Poly neighbourPoly = tileAndPoly.second; // Do not advance if the polygon is excluded by the filter. if (!filter.passFilter(neighbourRef, neighbourTile, neighbourPoly)) { continue; } // Find edge and calc distance to the edge. Result<PortalResult> pp = getPortalPoints(bestRef, bestPoly, bestTile, neighbourRef, neighbourPoly, neighbourTile, 0, 0); if (pp.failed()) { continue; } float[] va = pp.result.left; float[] vb = pp.result.right; // If the circle is not touching the next polygon, skip it. Tupple2<Float, Float> distseg = distancePtSegSqr2D(centerPos, va, vb); float distSqr = distseg.first; if (distSqr > radiusSqr) { continue; } Node neighbourNode = m_nodePool.getNode(neighbourRef); if ((neighbourNode.flags & Node.DT_NODE_CLOSED) != 0) { continue; } // Cost if (neighbourNode.flags == 0) { neighbourNode.pos = vLerp(va, vb, 0.5f); } float cost = filter.getCost(bestNode.pos, neighbourNode.pos, parentRef, parentTile, parentPoly, bestRef, bestTile, bestPoly, neighbourRef, neighbourTile, neighbourPoly); float total = bestNode.total + cost; // The node is already in open list and the new result is worse, skip. if ((neighbourNode.flags & Node.DT_NODE_OPEN) != 0 && total >= neighbourNode.total) { continue; } neighbourNode.id = neighbourRef; neighbourNode.pidx = m_nodePool.getNodeIdx(bestNode); neighbourNode.total = total; if ((neighbourNode.flags & Node.DT_NODE_OPEN) != 0) { m_openList.modify(neighbourNode); } else { neighbourNode.flags = Node.DT_NODE_OPEN; m_openList.push(neighbourNode); } } } return Result.success(new FindPolysAroundResult(resultRef, resultParent, resultCost)); } }
public class class_name { public Result<FindPolysAroundResult> findPolysAroundCircle(long startRef, float[] centerPos, float radius, QueryFilter filter) { // Validate input if (!m_nav.isValidPolyRef(startRef) || Objects.isNull(centerPos) || !vIsFinite(centerPos) || radius < 0 || !Float.isFinite(radius) || Objects.isNull(filter)) { return Result.invalidParam(); // depends on control dependency: [if], data = [none] } List<Long> resultRef = new ArrayList<>(); List<Long> resultParent = new ArrayList<>(); List<Float> resultCost = new ArrayList<>(); m_nodePool.clear(); m_openList.clear(); Node startNode = m_nodePool.getNode(startRef); vCopy(startNode.pos, centerPos); startNode.pidx = 0; startNode.cost = 0; startNode.total = 0; startNode.id = startRef; startNode.flags = Node.DT_NODE_OPEN; m_openList.push(startNode); float radiusSqr = sqr(radius); while (!m_openList.isEmpty()) { Node bestNode = m_openList.pop(); bestNode.flags &= ~Node.DT_NODE_OPEN; // depends on control dependency: [while], data = [none] bestNode.flags |= Node.DT_NODE_CLOSED; // depends on control dependency: [while], data = [none] // Get poly and tile. // The API input has been cheked already, skip checking internal data. long bestRef = bestNode.id; Tupple2<MeshTile, Poly> tileAndPoly = m_nav.getTileAndPolyByRefUnsafe(bestRef); MeshTile bestTile = tileAndPoly.first; Poly bestPoly = tileAndPoly.second; // Get parent poly and tile. long parentRef = 0; MeshTile parentTile = null; Poly parentPoly = null; if (bestNode.pidx != 0) { parentRef = m_nodePool.getNodeAtIdx(bestNode.pidx).id; // depends on control dependency: [if], data = [(bestNode.pidx] } if (parentRef != 0) { tileAndPoly = m_nav.getTileAndPolyByRefUnsafe(parentRef); // depends on control dependency: [if], data = [(parentRef] parentTile = tileAndPoly.first; // depends on control dependency: [if], data = [none] parentPoly = tileAndPoly.second; // depends on control dependency: [if], data = [none] } resultRef.add(bestRef); // depends on control dependency: [while], data = [none] resultParent.add(parentRef); // depends on control dependency: [while], data = [none] resultCost.add(bestNode.total); // depends on control dependency: [while], data = [none] for (int i = bestPoly.firstLink; i != NavMesh.DT_NULL_LINK; i = bestTile.links.get(i).next) { Link link = bestTile.links.get(i); long neighbourRef = link.ref; // Skip invalid neighbours and do not follow back to parent. if (neighbourRef == 0 || neighbourRef == parentRef) { continue; } // Expand to neighbour tileAndPoly = m_nav.getTileAndPolyByRefUnsafe(neighbourRef); // depends on control dependency: [for], data = [none] MeshTile neighbourTile = tileAndPoly.first; Poly neighbourPoly = tileAndPoly.second; // Do not advance if the polygon is excluded by the filter. if (!filter.passFilter(neighbourRef, neighbourTile, neighbourPoly)) { continue; } // Find edge and calc distance to the edge. Result<PortalResult> pp = getPortalPoints(bestRef, bestPoly, bestTile, neighbourRef, neighbourPoly, neighbourTile, 0, 0); if (pp.failed()) { continue; } float[] va = pp.result.left; float[] vb = pp.result.right; // If the circle is not touching the next polygon, skip it. Tupple2<Float, Float> distseg = distancePtSegSqr2D(centerPos, va, vb); float distSqr = distseg.first; if (distSqr > radiusSqr) { continue; } Node neighbourNode = m_nodePool.getNode(neighbourRef); if ((neighbourNode.flags & Node.DT_NODE_CLOSED) != 0) { continue; } // Cost if (neighbourNode.flags == 0) { neighbourNode.pos = vLerp(va, vb, 0.5f); // depends on control dependency: [if], data = [none] } float cost = filter.getCost(bestNode.pos, neighbourNode.pos, parentRef, parentTile, parentPoly, bestRef, bestTile, bestPoly, neighbourRef, neighbourTile, neighbourPoly); float total = bestNode.total + cost; // The node is already in open list and the new result is worse, skip. if ((neighbourNode.flags & Node.DT_NODE_OPEN) != 0 && total >= neighbourNode.total) { continue; } neighbourNode.id = neighbourRef; // depends on control dependency: [for], data = [none] neighbourNode.pidx = m_nodePool.getNodeIdx(bestNode); // depends on control dependency: [for], data = [none] neighbourNode.total = total; // depends on control dependency: [for], data = [none] if ((neighbourNode.flags & Node.DT_NODE_OPEN) != 0) { m_openList.modify(neighbourNode); // depends on control dependency: [if], data = [none] } else { neighbourNode.flags = Node.DT_NODE_OPEN; // depends on control dependency: [if], data = [none] m_openList.push(neighbourNode); // depends on control dependency: [if], data = [none] } } } return Result.success(new FindPolysAroundResult(resultRef, resultParent, resultCost)); } }
public class class_name { @Override public final void setTimeToLive(long value) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setTimeToLive", Long.valueOf(value)); if ((value >= MfpConstants.MIN_TIME_TO_LIVE) && (value <= MfpConstants.MAX_TIME_TO_LIVE)) { super.setTimeToLive(value); } else { IllegalArgumentException e = new IllegalArgumentException(Long.toString(value)); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "setTimeToLive", e); throw e; } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "setTimeToLive"); } }
public class class_name { @Override public final void setTimeToLive(long value) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setTimeToLive", Long.valueOf(value)); if ((value >= MfpConstants.MIN_TIME_TO_LIVE) && (value <= MfpConstants.MAX_TIME_TO_LIVE)) { super.setTimeToLive(value); // depends on control dependency: [if], data = [none] } else { IllegalArgumentException e = new IllegalArgumentException(Long.toString(value)); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "setTimeToLive", e); throw e; } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "setTimeToLive"); } }
public class class_name { @Action(name = "PowerShell Script Action", outputs = { @Output(RETURN_CODE), @Output(RETURN_RESULT), @Output(STDERR), @Output(SCRIPT_EXIT_CODE), @Output(EXCEPTION) }, responses = { @Response(text = Constants.ResponseNames.SUCCESS, field = RETURN_CODE, value = RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED), @Response(text = Constants.ResponseNames.FAILURE, field = RETURN_CODE, value = RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true) } ) public Map<String, String> execute( @Param(value = INPUT_HOST, required = true) String host, @Param(value = INPUT_PORT) String port, @Param(value = PROTOCOL) String protocol, @Param(value = USERNAME) String username, @Param(value = PASSWORD, encrypted = true) String password, @Param(value = AUTH_TYPE) String authType, @Param(value = PROXY_HOST) String proxyHost, @Param(value = PROXY_PORT) String proxyPort, @Param(value = PROXY_USERNAME) String proxyUsername, @Param(value = PROXY_PASSWORD, encrypted = true) String proxyPassword, @Param(value = TRUST_ALL_ROOTS) String trustAllRoots, @Param(value = X509_HOSTNAME_VERIFIER) String x509HostnameVerifier, @Param(value = TRUST_KEYSTORE) String trustKeystore, @Param(value = TRUST_PASSWORD, encrypted = true) String trustPassword, @Param(value = KERBEROS_CONFIG_FILE) String kerberosConfFile, @Param(value = KERBEROS_LOGIN_CONFIG_FILE) String kerberosLoginConfFile, @Param(value = KERBEROS_SKIP_PORT_CHECK) String kerberosSkipPortForLookup, @Param(value = KEYSTORE) String keystore, @Param(value = KEYSTORE_PASSWORD, encrypted = true) String keystorePassword, @Param(value = MAX_ENVELOP_SIZE) String maxEnvelopeSize, @Param(value = INPUT_SCRIPT, required = true) String script, @Param(value = MODULES) String modules, @Param(value = WINRM_LOCALE) String winrmLocale, @Param(value = OPERATION_TIMEOUT) String operationTimeout ) { try { WSManRemoteShellService wsManRemoteShellService = new WSManRemoteShellService(); WSManRequestInputs wsManRequestInputs = new WSManRequestInputs.WSManRequestInputsBuilder() .withHost(host) .withPort(port) .withProtocol(protocol) .withUsername(username) .withPassword(password) .withAuthType(authType) .withKerberosConfFile(kerberosConfFile) .withKerberosLoginConfFile(kerberosLoginConfFile) .withKerberosSkipPortForLookup(kerberosSkipPortForLookup) .withProxyHost(proxyHost) .withProxyPort(proxyPort) .withProxyUsername(proxyUsername) .withProxyPassword(proxyPassword) .withMaxEnvelopeSize(maxEnvelopeSize) .withTrustAllRoots(trustAllRoots) .withX509HostnameVerifier(x509HostnameVerifier) .withKeystore(defaultIfEmpty(keystore, DEFAULT_JAVA_KEYSTORE)) .withKeystorePassword(defaultIfEmpty(keystorePassword, CHANGEIT)) .withTrustKeystore(defaultIfEmpty(trustKeystore, DEFAULT_JAVA_KEYSTORE)) .withTrustPassword(defaultIfEmpty(trustPassword, CHANGEIT)) .withScript(script) .withModules(modules) .withWinrmLocale(winrmLocale) .withOperationTimeout(operationTimeout) .build(); Map<String, String> resultMap = wsManRemoteShellService.runCommand(wsManRequestInputs); verifyScriptExecutionStatus(resultMap); return resultMap; } catch (Exception e) { return getFailureResultsMap(e); } } }
public class class_name { @Action(name = "PowerShell Script Action", outputs = { @Output(RETURN_CODE), @Output(RETURN_RESULT), @Output(STDERR), @Output(SCRIPT_EXIT_CODE), @Output(EXCEPTION) }, responses = { @Response(text = Constants.ResponseNames.SUCCESS, field = RETURN_CODE, value = RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED), @Response(text = Constants.ResponseNames.FAILURE, field = RETURN_CODE, value = RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true) } ) public Map<String, String> execute( @Param(value = INPUT_HOST, required = true) String host, @Param(value = INPUT_PORT) String port, @Param(value = PROTOCOL) String protocol, @Param(value = USERNAME) String username, @Param(value = PASSWORD, encrypted = true) String password, @Param(value = AUTH_TYPE) String authType, @Param(value = PROXY_HOST) String proxyHost, @Param(value = PROXY_PORT) String proxyPort, @Param(value = PROXY_USERNAME) String proxyUsername, @Param(value = PROXY_PASSWORD, encrypted = true) String proxyPassword, @Param(value = TRUST_ALL_ROOTS) String trustAllRoots, @Param(value = X509_HOSTNAME_VERIFIER) String x509HostnameVerifier, @Param(value = TRUST_KEYSTORE) String trustKeystore, @Param(value = TRUST_PASSWORD, encrypted = true) String trustPassword, @Param(value = KERBEROS_CONFIG_FILE) String kerberosConfFile, @Param(value = KERBEROS_LOGIN_CONFIG_FILE) String kerberosLoginConfFile, @Param(value = KERBEROS_SKIP_PORT_CHECK) String kerberosSkipPortForLookup, @Param(value = KEYSTORE) String keystore, @Param(value = KEYSTORE_PASSWORD, encrypted = true) String keystorePassword, @Param(value = MAX_ENVELOP_SIZE) String maxEnvelopeSize, @Param(value = INPUT_SCRIPT, required = true) String script, @Param(value = MODULES) String modules, @Param(value = WINRM_LOCALE) String winrmLocale, @Param(value = OPERATION_TIMEOUT) String operationTimeout ) { try { WSManRemoteShellService wsManRemoteShellService = new WSManRemoteShellService(); WSManRequestInputs wsManRequestInputs = new WSManRequestInputs.WSManRequestInputsBuilder() .withHost(host) .withPort(port) .withProtocol(protocol) .withUsername(username) .withPassword(password) .withAuthType(authType) .withKerberosConfFile(kerberosConfFile) .withKerberosLoginConfFile(kerberosLoginConfFile) .withKerberosSkipPortForLookup(kerberosSkipPortForLookup) .withProxyHost(proxyHost) .withProxyPort(proxyPort) .withProxyUsername(proxyUsername) .withProxyPassword(proxyPassword) .withMaxEnvelopeSize(maxEnvelopeSize) .withTrustAllRoots(trustAllRoots) .withX509HostnameVerifier(x509HostnameVerifier) .withKeystore(defaultIfEmpty(keystore, DEFAULT_JAVA_KEYSTORE)) .withKeystorePassword(defaultIfEmpty(keystorePassword, CHANGEIT)) .withTrustKeystore(defaultIfEmpty(trustKeystore, DEFAULT_JAVA_KEYSTORE)) .withTrustPassword(defaultIfEmpty(trustPassword, CHANGEIT)) .withScript(script) .withModules(modules) .withWinrmLocale(winrmLocale) .withOperationTimeout(operationTimeout) .build(); Map<String, String> resultMap = wsManRemoteShellService.runCommand(wsManRequestInputs); verifyScriptExecutionStatus(resultMap); // depends on control dependency: [try], data = [none] return resultMap; // depends on control dependency: [try], data = [none] } catch (Exception e) { return getFailureResultsMap(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public Control getControlInstance(Control ctl) { if (ctl.getID().equals(PasswordPolicyControl.OID)) { return new PasswordPolicyResponseControl(ctl.getEncodedValue()); } return null; } }
public class class_name { public Control getControlInstance(Control ctl) { if (ctl.getID().equals(PasswordPolicyControl.OID)) { return new PasswordPolicyResponseControl(ctl.getEncodedValue()); // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { public static Method getMethod(Class<?> type, String methodName, Class<?>... parameterTypes) { try { return type.getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException cause) { if (type.getSuperclass() != null) { return getMethod(type.getSuperclass(), methodName, parameterTypes); } throw new MethodNotFoundException(cause); } } }
public class class_name { public static Method getMethod(Class<?> type, String methodName, Class<?>... parameterTypes) { try { return type.getDeclaredMethod(methodName, parameterTypes); // depends on control dependency: [try], data = [none] } catch (NoSuchMethodException cause) { if (type.getSuperclass() != null) { return getMethod(type.getSuperclass(), methodName, parameterTypes); // depends on control dependency: [if], data = [(type.getSuperclass()] } throw new MethodNotFoundException(cause); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private void doAttribute(Node receivedElement, Node receivedAttribute, Node sourceElement, XmlMessageValidationContext validationContext, NamespaceContext namespaceContext, TestContext context) { if (receivedAttribute.getNodeName().startsWith(XMLConstants.XMLNS_ATTRIBUTE)) { return; } String receivedAttributeName = receivedAttribute.getLocalName(); if (log.isDebugEnabled()) { log.debug("Validating attribute: " + receivedAttributeName + " (" + receivedAttribute.getNamespaceURI() + ")"); } NamedNodeMap sourceAttributes = sourceElement.getAttributes(); Node sourceAttribute = sourceAttributes.getNamedItemNS(receivedAttribute.getNamespaceURI(), receivedAttributeName); Assert.isTrue(sourceAttribute != null, "Attribute validation failed for element '" + receivedElement.getLocalName() + "', unknown attribute " + receivedAttributeName + " (" + receivedAttribute.getNamespaceURI() + ")"); if (XmlValidationUtils.isAttributeIgnored(receivedElement, receivedAttribute, sourceAttribute, validationContext.getIgnoreExpressions(), namespaceContext)) { return; } String receivedValue = receivedAttribute.getNodeValue(); String sourceValue = sourceAttribute.getNodeValue(); if (isValidationMatcherExpression(sourceAttribute)) { ValidationMatcherUtils.resolveValidationMatcher(sourceAttribute.getNodeName(), receivedAttribute.getNodeValue().trim(), sourceAttribute.getNodeValue().trim(), context); } else if (receivedValue.contains(":") && sourceValue.contains(":")) { doNamespaceQualifiedAttributeValidation(receivedElement, receivedAttribute, sourceElement, sourceAttribute); } else { Assert.isTrue(receivedValue.equals(sourceValue), ValidationUtils.buildValueMismatchErrorMessage("Values not equal for attribute '" + receivedAttributeName + "'", sourceValue, receivedValue)); } if (log.isDebugEnabled()) { log.debug("Attribute '" + receivedAttributeName + "'='" + receivedValue + "': OK"); } } }
public class class_name { private void doAttribute(Node receivedElement, Node receivedAttribute, Node sourceElement, XmlMessageValidationContext validationContext, NamespaceContext namespaceContext, TestContext context) { if (receivedAttribute.getNodeName().startsWith(XMLConstants.XMLNS_ATTRIBUTE)) { return; } // depends on control dependency: [if], data = [none] String receivedAttributeName = receivedAttribute.getLocalName(); if (log.isDebugEnabled()) { log.debug("Validating attribute: " + receivedAttributeName + " (" + receivedAttribute.getNamespaceURI() + ")"); } NamedNodeMap sourceAttributes = sourceElement.getAttributes(); Node sourceAttribute = sourceAttributes.getNamedItemNS(receivedAttribute.getNamespaceURI(), receivedAttributeName); Assert.isTrue(sourceAttribute != null, "Attribute validation failed for element '" + receivedElement.getLocalName() + "', unknown attribute " + receivedAttributeName + " (" + receivedAttribute.getNamespaceURI() + ")"); if (XmlValidationUtils.isAttributeIgnored(receivedElement, receivedAttribute, sourceAttribute, validationContext.getIgnoreExpressions(), namespaceContext)) { return; } String receivedValue = receivedAttribute.getNodeValue(); String sourceValue = sourceAttribute.getNodeValue(); if (isValidationMatcherExpression(sourceAttribute)) { ValidationMatcherUtils.resolveValidationMatcher(sourceAttribute.getNodeName(), receivedAttribute.getNodeValue().trim(), sourceAttribute.getNodeValue().trim(), context); } else if (receivedValue.contains(":") && sourceValue.contains(":")) { doNamespaceQualifiedAttributeValidation(receivedElement, receivedAttribute, sourceElement, sourceAttribute); } else { Assert.isTrue(receivedValue.equals(sourceValue), ValidationUtils.buildValueMismatchErrorMessage("Values not equal for attribute '" + receivedAttributeName + "'", sourceValue, receivedValue)); } if (log.isDebugEnabled()) { log.debug("Attribute '" + receivedAttributeName + "'='" + receivedValue + "': OK"); } } }
public class class_name { public static InputStream getResourceAsStream(String resourcePath, Object source) throws FileNotFoundException { // Try the current classloader InputStream is = source.getClass().getResourceAsStream(resourcePath); // Weblogic 10 likes this one better.. if (null == is) { ClassLoader cl = source.getClass().getClassLoader(); if (null != cl) { is = cl.getResourceAsStream(resourcePath); } } // If current classloader failed, try with the Threads context // classloader. If that fails ott, the resource is either not on the // classpath or inaccessible from the current context. if (null == is) { is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath); } if (null == is) { // Try to use the classloader of the current Jawr Config Manager // MBean // This will be used when a refresh is done in the configuration // using the JMX MBean MBeanServer mbs = JmxUtils.getMBeanServer(); if (mbs != null) { ObjectName name = ThreadLocalJawrContext.getJawrConfigMgrObjectName(); if (name != null) { try { ClassLoader cl = mbs.getClassLoaderFor(name); is = cl.getResourceAsStream(resourcePath); } catch (Exception e) { LOGGER.error("Unable to instanciate the Jawr MBean '" + name.getCanonicalName() + "'", e); } } } } // Try to retrieve by URL if (null == is) { try { URL url = getResourceURL(resourcePath, source); is = new FileInputStream(new File(url.getFile())); } catch (ResourceNotFoundException | IOException e) { throw new FileNotFoundException(resourcePath + " could not be found. "); } } return is; } }
public class class_name { public static InputStream getResourceAsStream(String resourcePath, Object source) throws FileNotFoundException { // Try the current classloader InputStream is = source.getClass().getResourceAsStream(resourcePath); // Weblogic 10 likes this one better.. if (null == is) { ClassLoader cl = source.getClass().getClassLoader(); if (null != cl) { is = cl.getResourceAsStream(resourcePath); // depends on control dependency: [if], data = [none] } } // If current classloader failed, try with the Threads context // classloader. If that fails ott, the resource is either not on the // classpath or inaccessible from the current context. if (null == is) { is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath); } if (null == is) { // Try to use the classloader of the current Jawr Config Manager // MBean // This will be used when a refresh is done in the configuration // using the JMX MBean MBeanServer mbs = JmxUtils.getMBeanServer(); if (mbs != null) { ObjectName name = ThreadLocalJawrContext.getJawrConfigMgrObjectName(); if (name != null) { try { ClassLoader cl = mbs.getClassLoaderFor(name); is = cl.getResourceAsStream(resourcePath); // depends on control dependency: [try], data = [none] } catch (Exception e) { LOGGER.error("Unable to instanciate the Jawr MBean '" + name.getCanonicalName() + "'", e); } // depends on control dependency: [catch], data = [none] } } } // Try to retrieve by URL if (null == is) { try { URL url = getResourceURL(resourcePath, source); is = new FileInputStream(new File(url.getFile())); // depends on control dependency: [try], data = [none] } catch (ResourceNotFoundException | IOException e) { throw new FileNotFoundException(resourcePath + " could not be found. "); } // depends on control dependency: [catch], data = [none] } return is; } }
public class class_name { @Nullable private static DimFilter toLeafFilter( final PlannerContext plannerContext, final DruidQuerySignature querySignature, final RexNode rexNode ) { if (rexNode.isAlwaysTrue()) { return Filtration.matchEverything(); } else if (rexNode.isAlwaysFalse()) { return Filtration.matchNothing(); } final DimFilter simpleFilter = toSimpleLeafFilter( plannerContext, querySignature, rexNode ); return simpleFilter != null ? simpleFilter : toExpressionLeafFilter(plannerContext, querySignature.getRowSignature(), rexNode); } }
public class class_name { @Nullable private static DimFilter toLeafFilter( final PlannerContext plannerContext, final DruidQuerySignature querySignature, final RexNode rexNode ) { if (rexNode.isAlwaysTrue()) { return Filtration.matchEverything(); // depends on control dependency: [if], data = [none] } else if (rexNode.isAlwaysFalse()) { return Filtration.matchNothing(); // depends on control dependency: [if], data = [none] } final DimFilter simpleFilter = toSimpleLeafFilter( plannerContext, querySignature, rexNode ); return simpleFilter != null ? simpleFilter : toExpressionLeafFilter(plannerContext, querySignature.getRowSignature(), rexNode); } }
public class class_name { @SuppressWarnings("unchecked") public boolean result(final Object iRecord) { final ODocument record = (ODocument) iRecord; boolean recordUpdated = false; parameters.reset(); // BIND VALUES TO UPDATE if (!setEntries.isEmpty()) { OSQLHelper.bindParameters(record, setEntries, parameters); recordUpdated = true; } // BIND VALUES TO INCREMENT for (Map.Entry<String, Number> entry : incrementEntries.entrySet()) { final Number prevValue = record.field(entry.getKey()); if (prevValue == null) // NO PREVIOUS VALUE: CONSIDER AS 0 record.field(entry.getKey(), entry.getValue()); else // COMPUTING INCREMENT record.field(entry.getKey(), OType.increment(prevValue, entry.getValue())); recordUpdated = true; } Object v; // BIND VALUES TO ADD Collection<Object> coll; Object fieldValue; for (OPair<String, Object> entry : addEntries) { coll = null; if (!record.containsField(entry.getKey())) { // GET THE TYPE IF ANY if (record.getSchemaClass() != null) { OProperty prop = record.getSchemaClass().getProperty(entry.getKey()); if (prop != null && prop.getType() == OType.LINKSET) // SET TYPE coll = new HashSet<Object>(); } if (coll == null) // IN ALL OTHER CASES USE A LIST coll = new ArrayList<Object>(); record.field(entry.getKey(), coll); } else { fieldValue = record.field(entry.getKey()); if (fieldValue instanceof Collection<?>) coll = (Collection<Object>) fieldValue; else continue; } v = entry.getValue(); if (v instanceof OSQLFilterItem) v = ((OSQLFilterItem) v).getValue(record, context); else if (v instanceof OSQLFunctionRuntime) v = ((OSQLFunctionRuntime) v).execute(record, this); coll.add(v); recordUpdated = true; } // BIND VALUES TO PUT (AS MAP) Map<String, Object> map; OPair<String, Object> pair; for (Entry<String, OPair<String, Object>> entry : putEntries.entrySet()) { fieldValue = record.field(entry.getKey()); if (fieldValue == null) { if (record.getSchemaClass() != null) { final OProperty property = record.getSchemaClass().getProperty(entry.getKey()); if (property != null && (property.getType() != null && (!property.getType().equals(OType.EMBEDDEDMAP) && !property.getType().equals( OType.LINKMAP)))) { throw new OCommandExecutionException("field " + entry.getKey() + " is not defined as a map"); } } fieldValue = new HashMap<String, Object>(); record.field(entry.getKey(), fieldValue); } if (fieldValue instanceof Map<?, ?>) { map = (Map<String, Object>) fieldValue; pair = entry.getValue(); if (pair.getValue() instanceof OSQLFilterItem) pair.setValue(((OSQLFilterItem) pair.getValue()).getValue(record, null)); else if (pair.getValue() instanceof OSQLFunctionRuntime) v = ((OSQLFunctionRuntime) pair.getValue()).execute(record, this); map.put(pair.getKey(), pair.getValue()); recordUpdated = true; } } // REMOVE FIELD IF ANY for (OPair<String, Object> entry : removeEntries) { v = entry.getValue(); if (v == EMPTY_VALUE) { record.removeField(entry.getKey()); recordUpdated = true; } else { fieldValue = record.field(entry.getKey()); if (fieldValue instanceof Collection<?>) { coll = (Collection<Object>) fieldValue; if (coll.remove(v)) recordUpdated = true; } else if (fieldValue instanceof Map<?, ?>) { map = (Map<String, Object>) fieldValue; if (map.remove(v) != null) recordUpdated = true; } } } if (recordUpdated) { record.setDirty(); record.save(); recordCount++; } return true; } }
public class class_name { @SuppressWarnings("unchecked") public boolean result(final Object iRecord) { final ODocument record = (ODocument) iRecord; boolean recordUpdated = false; parameters.reset(); // BIND VALUES TO UPDATE if (!setEntries.isEmpty()) { OSQLHelper.bindParameters(record, setEntries, parameters); // depends on control dependency: [if], data = [none] recordUpdated = true; // depends on control dependency: [if], data = [none] } // BIND VALUES TO INCREMENT for (Map.Entry<String, Number> entry : incrementEntries.entrySet()) { final Number prevValue = record.field(entry.getKey()); if (prevValue == null) // NO PREVIOUS VALUE: CONSIDER AS 0 record.field(entry.getKey(), entry.getValue()); else // COMPUTING INCREMENT record.field(entry.getKey(), OType.increment(prevValue, entry.getValue())); recordUpdated = true; // depends on control dependency: [for], data = [none] } Object v; // BIND VALUES TO ADD Collection<Object> coll; Object fieldValue; for (OPair<String, Object> entry : addEntries) { coll = null; // depends on control dependency: [for], data = [none] if (!record.containsField(entry.getKey())) { // GET THE TYPE IF ANY if (record.getSchemaClass() != null) { OProperty prop = record.getSchemaClass().getProperty(entry.getKey()); if (prop != null && prop.getType() == OType.LINKSET) // SET TYPE coll = new HashSet<Object>(); } if (coll == null) // IN ALL OTHER CASES USE A LIST coll = new ArrayList<Object>(); record.field(entry.getKey(), coll); // depends on control dependency: [if], data = [none] } else { fieldValue = record.field(entry.getKey()); // depends on control dependency: [if], data = [none] if (fieldValue instanceof Collection<?>) coll = (Collection<Object>) fieldValue; else continue; } v = entry.getValue(); // depends on control dependency: [for], data = [entry] if (v instanceof OSQLFilterItem) v = ((OSQLFilterItem) v).getValue(record, context); else if (v instanceof OSQLFunctionRuntime) v = ((OSQLFunctionRuntime) v).execute(record, this); coll.add(v); // depends on control dependency: [for], data = [none] recordUpdated = true; // depends on control dependency: [for], data = [none] } // BIND VALUES TO PUT (AS MAP) Map<String, Object> map; OPair<String, Object> pair; for (Entry<String, OPair<String, Object>> entry : putEntries.entrySet()) { fieldValue = record.field(entry.getKey()); // depends on control dependency: [for], data = [entry] if (fieldValue == null) { if (record.getSchemaClass() != null) { final OProperty property = record.getSchemaClass().getProperty(entry.getKey()); if (property != null && (property.getType() != null && (!property.getType().equals(OType.EMBEDDEDMAP) && !property.getType().equals( OType.LINKMAP)))) { throw new OCommandExecutionException("field " + entry.getKey() + " is not defined as a map"); } } fieldValue = new HashMap<String, Object>(); // depends on control dependency: [if], data = [none] record.field(entry.getKey(), fieldValue); // depends on control dependency: [if], data = [none] } if (fieldValue instanceof Map<?, ?>) { map = (Map<String, Object>) fieldValue; // depends on control dependency: [if], data = [)] pair = entry.getValue(); // depends on control dependency: [if], data = [)] if (pair.getValue() instanceof OSQLFilterItem) pair.setValue(((OSQLFilterItem) pair.getValue()).getValue(record, null)); else if (pair.getValue() instanceof OSQLFunctionRuntime) v = ((OSQLFunctionRuntime) pair.getValue()).execute(record, this); map.put(pair.getKey(), pair.getValue()); // depends on control dependency: [if], data = [)] recordUpdated = true; // depends on control dependency: [if], data = [none] } } // REMOVE FIELD IF ANY for (OPair<String, Object> entry : removeEntries) { v = entry.getValue(); // depends on control dependency: [for], data = [entry] if (v == EMPTY_VALUE) { record.removeField(entry.getKey()); // depends on control dependency: [if], data = [none] recordUpdated = true; // depends on control dependency: [if], data = [none] } else { fieldValue = record.field(entry.getKey()); // depends on control dependency: [if], data = [none] if (fieldValue instanceof Collection<?>) { coll = (Collection<Object>) fieldValue; // depends on control dependency: [if], data = [)] if (coll.remove(v)) recordUpdated = true; } else if (fieldValue instanceof Map<?, ?>) { map = (Map<String, Object>) fieldValue; // depends on control dependency: [if], data = [)] if (map.remove(v) != null) recordUpdated = true; } } } if (recordUpdated) { record.setDirty(); // depends on control dependency: [if], data = [none] record.save(); // depends on control dependency: [if], data = [none] recordCount++; // depends on control dependency: [if], data = [none] } return true; } }
public class class_name { @Override public Response toResponse(Exception e) { String id = System.nanoTime() + ""; LOGGER.error(id, e); if (e instanceof RobeRuntimeException) { return ((RobeRuntimeException) e).getResponse(id); } else if (e instanceof ConstraintViolationException) { ConstraintViolationException exception = (ConstraintViolationException) e; RobeMessage[] errors = new RobeMessage[exception.getConstraintViolations().size()]; int i = 0; for (ConstraintViolation error : exception.getConstraintViolations()) { errors[i++] = new RobeMessage.Builder().message(error.getMessage()).status(422).id(id).build(); } return Response.status(422).entity(errors).type(MediaType.APPLICATION_JSON).build(); } else if (e instanceof WebApplicationException) { WebApplicationException we = (WebApplicationException) e; RobeMessage error = new RobeMessage.Builder().id(id).message(we.getMessage()).status(we.getResponse().getStatus()).build(); return Response.fromResponse(we.getResponse()).entity(error).type(MediaType.APPLICATION_JSON).build(); } else { if (e.getClass().getName().equals("org.hibernate.exception.ConstraintViolationException")) { if (e.getCause() != null && e.getCause().getMessage() != null) { RobeMessage error = new RobeMessage.Builder().message(e.getCause().getMessage().split("for")[0]).status(Response.Status.CONFLICT.getStatusCode()).id(id).build(); return Response.status(Response.Status.CONFLICT).entity(error).type(MediaType.APPLICATION_JSON).build(); } } RobeMessage error = new RobeMessage.Builder().message(e.getMessage()).id(id).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).type(MediaType.APPLICATION_JSON).build(); } } }
public class class_name { @Override public Response toResponse(Exception e) { String id = System.nanoTime() + ""; LOGGER.error(id, e); if (e instanceof RobeRuntimeException) { return ((RobeRuntimeException) e).getResponse(id); } else if (e instanceof ConstraintViolationException) { ConstraintViolationException exception = (ConstraintViolationException) e; RobeMessage[] errors = new RobeMessage[exception.getConstraintViolations().size()]; int i = 0; for (ConstraintViolation error : exception.getConstraintViolations()) { errors[i++] = new RobeMessage.Builder().message(error.getMessage()).status(422).id(id).build(); // depends on control dependency: [for], data = [error] } return Response.status(422).entity(errors).type(MediaType.APPLICATION_JSON).build(); } else if (e instanceof WebApplicationException) { WebApplicationException we = (WebApplicationException) e; RobeMessage error = new RobeMessage.Builder().id(id).message(we.getMessage()).status(we.getResponse().getStatus()).build(); return Response.fromResponse(we.getResponse()).entity(error).type(MediaType.APPLICATION_JSON).build(); } else { if (e.getClass().getName().equals("org.hibernate.exception.ConstraintViolationException")) { if (e.getCause() != null && e.getCause().getMessage() != null) { RobeMessage error = new RobeMessage.Builder().message(e.getCause().getMessage().split("for")[0]).status(Response.Status.CONFLICT.getStatusCode()).id(id).build(); return Response.status(Response.Status.CONFLICT).entity(error).type(MediaType.APPLICATION_JSON).build(); } } RobeMessage error = new RobeMessage.Builder().message(e.getMessage()).id(id).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).type(MediaType.APPLICATION_JSON).build(); } } }
public class class_name { @Override public void serviceRequest(final Request request) { try { super.serviceRequest(request); } catch (Escape escape) { throw escape; } catch (Exception e) { LOG.error("Error processing content request in action phase. " + e.getMessage(), e); handleError(); } } }
public class class_name { @Override public void serviceRequest(final Request request) { try { super.serviceRequest(request); // depends on control dependency: [try], data = [none] } catch (Escape escape) { throw escape; } catch (Exception e) { // depends on control dependency: [catch], data = [none] LOG.error("Error processing content request in action phase. " + e.getMessage(), e); handleError(); } // depends on control dependency: [catch], data = [none] } }
public class class_name { void update(JobStatus status) { this.status = status; try { this.counters = running.getCounters(); this.completed = running.isComplete(); this.successful = running.isSuccessful(); this.mapProgress = running.mapProgress(); this.reduceProgress = running.reduceProgress(); // running.getTaskCompletionEvents(fromEvent); } catch (IOException ioe) { ioe.printStackTrace(); } this.completedMaps = (int) (this.totalMaps * this.mapProgress); this.completedReduces = (int) (this.totalReduces * this.reduceProgress); } }
public class class_name { void update(JobStatus status) { this.status = status; try { this.counters = running.getCounters(); // depends on control dependency: [try], data = [none] this.completed = running.isComplete(); // depends on control dependency: [try], data = [none] this.successful = running.isSuccessful(); // depends on control dependency: [try], data = [none] this.mapProgress = running.mapProgress(); // depends on control dependency: [try], data = [none] this.reduceProgress = running.reduceProgress(); // depends on control dependency: [try], data = [none] // running.getTaskCompletionEvents(fromEvent); } catch (IOException ioe) { ioe.printStackTrace(); } // depends on control dependency: [catch], data = [none] this.completedMaps = (int) (this.totalMaps * this.mapProgress); this.completedReduces = (int) (this.totalReduces * this.reduceProgress); } }
public class class_name { public boolean shouldBeProcessed(final ProfileSettings profileSettings) { if (profileSettings != null) { String propertyName = GetterUtilities.getFullQualifiedFieldName(baseType, method); Boolean shouldBeProcessed = profileSettings.getPropertyValue(propertyName); if (shouldBeProcessed == null) { propertyName = baseType.getCanonicalName() + "." + method.getName(); shouldBeProcessed = profileSettings.getPropertyValue(propertyName); } if (shouldBeProcessed == null && annotation != null) { shouldBeProcessed = annotation.enabledPerDefault(); } if (shouldBeProcessed != null) { return shouldBeProcessed; } } return true; } }
public class class_name { public boolean shouldBeProcessed(final ProfileSettings profileSettings) { if (profileSettings != null) { String propertyName = GetterUtilities.getFullQualifiedFieldName(baseType, method); Boolean shouldBeProcessed = profileSettings.getPropertyValue(propertyName); if (shouldBeProcessed == null) { propertyName = baseType.getCanonicalName() + "." + method.getName(); // depends on control dependency: [if], data = [none] shouldBeProcessed = profileSettings.getPropertyValue(propertyName); // depends on control dependency: [if], data = [none] } if (shouldBeProcessed == null && annotation != null) { shouldBeProcessed = annotation.enabledPerDefault(); // depends on control dependency: [if], data = [none] } if (shouldBeProcessed != null) { return shouldBeProcessed; // depends on control dependency: [if], data = [none] } } return true; } }
public class class_name { public void setChapterNumber(int number) { numbers.set(numbers.size() - 1, Integer.valueOf(number)); Object s; for (Iterator i = iterator(); i.hasNext(); ) { s = i.next(); if (s instanceof Section) { ((Section)s).setChapterNumber(number); } } } }
public class class_name { public void setChapterNumber(int number) { numbers.set(numbers.size() - 1, Integer.valueOf(number)); Object s; for (Iterator i = iterator(); i.hasNext(); ) { s = i.next(); // depends on control dependency: [for], data = [i] if (s instanceof Section) { ((Section)s).setChapterNumber(number); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public SimpleJob setSummarizer(Class<? extends Reducer<Key, Value, Key, Value>> clazz, boolean combine, int cache) { super.setReducerClass(clazz); reducer = true; if (combine) { setCombiner(clazz, cache); } return this; } }
public class class_name { public SimpleJob setSummarizer(Class<? extends Reducer<Key, Value, Key, Value>> clazz, boolean combine, int cache) { super.setReducerClass(clazz); reducer = true; if (combine) { setCombiner(clazz, cache); // depends on control dependency: [if], data = [none] } return this; } }
public class class_name { public int newField( final String owner, final String name, final String desc) { Item result = get(key3.set(FIELD, owner, name, desc)); if (result == null) { put122(FIELD, newClass(owner), newNameType(name, desc)); result = new Item(poolIndex++, key3); put(result); } return result.index; } }
public class class_name { public int newField( final String owner, final String name, final String desc) { Item result = get(key3.set(FIELD, owner, name, desc)); if (result == null) { put122(FIELD, newClass(owner), newNameType(name, desc)); // depends on control dependency: [if], data = [none] result = new Item(poolIndex++, key3); // depends on control dependency: [if], data = [none] put(result); // depends on control dependency: [if], data = [(result] } return result.index; } }
public class class_name { @FFDCIgnore(IllegalArgumentException.class) private String evaluateCallerBaseDn(boolean immediateOnly) { try { return elHelper.processString("callerBaseDn", this.idStoreDefinition.callerBaseDn(), immediateOnly); } catch (IllegalArgumentException e) { if (TraceComponent.isAnyTracingEnabled() && tc.isWarningEnabled()) { Tr.warning(tc, "JAVAEESEC_WARNING_IDSTORE_CONFIG", new Object[] { "callerBaseDn", "" }); } return ""; /* Default value from spec. */ } } }
public class class_name { @FFDCIgnore(IllegalArgumentException.class) private String evaluateCallerBaseDn(boolean immediateOnly) { try { return elHelper.processString("callerBaseDn", this.idStoreDefinition.callerBaseDn(), immediateOnly); // depends on control dependency: [try], data = [none] } catch (IllegalArgumentException e) { if (TraceComponent.isAnyTracingEnabled() && tc.isWarningEnabled()) { Tr.warning(tc, "JAVAEESEC_WARNING_IDSTORE_CONFIG", new Object[] { "callerBaseDn", "" }); // depends on control dependency: [if], data = [none] } return ""; /* Default value from spec. */ } // depends on control dependency: [catch], data = [none] } }
public class class_name { public CreateAssociationBatchResult withFailed(FailedCreateAssociation... failed) { if (this.failed == null) { setFailed(new com.amazonaws.internal.SdkInternalList<FailedCreateAssociation>(failed.length)); } for (FailedCreateAssociation ele : failed) { this.failed.add(ele); } return this; } }
public class class_name { public CreateAssociationBatchResult withFailed(FailedCreateAssociation... failed) { if (this.failed == null) { setFailed(new com.amazonaws.internal.SdkInternalList<FailedCreateAssociation>(failed.length)); // depends on control dependency: [if], data = [none] } for (FailedCreateAssociation ele : failed) { this.failed.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { @Pure public UnitVectorProperty firstAxisProperty() { if (this.raxis == null) { this.raxis = new UnitVectorProperty(this, MathFXAttributeNames.FIRST_AXIS, getGeomFactory()); } return this.raxis; } }
public class class_name { @Pure public UnitVectorProperty firstAxisProperty() { if (this.raxis == null) { this.raxis = new UnitVectorProperty(this, MathFXAttributeNames.FIRST_AXIS, getGeomFactory()); // depends on control dependency: [if], data = [none] } return this.raxis; } }
public class class_name { private boolean hasAbstractPackagePrivateSuperClassWithImplementation(Class<?> clazz, BridgeMethod bridgeMethod) { Class<?> superClass = clazz.getSuperclass(); while (superClass != null) { if (Modifier.isAbstract(superClass.getModifiers()) && Reflections.isPackagePrivate(superClass.getModifiers())) { // if superclass is abstract, we need to dig deeper for (Method method : superClass.getDeclaredMethods()) { if (bridgeMethod.signature.matches(method) && method.getGenericReturnType().equals(bridgeMethod.returnType) && !Reflections.isAbstract(method)) { // this is the case we are after -> methods have same signature and the one in super class has actual implementation return true; } } } superClass = superClass.getSuperclass(); } return false; } }
public class class_name { private boolean hasAbstractPackagePrivateSuperClassWithImplementation(Class<?> clazz, BridgeMethod bridgeMethod) { Class<?> superClass = clazz.getSuperclass(); while (superClass != null) { if (Modifier.isAbstract(superClass.getModifiers()) && Reflections.isPackagePrivate(superClass.getModifiers())) { // if superclass is abstract, we need to dig deeper for (Method method : superClass.getDeclaredMethods()) { if (bridgeMethod.signature.matches(method) && method.getGenericReturnType().equals(bridgeMethod.returnType) && !Reflections.isAbstract(method)) { // this is the case we are after -> methods have same signature and the one in super class has actual implementation return true; // depends on control dependency: [if], data = [none] } } } superClass = superClass.getSuperclass(); // depends on control dependency: [while], data = [none] } return false; } }
public class class_name { public static Properties extractSubset(final Properties properties, final String prefix) { final Properties subset = new Properties(); if (prefix == null || prefix.length() == 0) { return subset; } final String prefixToMatch = prefix.charAt(prefix.length() - 1) != '.' ? prefix + '.' : prefix; final List<String> keys = new ArrayList<>(); for (final String key : properties.stringPropertyNames()) { if (key.startsWith(prefixToMatch)) { subset.setProperty(key.substring(prefixToMatch.length()), properties.getProperty(key)); keys.add(key); } } for (final String key : keys) { properties.remove(key); } return subset; } }
public class class_name { public static Properties extractSubset(final Properties properties, final String prefix) { final Properties subset = new Properties(); if (prefix == null || prefix.length() == 0) { return subset; // depends on control dependency: [if], data = [none] } final String prefixToMatch = prefix.charAt(prefix.length() - 1) != '.' ? prefix + '.' : prefix; final List<String> keys = new ArrayList<>(); for (final String key : properties.stringPropertyNames()) { if (key.startsWith(prefixToMatch)) { subset.setProperty(key.substring(prefixToMatch.length()), properties.getProperty(key)); // depends on control dependency: [if], data = [none] keys.add(key); // depends on control dependency: [if], data = [none] } } for (final String key : keys) { properties.remove(key); // depends on control dependency: [for], data = [key] } return subset; } }
public class class_name { public static boolean evaluate(final String expression) { final Deque<String> operators = new ArrayDeque<>(); final Deque<String> values = new ArrayDeque<>(); final boolean result; char currentCharacter; int currentCharacterIndex = 0; try { while (currentCharacterIndex < expression.length()) { currentCharacter = expression.charAt(currentCharacterIndex); if (SeparatorToken.OPEN_PARENTHESIS.value == currentCharacter) { operators.push(SeparatorToken.OPEN_PARENTHESIS.toString()); currentCharacterIndex += moveCursor(SeparatorToken.OPEN_PARENTHESIS.toString()); } else if (SeparatorToken.SPACE.value == currentCharacter) { currentCharacterIndex += moveCursor(SeparatorToken.SPACE.toString()); } else if (SeparatorToken.CLOSE_PARENTHESIS.value == currentCharacter) { evaluateSubexpression(operators, values); currentCharacterIndex += moveCursor(SeparatorToken.CLOSE_PARENTHESIS.toString()); } else if (!Character.isDigit(currentCharacter)) { final String parsedNonDigit = parseNonDigits(expression, currentCharacterIndex); if (isBoolean(parsedNonDigit)) { values.push(replaceBooleanStringByIntegerRepresentation(parsedNonDigit)); } else { operators.push(validateOperator(parsedNonDigit)); } currentCharacterIndex += moveCursor(parsedNonDigit); } else if (Character.isDigit(currentCharacter)) { final String parsedDigits = parseDigits(expression, currentCharacterIndex); values.push(parsedDigits); currentCharacterIndex += moveCursor(parsedDigits); } } result = Boolean.valueOf(evaluateExpressionStack(operators, values)); if (log.isDebugEnabled()) { log.debug("Boolean expression {} evaluates to {}", expression, result); } } catch (final NoSuchElementException e) { throw new CitrusRuntimeException("Unable to parse boolean expression '" + expression + "'. Maybe expression is incomplete!", e); } return result; } }
public class class_name { public static boolean evaluate(final String expression) { final Deque<String> operators = new ArrayDeque<>(); final Deque<String> values = new ArrayDeque<>(); final boolean result; char currentCharacter; int currentCharacterIndex = 0; try { while (currentCharacterIndex < expression.length()) { currentCharacter = expression.charAt(currentCharacterIndex); // depends on control dependency: [while], data = [(currentCharacterIndex] if (SeparatorToken.OPEN_PARENTHESIS.value == currentCharacter) { operators.push(SeparatorToken.OPEN_PARENTHESIS.toString()); // depends on control dependency: [if], data = [none] currentCharacterIndex += moveCursor(SeparatorToken.OPEN_PARENTHESIS.toString()); // depends on control dependency: [if], data = [none] } else if (SeparatorToken.SPACE.value == currentCharacter) { currentCharacterIndex += moveCursor(SeparatorToken.SPACE.toString()); // depends on control dependency: [if], data = [none] } else if (SeparatorToken.CLOSE_PARENTHESIS.value == currentCharacter) { evaluateSubexpression(operators, values); // depends on control dependency: [if], data = [none] currentCharacterIndex += moveCursor(SeparatorToken.CLOSE_PARENTHESIS.toString()); // depends on control dependency: [if], data = [none] } else if (!Character.isDigit(currentCharacter)) { final String parsedNonDigit = parseNonDigits(expression, currentCharacterIndex); if (isBoolean(parsedNonDigit)) { values.push(replaceBooleanStringByIntegerRepresentation(parsedNonDigit)); // depends on control dependency: [if], data = [none] } else { operators.push(validateOperator(parsedNonDigit)); // depends on control dependency: [if], data = [none] } currentCharacterIndex += moveCursor(parsedNonDigit); // depends on control dependency: [if], data = [none] } else if (Character.isDigit(currentCharacter)) { final String parsedDigits = parseDigits(expression, currentCharacterIndex); values.push(parsedDigits); // depends on control dependency: [if], data = [none] currentCharacterIndex += moveCursor(parsedDigits); // depends on control dependency: [if], data = [none] } } result = Boolean.valueOf(evaluateExpressionStack(operators, values)); // depends on control dependency: [try], data = [none] if (log.isDebugEnabled()) { log.debug("Boolean expression {} evaluates to {}", expression, result); // depends on control dependency: [if], data = [none] } } catch (final NoSuchElementException e) { throw new CitrusRuntimeException("Unable to parse boolean expression '" + expression + "'. Maybe expression is incomplete!", e); } // depends on control dependency: [catch], data = [none] return result; } }
public class class_name { public String format(){ final StringBuilder sb = new StringBuilder(); if(betweenMs > 0){ long day = betweenMs / DateUnit.DAY.getMillis(); long hour = betweenMs / DateUnit.HOUR.getMillis() - day * 24; long minute = betweenMs / DateUnit.MINUTE.getMillis() - day * 24 * 60 - hour * 60; long second = betweenMs / DateUnit.SECOND.getMillis() - ((day * 24 + hour) * 60 + minute) * 60; long millisecond = betweenMs - (((day * 24 + hour) * 60 + minute) * 60 + second) * 1000; final int level = this.level.ordinal(); int levelCount = 0; if(isLevelCountValid(levelCount) && 0 != day && level >= Level.DAY.ordinal()){ sb.append(day).append(Level.DAY.name); levelCount++; } if(isLevelCountValid(levelCount) && 0 != hour && level >= Level.HOUR.ordinal()){ sb.append(hour).append(Level.HOUR.name); levelCount++; } if(isLevelCountValid(levelCount) && 0 != minute && level >= Level.MINUTE.ordinal()){ sb.append(minute).append(Level.MINUTE.name); levelCount++; } if(isLevelCountValid(levelCount) && 0 != second && level >= Level.SECOND.ordinal()){ sb.append(second).append(Level.SECOND.name); levelCount++; } if(isLevelCountValid(levelCount) && 0 != millisecond && level >= Level.MILLSECOND.ordinal()){ sb.append(millisecond).append(Level.MILLSECOND.name); levelCount++; } } if(StrUtil.isEmpty(sb)) { sb.append(0).append(this.level.name); } return sb.toString(); } }
public class class_name { public String format(){ final StringBuilder sb = new StringBuilder(); if(betweenMs > 0){ long day = betweenMs / DateUnit.DAY.getMillis(); long hour = betweenMs / DateUnit.HOUR.getMillis() - day * 24; long minute = betweenMs / DateUnit.MINUTE.getMillis() - day * 24 * 60 - hour * 60; long second = betweenMs / DateUnit.SECOND.getMillis() - ((day * 24 + hour) * 60 + minute) * 60; long millisecond = betweenMs - (((day * 24 + hour) * 60 + minute) * 60 + second) * 1000; final int level = this.level.ordinal(); int levelCount = 0; if(isLevelCountValid(levelCount) && 0 != day && level >= Level.DAY.ordinal()){ sb.append(day).append(Level.DAY.name); // depends on control dependency: [if], data = [none] levelCount++; // depends on control dependency: [if], data = [none] } if(isLevelCountValid(levelCount) && 0 != hour && level >= Level.HOUR.ordinal()){ sb.append(hour).append(Level.HOUR.name); // depends on control dependency: [if], data = [none] levelCount++; // depends on control dependency: [if], data = [none] } if(isLevelCountValid(levelCount) && 0 != minute && level >= Level.MINUTE.ordinal()){ sb.append(minute).append(Level.MINUTE.name); // depends on control dependency: [if], data = [none] levelCount++; // depends on control dependency: [if], data = [none] } if(isLevelCountValid(levelCount) && 0 != second && level >= Level.SECOND.ordinal()){ sb.append(second).append(Level.SECOND.name); // depends on control dependency: [if], data = [none] levelCount++; // depends on control dependency: [if], data = [none] } if(isLevelCountValid(levelCount) && 0 != millisecond && level >= Level.MILLSECOND.ordinal()){ sb.append(millisecond).append(Level.MILLSECOND.name); // depends on control dependency: [if], data = [none] levelCount++; // depends on control dependency: [if], data = [none] } } if(StrUtil.isEmpty(sb)) { sb.append(0).append(this.level.name); // depends on control dependency: [if], data = [none] } return sb.toString(); } }
public class class_name { private Map<String, CmsXmlContentProperty> removeHiddenProperties(Map<String, CmsXmlContentProperty> propConfig) { Map<String, CmsXmlContentProperty> result = new LinkedHashMap<String, CmsXmlContentProperty>(); for (Map.Entry<String, CmsXmlContentProperty> entry : propConfig.entrySet()) { if (!m_handler.isHiddenProperty(entry.getKey())) { result.put(entry.getKey(), entry.getValue()); } } return result; } }
public class class_name { private Map<String, CmsXmlContentProperty> removeHiddenProperties(Map<String, CmsXmlContentProperty> propConfig) { Map<String, CmsXmlContentProperty> result = new LinkedHashMap<String, CmsXmlContentProperty>(); for (Map.Entry<String, CmsXmlContentProperty> entry : propConfig.entrySet()) { if (!m_handler.isHiddenProperty(entry.getKey())) { result.put(entry.getKey(), entry.getValue()); // depends on control dependency: [if], data = [none] } } return result; } }
public class class_name { public JmxMessage attribute(String name, Object value, Class<?> valueType) { if (mbeanInvocation == null) { throw new CitrusRuntimeException("Invalid access to attribute for JMX message"); } ManagedBeanInvocation.Attribute attribute = new ManagedBeanInvocation.Attribute(); attribute.setName(name); if (value != null) { attribute.setValueObject(value); attribute.setType(valueType.getName()); } mbeanInvocation.setAttribute(attribute); return this; } }
public class class_name { public JmxMessage attribute(String name, Object value, Class<?> valueType) { if (mbeanInvocation == null) { throw new CitrusRuntimeException("Invalid access to attribute for JMX message"); } ManagedBeanInvocation.Attribute attribute = new ManagedBeanInvocation.Attribute(); attribute.setName(name); if (value != null) { attribute.setValueObject(value); // depends on control dependency: [if], data = [(value] attribute.setType(valueType.getName()); // depends on control dependency: [if], data = [(value] } mbeanInvocation.setAttribute(attribute); return this; } }
public class class_name { @Override public void renderView(FacesContext context, UIViewRoot view) throws IOException { if (!view.isRendered()) { return; } // log request if (log.isLoggable(Level.FINE)) { log.fine("Rendering View: " + view.getViewId()); } try { // build view - but not if we're in "buildBeforeRestore" // land and we've already got a populated view. Note // that this optimizations breaks if there's a "c:if" in // the page that toggles as a result of request processing - // should that be handled? Or // is this optimization simply so minor that it should just // be trimmed altogether? // See JSF 2.0 spec section 2.2.6, buildView is called before // Render Response //if (!isFilledView(context, view)) //{ // buildView(context, view); //} // setup writer and assign it to the context ResponseWriter origWriter = createResponseWriter(context); ExternalContext extContext = context.getExternalContext(); Writer outputWriter = extContext.getResponseOutputWriter(); StateWriter stateWriter = new StateWriter(outputWriter, 1024, context); try { ResponseWriter writer = origWriter.cloneWithWriter(stateWriter); try { context.setResponseWriter(writer); StateManager stateMgr = context.getApplication().getStateManager(); // force creation of session if saving state there // -= Leonardo Uribe =- Do this does not have any sense!. The only reference // about these lines are on http://java.net/projects/facelets/sources/svn/revision/376 // and it says: "fixed lazy session instantiation with eager response commit" // This code is obviously to prevent this exception: // java.lang.IllegalStateException: Cannot create a session after the response has been committed // But in theory if that so, StateManager.saveState must happen before writer.close() is called, // which can be done very easily. //if (!stateMgr.isSavingStateInClient(context)) //{ // extContext.getSession(true); //} // render the view to the response writer.startDocument(); view.encodeAll(context); writer.endDocument(); // finish writing // -= Leonardo Uribe =- This does not has sense too, because that's the reason // of the try/finally block. In practice, it only forces the close of the tag // in HtmlResponseWriter if necessary, but according to the spec, this should // be done using writer.flush() instead. // writer.close(); // flush to origWriter if (stateWriter.isStateWritten()) { // Call this method to force close the tag if necessary. // The spec javadoc says this: // "... Flush any ouput buffered by the output method to the underlying // Writer or OutputStream. This method will not flush the underlying // Writer or OutputStream; it simply clears any values buffered by this // ResponseWriter. ..." writer.flush(); // =-= markoc: STATE_KEY is in output ONLY if // stateManager.isSavingStateInClient(context)is true - see // org.apache.myfaces.application.ViewHandlerImpl.writeState(FacesContext) // TODO this class and ViewHandlerImpl contain same constant <!--@@JSF_FORM_STATE_MARKER@@--> Object stateObj = stateMgr.saveView(context); String content = stateWriter.getAndResetBuffer(); int end = content.indexOf(STATE_KEY); // See if we can find any trace of the saved state. // If so, we need to perform token replacement if (end >= 0) { // save state int start = 0; while (end != -1) { origWriter.write(content, start, end - start); String stateStr; if (view.isTransient()) { // Force state saving stateMgr.writeState(context, stateObj); stateStr = stateWriter.getAndResetBuffer(); } else if (stateObj == null) { stateStr = null; } else { stateMgr.writeState(context, stateObj); stateStr = stateWriter.getAndResetBuffer(); } if (stateStr != null) { origWriter.write(stateStr); } start = end + STATE_KEY_LEN; end = content.indexOf(STATE_KEY, start); } origWriter.write(content, start, content.length() - start); // No trace of any saved state, so we just need to flush // the buffer } else { origWriter.write(content); } } else if (stateWriter.isStateWrittenWithoutWrapper()) { // The state token has been written but the state has not been // saved yet. stateMgr.saveView(context); } else { // GET case without any form that trigger state saving. // Try to store it into cache. if (_viewPoolProcessor != null && _viewPoolProcessor.isViewPoolEnabledForThisView(context, view)) { ViewDeclarationLanguage vdl = context.getApplication(). getViewHandler().getViewDeclarationLanguage( context, view.getViewId()); if (ViewDeclarationLanguage.FACELETS_VIEW_DECLARATION_LANGUAGE_ID.equals( vdl.getId())) { StateManagementStrategy sms = vdl.getStateManagementStrategy( context, view.getId()); if (sms != null) { context.getAttributes().put(ViewPoolProcessor.FORCE_HARD_RESET, Boolean.TRUE); // Force indirectly to store the map in the cache try { Object state = sms.saveView(context); } finally { context.getAttributes().remove(ViewPoolProcessor.FORCE_HARD_RESET); } // Clear the calculated value from the application map context.getAttributes().remove(SERIALIZED_VIEW_REQUEST_ATTR); } } } } } finally { // The Facelets implementation must close the writer used to write the response writer.close(); } } finally { stateWriter.release(context); } } catch (FileNotFoundException fnfe) { handleFaceletNotFound(context, view.getViewId()); } catch (Exception e) { handleRenderException(context, e); } } }
public class class_name { @Override public void renderView(FacesContext context, UIViewRoot view) throws IOException { if (!view.isRendered()) { return; } // log request if (log.isLoggable(Level.FINE)) { log.fine("Rendering View: " + view.getViewId()); } try { // build view - but not if we're in "buildBeforeRestore" // land and we've already got a populated view. Note // that this optimizations breaks if there's a "c:if" in // the page that toggles as a result of request processing - // should that be handled? Or // is this optimization simply so minor that it should just // be trimmed altogether? // See JSF 2.0 spec section 2.2.6, buildView is called before // Render Response //if (!isFilledView(context, view)) //{ // buildView(context, view); //} // setup writer and assign it to the context ResponseWriter origWriter = createResponseWriter(context); ExternalContext extContext = context.getExternalContext(); Writer outputWriter = extContext.getResponseOutputWriter(); StateWriter stateWriter = new StateWriter(outputWriter, 1024, context); try { ResponseWriter writer = origWriter.cloneWithWriter(stateWriter); try { context.setResponseWriter(writer); // depends on control dependency: [try], data = [none] StateManager stateMgr = context.getApplication().getStateManager(); // force creation of session if saving state there // -= Leonardo Uribe =- Do this does not have any sense!. The only reference // about these lines are on http://java.net/projects/facelets/sources/svn/revision/376 // and it says: "fixed lazy session instantiation with eager response commit" // This code is obviously to prevent this exception: // java.lang.IllegalStateException: Cannot create a session after the response has been committed // But in theory if that so, StateManager.saveState must happen before writer.close() is called, // which can be done very easily. //if (!stateMgr.isSavingStateInClient(context)) //{ // extContext.getSession(true); //} // render the view to the response writer.startDocument(); // depends on control dependency: [try], data = [none] view.encodeAll(context); // depends on control dependency: [try], data = [none] writer.endDocument(); // depends on control dependency: [try], data = [none] // finish writing // -= Leonardo Uribe =- This does not has sense too, because that's the reason // of the try/finally block. In practice, it only forces the close of the tag // in HtmlResponseWriter if necessary, but according to the spec, this should // be done using writer.flush() instead. // writer.close(); // flush to origWriter if (stateWriter.isStateWritten()) { // Call this method to force close the tag if necessary. // The spec javadoc says this: // "... Flush any ouput buffered by the output method to the underlying // Writer or OutputStream. This method will not flush the underlying // Writer or OutputStream; it simply clears any values buffered by this // ResponseWriter. ..." writer.flush(); // depends on control dependency: [if], data = [none] // =-= markoc: STATE_KEY is in output ONLY if // stateManager.isSavingStateInClient(context)is true - see // org.apache.myfaces.application.ViewHandlerImpl.writeState(FacesContext) // TODO this class and ViewHandlerImpl contain same constant <!--@@JSF_FORM_STATE_MARKER@@--> Object stateObj = stateMgr.saveView(context); String content = stateWriter.getAndResetBuffer(); int end = content.indexOf(STATE_KEY); // See if we can find any trace of the saved state. // If so, we need to perform token replacement if (end >= 0) { // save state int start = 0; while (end != -1) { origWriter.write(content, start, end - start); // depends on control dependency: [while], data = [none] String stateStr; if (view.isTransient()) { // Force state saving stateMgr.writeState(context, stateObj); // depends on control dependency: [if], data = [none] stateStr = stateWriter.getAndResetBuffer(); // depends on control dependency: [if], data = [none] } else if (stateObj == null) { stateStr = null; // depends on control dependency: [if], data = [none] } else { stateMgr.writeState(context, stateObj); // depends on control dependency: [if], data = [none] stateStr = stateWriter.getAndResetBuffer(); // depends on control dependency: [if], data = [none] } if (stateStr != null) { origWriter.write(stateStr); // depends on control dependency: [if], data = [(stateStr] } start = end + STATE_KEY_LEN; // depends on control dependency: [while], data = [none] end = content.indexOf(STATE_KEY, start); // depends on control dependency: [while], data = [none] } origWriter.write(content, start, content.length() - start); // depends on control dependency: [if], data = [none] // No trace of any saved state, so we just need to flush // the buffer } else { origWriter.write(content); // depends on control dependency: [if], data = [none] } } else if (stateWriter.isStateWrittenWithoutWrapper()) { // The state token has been written but the state has not been // saved yet. stateMgr.saveView(context); // depends on control dependency: [if], data = [none] } else { // GET case without any form that trigger state saving. // Try to store it into cache. if (_viewPoolProcessor != null && _viewPoolProcessor.isViewPoolEnabledForThisView(context, view)) { ViewDeclarationLanguage vdl = context.getApplication(). getViewHandler().getViewDeclarationLanguage( context, view.getViewId()); if (ViewDeclarationLanguage.FACELETS_VIEW_DECLARATION_LANGUAGE_ID.equals( vdl.getId())) { StateManagementStrategy sms = vdl.getStateManagementStrategy( context, view.getId()); if (sms != null) { context.getAttributes().put(ViewPoolProcessor.FORCE_HARD_RESET, Boolean.TRUE); // depends on control dependency: [if], data = [none] // Force indirectly to store the map in the cache try { Object state = sms.saveView(context); } finally { context.getAttributes().remove(ViewPoolProcessor.FORCE_HARD_RESET); } // Clear the calculated value from the application map context.getAttributes().remove(SERIALIZED_VIEW_REQUEST_ATTR); // depends on control dependency: [if], data = [none] } } } } } finally { // The Facelets implementation must close the writer used to write the response writer.close(); } } finally { stateWriter.release(context); } } catch (FileNotFoundException fnfe) { handleFaceletNotFound(context, view.getViewId()); } catch (Exception e) { handleRenderException(context, e); } } }
public class class_name { private void expungeStaleEntries() { for (Object x; (x = queue.poll()) != null;) { synchronized (queue) { @SuppressWarnings("unchecked") Entry<K, V> e = (Entry<K, V>) x; int i = indexFor(e.hash, table.length); Entry<K, V> prev = table[i]; Entry<K, V> p = prev; while (p != null) { Entry<K, V> next = p.next; if (p == e) { if (prev == e) table[i] = next; else prev.next = next; // Must not null out e.next; // stale entries may be in use by a HashIterator e.value = null; // Help GC size--; break; } prev = p; p = next; } } } } }
public class class_name { private void expungeStaleEntries() { for (Object x; (x = queue.poll()) != null;) { synchronized (queue) { // depends on control dependency: [for], data = [none] @SuppressWarnings("unchecked") Entry<K, V> e = (Entry<K, V>) x; int i = indexFor(e.hash, table.length); Entry<K, V> prev = table[i]; Entry<K, V> p = prev; while (p != null) { Entry<K, V> next = p.next; if (p == e) { if (prev == e) table[i] = next; else prev.next = next; // Must not null out e.next; // stale entries may be in use by a HashIterator e.value = null; // Help GC // depends on control dependency: [if], data = [none] size--; // depends on control dependency: [if], data = [none] break; } prev = p; // depends on control dependency: [while], data = [none] p = next; // depends on control dependency: [while], data = [none] } } } } }
public class class_name { public final void transformTables(final Element root) { final Collection<Element> tables; // Tables to fix checkNotNull(root, "Received a null pointer as root element"); // Table rows with <th> tags in a <tbody> tables = root.select("table"); for (final Element table : tables) { table.addClass("table"); table.addClass("table-striped"); table.addClass("table-bordered"); } } }
public class class_name { public final void transformTables(final Element root) { final Collection<Element> tables; // Tables to fix checkNotNull(root, "Received a null pointer as root element"); // Table rows with <th> tags in a <tbody> tables = root.select("table"); for (final Element table : tables) { table.addClass("table"); // depends on control dependency: [for], data = [table] table.addClass("table-striped"); // depends on control dependency: [for], data = [table] table.addClass("table-bordered"); // depends on control dependency: [for], data = [table] } } }
public class class_name { private DateTimeColumn fillWith(int count, Iterator<LocalDateTime> iterator, Consumer<LocalDateTime> acceptor) { for (int r = 0; r < count; r++) { if (!iterator.hasNext()) { break; } acceptor.accept(iterator.next()); } return this; } }
public class class_name { private DateTimeColumn fillWith(int count, Iterator<LocalDateTime> iterator, Consumer<LocalDateTime> acceptor) { for (int r = 0; r < count; r++) { if (!iterator.hasNext()) { break; } acceptor.accept(iterator.next()); // depends on control dependency: [for], data = [none] } return this; } }
public class class_name { public static int versionCompare(String firstVersionString, String secondVersionString) { String[] firstVersion = parseVersionString(firstVersionString); String[] secondVersion = parseVersionString(secondVersionString); int i = 0; // set index to first non-equal ordinal or length of shortest version string while (i < firstVersion.length && i < secondVersion.length && firstVersion[i].equals(secondVersion[i])) { i++; } if (i < firstVersion.length && i < secondVersion.length) { // compare first non-equal ordinal number int diff = Integer.valueOf(firstVersion[i]).compareTo(Integer.valueOf(secondVersion[i])); return Integer.signum(diff); } else { // the strings are equal or one string is a substring of the other // e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4" return Integer.signum(firstVersion.length - secondVersion.length); } } }
public class class_name { public static int versionCompare(String firstVersionString, String secondVersionString) { String[] firstVersion = parseVersionString(firstVersionString); String[] secondVersion = parseVersionString(secondVersionString); int i = 0; // set index to first non-equal ordinal or length of shortest version string while (i < firstVersion.length && i < secondVersion.length && firstVersion[i].equals(secondVersion[i])) { i++; // depends on control dependency: [while], data = [none] } if (i < firstVersion.length && i < secondVersion.length) { // compare first non-equal ordinal number int diff = Integer.valueOf(firstVersion[i]).compareTo(Integer.valueOf(secondVersion[i])); return Integer.signum(diff); // depends on control dependency: [if], data = [none] } else { // the strings are equal or one string is a substring of the other // e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4" return Integer.signum(firstVersion.length - secondVersion.length); // depends on control dependency: [if], data = [none] } } }
public class class_name { static void resetOCSPResponseCacherServerURL(String ocspCacheServerUrl) { if (ocspCacheServerUrl == null || SF_OCSP_RESPONSE_CACHE_SERVER_RETRY_URL_PATTERN != null) { return; } SF_OCSP_RESPONSE_CACHE_SERVER_URL = ocspCacheServerUrl; if (!SF_OCSP_RESPONSE_CACHE_SERVER_URL.startsWith(DEFAULT_OCSP_CACHE_HOST)) { try { URL url = new URL(SF_OCSP_RESPONSE_CACHE_SERVER_URL); if (url.getPort() > 0) { SF_OCSP_RESPONSE_CACHE_SERVER_RETRY_URL_PATTERN = String.format("%s://%s:%d/retry/%s", url.getProtocol(), url.getHost(), url.getPort(), "%s/%s"); } else { SF_OCSP_RESPONSE_CACHE_SERVER_RETRY_URL_PATTERN = String.format("%s://%s/retry/%s", url.getProtocol(), url.getHost(), "%s/%s"); } } catch (IOException e) { throw new RuntimeException( String.format( "Failed to parse SF_OCSP_RESPONSE_CACHE_SERVER_URL: %s", SF_OCSP_RESPONSE_CACHE_SERVER_URL)); } } } }
public class class_name { static void resetOCSPResponseCacherServerURL(String ocspCacheServerUrl) { if (ocspCacheServerUrl == null || SF_OCSP_RESPONSE_CACHE_SERVER_RETRY_URL_PATTERN != null) { return; // depends on control dependency: [if], data = [none] } SF_OCSP_RESPONSE_CACHE_SERVER_URL = ocspCacheServerUrl; if (!SF_OCSP_RESPONSE_CACHE_SERVER_URL.startsWith(DEFAULT_OCSP_CACHE_HOST)) { try { URL url = new URL(SF_OCSP_RESPONSE_CACHE_SERVER_URL); if (url.getPort() > 0) { SF_OCSP_RESPONSE_CACHE_SERVER_RETRY_URL_PATTERN = String.format("%s://%s:%d/retry/%s", url.getProtocol(), url.getHost(), url.getPort(), "%s/%s"); // depends on control dependency: [if], data = [none] } else { SF_OCSP_RESPONSE_CACHE_SERVER_RETRY_URL_PATTERN = String.format("%s://%s/retry/%s", url.getProtocol(), url.getHost(), "%s/%s"); // depends on control dependency: [if], data = [none] } } catch (IOException e) { throw new RuntimeException( String.format( "Failed to parse SF_OCSP_RESPONSE_CACHE_SERVER_URL: %s", SF_OCSP_RESPONSE_CACHE_SERVER_URL)); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { private static <T> T withRequestLocale(Lang lang, Supplier<T> code) { try { LocaleContextHolder.setLocale(lang != null ? lang.toLocale() : null); } catch (Exception e) { // Just continue (Maybe there is no context or some internal error in LocaleContextHolder). // System default locale will be used. } try { return code.get(); } finally { LocaleContextHolder.resetLocaleContext(); // Clean up ThreadLocal } } }
public class class_name { private static <T> T withRequestLocale(Lang lang, Supplier<T> code) { try { LocaleContextHolder.setLocale(lang != null ? lang.toLocale() : null); // depends on control dependency: [try], data = [none] } catch (Exception e) { // Just continue (Maybe there is no context or some internal error in LocaleContextHolder). // System default locale will be used. } // depends on control dependency: [catch], data = [none] try { return code.get(); // depends on control dependency: [try], data = [none] } finally { LocaleContextHolder.resetLocaleContext(); // Clean up ThreadLocal } } }
public class class_name { public BoundingBox expandCoordinates(double maxProjectionLongitude) { BoundingBox expanded = new BoundingBox(this); double minLongitude = getMinLongitude(); double maxLongitude = getMaxLongitude(); if (minLongitude > maxLongitude) { int worldWraps = 1 + (int) ((minLongitude - maxLongitude) / (2 * maxProjectionLongitude)); maxLongitude += (worldWraps * 2 * maxProjectionLongitude); expanded.setMaxLongitude(maxLongitude); } return expanded; } }
public class class_name { public BoundingBox expandCoordinates(double maxProjectionLongitude) { BoundingBox expanded = new BoundingBox(this); double minLongitude = getMinLongitude(); double maxLongitude = getMaxLongitude(); if (minLongitude > maxLongitude) { int worldWraps = 1 + (int) ((minLongitude - maxLongitude) / (2 * maxProjectionLongitude)); maxLongitude += (worldWraps * 2 * maxProjectionLongitude); // depends on control dependency: [if], data = [none] expanded.setMaxLongitude(maxLongitude); // depends on control dependency: [if], data = [maxLongitude)] } return expanded; } }
public class class_name { public static Set<InjectionPoint> forStaticMethodsAndFields(TypeLiteral<?> type) { Errors errors = new Errors(); Set<InjectionPoint> result; if (type.getRawType().isInterface()) { errors.staticInjectionOnInterface(type.getRawType()); result = null; } else { result = getInjectionPoints(type, true, errors); } if (errors.hasErrors()) { throw new ConfigurationException(errors.getMessages()).withPartialValue(result); } return result; } }
public class class_name { public static Set<InjectionPoint> forStaticMethodsAndFields(TypeLiteral<?> type) { Errors errors = new Errors(); Set<InjectionPoint> result; if (type.getRawType().isInterface()) { errors.staticInjectionOnInterface(type.getRawType()); // depends on control dependency: [if], data = [none] result = null; // depends on control dependency: [if], data = [none] } else { result = getInjectionPoints(type, true, errors); // depends on control dependency: [if], data = [none] } if (errors.hasErrors()) { throw new ConfigurationException(errors.getMessages()).withPartialValue(result); } return result; } }
public class class_name { public String getSelectedResourceName() { String resParam = getJsp().getRequest().getParameter(getListId() + LIST_RACTION_SEL); if (CmsStringUtil.isNotEmpty(resParam)) { CmsListItem item = getList().getItem(resParam); return (String)item.get(LIST_COLUMN_NAME); } return null; } }
public class class_name { public String getSelectedResourceName() { String resParam = getJsp().getRequest().getParameter(getListId() + LIST_RACTION_SEL); if (CmsStringUtil.isNotEmpty(resParam)) { CmsListItem item = getList().getItem(resParam); return (String)item.get(LIST_COLUMN_NAME); // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { private void render(SVG.Image obj) { debug("Image render"); if (obj.width == null || obj.width.isZero() || obj.height == null || obj.height.isZero()) return; if (obj.href == null) return; // "If attribute 'preserveAspectRatio' is not specified, then the effect is as if a value of xMidYMid meet were specified." PreserveAspectRatio positioning = (obj.preserveAspectRatio != null) ? obj.preserveAspectRatio : PreserveAspectRatio.LETTERBOX; // Locate the referenced image Bitmap image = checkForImageDataURL(obj.href); if (image == null) { SVGExternalFileResolver fileResolver = SVG.getFileResolver(); if (fileResolver == null) return; image = fileResolver.resolveImage(obj.href); } if (image == null) { error("Could not locate image '%s'", obj.href); return; } SVG.Box imageNaturalSize = new SVG.Box(0, 0, image.getWidth(), image.getHeight()); updateStyleForElement(state, obj); if (!display()) return; if (!visible()) return; if (obj.transform != null) { canvas.concat(obj.transform); } float _x = (obj.x != null) ? obj.x.floatValueX(this) : 0f; float _y = (obj.y != null) ? obj.y.floatValueY(this) : 0f; float _w = obj.width.floatValueX(this); float _h = obj.height.floatValueX(this); state.viewPort = new SVG.Box(_x, _y, _w, _h); if (!state.style.overflow) { setClipRect(state.viewPort.minX, state.viewPort.minY, state.viewPort.width, state.viewPort.height); } obj.boundingBox = state.viewPort; updateParentBoundingBox(obj); checkForClipPath(obj); boolean compositing = pushLayer(); viewportFill(); canvas.save(); // Local transform from image's natural dimensions to the specified SVG dimensions canvas.concat(calculateViewBoxTransform(state.viewPort, imageNaturalSize, positioning)); Paint bmPaint = new Paint((state.style.imageRendering == RenderQuality.optimizeSpeed) ? 0 : Paint.FILTER_BITMAP_FLAG); canvas.drawBitmap(image, 0, 0, bmPaint); canvas.restore(); if (compositing) popLayer(obj); } }
public class class_name { private void render(SVG.Image obj) { debug("Image render"); if (obj.width == null || obj.width.isZero() || obj.height == null || obj.height.isZero()) return; if (obj.href == null) return; // "If attribute 'preserveAspectRatio' is not specified, then the effect is as if a value of xMidYMid meet were specified." PreserveAspectRatio positioning = (obj.preserveAspectRatio != null) ? obj.preserveAspectRatio : PreserveAspectRatio.LETTERBOX; // Locate the referenced image Bitmap image = checkForImageDataURL(obj.href); if (image == null) { SVGExternalFileResolver fileResolver = SVG.getFileResolver(); if (fileResolver == null) return; image = fileResolver.resolveImage(obj.href); // depends on control dependency: [if], data = [none] } if (image == null) { error("Could not locate image '%s'", obj.href); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } SVG.Box imageNaturalSize = new SVG.Box(0, 0, image.getWidth(), image.getHeight()); updateStyleForElement(state, obj); if (!display()) return; if (!visible()) return; if (obj.transform != null) { canvas.concat(obj.transform); // depends on control dependency: [if], data = [(obj.transform] } float _x = (obj.x != null) ? obj.x.floatValueX(this) : 0f; float _y = (obj.y != null) ? obj.y.floatValueY(this) : 0f; float _w = obj.width.floatValueX(this); float _h = obj.height.floatValueX(this); state.viewPort = new SVG.Box(_x, _y, _w, _h); if (!state.style.overflow) { setClipRect(state.viewPort.minX, state.viewPort.minY, state.viewPort.width, state.viewPort.height); // depends on control dependency: [if], data = [none] } obj.boundingBox = state.viewPort; updateParentBoundingBox(obj); checkForClipPath(obj); boolean compositing = pushLayer(); viewportFill(); canvas.save(); // Local transform from image's natural dimensions to the specified SVG dimensions canvas.concat(calculateViewBoxTransform(state.viewPort, imageNaturalSize, positioning)); Paint bmPaint = new Paint((state.style.imageRendering == RenderQuality.optimizeSpeed) ? 0 : Paint.FILTER_BITMAP_FLAG); canvas.drawBitmap(image, 0, 0, bmPaint); canvas.restore(); if (compositing) popLayer(obj); } }
public class class_name { public Long setnx(String key, Object value, int expiration) throws Exception { Long result = 0L; Jedis jedis = null; try { jedis = this.jedisPool.getResource(); result = jedis.setnx(SafeEncoder.encode(key), serialize(value)); jedis.expire(SafeEncoder.encode(key), expiration); return result; } catch (Exception e) { logger.error(e.getMessage(), e); this.jedisPool.returnBrokenResource(jedis); throw e; } finally { if (jedis != null) { this.jedisPool.returnResource(jedis); } } } }
public class class_name { public Long setnx(String key, Object value, int expiration) throws Exception { Long result = 0L; Jedis jedis = null; try { jedis = this.jedisPool.getResource(); result = jedis.setnx(SafeEncoder.encode(key), serialize(value)); jedis.expire(SafeEncoder.encode(key), expiration); return result; } catch (Exception e) { logger.error(e.getMessage(), e); this.jedisPool.returnBrokenResource(jedis); throw e; } finally { if (jedis != null) { this.jedisPool.returnResource(jedis); // depends on control dependency: [if], data = [(jedis] } } } }
public class class_name { public java.util.List<KeyListEntry> getKeys() { if (keys == null) { keys = new com.amazonaws.internal.SdkInternalList<KeyListEntry>(); } return keys; } }
public class class_name { public java.util.List<KeyListEntry> getKeys() { if (keys == null) { keys = new com.amazonaws.internal.SdkInternalList<KeyListEntry>(); // depends on control dependency: [if], data = [none] } return keys; } }
public class class_name { private final void fireEvents() throws IOException, SAXException, XMLStreamException { // First we are in prolog: int type; /* Need to enable lazy parsing, to get DTD start events before * its content events. Plus, can skip more efficiently too. */ mConfig.doParseLazily(false); while ((type = mScanner.next()) != XMLStreamConstants.START_ELEMENT) { fireAuxEvent(type, false); } // Now just starting the tree, need to process the START_ELEMENT fireStartTag(); int depth = 1; while (true) { type = mScanner.next(); if (type == XMLStreamConstants.START_ELEMENT) { fireStartTag(); ++depth; } else if (type == XMLStreamConstants.END_ELEMENT) { mScanner.fireSaxEndElement(mContentHandler); if (--depth < 1) { break; } } else if (type == XMLStreamConstants.CHARACTERS) { mScanner.fireSaxCharacterEvents(mContentHandler); } else { fireAuxEvent(type, true); } } // And then epilog: while (true) { type = mScanner.next(); if (type == XMLStreamConstants.END_DOCUMENT) { break; } if (type == XMLStreamConstants.SPACE) { // Not to be reported via SAX interface (which may or may not // be different from Stax) continue; } fireAuxEvent(type, false); } } }
public class class_name { private final void fireEvents() throws IOException, SAXException, XMLStreamException { // First we are in prolog: int type; /* Need to enable lazy parsing, to get DTD start events before * its content events. Plus, can skip more efficiently too. */ mConfig.doParseLazily(false); while ((type = mScanner.next()) != XMLStreamConstants.START_ELEMENT) { fireAuxEvent(type, false); } // Now just starting the tree, need to process the START_ELEMENT fireStartTag(); int depth = 1; while (true) { type = mScanner.next(); if (type == XMLStreamConstants.START_ELEMENT) { fireStartTag(); // depends on control dependency: [if], data = [none] ++depth; // depends on control dependency: [if], data = [none] } else if (type == XMLStreamConstants.END_ELEMENT) { mScanner.fireSaxEndElement(mContentHandler); // depends on control dependency: [if], data = [none] if (--depth < 1) { break; } } else if (type == XMLStreamConstants.CHARACTERS) { mScanner.fireSaxCharacterEvents(mContentHandler); // depends on control dependency: [if], data = [none] } else { fireAuxEvent(type, true); // depends on control dependency: [if], data = [(type] } } // And then epilog: while (true) { type = mScanner.next(); if (type == XMLStreamConstants.END_DOCUMENT) { break; } if (type == XMLStreamConstants.SPACE) { // Not to be reported via SAX interface (which may or may not // be different from Stax) continue; } fireAuxEvent(type, false); } } }
public class class_name { private void addWord(String word, boolean containsNewLine) { currentSentence.add(word); if (containsNewLine) { sentences.add(getSentenceFromListCheckingNewLines(currentSentence)); currentSentence.clear(); } } }
public class class_name { private void addWord(String word, boolean containsNewLine) { currentSentence.add(word); if (containsNewLine) { sentences.add(getSentenceFromListCheckingNewLines(currentSentence)); // depends on control dependency: [if], data = [none] currentSentence.clear(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static ScreenParent makeNewScreen(String componentType, ScreenLoc itsLocation, RecordOwnerParent screenParent, int iDisplayFieldDesc, Map<String, Object> properties, Rec mainRecord, boolean initScreen) { String screenClass = null; if (!componentType.contains(".")) screenClass = ScreenModel.BASE_PACKAGE + componentType; else if (componentType.startsWith(".")) screenClass = DBConstants.ROOT_PACKAGE + componentType.substring(1); else screenClass = componentType; ScreenParent screen = (ScreenParent)ClassServiceUtility.getClassService().makeObjectFromClassName(screenClass); if (screen == null) { Utility.getLogger().warning("Screen component not found " + componentType); screen = (ScreenParent)ClassServiceUtility.getClassService().makeObjectFromClassName(ScreenModel.BASE_PACKAGE + ScreenModel.SCREEN); } if (screen != null) { BaseAppletReference applet = null; if (screenParent.getTask() instanceof BaseAppletReference) applet = (BaseAppletReference)screenParent.getTask(); if (initScreen) { Object oldCursor = null; if (applet != null) oldCursor = applet.setStatus(Constant.WAIT, applet, null); Map<String,Object> screenProperties = new HashMap<String,Object>(); if (properties != null) screenProperties.putAll(properties); screenProperties.put(ScreenModel.DISPLAY, iDisplayFieldDesc); if (itsLocation != null) screenProperties.put(ScreenModel.LOCATION, itsLocation); //if (((iDisplayFieldDesc & ScreenConstants.DETAIL_MODE) == ScreenConstants.DETAIL_MODE) && (screen instanceof DetailGridScreen)) // ((DetailGridScreen)screen).init((Record)mainRecord, null, (ScreenLocation)itsLocation, (BasePanel)screenParent, null, iDisplayFieldDesc, properties); //else screen.init(screenParent, mainRecord, screenProperties); if (applet != null) applet.setStatus(0, applet, oldCursor); } } return screen; } }
public class class_name { public static ScreenParent makeNewScreen(String componentType, ScreenLoc itsLocation, RecordOwnerParent screenParent, int iDisplayFieldDesc, Map<String, Object> properties, Rec mainRecord, boolean initScreen) { String screenClass = null; if (!componentType.contains(".")) screenClass = ScreenModel.BASE_PACKAGE + componentType; else if (componentType.startsWith(".")) screenClass = DBConstants.ROOT_PACKAGE + componentType.substring(1); else screenClass = componentType; ScreenParent screen = (ScreenParent)ClassServiceUtility.getClassService().makeObjectFromClassName(screenClass); if (screen == null) { Utility.getLogger().warning("Screen component not found " + componentType); // depends on control dependency: [if], data = [none] screen = (ScreenParent)ClassServiceUtility.getClassService().makeObjectFromClassName(ScreenModel.BASE_PACKAGE + ScreenModel.SCREEN); // depends on control dependency: [if], data = [none] } if (screen != null) { BaseAppletReference applet = null; if (screenParent.getTask() instanceof BaseAppletReference) applet = (BaseAppletReference)screenParent.getTask(); if (initScreen) { Object oldCursor = null; if (applet != null) oldCursor = applet.setStatus(Constant.WAIT, applet, null); Map<String,Object> screenProperties = new HashMap<String,Object>(); if (properties != null) screenProperties.putAll(properties); screenProperties.put(ScreenModel.DISPLAY, iDisplayFieldDesc); // depends on control dependency: [if], data = [none] if (itsLocation != null) screenProperties.put(ScreenModel.LOCATION, itsLocation); //if (((iDisplayFieldDesc & ScreenConstants.DETAIL_MODE) == ScreenConstants.DETAIL_MODE) && (screen instanceof DetailGridScreen)) // ((DetailGridScreen)screen).init((Record)mainRecord, null, (ScreenLocation)itsLocation, (BasePanel)screenParent, null, iDisplayFieldDesc, properties); //else screen.init(screenParent, mainRecord, screenProperties); // depends on control dependency: [if], data = [none] if (applet != null) applet.setStatus(0, applet, oldCursor); } } return screen; } }
public class class_name { public void alias(DMatrixRMaj variable , String name ) { if( isReserved(name)) throw new RuntimeException("Reserved word or contains a reserved character"); VariableMatrix old = (VariableMatrix)variables.get(name); if( old == null ) { variables.put(name, new VariableMatrix(variable)); }else { old.matrix = variable; } } }
public class class_name { public void alias(DMatrixRMaj variable , String name ) { if( isReserved(name)) throw new RuntimeException("Reserved word or contains a reserved character"); VariableMatrix old = (VariableMatrix)variables.get(name); if( old == null ) { variables.put(name, new VariableMatrix(variable)); // depends on control dependency: [if], data = [none] }else { old.matrix = variable; // depends on control dependency: [if], data = [none] } } }
public class class_name { private static byte[] byteCopy(byte[] source, int offset, int count, byte[] target) { for (int i = offset, j = 0; i < offset + count; i++, j++) { target[j] = source[i]; } return target; } }
public class class_name { private static byte[] byteCopy(byte[] source, int offset, int count, byte[] target) { for (int i = offset, j = 0; i < offset + count; i++, j++) { target[j] = source[i]; // depends on control dependency: [for], data = [i] } return target; } }
public class class_name { private static int mergeMaps(Map<String, Integer> map, Map<String, Integer> other) { int deltaSize = 0; for (Map.Entry<String, Integer> entry : other.entrySet()) { if (!map.containsKey(entry.getKey())) { deltaSize += entry.getKey().getBytes().length + SIZE_OF_INT; } map.put(entry.getKey(), map.getOrDefault(entry.getKey(), 0) + other.getOrDefault(entry.getKey(), 0)); } return deltaSize; } }
public class class_name { private static int mergeMaps(Map<String, Integer> map, Map<String, Integer> other) { int deltaSize = 0; for (Map.Entry<String, Integer> entry : other.entrySet()) { if (!map.containsKey(entry.getKey())) { deltaSize += entry.getKey().getBytes().length + SIZE_OF_INT; // depends on control dependency: [if], data = [none] } map.put(entry.getKey(), map.getOrDefault(entry.getKey(), 0) + other.getOrDefault(entry.getKey(), 0)); // depends on control dependency: [for], data = [entry] } return deltaSize; } }
public class class_name { public String getPercentageResult() { int total = 0; for (Status status : Status.values()) { total += this.statusCounter.getValueFor(status); } return Util.formatAsPercentage(this.statusCounter.getValueFor(Status.PASSED), total); } }
public class class_name { public String getPercentageResult() { int total = 0; for (Status status : Status.values()) { total += this.statusCounter.getValueFor(status); // depends on control dependency: [for], data = [status] } return Util.formatAsPercentage(this.statusCounter.getValueFor(Status.PASSED), total); } }
public class class_name { public static base_responses clear(nitro_service client, lbpersistentsessions resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { lbpersistentsessions clearresources[] = new lbpersistentsessions[resources.length]; for (int i=0;i<resources.length;i++){ clearresources[i] = new lbpersistentsessions(); clearresources[i].vserver = resources[i].vserver; clearresources[i].persistenceparameter = resources[i].persistenceparameter; } result = perform_operation_bulk_request(client, clearresources,"clear"); } return result; } }
public class class_name { public static base_responses clear(nitro_service client, lbpersistentsessions resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { lbpersistentsessions clearresources[] = new lbpersistentsessions[resources.length]; for (int i=0;i<resources.length;i++){ clearresources[i] = new lbpersistentsessions(); // depends on control dependency: [for], data = [i] clearresources[i].vserver = resources[i].vserver; // depends on control dependency: [for], data = [i] clearresources[i].persistenceparameter = resources[i].persistenceparameter; // depends on control dependency: [for], data = [i] } result = perform_operation_bulk_request(client, clearresources,"clear"); } return result; } }
public class class_name { public String mkString(NumberFormat formatter, String delimiter) { StringBuilder sb = new StringBuilder(); VectorIterator it = iterator(); while (it.hasNext()) { double x = it.next(); int i = it.index(); sb.append(formatter.format(x)) .append((i < length - 1 ? delimiter : "")); } return sb.toString(); } }
public class class_name { public String mkString(NumberFormat formatter, String delimiter) { StringBuilder sb = new StringBuilder(); VectorIterator it = iterator(); while (it.hasNext()) { double x = it.next(); int i = it.index(); sb.append(formatter.format(x)) .append((i < length - 1 ? delimiter : "")); // depends on control dependency: [while], data = [none] } return sb.toString(); } }
public class class_name { public static <E> List<E> pageQuery(Dialect dialect, Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql, CacheKey cacheKey) throws SQLException { //判断是否需要进行分页查询 if (dialect.beforePage(ms, parameter, rowBounds)) { //生成分页的缓存 key CacheKey pageKey = cacheKey; //处理参数对象 parameter = dialect.processParameterObject(ms, parameter, boundSql, pageKey); //调用方言获取分页 sql String pageSql = dialect.getPageSql(ms, boundSql, parameter, rowBounds, pageKey); BoundSql pageBoundSql = new BoundSql(ms.getConfiguration(), pageSql, boundSql.getParameterMappings(), parameter); Map<String, Object> additionalParameters = getAdditionalParameter(boundSql); //设置动态参数 for (String key : additionalParameters.keySet()) { pageBoundSql.setAdditionalParameter(key, additionalParameters.get(key)); } //执行分页查询 return executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, pageKey, pageBoundSql); } else { //不执行分页的情况下,也不执行内存分页 return executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, boundSql); } } }
public class class_name { public static <E> List<E> pageQuery(Dialect dialect, Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql, CacheKey cacheKey) throws SQLException { //判断是否需要进行分页查询 if (dialect.beforePage(ms, parameter, rowBounds)) { //生成分页的缓存 key CacheKey pageKey = cacheKey; //处理参数对象 parameter = dialect.processParameterObject(ms, parameter, boundSql, pageKey); //调用方言获取分页 sql String pageSql = dialect.getPageSql(ms, boundSql, parameter, rowBounds, pageKey); BoundSql pageBoundSql = new BoundSql(ms.getConfiguration(), pageSql, boundSql.getParameterMappings(), parameter); Map<String, Object> additionalParameters = getAdditionalParameter(boundSql); //设置动态参数 for (String key : additionalParameters.keySet()) { pageBoundSql.setAdditionalParameter(key, additionalParameters.get(key)); // depends on control dependency: [for], data = [key] } //执行分页查询 return executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, pageKey, pageBoundSql); } else { //不执行分页的情况下,也不执行内存分页 return executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, boundSql); } } }
public class class_name { private void addDerivedTypes() { Iterator<DefinedType> typeIter = schema.getTypes().iterator(); while (typeIter.hasNext()) { DefinedType type = typeIter.next(); // debug (type.getName()+":"+type.getDomain(true).toString()); // if ((type.getDomain() instanceof SimpleType)==false && // (type instanceof EnumerationType)==false && // (type instanceof SelectType)==false){ /* * one of the hard things TODO : TYPE IfcCompoundPlaneAngleMeasure = * LIST [3:3] OF INTEGER; WHERE WR1 : { -360 <= SELF[1] < 360 }; WR2 * : { -60 <= SELF[2] < 60 }; WR3 : { -60 <= SELF[3] < 60 }; WR4 : * ((SELF[1] >= 0) AND (SELF[2] >= 0) AND (SELF[3] >= 0)) OR * ((SELF[1] <= 0) AND (SELF[2] <= 0) AND (SELF[3] <= 0)); END_TYPE; * * I am skipping this for now, it only occurs once in the model * future versions should definitely find an answer to this * * A fix for this has been implemented in addHackedTypes */ if (type.getName().equalsIgnoreCase("IfcCompoundPlaneAngleMeasure")) { EClass testType = getOrCreateEClass(type.getName()); DefinedType type2 = new DefinedType("Integer"); type2.setDomain(new IntegerType()); modifySimpleType(type2, testType); testType.getEAnnotations().add(createWrappedAnnotation()); } else if (type.getDomain() instanceof DefinedType) { if (schemaPack.getEClassifier(type.getName()) != null) { EClass testType = (EClass) schemaPack.getEClassifier(type.getName()); DefinedType domain = (DefinedType) type.getDomain(); EClassifier classifier = schemaPack.getEClassifier(domain.getName()); testType.getESuperTypes().add((EClass) classifier); testType.setInstanceClass(classifier.getInstanceClass()); } else { EClass testType = getOrCreateEClass(type.getName()); DefinedType domain = (DefinedType) type.getDomain(); if (simpleTypeReplacementMap.containsKey(domain.getName())) { // We can't subclass because it's a 'primitive' type simpleTypeReplacementMap.put(type.getName(), simpleTypeReplacementMap.get(domain.getName())); } else { EClass classifier = getOrCreateEClass(domain.getName()); testType.getESuperTypes().add((EClass) classifier); if (classifier.getEAnnotation("wrapped") != null) { testType.getEAnnotations().add(createWrappedAnnotation()); } testType.setInstanceClass(classifier.getInstanceClass()); } } } } } }
public class class_name { private void addDerivedTypes() { Iterator<DefinedType> typeIter = schema.getTypes().iterator(); while (typeIter.hasNext()) { DefinedType type = typeIter.next(); // debug (type.getName()+":"+type.getDomain(true).toString()); // if ((type.getDomain() instanceof SimpleType)==false && // (type instanceof EnumerationType)==false && // (type instanceof SelectType)==false){ /* * one of the hard things TODO : TYPE IfcCompoundPlaneAngleMeasure = * LIST [3:3] OF INTEGER; WHERE WR1 : { -360 <= SELF[1] < 360 }; WR2 * : { -60 <= SELF[2] < 60 }; WR3 : { -60 <= SELF[3] < 60 }; WR4 : * ((SELF[1] >= 0) AND (SELF[2] >= 0) AND (SELF[3] >= 0)) OR * ((SELF[1] <= 0) AND (SELF[2] <= 0) AND (SELF[3] <= 0)); END_TYPE; * * I am skipping this for now, it only occurs once in the model * future versions should definitely find an answer to this * * A fix for this has been implemented in addHackedTypes */ if (type.getName().equalsIgnoreCase("IfcCompoundPlaneAngleMeasure")) { EClass testType = getOrCreateEClass(type.getName()); DefinedType type2 = new DefinedType("Integer"); type2.setDomain(new IntegerType()); // depends on control dependency: [if], data = [none] modifySimpleType(type2, testType); // depends on control dependency: [if], data = [none] testType.getEAnnotations().add(createWrappedAnnotation()); // depends on control dependency: [if], data = [none] } else if (type.getDomain() instanceof DefinedType) { if (schemaPack.getEClassifier(type.getName()) != null) { EClass testType = (EClass) schemaPack.getEClassifier(type.getName()); DefinedType domain = (DefinedType) type.getDomain(); EClassifier classifier = schemaPack.getEClassifier(domain.getName()); testType.getESuperTypes().add((EClass) classifier); // depends on control dependency: [if], data = [none] testType.setInstanceClass(classifier.getInstanceClass()); // depends on control dependency: [if], data = [none] } else { EClass testType = getOrCreateEClass(type.getName()); DefinedType domain = (DefinedType) type.getDomain(); if (simpleTypeReplacementMap.containsKey(domain.getName())) { // We can't subclass because it's a 'primitive' type simpleTypeReplacementMap.put(type.getName(), simpleTypeReplacementMap.get(domain.getName())); // depends on control dependency: [if], data = [none] } else { EClass classifier = getOrCreateEClass(domain.getName()); testType.getESuperTypes().add((EClass) classifier); // depends on control dependency: [if], data = [none] if (classifier.getEAnnotation("wrapped") != null) { testType.getEAnnotations().add(createWrappedAnnotation()); // depends on control dependency: [if], data = [none] } testType.setInstanceClass(classifier.getInstanceClass()); // depends on control dependency: [if], data = [none] } } } } } }
public class class_name { public static void instrumentClass(Class<?> c, ConstructorCallback<?> sampler) throws UnmodifiableClassException { // IMPORTANT: Don't forget that other threads may be accessing this // class while this code is running. Specifically, the class may be // executed directly after the retransformClasses is called. Thus, we need // to be careful about what happens after the retransformClasses call. synchronized (samplerPutAtomicityLock) { List<ConstructorCallback<?>> list = samplerMap.get(c); if (list == null) { CopyOnWriteArrayList<ConstructorCallback<?>> samplerList = new CopyOnWriteArrayList<ConstructorCallback<?>>(); samplerList.add(sampler); samplerMap.put(c, samplerList); Instrumentation inst = AllocationRecorder.getInstrumentation(); Class<?>[] cs = new Class<?>[1]; cs[0] = c; inst.retransformClasses(c); } else { list.add(sampler); } } } }
public class class_name { public static void instrumentClass(Class<?> c, ConstructorCallback<?> sampler) throws UnmodifiableClassException { // IMPORTANT: Don't forget that other threads may be accessing this // class while this code is running. Specifically, the class may be // executed directly after the retransformClasses is called. Thus, we need // to be careful about what happens after the retransformClasses call. synchronized (samplerPutAtomicityLock) { List<ConstructorCallback<?>> list = samplerMap.get(c); if (list == null) { CopyOnWriteArrayList<ConstructorCallback<?>> samplerList = new CopyOnWriteArrayList<ConstructorCallback<?>>(); // depends on control dependency: [if], data = [none] samplerList.add(sampler); // depends on control dependency: [if], data = [none] samplerMap.put(c, samplerList); // depends on control dependency: [if], data = [none] Instrumentation inst = AllocationRecorder.getInstrumentation(); Class<?>[] cs = new Class<?>[1]; cs[0] = c; inst.retransformClasses(c); } else { list.add(sampler); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public static QName valueOf(String s) { if ((s == null) || s.equals("")) { throw new IllegalArgumentException("invalid QName literal"); } if (s.charAt(0) == '{') { int i = s.indexOf('}'); if (i == -1) { throw new IllegalArgumentException("invalid QName literal"); } if (i == s.length() - 1) { throw new IllegalArgumentException("invalid QName literal"); } else { return new QName(s.substring(1, i), s.substring(i + 1)); } } else { return new QName(s); } } }
public class class_name { public static QName valueOf(String s) { if ((s == null) || s.equals("")) { throw new IllegalArgumentException("invalid QName literal"); } if (s.charAt(0) == '{') { int i = s.indexOf('}'); if (i == -1) { throw new IllegalArgumentException("invalid QName literal"); } if (i == s.length() - 1) { throw new IllegalArgumentException("invalid QName literal"); } else { return new QName(s.substring(1, i), s.substring(i + 1)); // depends on control dependency: [if], data = [(i] } } else { return new QName(s); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void marshall(DeleteLoggingConfigurationRequest deleteLoggingConfigurationRequest, ProtocolMarshaller protocolMarshaller) { if (deleteLoggingConfigurationRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deleteLoggingConfigurationRequest.getResourceArn(), RESOURCEARN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(DeleteLoggingConfigurationRequest deleteLoggingConfigurationRequest, ProtocolMarshaller protocolMarshaller) { if (deleteLoggingConfigurationRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deleteLoggingConfigurationRequest.getResourceArn(), RESOURCEARN_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] } }