Java Code Examples for java.util.HashMap#clear()

The following examples show how to use java.util.HashMap#clear() . 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: HashMapCloneLeak.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    HashMap<Integer, Object> hm = makeMap();
    hm = (HashMap<Integer, Object>)hm.clone();
    hm.clear();
    // There should no longer be a strong reference to testObject
    // the WeakReference should be nulled out by GC. If not,
    // we will hang here until timed out by the test harness.
    Object[] chain = null;
    while (wr.get() != null) {
        try {
            Object[] allocate = new Object[1000000];
            allocate[0] = chain;
            chain = allocate;
        } catch (OutOfMemoryError oome) {
            chain = null;
        }
        System.gc();
        Thread.sleep(100);
    }
}
 
Example 2
Source File: DownloadDBHelper.java    From Android_framework with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 更新该线程下载的完成度
 */
public void updateInfos(String url, ArrayList<FileDownloadManager.DownloadInfo> infos){
    ArrayList<String> columns = DownloadDB.TABLES.DOWNLOAD.getTableColumns();
    HashMap<String, String> maps = new HashMap<>();

    initUpdateDB();
    if (mDb == null)
        return;
    try {
        mDb.beginTransaction();
        for (FileDownloadManager.DownloadInfo info : infos){
            maps.clear();
            maps.put(columns.get(4), info.completeSize+"");
            String whereClause = columns.get(0)+"=? and "+columns.get(1)+"=?";
            String[] whereArgs = new String[]{info.id+"", url};
            mDb.update(maps, whereClause, whereArgs);
        }
        mDb.setTransactionSuccessful();
    }catch (Exception e){
        e.printStackTrace();
    }finally {
        mDb.endTransaction();
        mDb.close();
    }
}
 
Example 3
Source File: GuildDeleteService.java    From gameserver with Apache License 2.0 6 votes vote down vote up
@Override
protected Void doInBackground() throws Exception {
	statusBar.updateStatus("删除公会数据");
	statusBar.progressBarAnimationStart();
	HashMap<String, DBObjectTreeTableNode> map = model.getChangedMap();
	Set<String> set = map.keySet();
	for ( String userId : set ) {
		int option = JOptionPane.showConfirmDialog(null, "您是否要删除公会"+userId+"?", "删除公会成员", 
				JOptionPane.YES_NO_OPTION);
		if ( option == JOptionPane.YES_OPTION ) {
			DBObject query = MongoUtil.createDBObject("userId", userId);
			//DBObject objectToSave = (DBObject)map.get(userId).getUserObject();
			//MongoUtil.saveToMongo(query, objectToSave, databaseName, namespace, collection, true);
			MongoUtil.deleteFromMongo(query, databaseName, namespace, collection, true);
			JOptionPane.showMessageDialog(null, "账号"+userId+"已经删除"); 
 		}
	}
	map.clear();
	statusBar.progressBarAnimationStop();
	statusBar.updateStatus("删除公会成员数据");
	return null;
}
 
Example 4
Source File: TvShowEpisodes.java    From Mizuu with Apache License 2.0 6 votes vote down vote up
@Override
protected Void doInBackground(Void... params) {
	HashMap<String, EpisodeCounter> seasons = MizuuApplication.getTvEpisodeDbAdapter().getSeasons(mShowId);

	File temp;
	for (String key : seasons.keySet()) {
		temp = FileUtils.getTvShowSeason(mContext, mShowId, key);				
		mItems.add(new GridSeason(mContext, mShowId, Integer.valueOf(key), seasons.get(key).getEpisodeCount(), seasons.get(key).getWatchedCount(),
				temp.exists() ? temp :
					FileUtils.getTvShowThumb(mContext, mShowId)));
	}

	seasons.clear();

	Collections.sort(mItems);

	return null;
}
 
