code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { private Session removeSession(String id) { try { Session session = sessionCache.delete(id); if (session != null) { session.beginInvalidate(); for (int i = sessionListeners.size() - 1; i >= 0; i--) { sessionListeners.get(i).sessionDestroyed(session); } } return session; } catch (Exception e) { log.warn("Failed to delete session", e); return null; } } }
public class class_name { private Session removeSession(String id) { try { Session session = sessionCache.delete(id); if (session != null) { session.beginInvalidate(); // depends on control dependency: [if], data = [none] for (int i = sessionListeners.size() - 1; i >= 0; i--) { sessionListeners.get(i).sessionDestroyed(session); // depends on control dependency: [for], data = [i] } } return session; // depends on control dependency: [try], data = [none] } catch (Exception e) { log.warn("Failed to delete session", e); return null; } // depends on control dependency: [catch], data = [none] } }
public class class_name { protected void unsuccessfulAuthentication(PortletRequest request, PortletResponse response, AuthenticationException failed) { SecurityContextHolder.clearContext(); if (logger.isDebugEnabled()) { logger.debug("Cleared security context due to exception", failed); } request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, failed); } }
public class class_name { protected void unsuccessfulAuthentication(PortletRequest request, PortletResponse response, AuthenticationException failed) { SecurityContextHolder.clearContext(); if (logger.isDebugEnabled()) { logger.debug("Cleared security context due to exception", failed); // depends on control dependency: [if], data = [none] } request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, failed); } }
public class class_name { protected void removeBehaviorListener(BehaviorListener listener) { if (listener == null) { throw new NullPointerException(); } if (listeners == null) { return; } listeners.remove(listener); clearInitialState(); } }
public class class_name { protected void removeBehaviorListener(BehaviorListener listener) { if (listener == null) { throw new NullPointerException(); } if (listeners == null) { return; // depends on control dependency: [if], data = [none] } listeners.remove(listener); clearInitialState(); } }
public class class_name { private static String marshal(String args) { if (args != null) { StringBuffer target = new StringBuffer(); StringBuffer source = new StringBuffer(args); // obtain the "permission=<classname>" options // the syntax of classname: IDENTIFIER.IDENTIFIER // the regular express to match a class name: // "[a-zA-Z_$][a-zA-Z0-9_$]*([.][a-zA-Z_$][a-zA-Z0-9_$]*)*" String keyReg = "[Pp][Ee][Rr][Mm][Ii][Ss][Ss][Ii][Oo][Nn]="; String keyStr = "permission="; String reg = keyReg + "[a-zA-Z_$][a-zA-Z0-9_$]*([.][a-zA-Z_$][a-zA-Z0-9_$]*)*"; Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(source); StringBuffer left = new StringBuffer(); while (matcher.find()) { String matched = matcher.group(); target.append(matched.replaceFirst(keyReg, keyStr)); target.append(" "); // delete the matched sequence matcher.appendReplacement(left, ""); } matcher.appendTail(left); source = left; // obtain the "codebase=<URL>" options // the syntax of URL is too flexible, and here assumes that the // URL contains no space, comma(','), and semicolon(';'). That // also means those characters also could be used as separator // after codebase option. // However, the assumption is incorrect in some special situation // when the URL contains comma or semicolon keyReg = "[Cc][Oo][Dd][Ee][Bb][Aa][Ss][Ee]="; keyStr = "codebase="; reg = keyReg + "[^, ;]*"; pattern = Pattern.compile(reg); matcher = pattern.matcher(source); left = new StringBuffer(); while (matcher.find()) { String matched = matcher.group(); target.append(matched.replaceFirst(keyReg, keyStr)); target.append(" "); // delete the matched sequence matcher.appendReplacement(left, ""); } matcher.appendTail(left); source = left; // convert the rest to lower-case characters target.append(source.toString().toLowerCase(Locale.ENGLISH)); return target.toString(); } return null; } }
public class class_name { private static String marshal(String args) { if (args != null) { StringBuffer target = new StringBuffer(); StringBuffer source = new StringBuffer(args); // obtain the "permission=<classname>" options // the syntax of classname: IDENTIFIER.IDENTIFIER // the regular express to match a class name: // "[a-zA-Z_$][a-zA-Z0-9_$]*([.][a-zA-Z_$][a-zA-Z0-9_$]*)*" String keyReg = "[Pp][Ee][Rr][Mm][Ii][Ss][Ss][Ii][Oo][Nn]="; String keyStr = "permission="; String reg = keyReg + "[a-zA-Z_$][a-zA-Z0-9_$]*([.][a-zA-Z_$][a-zA-Z0-9_$]*)*"; Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(source); StringBuffer left = new StringBuffer(); while (matcher.find()) { String matched = matcher.group(); target.append(matched.replaceFirst(keyReg, keyStr)); // depends on control dependency: [while], data = [none] target.append(" "); // depends on control dependency: [while], data = [none] // delete the matched sequence matcher.appendReplacement(left, ""); // depends on control dependency: [while], data = [none] } matcher.appendTail(left); // depends on control dependency: [if], data = [none] source = left; // depends on control dependency: [if], data = [none] // obtain the "codebase=<URL>" options // the syntax of URL is too flexible, and here assumes that the // URL contains no space, comma(','), and semicolon(';'). That // also means those characters also could be used as separator // after codebase option. // However, the assumption is incorrect in some special situation // when the URL contains comma or semicolon keyReg = "[Cc][Oo][Dd][Ee][Bb][Aa][Ss][Ee]="; // depends on control dependency: [if], data = [none] keyStr = "codebase="; reg = keyReg + "[^, ;]*"; // depends on control dependency: [if], data = [none] pattern = Pattern.compile(reg); // depends on control dependency: [if], data = [none] matcher = pattern.matcher(source); // depends on control dependency: [if], data = [none] left = new StringBuffer(); // depends on control dependency: [if], data = [none] while (matcher.find()) { String matched = matcher.group(); target.append(matched.replaceFirst(keyReg, keyStr)); // depends on control dependency: [while], data = [none] target.append(" "); // depends on control dependency: [while], data = [none] // delete the matched sequence matcher.appendReplacement(left, ""); // depends on control dependency: [while], data = [none] } matcher.appendTail(left); // depends on control dependency: [if], data = [none] source = left; // depends on control dependency: [if], data = [none] // convert the rest to lower-case characters target.append(source.toString().toLowerCase(Locale.ENGLISH)); // depends on control dependency: [if], data = [none] return target.toString(); // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { private void initRecyclerViewItems() { rvMessages = (RecyclerView) findViewById(R.id.rvMessages); rvMessages.setLayoutManager(new LinearLayoutManager(this)); //creating your adapter, it could be a custom adapter as well RecyclerExampleAdapter adapter = new RecyclerExampleAdapter(this); //your test devices' ids String[] testDevicesIds = new String[]{getString(R.string.testDeviceID), AdRequest.DEVICE_ID_EMULATOR}; //when you'll be ready for release please use another ctor with admobReleaseUnitId instead. adapterWrapper = AdmobBannerRecyclerAdapterWrapper.builder(this) .setLimitOfAds(10) .setFirstAdIndex(2) .setNoOfDataBetweenAds(10) .setTestDeviceIds(testDevicesIds) .setAdapter(adapter) //Use the following for the default Wrapping behaviour // .setAdViewWrappingStrategy(new BannerAdViewWrappingStrategy()) // Or implement your own custom wrapping behaviour: .setAdViewWrappingStrategy(new BannerAdViewWrappingStrategyBase() { @NonNull @Override protected ViewGroup getAdViewWrapper(ViewGroup parent) { return (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(R.layout.native_express_ad_container, parent, false); } @Override protected void recycleAdViewWrapper(@NonNull ViewGroup wrapper, @NonNull AdView ad) { //get the view which directly will contain ad ViewGroup container = (ViewGroup) wrapper.findViewById(R.id.ad_container); //iterating through all children of the container view and remove the first occured {@link NativeExpressAdView}. It could be different with {@param ad}!!!*//* for (int i = 0; i < container.getChildCount(); i++) { View v = container.getChildAt(i); if (v instanceof AdView) { container.removeViewAt(i); break; } } } @Override protected void addAdViewToWrapper(@NonNull ViewGroup wrapper, @NonNull AdView ad) { //get the view which directly will contain ad ViewGroup container = (ViewGroup) wrapper.findViewById(R.id.ad_container); //add the {@param ad} directly to the end of container*//* container.addView(ad); } }) .build(); rvMessages.setAdapter(adapterWrapper); // setting an AdmobBannerRecyclerAdapterWrapper to a RecyclerView //use the following commented block to use a grid layout with spanning ad blocks GridLayoutManager mLayoutManager = new GridLayoutManager(this, 2); mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { if(adapterWrapper.getItemViewType(position) == adapterWrapper.getViewTypeAdBanner()) return 2; else return 1; } }); rvMessages.setLayoutManager(mLayoutManager); //preparing the collection of data final String sItem = "item #"; ArrayList<String> lst = new ArrayList<String>(100); for(int i=1;i<=100;i++) lst.add(sItem.concat(Integer.toString(i))); //adding a collection of data to your adapter and rising the data set changed event adapter.addAll(lst); adapter.notifyDataSetChanged(); } }
public class class_name { private void initRecyclerViewItems() { rvMessages = (RecyclerView) findViewById(R.id.rvMessages); rvMessages.setLayoutManager(new LinearLayoutManager(this)); //creating your adapter, it could be a custom adapter as well RecyclerExampleAdapter adapter = new RecyclerExampleAdapter(this); //your test devices' ids String[] testDevicesIds = new String[]{getString(R.string.testDeviceID), AdRequest.DEVICE_ID_EMULATOR}; //when you'll be ready for release please use another ctor with admobReleaseUnitId instead. adapterWrapper = AdmobBannerRecyclerAdapterWrapper.builder(this) .setLimitOfAds(10) .setFirstAdIndex(2) .setNoOfDataBetweenAds(10) .setTestDeviceIds(testDevicesIds) .setAdapter(adapter) //Use the following for the default Wrapping behaviour // .setAdViewWrappingStrategy(new BannerAdViewWrappingStrategy()) // Or implement your own custom wrapping behaviour: .setAdViewWrappingStrategy(new BannerAdViewWrappingStrategyBase() { @NonNull @Override protected ViewGroup getAdViewWrapper(ViewGroup parent) { return (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(R.layout.native_express_ad_container, parent, false); } @Override protected void recycleAdViewWrapper(@NonNull ViewGroup wrapper, @NonNull AdView ad) { //get the view which directly will contain ad ViewGroup container = (ViewGroup) wrapper.findViewById(R.id.ad_container); //iterating through all children of the container view and remove the first occured {@link NativeExpressAdView}. It could be different with {@param ad}!!!*//* for (int i = 0; i < container.getChildCount(); i++) { View v = container.getChildAt(i); if (v instanceof AdView) { container.removeViewAt(i); // depends on control dependency: [if], data = [none] break; } } } @Override protected void addAdViewToWrapper(@NonNull ViewGroup wrapper, @NonNull AdView ad) { //get the view which directly will contain ad ViewGroup container = (ViewGroup) wrapper.findViewById(R.id.ad_container); //add the {@param ad} directly to the end of container*//* container.addView(ad); } }) .build(); rvMessages.setAdapter(adapterWrapper); // setting an AdmobBannerRecyclerAdapterWrapper to a RecyclerView //use the following commented block to use a grid layout with spanning ad blocks GridLayoutManager mLayoutManager = new GridLayoutManager(this, 2); mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { if(adapterWrapper.getItemViewType(position) == adapterWrapper.getViewTypeAdBanner()) return 2; else return 1; } }); rvMessages.setLayoutManager(mLayoutManager); //preparing the collection of data final String sItem = "item #"; ArrayList<String> lst = new ArrayList<String>(100); for(int i=1;i<=100;i++) lst.add(sItem.concat(Integer.toString(i))); //adding a collection of data to your adapter and rising the data set changed event adapter.addAll(lst); adapter.notifyDataSetChanged(); } }
public class class_name { private DateFormat getDateFormat(Locale locale) { // PENDING(craigmcc) - Implement pooling if needed for performance? if (pattern == null && type == null) { throw new IllegalArgumentException("Either pattern or type must" + " be specified."); } DateFormat df; if (pattern != null) { df = new SimpleDateFormat(pattern, locale); } else if (type.equals("both")) { df = DateFormat.getDateTimeInstance (getStyle(dateStyle), getStyle(timeStyle), locale); } else if (type.equals("date")) { df = DateFormat.getDateInstance(getStyle(dateStyle), locale); } else if (type.equals("time")) { df = DateFormat.getTimeInstance(getStyle(timeStyle), locale); } else { // PENDING(craigmcc) - i18n throw new IllegalArgumentException("Invalid type: " + type); } df.setLenient(false); return (df); } }
public class class_name { private DateFormat getDateFormat(Locale locale) { // PENDING(craigmcc) - Implement pooling if needed for performance? if (pattern == null && type == null) { throw new IllegalArgumentException("Either pattern or type must" + " be specified."); } DateFormat df; if (pattern != null) { df = new SimpleDateFormat(pattern, locale); // depends on control dependency: [if], data = [(pattern] } else if (type.equals("both")) { df = DateFormat.getDateTimeInstance (getStyle(dateStyle), getStyle(timeStyle), locale); // depends on control dependency: [if], data = [none] } else if (type.equals("date")) { df = DateFormat.getDateInstance(getStyle(dateStyle), locale); // depends on control dependency: [if], data = [none] } else if (type.equals("time")) { df = DateFormat.getTimeInstance(getStyle(timeStyle), locale); // depends on control dependency: [if], data = [none] } else { // PENDING(craigmcc) - i18n throw new IllegalArgumentException("Invalid type: " + type); } df.setLenient(false); return (df); } }
public class class_name { @SuppressWarnings("unchecked") public DataMapper<Object, DBObject> getDataMapper(Class<?> domainObjectClass) { if (additionalDataMappers != null) { for (DataMapper<Object, DBObject> each : additionalDataMappers) { if (each.canMapToData(domainObjectClass)) { return each; } } } if (dataMapper.canMapToData(domainObjectClass)) { return (DataMapper<Object, DBObject>) dataMapper; } // no matching return null; } }
public class class_name { @SuppressWarnings("unchecked") public DataMapper<Object, DBObject> getDataMapper(Class<?> domainObjectClass) { if (additionalDataMappers != null) { for (DataMapper<Object, DBObject> each : additionalDataMappers) { if (each.canMapToData(domainObjectClass)) { return each; // depends on control dependency: [if], data = [none] } } } if (dataMapper.canMapToData(domainObjectClass)) { return (DataMapper<Object, DBObject>) dataMapper; // depends on control dependency: [if], data = [none] } // no matching return null; } }
public class class_name { @Override public boolean retainAll(IntSet c) { modCount++; if (isEmpty() || c == this) { return false; } if (c == null || c.isEmpty()) { clear(); return true; } ConciseSet other = convert(c); if (other.size == 1) { if (contains(other.last)) { if (size == 1) { return false; } return replaceWith(convert(other.last)); } clear(); return true; } return replaceWith(performOperation(other, Operator.AND)); } }
public class class_name { @Override public boolean retainAll(IntSet c) { modCount++; if (isEmpty() || c == this) { return false; // depends on control dependency: [if], data = [none] } if (c == null || c.isEmpty()) { clear(); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } ConciseSet other = convert(c); if (other.size == 1) { if (contains(other.last)) { if (size == 1) { return false; // depends on control dependency: [if], data = [none] } return replaceWith(convert(other.last)); // depends on control dependency: [if], data = [none] } clear(); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } return replaceWith(performOperation(other, Operator.AND)); } }
public class class_name { public DataSetIterator getTrainIterator() { return new DataSetIterator() { @Override public DataSet next(int i) { throw new UnsupportedOperationException(); } @Override public List<String> getLabels() { return backedIterator.getLabels(); } @Override public int inputColumns() { return backedIterator.inputColumns(); } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public int totalOutcomes() { return backedIterator.totalOutcomes(); } @Override public boolean resetSupported() { return backedIterator.resetSupported(); } @Override public boolean asyncSupported() { return backedIterator.asyncSupported(); } @Override public void reset() { resetPending.set(true); } @Override public int batch() { return backedIterator.batch(); } @Override public void setPreProcessor(DataSetPreProcessor dataSetPreProcessor) { backedIterator.setPreProcessor(dataSetPreProcessor); } @Override public DataSetPreProcessor getPreProcessor() { return backedIterator.getPreProcessor(); } @Override public boolean hasNext() { if (resetPending.get()) { if (resetSupported()) { backedIterator.reset(); counter.set(0); resetPending.set(false); } else throw new UnsupportedOperationException("Reset isn't supported by underlying iterator"); } val state = backedIterator.hasNext(); if (state && counter.get() < numTrain) return true; else return false; } @Override public DataSet next() { counter.incrementAndGet(); val p = backedIterator.next(); if (counter.get() == 1 && firstTrain == null) { // first epoch ever, we'll save first dataset and will use it to check for equality later firstTrain = p.copy(); firstTrain.detach(); } else if (counter.get() == 1) { // epoch > 1, comparing first dataset to previously stored dataset. they should be equal int cnt = 0; if (!p.getFeatures().equalsWithEps(firstTrain.getFeatures(), 1e-5)) throw new ND4JIllegalStateException("First examples do not match. Randomization was used?"); } return p; } }; } }
public class class_name { public DataSetIterator getTrainIterator() { return new DataSetIterator() { @Override public DataSet next(int i) { throw new UnsupportedOperationException(); } @Override public List<String> getLabels() { return backedIterator.getLabels(); } @Override public int inputColumns() { return backedIterator.inputColumns(); } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public int totalOutcomes() { return backedIterator.totalOutcomes(); } @Override public boolean resetSupported() { return backedIterator.resetSupported(); } @Override public boolean asyncSupported() { return backedIterator.asyncSupported(); } @Override public void reset() { resetPending.set(true); } @Override public int batch() { return backedIterator.batch(); } @Override public void setPreProcessor(DataSetPreProcessor dataSetPreProcessor) { backedIterator.setPreProcessor(dataSetPreProcessor); } @Override public DataSetPreProcessor getPreProcessor() { return backedIterator.getPreProcessor(); } @Override public boolean hasNext() { if (resetPending.get()) { if (resetSupported()) { backedIterator.reset(); // depends on control dependency: [if], data = [none] counter.set(0); // depends on control dependency: [if], data = [none] resetPending.set(false); // depends on control dependency: [if], data = [none] } else throw new UnsupportedOperationException("Reset isn't supported by underlying iterator"); } val state = backedIterator.hasNext(); if (state && counter.get() < numTrain) return true; else return false; } @Override public DataSet next() { counter.incrementAndGet(); val p = backedIterator.next(); if (counter.get() == 1 && firstTrain == null) { // first epoch ever, we'll save first dataset and will use it to check for equality later firstTrain = p.copy(); // depends on control dependency: [if], data = [none] firstTrain.detach(); // depends on control dependency: [if], data = [none] } else if (counter.get() == 1) { // epoch > 1, comparing first dataset to previously stored dataset. they should be equal int cnt = 0; if (!p.getFeatures().equalsWithEps(firstTrain.getFeatures(), 1e-5)) throw new ND4JIllegalStateException("First examples do not match. Randomization was used?"); } return p; } }; } }
public class class_name { private static Object wrap(Object o) { if (o == null) { return JSONObject.NULL; } if (o instanceof JSONArray || o instanceof JSONObject) { return o; } if (o.equals(JSONObject.NULL)) { return o; } try { if (o instanceof Collection) { return new JSONArray((Collection) o); } else if (o.getClass().isArray()) { final int length = Array.getLength(o); JSONArray array = new JSONArray(); for (int i = 0; i < length; ++i) { array.put(wrap(Array.get(array, i))); } return array; } if (o instanceof Map) { //noinspection unchecked return toJsonObject((Map) o); } if (o instanceof Boolean || o instanceof Byte || o instanceof Character || o instanceof Double || o instanceof Float || o instanceof Integer || o instanceof Long || o instanceof Short || o instanceof String) { return o; } // Deviate from original implementation and return the String representation of the object // regardless of package. return o.toString(); } catch (Exception ignored) { } // Deviate from original and return JSONObject.NULL instead of null. return JSONObject.NULL; } }
public class class_name { private static Object wrap(Object o) { if (o == null) { return JSONObject.NULL; // depends on control dependency: [if], data = [none] } if (o instanceof JSONArray || o instanceof JSONObject) { return o; // depends on control dependency: [if], data = [none] } if (o.equals(JSONObject.NULL)) { return o; // depends on control dependency: [if], data = [none] } try { if (o instanceof Collection) { return new JSONArray((Collection) o); // depends on control dependency: [if], data = [none] } else if (o.getClass().isArray()) { final int length = Array.getLength(o); JSONArray array = new JSONArray(); for (int i = 0; i < length; ++i) { array.put(wrap(Array.get(array, i))); // depends on control dependency: [for], data = [i] } return array; // depends on control dependency: [if], data = [none] } if (o instanceof Map) { //noinspection unchecked return toJsonObject((Map) o); // depends on control dependency: [if], data = [none] } if (o instanceof Boolean || o instanceof Byte || o instanceof Character || o instanceof Double || o instanceof Float || o instanceof Integer || o instanceof Long || o instanceof Short || o instanceof String) { return o; // depends on control dependency: [if], data = [none] } // Deviate from original implementation and return the String representation of the object // regardless of package. return o.toString(); // depends on control dependency: [try], data = [none] } catch (Exception ignored) { } // depends on control dependency: [catch], data = [none] // Deviate from original and return JSONObject.NULL instead of null. return JSONObject.NULL; } }
public class class_name { @Override public Long getValue() { final JobStatus status = eg.getState(); if (status == JobStatus.RUNNING) { // running right now - report the uptime final long runningTimestamp = eg.getStatusTimestamp(JobStatus.RUNNING); // we use 'Math.max' here to avoid negative timestamps when clocks change return Math.max(System.currentTimeMillis() - runningTimestamp, 0); } else if (status.isTerminalState()) { // not running any more -> finished or not on leader return NO_LONGER_RUNNING; } else { // not yet running or not up at the moment return 0L; } } }
public class class_name { @Override public Long getValue() { final JobStatus status = eg.getState(); if (status == JobStatus.RUNNING) { // running right now - report the uptime final long runningTimestamp = eg.getStatusTimestamp(JobStatus.RUNNING); // we use 'Math.max' here to avoid negative timestamps when clocks change return Math.max(System.currentTimeMillis() - runningTimestamp, 0); // depends on control dependency: [if], data = [none] } else if (status.isTerminalState()) { // not running any more -> finished or not on leader return NO_LONGER_RUNNING; // depends on control dependency: [if], data = [none] } else { // not yet running or not up at the moment return 0L; // depends on control dependency: [if], data = [none] } } }
public class class_name { static void remote_exec( AutoBuffer ab ) { long lo = ab.get8(0), hi = ab._size >= 16 ? ab.get8(8) : 0; final int task = ab.getTask(); final int flag = ab.getFlag(); assert flag==CLIENT_UDP_SEND || flag==CLIENT_TCP_SEND; // Client-side send // Atomically record an instance of this task, one-time-only replacing a // null with an RPCCall, a placeholder while we work on a proper response - // and it serves to let us discard dup UDP requests. RPCCall old = ab._h2o.has_task(task); // This is a UDP packet requesting an answer back for a request sent via // TCP but the UDP packet has arrived ahead of the TCP. Just drop the UDP // and wait for the TCP to appear. if( old == null && flag == CLIENT_TCP_SEND ) { Log.warn("got tcp with existing task #, FROM " + ab._h2o.toString() + " AB: " /* + UDP.printx16(lo,hi)*/); assert !ab.hasTCP():"ERROR: got tcp with existing task #, FROM " + ab._h2o.toString() + " AB: " /* + UDP.printx16(lo,hi)*/; // All the resends should be UDP only // DROP PACKET } else if( old == null ) { // New task? RPCCall rpc; try { // Read the DTask Right Now. If we are the TCPReceiver thread, then we // are reading in that thread... and thus TCP reads are single-threaded. rpc = new RPCCall(ab.get(water.DTask.class),ab._h2o,task); } catch( AutoBuffer.AutoBufferException e ) { // Here we assume it's a TCP fail on read - and ignore the remote_exec // request. The caller will send it again. NOTE: this case is // indistinguishable from a broken short-writer/long-reader bug, except // that we'll re-send endlessly and fail endlessly. Log.info("Network congestion OR short-writer/long-reader: TCP "+e._ioe.getMessage()+", AB="+ab+", ignoring partial send"); ab.drainClose(); return; } RPCCall rpc2 = ab._h2o.record_task(rpc); if( rpc2==null ) { // Atomically insert (to avoid double-work) if( rpc._dt instanceof MRTask && rpc._dt.logVerbose() ) Log.debug("Start remote task#"+task+" "+rpc._dt.getClass()+" from "+ab._h2o); H2O.submitTask(rpc); // And execute! } else { // Else lost the task-insertion race if(ab.hasTCP()) ab.drainClose(); // DROP PACKET } } else if( !old._computedAndReplied) { // This packet has not been fully computed. Hence it's still a work-in- // progress locally. We have no answer to reply but we do not want to // re-offer the packet for repeated work. Send back a NACK, letting the // client know we're Working On It assert !ab.hasTCP():"got tcp with existing task #, FROM " + ab._h2o.toString() + " AB: " + UDP.printx16(lo,hi) + ", position = " + ab._bb.position(); ab.clearForWriting(udp.nack._prior).putTask(UDP.udp.nack.ordinal(), task); // DROP PACKET } else { // This is an old re-send of the same thing we've answered to before. // Send back the same old answer ACK. If we sent via TCP before, then // we know the answer got there so just send a control-ACK back. If we // sent via UDP, resend the whole answer. if(ab.hasTCP()) { Log.warn("got tcp with existing task #, FROM " + ab._h2o.toString() + " AB: " + UDP.printx16(lo,hi)); // All the resends should be UDP only ab.drainClose(); } if(old._dt != null) { // already ackacked ++old._ackResendCnt; if (old._ackResendCnt % 10 == 0) Log.err("Possibly broken network, can not send ack through, got " + old._ackResendCnt + " for task # " + old._tsknum + ", dt == null?" + (old._dt == null)); old.resend_ack(); } } ab.close(); } }
public class class_name { static void remote_exec( AutoBuffer ab ) { long lo = ab.get8(0), hi = ab._size >= 16 ? ab.get8(8) : 0; final int task = ab.getTask(); final int flag = ab.getFlag(); assert flag==CLIENT_UDP_SEND || flag==CLIENT_TCP_SEND; // Client-side send // Atomically record an instance of this task, one-time-only replacing a // null with an RPCCall, a placeholder while we work on a proper response - // and it serves to let us discard dup UDP requests. RPCCall old = ab._h2o.has_task(task); // This is a UDP packet requesting an answer back for a request sent via // TCP but the UDP packet has arrived ahead of the TCP. Just drop the UDP // and wait for the TCP to appear. if( old == null && flag == CLIENT_TCP_SEND ) { Log.warn("got tcp with existing task #, FROM " + ab._h2o.toString() + " AB: " /* + UDP.printx16(lo,hi)*/); // depends on control dependency: [if], data = [none] assert !ab.hasTCP():"ERROR: got tcp with existing task #, FROM " + ab._h2o.toString() + " AB: " /* + UDP.printx16(lo,hi)*/; // All the resends should be UDP only // depends on control dependency: [if], data = [none] // DROP PACKET } else if( old == null ) { // New task? RPCCall rpc; try { // Read the DTask Right Now. If we are the TCPReceiver thread, then we // are reading in that thread... and thus TCP reads are single-threaded. rpc = new RPCCall(ab.get(water.DTask.class),ab._h2o,task); // depends on control dependency: [try], data = [none] } catch( AutoBuffer.AutoBufferException e ) { // Here we assume it's a TCP fail on read - and ignore the remote_exec // request. The caller will send it again. NOTE: this case is // indistinguishable from a broken short-writer/long-reader bug, except // that we'll re-send endlessly and fail endlessly. Log.info("Network congestion OR short-writer/long-reader: TCP "+e._ioe.getMessage()+", AB="+ab+", ignoring partial send"); ab.drainClose(); return; } // depends on control dependency: [catch], data = [none] RPCCall rpc2 = ab._h2o.record_task(rpc); if( rpc2==null ) { // Atomically insert (to avoid double-work) if( rpc._dt instanceof MRTask && rpc._dt.logVerbose() ) Log.debug("Start remote task#"+task+" "+rpc._dt.getClass()+" from "+ab._h2o); H2O.submitTask(rpc); // And execute! // depends on control dependency: [if], data = [none] } else { // Else lost the task-insertion race if(ab.hasTCP()) ab.drainClose(); // DROP PACKET } } else if( !old._computedAndReplied) { // This packet has not been fully computed. Hence it's still a work-in- // progress locally. We have no answer to reply but we do not want to // re-offer the packet for repeated work. Send back a NACK, letting the // client know we're Working On It assert !ab.hasTCP():"got tcp with existing task #, FROM " + ab._h2o.toString() + " AB: " + UDP.printx16(lo,hi) + ", position = " + ab._bb.position(); // depends on control dependency: [if], data = [none] ab.clearForWriting(udp.nack._prior).putTask(UDP.udp.nack.ordinal(), task); // depends on control dependency: [if], data = [none] // DROP PACKET } else { // This is an old re-send of the same thing we've answered to before. // Send back the same old answer ACK. If we sent via TCP before, then // we know the answer got there so just send a control-ACK back. If we // sent via UDP, resend the whole answer. if(ab.hasTCP()) { Log.warn("got tcp with existing task #, FROM " + ab._h2o.toString() + " AB: " + UDP.printx16(lo,hi)); // All the resends should be UDP only // depends on control dependency: [if], data = [none] ab.drainClose(); // depends on control dependency: [if], data = [none] } if(old._dt != null) { // already ackacked ++old._ackResendCnt; // depends on control dependency: [if], data = [none] if (old._ackResendCnt % 10 == 0) Log.err("Possibly broken network, can not send ack through, got " + old._ackResendCnt + " for task # " + old._tsknum + ", dt == null?" + (old._dt == null)); old.resend_ack(); // depends on control dependency: [if], data = [none] } } ab.close(); } }
public class class_name { @Override public void fill(ClassModel classModel) { /** * FreeMarker function availlable inside templates to add dependencies * for the class. */ class AddDependencies implements TemplateMethodModelEx { ClassType model; public AddDependencies(ClassType model) { this.model = model; } @Override @SuppressWarnings("rawtypes") public Object exec(List arguments) throws TemplateModelException { if (arguments.size() < 1) { throw new TemplateModelException("addDependencies need at least one parameter."); } for (Object argument : arguments) { Object dependency = DeepUnwrap.unwrap((TemplateModel) argument); if (dependency instanceof String) { addDependency(context.getClassModel((String) dependency)); } else if (dependency instanceof ClassModel) { addDependency((ClassModel) dependency); } else if (dependency instanceof Collection) { for (Object depend : (Collection) dependency) { addDependency((ClassModel) depend); } } else if (dependency != null) { throw new TemplateModelException( "addDependencies arguments must be a class name, a ClassModel instance or a Collection of ClassModels."); } } return ""; } private void addDependency(ClassModel classModel) { model.getDependencies().add(classModel); } } /** * FreeMarker function availlable inside templates to add includes file * for the class. */ class AddIncludes implements TemplateMethodModelEx { ClassType model; public AddIncludes(ClassType model) { this.model = model; } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public Object exec(List arguments) throws TemplateModelException { if (arguments.size() < 1) { throw new TemplateModelException("addIncludes need at least one parameter."); } for (Object argument : arguments) { Object include = DeepUnwrap.unwrap((TemplateModel) argument); if (include instanceof String) { model.getIncludes().add((String) include); } else if (include instanceof Collection) { model.getIncludes().addAll((Collection) include); } else if (include != null) { throw new TemplateModelException("addIncludes arguments must be a String or a Collection of Strings."); } } return ""; } } ClassType typeModel = classModel.getType(); Class<?> clazz = typeModel.getClazz(); StringBuilder fullName = new StringBuilder(); String shortName = ""; String sep = ""; for (String namespace : mappings.getNamespace(clazz)) { fullName.append(sep).append(namespace); sep = "::"; shortName = namespace; } typeModel.setCppFullName(fullName.toString()); typeModel.setCppShortName(shortName); typeModel.setOwner(typeModel.isIsInnerClass() ? context.getClassModel(clazz.getDeclaringClass()) : classModel); if (clazz.isArray()) { typeModel.setInnerType(context.getClassModel(clazz.getComponentType())); Class<?> finalClazz = clazz; while (finalClazz.getComponentType() != null) { finalClazz = finalClazz.getComponentType(); } typeModel.setFinalInnerType(context.getClassModel(finalClazz)); } typeModel.setJavaSignature(Datatype.getJavaSignature(clazz)); typeModel.setJniSignature(Datatype.getJNISignature(clazz)); typeModel.setJniMethodName(Datatype.getJNIMethodName(clazz)); typeModel.setAddIncludes(new AddIncludes(typeModel)); typeModel.setAddDependencies(new AddDependencies(typeModel)); } }
public class class_name { @Override public void fill(ClassModel classModel) { /** * FreeMarker function availlable inside templates to add dependencies * for the class. */ class AddDependencies implements TemplateMethodModelEx { ClassType model; public AddDependencies(ClassType model) { this.model = model; } @Override @SuppressWarnings("rawtypes") public Object exec(List arguments) throws TemplateModelException { if (arguments.size() < 1) { throw new TemplateModelException("addDependencies need at least one parameter."); } for (Object argument : arguments) { Object dependency = DeepUnwrap.unwrap((TemplateModel) argument); if (dependency instanceof String) { addDependency(context.getClassModel((String) dependency)); // depends on control dependency: [if], data = [none] } else if (dependency instanceof ClassModel) { addDependency((ClassModel) dependency); // depends on control dependency: [if], data = [none] } else if (dependency instanceof Collection) { for (Object depend : (Collection) dependency) { addDependency((ClassModel) depend); // depends on control dependency: [for], data = [depend] } } else if (dependency != null) { throw new TemplateModelException( "addDependencies arguments must be a class name, a ClassModel instance or a Collection of ClassModels."); } } return ""; } private void addDependency(ClassModel classModel) { model.getDependencies().add(classModel); } } /** * FreeMarker function availlable inside templates to add includes file * for the class. */ class AddIncludes implements TemplateMethodModelEx { ClassType model; public AddIncludes(ClassType model) { this.model = model; } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public Object exec(List arguments) throws TemplateModelException { if (arguments.size() < 1) { throw new TemplateModelException("addIncludes need at least one parameter."); } for (Object argument : arguments) { Object include = DeepUnwrap.unwrap((TemplateModel) argument); if (include instanceof String) { model.getIncludes().add((String) include); } else if (include instanceof Collection) { model.getIncludes().addAll((Collection) include); } else if (include != null) { throw new TemplateModelException("addIncludes arguments must be a String or a Collection of Strings."); } } return ""; } } ClassType typeModel = classModel.getType(); Class<?> clazz = typeModel.getClazz(); StringBuilder fullName = new StringBuilder(); String shortName = ""; String sep = ""; for (String namespace : mappings.getNamespace(clazz)) { fullName.append(sep).append(namespace); sep = "::"; shortName = namespace; } typeModel.setCppFullName(fullName.toString()); typeModel.setCppShortName(shortName); typeModel.setOwner(typeModel.isIsInnerClass() ? context.getClassModel(clazz.getDeclaringClass()) : classModel); if (clazz.isArray()) { typeModel.setInnerType(context.getClassModel(clazz.getComponentType())); Class<?> finalClazz = clazz; while (finalClazz.getComponentType() != null) { finalClazz = finalClazz.getComponentType(); } typeModel.setFinalInnerType(context.getClassModel(finalClazz)); } typeModel.setJavaSignature(Datatype.getJavaSignature(clazz)); typeModel.setJniSignature(Datatype.getJNISignature(clazz)); typeModel.setJniMethodName(Datatype.getJNIMethodName(clazz)); typeModel.setAddIncludes(new AddIncludes(typeModel)); typeModel.setAddDependencies(new AddDependencies(typeModel)); } }
public class class_name { float getFloat(int bp) { DataInputStream bufin = new DataInputStream(new ByteArrayInputStream(buf, bp, 4)); try { return bufin.readFloat(); } catch (IOException e) { throw new AssertionError(e); } } }
public class class_name { float getFloat(int bp) { DataInputStream bufin = new DataInputStream(new ByteArrayInputStream(buf, bp, 4)); try { return bufin.readFloat(); // depends on control dependency: [try], data = [none] } catch (IOException e) { throw new AssertionError(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static synchronized CouchbaseConnector getInstance(BaseCouchbaseConfig config, List<Stage.ConfigIssue> issues, Stage.Context context) { Map<String, Object> runnerSharedMap = context.getStageRunnerSharedMap(); if(runnerSharedMap.containsKey(INSTANCE)) { LOG.debug("Using existing instance of CouchbaseConnector"); } else { LOG.debug("CouchbaseConnector not yet instantiated. Creating new instance"); validateConfig(config, issues, context); if(issues.isEmpty()) { runnerSharedMap.put(INSTANCE, new CouchbaseConnector(config, issues, context)); } } return (CouchbaseConnector) runnerSharedMap.get(INSTANCE); } }
public class class_name { public static synchronized CouchbaseConnector getInstance(BaseCouchbaseConfig config, List<Stage.ConfigIssue> issues, Stage.Context context) { Map<String, Object> runnerSharedMap = context.getStageRunnerSharedMap(); if(runnerSharedMap.containsKey(INSTANCE)) { LOG.debug("Using existing instance of CouchbaseConnector"); // depends on control dependency: [if], data = [none] } else { LOG.debug("CouchbaseConnector not yet instantiated. Creating new instance"); // depends on control dependency: [if], data = [none] validateConfig(config, issues, context); // depends on control dependency: [if], data = [none] if(issues.isEmpty()) { runnerSharedMap.put(INSTANCE, new CouchbaseConnector(config, issues, context)); // depends on control dependency: [if], data = [none] } } return (CouchbaseConnector) runnerSharedMap.get(INSTANCE); } }
public class class_name { private boolean isValidReturnCode(String returnCode) { if (CmsStringUtil.isEmptyOrWhitespaceOnly(returnCode)) { return false; } int pos = returnCode.indexOf(":"); if (pos > 0) { return CmsUUID.isValidUUID(returnCode.substring(0, pos)) && CmsUUID.isValidUUID(returnCode.substring(pos + 1)); } else { return CmsUUID.isValidUUID(returnCode); } } }
public class class_name { private boolean isValidReturnCode(String returnCode) { if (CmsStringUtil.isEmptyOrWhitespaceOnly(returnCode)) { return false; // depends on control dependency: [if], data = [none] } int pos = returnCode.indexOf(":"); if (pos > 0) { return CmsUUID.isValidUUID(returnCode.substring(0, pos)) && CmsUUID.isValidUUID(returnCode.substring(pos + 1)); // depends on control dependency: [if], data = [none] } else { return CmsUUID.isValidUUID(returnCode); // depends on control dependency: [if], data = [none] } } }
public class class_name { private LinkedList<Diff> diff_lineMode(String text1, String text2, long deadline) { // Scan the text on a line-by-line basis first. LinesToCharsResult b = diff_linesToChars(text1, text2); text1 = b.chars1; text2 = b.chars2; List<String> linearray = b.lineArray; LinkedList<Diff> diffs = diff_main(text1, text2, false, deadline); // Convert the diff back to original text. diff_charsToLines(diffs, linearray); // Eliminate freak matches (e.g. blank lines) diff_cleanupSemantic(diffs); // Rediff any replacement blocks, this time character-by-character. // Add a dummy entry at the end. diffs.add(new Diff(Operation.EQUAL, "")); int count_delete = 0; int count_insert = 0; String text_delete = ""; String text_insert = ""; ListIterator<Diff> pointer = diffs.listIterator(); Diff thisDiff = pointer.next(); while (thisDiff != null) { switch (thisDiff.operation) { case INSERT: count_insert++; text_insert += thisDiff.text; break; case DELETE: count_delete++; text_delete += thisDiff.text; break; case EQUAL: // Upon reaching an equality, check for prior redundancies. if (count_delete >= 1 && count_insert >= 1) { // Delete the offending records and add the merged ones. pointer.previous(); for (int j = 0; j < count_delete + count_insert; j++) { pointer.previous(); pointer.remove(); } for (Diff newDiff : diff_main(text_delete, text_insert, false, deadline)) { pointer.add(newDiff); } } count_insert = 0; count_delete = 0; text_delete = ""; text_insert = ""; break; } thisDiff = pointer.hasNext() ? pointer.next() : null; } diffs.removeLast(); // Remove the dummy entry at the end. return diffs; } }
public class class_name { private LinkedList<Diff> diff_lineMode(String text1, String text2, long deadline) { // Scan the text on a line-by-line basis first. LinesToCharsResult b = diff_linesToChars(text1, text2); text1 = b.chars1; text2 = b.chars2; List<String> linearray = b.lineArray; LinkedList<Diff> diffs = diff_main(text1, text2, false, deadline); // Convert the diff back to original text. diff_charsToLines(diffs, linearray); // Eliminate freak matches (e.g. blank lines) diff_cleanupSemantic(diffs); // Rediff any replacement blocks, this time character-by-character. // Add a dummy entry at the end. diffs.add(new Diff(Operation.EQUAL, "")); int count_delete = 0; int count_insert = 0; String text_delete = ""; String text_insert = ""; ListIterator<Diff> pointer = diffs.listIterator(); Diff thisDiff = pointer.next(); while (thisDiff != null) { switch (thisDiff.operation) { case INSERT: count_insert++; text_insert += thisDiff.text; break; case DELETE: count_delete++; text_delete += thisDiff.text; break; case EQUAL: // Upon reaching an equality, check for prior redundancies. if (count_delete >= 1 && count_insert >= 1) { // Delete the offending records and add the merged ones. pointer.previous(); // depends on control dependency: [if], data = [none] for (int j = 0; j < count_delete + count_insert; j++) { pointer.previous(); // depends on control dependency: [for], data = [none] pointer.remove(); // depends on control dependency: [for], data = [none] } for (Diff newDiff : diff_main(text_delete, text_insert, false, deadline)) { pointer.add(newDiff); // depends on control dependency: [for], data = [newDiff] } } count_insert = 0; count_delete = 0; text_delete = ""; text_insert = ""; break; } thisDiff = pointer.hasNext() ? pointer.next() : null; // depends on control dependency: [while], data = [none] } diffs.removeLast(); // Remove the dummy entry at the end. return diffs; } }
public class class_name { @Override public void decode() { Object message; int size = readBuffer.remaining(); while (readBuffer.hasRemaining()) { try { message = decoder.decode(readBuffer, this); if (message == null) { break; } else { if (statistics.isStatistics()) { statistics .statisticsRead(size - readBuffer.remaining()); size = readBuffer.remaining(); } } dispatchReceivedMessage(message); } catch (Exception e) { onException(e); log.error("Decode error", e); super.close(); break; } } } }
public class class_name { @Override public void decode() { Object message; int size = readBuffer.remaining(); while (readBuffer.hasRemaining()) { try { message = decoder.decode(readBuffer, this); // depends on control dependency: [try], data = [none] if (message == null) { break; } else { if (statistics.isStatistics()) { statistics .statisticsRead(size - readBuffer.remaining()); // depends on control dependency: [if], data = [none] size = readBuffer.remaining(); // depends on control dependency: [if], data = [none] } } dispatchReceivedMessage(message); // depends on control dependency: [try], data = [none] } catch (Exception e) { onException(e); log.error("Decode error", e); super.close(); break; } // depends on control dependency: [catch], data = [none] } } }
public class class_name { public void init(String webAppRfsPath, String servletMapping, String defaultWebApplication) { try { // explicit set to null to overwrite exiting values from session m_availableModules = null; m_fullDatabaseKey = null; m_databaseKey = null; m_databaseKeys = null; m_databaseProperties = null; m_configuration = null; m_installModules = null; m_moduleDependencies = null; m_sortedDatabaseKeys = null; m_moduleFilenames = null; if (servletMapping == null) { servletMapping = "/opencms/*"; } if (defaultWebApplication == null) { defaultWebApplication = "ROOT"; } m_servletMapping = servletMapping; m_defaultWebApplication = defaultWebApplication; setWebAppRfsPath(webAppRfsPath); m_errors = new ArrayList<String>(); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(webAppRfsPath)) { m_configuration = new CmsParameterConfiguration(m_configRfsPath + CmsSystemInfo.FILE_PROPERTIES); readDatabaseConfig(); } if (m_workplaceImportThread != null) { if (m_workplaceImportThread.isAlive()) { m_workplaceImportThread.kill(); } m_workplaceImportThread = null; m_newLoggingOffset = 0; m_oldLoggingOffset = 0; } } catch (Exception e) { e.printStackTrace(); m_errors.add(e.toString()); } } }
public class class_name { public void init(String webAppRfsPath, String servletMapping, String defaultWebApplication) { try { // explicit set to null to overwrite exiting values from session m_availableModules = null; // depends on control dependency: [try], data = [none] m_fullDatabaseKey = null; // depends on control dependency: [try], data = [none] m_databaseKey = null; // depends on control dependency: [try], data = [none] m_databaseKeys = null; // depends on control dependency: [try], data = [none] m_databaseProperties = null; // depends on control dependency: [try], data = [none] m_configuration = null; // depends on control dependency: [try], data = [none] m_installModules = null; // depends on control dependency: [try], data = [none] m_moduleDependencies = null; // depends on control dependency: [try], data = [none] m_sortedDatabaseKeys = null; // depends on control dependency: [try], data = [none] m_moduleFilenames = null; // depends on control dependency: [try], data = [none] if (servletMapping == null) { servletMapping = "/opencms/*"; // depends on control dependency: [if], data = [none] } if (defaultWebApplication == null) { defaultWebApplication = "ROOT"; // depends on control dependency: [if], data = [none] } m_servletMapping = servletMapping; // depends on control dependency: [try], data = [none] m_defaultWebApplication = defaultWebApplication; // depends on control dependency: [try], data = [none] setWebAppRfsPath(webAppRfsPath); // depends on control dependency: [try], data = [none] m_errors = new ArrayList<String>(); // depends on control dependency: [try], data = [none] if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(webAppRfsPath)) { m_configuration = new CmsParameterConfiguration(m_configRfsPath + CmsSystemInfo.FILE_PROPERTIES); // depends on control dependency: [if], data = [none] readDatabaseConfig(); // depends on control dependency: [if], data = [none] } if (m_workplaceImportThread != null) { if (m_workplaceImportThread.isAlive()) { m_workplaceImportThread.kill(); // depends on control dependency: [if], data = [none] } m_workplaceImportThread = null; // depends on control dependency: [if], data = [none] m_newLoggingOffset = 0; // depends on control dependency: [if], data = [none] m_oldLoggingOffset = 0; // depends on control dependency: [if], data = [none] } } catch (Exception e) { e.printStackTrace(); m_errors.add(e.toString()); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void setDefaultContentType(DefaultContentType value) { defaultContentType = value; if (defaultContentType != null) { setData(""); searchable = false; orderable = false; } } }
public class class_name { public void setDefaultContentType(DefaultContentType value) { defaultContentType = value; if (defaultContentType != null) { setData(""); // depends on control dependency: [if], data = [none] searchable = false; // depends on control dependency: [if], data = [none] orderable = false; // depends on control dependency: [if], data = [none] } } }
public class class_name { public Optional<ZipErrorCodes> zip() { try (FileOutputStream fos = new FileOutputStream(this.zipFile); ZipOutputStream zos = new ZipOutputStream(fos);) { if (!this.directoryToZip.exists()) { return Optional.of(ZipErrorCodes.DIRECTORY_TO_ZIP_DOES_NOT_EXIST); } if (!this.zipFile.exists()) { return Optional.of(ZipErrorCodes.ZIP_FILE_DOES_NOT_EXIST); } if (0 < this.zipLevel) { zos.setLevel(this.zipLevel); } else { zos.setLevel(9); } if (null != this.zipFileComment) { zos.setComment(this.zipFileComment); } if (0 < this.compressionMethod) { zos.setMethod(this.compressionMethod); } this.zipFiles(this.directoryToZip, zos); zos.flush(); zos.finish(); fos.flush(); } catch (IOException e) { log.log(Level.SEVERE, e.getLocalizedMessage(), e); return Optional.of(ZipErrorCodes.IO_ERROR); } return Optional.empty(); } }
public class class_name { public Optional<ZipErrorCodes> zip() { try (FileOutputStream fos = new FileOutputStream(this.zipFile); ZipOutputStream zos = new ZipOutputStream(fos);) { if (!this.directoryToZip.exists()) { return Optional.of(ZipErrorCodes.DIRECTORY_TO_ZIP_DOES_NOT_EXIST); // depends on control dependency: [if], data = [none] } if (!this.zipFile.exists()) { return Optional.of(ZipErrorCodes.ZIP_FILE_DOES_NOT_EXIST); // depends on control dependency: [if], data = [none] } if (0 < this.zipLevel) { zos.setLevel(this.zipLevel); // depends on control dependency: [if], data = [this.zipLevel)] } else { zos.setLevel(9); // depends on control dependency: [if], data = [none] } if (null != this.zipFileComment) { zos.setComment(this.zipFileComment); // depends on control dependency: [if], data = [this.zipFileComment)] } if (0 < this.compressionMethod) { zos.setMethod(this.compressionMethod); // depends on control dependency: [if], data = [this.compressionMethod)] } this.zipFiles(this.directoryToZip, zos); zos.flush(); zos.finish(); fos.flush(); } catch (IOException e) { log.log(Level.SEVERE, e.getLocalizedMessage(), e); return Optional.of(ZipErrorCodes.IO_ERROR); } return Optional.empty(); } }
public class class_name { public static float[][] toFloat(int[][] array) { float[][] n = new float[array.length][array[0].length]; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[0].length; j++) { n[i][j] = (float) array[i][j]; } } return n; } }
public class class_name { public static float[][] toFloat(int[][] array) { float[][] n = new float[array.length][array[0].length]; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[0].length; j++) { n[i][j] = (float) array[i][j]; // depends on control dependency: [for], data = [j] } } return n; } }
public class class_name { private Object readMetadataContentJdom( InvDataset dataset, Element mdataElement ) { Namespace catGenConfigNamespace = null; ArrayList catGenConfigList = new ArrayList(); // Get the "catalogGenConfig" children elements with // CatalogGenConfig namespace first and then with THREDDS namespace. Iterator iter = mdataElement.getChildren( "catalogGenConfig", CATALOG_GEN_CONFIG_NAMESPACE_0_5 ).iterator(); if ( ! iter.hasNext()) iter = mdataElement.getChildren( "catalogGenConfig", mdataElement.getNamespace() ).iterator(); while ( iter.hasNext() ) { Element catGenConfigElement = (Element) iter.next(); if ( debug ) { log.debug( "readMetadataContent=" + catGenConfigElement); } catGenConfigList.add( readCatGenConfigElement( dataset, catGenConfigElement ) ); } return ( catGenConfigList ); } }
public class class_name { private Object readMetadataContentJdom( InvDataset dataset, Element mdataElement ) { Namespace catGenConfigNamespace = null; ArrayList catGenConfigList = new ArrayList(); // Get the "catalogGenConfig" children elements with // CatalogGenConfig namespace first and then with THREDDS namespace. Iterator iter = mdataElement.getChildren( "catalogGenConfig", CATALOG_GEN_CONFIG_NAMESPACE_0_5 ).iterator(); if ( ! iter.hasNext()) iter = mdataElement.getChildren( "catalogGenConfig", mdataElement.getNamespace() ).iterator(); while ( iter.hasNext() ) { Element catGenConfigElement = (Element) iter.next(); if ( debug ) { log.debug( "readMetadataContent=" + catGenConfigElement); // depends on control dependency: [if], data = [none] } catGenConfigList.add( readCatGenConfigElement( dataset, catGenConfigElement ) ); // depends on control dependency: [while], data = [none] } return ( catGenConfigList ); } }
public class class_name { public static AuthenticationData createAuthenticationData(String userName, UserRegistry userRegistry) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { SibTr.entry(tc, CLASS_NAME + "createAuthenticationData", userName); } AuthenticationData authData = new WSAuthenticationData(); if (userName == null) { userName = ""; } String realm = getDefaultRealm(userRegistry); authData.set(AuthenticationData.USERNAME, userName); authData.set(AuthenticationData.REALM, realm); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { SibTr.exit(tc, CLASS_NAME + "createAuthenticationData", authData); } return authData; } }
public class class_name { public static AuthenticationData createAuthenticationData(String userName, UserRegistry userRegistry) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { SibTr.entry(tc, CLASS_NAME + "createAuthenticationData", userName); // depends on control dependency: [if], data = [none] } AuthenticationData authData = new WSAuthenticationData(); if (userName == null) { userName = ""; // depends on control dependency: [if], data = [none] } String realm = getDefaultRealm(userRegistry); authData.set(AuthenticationData.USERNAME, userName); authData.set(AuthenticationData.REALM, realm); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { SibTr.exit(tc, CLASS_NAME + "createAuthenticationData", authData); // depends on control dependency: [if], data = [none] } return authData; } }
public class class_name { public static Date parseCompressedISO8601Date(String dateString) { try { return new Date(compressedIso8601DateFormat.parseMillis(dateString)); } catch (RuntimeException ex) { throw handleException(ex); } } }
public class class_name { public static Date parseCompressedISO8601Date(String dateString) { try { return new Date(compressedIso8601DateFormat.parseMillis(dateString)); // depends on control dependency: [try], data = [none] } catch (RuntimeException ex) { throw handleException(ex); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static String guessDefaultTerminal() { if (System.getProperty("os.name", "").equalsIgnoreCase("windows")) { return "cmd.exe"; } String envPath = System.getenv("PATH"); if (envPath == null) { throw new RuntimeException("Could not find enviroment PATH setting."); } String[] pathes = envPath.split(":"); for (String term : TERMINAL_EMULATORS) { for (String path : pathes) { File terminalExe = new File(concatFilePath(path, term)); if (terminalExe.exists() && terminalExe.canExecute()) { return terminalExe.getAbsolutePath(); } } } return null; } }
public class class_name { public static String guessDefaultTerminal() { if (System.getProperty("os.name", "").equalsIgnoreCase("windows")) { return "cmd.exe"; } String envPath = System.getenv("PATH"); if (envPath == null) { throw new RuntimeException("Could not find enviroment PATH setting."); } String[] pathes = envPath.split(":"); for (String term : TERMINAL_EMULATORS) { for (String path : pathes) { File terminalExe = new File(concatFilePath(path, term)); if (terminalExe.exists() && terminalExe.canExecute()) { return terminalExe.getAbsolutePath(); // depends on control dependency: [if], data = [none] } } } return null; } }
public class class_name { public static PeriodType time() { PeriodType type = cTime; if (type == null) { type = new PeriodType( "Time", new DurationFieldType[] { DurationFieldType.hours(), DurationFieldType.minutes(), DurationFieldType.seconds(), DurationFieldType.millis(), }, new int[] { -1, -1, -1, -1, 0, 1, 2, 3, } ); cTime = type; } return type; } }
public class class_name { public static PeriodType time() { PeriodType type = cTime; if (type == null) { type = new PeriodType( "Time", new DurationFieldType[] { DurationFieldType.hours(), DurationFieldType.minutes(), DurationFieldType.seconds(), DurationFieldType.millis(), }, new int[] { -1, -1, -1, -1, 0, 1, 2, 3, } ); // depends on control dependency: [if], data = [none] cTime = type; // depends on control dependency: [if], data = [none] } return type; } }
public class class_name { public EClass getIfcRatioMeasure() { if (ifcRatioMeasureEClass == null) { ifcRatioMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(728); } return ifcRatioMeasureEClass; } }
public class class_name { public EClass getIfcRatioMeasure() { if (ifcRatioMeasureEClass == null) { ifcRatioMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(728); // depends on control dependency: [if], data = [none] } return ifcRatioMeasureEClass; } }
public class class_name { @VisibleForTesting void generateCode(Predicate<String> availableIdentifiers, StringBuilder outputCode) { outputCode.append(GENERATED_CODE_START_MARKER).append('\n'); // Before entering the real logic, generate any needed prefix. generatePrefix(outputCode); // First we collect all the side tables. // Like { '\n': '\\n', ... } that map characters to escape. List<Map<Character, String>> escapeMaps = Lists.newArrayList(); // Mangled directive names corresponding to escapeMaps used to generate <namespace>..._ names. List<String> escapeMapNames = Lists.newArrayList(); // Like /[\n\r'"]/g or r'[\n\r\'"]'that match all the characters that need escaping. List<String> matchers = Lists.newArrayList(); // Mangled directive names corresponding to matchers. List<String> matcherNames = Lists.newArrayList(); // RegExps that vet input values. List<String> filters = Lists.newArrayList(); // Mangled directive names corresponding to filters. List<String> filterNames = Lists.newArrayList(); // Bundles of directiveNames and indices into escapeMaps, matchers, etc. List<DirectiveDigest> digests = Lists.newArrayList(); escaperLoop: for (EscapingConventions.CrossLanguageStringXform escaper : EscapingConventions.getAllEscapers()) { // "|escapeHtml" -> "escapeHtml" String escapeDirectiveIdent = escaper.getDirectiveName().substring(1); // "escapeHtml" -> "ESCAPE_HTML" String escapeDirectiveUIdent = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, escapeDirectiveIdent); // If there is an existing function, use it. for (String existingFunction : escaper.getLangFunctionNames(getLanguage())) { if (availableIdentifiers.test(existingFunction)) { useExistingLibraryFunction(outputCode, escapeDirectiveIdent, existingFunction); continue escaperLoop; } } // Else generate definitions for side tables. int escapesVar = -1; int matcherVar = -1; if (!escaper.getEscapes().isEmpty()) { Map<Character, String> escapeMap = Maps.newTreeMap(); StringBuilder matcherRegexBuf = new StringBuilder(getRegexStart() + "["); int lastCodeUnit = Integer.MIN_VALUE; int rangeStart = Integer.MIN_VALUE; for (EscapingConventions.Escape esc : escaper.getEscapes()) { char ch = esc.getPlainText(); if (ch == lastCodeUnit) { throw new IllegalStateException( "Ambiguous escape " + esc.getEscaped() + " for " + escapeDirectiveIdent); } escapeMap.put(ch, esc.getEscaped()); if (ch != lastCodeUnit + 1) { if (rangeStart != Integer.MIN_VALUE) { escapeRegexpRangeOnto((char) rangeStart, (char) lastCodeUnit, matcherRegexBuf); } rangeStart = ch; } lastCodeUnit = ch; } if (rangeStart < 0) { throw new IllegalStateException(); } escapeRegexpRangeOnto((char) rangeStart, (char) lastCodeUnit, matcherRegexBuf); matcherRegexBuf.append("]").append(getRegexEnd()); // See if we can reuse an existing map. int numEscapeMaps = escapeMaps.size(); for (int i = 0; i < numEscapeMaps; ++i) { if (mapsHaveCompatibleOverlap(escapeMaps.get(i), escapeMap)) { escapesVar = i; break; } } if (escapesVar == -1) { escapesVar = numEscapeMaps; escapeMaps.add(escapeMap); escapeMapNames.add(escapeDirectiveUIdent); } else { escapeMaps.get(escapesVar).putAll(escapeMap); // ESCAPE_JS -> ESCAPE_JS_STRING__AND__ESCAPE_JS_REGEX escapeMapNames.set( escapesVar, escapeMapNames.get(escapesVar) + "__AND__" + escapeDirectiveUIdent); } String matcherRegex = matcherRegexBuf.toString(); matcherVar = matchers.indexOf(matcherRegex); if (matcherVar < 0) { matcherVar = matchers.size(); matchers.add(matcherRegex); matcherNames.add(escapeDirectiveUIdent); } else { matcherNames.set( matcherVar, matcherNames.get(matcherVar) + "__AND__" + escapeDirectiveUIdent); } } // Find a suitable filter or add one to filters. int filterVar = -1; Pattern filterPatternJava = escaper.getValueFilter(); if (filterPatternJava != null) { // This is an approximate translation from Java patterns to JavaScript patterns. String filterPattern = convertFromJavaRegex(filterPatternJava); filterVar = filters.indexOf(filterPattern); if (filterVar == -1) { filterVar = filters.size(); filters.add(filterPattern); filterNames.add(escapeDirectiveUIdent); } else { filterNames.set( filterVar, filterNames.get(filterVar) + "__AND__" + escapeDirectiveUIdent); } } digests.add( new DirectiveDigest( escapeDirectiveIdent, escapesVar, matcherVar, filterVar, escaper.getNonAsciiPrefix(), escaper.getInnocuousOutput())); } // TODO(msamuel): Maybe use java Soy templates to generate the JS? // Output the tables. for (int i = 0; i < escapeMaps.size(); ++i) { Map<Character, String> escapeMap = escapeMaps.get(i); String escapeMapName = escapeMapNames.get(i); generateCharacterMapSignature(outputCode, escapeMapName); outputCode.append(" = {"); boolean needsComma = false; for (Map.Entry<Character, String> e : escapeMap.entrySet()) { if (needsComma) { outputCode.append(','); } outputCode.append("\n "); writeUnsafeStringLiteral(e.getKey(), outputCode); outputCode.append(": "); writeStringLiteral(e.getValue(), outputCode); needsComma = true; } outputCode.append("\n}").append(getLineEndSyntax()).append("\n"); generateReplacerFunction(outputCode, escapeMapName); } for (int i = 0; i < matchers.size(); ++i) { String matcherName = matcherNames.get(i); String matcher = matchers.get(i); generateMatcher(outputCode, matcherName, matcher); } for (int i = 0; i < filters.size(); ++i) { String filterName = filterNames.get(i); String filter = filters.get(i); generateFilter(outputCode, filterName, filter); } // Finally, define the helper functions that use the escapes, filters, matchers, etc. for (DirectiveDigest digest : digests) { digest.updateNames(escapeMapNames, matcherNames, filterNames); generateHelperFunction(outputCode, digest); } // Emit patterns and constants needed by escaping functions that are not part of any one // escaping convention. generateCommonConstants(outputCode); outputCode.append('\n').append(GENERATED_CODE_END_MARKER).append('\n'); } }
public class class_name { @VisibleForTesting void generateCode(Predicate<String> availableIdentifiers, StringBuilder outputCode) { outputCode.append(GENERATED_CODE_START_MARKER).append('\n'); // Before entering the real logic, generate any needed prefix. generatePrefix(outputCode); // First we collect all the side tables. // Like { '\n': '\\n', ... } that map characters to escape. List<Map<Character, String>> escapeMaps = Lists.newArrayList(); // Mangled directive names corresponding to escapeMaps used to generate <namespace>..._ names. List<String> escapeMapNames = Lists.newArrayList(); // Like /[\n\r'"]/g or r'[\n\r\'"]'that match all the characters that need escaping. List<String> matchers = Lists.newArrayList(); // Mangled directive names corresponding to matchers. List<String> matcherNames = Lists.newArrayList(); // RegExps that vet input values. List<String> filters = Lists.newArrayList(); // Mangled directive names corresponding to filters. List<String> filterNames = Lists.newArrayList(); // Bundles of directiveNames and indices into escapeMaps, matchers, etc. List<DirectiveDigest> digests = Lists.newArrayList(); escaperLoop: for (EscapingConventions.CrossLanguageStringXform escaper : EscapingConventions.getAllEscapers()) { // "|escapeHtml" -> "escapeHtml" String escapeDirectiveIdent = escaper.getDirectiveName().substring(1); // "escapeHtml" -> "ESCAPE_HTML" String escapeDirectiveUIdent = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, escapeDirectiveIdent); // If there is an existing function, use it. for (String existingFunction : escaper.getLangFunctionNames(getLanguage())) { if (availableIdentifiers.test(existingFunction)) { useExistingLibraryFunction(outputCode, escapeDirectiveIdent, existingFunction); // depends on control dependency: [if], data = [none] continue escaperLoop; } } // Else generate definitions for side tables. int escapesVar = -1; int matcherVar = -1; if (!escaper.getEscapes().isEmpty()) { Map<Character, String> escapeMap = Maps.newTreeMap(); StringBuilder matcherRegexBuf = new StringBuilder(getRegexStart() + "["); int lastCodeUnit = Integer.MIN_VALUE; int rangeStart = Integer.MIN_VALUE; for (EscapingConventions.Escape esc : escaper.getEscapes()) { char ch = esc.getPlainText(); if (ch == lastCodeUnit) { throw new IllegalStateException( "Ambiguous escape " + esc.getEscaped() + " for " + escapeDirectiveIdent); } escapeMap.put(ch, esc.getEscaped()); // depends on control dependency: [for], data = [esc] if (ch != lastCodeUnit + 1) { if (rangeStart != Integer.MIN_VALUE) { escapeRegexpRangeOnto((char) rangeStart, (char) lastCodeUnit, matcherRegexBuf); // depends on control dependency: [if], data = [none] } rangeStart = ch; // depends on control dependency: [if], data = [none] } lastCodeUnit = ch; // depends on control dependency: [for], data = [none] } if (rangeStart < 0) { throw new IllegalStateException(); } escapeRegexpRangeOnto((char) rangeStart, (char) lastCodeUnit, matcherRegexBuf); // depends on control dependency: [if], data = [none] matcherRegexBuf.append("]").append(getRegexEnd()); // depends on control dependency: [if], data = [none] // See if we can reuse an existing map. int numEscapeMaps = escapeMaps.size(); for (int i = 0; i < numEscapeMaps; ++i) { if (mapsHaveCompatibleOverlap(escapeMaps.get(i), escapeMap)) { escapesVar = i; // depends on control dependency: [if], data = [none] break; } } if (escapesVar == -1) { escapesVar = numEscapeMaps; // depends on control dependency: [if], data = [none] escapeMaps.add(escapeMap); // depends on control dependency: [if], data = [none] escapeMapNames.add(escapeDirectiveUIdent); // depends on control dependency: [if], data = [none] } else { escapeMaps.get(escapesVar).putAll(escapeMap); // depends on control dependency: [if], data = [(escapesVar] // ESCAPE_JS -> ESCAPE_JS_STRING__AND__ESCAPE_JS_REGEX escapeMapNames.set( escapesVar, escapeMapNames.get(escapesVar) + "__AND__" + escapeDirectiveUIdent); // depends on control dependency: [if], data = [none] } String matcherRegex = matcherRegexBuf.toString(); matcherVar = matchers.indexOf(matcherRegex); // depends on control dependency: [if], data = [none] if (matcherVar < 0) { matcherVar = matchers.size(); // depends on control dependency: [if], data = [none] matchers.add(matcherRegex); // depends on control dependency: [if], data = [none] matcherNames.add(escapeDirectiveUIdent); // depends on control dependency: [if], data = [none] } else { matcherNames.set( matcherVar, matcherNames.get(matcherVar) + "__AND__" + escapeDirectiveUIdent); // depends on control dependency: [if], data = [none] } } // Find a suitable filter or add one to filters. int filterVar = -1; Pattern filterPatternJava = escaper.getValueFilter(); if (filterPatternJava != null) { // This is an approximate translation from Java patterns to JavaScript patterns. String filterPattern = convertFromJavaRegex(filterPatternJava); filterVar = filters.indexOf(filterPattern); // depends on control dependency: [if], data = [none] if (filterVar == -1) { filterVar = filters.size(); // depends on control dependency: [if], data = [none] filters.add(filterPattern); // depends on control dependency: [if], data = [none] filterNames.add(escapeDirectiveUIdent); // depends on control dependency: [if], data = [none] } else { filterNames.set( filterVar, filterNames.get(filterVar) + "__AND__" + escapeDirectiveUIdent); // depends on control dependency: [if], data = [none] } } digests.add( new DirectiveDigest( escapeDirectiveIdent, escapesVar, matcherVar, filterVar, escaper.getNonAsciiPrefix(), escaper.getInnocuousOutput())); // depends on control dependency: [for], data = [none] } // TODO(msamuel): Maybe use java Soy templates to generate the JS? // Output the tables. for (int i = 0; i < escapeMaps.size(); ++i) { Map<Character, String> escapeMap = escapeMaps.get(i); String escapeMapName = escapeMapNames.get(i); generateCharacterMapSignature(outputCode, escapeMapName); // depends on control dependency: [for], data = [none] outputCode.append(" = {"); // depends on control dependency: [for], data = [none] boolean needsComma = false; for (Map.Entry<Character, String> e : escapeMap.entrySet()) { if (needsComma) { outputCode.append(','); // depends on control dependency: [if], data = [none] } outputCode.append("\n "); // depends on control dependency: [for], data = [e] writeUnsafeStringLiteral(e.getKey(), outputCode); // depends on control dependency: [for], data = [e] outputCode.append(": "); // depends on control dependency: [for], data = [e] writeStringLiteral(e.getValue(), outputCode); // depends on control dependency: [for], data = [e] needsComma = true; // depends on control dependency: [for], data = [e] } outputCode.append("\n}").append(getLineEndSyntax()).append("\n"); // depends on control dependency: [for], data = [none] generateReplacerFunction(outputCode, escapeMapName); // depends on control dependency: [for], data = [none] } for (int i = 0; i < matchers.size(); ++i) { String matcherName = matcherNames.get(i); String matcher = matchers.get(i); generateMatcher(outputCode, matcherName, matcher); // depends on control dependency: [for], data = [none] } for (int i = 0; i < filters.size(); ++i) { String filterName = filterNames.get(i); String filter = filters.get(i); generateFilter(outputCode, filterName, filter); // depends on control dependency: [for], data = [none] } // Finally, define the helper functions that use the escapes, filters, matchers, etc. for (DirectiveDigest digest : digests) { digest.updateNames(escapeMapNames, matcherNames, filterNames); // depends on control dependency: [for], data = [digest] generateHelperFunction(outputCode, digest); // depends on control dependency: [for], data = [digest] } // Emit patterns and constants needed by escaping functions that are not part of any one // escaping convention. generateCommonConstants(outputCode); outputCode.append('\n').append(GENERATED_CODE_END_MARKER).append('\n'); } }
public class class_name { public void marshall(UpdateResolverRuleRequest updateResolverRuleRequest, ProtocolMarshaller protocolMarshaller) { if (updateResolverRuleRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(updateResolverRuleRequest.getResolverRuleId(), RESOLVERRULEID_BINDING); protocolMarshaller.marshall(updateResolverRuleRequest.getConfig(), CONFIG_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(UpdateResolverRuleRequest updateResolverRuleRequest, ProtocolMarshaller protocolMarshaller) { if (updateResolverRuleRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(updateResolverRuleRequest.getResolverRuleId(), RESOLVERRULEID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(updateResolverRuleRequest.getConfig(), CONFIG_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 getMemberCount(AVIMConversationMemberCountCallback callback) { if (StringUtil.isEmpty(getConversationId())) { if (null != callback) { callback.internalDone(new AVException(AVException.INVALID_QUERY, "ConversationId is empty")); } else { LOGGER.w("ConversationId is empty"); } return; } InternalConfiguration.getOperationTube().processMembers(client.getClientId(), conversationId, getType(), null, Conversation.AVIMOperation.CONVERSATION_MEMBER_COUNT_QUERY, callback); } }
public class class_name { public void getMemberCount(AVIMConversationMemberCountCallback callback) { if (StringUtil.isEmpty(getConversationId())) { if (null != callback) { callback.internalDone(new AVException(AVException.INVALID_QUERY, "ConversationId is empty")); // depends on control dependency: [if], data = [none] } else { LOGGER.w("ConversationId is empty"); // depends on control dependency: [if], data = [none] } return; // depends on control dependency: [if], data = [none] } InternalConfiguration.getOperationTube().processMembers(client.getClientId(), conversationId, getType(), null, Conversation.AVIMOperation.CONVERSATION_MEMBER_COUNT_QUERY, callback); } }
public class class_name { public void setParent( IParseTree l ) { if( l != null && !l.contains( this ) && getLength() > 0 ) { throw new IllegalArgumentException( "Attempted set the parent location, but the parent location's area is not a superset of this location's area." ); } if( _pe != null ) { ParsedElement parentElement = (ParsedElement)_pe.getParent(); if( parentElement != null ) { ParseTree oldParent = parentElement.getLocation(); if( oldParent != null ) { oldParent._children.remove( this ); } } _pe.setParent( l == null ? null : ((ParseTree)l)._pe ); } } }
public class class_name { public void setParent( IParseTree l ) { if( l != null && !l.contains( this ) && getLength() > 0 ) { throw new IllegalArgumentException( "Attempted set the parent location, but the parent location's area is not a superset of this location's area." ); } if( _pe != null ) { ParsedElement parentElement = (ParsedElement)_pe.getParent(); if( parentElement != null ) { ParseTree oldParent = parentElement.getLocation(); if( oldParent != null ) { oldParent._children.remove( this ); // depends on control dependency: [if], data = [none] } } _pe.setParent( l == null ? null : ((ParseTree)l)._pe ); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void execute() throws DataflowAnalysisException { boolean change; boolean debugWas = DEBUG; if (DEBUG) { reportAnalysis("Executing"); } int timestamp = 0; boolean firstTime = true; do { change = false; boolean sawBackEdge = false; ++numIterations; if (numIterations > MAX_ITERS && !DEBUG) { DEBUG = true; reportAnalysis("Too many iterations"); System.out.println(this.getClass().getName()); if (this.getClass() == UnconditionalValueDerefDataflow.class || this.getClass() == LiveLocalStoreDataflow.class) { try { ClassContext cc = Global.getAnalysisCache().getClassAnalysis(ClassContext.class, DescriptorFactory.createClassDescriptorFromDottedClassName(cfg.getMethodGen().getClassName())); System.out.println("Forwards cfg"); CFGPrinter printer = new CFGPrinter(cfg); printer.setIsForwards(true); printer.print(System.out); System.out.println("Backwards cfg"); printer = new CFGPrinter(cfg); printer.setIsForwards(false); printer.print(System.out); cc.dumpSimpleDataflowInformation(cfg.getMethodGen().getMethod()); } catch (CheckedAnalysisException e) { e.printStackTrace(System.out); } } } if (DEBUG) { System.out.println("----------------------------------------------------------------------"); System.out.println(this.getClass().getName() + " iteration: " + numIterations + ", timestamp: " + timestamp); MethodGen mg = cfg.getMethodGen(); System.out.println(mg.getClassName() + "." + mg.getName() + mg.getSignature()); System.out.println("----------------------------------------------------------------------"); } if (numIterations >= MAX_ITERS + 9) { throw new DataflowAnalysisException("Too many iterations (" + numIterations + ") in dataflow when analyzing " + getFullyQualifiedMethodName()); } analysis.startIteration(); if (DEBUG && firstTime && blockOrder instanceof ReverseDFSOrder) { ReverseDFSOrder rBlockOrder = (ReverseDFSOrder) blockOrder; System.out.println("Entry point is: " + logicalEntryBlock()); System.out.println("Basic block order: "); Iterator<BasicBlock> i = blockOrder.blockIterator(); while (i.hasNext()) { BasicBlock block = i.next(); debug(block, "rBlockOrder " + rBlockOrder.rdfs.getDiscoveryTime(block) + "\n"); } } Iterator<BasicBlock> i = blockOrder.blockIterator(); if (numIterations > 3 && numIterations % 2 == 0 && blockOrder instanceof ReverseDFSOrder) { if (DEBUG) { System.out.println("Trying program order"); } TreeSet<BasicBlock> bb = new TreeSet<>(new BackwardProgramOrder()); Iterator<BasicBlock> j = blockOrder.blockIterator(); while (j.hasNext()) { BasicBlock block = j.next(); bb.add(block); } if (DEBUG) { for (BasicBlock block : bb) { debug(block, "\n"); } } i = bb.iterator(); } if (DEBUG) { dumpDataflow(analysis); } // For each block in CFG... while (i.hasNext()) { BasicBlock block = i.next(); // Get start fact for block. Fact start = analysis.getStartFact(block); assert start != null; boolean needToRecompute = false; // Get result facts for block, Fact result = analysis.getResultFact(block); assert result != null; int originalResultTimestamp = analysis.getLastUpdateTimestamp(result); // Meet all of the logical predecessor results into this block's // start. // Special case: if the block is the logical entry, then it gets // the special "entry fact". if (block == logicalEntryBlock()) { analysis.makeFactTop(start); analysis.initEntryFact(start); if (DEBUG) { debug(block, "Init entry fact ==> " + analysis.factToString(start) + "\n"); } needToRecompute = true; } else { int lastCalculated = analysis.getLastUpdateTimestamp(start); Iterator<Edge> predEdgeIter = logicalPredecessorEdgeIterator(block); int predCount = 0; int rawPredCount = 0; while (predEdgeIter.hasNext()) { Edge edge = predEdgeIter.next(); rawPredCount++; if (needToRecompute) { // don't need to check to see if we need to recompute. if (firstTime && !sawBackEdge) { // may need to se sawBackEdge } else { continue; } } BasicBlock logicalPred = isForwards ? edge.getSource() : edge.getTarget(); int direction = blockOrder.compare(block, logicalPred); if (DEBUG) { debug(block, "direction " + direction + " for " + blockId(logicalPred) + "\n"); } if (direction < 0) { sawBackEdge = true; } // Get the predecessor result fact Fact predFact = analysis.getResultFact(logicalPred); int predLastUpdated = analysis.getLastUpdateTimestamp(predFact); if (!analysis.isTop(predFact)) { predCount++; if (predLastUpdated >= lastCalculated) { needToRecompute = true; if (DEBUG) { debug(block, "\n Need to recompute. My timestamp = " + lastCalculated + ", pred timestamp = " + predLastUpdated + ",\n pred fact = " + predFact + "\n"); } // break; } } } if (predCount == 0) { needToRecompute = true; } if (!needToRecompute) { continue; } analysis.makeFactTop(start); predEdgeIter = logicalPredecessorEdgeIterator(block); while (predEdgeIter.hasNext()) { Edge edge = predEdgeIter.next(); BasicBlock logicalPred = isForwards ? edge.getSource() : edge.getTarget(); // Get the predecessor result fact Fact predFact = analysis.getResultFact(logicalPred); // Apply the edge transfer function. Fact edgeFact = analysis.createFact(); analysis.copy(predFact, edgeFact); analysis.edgeTransfer(edge, edgeFact); if (DEBUG && !analysis.same(edgeFact, predFact)) { debug(block, logicalPred, edge, "Edge transfer " + analysis.factToString(predFact) + " ==> " + analysis.factToString(edgeFact)); } // Merge the predecessor fact (possibly transformed // by the edge transfer function) // into the block's start fact. if (DEBUG) { if (analysis.isTop(start)) { debug(block, logicalPred, edge, "\n First pred is " + analysis.factToString(edgeFact) + "\n last updated at " + analysis.getLastUpdateTimestamp(predFact) + "\n"); } else { debug(block, logicalPred, edge, "\n Meet " + analysis.factToString(start) + "\n with " + analysis.factToString(edgeFact) + "\n pred last updated at " + analysis.getLastUpdateTimestamp(predFact) + "\n"); } } if (analysis instanceof UnconditionalValueDerefAnalysis) { ((UnconditionalValueDerefAnalysis) analysis).meetInto((UnconditionalValueDerefSet) edgeFact, edge, (UnconditionalValueDerefSet) start, rawPredCount == 1); } else { analysis.meetInto(edgeFact, edge, start); } analysis.setLastUpdateTimestamp(start, timestamp); int pos = -1; if (block.getFirstInstruction() != null) { pos = block.getFirstInstruction().getPosition(); } if (DEBUG) { System.out.println(" [" + pos + "]==> " + analysis.factToString(start) + " @ " + timestamp + " \n"); } } } if (DEBUG) { debug(block, "start fact is " + analysis.factToString(start) + "\n"); } // making a copy of result facts (so we can detect if it // changed). boolean resultWasTop = analysis.isTop(result); Fact origResult = null; if (!resultWasTop) { origResult = analysis.createFact(); analysis.copy(result, origResult); } // if (true || analysis.isTop(start)) { // Apply the transfer function. analysis.transfer(block, null, start, result); // } else { // analysis.copy(start, result); // } if (DEBUG && SystemProperties.getBoolean("dataflow.blockdebug")) { debug(block, "Dumping flow values for block:\n"); Iterator<InstructionHandle> ii = block.instructionIterator(); while (ii.hasNext()) { InstructionHandle handle = ii.next(); Fact tmpResult = analysis.createFact(); analysis.transfer(block, handle, start, tmpResult); System.out.println("\t" + handle + " " + analysis.factToString(tmpResult)); } } // See if the result changed. if (DEBUG) { debug(block, "orig result is " + (origResult == null ? "TOP" : analysis.factToString(origResult)) + "\n"); } boolean thisResultChanged = false; if (resultWasTop) { thisResultChanged = !analysis.isTop(result); } else { thisResultChanged = !analysis.same(result, origResult); } if (thisResultChanged) { timestamp++; if (DEBUG) { debug(block, "result changed at timestamp " + timestamp + "\n"); } if (DEBUG && !needToRecompute) { System.out.println("I thought I didn't need to recompute"); } change = true; analysis.setLastUpdateTimestamp(result, timestamp); } else { analysis.setLastUpdateTimestamp(result, originalResultTimestamp); } if (DEBUG) { debug(block, "result is " + analysis.factToString(result) + " @ timestamp " + analysis.getLastUpdateTimestamp(result) + "\n"); } } analysis.finishIteration(); if (!sawBackEdge) { break; } } while (change); if (DEBUG) { System.out.println("-- Quiescence achieved-------------------------------------------------"); System.out.println(this.getClass().getName() + " iteration: " + numIterations + ", timestamp: " + timestamp); MethodGen mg = cfg.getMethodGen(); System.out.println(mg.getClassName() + "." + mg.getName() + mg.getSignature()); new RuntimeException("Quiescence achieved----------------------------------------------------------------") .printStackTrace(System.out); } DEBUG = debugWas; } }
public class class_name { public void execute() throws DataflowAnalysisException { boolean change; boolean debugWas = DEBUG; if (DEBUG) { reportAnalysis("Executing"); } int timestamp = 0; boolean firstTime = true; do { change = false; boolean sawBackEdge = false; ++numIterations; if (numIterations > MAX_ITERS && !DEBUG) { DEBUG = true; // depends on control dependency: [if], data = [none] reportAnalysis("Too many iterations"); // depends on control dependency: [if], data = [none] System.out.println(this.getClass().getName()); // depends on control dependency: [if], data = [none] if (this.getClass() == UnconditionalValueDerefDataflow.class || this.getClass() == LiveLocalStoreDataflow.class) { try { ClassContext cc = Global.getAnalysisCache().getClassAnalysis(ClassContext.class, DescriptorFactory.createClassDescriptorFromDottedClassName(cfg.getMethodGen().getClassName())); System.out.println("Forwards cfg"); // depends on control dependency: [try], data = [none] CFGPrinter printer = new CFGPrinter(cfg); printer.setIsForwards(true); // depends on control dependency: [try], data = [none] printer.print(System.out); // depends on control dependency: [try], data = [none] System.out.println("Backwards cfg"); // depends on control dependency: [try], data = [none] printer = new CFGPrinter(cfg); // depends on control dependency: [try], data = [none] printer.setIsForwards(false); // depends on control dependency: [try], data = [none] printer.print(System.out); // depends on control dependency: [try], data = [none] cc.dumpSimpleDataflowInformation(cfg.getMethodGen().getMethod()); // depends on control dependency: [try], data = [none] } catch (CheckedAnalysisException e) { e.printStackTrace(System.out); } // depends on control dependency: [catch], data = [none] } } if (DEBUG) { System.out.println("----------------------------------------------------------------------"); System.out.println(this.getClass().getName() + " iteration: " + numIterations + ", timestamp: " + timestamp); MethodGen mg = cfg.getMethodGen(); System.out.println(mg.getClassName() + "." + mg.getName() + mg.getSignature()); System.out.println("----------------------------------------------------------------------"); } if (numIterations >= MAX_ITERS + 9) { throw new DataflowAnalysisException("Too many iterations (" + numIterations + ") in dataflow when analyzing " + getFullyQualifiedMethodName()); } analysis.startIteration(); if (DEBUG && firstTime && blockOrder instanceof ReverseDFSOrder) { ReverseDFSOrder rBlockOrder = (ReverseDFSOrder) blockOrder; System.out.println("Entry point is: " + logicalEntryBlock()); System.out.println("Basic block order: "); Iterator<BasicBlock> i = blockOrder.blockIterator(); while (i.hasNext()) { BasicBlock block = i.next(); debug(block, "rBlockOrder " + rBlockOrder.rdfs.getDiscoveryTime(block) + "\n"); } } Iterator<BasicBlock> i = blockOrder.blockIterator(); if (numIterations > 3 && numIterations % 2 == 0 && blockOrder instanceof ReverseDFSOrder) { if (DEBUG) { System.out.println("Trying program order"); // depends on control dependency: [if], data = [none] } TreeSet<BasicBlock> bb = new TreeSet<>(new BackwardProgramOrder()); Iterator<BasicBlock> j = blockOrder.blockIterator(); while (j.hasNext()) { BasicBlock block = j.next(); bb.add(block); // depends on control dependency: [while], data = [none] } if (DEBUG) { for (BasicBlock block : bb) { debug(block, "\n"); // depends on control dependency: [for], data = [block] } } i = bb.iterator(); // depends on control dependency: [if], data = [none] } if (DEBUG) { dumpDataflow(analysis); // depends on control dependency: [if], data = [none] } // For each block in CFG... while (i.hasNext()) { BasicBlock block = i.next(); // Get start fact for block. Fact start = analysis.getStartFact(block); assert start != null; boolean needToRecompute = false; // Get result facts for block, Fact result = analysis.getResultFact(block); assert result != null; int originalResultTimestamp = analysis.getLastUpdateTimestamp(result); // Meet all of the logical predecessor results into this block's // start. // Special case: if the block is the logical entry, then it gets // the special "entry fact". if (block == logicalEntryBlock()) { analysis.makeFactTop(start); // depends on control dependency: [if], data = [none] analysis.initEntryFact(start); // depends on control dependency: [if], data = [none] if (DEBUG) { debug(block, "Init entry fact ==> " + analysis.factToString(start) + "\n"); // depends on control dependency: [if], data = [none] } needToRecompute = true; // depends on control dependency: [if], data = [none] } else { int lastCalculated = analysis.getLastUpdateTimestamp(start); Iterator<Edge> predEdgeIter = logicalPredecessorEdgeIterator(block); int predCount = 0; int rawPredCount = 0; while (predEdgeIter.hasNext()) { Edge edge = predEdgeIter.next(); rawPredCount++; // depends on control dependency: [while], data = [none] if (needToRecompute) { // don't need to check to see if we need to recompute. if (firstTime && !sawBackEdge) { // may need to se sawBackEdge } else { continue; } } BasicBlock logicalPred = isForwards ? edge.getSource() : edge.getTarget(); int direction = blockOrder.compare(block, logicalPred); if (DEBUG) { debug(block, "direction " + direction + " for " + blockId(logicalPred) + "\n"); // depends on control dependency: [if], data = [none] } if (direction < 0) { sawBackEdge = true; // depends on control dependency: [if], data = [none] } // Get the predecessor result fact Fact predFact = analysis.getResultFact(logicalPred); int predLastUpdated = analysis.getLastUpdateTimestamp(predFact); if (!analysis.isTop(predFact)) { predCount++; // depends on control dependency: [if], data = [none] if (predLastUpdated >= lastCalculated) { needToRecompute = true; // depends on control dependency: [if], data = [none] if (DEBUG) { debug(block, "\n Need to recompute. My timestamp = " + lastCalculated + ", pred timestamp = " + predLastUpdated + ",\n pred fact = " + predFact + "\n"); // depends on control dependency: [if], data = [none] } // break; } } } if (predCount == 0) { needToRecompute = true; // depends on control dependency: [if], data = [none] } if (!needToRecompute) { continue; } analysis.makeFactTop(start); // depends on control dependency: [if], data = [none] predEdgeIter = logicalPredecessorEdgeIterator(block); // depends on control dependency: [if], data = [(block] while (predEdgeIter.hasNext()) { Edge edge = predEdgeIter.next(); BasicBlock logicalPred = isForwards ? edge.getSource() : edge.getTarget(); // Get the predecessor result fact Fact predFact = analysis.getResultFact(logicalPred); // Apply the edge transfer function. Fact edgeFact = analysis.createFact(); analysis.copy(predFact, edgeFact); // depends on control dependency: [while], data = [none] analysis.edgeTransfer(edge, edgeFact); // depends on control dependency: [while], data = [none] if (DEBUG && !analysis.same(edgeFact, predFact)) { debug(block, logicalPred, edge, "Edge transfer " + analysis.factToString(predFact) + " ==> " + analysis.factToString(edgeFact)); // depends on control dependency: [if], data = [none] } // Merge the predecessor fact (possibly transformed // by the edge transfer function) // into the block's start fact. if (DEBUG) { if (analysis.isTop(start)) { debug(block, logicalPred, edge, "\n First pred is " + analysis.factToString(edgeFact) + "\n last updated at " + analysis.getLastUpdateTimestamp(predFact) + "\n"); // depends on control dependency: [if], data = [none] } else { debug(block, logicalPred, edge, "\n Meet " + analysis.factToString(start) + "\n with " + analysis.factToString(edgeFact) + "\n pred last updated at " + analysis.getLastUpdateTimestamp(predFact) + "\n"); // depends on control dependency: [if], data = [none] } } if (analysis instanceof UnconditionalValueDerefAnalysis) { ((UnconditionalValueDerefAnalysis) analysis).meetInto((UnconditionalValueDerefSet) edgeFact, edge, (UnconditionalValueDerefSet) start, rawPredCount == 1); // depends on control dependency: [if], data = [none] } else { analysis.meetInto(edgeFact, edge, start); // depends on control dependency: [if], data = [none] } analysis.setLastUpdateTimestamp(start, timestamp); // depends on control dependency: [while], data = [none] int pos = -1; if (block.getFirstInstruction() != null) { pos = block.getFirstInstruction().getPosition(); // depends on control dependency: [if], data = [none] } if (DEBUG) { System.out.println(" [" + pos + "]==> " + analysis.factToString(start) + " @ " + timestamp + " \n"); // depends on control dependency: [if], data = [none] } } } if (DEBUG) { debug(block, "start fact is " + analysis.factToString(start) + "\n"); // depends on control dependency: [if], data = [none] } // making a copy of result facts (so we can detect if it // changed). boolean resultWasTop = analysis.isTop(result); Fact origResult = null; if (!resultWasTop) { origResult = analysis.createFact(); // depends on control dependency: [if], data = [none] analysis.copy(result, origResult); // depends on control dependency: [if], data = [none] } // if (true || analysis.isTop(start)) { // Apply the transfer function. analysis.transfer(block, null, start, result); // } else { // analysis.copy(start, result); // } if (DEBUG && SystemProperties.getBoolean("dataflow.blockdebug")) { debug(block, "Dumping flow values for block:\n"); Iterator<InstructionHandle> ii = block.instructionIterator(); while (ii.hasNext()) { InstructionHandle handle = ii.next(); Fact tmpResult = analysis.createFact(); analysis.transfer(block, handle, start, tmpResult); System.out.println("\t" + handle + " " + analysis.factToString(tmpResult)); } } // See if the result changed. if (DEBUG) { debug(block, "orig result is " + (origResult == null ? "TOP" : analysis.factToString(origResult)) + "\n"); } boolean thisResultChanged = false; if (resultWasTop) { thisResultChanged = !analysis.isTop(result); } else { thisResultChanged = !analysis.same(result, origResult); } if (thisResultChanged) { timestamp++; if (DEBUG) { debug(block, "result changed at timestamp " + timestamp + "\n"); } if (DEBUG && !needToRecompute) { System.out.println("I thought I didn't need to recompute"); } change = true; analysis.setLastUpdateTimestamp(result, timestamp); } else { analysis.setLastUpdateTimestamp(result, originalResultTimestamp); } if (DEBUG) { debug(block, "result is " + analysis.factToString(result) + " @ timestamp " + analysis.getLastUpdateTimestamp(result) + "\n"); } } analysis.finishIteration(); if (!sawBackEdge) { break; } } while (change); if (DEBUG) { System.out.println("-- Quiescence achieved-------------------------------------------------"); System.out.println(this.getClass().getName() + " iteration: " + numIterations + ", timestamp: " + timestamp); MethodGen mg = cfg.getMethodGen(); System.out.println(mg.getClassName() + "." + mg.getName() + mg.getSignature()); new RuntimeException("Quiescence achieved----------------------------------------------------------------") .printStackTrace(System.out); } DEBUG = debugWas; } }
public class class_name { public BigMoney withAmount(BigDecimal amount) { MoneyUtils.checkNotNull(amount, "Amount must not be null"); if (this.amount.equals(amount)) { return this; } return BigMoney.of(currency, amount); } }
public class class_name { public BigMoney withAmount(BigDecimal amount) { MoneyUtils.checkNotNull(amount, "Amount must not be null"); if (this.amount.equals(amount)) { return this; // depends on control dependency: [if], data = [none] } return BigMoney.of(currency, amount); } }
public class class_name { private Void doConcat(SegmentHandle targetHandle, long offset, String sourceSegment) throws IOException { long traceId = LoggerHelpers.traceEnter(log, "concat", targetHandle.getSegmentName(), offset, sourceSegment); Path sourcePath = Paths.get(config.getRoot(), sourceSegment); Path targetPath = Paths.get(config.getRoot(), targetHandle.getSegmentName()); long length = Files.size(sourcePath); try (FileChannel targetChannel = FileChannel.open(targetPath, StandardOpenOption.WRITE); RandomAccessFile sourceFile = new RandomAccessFile(String.valueOf(sourcePath), "r")) { if (isWritableFile(sourcePath)) { throw new IllegalStateException(String.format("Source segment (%s) is not sealed.", sourceSegment)); } while (length > 0) { long bytesTransferred = targetChannel.transferFrom(sourceFile.getChannel(), offset, length); offset += bytesTransferred; length -= bytesTransferred; } targetChannel.force(false); Files.delete(sourcePath); LoggerHelpers.traceLeave(log, "concat", traceId); return null; } } }
public class class_name { private Void doConcat(SegmentHandle targetHandle, long offset, String sourceSegment) throws IOException { long traceId = LoggerHelpers.traceEnter(log, "concat", targetHandle.getSegmentName(), offset, sourceSegment); Path sourcePath = Paths.get(config.getRoot(), sourceSegment); Path targetPath = Paths.get(config.getRoot(), targetHandle.getSegmentName()); long length = Files.size(sourcePath); try (FileChannel targetChannel = FileChannel.open(targetPath, StandardOpenOption.WRITE); RandomAccessFile sourceFile = new RandomAccessFile(String.valueOf(sourcePath), "r")) { if (isWritableFile(sourcePath)) { throw new IllegalStateException(String.format("Source segment (%s) is not sealed.", sourceSegment)); } while (length > 0) { long bytesTransferred = targetChannel.transferFrom(sourceFile.getChannel(), offset, length); offset += bytesTransferred; // depends on control dependency: [while], data = [none] length -= bytesTransferred; // depends on control dependency: [while], data = [none] } targetChannel.force(false); Files.delete(sourcePath); LoggerHelpers.traceLeave(log, "concat", traceId); return null; } } }
public class class_name { public static Callable getElemFunctionAndThis(Object obj, Object elem, Context cx, Scriptable scope) { Scriptable thisObj; Object value; if (isSymbol(elem)) { thisObj = toObjectOrNull(cx, obj, scope); if (thisObj == null) { throw undefCallError(obj, String.valueOf(elem)); } value = ScriptableObject.getProperty(thisObj, (Symbol)elem); } else { String str = toStringIdOrIndex(cx, elem); if (str != null) { return getPropFunctionAndThis(obj, str, cx, scope); } int index = lastIndexResult(cx); thisObj = toObjectOrNull(cx, obj, scope); if (thisObj == null) { throw undefCallError(obj, String.valueOf(elem)); } value = ScriptableObject.getProperty(thisObj, index); } if (!(value instanceof Callable)) { throw notFunctionError(value, elem); } storeScriptable(cx, thisObj); return (Callable)value; } }
public class class_name { public static Callable getElemFunctionAndThis(Object obj, Object elem, Context cx, Scriptable scope) { Scriptable thisObj; Object value; if (isSymbol(elem)) { thisObj = toObjectOrNull(cx, obj, scope); // depends on control dependency: [if], data = [none] if (thisObj == null) { throw undefCallError(obj, String.valueOf(elem)); } value = ScriptableObject.getProperty(thisObj, (Symbol)elem); // depends on control dependency: [if], data = [none] } else { String str = toStringIdOrIndex(cx, elem); if (str != null) { return getPropFunctionAndThis(obj, str, cx, scope); // depends on control dependency: [if], data = [none] } int index = lastIndexResult(cx); thisObj = toObjectOrNull(cx, obj, scope); // depends on control dependency: [if], data = [none] if (thisObj == null) { throw undefCallError(obj, String.valueOf(elem)); } value = ScriptableObject.getProperty(thisObj, index); // depends on control dependency: [if], data = [none] } if (!(value instanceof Callable)) { throw notFunctionError(value, elem); } storeScriptable(cx, thisObj); return (Callable)value; } }
public class class_name { public EClass getIfcSurfaceOrFaceSurface() { if (ifcSurfaceOrFaceSurfaceEClass == null) { ifcSurfaceOrFaceSurfaceEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(973); } return ifcSurfaceOrFaceSurfaceEClass; } }
public class class_name { public EClass getIfcSurfaceOrFaceSurface() { if (ifcSurfaceOrFaceSurfaceEClass == null) { ifcSurfaceOrFaceSurfaceEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(973); // depends on control dependency: [if], data = [none] } return ifcSurfaceOrFaceSurfaceEClass; } }
public class class_name { @NullSafe @SuppressWarnings("all") public static boolean areAllNull(Object... values) { for (Object value : nullSafeArray(values)) { if (value != null) { return false; } } return true; } }
public class class_name { @NullSafe @SuppressWarnings("all") public static boolean areAllNull(Object... values) { for (Object value : nullSafeArray(values)) { if (value != null) { return false; // depends on control dependency: [if], data = [none] } } return true; } }
public class class_name { protected void setTuitionRequestedYears(Budget budget) { ProposalDevelopmentBudgetExtContract pBudget = s2SCommonBudgetService.getBudget(pdDoc.getDevelopmentProposal()); if (pBudget == null) { return; } ScaleTwoDecimal tuitionTotal = ScaleTwoDecimal.ZERO; for (BudgetPeriodContract budgetPeriod : pBudget.getBudgetPeriods()) { ScaleTwoDecimal tuition = ScaleTwoDecimal.ZERO; for (BudgetLineItemContract budgetLineItem : budgetPeriod.getBudgetLineItems()) { if (getCostElementsByParam(ConfigurationConstants.TUITION_COST_ELEMENTS).contains(budgetLineItem.getCostElementBO().getCostElement())) { tuition = tuition.add(budgetLineItem.getLineItemCost()); } } tuitionTotal = tuitionTotal.add(tuition); switch (budgetPeriod.getBudgetPeriod()) { case 1: budget.setTuitionRequestedYear1(tuition.bigDecimalValue()); break; case 2: budget.setTuitionRequestedYear2(tuition.bigDecimalValue()); break; case 3: budget.setTuitionRequestedYear3(tuition.bigDecimalValue()); break; case 4: budget.setTuitionRequestedYear4(tuition.bigDecimalValue()); break; case 5: budget.setTuitionRequestedYear5(tuition.bigDecimalValue()); break; case 6: budget.setTuitionRequestedYear6(tuition.bigDecimalValue()); break; default: break; } } budget.setTuitionRequestedTotal(tuitionTotal.bigDecimalValue()); if (!tuitionTotal.equals(ScaleTwoDecimal.ZERO)) { budget.setTuitionAndFeesRequested(YesNoDataType.Y_YES); } } }
public class class_name { protected void setTuitionRequestedYears(Budget budget) { ProposalDevelopmentBudgetExtContract pBudget = s2SCommonBudgetService.getBudget(pdDoc.getDevelopmentProposal()); if (pBudget == null) { return; // depends on control dependency: [if], data = [none] } ScaleTwoDecimal tuitionTotal = ScaleTwoDecimal.ZERO; for (BudgetPeriodContract budgetPeriod : pBudget.getBudgetPeriods()) { ScaleTwoDecimal tuition = ScaleTwoDecimal.ZERO; for (BudgetLineItemContract budgetLineItem : budgetPeriod.getBudgetLineItems()) { if (getCostElementsByParam(ConfigurationConstants.TUITION_COST_ELEMENTS).contains(budgetLineItem.getCostElementBO().getCostElement())) { tuition = tuition.add(budgetLineItem.getLineItemCost()); // depends on control dependency: [if], data = [none] } } tuitionTotal = tuitionTotal.add(tuition); // depends on control dependency: [for], data = [none] switch (budgetPeriod.getBudgetPeriod()) { case 1: budget.setTuitionRequestedYear1(tuition.bigDecimalValue()); break; case 2: budget.setTuitionRequestedYear2(tuition.bigDecimalValue()); break; case 3: budget.setTuitionRequestedYear3(tuition.bigDecimalValue()); break; case 4: budget.setTuitionRequestedYear4(tuition.bigDecimalValue()); break; case 5: budget.setTuitionRequestedYear5(tuition.bigDecimalValue()); break; case 6: budget.setTuitionRequestedYear6(tuition.bigDecimalValue()); break; default: break; } } budget.setTuitionRequestedTotal(tuitionTotal.bigDecimalValue()); if (!tuitionTotal.equals(ScaleTwoDecimal.ZERO)) { budget.setTuitionAndFeesRequested(YesNoDataType.Y_YES); } } }
public class class_name { @NotNull public static LongStream rangeClosed(final long startInclusive, final long endInclusive) { if (startInclusive > endInclusive) { return empty(); } else if (startInclusive == endInclusive) { return of(startInclusive); } else return new LongStream(new LongRangeClosed(startInclusive, endInclusive)); } }
public class class_name { @NotNull public static LongStream rangeClosed(final long startInclusive, final long endInclusive) { if (startInclusive > endInclusive) { return empty(); // depends on control dependency: [if], data = [none] } else if (startInclusive == endInclusive) { return of(startInclusive); // depends on control dependency: [if], data = [(startInclusive] } else return new LongStream(new LongRangeClosed(startInclusive, endInclusive)); } }
public class class_name { @Override public EClass getIfcWasteTerminal() { if (ifcWasteTerminalEClass == null) { ifcWasteTerminalEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(762); } return ifcWasteTerminalEClass; } }
public class class_name { @Override public EClass getIfcWasteTerminal() { if (ifcWasteTerminalEClass == null) { ifcWasteTerminalEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(762); // depends on control dependency: [if], data = [none] } return ifcWasteTerminalEClass; } }
public class class_name { public boolean checkedAdd(final int x) { final short hb = Util.highbits(x); final int i = highLowContainer.getIndex(hb); if (i >= 0) { Container c = highLowContainer.getContainerAtIndex(i); int oldCard = c.getCardinality(); // we need to keep the newContainer if a switch between containers type // occur, in order to get the new cardinality Container newCont = c.add(Util.lowbits(x)); highLowContainer.setContainerAtIndex(i, newCont); if (newCont.getCardinality() > oldCard) { return true; } } else { final ArrayContainer newac = new ArrayContainer(); highLowContainer.insertNewKeyValueAt(-i - 1, hb, newac.add(Util.lowbits(x))); return true; } return false; } }
public class class_name { public boolean checkedAdd(final int x) { final short hb = Util.highbits(x); final int i = highLowContainer.getIndex(hb); if (i >= 0) { Container c = highLowContainer.getContainerAtIndex(i); int oldCard = c.getCardinality(); // we need to keep the newContainer if a switch between containers type // occur, in order to get the new cardinality Container newCont = c.add(Util.lowbits(x)); highLowContainer.setContainerAtIndex(i, newCont); // depends on control dependency: [if], data = [(i] if (newCont.getCardinality() > oldCard) { return true; // depends on control dependency: [if], data = [none] } } else { final ArrayContainer newac = new ArrayContainer(); highLowContainer.insertNewKeyValueAt(-i - 1, hb, newac.add(Util.lowbits(x))); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } return false; } }
public class class_name { private void leave(CompletableFuture<Void> future) { // Set a timer to retry the attempt to leave the cluster. leaveTimeout = raft.getThreadContext().schedule(raft.getElectionTimeout(), () -> { leave(future); }); // Attempt to leave the cluster by submitting a LeaveRequest directly to the server state. // Non-leader states should forward the request to the leader if there is one. Leader states // will log, replicate, and commit the reconfiguration. raft.getRaftRole().onLeave(LeaveRequest.builder() .withMember(getMember()) .build()).whenComplete((response, error) -> { // Cancel the leave timer. cancelLeaveTimer(); if (error == null && response.status() == RaftResponse.Status.OK) { Configuration configuration = new Configuration(response.index(), response.term(), response.timestamp(), response.members()); // Configure the cluster and commit the configuration as we know the successful response // indicates commitment. configure(configuration).commit(); future.complete(null); } else { // Reset the leave timer. leaveTimeout = raft.getThreadContext().schedule(raft.getElectionTimeout(), () -> { leave(future); }); } }); } }
public class class_name { private void leave(CompletableFuture<Void> future) { // Set a timer to retry the attempt to leave the cluster. leaveTimeout = raft.getThreadContext().schedule(raft.getElectionTimeout(), () -> { leave(future); }); // Attempt to leave the cluster by submitting a LeaveRequest directly to the server state. // Non-leader states should forward the request to the leader if there is one. Leader states // will log, replicate, and commit the reconfiguration. raft.getRaftRole().onLeave(LeaveRequest.builder() .withMember(getMember()) .build()).whenComplete((response, error) -> { // Cancel the leave timer. cancelLeaveTimer(); if (error == null && response.status() == RaftResponse.Status.OK) { Configuration configuration = new Configuration(response.index(), response.term(), response.timestamp(), response.members()); // Configure the cluster and commit the configuration as we know the successful response // indicates commitment. configure(configuration).commit(); // depends on control dependency: [if], data = [none] future.complete(null); // depends on control dependency: [if], data = [none] } else { // Reset the leave timer. leaveTimeout = raft.getThreadContext().schedule(raft.getElectionTimeout(), () -> { leave(future); }); // depends on control dependency: [if], data = [none] } }); } }
public class class_name { private void parseTagkCustomRule() { if (meta.getTags() == null || meta.getTags().isEmpty()) { throw new IllegalStateException( "Timeseries meta data was missing tags"); } // first, find the tagk UIDMeta we're matching against UIDMeta tagk = null; for (UIDMeta tag: meta.getTags()) { if (tag.getType() == UniqueIdType.TAGK && tag.getName().equals(rule.getField())) { tagk = tag; break; } } if (tagk == null) { testMessage("No match on tagk [" + rule.getField() + "] for rule: " + rule); return; } // now scan the custom tags for a matching tag name and it's value testMessage("Matched tagk [" + rule.getField() + "] for rule: " + rule); final Map<String, String> custom = tagk.getCustom(); if (custom != null && custom.containsKey(rule.getCustomField())) { if (custom.get(rule.getCustomField()) == null) { throw new IllegalStateException( "Value for custom tagk field [" + rule.getCustomField() + "] was null"); } processParsedValue(custom.get(rule.getCustomField())); testMessage("Matched custom tag [" + rule.getCustomField() + "] for rule: " + rule); } else { testMessage("No match on custom tag [" + rule.getCustomField() + "] for rule: " + rule); return; } } }
public class class_name { private void parseTagkCustomRule() { if (meta.getTags() == null || meta.getTags().isEmpty()) { throw new IllegalStateException( "Timeseries meta data was missing tags"); } // first, find the tagk UIDMeta we're matching against UIDMeta tagk = null; for (UIDMeta tag: meta.getTags()) { if (tag.getType() == UniqueIdType.TAGK && tag.getName().equals(rule.getField())) { tagk = tag; // depends on control dependency: [if], data = [none] break; } } if (tagk == null) { testMessage("No match on tagk [" + rule.getField() + "] for rule: " + rule); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } // now scan the custom tags for a matching tag name and it's value testMessage("Matched tagk [" + rule.getField() + "] for rule: " + rule); final Map<String, String> custom = tagk.getCustom(); if (custom != null && custom.containsKey(rule.getCustomField())) { if (custom.get(rule.getCustomField()) == null) { throw new IllegalStateException( "Value for custom tagk field [" + rule.getCustomField() + "] was null"); } processParsedValue(custom.get(rule.getCustomField())); // depends on control dependency: [if], data = [(custom] testMessage("Matched custom tag [" + rule.getCustomField() + "] for rule: " + rule); // depends on control dependency: [if], data = [none] } else { testMessage("No match on custom tag [" + rule.getCustomField() + "] for rule: " + rule); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } } }
public class class_name { public boolean canConnect() { try { wake(); ClientSocket stream = open(); if (stream != null) { stream.free(stream.getIdleStartTime()); return true; } return false; } catch (Exception e) { log.log(Level.FINER, e.toString(), e); return false; } } }
public class class_name { public boolean canConnect() { try { wake(); // depends on control dependency: [try], data = [none] ClientSocket stream = open(); if (stream != null) { stream.free(stream.getIdleStartTime()); // depends on control dependency: [if], data = [(stream] return true; // depends on control dependency: [if], data = [none] } return false; // depends on control dependency: [try], data = [none] } catch (Exception e) { log.log(Level.FINER, e.toString(), e); return false; } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static Object instantiate(String classname, Properties info, boolean tryString, String stringarg) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { Object[] args = {info}; Constructor<?> ctor = null; Class<?> cls = Class.forName(classname); try { ctor = cls.getConstructor(Properties.class); } catch (NoSuchMethodException nsme) { if (tryString) { try { ctor = cls.getConstructor(String.class); args = new String[]{stringarg}; } catch (NoSuchMethodException nsme2) { tryString = false; } } if (!tryString) { ctor = cls.getConstructor((Class[]) null); args = null; } } return ctor.newInstance(args); } }
public class class_name { public static Object instantiate(String classname, Properties info, boolean tryString, String stringarg) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { Object[] args = {info}; Constructor<?> ctor = null; Class<?> cls = Class.forName(classname); try { ctor = cls.getConstructor(Properties.class); } catch (NoSuchMethodException nsme) { if (tryString) { try { ctor = cls.getConstructor(String.class); // depends on control dependency: [try], data = [none] args = new String[]{stringarg}; // depends on control dependency: [try], data = [none] } catch (NoSuchMethodException nsme2) { tryString = false; } // depends on control dependency: [catch], data = [none] } if (!tryString) { ctor = cls.getConstructor((Class[]) null); // depends on control dependency: [if], data = [none] args = null; // depends on control dependency: [if], data = [none] } } return ctor.newInstance(args); } }
public class class_name { public static @Nullable String externalizeUrl(@NotNull String url, @NotNull ResourceResolver resolver, @Nullable SlingHttpServletRequest request) { // apply externalization only path part String path = url; // split off query string or fragment that may be appended to the URL String urlRemainder = null; int urlRemainderPos = StringUtils.indexOfAny(path, '?', '#'); if (urlRemainderPos >= 0) { urlRemainder = path.substring(urlRemainderPos); path = path.substring(0, urlRemainderPos); } // apply reverse mapping based on current sling mapping configuration for current request // e.g. to support a host-based prefix stripping mapping configuration configured at /etc/map // please note: the sling map method does a lot of things: // 1. applies reverse mapping depending on the sling mapping configuration // (this can even add a hostname if defined in sling mapping configuration) // 2. applies namespace mangling (e.g. replace jcr: with _jcr_) // 3. adds webapp context path if required // 4. url-encodes the whole url if (request != null) { path = resolver.map(request, path); } else { path = resolver.map(path); } // remove scheme and hostname (probably added by sling mapping), but leave path in escaped form try { path = new URI(path).getRawPath(); // replace %2F back to / for better readability path = StringUtils.replace(path, "%2F", "/"); } catch (URISyntaxException ex) { throw new RuntimeException("Sling map method returned invalid URI: " + path, ex); } // build full URL again if (path == null) { return null; } else { return path + (urlRemainder != null ? urlRemainder : ""); } } }
public class class_name { public static @Nullable String externalizeUrl(@NotNull String url, @NotNull ResourceResolver resolver, @Nullable SlingHttpServletRequest request) { // apply externalization only path part String path = url; // split off query string or fragment that may be appended to the URL String urlRemainder = null; int urlRemainderPos = StringUtils.indexOfAny(path, '?', '#'); if (urlRemainderPos >= 0) { urlRemainder = path.substring(urlRemainderPos); // depends on control dependency: [if], data = [(urlRemainderPos] path = path.substring(0, urlRemainderPos); // depends on control dependency: [if], data = [none] } // apply reverse mapping based on current sling mapping configuration for current request // e.g. to support a host-based prefix stripping mapping configuration configured at /etc/map // please note: the sling map method does a lot of things: // 1. applies reverse mapping depending on the sling mapping configuration // (this can even add a hostname if defined in sling mapping configuration) // 2. applies namespace mangling (e.g. replace jcr: with _jcr_) // 3. adds webapp context path if required // 4. url-encodes the whole url if (request != null) { path = resolver.map(request, path); // depends on control dependency: [if], data = [(request] } else { path = resolver.map(path); // depends on control dependency: [if], data = [none] } // remove scheme and hostname (probably added by sling mapping), but leave path in escaped form try { path = new URI(path).getRawPath(); // depends on control dependency: [try], data = [none] // replace %2F back to / for better readability path = StringUtils.replace(path, "%2F", "/"); // depends on control dependency: [try], data = [none] } catch (URISyntaxException ex) { throw new RuntimeException("Sling map method returned invalid URI: " + path, ex); } // depends on control dependency: [catch], data = [none] // build full URL again if (path == null) { return null; // depends on control dependency: [if], data = [none] } else { return path + (urlRemainder != null ? urlRemainder : ""); // depends on control dependency: [if], data = [none] } } }
public class class_name { private boolean isNumber(String in1) { //noinspection LoopStatementThatDoesntLoop for (StringTokenizer stringTokenizer = new StringTokenizer(in1, numberCharacters); stringTokenizer.hasMoreTokens(); ) { return false; } return true; } }
public class class_name { private boolean isNumber(String in1) { //noinspection LoopStatementThatDoesntLoop for (StringTokenizer stringTokenizer = new StringTokenizer(in1, numberCharacters); stringTokenizer.hasMoreTokens(); ) { return false; // depends on control dependency: [for], data = [none] } return true; } }
public class class_name { public java.util.List<HostOffering> getOfferingSet() { if (offeringSet == null) { offeringSet = new com.amazonaws.internal.SdkInternalList<HostOffering>(); } return offeringSet; } }
public class class_name { public java.util.List<HostOffering> getOfferingSet() { if (offeringSet == null) { offeringSet = new com.amazonaws.internal.SdkInternalList<HostOffering>(); // depends on control dependency: [if], data = [none] } return offeringSet; } }
public class class_name { protected static void initEndpointInfo(List<EndpointInfo> endpoints) { for (int i = 0; i < endpoints.size(); i++) { initEndpointInfo(endpoints.get(i)); } } }
public class class_name { protected static void initEndpointInfo(List<EndpointInfo> endpoints) { for (int i = 0; i < endpoints.size(); i++) { initEndpointInfo(endpoints.get(i)); // depends on control dependency: [for], data = [i] } } }
public class class_name { public final Point2D getPoint2D(Point2D pSrcPt, Point2D pDstPt) { // Create new Point, if needed if (pDstPt == null) { pDstPt = new Point2D.Float(); } // Copy location pDstPt.setLocation(pSrcPt.getX(), pSrcPt.getY()); // Return dest return pDstPt; } }
public class class_name { public final Point2D getPoint2D(Point2D pSrcPt, Point2D pDstPt) { // Create new Point, if needed if (pDstPt == null) { pDstPt = new Point2D.Float(); // depends on control dependency: [if], data = [none] } // Copy location pDstPt.setLocation(pSrcPt.getX(), pSrcPt.getY()); // Return dest return pDstPt; } }
public class class_name { public List<ExtendedRelation> getRelationships() { List<ExtendedRelation> result = null; try { if (extendedRelationsDao.isTableExists()) { result = extendedRelationsDao.queryForAll(); } else { result = new ArrayList<>(); } } catch (SQLException e) { throw new GeoPackageException("Failed to query for relationships " + "in " + EXTENSION_NAME, e); } return result; } }
public class class_name { public List<ExtendedRelation> getRelationships() { List<ExtendedRelation> result = null; try { if (extendedRelationsDao.isTableExists()) { result = extendedRelationsDao.queryForAll(); // depends on control dependency: [if], data = [none] } else { result = new ArrayList<>(); // depends on control dependency: [if], data = [none] } } catch (SQLException e) { throw new GeoPackageException("Failed to query for relationships " + "in " + EXTENSION_NAME, e); } // depends on control dependency: [catch], data = [none] return result; } }
public class class_name { @SuppressWarnings({ "rawtypes", "unchecked" }) @Nullable public final XPath decompose(final Map<URI, Set<Object>> restrictions) { Preconditions.checkNotNull(restrictions); try { Expr remaining = null; for (final Expr node : toCNF(this.support.expr)) { URI property = null; Object valueOrRange = null; if (node instanceof LocationPath) { property = extractProperty(node); valueOrRange = Boolean.TRUE; } else if (node instanceof FunctionCallExpr) { final FunctionCallExpr call = (FunctionCallExpr) node; if ("not".equals(call.getFunctionName())) { property = extractProperty((Expr) call.getParameters().get(0)); valueOrRange = Boolean.FALSE; } } else if (node instanceof BinaryExpr) { final BinaryExpr binary = (BinaryExpr) node; property = extractProperty(binary.getLHS()); Object value = extractValue(binary.getRHS()); boolean swap = false; if (property == null || value == null) { property = extractProperty(binary.getRHS()); value = extractValue(binary.getLHS()); swap = true; } if (value instanceof Literal) { final Literal lit = (Literal) value; final URI dt = lit.getDatatype(); if (dt == null || dt.equals(XMLSchema.STRING)) { value = lit.stringValue(); } else if (dt.equals(XMLSchema.BOOLEAN)) { value = lit.booleanValue(); } else if (dt.equals(XMLSchema.DATE) || dt.equals(XMLSchema.DATETIME)) { value = lit.calendarValue().toGregorianCalendar().getTime(); } else if (dt.equals(XMLSchema.INT) || dt.equals(XMLSchema.LONG) || dt.equals(XMLSchema.DOUBLE) || dt.equals(XMLSchema.FLOAT) || dt.equals(XMLSchema.SHORT) || dt.equals(XMLSchema.BYTE) || dt.equals(XMLSchema.DECIMAL) || dt.equals(XMLSchema.INTEGER) || dt.equals(XMLSchema.NON_NEGATIVE_INTEGER) || dt.equals(XMLSchema.NON_POSITIVE_INTEGER) || dt.equals(XMLSchema.NEGATIVE_INTEGER) || dt.equals(XMLSchema.POSITIVE_INTEGER)) { value = lit.doubleValue(); } else if (dt.equals(XMLSchema.NORMALIZEDSTRING) || dt.equals(XMLSchema.TOKEN) || dt.equals(XMLSchema.NMTOKEN) || dt.equals(XMLSchema.LANGUAGE) || dt.equals(XMLSchema.NAME) || dt.equals(XMLSchema.NCNAME)) { value = lit.getLabel(); } } if (property != null && value != null) { if ("=".equals(binary.getOperator())) { valueOrRange = value; } else if (value instanceof Comparable<?>) { final Comparable<?> comp = (Comparable<?>) value; if (">".equals(binary.getOperator())) { valueOrRange = swap ? Range.lessThan(comp) : Range .greaterThan(comp); } else if (">=".equals(binary.getOperator())) { valueOrRange = swap ? Range.atMost(comp) : Range.atLeast(comp); } else if ("<".equals(binary.getOperator())) { valueOrRange = swap ? Range.greaterThan(comp) : Range .lessThan(comp); } else if ("<=".equals(binary.getOperator())) { valueOrRange = swap ? Range.atLeast(comp) : Range.atMost(comp); } } } } boolean processed = false; if (property != null && valueOrRange != null) { Set<Object> set = restrictions.get(property); if (set == null) { set = ImmutableSet.of(valueOrRange); restrictions.put(property, set); processed = true; } else { final Object oldValue = set.iterator().next(); if (oldValue instanceof Range) { final Range oldRange = (Range) oldValue; if (valueOrRange instanceof Range) { final Range newRange = (Range) valueOrRange; if (oldRange.isConnected(newRange)) { restrictions.put(property, ImmutableSet.of(oldRange.intersection(newRange))); processed = true; } } else if (valueOrRange instanceof Comparable) { if (oldRange.contains((Comparable) valueOrRange)) { restrictions.put(property, ImmutableSet.of(valueOrRange)); processed = true; } } } } } if (!processed) { remaining = remaining == null ? node : FACTORY.createAndExpr(remaining, node); } } return remaining == null ? null : parse(this.support.namespaces, remaining.getText()); } catch (final JaxenException ex) { throw new RuntimeException(ex.getMessage(), ex); } } }
public class class_name { @SuppressWarnings({ "rawtypes", "unchecked" }) @Nullable public final XPath decompose(final Map<URI, Set<Object>> restrictions) { Preconditions.checkNotNull(restrictions); try { Expr remaining = null; for (final Expr node : toCNF(this.support.expr)) { URI property = null; Object valueOrRange = null; if (node instanceof LocationPath) { property = extractProperty(node); // depends on control dependency: [if], data = [none] valueOrRange = Boolean.TRUE; // depends on control dependency: [if], data = [none] } else if (node instanceof FunctionCallExpr) { final FunctionCallExpr call = (FunctionCallExpr) node; if ("not".equals(call.getFunctionName())) { property = extractProperty((Expr) call.getParameters().get(0)); // depends on control dependency: [if], data = [none] valueOrRange = Boolean.FALSE; // depends on control dependency: [if], data = [none] } } else if (node instanceof BinaryExpr) { final BinaryExpr binary = (BinaryExpr) node; property = extractProperty(binary.getLHS()); // depends on control dependency: [if], data = [none] Object value = extractValue(binary.getRHS()); boolean swap = false; if (property == null || value == null) { property = extractProperty(binary.getRHS()); // depends on control dependency: [if], data = [none] value = extractValue(binary.getLHS()); // depends on control dependency: [if], data = [none] swap = true; // depends on control dependency: [if], data = [none] } if (value instanceof Literal) { final Literal lit = (Literal) value; final URI dt = lit.getDatatype(); if (dt == null || dt.equals(XMLSchema.STRING)) { value = lit.stringValue(); // depends on control dependency: [if], data = [none] } else if (dt.equals(XMLSchema.BOOLEAN)) { value = lit.booleanValue(); // depends on control dependency: [if], data = [none] } else if (dt.equals(XMLSchema.DATE) || dt.equals(XMLSchema.DATETIME)) { value = lit.calendarValue().toGregorianCalendar().getTime(); // depends on control dependency: [if], data = [none] } else if (dt.equals(XMLSchema.INT) || dt.equals(XMLSchema.LONG) || dt.equals(XMLSchema.DOUBLE) || dt.equals(XMLSchema.FLOAT) || dt.equals(XMLSchema.SHORT) || dt.equals(XMLSchema.BYTE) || dt.equals(XMLSchema.DECIMAL) || dt.equals(XMLSchema.INTEGER) || dt.equals(XMLSchema.NON_NEGATIVE_INTEGER) || dt.equals(XMLSchema.NON_POSITIVE_INTEGER) || dt.equals(XMLSchema.NEGATIVE_INTEGER) || dt.equals(XMLSchema.POSITIVE_INTEGER)) { value = lit.doubleValue(); // depends on control dependency: [if], data = [none] } else if (dt.equals(XMLSchema.NORMALIZEDSTRING) || dt.equals(XMLSchema.TOKEN) || dt.equals(XMLSchema.NMTOKEN) || dt.equals(XMLSchema.LANGUAGE) || dt.equals(XMLSchema.NAME) || dt.equals(XMLSchema.NCNAME)) { value = lit.getLabel(); // depends on control dependency: [if], data = [none] } } if (property != null && value != null) { if ("=".equals(binary.getOperator())) { valueOrRange = value; // depends on control dependency: [if], data = [none] } else if (value instanceof Comparable<?>) { final Comparable<?> comp = (Comparable<?>) value; if (">".equals(binary.getOperator())) { valueOrRange = swap ? Range.lessThan(comp) : Range .greaterThan(comp); // depends on control dependency: [if], data = [none] } else if (">=".equals(binary.getOperator())) { valueOrRange = swap ? Range.atMost(comp) : Range.atLeast(comp); // depends on control dependency: [if], data = [none] } else if ("<".equals(binary.getOperator())) { valueOrRange = swap ? Range.greaterThan(comp) : Range .lessThan(comp); // depends on control dependency: [if], data = [none] } else if ("<=".equals(binary.getOperator())) { valueOrRange = swap ? Range.atLeast(comp) : Range.atMost(comp); // depends on control dependency: [if], data = [none] } } } } boolean processed = false; if (property != null && valueOrRange != null) { Set<Object> set = restrictions.get(property); if (set == null) { set = ImmutableSet.of(valueOrRange); // depends on control dependency: [if], data = [none] restrictions.put(property, set); // depends on control dependency: [if], data = [none] processed = true; // depends on control dependency: [if], data = [none] } else { final Object oldValue = set.iterator().next(); if (oldValue instanceof Range) { final Range oldRange = (Range) oldValue; if (valueOrRange instanceof Range) { final Range newRange = (Range) valueOrRange; if (oldRange.isConnected(newRange)) { restrictions.put(property, ImmutableSet.of(oldRange.intersection(newRange))); // depends on control dependency: [if], data = [none] processed = true; // depends on control dependency: [if], data = [none] } } else if (valueOrRange instanceof Comparable) { if (oldRange.contains((Comparable) valueOrRange)) { restrictions.put(property, ImmutableSet.of(valueOrRange)); // depends on control dependency: [if], data = [none] processed = true; // depends on control dependency: [if], data = [none] } } } } } if (!processed) { remaining = remaining == null ? node : FACTORY.createAndExpr(remaining, node); // depends on control dependency: [if], data = [none] } } return remaining == null ? null : parse(this.support.namespaces, remaining.getText()); // depends on control dependency: [try], data = [none] } catch (final JaxenException ex) { throw new RuntimeException(ex.getMessage(), ex); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public void processMessage(final WebSocketMessage webSocketData) { setDoTransactionNotifications(true); final SecurityContext securityContext = getWebSocket().getSecurityContext(); final App app = StructrApp.getInstance(securityContext); try { final PropertyMap properties = PropertyMap.inputTypeToJavaType(securityContext, webSocketData.getNodeData()); Class type = SchemaHelper.getEntityClassForRawType(properties.get(AbstractNode.type)); final NodeInterface newNode = app.create(type, properties); TransactionCommand.registerNodeCallback(newNode, callback); // check for File node and store in WebSocket to receive chunks if (newNode instanceof File) { getWebSocket().createFileUploadHandler((File) newNode); } } catch (FrameworkException fex) { logger.warn("Could not create node.", fex); getWebSocket().send(MessageBuilder.status().code(fex.getStatus()).message(fex.getMessage()).build(), true); } } }
public class class_name { @Override public void processMessage(final WebSocketMessage webSocketData) { setDoTransactionNotifications(true); final SecurityContext securityContext = getWebSocket().getSecurityContext(); final App app = StructrApp.getInstance(securityContext); try { final PropertyMap properties = PropertyMap.inputTypeToJavaType(securityContext, webSocketData.getNodeData()); Class type = SchemaHelper.getEntityClassForRawType(properties.get(AbstractNode.type)); final NodeInterface newNode = app.create(type, properties); TransactionCommand.registerNodeCallback(newNode, callback); // depends on control dependency: [try], data = [none] // check for File node and store in WebSocket to receive chunks if (newNode instanceof File) { getWebSocket().createFileUploadHandler((File) newNode); // depends on control dependency: [if], data = [none] } } catch (FrameworkException fex) { logger.warn("Could not create node.", fex); getWebSocket().send(MessageBuilder.status().code(fex.getStatus()).message(fex.getMessage()).build(), true); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void setConfig(String configName, String configValue) { if (config == null) { config = new Properties(); } if(configValue == null) { config.remove(configName); } else { config.setProperty(configName, configValue); } } }
public class class_name { public void setConfig(String configName, String configValue) { if (config == null) { config = new Properties(); // depends on control dependency: [if], data = [none] } if(configValue == null) { config.remove(configName); // depends on control dependency: [if], data = [none] } else { config.setProperty(configName, configValue); // depends on control dependency: [if], data = [none] } } }
public class class_name { public T getExtension(String alias) { ExtensionClass<T> extensionClass = getExtensionClass(alias); if (extensionClass == null) { throw new SofaRpcRuntimeException("Not found extension of " + interfaceName + " named: \"" + alias + "\"!"); } else { if (extensible.singleton() && factory != null) { T t = factory.get(alias); if (t == null) { synchronized (this) { t = factory.get(alias); if (t == null) { t = extensionClass.getExtInstance(); factory.put(alias, t); } } } return t; } else { return extensionClass.getExtInstance(); } } } }
public class class_name { public T getExtension(String alias) { ExtensionClass<T> extensionClass = getExtensionClass(alias); if (extensionClass == null) { throw new SofaRpcRuntimeException("Not found extension of " + interfaceName + " named: \"" + alias + "\"!"); } else { if (extensible.singleton() && factory != null) { T t = factory.get(alias); if (t == null) { synchronized (this) { // depends on control dependency: [if], data = [(t] t = factory.get(alias); if (t == null) { t = extensionClass.getExtInstance(); // depends on control dependency: [if], data = [none] factory.put(alias, t); // depends on control dependency: [if], data = [none] } } } return t; // depends on control dependency: [if], data = [none] } else { return extensionClass.getExtInstance(); // depends on control dependency: [if], data = [none] } } } }
public class class_name { private static boolean isBigDecimal( Number n ) { if( n instanceof BigDecimal ){ return true; } try{ new BigDecimal( String.valueOf( n ) ); return true; }catch( NumberFormatException e ){ return false; } } }
public class class_name { private static boolean isBigDecimal( Number n ) { if( n instanceof BigDecimal ){ return true; // depends on control dependency: [if], data = [none] } try{ new BigDecimal( String.valueOf( n ) ); // depends on control dependency: [try], data = [none] return true; // depends on control dependency: [try], data = [none] }catch( NumberFormatException e ){ return false; } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static String sha1(File file) { InputStream is = null; try { is = new FileInputStream(file); return sha1(is); } catch (FileNotFoundException fnfe) { throw new RuntimeIOException.FileNotFound(file); } finally { // This must be in a catch block because sha1(InputStream) may throw RuntimeIOException. if (is != null) { try { is.close(); } catch (IOException ioe) { log.warn("Failed to close stream for File: " + file, ioe); throw new RuntimeIOException(ioe); } } } } }
public class class_name { public static String sha1(File file) { InputStream is = null; try { is = new FileInputStream(file); // depends on control dependency: [try], data = [none] return sha1(is); // depends on control dependency: [try], data = [none] } catch (FileNotFoundException fnfe) { throw new RuntimeIOException.FileNotFound(file); } finally { // depends on control dependency: [catch], data = [none] // This must be in a catch block because sha1(InputStream) may throw RuntimeIOException. if (is != null) { try { is.close(); // depends on control dependency: [try], data = [none] } catch (IOException ioe) { log.warn("Failed to close stream for File: " + file, ioe); throw new RuntimeIOException(ioe); } // depends on control dependency: [catch], data = [none] } } } }
public class class_name { static void cleanup() { String tempFolder = getTempDir().getAbsolutePath(); File dir = new File(tempFolder); File[] nativeLibFiles = dir.listFiles(new FilenameFilter() { private final String searchPattern = "secp256k1-"; public boolean accept(File dir, String name) { return name.startsWith(searchPattern) && !name.endsWith(".lck"); } }); if(nativeLibFiles != null) { for(File nativeLibFile : nativeLibFiles) { File lckFile = new File(nativeLibFile.getAbsolutePath() + ".lck"); if(!lckFile.exists()) { try { nativeLibFile.delete(); } catch(SecurityException e) { System.err.println("Failed to delete old native lib" + e.getMessage()); } } } } } }
public class class_name { static void cleanup() { String tempFolder = getTempDir().getAbsolutePath(); File dir = new File(tempFolder); File[] nativeLibFiles = dir.listFiles(new FilenameFilter() { private final String searchPattern = "secp256k1-"; public boolean accept(File dir, String name) { return name.startsWith(searchPattern) && !name.endsWith(".lck"); } }); if(nativeLibFiles != null) { for(File nativeLibFile : nativeLibFiles) { File lckFile = new File(nativeLibFile.getAbsolutePath() + ".lck"); if(!lckFile.exists()) { try { nativeLibFile.delete(); // depends on control dependency: [try], data = [none] } catch(SecurityException e) { System.err.println("Failed to delete old native lib" + e.getMessage()); } // depends on control dependency: [catch], data = [none] } } } } }
public class class_name { private static void addProperty ( final Map<String, String> props, final String key, final String value ) { if ( value == null ) { return; } props.put ( key, value ); } }
public class class_name { private static void addProperty ( final Map<String, String> props, final String key, final String value ) { if ( value == null ) { return; // depends on control dependency: [if], data = [none] } props.put ( key, value ); } }
public class class_name { private void updateVertexProperty(AtlasVertex vertex, String propertyName, Date newValue) { if (newValue != null) { Number currValue = vertex.getProperty(propertyName, Number.class); if (currValue == null || !currValue.equals(newValue.getTime())) { vertex.setProperty(propertyName, newValue.getTime()); } } } }
public class class_name { private void updateVertexProperty(AtlasVertex vertex, String propertyName, Date newValue) { if (newValue != null) { Number currValue = vertex.getProperty(propertyName, Number.class); if (currValue == null || !currValue.equals(newValue.getTime())) { vertex.setProperty(propertyName, newValue.getTime()); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public String getCPNameForClass( Class cl ) { String res = minbinNamesReverse.get(cl.getName()); if (res == null) { if (cl.isAnonymousClass()) { return getCPNameForClass(cl.getSuperclass()); } return cl.getName(); } return res; } }
public class class_name { public String getCPNameForClass( Class cl ) { String res = minbinNamesReverse.get(cl.getName()); if (res == null) { if (cl.isAnonymousClass()) { return getCPNameForClass(cl.getSuperclass()); // depends on control dependency: [if], data = [none] } return cl.getName(); // depends on control dependency: [if], data = [none] } return res; } }
public class class_name { public Iterable<Vertex> getVertices(final String label, final String[] iKey, Object[] iValue) { if (iKey.length != iValue.length) { throw new IllegalArgumentException("key names and values must be arrays of the same size"); } makeActive(); final OClass clazz = getDatabase().getMetadata().getImmutableSchemaSnapshot().getClass(label); if (clazz != null) { Set<OIndex<?>> indexes = clazz.getInvolvedIndexes(Arrays.asList(iKey)); Iterator<OIndex<?>> iterator = indexes.iterator(); while (iterator.hasNext()) { final OIndex<?> idx = iterator.next(); if (idx != null) { if ("lucene".equalsIgnoreCase(idx.getAlgorithm())) { continue; } Object[] sortedParams = new Object[iValue.length]; List<String> indexFields = idx.getDefinition().getFields(); for (int i = 0; i < iKey.length; i++) { sortedParams[indexFields.indexOf(iKey[i])] = iValue[i]; } List<Object> keys = Arrays.asList(convertKeys(idx, sortedParams)); Object key; if (indexFields.size() == 1) { key = keys.get(0); } else { key = new OCompositeKey(keys); } Object indexValue = idx.get(key); if (indexValue != null && !(indexValue instanceof Iterable<?>)) indexValue = Arrays.asList(indexValue); return new OrientClassVertexIterable(this, (Iterable<?>) indexValue, label); } } } // NO INDEX: EXECUTE A QUERY OrientGraphQuery query = (OrientGraphQuery) query(); query.labels(label); for (int i = 0; i < iKey.length; i++) { query.has(iKey[i], iValue[i]); } return query.vertices(); } }
public class class_name { public Iterable<Vertex> getVertices(final String label, final String[] iKey, Object[] iValue) { if (iKey.length != iValue.length) { throw new IllegalArgumentException("key names and values must be arrays of the same size"); } makeActive(); final OClass clazz = getDatabase().getMetadata().getImmutableSchemaSnapshot().getClass(label); if (clazz != null) { Set<OIndex<?>> indexes = clazz.getInvolvedIndexes(Arrays.asList(iKey)); // depends on control dependency: [if], data = [none] Iterator<OIndex<?>> iterator = indexes.iterator(); // depends on control dependency: [if], data = [none] while (iterator.hasNext()) { final OIndex<?> idx = iterator.next(); if (idx != null) { if ("lucene".equalsIgnoreCase(idx.getAlgorithm())) { continue; } Object[] sortedParams = new Object[iValue.length]; List<String> indexFields = idx.getDefinition().getFields(); for (int i = 0; i < iKey.length; i++) { sortedParams[indexFields.indexOf(iKey[i])] = iValue[i]; // depends on control dependency: [for], data = [i] } List<Object> keys = Arrays.asList(convertKeys(idx, sortedParams)); Object key; if (indexFields.size() == 1) { key = keys.get(0); // depends on control dependency: [if], data = [none] } else { key = new OCompositeKey(keys); // depends on control dependency: [if], data = [none] } Object indexValue = idx.get(key); if (indexValue != null && !(indexValue instanceof Iterable<?>)) indexValue = Arrays.asList(indexValue); return new OrientClassVertexIterable(this, (Iterable<?>) indexValue, label); // depends on control dependency: [if], data = [none] } } } // NO INDEX: EXECUTE A QUERY OrientGraphQuery query = (OrientGraphQuery) query(); query.labels(label); for (int i = 0; i < iKey.length; i++) { query.has(iKey[i], iValue[i]); // depends on control dependency: [for], data = [i] } return query.vertices(); } }
public class class_name { private static String getFinalResponseUrl( final HttpClientContext context, final String candidateUrl) { List<URI> redirectLocations = context.getRedirectLocations(); if (redirectLocations != null) { return redirectLocations.get(redirectLocations.size() - 1).toString(); } return candidateUrl; } }
public class class_name { private static String getFinalResponseUrl( final HttpClientContext context, final String candidateUrl) { List<URI> redirectLocations = context.getRedirectLocations(); if (redirectLocations != null) { return redirectLocations.get(redirectLocations.size() - 1).toString(); // depends on control dependency: [if], data = [(redirectLocations] } return candidateUrl; } }
public class class_name { @Override public double nextRandom() { double val = random.nextDouble(); if(val < .5) { return FastMath.log(2 * val) / rate + location; } else { return -FastMath.log(2. - 2. * val) / rate + location; } } }
public class class_name { @Override public double nextRandom() { double val = random.nextDouble(); if(val < .5) { return FastMath.log(2 * val) / rate + location; // depends on control dependency: [if], data = [none] } else { return -FastMath.log(2. - 2. * val) / rate + location; // depends on control dependency: [if], data = [none] } } }
public class class_name { public static List<PartitionDefinition> assignPartitions(List<PartitionDefinition> partitions, int currentTask, int totalTasks) { int esPartitions = partitions.size(); if (totalTasks >= esPartitions) { return (currentTask >= esPartitions ? Collections.<PartitionDefinition>emptyList() : Collections.singletonList(partitions.get(currentTask))); } else { int partitionsPerTask = esPartitions / totalTasks; int remainder = esPartitions % totalTasks; int partitionsPerCurrentTask = partitionsPerTask; // spread the reminder against the tasks if (currentTask < remainder) { partitionsPerCurrentTask++; } // find the offset inside the collection int offset = partitionsPerTask * currentTask; if (currentTask != 0) { offset += (remainder > currentTask ? 1 : remainder); } // common case if (partitionsPerCurrentTask == 1) { return Collections.singletonList(partitions.get(offset)); } List<PartitionDefinition> pa = new ArrayList<PartitionDefinition>(partitionsPerCurrentTask); for (int index = offset; index < offset + partitionsPerCurrentTask; index++) { pa.add(partitions.get(index)); } return pa; } } }
public class class_name { public static List<PartitionDefinition> assignPartitions(List<PartitionDefinition> partitions, int currentTask, int totalTasks) { int esPartitions = partitions.size(); if (totalTasks >= esPartitions) { return (currentTask >= esPartitions ? Collections.<PartitionDefinition>emptyList() : Collections.singletonList(partitions.get(currentTask))); // depends on control dependency: [if], data = [none] } else { int partitionsPerTask = esPartitions / totalTasks; int remainder = esPartitions % totalTasks; int partitionsPerCurrentTask = partitionsPerTask; // spread the reminder against the tasks if (currentTask < remainder) { partitionsPerCurrentTask++; // depends on control dependency: [if], data = [none] } // find the offset inside the collection int offset = partitionsPerTask * currentTask; if (currentTask != 0) { offset += (remainder > currentTask ? 1 : remainder); // depends on control dependency: [if], data = [none] } // common case if (partitionsPerCurrentTask == 1) { return Collections.singletonList(partitions.get(offset)); // depends on control dependency: [if], data = [none] } List<PartitionDefinition> pa = new ArrayList<PartitionDefinition>(partitionsPerCurrentTask); for (int index = offset; index < offset + partitionsPerCurrentTask; index++) { pa.add(partitions.get(index)); // depends on control dependency: [for], data = [index] } return pa; // depends on control dependency: [if], data = [none] } } }
public class class_name { public void marshall(ConferenceProvider conferenceProvider, ProtocolMarshaller protocolMarshaller) { if (conferenceProvider == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(conferenceProvider.getArn(), ARN_BINDING); protocolMarshaller.marshall(conferenceProvider.getName(), NAME_BINDING); protocolMarshaller.marshall(conferenceProvider.getType(), TYPE_BINDING); protocolMarshaller.marshall(conferenceProvider.getIPDialIn(), IPDIALIN_BINDING); protocolMarshaller.marshall(conferenceProvider.getPSTNDialIn(), PSTNDIALIN_BINDING); protocolMarshaller.marshall(conferenceProvider.getMeetingSetting(), MEETINGSETTING_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(ConferenceProvider conferenceProvider, ProtocolMarshaller protocolMarshaller) { if (conferenceProvider == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(conferenceProvider.getArn(), ARN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(conferenceProvider.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(conferenceProvider.getType(), TYPE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(conferenceProvider.getIPDialIn(), IPDIALIN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(conferenceProvider.getPSTNDialIn(), PSTNDIALIN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(conferenceProvider.getMeetingSetting(), MEETINGSETTING_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 handleMessage (Message message) { // if the client has been getting crazy with the cheeze whiz, stick a fork in them; the // first time through we end our session, subsequently _throttle is null and we just drop // any messages that come in until we've fully shutdown if (_throttle == null) { // log.info("Dropping message from force-quit client", "conn", getConnection(), // "msg", message); return; } else if (_throttle.throttleOp(message.received)) { handleThrottleExceeded(); } dispatchMessage(message); } }
public class class_name { public void handleMessage (Message message) { // if the client has been getting crazy with the cheeze whiz, stick a fork in them; the // first time through we end our session, subsequently _throttle is null and we just drop // any messages that come in until we've fully shutdown if (_throttle == null) { // log.info("Dropping message from force-quit client", "conn", getConnection(), // "msg", message); return; // depends on control dependency: [if], data = [none] } else if (_throttle.throttleOp(message.received)) { handleThrottleExceeded(); // depends on control dependency: [if], data = [none] } dispatchMessage(message); } }
public class class_name { public Number optNumber(String key, Number defaultValue) { Object val = this.opt(key); if (NULL.equals(val)) { return defaultValue; } if (val instanceof Number){ return (Number) val; } try { return stringToNumber(val.toString()); } catch (Exception e) { return defaultValue; } } }
public class class_name { public Number optNumber(String key, Number defaultValue) { Object val = this.opt(key); if (NULL.equals(val)) { return defaultValue; // depends on control dependency: [if], data = [none] } if (val instanceof Number){ return (Number) val; // depends on control dependency: [if], data = [none] } try { return stringToNumber(val.toString()); // depends on control dependency: [try], data = [none] } catch (Exception e) { return defaultValue; } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public int compareTo(ValueArray<FloatValue> o) { FloatValueArray other = (FloatValueArray) o; int min = Math.min(position, other.position); for (int i = 0; i < min; i++) { int cmp = Float.compare(data[i], other.data[i]); if (cmp != 0) { return cmp; } } return Integer.compare(position, other.position); } }
public class class_name { @Override public int compareTo(ValueArray<FloatValue> o) { FloatValueArray other = (FloatValueArray) o; int min = Math.min(position, other.position); for (int i = 0; i < min; i++) { int cmp = Float.compare(data[i], other.data[i]); if (cmp != 0) { return cmp; // depends on control dependency: [if], data = [none] } } return Integer.compare(position, other.position); } }
public class class_name { public void addConvergedSessionDeletegateToSession(String sessionId, ConvergedSessionDelegate convergedSessionDelegate){ ConvergedInMemorySession sess = sessions.get(sessionId); if(sess!=null){ sess.addConvergedSessionDelegate(convergedSessionDelegate); } } }
public class class_name { public void addConvergedSessionDeletegateToSession(String sessionId, ConvergedSessionDelegate convergedSessionDelegate){ ConvergedInMemorySession sess = sessions.get(sessionId); if(sess!=null){ sess.addConvergedSessionDelegate(convergedSessionDelegate); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void startActivity(int requestCode, Context currentContext, Intent intent, Postcard postcard, NavigationCallback callback) { if (requestCode >= 0) { // Need start for result if (currentContext instanceof Activity) { ActivityCompat.startActivityForResult((Activity) currentContext, intent, requestCode, postcard.getOptionsBundle()); } else { logger.warning(Consts.TAG, "Must use [navigation(activity, ...)] to support [startActivityForResult]"); } } else { ActivityCompat.startActivity(currentContext, intent, postcard.getOptionsBundle()); } if ((-1 != postcard.getEnterAnim() && -1 != postcard.getExitAnim()) && currentContext instanceof Activity) { // Old version. ((Activity) currentContext).overridePendingTransition(postcard.getEnterAnim(), postcard.getExitAnim()); } if (null != callback) { // Navigation over. callback.onArrival(postcard); } } }
public class class_name { private void startActivity(int requestCode, Context currentContext, Intent intent, Postcard postcard, NavigationCallback callback) { if (requestCode >= 0) { // Need start for result if (currentContext instanceof Activity) { ActivityCompat.startActivityForResult((Activity) currentContext, intent, requestCode, postcard.getOptionsBundle()); // depends on control dependency: [if], data = [none] } else { logger.warning(Consts.TAG, "Must use [navigation(activity, ...)] to support [startActivityForResult]"); // depends on control dependency: [if], data = [none] } } else { ActivityCompat.startActivity(currentContext, intent, postcard.getOptionsBundle()); // depends on control dependency: [if], data = [none] } if ((-1 != postcard.getEnterAnim() && -1 != postcard.getExitAnim()) && currentContext instanceof Activity) { // Old version. ((Activity) currentContext).overridePendingTransition(postcard.getEnterAnim(), postcard.getExitAnim()); // depends on control dependency: [if], data = [none] } if (null != callback) { // Navigation over. callback.onArrival(postcard); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void myFocusGained() { m_bInFocus = true; String strText = super.getText(); if (m_strDescription.equals(strText)) { // Don't notify of change if (m_actionListener != null) this.removeActionListener(m_actionListener); this.changeFont(false); super.setText(Constants.BLANK); if (m_actionListener != null) this.addActionListener(m_actionListener); } } }
public class class_name { public void myFocusGained() { m_bInFocus = true; String strText = super.getText(); if (m_strDescription.equals(strText)) { // Don't notify of change if (m_actionListener != null) this.removeActionListener(m_actionListener); this.changeFont(false); // depends on control dependency: [if], data = [none] super.setText(Constants.BLANK); // depends on control dependency: [if], data = [none] if (m_actionListener != null) this.addActionListener(m_actionListener); } } }
public class class_name { @SuppressWarnings({"unchecked", "SuspiciousToArrayCall"}) public Cache<K, V> buildAsIs() { if (config.getValueType() == null) { config.setValueType((Class<V>) Object.class); } if (config.getKeyType() == null) { config.setKeyType((Class<K>) Object.class); } if (config.getName() == null) { config.setName(deriveNameFromStackTrace()); } checkConfiguration(); Class<?> _implClass = HeapCache.class; Class<?> _keyType = config.getKeyType().getType(); if (_keyType == Integer.class) { _implClass = IntHeapCache.class; } else if (_keyType == Long.class) { _implClass = LongHeapCache.class; } InternalCache<K, V> _cache = constructImplementationAndFillParameters(_implClass); InternalClock _timeReference = (InternalClock) _cache.createCustomization(config.getTimeReference()); if (_timeReference == null) { _timeReference = ClockDefaultImpl.INSTANCE; } HeapCache bc = (HeapCache) _cache; bc.setCacheManager(manager); if (config.hasCacheClosedListeners()) { bc.setCacheClosedListeners(config.getCacheClosedListeners()); } configureViaSettersDirect(bc); bc.setClock(_timeReference); if (config.isRefreshAhead() && !( config.getAsyncLoader() != null || config.getLoader() != null || config.getAdvancedLoader() != null)) { throw new IllegalArgumentException("refresh ahead enabled, but no loader defined"); } boolean _wrap = config.getWeigher() != null || config.hasListeners() || config.hasAsyncListeners() || config.getWriter() != null || config.getAsyncLoader() != null; WiredCache<K, V> wc = null; if (_wrap) { if (_keyType == Integer.class) { wc = (WiredCache<K, V>) new IntWiredCache<V>(); } else if (_keyType == Long.class) { wc = (WiredCache<K, V>) new LongWiredCache<V>(); } else { wc = new WiredCache<K, V>(); } wc.heapCache = bc; _cache = wc; } String _name = manager.newCache(_cache, bc.getName()); bc.setName(_name); if (_wrap) { wc.loader = bc.loader; wc.writer = (CacheWriter<K, V>) bc.createCustomization(config.getWriter()); wc.asyncLoader = (AsyncCacheLoader<K, V>) bc.createCustomization(config.getAsyncLoader()); List<CacheEntryCreatedListener<K, V>> _syncCreatedListeners = new ArrayList<CacheEntryCreatedListener<K, V>>(); List<CacheEntryUpdatedListener<K, V>> _syncUpdatedListeners = new ArrayList<CacheEntryUpdatedListener<K, V>>(); List<CacheEntryRemovedListener<K, V>> _syncRemovedListeners = new ArrayList<CacheEntryRemovedListener<K, V>>(); List<CacheEntryExpiredListener<K, V>> _syncExpiredListeners = new ArrayList<CacheEntryExpiredListener<K, V>>(); List<CacheEntryEvictedListener<K, V>> _syncEvictedListeners = new ArrayList<CacheEntryEvictedListener<K,V>>(); List<CacheEntryExpiredListener<K, V>> _expiredListeners = new ArrayList<CacheEntryExpiredListener<K, V>>(); if (config.hasListeners()) { for (CustomizationSupplier<CacheEntryOperationListener<K, V>> f : config.getListeners()) { CacheEntryOperationListener<K, V> el = ( CacheEntryOperationListener<K, V>) bc.createCustomization(f); if (el instanceof CacheEntryCreatedListener) { _syncCreatedListeners.add((CacheEntryCreatedListener) el); } if (el instanceof CacheEntryUpdatedListener) { _syncUpdatedListeners.add((CacheEntryUpdatedListener) el); } if (el instanceof CacheEntryRemovedListener) { _syncRemovedListeners.add((CacheEntryRemovedListener) el); } if (el instanceof CacheEntryExpiredListener) { _expiredListeners.add((CacheEntryExpiredListener) el); } if (el instanceof CacheEntryEvictedListener) { _syncEvictedListeners.add((CacheEntryEvictedListener) el); } } } if (config.hasAsyncListeners() || !_expiredListeners.isEmpty()) { Executor _executor = DEFAULT_ASYNC_LISTENER_EXECUTOR; if (config.getAsyncListenerExecutor() != null) { _executor = _cache.createCustomization(config.getAsyncListenerExecutor()); } AsyncDispatcher<K> _asyncDispatcher = new AsyncDispatcher<K>(wc, _executor); List<CacheEntryCreatedListener<K, V>> cll = new ArrayList<CacheEntryCreatedListener<K, V>>(); List<CacheEntryUpdatedListener<K, V>> ull = new ArrayList<CacheEntryUpdatedListener<K, V>>(); List<CacheEntryRemovedListener<K, V>> rll = new ArrayList<CacheEntryRemovedListener<K, V>>(); List<CacheEntryExpiredListener<K, V>> ell = new ArrayList<CacheEntryExpiredListener<K, V>>(); List<CacheEntryEvictedListener<K, V>> evl = new ArrayList<CacheEntryEvictedListener<K, V>>(); for (CustomizationSupplier<CacheEntryOperationListener<K, V>> f : config.getAsyncListeners()) { CacheEntryOperationListener<K, V> el = (CacheEntryOperationListener<K, V>) bc.createCustomization(f); if (el instanceof CacheEntryCreatedListener) { cll.add((CacheEntryCreatedListener) el); } if (el instanceof CacheEntryUpdatedListener) { ull.add((CacheEntryUpdatedListener) el); } if (el instanceof CacheEntryRemovedListener) { rll.add((CacheEntryRemovedListener) el); } if (el instanceof CacheEntryExpiredListener) { ell.add((CacheEntryExpiredListener) el); } if (el instanceof CacheEntryEvictedListener) { evl.add((CacheEntryEvictedListener) el); } } for (CacheEntryCreatedListener l : cll) { _syncCreatedListeners.add(new AsyncCreatedListener<K, V>(_asyncDispatcher, l)); } for (CacheEntryUpdatedListener l : ull) { _syncUpdatedListeners.add(new AsyncUpdatedListener<K, V>(_asyncDispatcher, l)); } for (CacheEntryRemovedListener l : rll) { _syncRemovedListeners.add(new AsyncRemovedListener<K, V>(_asyncDispatcher, l)); } for (CacheEntryExpiredListener l : ell) { _syncExpiredListeners.add(new AsyncExpiredListener<K, V>(_asyncDispatcher, l)); } for (CacheEntryExpiredListener l : _expiredListeners) { _syncExpiredListeners.add(new AsyncExpiredListener<K, V>(_asyncDispatcher, l)); } for (CacheEntryEvictedListener l : evl) { _syncEvictedListeners.add(new AsyncEvictedListener<K, V>(_asyncDispatcher, l)); } } if (!_syncCreatedListeners.isEmpty()) { wc.syncEntryCreatedListeners = _syncCreatedListeners.toArray(new CacheEntryCreatedListener[0]); } if (!_syncUpdatedListeners.isEmpty()) { wc.syncEntryUpdatedListeners = _syncUpdatedListeners.toArray(new CacheEntryUpdatedListener[0]); } if (!_syncRemovedListeners.isEmpty()) { wc.syncEntryRemovedListeners = _syncRemovedListeners.toArray(new CacheEntryRemovedListener[0]); } if (!_syncExpiredListeners.isEmpty()) { wc.syncEntryExpiredListeners = _syncExpiredListeners.toArray(new CacheEntryExpiredListener[0]); } if (!_syncEvictedListeners.isEmpty()) { wc.syncEntryEvictedListeners = _syncEvictedListeners.toArray(new CacheEntryEvictedListener[0]); } bc.eviction = constructEviction(bc, wc, config); TimingHandler rh = TimingHandler.of(_timeReference, config); bc.setTiming(rh); wc.init(); } else { TimingHandler rh = TimingHandler.of(_timeReference, config); bc.setTiming(rh); bc.eviction = constructEviction(bc, HeapCacheListener.NO_OPERATION, config); bc.init(); } manager.sendCreatedEvent(_cache, config); return _cache; } }
public class class_name { @SuppressWarnings({"unchecked", "SuspiciousToArrayCall"}) public Cache<K, V> buildAsIs() { if (config.getValueType() == null) { config.setValueType((Class<V>) Object.class); // depends on control dependency: [if], data = [none] } if (config.getKeyType() == null) { config.setKeyType((Class<K>) Object.class); // depends on control dependency: [if], data = [none] } if (config.getName() == null) { config.setName(deriveNameFromStackTrace()); // depends on control dependency: [if], data = [none] } checkConfiguration(); Class<?> _implClass = HeapCache.class; Class<?> _keyType = config.getKeyType().getType(); if (_keyType == Integer.class) { _implClass = IntHeapCache.class; // depends on control dependency: [if], data = [none] } else if (_keyType == Long.class) { _implClass = LongHeapCache.class; // depends on control dependency: [if], data = [none] } InternalCache<K, V> _cache = constructImplementationAndFillParameters(_implClass); InternalClock _timeReference = (InternalClock) _cache.createCustomization(config.getTimeReference()); if (_timeReference == null) { _timeReference = ClockDefaultImpl.INSTANCE; // depends on control dependency: [if], data = [none] } HeapCache bc = (HeapCache) _cache; bc.setCacheManager(manager); if (config.hasCacheClosedListeners()) { bc.setCacheClosedListeners(config.getCacheClosedListeners()); // depends on control dependency: [if], data = [none] } configureViaSettersDirect(bc); bc.setClock(_timeReference); if (config.isRefreshAhead() && !( config.getAsyncLoader() != null || config.getLoader() != null || config.getAdvancedLoader() != null)) { throw new IllegalArgumentException("refresh ahead enabled, but no loader defined"); } boolean _wrap = config.getWeigher() != null || config.hasListeners() || config.hasAsyncListeners() || config.getWriter() != null || config.getAsyncLoader() != null; WiredCache<K, V> wc = null; if (_wrap) { if (_keyType == Integer.class) { wc = (WiredCache<K, V>) new IntWiredCache<V>(); // depends on control dependency: [if], data = [none] } else if (_keyType == Long.class) { wc = (WiredCache<K, V>) new LongWiredCache<V>(); // depends on control dependency: [if], data = [none] } else { wc = new WiredCache<K, V>(); // depends on control dependency: [if], data = [none] } wc.heapCache = bc; // depends on control dependency: [if], data = [none] _cache = wc; // depends on control dependency: [if], data = [none] } String _name = manager.newCache(_cache, bc.getName()); bc.setName(_name); if (_wrap) { wc.loader = bc.loader; // depends on control dependency: [if], data = [none] wc.writer = (CacheWriter<K, V>) bc.createCustomization(config.getWriter()); // depends on control dependency: [if], data = [none] wc.asyncLoader = (AsyncCacheLoader<K, V>) bc.createCustomization(config.getAsyncLoader()); // depends on control dependency: [if], data = [none] List<CacheEntryCreatedListener<K, V>> _syncCreatedListeners = new ArrayList<CacheEntryCreatedListener<K, V>>(); List<CacheEntryUpdatedListener<K, V>> _syncUpdatedListeners = new ArrayList<CacheEntryUpdatedListener<K, V>>(); List<CacheEntryRemovedListener<K, V>> _syncRemovedListeners = new ArrayList<CacheEntryRemovedListener<K, V>>(); List<CacheEntryExpiredListener<K, V>> _syncExpiredListeners = new ArrayList<CacheEntryExpiredListener<K, V>>(); List<CacheEntryEvictedListener<K, V>> _syncEvictedListeners = new ArrayList<CacheEntryEvictedListener<K,V>>(); List<CacheEntryExpiredListener<K, V>> _expiredListeners = new ArrayList<CacheEntryExpiredListener<K, V>>(); if (config.hasListeners()) { for (CustomizationSupplier<CacheEntryOperationListener<K, V>> f : config.getListeners()) { CacheEntryOperationListener<K, V> el = ( CacheEntryOperationListener<K, V>) bc.createCustomization(f); if (el instanceof CacheEntryCreatedListener) { _syncCreatedListeners.add((CacheEntryCreatedListener) el); // depends on control dependency: [if], data = [none] } if (el instanceof CacheEntryUpdatedListener) { _syncUpdatedListeners.add((CacheEntryUpdatedListener) el); // depends on control dependency: [if], data = [none] } if (el instanceof CacheEntryRemovedListener) { _syncRemovedListeners.add((CacheEntryRemovedListener) el); // depends on control dependency: [if], data = [none] } if (el instanceof CacheEntryExpiredListener) { _expiredListeners.add((CacheEntryExpiredListener) el); // depends on control dependency: [if], data = [none] } if (el instanceof CacheEntryEvictedListener) { _syncEvictedListeners.add((CacheEntryEvictedListener) el); // depends on control dependency: [if], data = [none] } } } if (config.hasAsyncListeners() || !_expiredListeners.isEmpty()) { Executor _executor = DEFAULT_ASYNC_LISTENER_EXECUTOR; if (config.getAsyncListenerExecutor() != null) { _executor = _cache.createCustomization(config.getAsyncListenerExecutor()); // depends on control dependency: [if], data = [(config.getAsyncListenerExecutor()] } AsyncDispatcher<K> _asyncDispatcher = new AsyncDispatcher<K>(wc, _executor); List<CacheEntryCreatedListener<K, V>> cll = new ArrayList<CacheEntryCreatedListener<K, V>>(); List<CacheEntryUpdatedListener<K, V>> ull = new ArrayList<CacheEntryUpdatedListener<K, V>>(); List<CacheEntryRemovedListener<K, V>> rll = new ArrayList<CacheEntryRemovedListener<K, V>>(); List<CacheEntryExpiredListener<K, V>> ell = new ArrayList<CacheEntryExpiredListener<K, V>>(); List<CacheEntryEvictedListener<K, V>> evl = new ArrayList<CacheEntryEvictedListener<K, V>>(); for (CustomizationSupplier<CacheEntryOperationListener<K, V>> f : config.getAsyncListeners()) { CacheEntryOperationListener<K, V> el = (CacheEntryOperationListener<K, V>) bc.createCustomization(f); if (el instanceof CacheEntryCreatedListener) { cll.add((CacheEntryCreatedListener) el); // depends on control dependency: [if], data = [none] } if (el instanceof CacheEntryUpdatedListener) { ull.add((CacheEntryUpdatedListener) el); // depends on control dependency: [if], data = [none] } if (el instanceof CacheEntryRemovedListener) { rll.add((CacheEntryRemovedListener) el); // depends on control dependency: [if], data = [none] } if (el instanceof CacheEntryExpiredListener) { ell.add((CacheEntryExpiredListener) el); // depends on control dependency: [if], data = [none] } if (el instanceof CacheEntryEvictedListener) { evl.add((CacheEntryEvictedListener) el); // depends on control dependency: [if], data = [none] } } for (CacheEntryCreatedListener l : cll) { _syncCreatedListeners.add(new AsyncCreatedListener<K, V>(_asyncDispatcher, l)); // depends on control dependency: [for], data = [l] } for (CacheEntryUpdatedListener l : ull) { _syncUpdatedListeners.add(new AsyncUpdatedListener<K, V>(_asyncDispatcher, l)); // depends on control dependency: [for], data = [l] } for (CacheEntryRemovedListener l : rll) { _syncRemovedListeners.add(new AsyncRemovedListener<K, V>(_asyncDispatcher, l)); // depends on control dependency: [for], data = [l] } for (CacheEntryExpiredListener l : ell) { _syncExpiredListeners.add(new AsyncExpiredListener<K, V>(_asyncDispatcher, l)); // depends on control dependency: [for], data = [l] } for (CacheEntryExpiredListener l : _expiredListeners) { _syncExpiredListeners.add(new AsyncExpiredListener<K, V>(_asyncDispatcher, l)); // depends on control dependency: [for], data = [l] } for (CacheEntryEvictedListener l : evl) { _syncEvictedListeners.add(new AsyncEvictedListener<K, V>(_asyncDispatcher, l)); // depends on control dependency: [for], data = [l] } } if (!_syncCreatedListeners.isEmpty()) { wc.syncEntryCreatedListeners = _syncCreatedListeners.toArray(new CacheEntryCreatedListener[0]); // depends on control dependency: [if], data = [none] } if (!_syncUpdatedListeners.isEmpty()) { wc.syncEntryUpdatedListeners = _syncUpdatedListeners.toArray(new CacheEntryUpdatedListener[0]); // depends on control dependency: [if], data = [none] } if (!_syncRemovedListeners.isEmpty()) { wc.syncEntryRemovedListeners = _syncRemovedListeners.toArray(new CacheEntryRemovedListener[0]); // depends on control dependency: [if], data = [none] } if (!_syncExpiredListeners.isEmpty()) { wc.syncEntryExpiredListeners = _syncExpiredListeners.toArray(new CacheEntryExpiredListener[0]); // depends on control dependency: [if], data = [none] } if (!_syncEvictedListeners.isEmpty()) { wc.syncEntryEvictedListeners = _syncEvictedListeners.toArray(new CacheEntryEvictedListener[0]); // depends on control dependency: [if], data = [none] } bc.eviction = constructEviction(bc, wc, config); // depends on control dependency: [if], data = [none] TimingHandler rh = TimingHandler.of(_timeReference, config); bc.setTiming(rh); // depends on control dependency: [if], data = [none] wc.init(); // depends on control dependency: [if], data = [none] } else { TimingHandler rh = TimingHandler.of(_timeReference, config); bc.setTiming(rh); // depends on control dependency: [if], data = [none] bc.eviction = constructEviction(bc, HeapCacheListener.NO_OPERATION, config); // depends on control dependency: [if], data = [none] bc.init(); // depends on control dependency: [if], data = [none] } manager.sendCreatedEvent(_cache, config); return _cache; } }
public class class_name { @SuppressWarnings({"unused", "WeakerAccess"}) public void setOffline(boolean value){ offline = value; if (offline) { getConfigLogger().debug(getAccountId(), "CleverTap Instance has been set to offline, won't send events queue"); } else { getConfigLogger().debug(getAccountId(), "CleverTap Instance has been set to online, sending events queue"); flush(); } } }
public class class_name { @SuppressWarnings({"unused", "WeakerAccess"}) public void setOffline(boolean value){ offline = value; if (offline) { getConfigLogger().debug(getAccountId(), "CleverTap Instance has been set to offline, won't send events queue"); // depends on control dependency: [if], data = [none] } else { getConfigLogger().debug(getAccountId(), "CleverTap Instance has been set to online, sending events queue"); // depends on control dependency: [if], data = [none] flush(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public String curiedRelFrom(final String rel) { if (isMatchingCuriedRel(rel)) { return rel; } if (isMatchingExpandedRel(rel)) { return curi.getName() + ":" + relPlaceHolderFrom(rel); } throw new IllegalArgumentException("Rel does not match the CURI template."); } }
public class class_name { public String curiedRelFrom(final String rel) { if (isMatchingCuriedRel(rel)) { return rel; // depends on control dependency: [if], data = [none] } if (isMatchingExpandedRel(rel)) { return curi.getName() + ":" + relPlaceHolderFrom(rel); // depends on control dependency: [if], data = [none] } throw new IllegalArgumentException("Rel does not match the CURI template."); } }
public class class_name { public void marshall(LoggingConfiguration loggingConfiguration, ProtocolMarshaller protocolMarshaller) { if (loggingConfiguration == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(loggingConfiguration.getResourceArn(), RESOURCEARN_BINDING); protocolMarshaller.marshall(loggingConfiguration.getLogDestinationConfigs(), LOGDESTINATIONCONFIGS_BINDING); protocolMarshaller.marshall(loggingConfiguration.getRedactedFields(), REDACTEDFIELDS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(LoggingConfiguration loggingConfiguration, ProtocolMarshaller protocolMarshaller) { if (loggingConfiguration == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(loggingConfiguration.getResourceArn(), RESOURCEARN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(loggingConfiguration.getLogDestinationConfigs(), LOGDESTINATIONCONFIGS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(loggingConfiguration.getRedactedFields(), REDACTEDFIELDS_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 String replaceVariables(String input, Map<String, Object> variables, boolean systemOverrideMode) { Matcher matcher = VARIABLE_PATTERN.matcher(input); String result = input; while(matcher.find()) { String variableName = matcher.group(); variableName = variableName.substring(2, variableName.length()-1); Object variable = resolveVariable(variableName, variables, systemOverrideMode); if(variable != null) { result = result.replaceFirst(VARIABLE_PATTERN.pattern(), variable.toString().replace("\\", "\\\\")); } } return result; } }
public class class_name { public static String replaceVariables(String input, Map<String, Object> variables, boolean systemOverrideMode) { Matcher matcher = VARIABLE_PATTERN.matcher(input); String result = input; while(matcher.find()) { String variableName = matcher.group(); variableName = variableName.substring(2, variableName.length()-1); // depends on control dependency: [while], data = [none] Object variable = resolveVariable(variableName, variables, systemOverrideMode); if(variable != null) { result = result.replaceFirst(VARIABLE_PATTERN.pattern(), variable.toString().replace("\\", "\\\\")); // depends on control dependency: [if], data = [none] } } return result; } }
public class class_name { public NodeGroupConfiguration withReplicaAvailabilityZones(String... replicaAvailabilityZones) { if (this.replicaAvailabilityZones == null) { setReplicaAvailabilityZones(new com.amazonaws.internal.SdkInternalList<String>(replicaAvailabilityZones.length)); } for (String ele : replicaAvailabilityZones) { this.replicaAvailabilityZones.add(ele); } return this; } }
public class class_name { public NodeGroupConfiguration withReplicaAvailabilityZones(String... replicaAvailabilityZones) { if (this.replicaAvailabilityZones == null) { setReplicaAvailabilityZones(new com.amazonaws.internal.SdkInternalList<String>(replicaAvailabilityZones.length)); // depends on control dependency: [if], data = [none] } for (String ele : replicaAvailabilityZones) { this.replicaAvailabilityZones.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { public void setBorderPaint(final Paint PAINT) { if (null == borderPaint) { _borderPaint = PAINT; fireUpdateEvent(REDRAW_EVENT); } else { borderPaint.set(PAINT); } } }
public class class_name { public void setBorderPaint(final Paint PAINT) { if (null == borderPaint) { _borderPaint = PAINT; // depends on control dependency: [if], data = [none] fireUpdateEvent(REDRAW_EVENT); // depends on control dependency: [if], data = [none] } else { borderPaint.set(PAINT); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void expireOldEntries () { // Expire old entries final ICommonsList <IReIndexWorkItem> aExpiredItems = m_aReIndexList.getAndRemoveAllEntries (IReIndexWorkItem::isExpired); if (aExpiredItems.isNotEmpty ()) { LOGGER.info ("Expiring " + aExpiredItems.size () + " re-index work items and move them to the dead list"); for (final IReIndexWorkItem aItem : aExpiredItems) { // remove them from the overall list but move to dead item list m_aRWLock.writeLocked ( () -> m_aUniqueItems.remove (aItem.getWorkItem ())); // move all to the dead item list m_aDeadList.addItem ((ReIndexWorkItem) aItem); LOGGER.info ("Added " + aItem.getLogText () + " to the dead list"); } } } }
public class class_name { public void expireOldEntries () { // Expire old entries final ICommonsList <IReIndexWorkItem> aExpiredItems = m_aReIndexList.getAndRemoveAllEntries (IReIndexWorkItem::isExpired); if (aExpiredItems.isNotEmpty ()) { LOGGER.info ("Expiring " + aExpiredItems.size () + " re-index work items and move them to the dead list"); // depends on control dependency: [if], data = [none] for (final IReIndexWorkItem aItem : aExpiredItems) { // remove them from the overall list but move to dead item list m_aRWLock.writeLocked ( () -> m_aUniqueItems.remove (aItem.getWorkItem ())); // depends on control dependency: [for], data = [aItem] // move all to the dead item list m_aDeadList.addItem ((ReIndexWorkItem) aItem); // depends on control dependency: [for], data = [aItem] LOGGER.info ("Added " + aItem.getLogText () + " to the dead list"); // depends on control dependency: [for], data = [aItem] } } } }
public class class_name { public static RpcResponse rpcResponse(Status status, @Nullable Object message) { if (status.isOk()) { return RpcResponse.of(message); } else { return RpcResponse.ofFailure(status.asException()); } } }
public class class_name { public static RpcResponse rpcResponse(Status status, @Nullable Object message) { if (status.isOk()) { return RpcResponse.of(message); // depends on control dependency: [if], data = [none] } else { return RpcResponse.ofFailure(status.asException()); // depends on control dependency: [if], data = [none] } } }
public class class_name { private static void resetHostList(AuroraListener listener, Deque<HostAddress> loopAddresses) { //if all servers have been connected without result //add back all servers List<HostAddress> servers = new ArrayList<>(); servers.addAll(listener.getUrlParser().getHostAddresses()); Collections.shuffle(servers); //if cluster host is set, add it to the end of the list if (listener.getClusterHostAddress() != null && listener.getUrlParser().getHostAddresses().size() < 2) { servers.add(listener.getClusterHostAddress()); } //remove current connected hosts to avoid reconnect them servers.removeAll(listener.connectedHosts()); loopAddresses.clear(); loopAddresses.addAll(servers); } }
public class class_name { private static void resetHostList(AuroraListener listener, Deque<HostAddress> loopAddresses) { //if all servers have been connected without result //add back all servers List<HostAddress> servers = new ArrayList<>(); servers.addAll(listener.getUrlParser().getHostAddresses()); Collections.shuffle(servers); //if cluster host is set, add it to the end of the list if (listener.getClusterHostAddress() != null && listener.getUrlParser().getHostAddresses().size() < 2) { servers.add(listener.getClusterHostAddress()); // depends on control dependency: [if], data = [(listener.getClusterHostAddress()] } //remove current connected hosts to avoid reconnect them servers.removeAll(listener.connectedHosts()); loopAddresses.clear(); loopAddresses.addAll(servers); } }
public class class_name { String getForwardPluginUri( String pluginId, @Nullable @CheckForNull String pathRemainder, @Nullable @CheckForNull String queryString) { // get plugin path with elevated permissions because the anonymous user can also request plugins Plugin plugin = runAsSystem(() -> dataService.findOneById(PLUGIN, pluginId, Plugin.class)); if (plugin == null) { throw new UnknownPluginException(pluginId); } StringBuilder strBuilder = new StringBuilder("forward:"); strBuilder.append(PluginController.PLUGIN_URI_PREFIX).append(plugin.getPath()); // If you do not append the trailing slash the queryString will be appended by an unknown code // snippet. // The trailing slash is needed for clients to serve resources 'relative' to the URI-path. if (pluginId.startsWith("app")) { strBuilder.append("/"); } if (pathRemainder != null && !pathRemainder.isEmpty()) { strBuilder.append("/").append(pathRemainder); } if (queryString != null && !queryString.isEmpty()) { strBuilder.append('?').append(queryString); } return strBuilder.toString(); } }
public class class_name { String getForwardPluginUri( String pluginId, @Nullable @CheckForNull String pathRemainder, @Nullable @CheckForNull String queryString) { // get plugin path with elevated permissions because the anonymous user can also request plugins Plugin plugin = runAsSystem(() -> dataService.findOneById(PLUGIN, pluginId, Plugin.class)); if (plugin == null) { throw new UnknownPluginException(pluginId); } StringBuilder strBuilder = new StringBuilder("forward:"); strBuilder.append(PluginController.PLUGIN_URI_PREFIX).append(plugin.getPath()); // If you do not append the trailing slash the queryString will be appended by an unknown code // snippet. // The trailing slash is needed for clients to serve resources 'relative' to the URI-path. if (pluginId.startsWith("app")) { strBuilder.append("/"); // depends on control dependency: [if], data = [none] } if (pathRemainder != null && !pathRemainder.isEmpty()) { strBuilder.append("/").append(pathRemainder); // depends on control dependency: [if], data = [(pathRemainder] } if (queryString != null && !queryString.isEmpty()) { strBuilder.append('?').append(queryString); // depends on control dependency: [if], data = [(queryString] } return strBuilder.toString(); } }
public class class_name { public static int getMillisYield() { String s = System.getProperty(MILLIS_YIELD_PROPERTY); int millis = DEFAULT_MILLIS_YIELD; if (s != null) { try { millis = Integer.parseInt(s); } catch (NumberFormatException ex) { // records remains DEFAULT_MILLIS_YIELD } } return millis; } }
public class class_name { public static int getMillisYield() { String s = System.getProperty(MILLIS_YIELD_PROPERTY); int millis = DEFAULT_MILLIS_YIELD; if (s != null) { try { millis = Integer.parseInt(s); // depends on control dependency: [try], data = [none] } catch (NumberFormatException ex) { // records remains DEFAULT_MILLIS_YIELD } // depends on control dependency: [catch], data = [none] } return millis; } }
public class class_name { private static void addDelegateMethod(ClassWriter cw, String tieClassName, Set<String> classConstantFieldNames, String servantClassName, String servantDescriptor, Method method, String idlName, boolean isRmiRemote, int rmicCompatible) throws EJBConfigurationException { GeneratorAdapter mg; Class<?>[] methodParameters = method.getParameterTypes(); Type[] argTypes = getTypes(methodParameters); final int numArgs = argTypes.length; Class<?> returnClass = method.getReturnType(); Type returnType = Type.getType(returnClass); String methodDescriptor = Type.getMethodDescriptor(returnType, argTypes); Class<?>[] checkedExceptions = DeploymentUtil.getCheckedExceptions(method, isRmiRemote, DeploymentUtil.DeploymentTarget.TIE); // d660332 Type[] checkedTypes = getTypes(checkedExceptions); int numChecked = checkedExceptions.length; if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, INDENT + "adding method : " + idlName + " (Lorg/omg/CORBA_2_3/portable/InputStream;" + "Lorg/omg/CORBA/portable/ResponseHandler;)" + "Lorg/omg/CORBA/portable/OutputStream;"); // ----------------------------------------------------------------------- // private OutputStream <idl name> (InputStream in , ResponseHandler reply) // throws Throwable // ----------------------------------------------------------------------- Type delegateReturnType = TYPE_CORBA_OutputStream; Type[] delegateArgTypes = { TYPE_CORBA_2_3_InputStream, TYPE_CORBA_ResponseHandler }; Type[] delegateExceptionTypes = { TYPE_Throwable }; org.objectweb.asm.commons.Method m = new org.objectweb.asm.commons.Method(idlName, delegateReturnType, delegateArgTypes); // Create an ASM GeneratorAdapter object for the ASM Method, which // makes generating dynamic code much easier... as it keeps track // of the position of the arguements and local variables, etc. mg = new GeneratorAdapter(ACC_PRIVATE, m, null, delegateExceptionTypes, cw); // ----------------------------------------------------------------------- // Begin Method Code... // ----------------------------------------------------------------------- mg.visitCode(); /* * mg.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); * mg.visitTypeInsn(NEW, "java/lang/StringBuilder"); * mg.visitInsn(DUP); * mg.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "()V"); * mg.visitLdcInsn(idlName + " called!!"); * mg.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;"); * mg.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;"); * mg.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", * "(Ljava/lang/String;)V"); */ // ----------------------------------------------------------------------- // <arg type> argX = in.read_<primitive>(); // or // <arg type> argX = (<arg type>)in.read_value( <arg class> ); // or // <arg type> argX = (<arg type>)in.read_Object( <arg class> ); // CORBA.Object // ----------------------------------------------------------------------- int[] argValues = new int[numArgs]; for (int i = 0; i < numArgs; i++) { JITUtils.setLineNumber(mg, JITUtils.LINE_NUMBER_ARG_BEGIN + i); // d726162 argValues[i] = mg.newLocal(argTypes[i]); mg.loadArg(0); read_value(mg, tieClassName, classConstantFieldNames, // RTC111522 method, methodParameters[i], argTypes[i], rmicCompatible); // d450525 mg.storeLocal(argValues[i]); } JITUtils.setLineNumber(mg, JITUtils.LINE_NUMBER_DEFAULT); // d726162 // ----------------------------------------------------------------------- // // The try/catch block is only needed if there are // // checked exceptions other than RemoteException. // try // { // ----------------------------------------------------------------------- Label try_begin = null; if (numChecked > 0) { try_begin = new Label(); mg.visitLabel(try_begin); } // ----------------------------------------------------------------------- // target.<servant method>( argX, argX,... ); // or // <return type> result = target.<servant method>( argX, argX,... ); // ----------------------------------------------------------------------- mg.loadThis(); mg.visitFieldInsn(GETFIELD, tieClassName, "target", servantDescriptor); for (int arg : argValues) { mg.loadLocal(arg); } mg.visitMethodInsn(INVOKEVIRTUAL, servantClassName, method.getName(), methodDescriptor); int result = -1; if (returnType != Type.VOID_TYPE) { result = mg.newLocal(returnType); mg.storeLocal(result); } // ----------------------------------------------------------------------- // } // end of try - only when checked exceptions // ----------------------------------------------------------------------- Label try_end = null; Label try_catch_exit = null; if (numChecked > 0) { try_end = new Label(); mg.visitLabel(try_end); try_catch_exit = new Label(); mg.visitJumpInsn(GOTO, try_catch_exit); // jump past catch blocks } // ----------------------------------------------------------------------- // // For every checked exception (that is NOT a RemoteException). // // Note that the exceptions have been sorted in order, so that the // // subclasses are first... to avoid 'unreachable' code. // // catch ( <exception type> ex ) // { // String id = <idl exception name>; // "IDL:xxx/XxxEx:1.0" // 2_3.OutputStream out = (2_3.OutputStream) reply.createExceptionReply(); // out.write_string( id ); // out.write_value( ex, <exception type>.class ); // return out; // } // ----------------------------------------------------------------------- Label[] catch_checked_labels = null; if (numChecked > 0) { catch_checked_labels = new Label[numChecked]; for (int i = 0; i < numChecked; ++i) { JITUtils.setLineNumber(mg, JITUtils.LINE_NUMBER_CATCH_BEGIN + i); // d726162 // catch ( <exception type> ex ) Label catch_label = new Label(); catch_checked_labels[i] = catch_label; mg.visitLabel(catch_label); int ex = mg.newLocal(checkedTypes[i]); mg.storeLocal(ex); // String id = <idl exception name>; // "IDL:xxx/XxxEx:1.0" int id = mg.newLocal(TYPE_String); boolean mangleComponents = com.ibm.wsspi.ejbcontainer.JITDeploy.isRMICCompatibleExceptions(rmicCompatible); // PM94096 String exIdlName = getIdlExceptionName(checkedExceptions[i].getName(), mangleComponents); mg.visitLdcInsn(exIdlName); mg.storeLocal(id); // 2_3.OutputStream out = (2_3.OutputStream) reply.createExceptionReply(); int out = mg.newLocal(TYPE_CORBA_2_3_OutputStream); mg.loadArg(1); mg.visitMethodInsn(INVOKEINTERFACE, "org/omg/CORBA/portable/ResponseHandler", "createExceptionReply", "()Lorg/omg/CORBA/portable/OutputStream;"); mg.checkCast(TYPE_CORBA_2_3_OutputStream); mg.storeLocal(out); // out.write_string( id ); mg.loadLocal(out); mg.loadLocal(id); mg.visitMethodInsn(INVOKEVIRTUAL, "org/omg/CORBA/portable/OutputStream", "write_string", "(Ljava/lang/String;)V"); // out.write_value( ex, <exception type>.class ); mg.loadLocal(out); mg.loadLocal(ex); JITUtils.loadClassConstant(mg, tieClassName, classConstantFieldNames, checkedExceptions[i]); // RTC111522 mg.visitMethodInsn(INVOKEVIRTUAL, "org/omg/CORBA_2_3/portable/OutputStream", "write_value", "(Ljava/io/Serializable;Ljava/lang/Class;)V"); // return out; mg.loadLocal(out); mg.returnValue(); } mg.visitLabel(try_catch_exit); } JITUtils.setLineNumber(mg, JITUtils.LINE_NUMBER_RETURN); // d726162 // ----------------------------------------------------------------------- // OutputStream out = reply.createReply(); // or // CORBA_2_3.OutputStream out = (CORBA_2_3.OutputStream)reply.createReply(); // ----------------------------------------------------------------------- Type outType = CORBA_Utils.getRequiredOutputStreamType(returnClass, rmicCompatible); // PM46698 int out = mg.newLocal(TYPE_CORBA_OutputStream); mg.loadArg(1); mg.visitMethodInsn(INVOKEINTERFACE, "org/omg/CORBA/portable/ResponseHandler", "createReply", "()Lorg/omg/CORBA/portable/OutputStream;"); if (outType != TYPE_CORBA_OutputStream) { mg.checkCast(outType); } mg.storeLocal(out); // ----------------------------------------------------------------------- // out.write_<primitive>( result ); // or // out.write_value( result, <class> ); // or // Util.writeAny( out, result ); // or // Util.writeRemoteObject( out, result ); // ----------------------------------------------------------------------- if (returnType != Type.VOID_TYPE) { mg.loadLocal(out); mg.loadLocal(result); write_value(mg, tieClassName, classConstantFieldNames, // RTC111522 method, returnClass, rmicCompatible); // d450525, PM46698 } // ----------------------------------------------------------------------- // return out; // ----------------------------------------------------------------------- mg.loadLocal(out); mg.returnValue(); // ----------------------------------------------------------------------- // All Try-Catch-Finally definitions for above // ----------------------------------------------------------------------- for (int i = 0; i < numChecked; ++i) { String exName = convertClassName(checkedExceptions[i].getName()); mg.visitTryCatchBlock(try_begin, try_end, catch_checked_labels[i], exName); } // ----------------------------------------------------------------------- // End Method Code... // ----------------------------------------------------------------------- mg.endMethod(); // GeneratorAdapter accounts for visitMaxs(x,y) mg.visitEnd(); } }
public class class_name { private static void addDelegateMethod(ClassWriter cw, String tieClassName, Set<String> classConstantFieldNames, String servantClassName, String servantDescriptor, Method method, String idlName, boolean isRmiRemote, int rmicCompatible) throws EJBConfigurationException { GeneratorAdapter mg; Class<?>[] methodParameters = method.getParameterTypes(); Type[] argTypes = getTypes(methodParameters); final int numArgs = argTypes.length; Class<?> returnClass = method.getReturnType(); Type returnType = Type.getType(returnClass); String methodDescriptor = Type.getMethodDescriptor(returnType, argTypes); Class<?>[] checkedExceptions = DeploymentUtil.getCheckedExceptions(method, isRmiRemote, DeploymentUtil.DeploymentTarget.TIE); // d660332 Type[] checkedTypes = getTypes(checkedExceptions); int numChecked = checkedExceptions.length; if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, INDENT + "adding method : " + idlName + " (Lorg/omg/CORBA_2_3/portable/InputStream;" + "Lorg/omg/CORBA/portable/ResponseHandler;)" + "Lorg/omg/CORBA/portable/OutputStream;"); // ----------------------------------------------------------------------- // private OutputStream <idl name> (InputStream in , ResponseHandler reply) // throws Throwable // ----------------------------------------------------------------------- Type delegateReturnType = TYPE_CORBA_OutputStream; Type[] delegateArgTypes = { TYPE_CORBA_2_3_InputStream, TYPE_CORBA_ResponseHandler }; Type[] delegateExceptionTypes = { TYPE_Throwable }; org.objectweb.asm.commons.Method m = new org.objectweb.asm.commons.Method(idlName, delegateReturnType, delegateArgTypes); // Create an ASM GeneratorAdapter object for the ASM Method, which // makes generating dynamic code much easier... as it keeps track // of the position of the arguements and local variables, etc. mg = new GeneratorAdapter(ACC_PRIVATE, m, null, delegateExceptionTypes, cw); // ----------------------------------------------------------------------- // Begin Method Code... // ----------------------------------------------------------------------- mg.visitCode(); /* * mg.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); * mg.visitTypeInsn(NEW, "java/lang/StringBuilder"); * mg.visitInsn(DUP); * mg.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "()V"); * mg.visitLdcInsn(idlName + " called!!"); * mg.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;"); * mg.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;"); * mg.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", * "(Ljava/lang/String;)V"); */ // ----------------------------------------------------------------------- // <arg type> argX = in.read_<primitive>(); // or // <arg type> argX = (<arg type>)in.read_value( <arg class> ); // or // <arg type> argX = (<arg type>)in.read_Object( <arg class> ); // CORBA.Object // ----------------------------------------------------------------------- int[] argValues = new int[numArgs]; for (int i = 0; i < numArgs; i++) { JITUtils.setLineNumber(mg, JITUtils.LINE_NUMBER_ARG_BEGIN + i); // d726162 argValues[i] = mg.newLocal(argTypes[i]); mg.loadArg(0); read_value(mg, tieClassName, classConstantFieldNames, // RTC111522 method, methodParameters[i], argTypes[i], rmicCompatible); // d450525 mg.storeLocal(argValues[i]); } JITUtils.setLineNumber(mg, JITUtils.LINE_NUMBER_DEFAULT); // d726162 // ----------------------------------------------------------------------- // // The try/catch block is only needed if there are // // checked exceptions other than RemoteException. // try // { // ----------------------------------------------------------------------- Label try_begin = null; if (numChecked > 0) { try_begin = new Label(); mg.visitLabel(try_begin); } // ----------------------------------------------------------------------- // target.<servant method>( argX, argX,... ); // or // <return type> result = target.<servant method>( argX, argX,... ); // ----------------------------------------------------------------------- mg.loadThis(); mg.visitFieldInsn(GETFIELD, tieClassName, "target", servantDescriptor); for (int arg : argValues) { mg.loadLocal(arg); } mg.visitMethodInsn(INVOKEVIRTUAL, servantClassName, method.getName(), methodDescriptor); int result = -1; if (returnType != Type.VOID_TYPE) { result = mg.newLocal(returnType); mg.storeLocal(result); } // ----------------------------------------------------------------------- // } // end of try - only when checked exceptions // ----------------------------------------------------------------------- Label try_end = null; Label try_catch_exit = null; if (numChecked > 0) { try_end = new Label(); mg.visitLabel(try_end); try_catch_exit = new Label(); mg.visitJumpInsn(GOTO, try_catch_exit); // jump past catch blocks } // ----------------------------------------------------------------------- // // For every checked exception (that is NOT a RemoteException). // // Note that the exceptions have been sorted in order, so that the // // subclasses are first... to avoid 'unreachable' code. // // catch ( <exception type> ex ) // { // String id = <idl exception name>; // "IDL:xxx/XxxEx:1.0" // 2_3.OutputStream out = (2_3.OutputStream) reply.createExceptionReply(); // out.write_string( id ); // out.write_value( ex, <exception type>.class ); // return out; // } // ----------------------------------------------------------------------- Label[] catch_checked_labels = null; if (numChecked > 0) { catch_checked_labels = new Label[numChecked]; for (int i = 0; i < numChecked; ++i) { JITUtils.setLineNumber(mg, JITUtils.LINE_NUMBER_CATCH_BEGIN + i); // d726162 // depends on control dependency: [for], data = [i] // catch ( <exception type> ex ) Label catch_label = new Label(); catch_checked_labels[i] = catch_label; // depends on control dependency: [for], data = [i] mg.visitLabel(catch_label); // depends on control dependency: [for], data = [none] int ex = mg.newLocal(checkedTypes[i]); mg.storeLocal(ex); // depends on control dependency: [for], data = [none] // String id = <idl exception name>; // "IDL:xxx/XxxEx:1.0" int id = mg.newLocal(TYPE_String); boolean mangleComponents = com.ibm.wsspi.ejbcontainer.JITDeploy.isRMICCompatibleExceptions(rmicCompatible); // PM94096 String exIdlName = getIdlExceptionName(checkedExceptions[i].getName(), mangleComponents); mg.visitLdcInsn(exIdlName); // depends on control dependency: [for], data = [none] mg.storeLocal(id); // depends on control dependency: [for], data = [none] // 2_3.OutputStream out = (2_3.OutputStream) reply.createExceptionReply(); int out = mg.newLocal(TYPE_CORBA_2_3_OutputStream); mg.loadArg(1); // depends on control dependency: [for], data = [none] mg.visitMethodInsn(INVOKEINTERFACE, "org/omg/CORBA/portable/ResponseHandler", "createExceptionReply", "()Lorg/omg/CORBA/portable/OutputStream;"); mg.checkCast(TYPE_CORBA_2_3_OutputStream); mg.storeLocal(out); // depends on control dependency: [for], data = [none] // out.write_string( id ); mg.loadLocal(out); // depends on control dependency: [for], data = [none] mg.loadLocal(id); // depends on control dependency: [for], data = [none] mg.visitMethodInsn(INVOKEVIRTUAL, "org/omg/CORBA/portable/OutputStream", "write_string", "(Ljava/lang/String;)V"); // depends on control dependency: [for], data = [none] // out.write_value( ex, <exception type>.class ); mg.loadLocal(out); // depends on control dependency: [for], data = [none] mg.loadLocal(ex); // depends on control dependency: [for], data = [none] JITUtils.loadClassConstant(mg, tieClassName, classConstantFieldNames, checkedExceptions[i]); // RTC111522 // depends on control dependency: [for], data = [i] mg.visitMethodInsn(INVOKEVIRTUAL, "org/omg/CORBA_2_3/portable/OutputStream", "write_value", "(Ljava/io/Serializable;Ljava/lang/Class;)V"); // depends on control dependency: [for], data = [none] // return out; mg.loadLocal(out); // depends on control dependency: [for], data = [none] mg.returnValue(); // depends on control dependency: [for], data = [none] } mg.visitLabel(try_catch_exit); } JITUtils.setLineNumber(mg, JITUtils.LINE_NUMBER_RETURN); // d726162 // ----------------------------------------------------------------------- // OutputStream out = reply.createReply(); // or // CORBA_2_3.OutputStream out = (CORBA_2_3.OutputStream)reply.createReply(); // ----------------------------------------------------------------------- Type outType = CORBA_Utils.getRequiredOutputStreamType(returnClass, rmicCompatible); // PM46698 int out = mg.newLocal(TYPE_CORBA_OutputStream); mg.loadArg(1); mg.visitMethodInsn(INVOKEINTERFACE, "org/omg/CORBA/portable/ResponseHandler", "createReply", "()Lorg/omg/CORBA/portable/OutputStream;"); if (outType != TYPE_CORBA_OutputStream) { mg.checkCast(outType); } mg.storeLocal(out); // ----------------------------------------------------------------------- // out.write_<primitive>( result ); // or // out.write_value( result, <class> ); // or // Util.writeAny( out, result ); // or // Util.writeRemoteObject( out, result ); // ----------------------------------------------------------------------- if (returnType != Type.VOID_TYPE) { mg.loadLocal(out); mg.loadLocal(result); write_value(mg, tieClassName, classConstantFieldNames, // RTC111522 method, returnClass, rmicCompatible); // d450525, PM46698 } // ----------------------------------------------------------------------- // return out; // ----------------------------------------------------------------------- mg.loadLocal(out); mg.returnValue(); // ----------------------------------------------------------------------- // All Try-Catch-Finally definitions for above // ----------------------------------------------------------------------- for (int i = 0; i < numChecked; ++i) { String exName = convertClassName(checkedExceptions[i].getName()); mg.visitTryCatchBlock(try_begin, try_end, catch_checked_labels[i], exName); } // ----------------------------------------------------------------------- // End Method Code... // ----------------------------------------------------------------------- mg.endMethod(); // GeneratorAdapter accounts for visitMaxs(x,y) mg.visitEnd(); } }
public class class_name { public void setStartGallery(String galleryType, String galleryUri) { if (galleryUri == null) { m_startGalleriesSettings.remove(galleryType); } else { m_startGalleriesSettings.put(galleryType, galleryUri); } } }
public class class_name { public void setStartGallery(String galleryType, String galleryUri) { if (galleryUri == null) { m_startGalleriesSettings.remove(galleryType); // depends on control dependency: [if], data = [none] } else { m_startGalleriesSettings.put(galleryType, galleryUri); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static void equalizeLocalInner( GrayU8 input , int radius , GrayU8 output , IWorkArrays workArrays ) { int width = 2*radius+1; int area = width*width; int maxValue = workArrays.length()-1; //CONCURRENT_BELOW BoofConcurrency.loopBlocks(radius,input.height-radius,(y0,y1)->{ int y0 = radius, y1 = input.height-radius; int[] histogram = workArrays.pop(); for( int y = y0; y < y1; y++ ) { localHistogram(input,0,y-radius,width,y+radius+1,histogram); // compute equalized pixel value using the local histogram int inputValue = input.unsafe_get(radius, y); int sum = 0; for( int i = 0; i <= inputValue; i++ ) { sum += histogram[i]; } output.set(radius,y, (sum*maxValue)/area ); // start of old and new columns in histogram region int indexOld = input.startIndex + y*input.stride; int indexNew = indexOld+width; // index of pixel being examined int indexIn = input.startIndex + y*input.stride+radius+1; int indexOut = output.startIndex + y*output.stride+radius+1; for( int x = radius+1; x < input.width-radius; x++ ) { // update local histogram by removing the left column for( int i = -radius; i <= radius; i++ ) { histogram[input.data[indexOld + i*input.stride] & 0xFF]--; } // update local histogram by adding the right column for( int i = -radius; i <= radius; i++ ) { histogram[input.data[indexNew + i*input.stride] & 0xFF]++; } // compute equalized pixel value using the local histogram inputValue = input.data[indexIn++] & 0xFF; sum = 0; for( int i = 0; i <= inputValue; i++ ) { sum += histogram[i]; } output.data[indexOut++] = (byte)((sum*maxValue)/area); indexOld++; indexNew++; } } workArrays.recycle(histogram); //CONCURRENT_ABOVE }); } }
public class class_name { public static void equalizeLocalInner( GrayU8 input , int radius , GrayU8 output , IWorkArrays workArrays ) { int width = 2*radius+1; int area = width*width; int maxValue = workArrays.length()-1; //CONCURRENT_BELOW BoofConcurrency.loopBlocks(radius,input.height-radius,(y0,y1)->{ int y0 = radius, y1 = input.height-radius; int[] histogram = workArrays.pop(); for( int y = y0; y < y1; y++ ) { localHistogram(input,0,y-radius,width,y+radius+1,histogram); // depends on control dependency: [for], data = [y] // compute equalized pixel value using the local histogram int inputValue = input.unsafe_get(radius, y); int sum = 0; for( int i = 0; i <= inputValue; i++ ) { sum += histogram[i]; // depends on control dependency: [for], data = [i] } output.set(radius,y, (sum*maxValue)/area ); // depends on control dependency: [for], data = [y] // start of old and new columns in histogram region int indexOld = input.startIndex + y*input.stride; int indexNew = indexOld+width; // index of pixel being examined int indexIn = input.startIndex + y*input.stride+radius+1; int indexOut = output.startIndex + y*output.stride+radius+1; for( int x = radius+1; x < input.width-radius; x++ ) { // update local histogram by removing the left column for( int i = -radius; i <= radius; i++ ) { histogram[input.data[indexOld + i*input.stride] & 0xFF]--; // depends on control dependency: [for], data = [i] } // update local histogram by adding the right column for( int i = -radius; i <= radius; i++ ) { histogram[input.data[indexNew + i*input.stride] & 0xFF]++; // depends on control dependency: [for], data = [i] } // compute equalized pixel value using the local histogram inputValue = input.data[indexIn++] & 0xFF; // depends on control dependency: [for], data = [none] sum = 0; // depends on control dependency: [for], data = [none] for( int i = 0; i <= inputValue; i++ ) { sum += histogram[i]; // depends on control dependency: [for], data = [i] } output.data[indexOut++] = (byte)((sum*maxValue)/area); // depends on control dependency: [for], data = [none] indexOld++; // depends on control dependency: [for], data = [none] indexNew++; // depends on control dependency: [for], data = [none] } } workArrays.recycle(histogram); //CONCURRENT_ABOVE }); } }
public class class_name { @Override public Map<Column, Bytes> get(Bytes row, Set<Column> columns) { Map<Column, Bytes> colVal = txb.get(row, columns); for (Map.Entry<Column, Bytes> entry : colVal.entrySet()) { txLog.filteredAdd(LogEntry.newGet(row, entry.getKey(), entry.getValue()), filter); } return colVal; } }
public class class_name { @Override public Map<Column, Bytes> get(Bytes row, Set<Column> columns) { Map<Column, Bytes> colVal = txb.get(row, columns); for (Map.Entry<Column, Bytes> entry : colVal.entrySet()) { txLog.filteredAdd(LogEntry.newGet(row, entry.getKey(), entry.getValue()), filter); // depends on control dependency: [for], data = [entry] } return colVal; } }
public class class_name { public static Prop use(String fileName, String encoding) { Prop result = map.get(fileName); if (result == null) { synchronized (PropKit.class) { result = map.get(fileName); if (result == null) { result = new Prop(fileName, encoding); map.put(fileName, result); if (PropKit.prop == null) { PropKit.prop = result; } } } } return result; } }
public class class_name { public static Prop use(String fileName, String encoding) { Prop result = map.get(fileName); if (result == null) { synchronized (PropKit.class) { // depends on control dependency: [if], data = [none] result = map.get(fileName); if (result == null) { result = new Prop(fileName, encoding); // depends on control dependency: [if], data = [none] map.put(fileName, result); // depends on control dependency: [if], data = [none] if (PropKit.prop == null) { PropKit.prop = result; // depends on control dependency: [if], data = [none] } } } } return result; } }
public class class_name { static CyclicYear parse( CharSequence text, ParsePosition pp, Locale locale, boolean lenient ) { int pos = pp.getIndex(); int len = text.length(); boolean root = locale.getLanguage().isEmpty(); if ((pos + 1 >= len) ||(pos < 0)) { pp.setErrorIndex(pos); return null; } Stem stem = null; Branch branch = null; if (LANGS_WITHOUT_SEP.contains(locale.getLanguage())) { for (Stem s : Stem.values()) { if (s.getDisplayName(locale).charAt(0) == text.charAt(pos)) { stem = s; break; } } if (stem != null) { for (Branch b : Branch.values()) { if (b.getDisplayName(locale).charAt(0) == text.charAt(pos + 1)) { branch = b; pos += 2; break; } } } } else { int sep = -1; for (int i = pos + 1; i < len; i++) { if (text.charAt(i) == '-') { sep = i; break; } } if (sep == -1) { pp.setErrorIndex(pos); return null; } for (Stem s : Stem.values()) { String test = s.getDisplayName(locale); for (int i = pos; i < sep; i++) { int offset = i - pos; char c = text.charAt(i); if (root) { c = toASCII(c); } if ((offset < test.length()) && (test.charAt(offset) == c)) { if (offset + 1 == test.length()) { stem = s; break; } } else { break; // not found } } } if (stem == null) { if (lenient && !root && (sep + 1 < len)) { return parse(text, pp, Locale.ROOT, true); // recursive } else { pp.setErrorIndex(pos); return null; } } for (Branch b : Branch.values()) { String test = b.getDisplayName(locale); for (int i = sep + 1; i < len; i++) { int offset = i - sep - 1; char c = text.charAt(i); if (root) { c = toASCII(c); } if ((offset < test.length()) && (test.charAt(offset) == c)) { if (offset + 1 == test.length()) { branch = b; pos = i + 1; break; } } else { break; // not found } } } } if ((stem == null) || (branch == null)) { if (lenient && !root) { return parse(text, pp, Locale.ROOT, true); // recursive } else { pp.setErrorIndex(pos); return null; } } pp.setIndex(pos); return CyclicYear.of(stem, branch); } }
public class class_name { static CyclicYear parse( CharSequence text, ParsePosition pp, Locale locale, boolean lenient ) { int pos = pp.getIndex(); int len = text.length(); boolean root = locale.getLanguage().isEmpty(); if ((pos + 1 >= len) ||(pos < 0)) { pp.setErrorIndex(pos); // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [none] } Stem stem = null; Branch branch = null; if (LANGS_WITHOUT_SEP.contains(locale.getLanguage())) { for (Stem s : Stem.values()) { if (s.getDisplayName(locale).charAt(0) == text.charAt(pos)) { stem = s; // depends on control dependency: [if], data = [none] break; } } if (stem != null) { for (Branch b : Branch.values()) { if (b.getDisplayName(locale).charAt(0) == text.charAt(pos + 1)) { branch = b; // depends on control dependency: [if], data = [none] pos += 2; // depends on control dependency: [if], data = [none] break; } } } } else { int sep = -1; for (int i = pos + 1; i < len; i++) { if (text.charAt(i) == '-') { sep = i; // depends on control dependency: [if], data = [none] break; } } if (sep == -1) { pp.setErrorIndex(pos); // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [none] } for (Stem s : Stem.values()) { String test = s.getDisplayName(locale); for (int i = pos; i < sep; i++) { int offset = i - pos; char c = text.charAt(i); if (root) { c = toASCII(c); // depends on control dependency: [if], data = [none] } if ((offset < test.length()) && (test.charAt(offset) == c)) { if (offset + 1 == test.length()) { stem = s; // depends on control dependency: [if], data = [none] break; } } else { break; // not found } } } if (stem == null) { if (lenient && !root && (sep + 1 < len)) { return parse(text, pp, Locale.ROOT, true); // recursive // depends on control dependency: [if], data = [none] } else { pp.setErrorIndex(pos); // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [none] } } for (Branch b : Branch.values()) { String test = b.getDisplayName(locale); for (int i = sep + 1; i < len; i++) { int offset = i - sep - 1; char c = text.charAt(i); if (root) { c = toASCII(c); // depends on control dependency: [if], data = [none] } if ((offset < test.length()) && (test.charAt(offset) == c)) { if (offset + 1 == test.length()) { branch = b; // depends on control dependency: [if], data = [none] pos = i + 1; // depends on control dependency: [if], data = [none] break; } } else { break; // not found } } } } if ((stem == null) || (branch == null)) { if (lenient && !root) { return parse(text, pp, Locale.ROOT, true); // recursive // depends on control dependency: [if], data = [none] } else { pp.setErrorIndex(pos); // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [none] } } pp.setIndex(pos); return CyclicYear.of(stem, branch); } }
public class class_name { public int getResultingHeight() { int height = getResultingTargetHeight(); if (height == -1) { if (isCropped()) { height = m_cropHeight; } else { height = m_orgHeight; } } return height; } }
public class class_name { public int getResultingHeight() { int height = getResultingTargetHeight(); if (height == -1) { if (isCropped()) { height = m_cropHeight; // depends on control dependency: [if], data = [none] } else { height = m_orgHeight; // depends on control dependency: [if], data = [none] } } return height; } }
public class class_name { @Nullable @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private CodecType identifyCodecType(@NonNull MediaCodecInfo codecInfo) { final String name = codecInfo.getName(); for (String token : AVC_TYPES) { if (name.contains(token)) { return CodecType.AVC; } } for (String token : H263_TYPES) { if (name.contains(token)) { return CodecType.H263; } } for (String token : MPEG4_TYPES) { if (name.contains(token)) { return CodecType.MPEG4; } } for (String token : AAC_TYPES) { if (name.contains(token)) { return CodecType.AAC; } } return null; } }
public class class_name { @Nullable @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private CodecType identifyCodecType(@NonNull MediaCodecInfo codecInfo) { final String name = codecInfo.getName(); for (String token : AVC_TYPES) { if (name.contains(token)) { return CodecType.AVC; // depends on control dependency: [if], data = [none] } } for (String token : H263_TYPES) { if (name.contains(token)) { return CodecType.H263; // depends on control dependency: [if], data = [none] } } for (String token : MPEG4_TYPES) { if (name.contains(token)) { return CodecType.MPEG4; // depends on control dependency: [if], data = [none] } } for (String token : AAC_TYPES) { if (name.contains(token)) { return CodecType.AAC; // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { public void setKeyObtentionIterations(final String iter) { if (StringUtils.isNotBlank(iter) && NumberUtils.isCreatable(iter)) { LOGGER.debug("Configured Jasypt iterations"); jasyptInstance.setKeyObtentionIterations(Integer.parseInt(iter)); } } }
public class class_name { public void setKeyObtentionIterations(final String iter) { if (StringUtils.isNotBlank(iter) && NumberUtils.isCreatable(iter)) { LOGGER.debug("Configured Jasypt iterations"); // depends on control dependency: [if], data = [none] jasyptInstance.setKeyObtentionIterations(Integer.parseInt(iter)); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static FileOrder fromName(final String name) { if (name == null) { return null; } for (final FileOrder fo : INSTANCES) { if (fo.name.equals(name)) { return fo; } } throw new IllegalArgumentException("Unknown name: " + name); } }
public class class_name { public static FileOrder fromName(final String name) { if (name == null) { return null; // depends on control dependency: [if], data = [none] } for (final FileOrder fo : INSTANCES) { if (fo.name.equals(name)) { return fo; // depends on control dependency: [if], data = [none] } } throw new IllegalArgumentException("Unknown name: " + name); } }
public class class_name { public int strLength(byte[]bytes, int p, int end) { int n = 0; int q = p; while (q < end) { q += length(bytes, q, end); n++; } return n; } }
public class class_name { public int strLength(byte[]bytes, int p, int end) { int n = 0; int q = p; while (q < end) { q += length(bytes, q, end); // depends on control dependency: [while], data = [end)] n++; // depends on control dependency: [while], data = [none] } return n; } }
public class class_name { public void writeClass(String strClassName, CodeType codeType) { if (!this.readThisClass(strClassName)) // Get the field this is based on return; boolean bResourceListBundle = ResourceTypeField.LIST_RESOURCE_BUNDLE.equals(this.getRecord(ProgramControl.PROGRAM_CONTROL_FILE).getField(ProgramControl.CLASS_RESOURCE_TYPE).toString()); String strFileName = strClassName; if (!bResourceListBundle) strFileName += ".properties"; this.writeHeading(strFileName, this.getPackage(codeType), bResourceListBundle ? CodeType.RESOURCE_CODE : CodeType.RESOURCE_PROPERTIES); // Write the first few lines of the files if (bResourceListBundle) { this.writeIncludes(CodeType.THICK); m_StreamOut.writeit("import java.util.*;\n"); if (m_MethodNameList.size() != 0) m_MethodNameList.removeAllElements(); this.writeClassInterface(); this.writeClassFields(CodeType.THICK); // Write the C++ fields for this class this.writeResources(strClassName); this.writeMethodInterface(null, "getContents", "Object[][]", "", "", "Get the resource table", null); m_StreamOut.writeit("\treturn contents;\n"); m_StreamOut.writeit("}\n"); this.writeClassMethods(CodeType.THICK); // Write the remaining methods for this class } else { this.writeResources(strClassName); } this.writeEndCode(bResourceListBundle); } }
public class class_name { public void writeClass(String strClassName, CodeType codeType) { if (!this.readThisClass(strClassName)) // Get the field this is based on return; boolean bResourceListBundle = ResourceTypeField.LIST_RESOURCE_BUNDLE.equals(this.getRecord(ProgramControl.PROGRAM_CONTROL_FILE).getField(ProgramControl.CLASS_RESOURCE_TYPE).toString()); String strFileName = strClassName; if (!bResourceListBundle) strFileName += ".properties"; this.writeHeading(strFileName, this.getPackage(codeType), bResourceListBundle ? CodeType.RESOURCE_CODE : CodeType.RESOURCE_PROPERTIES); // Write the first few lines of the files if (bResourceListBundle) { this.writeIncludes(CodeType.THICK); // depends on control dependency: [if], data = [none] m_StreamOut.writeit("import java.util.*;\n"); // depends on control dependency: [if], data = [none] if (m_MethodNameList.size() != 0) m_MethodNameList.removeAllElements(); this.writeClassInterface(); // depends on control dependency: [if], data = [none] this.writeClassFields(CodeType.THICK); // Write the C++ fields for this class // depends on control dependency: [if], data = [none] this.writeResources(strClassName); // depends on control dependency: [if], data = [none] this.writeMethodInterface(null, "getContents", "Object[][]", "", "", "Get the resource table", null); // depends on control dependency: [if], data = [none] m_StreamOut.writeit("\treturn contents;\n"); // depends on control dependency: [if], data = [none] m_StreamOut.writeit("}\n"); // depends on control dependency: [if], data = [none] this.writeClassMethods(CodeType.THICK); // Write the remaining methods for this class // depends on control dependency: [if], data = [none] } else { this.writeResources(strClassName); // depends on control dependency: [if], data = [none] } this.writeEndCode(bResourceListBundle); } }
public class class_name { public static <T> List<List<T>> chunkifyList(List<T> list, int maxChunkSize) { // sanity-check input param if (maxChunkSize < 1) throw new InvalidParameterException("maxChunkSize must be greater than zero"); // initialize return object List<List<T>> chunkedLists = new ArrayList<List<T>>(); // if the given list is smaller than the maxChunksize, there's // no need to break it up into chunks if (list.size() <= maxChunkSize) { chunkedLists.add(list); return chunkedLists; } // initialize counters int index = 0; int count; // loop through and grab chunks of maxChunkSize from the // original list, but stop early enough so that we don't wind // up with tiny runt chunks at the end while (index < list.size() - (maxChunkSize * 2)) { count = Math.min(index + maxChunkSize, list.size()); chunkedLists.add(list.subList(index, count)); index += maxChunkSize; } // take whatever's left, split it into two relatively-equal // chunks, and add these to the return object count = index + ((list.size() - index) / 2); chunkedLists.add(list.subList(index, count)); chunkedLists.add(list.subList(count, list.size())); return chunkedLists; } }
public class class_name { public static <T> List<List<T>> chunkifyList(List<T> list, int maxChunkSize) { // sanity-check input param if (maxChunkSize < 1) throw new InvalidParameterException("maxChunkSize must be greater than zero"); // initialize return object List<List<T>> chunkedLists = new ArrayList<List<T>>(); // if the given list is smaller than the maxChunksize, there's // no need to break it up into chunks if (list.size() <= maxChunkSize) { chunkedLists.add(list); // depends on control dependency: [if], data = [none] return chunkedLists; // depends on control dependency: [if], data = [none] } // initialize counters int index = 0; int count; // loop through and grab chunks of maxChunkSize from the // original list, but stop early enough so that we don't wind // up with tiny runt chunks at the end while (index < list.size() - (maxChunkSize * 2)) { count = Math.min(index + maxChunkSize, list.size()); // depends on control dependency: [while], data = [(index] chunkedLists.add(list.subList(index, count)); // depends on control dependency: [while], data = [(index] index += maxChunkSize; // depends on control dependency: [while], data = [none] } // take whatever's left, split it into two relatively-equal // chunks, and add these to the return object count = index + ((list.size() - index) / 2); chunkedLists.add(list.subList(index, count)); chunkedLists.add(list.subList(count, list.size())); return chunkedLists; } }
public class class_name { public boolean and(BitArray other) { if (bits != other.bits) { throw new IllegalArgumentException("number of bits differ"); } int l = bits/8; for (int ii=0;ii<l;ii++) { if ((array[ii] & other.array[ii]) != 0) { return true; } } for (int ii=l*8;ii<bits;ii++) { if (isSet(ii) && other.isSet(ii)) { return true; } } return false; } }
public class class_name { public boolean and(BitArray other) { if (bits != other.bits) { throw new IllegalArgumentException("number of bits differ"); } int l = bits/8; for (int ii=0;ii<l;ii++) { if ((array[ii] & other.array[ii]) != 0) { return true; // depends on control dependency: [if], data = [none] } } for (int ii=l*8;ii<bits;ii++) { if (isSet(ii) && other.isSet(ii)) { return true; // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { public static Object getClassForName(String className) { Object object = null; try { Class classDefinition = Class.forName(className); object = classDefinition.newInstance(); } catch (ClassNotFoundException e) { if (log.isEnabledFor(Level.ERROR)) { log.error("ClassNotFoundException", e); } } catch (InstantiationException e) { if (log.isEnabledFor(Level.ERROR)) { log.error("InstantiationException " + e.getMessage(), e); } } catch (IllegalAccessException e) { if (log.isEnabledFor(Level.ERROR)) { log.error("IllegalAccessException", e); } } return object; } }
public class class_name { public static Object getClassForName(String className) { Object object = null; try { Class classDefinition = Class.forName(className); // depends on control dependency: [try], data = [none] object = classDefinition.newInstance(); // depends on control dependency: [try], data = [none] } catch (ClassNotFoundException e) { if (log.isEnabledFor(Level.ERROR)) { log.error("ClassNotFoundException", e); // depends on control dependency: [if], data = [none] } } catch (InstantiationException e) { // depends on control dependency: [catch], data = [none] if (log.isEnabledFor(Level.ERROR)) { log.error("InstantiationException " + e.getMessage(), e); // depends on control dependency: [if], data = [none] } } catch (IllegalAccessException e) { // depends on control dependency: [catch], data = [none] if (log.isEnabledFor(Level.ERROR)) { log.error("IllegalAccessException", e); // depends on control dependency: [if], data = [none] } } // depends on control dependency: [catch], data = [none] return object; } }