List of usage examples for java.util Map isEmpty
boolean isEmpty();
From source file:com.ciphertool.sentencebuilder.dao.IndexedWordMapDao.java
/** * Add the word to the map by reference a number of times equal to the * frequency value//from www.j a v a2 s. c o m * * We can probably reduce memory utilization even more if we combine the * words into one ArrayList not separated by PartOfSpeech, and then only * separate the index HashMap by parts of speech * * @param byPartOfSpeech * the Map of Words keyed by PartOfSpeech * @return the index Map keyed by length */ protected static Map<PartOfSpeechType, int[]> buildIndexedFrequencyMapByPartOfSpeech( Map<PartOfSpeechType, ArrayList<Word>> byPartOfSpeech) { if (byPartOfSpeech == null || byPartOfSpeech.isEmpty()) { throw new IllegalArgumentException( "Error indexing PartOfSpeech map. The supplied Map of Words cannot be null or empty."); } HashMap<PartOfSpeechType, int[]> byFrequency = new HashMap<PartOfSpeechType, int[]>(); int frequencySum; /* * Loop through each PartOfSpeech, add up the frequency weights, and * create an int array of the resulting length */ for (Map.Entry<PartOfSpeechType, ArrayList<Word>> pos : byPartOfSpeech.entrySet()) { frequencySum = 0; for (Word w : byPartOfSpeech.get(pos.getKey())) { frequencySum += w.getFrequencyWeight(); } byFrequency.put(pos.getKey(), new int[frequencySum]); } int frequencyIndex; int wordIndex; /* * Loop through each PartOfSpeech and Word, and add the index to the * frequencyMap a number of times equal to the word's frequency weight */ for (Map.Entry<PartOfSpeechType, ArrayList<Word>> partOfSpeechEntry : byPartOfSpeech.entrySet()) { frequencyIndex = 0; wordIndex = 0; for (Word w : byPartOfSpeech.get(partOfSpeechEntry.getKey())) { for (int i = 0; i < w.getFrequencyWeight(); i++) { byFrequency.get(partOfSpeechEntry.getKey())[frequencyIndex] = wordIndex; frequencyIndex++; } wordIndex++; } } return byFrequency; }
From source file:com.intuit.tank.http.BaseRequestHandler.java
public static String getQueryString(Map<String, String> urlVariables) { StringBuilder queryString = new StringBuilder(); // Set the query string if (urlVariables != null) { if (!urlVariables.isEmpty()) { queryString.append("?"); // Set<Map.Entry<String, String>> set = urlVariables.entrySet(); // Iterator<Map.Entry<String, String>> iterator = // set.iterator(); for (Entry<String, String> entry : urlVariables.entrySet()) { try { StringBuilder nvp = new StringBuilder(); nvp.append(URLEncoder.encode(entry.getKey(), "UTF-8")); if (entry.getValue() != null) { nvp.append("="); nvp.append(URLEncoder.encode(entry.getValue(), "UTF-8")); }//from w w w . ja v a 2 s . c o m nvp.append("&"); queryString.append(nvp.toString()); } catch (Exception ex) { logger.warn(LogUtil.getLogMessage("Unable to set query string value: " + ex.getMessage(), LogEventType.System)); } } } } // Remove the last & String reqQueryString = ""; if (queryString.length() > 0) { if (queryString.charAt(queryString.length() - 1) == '&') reqQueryString = queryString.deleteCharAt(queryString.length() - 1).toString(); else reqQueryString = queryString.toString(); } return reqQueryString; }
From source file:exm.stc.ic.ICUtil.java
public static void replaceArgsInList(Map<Var, Arg> renames, List<Arg> args, boolean nullsOk) { if (renames.isEmpty()) { return;//from w ww .ja va 2s. c o m } for (int i = 0; i < args.size(); i++) { Arg oa = args.get(i); if (oa == null) { if (nullsOk) { continue; } else { throw new STCRuntimeError("null arg in list: " + args); } } if (oa.isVar()) { Arg val = renames.get(oa.getVar()); if (val != null) { args.set(i, val); } } } }
From source file:Main.java
public static void style(Reader xsl, Reader xml, Writer out, Map params) throws TransformerException { Source xmlSource = new javax.xml.transform.stream.StreamSource(xml); TransformerFactory factory = TransformerFactory.newInstance(); Source xslSource = new javax.xml.transform.stream.StreamSource(xsl); Transformer transformer;//from w ww . j av a 2 s. c om transformer = factory.newTransformer(xslSource); if (params != null && !params.isEmpty()) { Iterator entries = params.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); transformer.setParameter((String) entry.getKey(), entry.getValue()); } } StreamResult result = new StreamResult(out); transformer.transform(xmlSource, result); }
From source file:com.erudika.para.validation.ValidationUtils.java
/** * Validates objects./*from w w w .j av a2s. c o m*/ * @param content an object to be validated * @param app the current app * @return a list of error messages or empty if object is valid */ public static String[] validateObject(App app, ParaObject content) { if (content == null || app == null) { return new String[] { "Object cannot be null." }; } try { String type = content.getType(); boolean isCustomType = (content instanceof Sysprop) && !type.equals(Utils.type(Sysprop.class)); // Validate custom types and user-defined properties if (!app.getValidationConstraints().isEmpty() && isCustomType) { Map<String, Map<String, Map<String, ?>>> fieldsMap = app.getValidationConstraints().get(type); if (fieldsMap != null && !fieldsMap.isEmpty()) { LinkedList<String> errors = new LinkedList<String>(); for (Map.Entry<String, Map<String, Map<String, ?>>> e : fieldsMap.entrySet()) { String field = e.getKey(); Object actualValue = ((Sysprop) content).getProperty(field); // overriding core property validation rules is allowed if (actualValue == null && PropertyUtils.isReadable(content, field)) { actualValue = PropertyUtils.getProperty(content, field); } Map<String, Map<String, ?>> consMap = e.getValue(); for (Map.Entry<String, Map<String, ?>> constraint : consMap.entrySet()) { String consName = constraint.getKey(); Map<String, ?> vals = constraint.getValue(); if (vals == null) { vals = Collections.emptyMap(); } Object val = vals.get("value"); Object min = vals.get("min"); Object max = vals.get("max"); Object in = vals.get("integer"); Object fr = vals.get("fraction"); if ("required".equals(consName) && !required().isValid(actualValue)) { errors.add(Utils.formatMessage("{0} is required.", field)); } else if (matches(Min.class, consName) && !min(val).isValid(actualValue)) { errors.add( Utils.formatMessage("{0} must be a number larger than {1}.", field, val)); } else if (matches(Max.class, consName) && !max(val).isValid(actualValue)) { errors.add( Utils.formatMessage("{0} must be a number smaller than {1}.", field, val)); } else if (matches(Size.class, consName) && !size(min, max).isValid(actualValue)) { errors.add( Utils.formatMessage("{0} must be between {1} and {2}.", field, min, max)); } else if (matches(Email.class, consName) && !email().isValid(actualValue)) { errors.add(Utils.formatMessage("{0} is not a valid email.", field)); } else if (matches(Digits.class, consName) && !digits(in, fr).isValid(actualValue)) { errors.add( Utils.formatMessage("{0} is not a valid number or within range.", field)); } else if (matches(Pattern.class, consName) && !pattern(val).isValid(actualValue)) { errors.add(Utils.formatMessage("{0} doesn't match the pattern {1}.", field, val)); } else if (matches(AssertFalse.class, consName) && !falsy().isValid(actualValue)) { errors.add(Utils.formatMessage("{0} must be false.", field)); } else if (matches(AssertTrue.class, consName) && !truthy().isValid(actualValue)) { errors.add(Utils.formatMessage("{0} must be true.", field)); } else if (matches(Future.class, consName) && !future().isValid(actualValue)) { errors.add(Utils.formatMessage("{0} must be in the future.", field)); } else if (matches(Past.class, consName) && !past().isValid(actualValue)) { errors.add(Utils.formatMessage("{0} must be in the past.", field)); } else if (matches(URL.class, consName) && !url().isValid(actualValue)) { errors.add(Utils.formatMessage("{0} is not a valid URL.", field)); } } } if (!errors.isEmpty()) { return errors.toArray(new String[0]); } } } } catch (Exception ex) { logger.error(null, ex); } return validateObject(content); }
From source file:controllers.OldSensorReadingController.java
private static String getDateFormat() { String dateFormat = null;//from w ww . j a v a 2 s . com final Map<String, String[]> entries = request().queryString(); if (!entries.isEmpty() && entries.containsKey("dateformat")) { dateFormat = entries.get("dateformat")[0]; } return dateFormat; }
From source file:musite.ui.cmd.CmdLineTools.java
private static String printResult(PredictionResult result) { if (result == null || result.getModels().isEmpty()) { return ""; }//from w ww . j a v a 2 s. c o m StringBuilder sb = new StringBuilder(); sb.append("Position\tAmino Acid\tSurr. Sequence\tScore\tSpecificity\tModel\n"); Iterator<Protein> it = result.proteinIterator(); while (it.hasNext()) { Protein protein = it.next(); String acc = protein.getAccession(); sb.append('>'); sb.append(protein.toString()); sb.append('\n'); for (PredictionModel model : result.getModels()) { Map<Integer, Double> preds = result.getPredictions(model, acc); if (preds == null || preds.isEmpty()) continue; String proteinSeq = protein.getSequence(); int len = proteinSeq.length(); for (Map.Entry<Integer, Double> entry : preds.entrySet()) { int site = entry.getKey(); sb.append(site + 1); sb.append('\t'); if (site < offset) { sb.append(StringUtils.repeat("*", offset - site)); sb.append(proteinSeq.substring(0, site)); } else { sb.append(proteinSeq.substring(site - offset, site)); } int end = site + offset + 1; if (end > len) { sb.append(proteinSeq.substring(site, len)); sb.append(StringUtils.repeat("*", end - len)); } else { sb.append(proteinSeq.substring(site, end)); } sb.append('\t'); sb.append(proteinSeq.charAt(site)); sb.append('\t'); sb.append(preds.get(site)); sb.append('\t'); SpecificityEstimator est = model.getSpecEstimator(); sb.append(est.specificity(preds.get(site))); sb.append('\t'); sb.append(model.getName()); sb.append('\n'); } } } return sb.toString(); }
From source file:com.betfair.application.performance.BaselinePerformanceTester.java
public static void simpleSummary(String ident, Map<HttpCallLogEntry, CallLogCount> calls) { if (calls.isEmpty()) return;/*from w w w .j a v a 2 s .co m*/ long totalCalls = 0; long totalCallTime = 0; for (Map.Entry<HttpCallLogEntry, CallLogCount> entry : calls.entrySet()) { CallLogCount c = entry.getValue(); totalCalls += c.numCalls.get(); totalCallTime += c.callTime.get(); } System.out.format("%20s: Total Calls: %6d, Ave time per call: %3.3f ms\n", ident, totalCalls, totalCallTime / (totalCalls * 1000000d)); }
From source file:SearchApiExample.java
/** * Process command line options and call the service. *//* w w w . j a va2 s . co m*/ private static void processCommandLine(CommandLine line, Options options) { if (line.hasOption(HELP_OPTION)) { printHelp(options); } else if (line.hasOption(CONSUMER_KEY_OPTION) && line.hasOption(CONSUMER_SECRET_OPTION) && line.hasOption(ACCESS_TOKEN_OPTION) && line.hasOption(ACCESS_TOKEN_SECRET_OPTION)) { final String consumerKeyValue = line.getOptionValue(CONSUMER_KEY_OPTION); final String consumerSecretValue = line.getOptionValue(CONSUMER_SECRET_OPTION); final String accessTokenValue = line.getOptionValue(ACCESS_TOKEN_OPTION); final String tokenSecretValue = line.getOptionValue(ACCESS_TOKEN_SECRET_OPTION); final LinkedInApiClientFactory factory = LinkedInApiClientFactory.newInstance(consumerKeyValue, consumerSecretValue); final LinkedInApiClient client = factory.createLinkedInApiClient(accessTokenValue, tokenSecretValue); Map<SearchParameter, String> searchParameters = getSearchParameters(line); if (!searchParameters.isEmpty()) { System.out.println("Searching for users."); List<Parameter<FacetType, String>> facets = new ArrayList<Parameter<FacetType, String>>(); facets.add(new Parameter<FacetType, String>(FacetType.NETWORK, RelationshipCodes.OUT_OF_NETWORK_CONNECTIONS)); facets.add(new Parameter<FacetType, String>(FacetType.NETWORK, RelationshipCodes.SECOND_DEGREE_CONNECTIONS)); facets.add(new Parameter<FacetType, String>(FacetType.LANGUAGE, LanguageCodes.ENGLISH)); PeopleSearch people = client.searchPeople(searchParameters, EnumSet.of(ProfileField.FIRST_NAME, ProfileField.LAST_NAME, ProfileField.ID, ProfileField.HEADLINE), EnumSet.of(FacetField.NAME, FacetField.CODE, FacetField.BUCKET_NAME, FacetField.BUCKET_CODE, FacetField.BUCKET_COUNT), facets); printResult(people.getPeople()); printResult(people.getFacets()); } else { System.out.println("Searching for users."); People people = client.searchPeople(); printResult(people); } } else { printHelp(options); } }
From source file:com.bstek.dorado.common.event.ClientEventRegistry.java
/** * ?Class??/*from w ww .j a v a2 s. c o m*/ * * @param type * Class * @return ?Map?Map???? */ @SuppressWarnings("unchecked") public static Map<String, ClientEventRegisterInfo> getClientEventRegisterInfos( Class<? extends ClientEventSupported> type) { synchronized (type) { Map<String, ClientEventRegisterInfo> eventMap = typeMapCache.get(type); if (eventMap == null) { eventMap = new HashMap<String, ClientEventRegisterInfo>(); collectClientEventRegisterInfos(eventMap, type); eventMap = (eventMap.isEmpty()) ? EMPTY_MAP : UnmodifiableMap.decorate(eventMap); typeMapCache.put(type, eventMap); } return eventMap; } }