Example 5
Source File: SimplePrincipalMapper.java    From knox with Apache License 2.0 5 votes vote down vote up
private Map<String, String[]> parseMapping(String mappings)
    throws PrincipalMappingException {
  if (mappings == null) {
    return null;
  }
  HashMap<String, String[]> table = new HashMap<>();
  try {
    StringTokenizer t = new StringTokenizer(mappings, ";");
    if (t.hasMoreTokens()) {
      do {
        String mapping = t.nextToken();
        String principals = mapping.substring(0, mapping.indexOf('='));
        String value = mapping.substring(mapping.indexOf('=')+1);
        String[] v = value.split(",");
        String[] p = principals.split(",");
        for (String s : p) {
          table.put(s, v);
        }
      } while(t.hasMoreTokens());
    }
    return table;
  }
  catch (Exception e) {
    // do not leave table in an unknown state - clear it instead
    // no principal mapping will occur
    table.clear();
    throw new PrincipalMappingException("Unable to load mappings from provided string: " + mappings + " - no principal mapping will be provided.", e);
  }
}
 
Example 6
Source File: BenefitsCalculationLookupableHelperServiceImpl.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @see org.kuali.rice.kns.lookup.AbstractLookupableHelperServiceImpl#validateSearchParameters(java.util.Map)
 */
@Override
public void validateSearchParameters(Map fieldValues) {
    super.validateSearchParameters(fieldValues);
    
    HashMap<String, String> fieldsMap = new HashMap<String, String>();
    
    String accountNumber = (String) fieldValues.get("accountCodeOffset");
    String objectCode = (String) fieldValues.get("objectCodeOffset");
    
    // Validate the Account Number field is a valid Account Number in the DB
    if (StringUtils.isNotEmpty(accountNumber)) {
        fieldsMap.clear();
        fieldsMap.put(GeneralLedgerConstants.ColumnNames.ACCOUNT_NUMBER, accountNumber);
        List<Account> accountNums = (List<Account>) SpringContext.getBean(BusinessObjectService.class).findMatching(Account.class, fieldsMap);
       
        
        if (accountNums == null || accountNums.size() <= 0) {
            GlobalVariables.getMessageMap().putError("accountNumber", KFSKeyConstants.ERROR_CUSTOM, new String[] { "Invalid Account Number: " + accountNumber });
            throw new ValidationException("errors in search criteria");
        }
    }
    
    // Validate the Object Code field is a valid Object Code in the DB
    if (StringUtils.isNotEmpty(objectCode)) {
        fieldsMap.clear();
        fieldsMap.put(GeneralLedgerConstants.ColumnNames.OBJECT_CODE, objectCode);
        List<ObjectCode> objCodes = (List<ObjectCode>) SpringContext.getBean(BusinessObjectService.class).findMatching(ObjectCode.class, fieldsMap);
       
        
        if (objCodes == null || objCodes.size() <= 0) {
            GlobalVariables.getMessageMap().putError(KFSPropertyConstants.OBJECT_CODE, KFSKeyConstants.ERROR_CUSTOM, new String[] { "Invalid Object Code: " + objectCode });
            throw new ValidationException("errors in search criteria");
        }
    }
}
 
Example 7
Source File: Preprocessor.java    From 3Dscript with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static void collectMacros(StringBuffer textbuffer, boolean del, HashMap<String, String> ret) throws PreprocessingException {
	MacroExtractor me = new MacroExtractor(textbuffer);
	me.parse();
	if(del)
		me.deleteScripts();
	ret.clear();
	ret.putAll(me.scripts);
}
 
