public static Map<String, List<String>> toMultimap(Headers headers, String valueForNullKey) { Map<String, List<String>> result = new TreeMap(FIELD_NAME_COMPARATOR); int size = headers.size(); for (int i = 0; i < size; i++) { String fieldName = headers.name(i); String value = headers.value(i); List<String> allValues = new ArrayList(); List<String> otherValues = (List) result.get(fieldName); if (otherValues != null) { allValues.addAll(otherValues); } allValues.add(value); result.put(fieldName, Collections.unmodifiableList(allValues)); } if (valueForNullKey != null) { result.put(null, Collections.unmodifiableList(Collections.singletonList (valueForNullKey))); } return Collections.unmodifiableMap(result); }
/** * Retrieves the services that are available for use with the description for each service. * The Services are determined by looking up all of the implementations of the * Customer Service interface that are using the DataService qualifier annotation. * The DataService annotation contains the service name and description information. * @return Map containing a list of services available and a description of each one. */ public Map<String,String> getServices (){ TreeMap<String,String> services = new TreeMap<String,String>(); logger.fine("Getting CustomerService Impls"); Set<Bean<?>> beans = beanManager.getBeans(CustomerService.class,new AnnotationLiteral<Any>() { private static final long serialVersionUID = 1L;}); for (Bean<?> bean : beans) { for (Annotation qualifer: bean.getQualifiers()){ if(DataService.class.getName().equalsIgnoreCase(qualifer.annotationType().getName())){ DataService service = (DataService) qualifer; logger.fine(" name="+service.name()+" description="+service.description()); services.put(service.name(), service.description()); } } } return services; }
public static final String calculate(Map<String, ? extends Object> parameters, String appsecret) { TreeMap<String, Object> params = new TreeMap(parameters); params.remove("sign"); params.put("appsecret", appsecret); StringBuilder stringBuilder = new StringBuilder(); Iterator var4 = params.entrySet().iterator(); while(var4.hasNext()) { Map.Entry<String, Object> entry = (Map.Entry)var4.next(); stringBuilder.append(((String)entry.getKey()).trim()); stringBuilder.append("="); stringBuilder.append(entry.getValue().toString().trim()); stringBuilder.append("&"); } stringBuilder.deleteCharAt(stringBuilder.length() - 1); return DigestUtils.sha1Hex(stringBuilder.toString()); }
private static SortedMap<String, Object> makeMap( String[] itemNames, Object[] itemValues) throws OpenDataException { if (itemNames == null || itemValues == null) throw new IllegalArgumentException("Null itemNames or itemValues"); if (itemNames.length == 0 || itemValues.length == 0) throw new IllegalArgumentException("Empty itemNames or itemValues"); if (itemNames.length != itemValues.length) { throw new IllegalArgumentException( "Different lengths: itemNames[" + itemNames.length + "], itemValues[" + itemValues.length + "]"); } SortedMap<String, Object> map = new TreeMap<String, Object>(); for (int i = 0; i < itemNames.length; i++) { String name = itemNames[i]; if (name == null || name.equals("")) throw new IllegalArgumentException("Null or empty item name"); if (map.containsKey(name)) throw new OpenDataException("Duplicate item name " + name); map.put(itemNames[i], itemValues[i]); } return map; }
public static TreeMap<String, MassBank> getAllDBFiles(File[] inputFiles, String ser, boolean forceRecalculation, boolean withPeaks)throws Exception { TreeMap<String, MassBank> dbFiles=null; if(!forceRecalculation){ try{ ObjectInputStream ois = new ObjectInputStream(new FileInputStream(ser)); dbFiles = (TreeMap<String, MassBank>) ois.readObject(); ois.close(); }catch(Exception e){ System.err.println(e); } } if(dbFiles==null){ System.out.println("calculating database file..."); dbFiles=new TreeMap<String,MassBank>(); for(File f:inputFiles){ getAllDBFiles(f, dbFiles, withPeaks); } ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(ser)); oos.writeObject(dbFiles); oos.flush(); oos.close(); System.out.println("...finished"); } return dbFiles; }
public Map<String, TestSite> getSitesForUser(String username) { if(username == null) { username = AuthenticationUtil.getAdminUserName(); } List<SiteInfo> sites = TenantUtil.runAsUserTenant(new TenantRunAsWork<List<SiteInfo>>() { @Override public List<SiteInfo> doWork() throws Exception { List<SiteInfo> results = siteService.listSites(null, null); return results; } }, username, getId()); TreeMap<String, TestSite> ret = new TreeMap<String, TestSite>(); for(SiteInfo siteInfo : sites) { TestSite site = new TestSite(TestNetwork.this, siteInfo/*, null*/); ret.put(site.getSiteId(), site); } return ret; }
void write(File outputFile) throws IOException { IoActions.writeTextFile(outputFile, new ErroringAction<BufferedWriter>() { @Override protected void doExecute(BufferedWriter writer) throws Exception { final Map<String, JavadocOptionFileOption<?>> options = new TreeMap<String, JavadocOptionFileOption<?>>(optionFile.getOptions()); JavadocOptionFileWriterContext writerContext = new JavadocOptionFileWriterContext(writer); JavadocOptionFileOption<?> localeOption = options.remove("locale"); if (localeOption != null) { localeOption.write(writerContext); } for (final String option : options.keySet()) { options.get(option).write(writerContext); } optionFile.getSourceNames().write(writerContext); } }); }
@Override public synchronized void putBuffer(ByteBuffer buffer) { TreeMap<Key, ByteBuffer> tree = getBufferTree(buffer.isDirect()); while (true) { Key key = new Key(buffer.capacity(), System.nanoTime()); if (!tree.containsKey(key)) { tree.put(key, buffer); return; } // Buffers are indexed by (capacity, time). // If our key is not unique on the first try, we try again, since the // time will be different. Since we use nanoseconds, it's pretty // unlikely that we'll loop even once, unless the system clock has a // poor granularity. } }
/** Combine results */ static <T extends Combinable<T>> Map<Parameter, T> combine(Map<Parameter, List<T>> m) { final Map<Parameter, T> combined = new TreeMap<Parameter, T>(); for(Parameter p : Parameter.values()) { //note: results would never be null due to the design of Util.combine final List<T> results = Util.combine(m.get(p)); Util.out.format("%-6s => ", p); if (results.size() != 1) Util.out.println(results.toString().replace(", ", ",\n ")); else { final T r = results.get(0); combined.put(p, r); Util.out.println(r); } } return combined; }
/** * The constructor for chaining nodes inside of ConditionVertex. * * @param state the actual CollisionAtPosition * @param scene the actual SimulatedLevelScene (has to updated befor) * @param knowledge (not actually used in this constructor) knowledge is extracted from the scene (?) * @param effects the known effects * @param depth the depth of the actual node (incremented in everytime a node is expanded) * @param previousInteraction the goal which was reached in the previous node in the simulation * @param relevantEffect the relevant Effect * @param topProbability the maximum probability */ public ConditionVertex(CollisionAtPosition state, SimulatedLevelScene scene, TreeMap<ConditionDirectionPair, TreeMap<Effect, Double>> knowledge, TreeMap<Effect, Double> effects, int depth, Goal previousInteraction, Effect relevantEffect, double topProbability) { this.scene = scene; this.depth = depth; this.effects = effects; this.previousInteraction = previousInteraction; this.state = state; this.knowledge = scene.getKnowledge(); this.importantEffect = relevantEffect; this.topProbability = topProbability; }
static void fastScrollVertical(int amountAxis, RecyclerView recyclerView) { LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager(); if (indexHeight == null) { indexHeight = new TreeMap<>(); //call this method the OnScrollListener's onScrolled will be called,but dx and dy always be zero. linearLayoutManager.scrollToPositionWithOffset(0, -amountAxis); } else { int total = 0, count = 0; Iterator<Integer> iterator = indexHeight.keySet().iterator(); while (null != iterator && iterator.hasNext()) { int height = indexHeight.get(iterator.next()); if (total + height >= amountAxis) { break; } total += height; count++; } linearLayoutManager.scrollToPositionWithOffset(count, -(amountAxis - total)); } }
/** * higherKey returns next element */ public void testHigherKey() { TreeMap q = map5(); Object e1 = q.higherKey(three); assertEquals(four, e1); Object e2 = q.higherKey(zero); assertEquals(one, e2); Object e3 = q.higherKey(five); assertNull(e3); Object e4 = q.higherKey(six); assertNull(e4); }
static void findMinLightsCount(Node[] nodes, int curr, TreeMap<Integer, Integer> lightsToVariantsCount) { if (curr == nodes.length) { if (allEdgesHighlighted(nodes[0])) { int amountOfSwitchedOnNodes = calculateSwitchedOnNodes(nodes); Integer variantsCount = lightsToVariantsCount.getOrDefault(amountOfSwitchedOnNodes, 0); lightsToVariantsCount.put(amountOfSwitchedOnNodes, variantsCount + 1); } return; } nodes[curr].isSwitchedOn = true; findMinLightsCount(nodes, curr + 1, lightsToVariantsCount); nodes[curr].isSwitchedOn = false; findMinLightsCount(nodes, curr + 1, lightsToVariantsCount); }
/** * Returns an unmodifiable map of general request properties used by this * connection. */ @Override public Map<String, List<String>> getRequestProperties() { if (connected) { throw new IllegalStateException( "Cannot access request headers after connection is set."); } Map<String, List<String>> map = new TreeMap<String, List<String>>( String.CASE_INSENSITIVE_ORDER); for (Pair<String, String> entry : mRequestHeaders) { if (map.containsKey(entry.first)) { // This should not happen due to setRequestPropertyInternal. throw new IllegalStateException( "Should not have multiple values."); } else { List<String> values = new ArrayList<String>(); values.add(entry.second); map.put(entry.first, Collections.unmodifiableList(values)); } } return Collections.unmodifiableMap(map); }
public void index(Map<String, Object> context) throws Exception { Map<String, String> properties = new TreeMap<String, String>(); StringBuilder msg = new StringBuilder(); msg.append("Version: "); msg.append(Version.getVersion(Envs.class, "2.2.0")); properties.put("Registry", msg.toString()); String address = NetUtils.getLocalHost(); properties.put("Host", NetUtils.getHostName(address) + "/" + address); properties.put("Java", System.getProperty("java.runtime.name") + " " + System.getProperty("java.runtime.version")); properties.put("OS", System.getProperty("os.name") + " " + System.getProperty("os.version")); properties.put("CPU", System.getProperty("os.arch", "") + ", " + String.valueOf(Runtime.getRuntime().availableProcessors()) + " cores"); properties.put("Locale", Locale.getDefault().toString() + "/" + System.getProperty("file.encoding")); properties.put("Uptime", formatUptime(ManagementFactory.getRuntimeMXBean().getUptime()) + " From " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z").format(new Date(ManagementFactory.getRuntimeMXBean().getStartTime())) + " To " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z").format(new Date())); context.put("properties", properties); }
private SchemaObjectIterator( List<T> schemaObjects, ReferenceCallback<T> callback ) { this.schemaObjects = schemaObjects; this.callback = callback; this.oid2numericOid = new HashMap<>(); this.numericOid2schemaObject = new TreeMap<>(); this.loopCount = 0; for ( T schemaObject : schemaObjects ) { String oid = Strings.toLowerCaseAscii( schemaObject.getOid() ); oid2numericOid.put( oid, oid ); for ( String name : schemaObject.getNames() ) { oid2numericOid.put( Strings.toLowerCaseAscii( name ), oid ); } numericOid2schemaObject.put( oid, schemaObject ); } }
/** @return a map of CAP that is specially suited for GUIs */ private TreeMap<Condition, TreeMap<CollisionDirection, TreeMap<Effect, Double>>> getMapForGUI() { TreeMap<Condition, TreeMap<CollisionDirection, TreeMap<Effect, Double>>> ret = new TreeMap<Condition, TreeMap<CollisionDirection, TreeMap<Effect, Double>>>(); for (Entry<ConditionDirectionPair, TreeMap<Effect, Double>> entry : knowledge .entrySet()) { if (!ret.containsKey(entry.getKey().condition)) { ret.put(entry.getKey().condition, new TreeMap<CollisionDirection, TreeMap<Effect, Double>>()); } ret.get(entry.getKey().condition).put( entry.getKey().collisionDirection, new TreeMap<Effect, Double>(entry.getValue())); } return ret; }
public ByteBufferBucketPool(long minBufferSize, long maxBufferSize, int minChunkSize, int increment, int maxChunkSize) { super(minBufferSize, maxBufferSize, minChunkSize, increment, maxChunkSize); int bucketsCount = maxChunkSize / increment; this._buckets = new TreeMap<Integer, ByteBufferBucket>(); // 平均分配初始化的桶size long bucketBufferSize = minBufferSize / bucketsCount; // 初始化桶 int chunkSize = 0; for (int i = 0; i < bucketsCount; i++) { chunkSize += increment; int chunkCount = (int) (bucketBufferSize / chunkSize); ByteBufferBucket bucket = new ByteBufferBucket(this, chunkSize, chunkCount); this._buckets.put(bucket.getChunkSize(), bucket); } }
/** * コンストラクタ. * @param srcHandler OEntityDocHandler * @param tgtHandler OEntityDocHandler */ public LinkDocHandler(final EntitySetDocHandler srcHandler, final EntitySetDocHandler tgtHandler) { this.cellId = srcHandler.getCellId(); this.boxId = srcHandler.getBoxId(); this.nodeId = srcHandler.getNodeId(); String srcType = srcHandler.getType(); String srcId = srcHandler.getId(); String tgtType = tgtHandler.getType(); String tgtId = tgtHandler.getId(); // ES 保存時の一意キー作成 TreeMap<String, String> tm = new TreeMap<String, String>(); tm.put(srcType, srcId); tm.put(tgtType, tgtId); this.ent1Type = tm.firstKey(); this.ent2Type = tm.lastKey(); this.ent1Key = tm.get(ent1Type); this.ent2Key = tm.get(ent2Type); this.id = this.createLinkId(); long dateTime = new Date().getTime(); this.published = dateTime; this.updated = dateTime; }
@Test(dataProvider = "StreamTestData<Integer>", dataProviderClass = StreamTestDataProvider.class) public void testSimpleGroupBy(String name, TestData.OfRef<Integer> data) throws ReflectiveOperationException { Function<Integer, Integer> classifier = i -> i % 3; // Single-level groupBy exerciseMapTabulation(data, groupingBy(classifier), new GroupedMapAssertion<>(classifier, HashMap.class, new ListAssertion<>())); exerciseMapTabulation(data, groupingByConcurrent(classifier), new GroupedMapAssertion<>(classifier, ConcurrentHashMap.class, new ListAssertion<>())); // With explicit constructors exerciseMapTabulation(data, groupingBy(classifier, TreeMap::new, toCollection(HashSet::new)), new GroupedMapAssertion<>(classifier, TreeMap.class, new CollectionAssertion<Integer>(HashSet.class, false))); exerciseMapTabulation(data, groupingByConcurrent(classifier, ConcurrentSkipListMap::new, toCollection(HashSet::new)), new GroupedMapAssertion<>(classifier, ConcurrentSkipListMap.class, new CollectionAssertion<Integer>(HashSet.class, false))); }
/** * View all notebook entries */ public ActionForward viewAll(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // initialize service object ICoreNotebookService notebookService = getNotebookService(); DynaActionForm notebookForm = (DynaActionForm) actionForm; // getting requested object according to coming parameters Integer learnerID = LearningWebUtil.getUserId(); // lessonID Long lessonID = (Long) notebookForm.get("currentLessonID"); if (lessonID == null || lessonID == 0) { lessonID = (Long) notebookForm.get(AttributeNames.PARAM_LESSON_ID); } // get all notebook entries for the learner TreeMap<Long, List<NotebookEntry>> entries = notebookService.getEntryByLesson(learnerID, CoreNotebookConstants.SCRATCH_PAD); request.getSession().setAttribute("entries", entries.values()); request.setAttribute("lessonID", lessonID); return mapping.findForward(NotebookAction.VIEW_ALL); }
@Test public void testDelete_CheckTimestampUpdated() throws IOException { TableName tableName = TableName.valueOf(name.getMethodName()); byte[] row1 = Bytes.toBytes("row1"); byte[] col1 = Bytes.toBytes("col1"); byte[] col2 = Bytes.toBytes("col2"); byte[] col3 = Bytes.toBytes("col3"); // Setting up region String method = this.getName(); this.region = initHRegion(tableName, method, CONF, fam1); try { // Building checkerList List<Cell> kvs = new ArrayList<Cell>(); kvs.add(new KeyValue(row1, fam1, col1, null)); kvs.add(new KeyValue(row1, fam1, col2, null)); kvs.add(new KeyValue(row1, fam1, col3, null)); NavigableMap<byte[], List<Cell>> deleteMap = new TreeMap<byte[], List<Cell>>( Bytes.BYTES_COMPARATOR); deleteMap.put(fam1, kvs); region.delete(deleteMap, Durability.SYNC_WAL); // extract the key values out the memstore: // This is kinda hacky, but better than nothing... long now = System.currentTimeMillis(); DefaultMemStore memstore = (DefaultMemStore) ((HStore) region.getStore(fam1)).memstore; Cell firstCell = memstore.cellSet.first(); assertTrue(firstCell.getTimestamp() <= now); now = firstCell.getTimestamp(); for (Cell cell : memstore.cellSet) { assertTrue(cell.getTimestamp() <= now); now = cell.getTimestamp(); } } finally { HRegion.closeHRegion(this.region); this.region = null; } }
@Override public Map<String, ApplicationGatewayRequestRoutingRule> requestRoutingRules() { Map<String, ApplicationGatewayRequestRoutingRule> rules = new TreeMap<>(); if (null != this.inner().requestRoutingRules()) { for (SubResource ruleRef : this.inner().requestRoutingRules()) { String ruleName = ResourceUtils.nameFromResourceId(ruleRef.id()); ApplicationGatewayRequestRoutingRule rule = this.parent().requestRoutingRules().get(ruleName); if (null != rule) { rules.put(ruleName, rule); } } } return Collections.unmodifiableMap(rules); }
private void updateList(long filesize) { Long prevKey = null; ArrayList<Object> al = null; if (this.indexList == null) { System.out.println("no pattern found -> nothing to do."); this.indexList = new TreeMap<Long,ArrayList<Object>>(); return; } //System.out.println("first entry = "+this.indexList.firstEntry().getKey()); if ( this.indexList.firstEntry().getKey() > 0 ) { // return first chunk al = new ArrayList<Object>(); al.add(this.indexList.firstEntry().getKey()-1); al.add("_prefix_".getBytes()); this.indexList.put(0L,al); } for (Long key : this.indexList.keySet()) { if (prevKey == null){ prevKey = key; continue; } al = this.indexList.get(prevKey); al.remove(0); al.add(0,key-prevKey); prevKey=key; } Long lastKey = (Long) this.indexList.keySet().toArray()[this.indexList.keySet().size()-1]; al = this.indexList.get(lastKey); al.remove(0); al.add(0,filesize-lastKey); //this.printIndexList(); }
public TreeMap<NumericVariable, Integer> getDegree(){ TreeMap<NumericVariable, Integer> result = new TreeMap<NumericVariable, Integer>(); for (Monomial monomial: monomials.keySet()){ TreeMap<NumericVariable, Integer> monomialDegree = monomial.getDegree(); for (NumericVariable var: monomialDegree.keySet()){ Integer currentVal = result.get(var); Integer monomialVal = monomialDegree.get(var); if (currentVal == null || currentVal.intValue() < monomialVal.intValue()) result.put(var, monomialVal); } } return result; }
private Map<String, Object> getRequestAsMap(HttpServletRequest request){ TreeMap<String, Object> map = Maps.newTreeMap(); map.put("IP", request.getRemoteAddr()); map.put("URI", request.getRequestURI()); map.put("method", request.getMethod()); map.put("queryString", request.getQueryString()); return map; }
@JsonProperty("p") public TreeMap<String, Object> getProperties() { if (properties == null) { return null; } else { TreeMap<String, Object> ans = new TreeMap<String, Object>(); for (String key : properties.getPropertyKeys()) { ans.put(key, properties.getProperty(key)); } return ans; } }
/** * Converts Headers[] to Map<String, String>. */ protected static Map<String, String> convertHeaders(Header[] headers) { Map<String, String> result = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); for (int i = 0; i < headers.length; i++) { result.put(headers[i].getName(), headers[i].getValue()); } return result; }
/** * Split string by ';' and generates a variable map for saving. * * @param saveString - save variables string * @return - a map of variables to save */ public static Map<String, String> getMapFromSaveString(String saveString){ Map<String, String> saveMap = new TreeMap<>(); Arrays.asList(saveString.split(";")).forEach( pair -> { final String[] entry = pair.split("="); saveMap.put(entry[0], entry[1]); } ); return saveMap; }
public void saveFreq(int freq, int activetransmitters, TreeMap<BlockPos, Boolean> transmittermap, Map<Integer, Integer> dimensionHash) { try { freqDimensionHashes[freq] = new ArrayList<>(dimensionHash.entrySet()); hashChanged = true; int numnodes = 0; ArrayList<BlockPos> nodes = new ArrayList<>(activetransmitters); for(Iterator<BlockPos> iterator = transmittermap.keySet().iterator(); iterator.hasNext() && numnodes < activetransmitters;) { BlockPos node = iterator.next(); if(transmittermap.get(node)) { nodes.add(node); numnodes++; } } if(numnodes == 0) { setFreqSector(freq, -1); return; } writeNodes(freq, numnodes, nodes); } catch(Exception e) { throw new RuntimeException(e); } }
@Override public Response reload() { ApplicationProperties.reload(); Properties copyToReturn = ApplicationProperties.getProperties(); configurer.setProperties(copyToReturn); filesConfiguration.reload(); LogManager.resetConfiguration(); DOMConfigurator.configure("../data/conf/log4j.xml"); copyToReturn.put("logging-reload-state", "Property reload complete"); return ResponseBuilder.ok(new TreeMap<>(copyToReturn)); }
private MultiResponse getMultiResponse() throws IOException { throwIfCancelled(); Connection connection = endpoint != null ? connectionProvider.obtainConnection(endpoint) : connectionProvider.obtainConnection(); this.connection = connection; boolean success = false; Map<Integer, Response> responseMap = new TreeMap<>(); try { // Write all requests. writeRequests(connection); // Start reading responses. final int expectedCount = requests.size(); initializeResponseMap(responseMap, expectedCount); int completedCount = 0; while (completedCount < expectedCount) { readNextBufferedResponse(connection, responseMap); completedCount++; } success = true; } finally { if (success) { connectionProvider.recycleConnection(connection); } else { closeAndClearCompletedResponses(responseMap); closeQuietly(connection); } this.connection = null; } return new MultiResponse(new ArrayList<>(responseMap.values())); }
/** * {@inheritDoc} */ @Override public SortedMap<String, ToolOutputDefinition> getToolOutputDefinitions(Object toolContentObject, int definitionType) throws ToolException { SortedMap<String, ToolOutputDefinition> definitionMap = new TreeMap<String, ToolOutputDefinition>(); Class stringArrayClass = new String[] {}.getClass(); switch (definitionType) { case ToolOutputDefinition.DATA_OUTPUT_DEFINITION_TYPE_CONDITION: if (toolContentObject != null) { ToolOutputDefinition chatMessagesDefinition = buildComplexOutputDefinition( ChatConstants.USER_MESSAGES_DEFINITION_NAME, stringArrayClass); Chat chat = (Chat) toolContentObject; // adding all existing conditions chatMessagesDefinition.setConditions(new ArrayList<BranchCondition>(chat.getConditions())); definitionMap.put(ChatConstants.USER_MESSAGES_DEFINITION_NAME, chatMessagesDefinition); } ToolOutputDefinition numberOfPostsDefinition = buildRangeDefinition( ChatConstants.LEARNER_NUM_POSTS_DEFINITION_NAME, new Long(0), null); definitionMap.put(ChatConstants.LEARNER_NUM_POSTS_DEFINITION_NAME, numberOfPostsDefinition); break; case ToolOutputDefinition.DATA_OUTPUT_DEFINITION_TYPE_DATA_FLOW: ToolOutputDefinition allUsersMessagesDefinition = buildComplexOutputDefinition( ChatConstants.ALL_USERS_MESSAGES_DEFINITION_NAME, stringArrayClass); definitionMap.put(ChatConstants.ALL_USERS_MESSAGES_DEFINITION_NAME, allUsersMessagesDefinition); break; } return definitionMap; }
@Test public void testMetricResponsesAreCached() throws Exception { // ARRANGE String now = Long.valueOf(Instant.now().toEpochMilli()).toString(); MetricResponse response = ImmutableMetricResponse.builder() .metric("argus-metric") .datapoints(new TreeMap<>(Collections.singletonMap(now, "1.2"))) .build(); // bootstrap fixtures.appConfigMocks() .runOnce(); fixtures.oneArgusToRefocusConfigurationWithCache() .realMetricResponseCache() .callRealArgusExtractProcessor() .argusClientReturns(Collections.singletonList(response)) .initializeFixtures(); // init app ConfigurationUpdateManager manager = fixtures.configurationManager(); manager.run(); fixtures.awaitUntilAllTasksHaveBeenProcessed(false); // ACT manager = fixtures.initConfigurationManager().configurationManager(); manager.run(); fixtures.awaitUntilAllTasksHaveBeenProcessed(true); // ASSERT verify(fixtures.systemStatus(), times(2)).meter("Argus", MeterType.ExtractSuccess); verify(fixtures.metricResponseCache(), times(4)).isCached("argus-metric"); verify(fixtures.metricResponseCache(), times(1)).cache(any(), anyLong()); }
@Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { activity = (NewScheduleActivity) getActivity(); ActionBar actionBar = activity.getSupportActionBar(); actionBar.setTitle("Choose a schedule"); actionBar.setDisplayHomeAsUpEnabled(true); // save inflater this.inflater = inflater; // organize schedules by how many minutes they take schedules = new TreeMap<>(); for (ScheduleType scheduleType : ScheduleData.scheduleList) { if (!schedules.containsKey(scheduleType.getMinutesDay())) { schedules.put(scheduleType.getMinutesDay(), new ArrayList<>()); } schedules.get(scheduleType.getMinutesDay()).add(scheduleType); } // load view View view = inflater.inflate(R.layout.fragment_new_schedule_schedule, container, false); circleContainer = view.findViewById(R.id.circleContainer); loadMinuteCircles(); return view; }
public CsvFile(File file) throws IOException { this.file = file; srgMemberName2CsvData = new TreeMap<String, CsvData>(); readFromFile(); isDirty = false; }
/** * Convert transaction to map * * @param transaction * transaction * @return Map */ public static Map<String, Object> convert(Transaction transaction) { Map<String, Object> map = new TreeMap<>(); if (transaction.getSignature() != null) { map.put(Constants.SIGNATURE, Format.convert(transaction.getSignature())); } map.put(Constants.TYPE, transaction.getType()); map.put(Constants.TIMESTAMP, transaction.getTimestamp()); map.put(Constants.DEADLINE, transaction.getDeadline()); map.put(Constants.FEE, transaction.getFee()); map.put(Constants.VERSION, transaction.getVersion()); if (transaction.getReference() != 0) { map.put(Constants.REFERENCED_TRANSACTION, Format.ID.transactionId(transaction.getReference())); } map.put(Constants.SENDER, Format.ID.accountId(transaction.getSenderID())); if (transaction.getData() != null) { map.put(Constants.ATTACHMENT, transaction.getData()); } else { map.put(Constants.ATTACHMENT, new HashMap<>()); } if (transaction.getConfirmations() != null && !transaction.getConfirmations().isEmpty()) { map.put(Constants.CONFIRMATIONS, transaction.getConfirmations()); } return map; }
public WxSign(String appId,String jsTicket,String url){ String timestamp = String.valueOf(System.currentTimeMillis()/1000); String nonceStr = SecurityUtil.getRandomString(8); SortedMap<String,String> map = new TreeMap<String, String>(); map.put("jsapi_ticket", jsTicket); map.put("noncestr", nonceStr); map.put("timestamp", timestamp); map.put("url", url); this.appId = appId; this.nonceStr = nonceStr; this.timestamp = timestamp; this.signature = SignUtil.signature(map); }
private boolean dependsOnTransitively(String kit1, String kit2, TreeMap<String, TreeSet<String>> dependingKits) { TreeSet<String> kits = dependingKits.get(kit1); if (kits == null) { return false; } return kits.contains(kit2); }
public static Map<String, TreeMap<String, Boolean>> listWhitelisted(int uid, String type) { checkCaller(); Map<String, TreeMap<String, Boolean>> mapWhitelisted = new HashMap<String, TreeMap<String, Boolean>>(); for (PSetting setting : getSettingList(uid, type)) if (Meta.isWhitelist(setting.type)) { if (!mapWhitelisted.containsKey(setting.type)) mapWhitelisted.put(setting.type, new TreeMap<String, Boolean>()); mapWhitelisted.get(setting.type).put(setting.name, Boolean.parseBoolean(setting.value)); } return mapWhitelisted; }