List of usage examples for java.util TreeMap containsKey
public boolean containsKey(Object key)
From source file:org.lockss.servlet.DisplayContentStatus.java
/** * Handle a request/* ww w .j av a 2 s . c o m*/ * * @throws IOException */ public void lockssHandleRequest() throws IOException { if (!StringUtil.isNullString(req.getParameter("isDaemonReady"))) { if (pluginMgr.areAusStarted()) { resp.setStatus(200); PrintWriter wrtr = resp.getWriter(); resp.setContentType("text/plain"); wrtr.println("true"); } else { PrintWriter wrtr = resp.getWriter(); resp.setContentType("text/plain"); wrtr.println("false"); resp.sendError(202, "Not ready"); } return; } action = req.getParameter(ACTION_TAG); auName = req.getParameter(AU_TO_REMOVE); if ("Delete selected".equals(req.getParameter("submit"))) { String[] deleteAUs = req.getParameterValues("deleteAu"); if (deleteAUs != null) { log.error("AUs: " + Arrays.asList(deleteAUs)); doRemoveAus(Arrays.asList(deleteAUs)); } else { log.error("No AUs selected"); deleteMessage = "No AUs selected!"; } } String publisher = req.getParameter("deletePublisher"); if (!StringUtil.isNullString(publisher)) { TreeMap<String, TreeMap<String, TreeSet<ArchivalUnit>>> auMap = DisplayContentTab .getAusByPublisherName(); ArrayList<String> auIds = new ArrayList<String>(); if (auMap.containsKey(publisher)) { Iterator it = auMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); String publisherString = pairs.getKey().toString(); log.error("Publisher: " + publisher); log.error("Publisher string: " + publisherString); if (publisher.equals(publisherString)) { TreeMap<String, TreeSet<ArchivalUnit>> titleMap = (TreeMap<String, TreeSet<ArchivalUnit>>) pairs .getValue(); Iterator titleIterator = titleMap.entrySet().iterator(); while (titleIterator.hasNext()) { Map.Entry titlePairs = (Map.Entry) titleIterator.next(); TreeSet<ArchivalUnit> auSet = (TreeSet<ArchivalUnit>) titlePairs.getValue(); for (ArchivalUnit au : auSet) { auIds.add(au.getAuId()); } } } } doRemoveAus(auIds); } } if (action != null && auName != null) { String auString = URLDecoder.decode(auName, "UTF-8"); java.util.List<String> auList = new ArrayList<String>(); auList.add(auString); doRemoveAus(auList); } if (StringUtil.isNullString(action)) { try { getMultiPartRequest(); if (multiReq != null) { action = multiReq.getString(ACTION_TAG); } } catch (FormDataTooLongException e) { errMsg = "Uploaded file too large: " + e.getMessage(); // leave action null, will call displayAuSummary() below } } outputFmt = OUTPUT_HTML; // default output is html String outputParam = req.getParameter("output"); if (!StringUtil.isNullString(outputParam)) { if ("html".equalsIgnoreCase(outputParam)) { outputFmt = OUTPUT_HTML; } else if ("xml".equalsIgnoreCase(outputParam)) { outputFmt = OUTPUT_XML; } else if ("text".equalsIgnoreCase(outputParam)) { outputFmt = OUTPUT_TEXT; } else if ("csv".equalsIgnoreCase(outputParam)) { outputFmt = OUTPUT_CSV; } else { log.warning("Unknown output format: " + outputParam); } } String optionsParam = req.getParameter("options"); tableOptions = new BitSet(); if (isDebugUser()) { log.debug2("Debug user. Setting OPTION_DEBUG_USER"); tableOptions.set(StatusTable.OPTION_DEBUG_USER); } for (Iterator iter = StringUtil.breakAt(optionsParam, ',').iterator(); iter.hasNext();) { String s = (String) iter.next(); if ("norows".equalsIgnoreCase(s)) { tableOptions.set(StatusTable.OPTION_NO_ROWS); } } tableName = req.getParameter("table"); tableKey = req.getParameter("key"); if (StringUtil.isNullString(tableName)) { tableName = "AuOverview"; } if (StringUtil.isNullString(tableKey)) { tableKey = null; } sortKey = req.getParameter("sort"); if (StringUtil.isNullString(sortKey)) { sortKey = null; } groupKey = req.getParameter("group"); if (StringUtil.isNullString(groupKey)) { groupKey = "publisher"; } typeKey = req.getParameter("type"); filterKey = req.getParameter("filterKey"); tabKey = req.getParameter("tab"); timeKey = req.getParameter("timeKey"); switch (outputFmt) { case OUTPUT_HTML: doHtmlStatusTable(); break; case OUTPUT_XML: try { doXmlStatusTable(); } catch (Exception e) { throw new IOException("Error building XML", e); } break; case OUTPUT_TEXT: doTextStatusTable(); break; case OUTPUT_CSV: doCsvStatusTable(); break; } }
From source file:com.stgmastek.core.logic.ExecutionOrder.java
/** * Static method to setup the execution order. * This method essentially looks up in to the setup table BATCH_COLUMN_MAP to * get the details.Using the details it would setup the execution order for the batch * Once the execution order is set, it sets the order into the {@link BatchInfo#setOrderedMap(TreeMap)} * for all other objects to derive knowledge from. * Note: The batch could be run for - /*from w w w.ja v a2 s.com*/ * <OL> * <LI> For a date i.e. all entities and all values for those entities. * <LI> For an entity i.e. batch for only policy records and all its values * i.e. P1, P2 ... Pn * <LI> For a single object identified as GENERAL type of job with a * sequence number i.e. JOB_SCHEDULE.job_seq * <LI> For only Meta events like ALL PRE and ALL POST * <LI> For any combination of above, a few given - * <UL> * <LI> Policy P1 and ALL PRE * <LI> ALL Agency records and Policy P1 * <LI> Policy P1 and Agency A1 * </UL> * </OL> * * Every step has inline comments associated with it. * * @param batchContext * The context for the batch * @return true * If the setup is done successfully * @throws BatchException * Any database I/O exception */ public synchronized static Boolean setExecutionOrder(BatchContext batchContext) throws BatchException { //Get request parameters HashMap<String, Object> params = batchContext.getRequestParams().getProcessRequestParams(); //Check whether it is a date batch run or specific batch run if (params.size() < 1) { batchContext.getBatchInfo().setDateRun(true); } Connection con = batchContext.getBATCHConnection(); IBatchDao bDao = DaoFactory.getBatchDao(); try { //Query the setup table to get the setup values LookupTable lookupTable = bDao.getLookupTable(con); Map<String, String> orderByLookupTable = bDao.getOrderByLookupTable(con); TreeMap<Integer, EntityParams> orderedMap = new TreeMap<Integer, EntityParams>(); //If it is date batch run, then for all entities, populate "ALL" if (batchContext.getBatchInfo().isDateRun()) { Iterator<String> lTableIter = lookupTable.keySet().iterator(); while (lTableIter.hasNext()) { String entity = lTableIter.next(); params.put(entity + "_1", "ALL"); } } //Iterate over each parameters set for (Entry<String, Object> entry : params.entrySet()) { String paramName = entry.getKey(); Object paramValue = entry.getValue(); if (logger.isDebugEnabled()) { logger.debug("In ExecutionOrder >>>> paramName ==>" + paramName); } String entity = null; //Strip the last occurrence of _ and get the entity name entity = paramName.substring(0, paramName.lastIndexOf("_")); if (logger.isDebugEnabled()) { logger.debug("In ExecutionOrder >>>> Entity ==>" + entity); } //Validate whether the entity is setup appropriately in //the BATCH_COLUMN_MAP table if (!lookupTable.containsKey(entity)) { //If the entity is not set, raise an exception and exit throw new BatchException("The entity " + entity + " is not set up in the COLUMN_MAP table."); } else { //Get the lookup record //Once found, get the details and set it against the entity List<ColumnLookup> lookupColumns = lookupTable.get(entity); Integer order = lookupColumns.get(0).getPrecedenceOrder(); if (!orderedMap.containsKey(order)) { EntityParams entityParams = new EntityParams(entity); orderedMap.put(order, entityParams); } EntityParams entityParams = orderedMap.get(order); entityParams.setLookupColumns(lookupColumns); entityParams.setOrderByMap(orderByLookupTable);//Added on 01-OCT-2013 - Mandar //Check 'ALL' or for specific entity values. //Note: Batch could be run for a date i.e. all entities (and all values) // or for any combination of entity and values if (!paramValue.equals("ALL")) { List<GroupInfo> list = entityParams.getValues(); //check if all exists. If exists do not write the new value if (list.size() == 0 || !list.get(0).getEntityValue().equals("ALL")) entityParams.getValues().add(new GroupInfo((String) paramValue)); } else { entityParams.setAll(new GroupInfo((String) paramValue)); } } } batchContext.getBatchInfo().setOrderedMap(orderedMap); } finally { bDao.releaseResources(null, null, con); } return true; }
From source file:ANNFileDetect.EncogTestClass.java
public MLData runNet(String fileToExamine, BasicNetwork nn, boolean wantGraph, int graphMinima) throws IOException { double[] output = new double[] { 0.0 }; System.out.println("File: " + fileToExamine); TreeMap<Double, Integer> ht = new TreeMap<Double, Integer>(); FileOperations fo = new FileOperations(); int inputNeurons = nn.getInputCount(); int outputNeurons = nn.getOutputCount(); byte[] file = fo.fileToByte(fileToExamine); filebytes = file.length;/*from www . j a v a 2 s . c om*/ double[][] fileMatrix = fo.DoubleMatrix(file, inputNeurons, 0); double[][] Output = new double[fileMatrix.length][]; for (int i = 0; i < fileMatrix.length; i++) { Output[i] = output; } MLDataSet trainingSet = new BasicMLDataSet(fileMatrix, Output); MLData out = null; double[] average = new double[outputNeurons]; for (MLDataPair pair : trainingSet) { out = nn.compute(pair.getInput()); //System.out.println("Output Computed for file: " + fileToExamine + ": "); for (int a = 0; a < outputNeurons; a++) { average[a] = (average[a] + out.getData(a)) / 2; Double tst = hashDbl(out.getData(a)); if (ht.containsKey(tst)) { ht.put(tst, (ht.get(tst) + 1)); } else { ht.put(tst, 1); } } } if (wantGraph) { drawchart(ht, fileToExamine, graphMinima); } else { createReport(ht, fileToExamine); } for (int i = 0; i < average.length; i++) { System.out.println("Neuron" + i + ": " + average[i]); } return out; }
From source file:org.catrobat.jira.adminhelper.rest.UserRest.java
private Response searchUser(String query, HttpServletRequest request) { Response unauthorized = checkPermission(request); if (unauthorized != null) { return unauthorized; }/*from w w w . j a v a 2 s . c om*/ if (lendingService == null) { return Response.serverError().entity("Lending Service must not be null").build(); } if (query == null || query.length() < 1) { return Response.ok(new ArrayList<JsonUser>()).build(); } query = StringEscapeUtils.escapeHtml4(query); com.atlassian.jira.user.util.UserManager jiraUserManager = ComponentAccessor.getUserManager(); TreeMap<String, JsonUser> jsonUsers = new TreeMap<String, JsonUser>(); for (ApplicationUser user : jiraUserManager.getAllUsers()) { if (user.getName().toLowerCase().contains(query.toLowerCase()) || user.getDisplayName().toLowerCase().contains(query.toLowerCase())) { JsonUser jsonUser = new JsonUser(); jsonUser.setUserName(user.getKey()); jsonUser.setDisplayName(user.getDisplayName()); jsonUsers.put(user.getName().toLowerCase(), jsonUser); } } for (Lending lending : lendingService.all()) { if (lending.getLendingByUserKey().toLowerCase().contains(query.toLowerCase()) && !jsonUsers.containsKey(lending.getLendingByUserKey().toLowerCase())) { JsonUser jsonUser = new JsonUser(); jsonUser.setUserName(lending.getLendingByUserKey()); jsonUser.setDisplayName(lending.getLendingByUserKey()); String userKey = jsonUser.getUserName().toLowerCase().replaceAll(" ", "").replaceAll("ä", "ae") .replaceAll("ö", "oe").replaceAll("ü", "ue").replaceAll("ß", "ss"); jsonUsers.put(userKey, jsonUser); } } return Response.ok(jsonUsers.values()).build(); }
From source file:org.apache.nutch.crawl.CrawlDbReader.java
public void processStatJob(String crawlDb, Configuration config, boolean sort) throws IOException, InterruptedException, ClassNotFoundException { double quantiles[] = { .01, .05, .1, .2, .25, .3, .4, .5, .6, .7, .75, .8, .9, .95, .99 }; if (config.get("db.stats.score.quantiles") != null) { List<Double> qs = new ArrayList<>(); for (String s : config.getStrings("db.stats.score.quantiles")) { try { double d = Double.parseDouble(s); if (d >= 0.0 && d <= 1.0) { qs.add(d);/* ww w . j a v a 2 s. com*/ } else { LOG.warn("Skipping quantile {} not in range in db.stats.score.quantiles: {}", s); } } catch (NumberFormatException e) { LOG.warn("Skipping bad floating point number {} in db.stats.score.quantiles: {}", s, e.getMessage()); } quantiles = new double[qs.size()]; int i = 0; for (Double q : qs) { quantiles[i++] = q; } Arrays.sort(quantiles); } } if (LOG.isInfoEnabled()) { LOG.info("CrawlDb statistics start: " + crawlDb); } TreeMap<String, Writable> stats = processStatJobHelper(crawlDb, config, sort); if (LOG.isInfoEnabled()) { LOG.info("Statistics for CrawlDb: " + crawlDb); LongWritable totalCnt = new LongWritable(0); if (stats.containsKey("T")) { totalCnt = ((LongWritable) stats.get("T")); stats.remove("T"); } LOG.info("TOTAL urls:\t" + totalCnt.get()); for (Map.Entry<String, Writable> entry : stats.entrySet()) { String k = entry.getKey(); long value = 0; double fvalue = 0.0; byte[] bytesValue = null; Writable val = entry.getValue(); if (val instanceof LongWritable) { value = ((LongWritable) val).get(); } else if (val instanceof FloatWritable) { fvalue = ((FloatWritable) val).get(); } else if (val instanceof BytesWritable) { bytesValue = ((BytesWritable) val).getBytes(); } if (k.equals("scn")) { LOG.info("min score:\t" + fvalue); } else if (k.equals("scx")) { LOG.info("max score:\t" + fvalue); } else if (k.equals("sct")) { LOG.info("avg score:\t" + (fvalue / totalCnt.get())); } else if (k.equals("scNaN")) { LOG.info("score == NaN:\t" + value); } else if (k.equals("ftn")) { LOG.info("earliest fetch time:\t" + new Date(1000 * 60 * value)); } else if (k.equals("ftx")) { LOG.info("latest fetch time:\t" + new Date(1000 * 60 * value)); } else if (k.equals("ftt")) { LOG.info("avg of fetch times:\t" + new Date(1000 * 60 * (value / totalCnt.get()))); } else if (k.equals("fin")) { LOG.info("shortest fetch interval:\t{}", TimingUtil.secondsToDaysHMS(value)); } else if (k.equals("fix")) { LOG.info("longest fetch interval:\t{}", TimingUtil.secondsToDaysHMS(value)); } else if (k.equals("fit")) { LOG.info("avg fetch interval:\t{}", TimingUtil.secondsToDaysHMS(value / totalCnt.get())); } else if (k.startsWith("status")) { String[] st = k.split(" "); int code = Integer.parseInt(st[1]); if (st.length > 2) LOG.info(" " + st[2] + " :\t" + val); else LOG.info(st[0] + " " + code + " (" + CrawlDatum.getStatusName((byte) code) + "):\t" + val); } else if (k.equals("scd")) { MergingDigest tdigest = MergingDigest.fromBytes(ByteBuffer.wrap(bytesValue)); for (double q : quantiles) { LOG.info("score quantile {}:\t{}", q, tdigest.quantile(q)); } } else { LOG.info(k + ":\t" + val); } } } if (LOG.isInfoEnabled()) { LOG.info("CrawlDb statistics: done"); } }
From source file:com.cmart.PageControllers.SellItemImagesController.java
/** * This method checks the page for any input errors that may have come from Client generator error * These would need to be check in real life to stop users attempting to hack and mess with things * //w w w. j a v a2s . c o m * @param request * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com) */ public void checkInputs(HttpServletRequest request) { super.startTimer(); if (request != null) { // If there is a multiform there are probably pictures if (ServletFileUpload.isMultipartContent(request)) { // Get the parameters try { // Create the objects needed to read the parameters factory = new DiskFileItemFactory(); factory.setRepository(GV.LOCAL_TEMP_DIR); upload = new ServletFileUpload(factory); items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); TreeMap<String, String> params = new TreeMap<String, String>(); // Go through all the parameters and get the ones that are form fields while (iter.hasNext()) { FileItem item = iter.next(); // If the item is a parameter, read it if (item.isFormField()) { params.put(item.getFieldName(), item.getString()); } else { this.images.add(item); } } /* * Get the parameters */ // Get the userID if (params.containsKey("userID")) { try { this.userID = Long.parseLong(params.get("userID")); if (this.userID < 0) if (!errors.contains(GlobalErrors.userIDLessThanZero)) errors.add(GlobalErrors.userIDLessThanZero); } catch (NumberFormatException e) { if (!errors.contains(GlobalErrors.userIDNotAnInteger)) errors.add(GlobalErrors.userIDNotAnInteger); } } else { if (!errors.contains(GlobalErrors.userIDNotPresent)) errors.add(GlobalErrors.userIDNotPresent); } // We nned to get the html5 tag as the parent cannot do the normal parsing if (params.containsKey("useHTML5")) { try { int u5 = Integer.parseInt(params.get("useHTML5")); if (u5 == 1) this.useHTML5 = true; else this.useHTML5 = false; } catch (Exception e) { this.useHTML5 = false; } } // Get the authToken if (params.containsKey("authToken")) { this.authToken = params.get("authToken"); if (this.authToken.equals(EMPTY)) if (!errors.contains(GlobalErrors.authTokenEmpty)) errors.add(GlobalErrors.authTokenEmpty); } else { if (!errors.contains(GlobalErrors.authTokenNotPresent)) errors.add(GlobalErrors.authTokenNotPresent); } // Get the itemID if (params.containsKey("itemID")) { try { this.itemID = Long.parseLong(params.get("itemID")); if (this.itemID <= 0) if (!errors.contains(GlobalErrors.itemIDLessThanZero)) errors.add(GlobalErrors.itemIDLessThanZero); } catch (NumberFormatException e) { if (!errors.contains(GlobalErrors.itemIDNotAnInteger)) errors.add(GlobalErrors.itemIDNotAnInteger); } } else { if (!errors.contains(GlobalErrors.itemIDNotPresent)) errors.add(GlobalErrors.itemIDNotPresent); } } catch (FileUploadException e1) { // TODO Auto-generated catch block //System.out.println("SellItemImageController (checkInputs): There was an error in the multi-form"); e1.printStackTrace(); } } // Do normal request processing else { super.checkInputs(request); // Get the userID (if exists), we will pass it along to the next pages try { this.userID = CheckInputs.checkUserID(request); } catch (Error e) { // The user must be logged in to upload the images if (!errors.contains(e)) errors.add(e); } // Get the authToken (if exists), we will pass it along to the next pages try { this.authToken = CheckInputs.checkAuthToken(request); } catch (Error e) { if (!errors.contains(e)) errors.add(e); } // Get the itemID try { this.itemID = CheckInputs.checkItemID(request); if (this.itemID <= 0) if (!errors.contains(GlobalErrors.itemIDLessThanZero)) errors.add(GlobalErrors.itemIDLessThanZero); } catch (Error e) { if (!errors.contains(e)) errors.add(e); this.itemID = -1; } } } // Calculate how long that took super.stopTimerAddParam(); }
From source file:com.sfs.whichdoctor.dao.RelationshipDAOImpl.java
/** * Load supervisor relationships./*from w ww .j a va 2 s . com*/ * * @param relationshipClass the relationship class * @return the tree map<integer, string> * * @throws WhichDoctorDaoException the which doctor dao exception */ private TreeMap<Integer, String> loadSupervisorRelationships(final String relationshipClass) throws WhichDoctorDaoException { dataLogger.info("Loading map of supervisor relationships types"); TreeMap<Integer, String> supervisorMap = new TreeMap<Integer, String>(); Collection<RelationshipBean> relationships = loadSupervisors(relationshipClass); for (RelationshipBean relationship : relationships) { if (relationship.getHierarchy() > 0 && !supervisorMap.containsKey(relationship.getHierarchy())) { supervisorMap.put(relationship.getHierarchy(), relationship.getRelationshipType()); } } return supervisorMap; }
From source file:ubic.gemma.core.analysis.report.WhatsNewServiceImpl.java
/** * Give breakdown by taxon. "Private" experiments are not included. *///from w w w .j a v a 2 s . c om private Map<Taxon, Collection<Long>> getExpressionExperimentIdsByTaxon(Collection<ExpressionExperiment> ees) { /* * Sort taxa by name. */ TreeMap<Taxon, Collection<Long>> eesPerTaxon = new TreeMap<>(new Comparator<Taxon>() { @Override public int compare(Taxon o1, Taxon o2) { if (o1 == null) { return 1; } else if (o2 == null) { return -1; } else { return o1.getScientificName().compareTo(o2.getScientificName()); } } }); if (ees.isEmpty()) return eesPerTaxon; Collection<ExpressionExperiment> publicEEs = securityService.choosePublic(ees); Map<ExpressionExperiment, Taxon> taxa = expressionExperimentService.getTaxa(publicEEs); // invert the map. for (ExpressionExperiment ee : taxa.keySet()) { Taxon t = taxa.get(ee); Collection<Long> ids; if (eesPerTaxon.containsKey(t)) { ids = eesPerTaxon.get(t); } else { ids = new ArrayList<>(); } ids.add(ee.getId()); eesPerTaxon.put(t, ids); } return eesPerTaxon; }
From source file:org.wso2.carbon.apimgt.hostobjects.AssetStoreHostObject.java
public static NativeArray jsFunction_getAllTags(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws ScriptException, APIManagementException { NativeArray tagArray = new NativeArray(0); try {//from w w w . j a v a 2 s .c o m Collection collection = getRegistry(thisObj).executeQuery( RegistryConstants.QUERIES_COLLECTION_PATH + "/tags", Collections.<String, String>emptyMap()); int i = 0; TreeMap<String, Integer> map = new TreeMap<String, Integer>(); for (String fullTag : collection.getChildren()) { String tag = fullTag.split(";")[1].split(":")[1]; map.put(tag, 1 + (map.containsKey(tag) ? map.get(tag) : 0)); } for (Map.Entry<String, Integer> e : map.entrySet()) { NativeObject currentTag = new NativeObject(); currentTag.put("name", currentTag, e.getKey()); currentTag.put("count", currentTag, e.getValue()); tagArray.put(i++, tagArray, currentTag); } } catch (Exception e) { log.error("Error while getting All Tags", e); } return tagArray; }
From source file:org.wso2.carbon.appmgt.hostobjects.AssetStoreHostObject.java
public static NativeArray jsFunction_getAllTags(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws ScriptException, AppManagementException { NativeArray tagArray = new NativeArray(0); try {//from w w w . ja va2 s . c o m Collection collection = getRegistry(thisObj).executeQuery( RegistryConstants.QUERIES_COLLECTION_PATH + "/tags", Collections.<String, String>emptyMap()); int i = 0; TreeMap<String, Integer> map = new TreeMap<String, Integer>(); for (String fullTag : collection.getChildren()) { String tag = fullTag.split(";")[1].split(":")[1]; map.put(tag, 1 + (map.containsKey(tag) ? map.get(tag) : 0)); } for (Map.Entry<String, Integer> e : map.entrySet()) { NativeObject currentTag = new NativeObject(); currentTag.put("name", currentTag, e.getKey()); currentTag.put("count", currentTag, e.getValue()); tagArray.put(i++, tagArray, currentTag); } } catch (Exception e) { log.error("Error while getting All Tags", e); } return tagArray; }