Example 8
Source File: TraceabilityDashboardServiceImpl.java    From Insights with Apache License 2.0 5 votes vote down vote up
private HashMap<String, List<String>> resolveUpAndDownLinks(HashMap<String, List<String>> drilldownListMap,
		List<String> baseTool) throws GraphDBException {

	HashMap<String, List<String>> mainToolList = new HashMap<>();
	List<String> excludeLabels = new ArrayList<>();
	excludeLabels.addAll(baseTool);
	while (drilldownListMap.size() > 0) {
		List<String> labelsTemp = new ArrayList<>();
		HashMap<String, List<String>> tempMap = new HashMap<>();
		for (Map.Entry<String, List<String>> entry : drilldownListMap.entrySet()) {
			String tool = entry.getKey();
			List<String> uuids = entry.getValue();
			mainToolList.put(tool, uuids);
			String cypher = buildCypherQuery(tool, "uuid", uuids, excludeLabels, 2);
			/* collect all parent or child uuids for current basenode. */
			tempMap.putAll(format(executeCypherQuery(cypher), Arrays.asList(tool)));
			/* collect the tools as basetool for the next hop in drilldown */
			labelsTemp.addAll(Arrays.asList(tool));

		}
		excludeLabels = (labelsTemp.stream().distinct().collect(Collectors.toList()));
		drilldownListMap.clear();
		drilldownListMap.putAll(tempMap);

	}
	return mainToolList;
}
 
Example 9
Source File: HeapPriorityQueueSet.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void clear() {
	super.clear();
	for (HashMap<?, ?> elementHashMap : deduplicationMapsByKeyGroup) {
		elementHashMap.clear();
	}
}
 
Example 10
Source File: BLEService.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
public void startScan(int i)
{
    Debug.TRACE();
    HashMap hashmap = new HashMap();
    if (m_LeScanCallback == null)
    {
        m_LeScanCallback = new f(this, hashmap);
    }
    hashmap.clear();
    Iterator iterator = getConnectedDevices().iterator();
    do
    {
        if (!iterator.hasNext())
        {
            break;
        }
        BluetoothDevice bluetoothdevice = (BluetoothDevice)iterator.next();
        if (bluetoothdevice.getAddress().startsWith("88:0F:10"))
        {
            hashmap.put(bluetoothdevice.getAddress(), bluetoothdevice);
            Intent intent = new Intent(INTENT_ACTION_DEVICE_FOUND);
            intent.putExtra(INTENT_EXTRA_DEVICE, bluetoothdevice);
            intent.putExtra(INTENT_EXTRA_PARAM, 0);
            c_BroadcastManager.sendBroadcast(intent);
        }
    } while (true);
    m_BluetoothAdapter.startLeScan(m_LeScanCallback);
    boolean flag;
    if (i > 0)
    {
        flag = true;
    } else
    {
        flag = false;
    }
    Debug.ASSERT_TRUE(flag);
    m_StopScanRunnable = new g(this);
    m_Handler.postDelayed(m_StopScanRunnable, i);
}
 
Example 11
Source File: ExceptMapTest.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
public void testNodeProcessingSchema(ExceptMap oper)
{
  CountAndLastTupleTestSink exceptSink = new CountAndLastTupleTestSink();
  oper.except.setSink(exceptSink);
  oper.setKey("a");
  oper.setValue(3.0);
  oper.setTypeEQ();

  oper.beginWindow(0);
  HashMap<String, Number> input = new HashMap<String, Number>();
  input.put("a", 2);
  input.put("b", 20);
  input.put("c", 1000);
  oper.data.process(input);
  input.clear();
  input.put("a", 3);
  oper.data.process(input);
  oper.endWindow();

  // One for each key
  Assert.assertEquals("number emitted tuples", 1, exceptSink.count);
  for (Map.Entry<String, Number> e : ((HashMap<String, Number>)exceptSink.tuple)
      .entrySet()) {
    if (e.getKey().equals("a")) {
      Assert.assertEquals("emitted value for 'a' was ", new Double(2), e
          .getValue().doubleValue(), 0);
    } else if (e.getKey().equals("b")) {
      Assert.assertEquals("emitted tuple for 'b' was ", new Double(20), e
          .getValue().doubleValue(), 0);
    } else if (e.getKey().equals("c")) {
      Assert.assertEquals("emitted tuple for 'c' was ", new Double(1000), e
          .getValue().doubleValue(), 0);
    }
  }
}
 
