List of usage examples for java.util TreeMap put
public V put(K key, V value)
From source file:net.rim.ejde.internal.util.ComponentPackUtils.java
/** * Gets the component pack paths based on the CP extension point * * @return the component pack paths//from w w w . j av a 2 s . c o m */ public static Map<String, JDEInfo> getComponentPackPaths() { ComponentPackUtils.log.debug("Starting Search for CPs"); //$NON-NLS-1$ IExtension[] extensions; final IExtensionRegistry registry = RegistryFactory.getRegistry(); final IExtensionPoint point = registry.getExtensionPoint(IConstants.CP_EXTENSION_POINT_ID); final TreeMap<String, JDEInfo> packs = new TreeMap<String, JDEInfo>(new ComponentPackComparator()); if ((null == point) || !point.isValid()) { ComponentPackUtils.log.debug("Extention Point Null or Invalid"); //$NON-NLS-1$ return packs; } extensions = point.getExtensions(); if ((null == extensions) || (0 == extensions.length)) { ComponentPackUtils.log.debug("Extentions Null or Non-Existant"); //$NON-NLS-1$ return packs; } Bundle bundle; URL url; String name, version, path; File file; for (final IExtension extension : extensions) { try { bundle = Platform.getBundle(extension.getNamespaceIdentifier()); final int bundleState = bundle.getState(); if ((bundleState != Bundle.UNINSTALLED) && (bundleState != Bundle.STOPPING)) { url = FileLocator.resolve(FileLocator.find(bundle, Path.ROOT, null)); name = bundle.getHeaders().get(Constants.BUNDLE_NAME); version = bundle.getHeaders().get(Constants.BUNDLE_VERSION); if (StringUtils.isBlank(name) || StringUtils.isBlank(version)) { break; } file = new File(url.getFile()); if (!file.exists()) { break; } path = file.getAbsolutePath() + ComponentPackUtils.SUFFIX; ComponentPackUtils.log.debug("CP named " + name + " was found at " + path); //$NON-NLS-1$ //$NON-NLS-2$ packs.put(name, new JDEInfo(name, path, version)); } } catch (final Throwable e) { ComponentPackUtils.log.error(e.getMessage(), e); } } return packs; }
From source file:com.adobe.cq.dialogconversion.datasources.DialogsDataSource.java
private void setDataSource(Resource resource, String path, ResourceResolver resourceResolver, SlingHttpServletRequest request, String itemResourceType) throws RepositoryException { List<Resource> resources = new ArrayList<Resource>(); if (StringUtils.isNotEmpty(path)) { Session session = request.getResourceResolver().adaptTo(Session.class); TreeMap<String, Node> nodeMap = new TreeMap<String, Node>(); // sanitize path path = path.trim();// www . j ava2s . c o m if (!path.startsWith("/")) { path = "/" + path; } // First check if the supplied path is a dialog node itself if (session.nodeExists(path)) { Node node = session.getNode(path); DialogType type = DialogRewriteUtils.getDialogType(node); if (type != DialogType.UNKNOWN && type != DialogType.CORAL_3) { nodeMap.put(node.getPath(), node); } } // If the path does not point to a dialog node: we query for dialog nodes if (nodeMap.isEmpty()) { String encodedPath = "/".equals(path) ? "" : ISO9075.encodePath(path); if (encodedPath.length() > 1 && encodedPath.endsWith("/")) { encodedPath = encodedPath.substring(0, encodedPath.length() - 1); } String classicStatement = "SELECT * FROM [" + NT_DIALOG + "] AS s WHERE ISDESCENDANTNODE(s, '" + encodedPath + "') " + "AND NAME() IN ('" + NameConstants.NN_DIALOG + "', '" + NameConstants.NN_DESIGN_DIALOG + "')"; String coral2Statement = "SELECT parent.* FROM [nt:unstructured] AS parent INNER JOIN [nt:unstructured] " + "AS child on ISCHILDNODE(child, parent) WHERE ISDESCENDANTNODE(parent, '" + encodedPath + "') " + "AND NAME(parent) IN ('" + NN_CQ_DIALOG + "', '" + NN_CQ_DIALOG + CORAL_2_BACKUP_SUFFIX + "', '" + NN_CQ_DESIGN_DIALOG + "', '" + NN_CQ_DESIGN_DIALOG + CORAL_2_BACKUP_SUFFIX + "') " + "AND NAME(child) = 'content' AND child.[sling:resourceType] NOT LIKE '" + DIALOG_CONTENT_RESOURCETYPE_PREFIX_CORAL3 + "%'"; QueryManager queryManager = session.getWorkspace().getQueryManager(); List<Query> queries = new ArrayList<Query>(); queries.add(queryManager.createQuery(classicStatement, Query.JCR_SQL2)); queries.add(queryManager.createQuery(coral2Statement, Query.JCR_SQL2)); for (Query query : queries) { NodeIterator iterator = query.execute().getNodes(); while (iterator.hasNext()) { Node node = iterator.nextNode(); Node parent = node.getParent(); if (parent != null) { // put design dialogs at a relative key String key = (DialogRewriteUtils.isDesignDialog(node)) ? parent.getPath() + "/" + NameConstants.NN_DESIGN_DIALOG : parent.getPath(); // backup Coral 2 dialogs shouldn't override none backup ones if (node.getName().endsWith(CORAL_2_BACKUP_SUFFIX) && nodeMap.get(key) != null) { continue; } nodeMap.put(key, node); } } } } int index = 0; Iterator iterator = nodeMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); Node dialog = (Node) entry.getValue(); if (dialog == null) { continue; } Node parent = dialog.getParent(); if (parent == null) { continue; } DialogType dialogType = DialogRewriteUtils.getDialogType(dialog); String dialogPath = dialog.getPath(); String type = dialogType.getString(); String href = externalizer.relativeLink(request, dialogPath) + ".html"; String crxHref = externalizer.relativeLink(request, CRX_LITE_PATH) + ".jsp#" + dialogPath; boolean isDesignDialog = DialogRewriteUtils.isDesignDialog(dialog); // only allow Coral 2 backup dialogs in the result if there's a replacement if (dialogType == DialogType.CORAL_2 && dialog.getName().endsWith(CORAL_2_BACKUP_SUFFIX)) { if ((!isDesignDialog && !parent.hasNode(NN_CQ_DIALOG)) || (isDesignDialog && !parent.hasNode(NN_CQ_DESIGN_DIALOG))) { continue; } } boolean converted = false; if (dialogType == DialogType.CLASSIC) { converted = isDesignDialog ? parent.hasNode(NN_CQ_DESIGN_DIALOG) : parent.hasNode(NN_CQ_DIALOG); } else if (dialogType == DialogType.CORAL_2) { converted = dialog.getName().endsWith(CORAL_2_BACKUP_SUFFIX); } Map<String, Object> map = new HashMap<String, Object>(); map.put("dialogPath", dialogPath); map.put("type", type); map.put("href", href); map.put("converted", converted); map.put("crxHref", crxHref); if (converted) { Node convertedNode = (isDesignDialog) ? parent.getNode(NN_CQ_DESIGN_DIALOG) : parent.getNode(NN_CQ_DIALOG); String touchHref = externalizer.relativeLink(request, convertedNode.getPath()) + ".html"; String touchCrxHref = externalizer.relativeLink(request, CRX_LITE_PATH) + ".jsp#" + convertedNode.getPath().replaceAll(":", "%3A"); map.put("touchHref", touchHref); map.put("touchCrxHref", touchCrxHref); } resources.add(new ValueMapResource(resourceResolver, resource.getPath() + "/dialog_" + index, itemResourceType, new ValueMapDecorator(map))); index++; } } DataSource ds = new SimpleDataSource(resources.iterator()); request.setAttribute(DataSource.class.getName(), ds); }
From source file:gtu._work.ui.RegexReplacer.java
/** * @param fromPattern/*from w w w . j a v a2 s. c om*/ * ???pattern * @param toFormat * ??pattern * @param replaceText * ?? */ String replacer(String fromPattern, String toFormat, String replaceText) { String errorRtn = replaceText.toString(); try { int patternFlag = 0; // if (multiLineCheckBox.isSelected()) { patternFlag = Pattern.DOTALL | Pattern.MULTILINE; } Pattern pattern = Pattern.compile(fromPattern, patternFlag); Matcher matcher = pattern.matcher(replaceText); StringBuffer sb = new StringBuffer(); String tempStr = null; TradeOffConfig config = this.getTradeOffConfig(); { int startPos = 0; for (; matcher.find();) { tempStr = toFormat.toString(); sb.append(replaceText.substring(startPos, matcher.start())); // ---------------------------------------------- if (StringUtils.isBlank(config.fremarkerKey)) { // regex for (int ii = 0; ii <= matcher.groupCount(); ii++) { System.out.println(ii + " -- " + matcher.group(ii)); tempStr = tempStr.replaceAll("#" + ii + "#", Matcher.quoteReplacement(matcher.group(ii))); } } else if (StringUtils.isNotBlank(config.fremarkerKey)) { // freemarker Map<String, Object> root = new HashMap<String, Object>(); TreeMap<Integer, Object> lstMap = new TreeMap<Integer, Object>(); for (int ii = 0; ii <= matcher.groupCount(); ii++) { lstMap.put(ii, matcher.group(ii)); } root.put(StringUtils.trimToEmpty(config.fremarkerKey), lstMap.values()); System.out.println("template Map : " + root); tempStr = FreeMarkerSimpleUtil.replace(tempStr, root); } // ---------------------------------------------- sb.append(tempStr); startPos = matcher.end(); } sb.append(replaceText.substring(startPos)); } return sb.toString(); } catch (Exception ex) { JOptionPaneUtil.newInstance().iconErrorMessage().showMessageDialog(ex.getMessage(), getTitle()); return errorRtn; } }
From source file:com.yanbang.portal.controller.PortalController.java
/** * ??/* www . j a v a2 s. co m*/ * * @param request * @param response * @return * @throws Exception */ @SuppressWarnings("rawtypes") @RequestMapping(params = "action=portalLeft") public ModelAndView portalBottom(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); SysUser user = (SysUser) this.getLoginUser(request); Collection<SysRole> rolelist = portalBiz.findRolesByUserCode(user.getUserCode()); String soft_licence = portalBiz.getLicences(); UserCompareBiz usercom = UserCompareBiz.getInstance(); usercom.setAddress(portalBiz.getServerAddr()); if (usercom.validaeAddress() || ValidateLicense.isLicenceNoExpired(soft_licence)) { rolelist = portalBiz.findRolesByUserCode(user.getUserCode()); } else { if (ValidateLicense.isLicenceDateExpired(soft_licence)) { rolelist = new ArrayList<SysRole>(); } else { rolelist = portalBiz.findRolesByUserCode(user.getUserCode()); } } // ?? HashMap<Long, SysMenu> totalMenuList = new HashMap<Long, SysMenu>(); // ?? TreeMap<Long, SysMenu> firstMenuMap = new TreeMap<Long, SysMenu>(); // ?? for (SysRole role : rolelist) { Collection<SysMenu> menulist = portalBiz.findMenusByListId(role.getRoleMenus()); for (SysMenu menu : menulist) { totalMenuList.put(menu.getMenuId(), menu); if (menu.getMenuGrade() == 1) { firstMenuMap.put(menu.getMenuOrder(), menu); } } } // =========================================== String strTotalMenusIds = "-1"; Iterator iterTotal = totalMenuList.entrySet().iterator(); while (iterTotal.hasNext()) { Map.Entry entry = (Map.Entry) iterTotal.next(); SysMenu menu = (SysMenu) entry.getValue(); strTotalMenusIds = strTotalMenusIds + "," + menu.getMenuId(); } // ============================================ Iterator iter = firstMenuMap.entrySet().iterator(); ArrayList<SysMenu> menulist = new ArrayList<SysMenu>(); // ??? while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); SysMenu menu1 = (SysMenu) entry.getValue(); MenuModel menuModel1 = new MenuModel(); menuModel1.setMenuId(menu1.getMenuId()); menuModel1.setMenuName(menu1.getMenuName()); menuModel1.setMenuURL(menu1.getMenuURL()); menuModel1.setMenuParentId(menu1.getMenuParentId()); menuModel1.setMenuGrade(menu1.getMenuGrade()); menuModel1.setMenuTarget(menu1.getMenuTarget()); // ---------------------------------------------------------- // ??? Collection<SysMenu> menu2list = portalBiz.findAllChildMenus(menu1.getMenuId(), strTotalMenusIds); if (menu2list != null) { ArrayList<MenuModel> menu2RetList = new ArrayList<MenuModel>(); for (SysMenu menu2 : menu2list) { MenuModel menuModel2 = new MenuModel(); menuModel2.setMenuId(menu2.getMenuId()); menuModel2.setMenuName(menu2.getMenuName()); menuModel2.setMenuURL(menu2.getMenuURL()); menuModel2.setMenuParentId(menu2.getMenuParentId()); menuModel2.setMenuGrade(menu2.getMenuGrade()); menuModel2.setMenuTarget(menu2.getMenuTarget()); // ??? Collection<SysMenu> menu3list = portalBiz.findAllChildMenus(menu2.getMenuId(), strTotalMenusIds); if (menu3list != null) { ArrayList<MenuModel> menu3RetList = new ArrayList<MenuModel>(); for (SysMenu menu3 : menu3list) { MenuModel menuModel3 = new MenuModel(); menuModel3.setMenuId(menu3.getMenuId()); menuModel3.setMenuName(menu3.getMenuName()); menuModel3.setMenuURL(menu3.getMenuURL()); menuModel3.setMenuParentId(menu3.getMenuParentId()); menuModel3.setMenuGrade(menu3.getMenuGrade()); menuModel3.setMenuTarget(menu3.getMenuTarget()); menu3RetList.add(menuModel3); } menuModel2.setChildMenuList(menu3RetList); } menu2RetList.add(menuModel2); } menuModel1.setChildMenuList(menu2RetList); } // ---------------------------------------------------------- menulist.add(menuModel1); } map.put("menulist", menulist); return new ModelAndView("portal/portalLeft", map); }
From source file:org.powertac.householdcustomer.HouseholdCustomerServiceTests.java
@Before public void setUp() { customerRepo.recycle();// www . j a va2s. c o m brokerRepo.recycle(); tariffRepo.recycle(); tariffSubscriptionRepo.recycle(); randomSeedRepo.recycle(); timeslotRepo.recycle(); weatherReportRepo.recycle(); weatherReportRepo.runOnce(); householdCustomerService.clearConfiguration(); reset(mockAccounting); reset(mockServerProperties); // create a Competition, needed for initialization comp = Competition.newInstance("household-customer-test"); broker1 = new Broker("Joe"); // now = new DateTime(2009, 10, 10, 0, 0, 0, 0, // DateTimeZone.UTC).toInstant(); now = comp.getSimulationBaseTime(); timeService.setCurrentTime(now); timeService.setBase(now.getMillis()); exp = now.plus(TimeService.WEEK * 10); defaultTariffSpec = new TariffSpecification(broker1, PowerType.CONSUMPTION).withExpiration(exp) .addRate(new Rate().withValue(-0.5)); defaultTariff = new Tariff(defaultTariffSpec); defaultTariff.init(); defaultTariff.setState(Tariff.State.OFFERED); tariffRepo.setDefaultTariff(defaultTariffSpec); when(mockTariffMarket.getDefaultTariff(PowerType.CONSUMPTION)).thenReturn(defaultTariff); when(mockTariffMarket.getDefaultTariff(PowerType.INTERRUPTIBLE_CONSUMPTION)).thenReturn(defaultTariff); accountingArgs = new ArrayList<Object[]>(); // mock the AccountingService, capture args doAnswer(new Answer() { public Object answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); accountingArgs.add(args); return null; } }).when(mockAccounting).addTariffTransaction(isA(TariffTransaction.Type.class), isA(Tariff.class), isA(CustomerInfo.class), anyInt(), anyDouble(), anyDouble()); // Set up serverProperties mock ReflectionTestUtils.setField(householdCustomerService, "serverPropertiesService", mockServerProperties); config = new Configurator(); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); config.configureSingleton(args[0]); return null; } }).when(mockServerProperties).configureMe(anyObject()); TreeMap<String, String> map = new TreeMap<String, String>(); map.put("householdcustomer.householdCustomerService.configFile1", "VillageType1.properties"); map.put("common.competition.expectedTimeslotCount", "1440"); Configuration mapConfig = new MapConfiguration(map); config.setConfiguration(mapConfig); config.configureSingleton(comp); }
From source file:com.nubits.nubot.trading.wrappers.PeatioWrapper.java
@Override public ApiResponse clearOrders(CurrencyPair pair) { ApiResponse apiResponse = new ApiResponse(); String method = API_CLEAR_ORDERS; String url = apiBaseUrl;//from ww w . j ava2s . com boolean isGet = false; TreeMap<String, String> query_args = new TreeMap<>(); query_args.put("canonical_verb", "POST"); query_args.put("canonical_uri", method); ApiResponse response = getQuery(url, method, query_args, true, isGet); if (response.isPositive()) { apiResponse.setResponseObject(true); } else { apiResponse = response; } return apiResponse; }
From source file:com.clust4j.algo.KMeans.java
/** * Reorder the labels in order of appearance using the * {@link LabelEncoder}. Also reorder the centroids to correspond * with new label order/* w w w .j av a2 s.c o m*/ */ @Override protected void reorderLabelsAndCentroids() { boolean wss_null = null == wss; /* * reorder labels... */ final LabelEncoder encoder = new LabelEncoder(labels).fit(); labels = encoder.getEncodedLabels(); // also reorder centroids... takes O(2K) passes TreeMap<Integer, double[]> tmpCentroids = new TreeMap<>(); double[] new_wss = new double[k]; /* * We have to be delicate about this--KMedoids stores * labels as indices pointing to which record is the medoid, * whereas KMeans uses 0 thru K. Thus we can simply index in * KMeans, but will get an IndexOOB exception in Kmedoids, so * we need to come up with a universal solution which might * look ugly at a glance, but is robust to both. */ int encoded; for (int i = 0; i < k; i++) { encoded = encoder.reverseEncodeOrNull(i); tmpCentroids.put(i, centroids.get(encoded)); new_wss[i] = wss_null ? Double.NaN : wss[encoded]; } for (int i = 0; i < k; i++) centroids.set(i, tmpCentroids.get(i)); // reset wss this.wss = new_wss; }
From source file:com.rapidminer.gui.plotter.charts.DistributionPlotter.java
private CategoryDataset createNominalDataSet() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); for (Integer classIndex : model.getClassIndices()) { DiscreteDistribution distribution = (DiscreteDistribution) model.getDistribution(classIndex, translateToModelColumn(plotColumn)); String labelName = model.getClassName(classIndex); // sort values by name TreeMap<String, Double> valueMap = new TreeMap<String, Double>(); for (Double value : distribution.getValues()) { String valueName;/*from w ww . j ava 2 s.co m*/ if (Double.isNaN(value)) { valueName = "Unknown"; } else { valueName = distribution.mapValue(value); } valueMap.put(valueName, value); } for (Entry<String, Double> entry : valueMap.entrySet()) { dataset.addValue(distribution.getProbability(entry.getValue()), labelName, entry.getKey()); } } return dataset; }
From source file:com.sfs.whichdoctor.dao.BulkContactDAOImpl.java
/** * Prepare the bulk contact bean./*w w w . ja v a 2 s.c o m*/ * * @param contactBean the bulk contact bean * @param exportMap the export map * @param user the user * @return the bulk contact bean */ public final BulkContactBean prepare(final BulkContactBean contactBean, final TreeMap<String, ItemBean> exportMap, final UserBean user) { TreeMap<Integer, Integer> exportGUIDs = new TreeMap<Integer, Integer>(); Collection<Object> guids = new ArrayList<Object>(); /** Get a list of the unique GUIDs **/ for (String key : exportMap.keySet()) { try { ItemBean details = (ItemBean) exportMap.get(key); exportGUIDs.put(details.getObject1GUID(), details.getObject1GUID()); } catch (Exception e) { dataLogger.error("Error casting object to export map: " + e.getMessage()); } } for (Integer guid : exportGUIDs.keySet()) { guids.add(guid); } BulkContactBean bulkContact = performSearch(contactBean, guids, user, true); return bulkContact; }