Java Code Examples for java.util.LinkedList#poll()

The following examples show how to use java.util.LinkedList#poll() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Solution6.java    From code with Apache License 2.0 6 votes vote down vote up
/**
 * 题目地址:https://leetcode-cn.com/problems/same-tree/
 * -------------------------------------------------------------------
 * 思考:
 * -------------------------------------------------------------------
 * 思路:层次遍历-迭代
 *  使用1个队列同时遍历两颗树
 * -------------------------------------------------------------------
 * 时间复杂度:
 * 空间复杂度:
 */

public boolean isSameTree(TreeNode p, TreeNode q) {
    LinkedList<TreeNode> queue = new LinkedList<>();
    queue.add(p);
    queue.add(q);
    while (!queue.isEmpty()) {
        p = queue.poll();
        q = queue.poll();

        if (p == null && q == null) continue;
        if (p == null || q == null) return false;
        if (p.val != q.val) return false;

        queue.add(p.left);
        queue.add(q.left);
        queue.add(p.right);
        queue.add(q.right);
    }
    return true;
}
 
Example 2
Source File: 二叉树的层次遍历2.java    From algorithm-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
public static List<List<Integer>> levelOrderBottom(TreeNode root) {
    List<List<Integer>> result = new LinkedList<>();
    LinkedList<TreeNode> queue = new LinkedList<>();
    if (root == null) return result;
    queue.offer(root);
    while (!queue.isEmpty()) {
        int size = queue.size();
        List<Integer> list = new LinkedList<>();
        for (int i = 0; i < size; i++) {
            TreeNode node = queue.poll();
            if (node != null) {
                list.add(node.val);
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
        }
        result.add(list);
    }
    Collections.reverse(result);
    return result;
}
 
Example 3
Source File: CPFileImportController.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Breadth-first search for leafs inside the container that are to be added to the tree.
 * 
 * @param container
 * @param menuItemTypes
 * @return true if there is a leaf inside container that should be added
 */
private boolean containsItemsToAdd(final VFSContainer container, final Set<String> menuItemTypes) {
    final LinkedList<VFSItem> queue = new LinkedList<VFSItem>();
    // enqueue root node
    queue.add(container);
    do {
        // dequeue and exmaine
        final VFSItem item = queue.poll();
        if (item instanceof VFSLeaf) {
            if (isToBeAdded((VFSLeaf) item, menuItemTypes)) {
                // node found, return
                return true;
            }
        } else {
            // enqueue successors
            final VFSContainer parent = (VFSContainer) item;
            queue.addAll(parent.getItems());
        }
    } while (!queue.isEmpty());
    return false;
}
 
Example 4
Source File: SortCodeGeneratorTest.java    From flink with Apache License 2.0 6 votes vote down vote up
private void randomKeysAndOrders() {
	Random rnd = new Random();
	fields = new int[rnd.nextInt(9) + 1];
	for (int i = 0; i < fields.length; i++) {
		fields[i] = rnd.nextInt(types.length);
	}

	keys = new int[rnd.nextInt(fields.length) + 1];
	LinkedList<Integer> indexQueue = new LinkedList<>();
	for (int i = 0; i < fields.length; i++) {
		indexQueue.add(i);
	}
	Collections.shuffle(indexQueue);
	orders = new boolean[keys.length];
	for (int i = 0; i < keys.length; i++) {
		keys[i] = indexQueue.poll();
		orders[i] = rnd.nextBoolean();
	}
	nullsIsLast = SortUtil.getNullDefaultOrders(orders);
}
 
Example 5
Source File: PluginImpl.java    From java-trader with Apache License 2.0 6 votes vote down vote up
@Override
public List<File> scanFiles(FileFilter filter)
{
    List<String> ignoredFiles = Arrays.asList( new String[] {FILE_DESCRIPTOR, "classes", "jars", "lib"} );
    List<File> result = new ArrayList<>();

    LinkedList<File> fileQueue = new LinkedList<>();
    fileQueue.addAll( Arrays.asList(pluginDir.listFiles()) );
    while(!fileQueue.isEmpty()) {
        File file = fileQueue.poll();
        if ( null==file || ignoredFiles.contains(file.getName())) {
            continue;
        }
        if ( file.isDirectory() ) {
            File[] files = file.listFiles();
            if ( null!=files ) {
                fileQueue.addAll( Arrays.asList(files) );
            }
            continue;
        }
        if (filter.accept(file) ) {
            result.add(file);
        }
    }
    return result;
}
 
Example 6
Source File: CubeBuildJob.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
private void build(Collection<NBuildSourceInfo> buildSourceInfos, SegmentInfo seg, SpanningTree st) {

        List<NBuildSourceInfo> theFirstLevelBuildInfos = buildLayer(buildSourceInfos, seg, st);
        LinkedList<List<NBuildSourceInfo>> queue = new LinkedList<>();

        if (!theFirstLevelBuildInfos.isEmpty()) {
            queue.offer(theFirstLevelBuildInfos);
        }

        while (!queue.isEmpty()) {
            List<NBuildSourceInfo> buildInfos = queue.poll();
            List<NBuildSourceInfo> theNextLayer = buildLayer(buildInfos, seg, st);
            if (!theNextLayer.isEmpty()) {
                queue.offer(theNextLayer);
            }
        }

    }
 
Example 7
Source File: SortCodeGeneratorTest.java    From flink with Apache License 2.0 6 votes vote down vote up
private void randomKeysAndOrders() {
	Random rnd = new Random();
	fields = new int[rnd.nextInt(9) + 1];
	for (int i = 0; i < fields.length; i++) {
		fields[i] = rnd.nextInt(types.length);
	}

	keys = new int[rnd.nextInt(fields.length) + 1];
	LinkedList<Integer> indexQueue = new LinkedList<>();
	for (int i = 0; i < fields.length; i++) {
		indexQueue.add(i);
	}
	Collections.shuffle(indexQueue);
	orders = new boolean[keys.length];
	for (int i = 0; i < keys.length; i++) {
		keys[i] = indexQueue.poll();
		orders[i] = rnd.nextBoolean();
	}
	nullsIsLast = SortUtil.getNullDefaultOrders(orders);
}
 
Example 8
Source File: VariableByte.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public static LinkedList<Byte> vbEncode(LinkedList<Integer> numbers) {
	LinkedList<Byte> code = new LinkedList<Byte>();
	while (numbers.size() > 0) {
		int n = numbers.poll();
		code.addAll(vbEncodeNumber(n));
	}
	return code;
}
 
Example 9
Source File: XMLConfigProvider.java    From java-trader with Apache License 2.0 5 votes vote down vote up
/**
 * 返回List<Map>
 */
private List<Object> getItems(String[] configParts)
{
    LinkedList<String> parts = new LinkedList<String>( Arrays.asList(configParts));
    Element parentElem = doc.getRootElement();
    while( parentElem!=null && parts.size()>1 ){
        String part = parts.poll();
        if ( part.length()==0 ){
            continue;
        }
        parentElem = getChildElem(parentElem, part);
        if ( parentElem==null ){
            break;
        }
        continue;
    }
    if ( parentElem==null || parts.size()==0 ){
        return Collections.emptyList();
    }
    List<Object> result = new LinkedList<>();
    for(Element elem:parentElem.getChildren(parts.poll())){
        Map<String, String> map = new HashMap<>();
        map.put("text", elem.getTextTrim());
        for( Attribute attr:elem.getAttributes()){
            map.put(attr.getName(), attr.getValue());
        }
        result.add(map);
    }
    return result;
}
 
Example 10
Source File: SPADEQuery.java    From SPADE with GNU General Public License v3.0 5 votes vote down vote up
public Set<Object> getAllResults(){
	Set<Object> results = new HashSet<Object>();

	LinkedList<SPADEQuery> currentSet = new LinkedList<SPADEQuery>();
	currentSet.add(this);
	while(!currentSet.isEmpty()){
		SPADEQuery current = currentSet.poll();
		if(current.getResult() != null){
			results.add(current.getResult());
		}
		currentSet.addAll(current.getRemoteSubqueries());
	}

	return results;
}
 
Example 11
Source File: DeviceHandlerImpl.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
private <RSC extends AbsResource<RSC>> Map<DeviceLayer, Set<AbsRscLayerObject<RSC>>> groupByLayer(
    Collection<RSC> allResources
)
{
    Map<DeviceLayer, Set<AbsRscLayerObject<RSC>>> ret = new HashMap<>();
    try
    {
        for (RSC absRsc : allResources)
        {
            AbsRscLayerObject<RSC> rootRscData = absRsc.getLayerData(wrkCtx);

            LinkedList<AbsRscLayerObject<RSC>> toProcess = new LinkedList<>();
            toProcess.add(rootRscData);
            while (!toProcess.isEmpty())
            {
                AbsRscLayerObject<RSC> rscData = toProcess.poll();
                toProcess.addAll(rscData.getChildren());

                DeviceLayer devLayer = layerFactory.getDeviceLayer(rscData.getLayerKind());
                ret.computeIfAbsent(devLayer, ignored -> new HashSet<>()).add(rscData);
            }
        }
    }
    catch (AccessDeniedException accDeniedExc)
    {
        throw new ImplementationError(accDeniedExc);
    }
    return ret;
}
 
Example 12
Source File: MagicQueue.java    From snowblossom with Apache License 2.0 5 votes vote down vote up
/**
 * Returns null or a ByteBuffer with position 0 and limit set to how much data is there.
 * ready for reading.
 */

public ByteBuffer readBucket(int bucket)
{
  LinkedList<ByteBuffer> lst = global_buckets[bucket];
  synchronized(lst)
  {
    ByteBuffer bb = lst.poll();
    if (bb == null) return null;
    bb.flip();
    return bb;
  }
}
 
Example 13
Source File: JavaMethodToProcessWrapper.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
private static Object executeCommand(final File folder, final String clazz, final String method_name, final String target, final LinkedList<String> argsArray) throws CommandExecutionException {

		try {
			logger.info("Invoking in folder {} method {} on class {}", folder, clazz, method_name);
			Object targetObject = null;
			if (!target.equals("null")) {
				targetObject = FileUtil.unserializeObject(folder.getAbsolutePath() + File.separator + target);
			}

			Class<?>[] params = new Class[argsArray.size()];
			Object[] objcts = new Object[argsArray.size()];
			int counter = 0;
			while (!argsArray.isEmpty()) {
				String descriptor = argsArray.poll();
				boolean isNull = descriptor.equals("");
				objcts[counter] = isNull ? null : FileUtil.unserializeObject(folder.getAbsolutePath() + File.separator + descriptor);
				params[counter] = isNull ? null : Class.forName(descriptor.substring(0, descriptor.lastIndexOf('.')));
				counter++;
			}

			/* retrieve method and call it */
			Method method = MethodUtils.getMatchingAccessibleMethod(Class.forName(clazz), method_name, params);
			return method.invoke(targetObject, objcts);
		} catch (Exception e) {
			throw new CommandExecutionException(e);
		}
	}
 
Example 14
Source File: DirectoryScanner.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
private void scan(ScanTask task, LinkedList<File> list) {
    setStateAndNotify(RUNNING);
    task.info = "In Progress";
    try {

        // The FileFilter will tell us which files match and which don't.
        //
        final FileFilter filter = config.buildFileFilter();

        // We have two condition to end the loop: either the list is
        // empty, meaning there's nothing more to scan, or the state of
        // the DirectoryScanner was asynchronously switched to STOPPED by
        // another thread, e.g. because someone called "stop" on the
        // ScanManagerMXBean
        //
        while (!list.isEmpty() && state == RUNNING) {

            // Get and remove the first element in the list.
            //
            final File current = list.poll();

            // Increment number of file scanned.
            task.scanned++;

            // If 'current' is a file, it's already been matched by our
            // file filter (see below): act on it.
            // Note that for the first iteration of this loop, there will
            // be one single file in the list: the root directory for this
            // scanner.
            //
            if (current.isFile()) {
                task.matching++;
                actOn(current);
            }

            // If 'current' is a directory, then
            // find files and directories that match the file filter
            // in this directory
            //
            if (current.isDirectory()) {

                // Gets matching files and directories
                final File[] content = current.listFiles(filter);
                if (content == null) continue;

                // Adds all matching file to the list.
                list.addAll(0,Arrays.asList(content));
            }
        }

        // The loop terminated. If the list is empty, then we have
        // completed our task. If not, then somebody must have called
        // stop() on this directory scanner.
        //
        if (list.isEmpty()) {
            task.info = "Successfully Completed";
            setStateAndNotify(COMPLETED);
        }
    } catch (Exception x) {
        // We got an exception: stop the scan
        //
        task.info = "Failed: "+x;
        if (LOG.isLoggable(Level.FINEST))
            LOG.log(Level.FINEST,"scan task failed: "+x,x);
        else if (LOG.isLoggable(Level.FINE))
            LOG.log(Level.FINE,"scan task failed: "+x);
        setStateAndNotify(STOPPED);
    } catch (Error e) {
        // We got an Error:
        // Should not happen unless we ran out of memory or
        // whatever - don't even try to notify, but
        // stop the scan anyway!
        //
        state=STOPPED;
        task.info = "Error: "+e;

        // rethrow error.
        //
        throw e;
    }
}
 
Example 15
Source File: MarketDataImportAction.java    From java-trader with Apache License 2.0 4 votes vote down vote up
/**
 * 金数源 目录
 */
private void importJinshuyuan() throws Exception
{
    File mdDir = new File(dataDir);
    writer.println("从目录导入: "+mdDir.getAbsolutePath());writer.flush();
    LinkedList<File> files = new LinkedList<>();
    files.add(mdDir);
    while(!files.isEmpty()) {
        File file = files.poll();
        if ( file.isDirectory() ) {
            File[] childs = file.listFiles();
            if ( childs!=null ) {
                List<File> files0 = new ArrayList<>(Arrays.asList(childs));
                Collections.sort(files0);
                files.addAll(files0);
            }
            continue;
        }
        if ( !file.getName().toLowerCase().endsWith(".csv") || file.getName().indexOf("主力")>=0 || file.getName().indexOf("连续")>=0 ) {
            continue;
        }
        CtpCSVMarshallHelper ctpCsvHelper = new CtpCSVMarshallHelper();
        CSVWriter<CThostFtdcDepthMarketDataField> ctpCsvWrite = new CSVWriter<>(ctpCsvHelper);
        CSVDataSet ds = CSVUtil.parse(new InputStreamReader(new FileInputStream(file), StringUtil.GBK), ',', true);
        String ctpInstrument=null;
        LocalDate ctpTradingDay=null;
        List<MarketData> ctpTicks = new ArrayList<>();
        while(ds.next()) {
            String row[] = new String[] {
                    ds.get("交易日")
                    ,ds.get("合约代码")
                    ,ds.get("交易所代码")
                    ,ds.get("合约在交易所的代码")
                    ,ds.get("最新价")
                    ,ds.get("上次结算价")
                    ,ds.get("昨收盘")
                    ,ds.get("昨持仓量")
                    ,ds.get("今开盘")
                    ,ds.get("最高价")
                    ,ds.get("最低价")
                    ,ds.get("数量")
                    ,ds.get("成交金额")
                    ,ds.get("持仓量")
                    ,ds.get("今收盘")
                    ,ds.get("本次结算价")
                    ,ds.get("涨停板价")
                    ,ds.get("跌停板价")
                    ,ds.get("昨虚实度")
                    ,ds.get("今虚实度")
                    ,ds.get("最后修改时间")
                    ,ds.get("最后修改毫秒")

                    ,ds.get("申买价一")
                    ,ds.get("申买量一")
                    ,ds.get("申卖价一")
                    ,ds.get("申卖量一")

                    ,ds.get("申买价二")
                    ,ds.get("申买量二")
                    ,ds.get("申卖价二")
                    ,ds.get("申卖量二")

                    ,ds.get("申买价三")
                    ,ds.get("申买量三")
                    ,ds.get("申卖价三")
                    ,ds.get("申卖量三")

                    ,ds.get("申买价四")
                    ,ds.get("申买量四")
                    ,ds.get("申卖价四")
                    ,ds.get("申卖量四")

                    ,ds.get("申买价五")
                    ,ds.get("申买量五")
                    ,ds.get("申卖价五")
                    ,ds.get("申卖量五")

                    ,ds.get("当日均价")
                    ,ds.get("业务日期")
            };
            CThostFtdcDepthMarketDataField ctpData = ctpCsvHelper.unmarshall(row);
            ctpInstrument = ctpData.InstrumentID;
            ctpTradingDay = DateUtil.str2localdate(ctpData.TradingDay);
            ctpTicks.add(new CtpMarketData(MarketDataProducer.PROVIDER_CTP, Future.fromString(ctpData.InstrumentID), ctpData, ctpTradingDay));
            ctpCsvWrite.next();
            ctpCsvWrite.marshall(ctpData);
        }
        Exchangeable ctpFuture = Exchangeable.fromString(ctpInstrument);
        data.save(ctpFuture, ExchangeableData.TICK_CTP, ctpTradingDay, ctpCsvWrite.toString());
        saveDayBars(data, ctpFuture, ctpTradingDay, ctpTicks);
        writer.println(file.getAbsolutePath()+" : "+ctpFuture+" "+ctpTradingDay);
    }
}
 
Example 16
Source File: FairQueue.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
private E getNext (boolean remove)
{
   // Always called after using a takeLock.lock
   LinkedList<E> list = null;
   boolean found = false;
   Object listKey = null;

   for (Object key : keys)
   {
      // save first list if lastKey is the last of the keys
      if (list == null)
      {
         listKey = key;
         list = storage.get (key);
         // for first iteration, take the first list
         if (lastUsedKey == null)
         {
            break;
         }
      }

      if (lastUsedKey != null && lastUsedKey.equals (key))
      {
         found = true;
         continue;
      }
      // if key is found, take the next list
      if (found)
      {
         listKey = key;
         list = storage.get (key);
         break;
      }
   }

   E e = remove ? list.poll () : list.peek ();
   if (list.isEmpty ())
   {
      // remove empty list from storage and keep lastKey as it is
      storage.remove (listKey);
      keys.remove (listKey);
   }
   else
      if (remove)
      {
         // save last used list key
         lastUsedKey = listKey;
      }
   return e;
}
 
Example 17
Source File: DirectoryScanner.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
private void scan(ScanTask task, LinkedList<File> list) {
    setStateAndNotify(RUNNING);
    task.info = "In Progress";
    try {

        // The FileFilter will tell us which files match and which don't.
        //
        final FileFilter filter = config.buildFileFilter();

        // We have two condition to end the loop: either the list is
        // empty, meaning there's nothing more to scan, or the state of
        // the DirectoryScanner was asynchronously switched to STOPPED by
        // another thread, e.g. because someone called "stop" on the
        // ScanManagerMXBean
        //
        while (!list.isEmpty() && state == RUNNING) {

            // Get and remove the first element in the list.
            //
            final File current = list.poll();

            // Increment number of file scanned.
            task.scanned++;

            // If 'current' is a file, it's already been matched by our
            // file filter (see below): act on it.
            // Note that for the first iteration of this loop, there will
            // be one single file in the list: the root directory for this
            // scanner.
            //
            if (current.isFile()) {
                task.matching++;
                actOn(current);
            }

            // If 'current' is a directory, then
            // find files and directories that match the file filter
            // in this directory
            //
            if (current.isDirectory()) {

                // Gets matching files and directories
                final File[] content = current.listFiles(filter);
                if (content == null) continue;

                // Adds all matching file to the list.
                list.addAll(0,Arrays.asList(content));
            }
        }

        // The loop terminated. If the list is empty, then we have
        // completed our task. If not, then somebody must have called
        // stop() on this directory scanner.
        //
        if (list.isEmpty()) {
            task.info = "Successfully Completed";
            setStateAndNotify(COMPLETED);
        }
    } catch (Exception x) {
        // We got an exception: stop the scan
        //
        task.info = "Failed: "+x;
        if (LOG.isLoggable(Level.FINEST))
            LOG.log(Level.FINEST,"scan task failed: "+x,x);
        else if (LOG.isLoggable(Level.FINE))
            LOG.log(Level.FINE,"scan task failed: "+x);
        setStateAndNotify(STOPPED);
    } catch (Error e) {
        // We got an Error:
        // Should not happen unless we ran out of memory or
        // whatever - don't even try to notify, but
        // stop the scan anyway!
        //
        state=STOPPED;
        task.info = "Error: "+e;

        // rethrow error.
        //
        throw e;
    }
}
 
Example 18
Source File: DirectoryScanner.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
private void scan(ScanTask task, LinkedList<File> list) {
    setStateAndNotify(RUNNING);
    task.info = "In Progress";
    try {

        // The FileFilter will tell us which files match and which don't.
        //
        final FileFilter filter = config.buildFileFilter();

        // We have two condition to end the loop: either the list is
        // empty, meaning there's nothing more to scan, or the state of
        // the DirectoryScanner was asynchronously switched to STOPPED by
        // another thread, e.g. because someone called "stop" on the
        // ScanManagerMXBean
        //
        while (!list.isEmpty() && state == RUNNING) {

            // Get and remove the first element in the list.
            //
            final File current = list.poll();

            // Increment number of file scanned.
            task.scanned++;

            // If 'current' is a file, it's already been matched by our
            // file filter (see below): act on it.
            // Note that for the first iteration of this loop, there will
            // be one single file in the list: the root directory for this
            // scanner.
            //
            if (current.isFile()) {
                task.matching++;
                actOn(current);
            }

            // If 'current' is a directory, then
            // find files and directories that match the file filter
            // in this directory
            //
            if (current.isDirectory()) {

                // Gets matching files and directories
                final File[] content = current.listFiles(filter);
                if (content == null) continue;

                // Adds all matching file to the list.
                list.addAll(0,Arrays.asList(content));
            }
        }

        // The loop terminated. If the list is empty, then we have
        // completed our task. If not, then somebody must have called
        // stop() on this directory scanner.
        //
        if (list.isEmpty()) {
            task.info = "Successfully Completed";
            setStateAndNotify(COMPLETED);
        }
    } catch (Exception x) {
        // We got an exception: stop the scan
        //
        task.info = "Failed: "+x;
        if (LOG.isLoggable(Level.FINEST))
            LOG.log(Level.FINEST,"scan task failed: "+x,x);
        else if (LOG.isLoggable(Level.FINE))
            LOG.log(Level.FINE,"scan task failed: "+x);
        setStateAndNotify(STOPPED);
    } catch (Error e) {
        // We got an Error:
        // Should not happen unless we ran out of memory or
        // whatever - don't even try to notify, but
        // stop the scan anyway!
        //
        state=STOPPED;
        task.info = "Error: "+e;

        // rethrow error.
        //
        throw e;
    }
}
 
Example 19
Source File: SeatsTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
private boolean deleteReservation(Connection conn) throws SQLException {
  if (logDML) log().info("Let's look for a Reservation that we can delete");
  
  Reservation r = null;
  synchronized(DELETE){
    LinkedList<Reservation> cache = CACHE_RESERVATIONS.get(CacheType.PENDING_DELETES);
    if (cache == null) {
      throw new TestException("Unexpected " + CacheType.PENDING_DELETES);
    }
    r = cache.poll();
    
    if (r == null) {
      if (logDML) log().info(String.format("Failed to find Reservation to delete [cache=%d]", cache.size()));
      return (false);
    }
  } 

  if (logDML) log().info("Ok let's try to delete " + r);
  
  int rand = random.nextInt(HUNDRED);
  
  // Parameters
  long f_id = r.flightInfo.getFlightId();
  Long c_id = null;
  String c_id_str = null;
  String ff_c_id_str = null;
  Long ff_al_id = null;
  long r_seatnum = r.seatnum;
  
  // Delete with the Customer's id as a string 
  if (rand < PROB_DELETE_WITH_CUSTOMER_ID_STR) {
    c_id_str = Long.toString(r.customer_id.getId());
  }
  // Delete using their FrequentFlyer information
  else if (rand < PROB_DELETE_WITH_CUSTOMER_ID_STR + PROB_DELETE_WITH_FREQUENTFLYER_ID_STR) {
    ff_c_id_str = Long.toString(r.customer_id.getId());
    ff_al_id = r.flightInfo.getAlId();
  }
  // Delete using their Customer id
  else {
    c_id = r.customer_id.getId();
  }
  
  if (logDML) log().info("Calling deleteReservation txn");
  boolean success = new DeleteReservation().doTxn(conn, f_id, c_id, c_id_str, ff_c_id_str, ff_al_id, r_seatnum);
  if (!success) {
    conn.rollback();
    log().info("rollback the connection");
    return false;
  }
      
  conn.commit();
  
  // We can remove this from our set of full flights because know that there is now a free seat
  BitSet seats = getSeatsBitSet(r.flightInfo);
  seats.set(r.seatnum, false);

  // And then put it up for a pending insert
  if (random.nextInt(HUNDRED) < PROB_REQUEUE_DELETED_RESERVATION) {
    synchronized(INSERT) {
      CACHE_RESERVATIONS.get(CacheType.PENDING_INSERTS).add(r);
    }
  }

  return true;
  
}
 
Example 20
Source File: SeatsTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
private boolean makeNewReservation(Connection conn) throws SQLException {
    Reservation reservation = null;
    BitSet seats = null;
    boolean success = false;
    
    while (reservation == null) {
      Reservation r = null;
      synchronized(INSERT) {
        LinkedList<Reservation> cache = CACHE_RESERVATIONS.get(CacheType.PENDING_INSERTS);
        if (cache == null) throw new TestException("Unexpected " + CacheType.PENDING_INSERTS);
        if (logDML)
          log().info(String.format("Attempting to get a new pending insert Reservation [totalPendingInserts=%d]",
                                  cache.size()));
        r = cache.poll();
      } 
      if (r == null) {
        if (logDML) log().warning("Unable to execute NewReservation - No available reservations to insert");
        break;
      }
      
      seats = getSeatsBitSet(r.flightInfo);
      
      if (isFlightFull(seats)) {
        if (logDML) log().info(String.format("%s is full", r.flightInfo));
        continue;
      }
      else if (isCustomerBookedOnFlight(r.customer_id, r.flightInfo)) {
        if (logDML) log().info(String.format("%s is already booked on %s", r.customer_id, r.flightInfo));
        continue;
      }
      reservation = r; 
    } // WHILE
    if (reservation == null) {
      if (logDML) log().warning("Failed to find a valid pending insert Reservation\n" + this.toString());
      return false;
    }
    
    // Generate a random price for now
    //double price = 2.0 * random.number(RESERVATION_PRICE_MIN,
    //                                RESERVATION_PRICE_MAX);

    
    double price = reservation.price;
    
    // Generate random attributes
    long attributes[] = new long[9];
    for (int i = 0; i < attributes.length; i++) {
      attributes[i] = random.nextLong();
    } // FOR
    
    if (logDML) log().info("Calling NewResveraton");
    boolean retry = true;
    int retryNum = 0;
    int maxRetries = 3;
    while (retry && retryNum<maxRetries) {
      try {
        success = new NewReservation().doTxn(conn, reservation.id,
                       reservation.customer_id.id,
                       reservation.flightInfo.flight_id,
                       (long) reservation.seatnum,
                       price,
                       attributes);
        retry = false;
        retryNum++;
      } catch (SQLException se) {
        if (se.getSQLState().equals("X0Z02")) {
          log().info("update on flight could get conflict exception, will retry");
          retry = true;
        }
        else throw se;
      }
    }
    if (!success) {
      conn.rollback(); 
      return success;
    }
    conn.commit();
    
    // Mark this seat as successfully reserved
    seats.set(reservation.seatnum);
    
    // Set it up so we can play with it later
    this.requeueReservation(reservation);
    
    return success;
}