Example 12
Source File: CompareMapTest.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testNodeProcessingSchema(CompareMap oper)
{
  CountAndLastTupleTestSink matchSink = new CountAndLastTupleTestSink();
  oper.compare.setSink(matchSink);
  oper.setKey("a");
  oper.setValue(3.0);
  oper.setTypeNEQ();

  oper.beginWindow(0);
  HashMap<String, Number> input = new HashMap<String, Number>();

  input.put("a", 2);
  input.put("b", 20);
  input.put("c", 1000);
  oper.data.process(input);
  input.clear();
  input.put("a", 3);
  oper.data.process(input);
  oper.endWindow();

  // One for each key
  Assert.assertEquals("number emitted tuples", 1, matchSink.count);
  for (Map.Entry<String, Number> e : ((HashMap<String, Number>)matchSink.tuple).entrySet()) {
    if (e.getKey().equals("a")) {
      Assert.assertEquals("emitted value for 'a' was ", new Double(2), e.getValue().doubleValue(), 0);
    } else if (e.getKey().equals("b")) {
      Assert.assertEquals("emitted tuple for 'b' was ", new Double(20), e.getValue().doubleValue(), 0);
    } else if (e.getKey().equals("c")) {
      Assert.assertEquals("emitted tuple for 'c' was ", new Double(1000), e.getValue().doubleValue(), 0);
    }
  }
}
 
Example 13
Source File: GroupParser.java    From dsworkbench with Apache License 2.0 5 votes vote down vote up
private boolean parseVillageRenamerData(String pData) {
    HashMap<String, List<Village>> mappings = new HashMap<>();
    try {
        JSONObject sectorObject = new JSONObject(pData);
        JSONObject data = (JSONObject) sectorObject.get("id");
        Iterator<String> keys = data.keys();
        while (keys.hasNext()) {
            String villageId = keys.next();
            String groupName = (String) data.get(villageId);

            List<Village> groups = mappings.get(groupName);
            if (groups == null) {
                groups = new LinkedList<>();
                mappings.put(groupName, groups);
            }
            Village v = DataHolder.getSingleton().getVillagesById().get(Integer.parseInt(villageId));
            groups.add(v);
        }
    } catch (JSONException | NumberFormatException e) {
        logger.warn("Failed to parse group info from village renamer data");
        mappings.clear();
    }

    if (!mappings.isEmpty()) {
        DSWorkbenchMainFrame.getSingleton().fireGroupParserEvent(mappings);
        return true;
    }
    return false;
}
 
Example 14
Source File: FaithfulRScript.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Override
public void endWindow()
{
  if (readingsList.size() == 0) {
    return;
  }
  LOG.info("Input data size: readingsList - " + readingsList.size());

  double[] eruptionDuration = new double[readingsList.size()];
  int[] waitingTime = new int[readingsList.size()];

  for (int i = 0; i < readingsList.size(); i++) {
    eruptionDuration[i] = readingsList.get(i).getEruptionDuration();
    waitingTime[i] = readingsList.get(i).getWaitingTime();
  }
  LOG.info("Input data size: eruptionDuration - " + eruptionDuration.length);
  LOG.info("Input data size: waitingTime - " + waitingTime.length);

  HashMap<String, Object> map = new HashMap<String, Object>();

  map.put("ELAPSEDTIME", elapsedTime);
  map.put("ERUPTIONS", eruptionDuration);
  map.put("WAITING", waitingTime);

  super.process(map);
  readingsList.clear();
  map.clear();
}
 
Example 15
Source File: ScheduledDeliveryHandlerImpl.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
   HashMap<Queue, LinkedList<MessageReference>> refs = new HashMap<>();

   runnables.remove(deliveryTime);

   final long now = System.currentTimeMillis();

   if (now < deliveryTime) {
      // Ohhhh... blame it on the OS
      // on some OSes (so far Windows only) the precision of the scheduled executor could eventually give
      // an executor call earlier than it was supposed...
      // for that reason we will schedule it again so no messages are lost!
      // we can't just assume deliveryTime here as we could deliver earlier than what we are supposed to
      // this is basically a hack to work around an OS or JDK bug!
      if (logger.isTraceEnabled()) {
         logger.trace("Scheduler is working around OS imprecisions on " +
                         "timing and re-scheduling an executor. now=" + now +
                         " and deliveryTime=" + deliveryTime);
      }
      ScheduledDeliveryHandlerImpl.this.scheduleDelivery(deliveryTime);
   }

   if (logger.isTraceEnabled()) {
      logger.trace("Is it " + System.currentTimeMillis() + " now and we are running deliveryTime = " + deliveryTime);
   }

   synchronized (scheduledReferences) {

      Iterator<RefScheduled> iter = scheduledReferences.iterator();
      while (iter.hasNext()) {
         MessageReference reference = iter.next().getRef();
         if (reference.getScheduledDeliveryTime() > now) {
            // We will delivery as long as there are messages to be delivered
            break;
         }

         iter.remove();
         metrics.decrementMetrics(reference);

         reference.setScheduledDeliveryTime(0);

         LinkedList<MessageReference> references = refs.get(reference.getQueue());

         if (references == null) {
            references = new LinkedList<>();
            refs.put(reference.getQueue(), references);
         }

         if (logger.isTraceEnabled()) {
            logger.trace("sending message " + reference + " to delivery, deliveryTime =  " + deliveryTime);
         }

         references.addFirst(reference);
      }
      if (logger.isTraceEnabled()) {
         logger.trace("Finished loop on deliveryTime = " + deliveryTime);
      }
   }

   for (Map.Entry<Queue, LinkedList<MessageReference>> entry : refs.entrySet()) {

      Queue queue = entry.getKey();
      LinkedList<MessageReference> list = entry.getValue();
      if (logger.isTraceEnabled()) {
         logger.trace("Delivering " + list.size() + " elements on list to queue " + queue);
      }
      queue.addHead(list, true);
   }

   // Just to speed up GC
   refs.clear();
}
 
Example 16
Source File: MonthAdapter.java    From AlarmOn with Apache License 2.0 4 votes vote down vote up
@SuppressLint("NewApi")
@SuppressWarnings("unchecked")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    MonthView v;
    HashMap<String, Integer> drawingParams = null;
    if (convertView != null) {
        v = (MonthView) convertView;
        // We store the drawing parameters in the view so it can be recycled
        drawingParams = (HashMap<String, Integer>) v.getTag();
    } else {
        v = createMonthView(mContext);
        // Set up the new view
        LayoutParams params = new LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        v.setLayoutParams(params);
        v.setClickable(true);
        v.setOnDayClickListener(this);
    }
    if (drawingParams == null) {
        drawingParams = new HashMap<>();
    }
    drawingParams.clear();

    final int month = (position + mController.getStartDate().get(Calendar.MONTH)) % MONTHS_IN_YEAR;
    final int year = (position + mController.getStartDate().get(Calendar.MONTH)) / MONTHS_IN_YEAR + mController.getMinYear();

    int selectedDay = -1;
    if (isSelectedDayInMonth(year, month)) {
        selectedDay = mSelectedDay.day;
    }

    // Invokes requestLayout() to ensure that the recycled view is set with the appropriate
    // height/number of weeks before being displayed.
    v.reuse();

    drawingParams.put(MonthView.VIEW_PARAMS_SELECTED_DAY, selectedDay);
    drawingParams.put(MonthView.VIEW_PARAMS_YEAR, year);
    drawingParams.put(MonthView.VIEW_PARAMS_MONTH, month);
    drawingParams.put(MonthView.VIEW_PARAMS_WEEK_START, mController.getFirstDayOfWeek());
    v.setMonthParams(drawingParams);
    v.invalidate();
    return v;
}
 
Example 17
Source File: TopNUniqueTest.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testNodeProcessingSchema(TopNUnique oper)
{
  CollectorTestSink sortSink = new CollectorTestSink();
  oper.top.setSink(sortSink);
  oper.setN(3);

  oper.beginWindow(0);
  HashMap<String, Number> input = new HashMap<String, Number>();

  input.put("a", 2);
  oper.data.process(input);

  input.clear();
  input.put("a", 20);
  oper.data.process(input);

  input.clear();
  input.put("a", 1000);
  oper.data.process(input);

  input.clear();
  input.put("a", 5);
  oper.data.process(input);

  input.clear();
  input.put("a", 20);
  input.put("b", 33);
  oper.data.process(input);

  input.clear();
  input.put("a", 33);
  input.put("b", 34);
  oper.data.process(input);

  input.clear();
  input.put("b", 34);
  input.put("a", 1);
  oper.data.process(input);

  input.clear();
  input.put("b", 6);
  input.put("a", 1001);
  oper.data.process(input);

  input.clear();
  input.put("c", 9);
  input.put("a", 5);
  oper.data.process(input);
  oper.endWindow();

  Assert.assertEquals("number emitted tuples", 3, sortSink.collectedTuples.size());
  for (Object o: sortSink.collectedTuples) {
    log.debug(o.toString());
    for (Map.Entry<String, ArrayList<HashMap<Number, Integer>>> e: ((HashMap<String, ArrayList<HashMap<Number, Integer>>>)o).entrySet()) {
      if (e.getKey().equals("a")) {
        Assert.assertEquals("emitted value for 'a' was ", 3, e.getValue().size());
      } else if (e.getKey().equals("b")) {
        Assert.assertEquals("emitted tuple for 'b' was ", 3, e.getValue().size());
      } else if (e.getKey().equals("c")) {
        Assert.assertEquals("emitted tuple for 'c' was ", 1, e.getValue().size());
      }
    }
  }
  log.debug("Done testing round\n");
}
 
Example 18
Source File: ResourceUtilsTests.java    From Indic-Keyboard with Apache License 2.0 4 votes vote down vote up
public void testFindConstantForKeyValuePairsCombined() {
    final String HARDWARE_KEY = "HARDWARE";
    final String MODEL_KEY = "MODEL";
    final String MANUFACTURER_KEY = "MANUFACTURER";
    final String[] array = {
        ",defaultValue",
        "no_comma",
        "error_pattern,0.1",
        "HARDWARE=grouper:MANUFACTURER=asus,0.3",
        "HARDWARE=mako:MODEL=Nexus 4,0.4",
        "HARDWARE=manta:MODEL=Nexus 10:MANUFACTURER=samsung,0.2"
    };
    final String[] failArray = {
        ",defaultValue",
        "HARDWARE=grouper:MANUFACTURER=ASUS,0.3",
        "HARDWARE=mako:MODEL=Nexus_4,0.4",
        "HARDWARE=mantaray:MODEL=Nexus 10:MANUFACTURER=samsung,0.2"
    };

    final HashMap<String,String> keyValues = new HashMap<>();
    keyValues.put(HARDWARE_KEY, "grouper");
    keyValues.put(MODEL_KEY, "Nexus 7");
    keyValues.put(MANUFACTURER_KEY, "asus");
    assertEquals("0.3", ResourceUtils.findConstantForKeyValuePairs(keyValues, array));
    assertNull(ResourceUtils.findConstantForKeyValuePairs(keyValues, failArray));

    keyValues.clear();
    keyValues.put(HARDWARE_KEY, "mako");
    keyValues.put(MODEL_KEY, "Nexus 4");
    keyValues.put(MANUFACTURER_KEY, "LGE");
    assertEquals("0.4", ResourceUtils.findConstantForKeyValuePairs(keyValues, array));
    assertNull(ResourceUtils.findConstantForKeyValuePairs(keyValues, failArray));

    keyValues.clear();
    keyValues.put(HARDWARE_KEY, "manta");
    keyValues.put(MODEL_KEY, "Nexus 10");
    keyValues.put(MANUFACTURER_KEY, "samsung");
    assertEquals("0.2", ResourceUtils.findConstantForKeyValuePairs(keyValues, array));
    assertNull(ResourceUtils.findConstantForKeyValuePairs(keyValues, failArray));
    keyValues.put(HARDWARE_KEY, "mantaray");
    assertNull(ResourceUtils.findConstantForKeyValuePairs(keyValues, array));
    assertEquals("0.2", ResourceUtils.findConstantForKeyValuePairs(keyValues, failArray));
}
 
Example 19
Source File: MonthAdapter.java    From StyleableDateTimePicker with MIT License 4 votes vote down vote up
@SuppressLint("NewApi")
@SuppressWarnings("unchecked")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    MonthView v;
    HashMap<String, Integer> drawingParams = null;
    if (convertView != null) {
        v = (MonthView) convertView;
        // We store the drawing parameters in the view so it can be recycled
        drawingParams = (HashMap<String, Integer>) v.getTag();
    } else {
        v = createMonthView(mContext);
        // Set up the new view
        LayoutParams params = new LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        v.setLayoutParams(params);
        v.setClickable(true);
        v.setOnDayClickListener(this);
    }
    if (drawingParams == null) {
        drawingParams = new HashMap<String, Integer>();
    }
    drawingParams.clear();

    final int month = position % MONTHS_IN_YEAR;
    final int year = position / MONTHS_IN_YEAR + mController.getMinYear();

    int selectedDay = -1;
    if (isSelectedDayInMonth(year, month)) {
        selectedDay = mSelectedDay.day;
    }

    // Invokes requestLayout() to ensure that the recycled view is set with the appropriate
    // height/number of weeks before being displayed.
    v.reuse();

    drawingParams.put(MonthView.VIEW_PARAMS_SELECTED_DAY, selectedDay);
    drawingParams.put(MonthView.VIEW_PARAMS_YEAR, year);
    drawingParams.put(MonthView.VIEW_PARAMS_MONTH, month);
    drawingParams.put(MonthView.VIEW_PARAMS_WEEK_START, mController.getFirstDayOfWeek());
    v.setMonthParams(drawingParams);
    v.invalidate();
    return v;
}
 
Example 20
Source File: DistinctMapTest.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
/**
 * Test node logic emits correct results
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testNodeProcessing() throws Exception
{
  DistinctMap<String, Number> oper = new DistinctMap<String, Number>();

  CollectorTestSink sortSink = new CollectorTestSink();
  oper.distinct.setSink(sortSink);


  oper.beginWindow(0);
  HashMap<String, Number> input = new HashMap<String, Number>();

  input.put("a", 2);
  oper.data.process(input);
  input.clear();
  input.put("a", 2);
  oper.data.process(input);

  input.clear();
  input.put("a", 1000);
  oper.data.process(input);

  input.clear();
  input.put("a", 5);
  oper.data.process(input);

  input.clear();
  input.put("a", 2);
  input.put("b", 33);
  oper.data.process(input);

  input.clear();
  input.put("a", 33);
  input.put("b", 34);
  oper.data.process(input);

  input.clear();
  input.put("b", 34);
  oper.data.process(input);

  input.clear();
  input.put("b", 6);
  input.put("a", 2);
  oper.data.process(input);
  input.clear();
  input.put("c", 9);
  oper.data.process(input);
  oper.endWindow();

  Assert.assertEquals("number emitted tuples", 8, sortSink.collectedTuples.size());
  int aval = 0;
  int bval = 0;
  int cval = 0;
  for (Object o: sortSink.collectedTuples) {
    for (Map.Entry<String, Integer> e: ((HashMap<String, Integer>)o).entrySet()) {
      String key = e.getKey();
      if (key.equals("a")) {
        aval += e.getValue();
      } else if (key.equals("b")) {
        bval += e.getValue();
      } else if (key.equals("c")) {
        cval += e.getValue();
      }
    }
  }
  Assert.assertEquals("Total for key \"a\" ", 1040, aval);
  Assert.assertEquals("Total for key \"a\" ", 73, bval);
  Assert.assertEquals("Total for key \"a\" ", 9, cval);
}