List of usage examples for java.util AbstractMap.SimpleEntry AbstractMap.SimpleEntry
public SimpleEntry(K key, V value)
From source file:de.uni_tuebingen.ub.ixTheo.handler.component.FacetPrefixSortComponent.java
/** * Actually run the query// w w w .j av a 2 s . c om */ @Override public void process(ResponseBuilder rb) throws IOException { if (rb.doFacets) { final ModifiableSolrParams params = new ModifiableSolrParams(); final SolrParams origParams = rb.req.getParams(); final Iterator<String> iter = origParams.getParameterNamesIterator(); setCollator(origParams.get("lang")); while (iter.hasNext()) { final String paramName = iter.next(); // Deduplicate the list with LinkedHashSet, but _only_ for facet // params. if (!paramName.startsWith(FacetParams.FACET)) { params.add(paramName, origParams.getParams(paramName)); continue; } final HashSet<String> deDupe = new LinkedHashSet<>(Arrays.asList(origParams.getParams(paramName))); params.add(paramName, deDupe.toArray(new String[deDupe.size()])); } final SimplePrefixSortFacets facets = new SimplePrefixSortFacets(rb.req, rb.getResults().docSet, params, rb); final NamedList<Object> counts = org.apache.solr.handler.component.FacetComponent .getFacetCounts(facets); final String[] pivots = params.getParams(FacetParams.FACET_PIVOT); if (pivots != null && pivots.length > 0) { PivotFacetProcessor pivotProcessor = new PivotFacetProcessor(rb.req, rb.getResults().docSet, params, rb); SimpleOrderedMap<List<NamedList<Object>>> v = pivotProcessor.process(pivots); if (v != null) { counts.add(PIVOT_KEY, v); } } // Check whether we have to reorder out results // according to prefix final String sort = params.get(FacetParams.FACET_SORT); if (FacetPrefixSortParams.FACET_SORT_PREFIX.equals(sort)) { // Determine a score relative to the original query // Determine the query and make it compatible with our metric // class // by splitting the single terms String[] queryTerms = params.getParams(CommonParams.Q); final Collection<String> queryTermsCollection = new ArrayList<>(); for (String s : queryTerms) { // Split at whitespace except we have a quoted term Matcher matcher = WHITE_SPACES_WITH_QUOTES_SPLITTING_PATTERN.matcher(s); while (matcher.find()) { queryTermsCollection.add(matcher.group().replaceAll("^\"|\"$", "")); } } // In some contexts, i.e. in KWC that are derived from ordinary // keywords or if // wildcards occur, also add all the query terms as a single // phrase term // with stripped wildcards StringBuilder sb = new StringBuilder(); for (String s : queryTermsCollection) { s = s.replace("*", ""); sb.append(s); sb.append(" "); } queryTermsCollection.add(sb.toString().trim()); final ArrayList<String> queryList = new ArrayList<>(queryTermsCollection); final String facetfield = params.get(FacetParams.FACET_FIELD); // Get the current facet entry and make it compatible with our // metric class // "facet_fields" itself contains a NamedList with the // facet.field as key final NamedList<Object> facetFieldsNamedList = (NamedList<Object>) counts.get("facet_fields"); final NamedList<Object> facetFields = (NamedList<Object>) facetFieldsNamedList.get(facetfield); final List<Entry<Entry<String, Object>, Double>> facetPrefixListScored = new ArrayList<>(); for (final Entry<String, Object> entry : facetFields) { final String facetTerms = entry.getKey(); // Split up each KWC and calculate the scoring ArrayList<String> facetList = new ArrayList<>( Arrays.asList(facetTerms.split("(?<!" + Pattern.quote("\\") + ")/"))); // For usability reasons sort the result facets according to // the order of the search facetList = KeywordSort.sortToReferenceChain(queryList, facetList); final double score = KeywordChainMetric.calculateSimilarityScore(queryList, facetList); // Collect the result in a sorted list and throw away // garbage if (score > 0) { String facetTermsSorted = StringUtils.join(facetList, "/"); Map.Entry<String, Object> sortedEntry = new AbstractMap.SimpleEntry<>(facetTermsSorted, entry.getValue()); facetPrefixListScored.add(new AbstractMap.SimpleEntry<>(sortedEntry, score)); } } Collections.sort(facetPrefixListScored, ENTRY_COMPARATOR); // Extract all the values wrap it back to NamedList again and // replace in the original structure facetFieldsNamedList.clear(); NamedList<Object> facetNamedListSorted = new NamedList<>(); // We had to disable all limits and offsets sort according // Handle this accordingly now int offset = (params.getInt(FacetParams.FACET_OFFSET) != null) ? params.getInt(FacetParams.FACET_OFFSET) : 0; int limit = (params.getInt(FacetParams.FACET_LIMIT) != null) ? params.getInt(FacetParams.FACET_LIMIT) : 100; // Strip uneeded elements int s = facetPrefixListScored.size(); int off = (offset < s) ? offset : 0; limit = (limit < 0) ? s : limit; // Handle a negative limit // param, i.e. unlimited results int lim = (offset + limit <= s) ? (offset + limit) : s; final List<Entry<Entry<String, Object>, Double>> facetPrefixListScoredTruncated = facetPrefixListScored .subList(off, lim); for (Entry<Entry<String, Object>, Double> e : facetPrefixListScoredTruncated) { facetNamedListSorted.add(e.getKey().getKey(), e.getKey().getValue()); } facetFieldsNamedList.add(facetfield, facetNamedListSorted); NamedList<Object> countList = new NamedList<>(); countList.add("count", facetPrefixListScored.size()); facetFieldsNamedList.add(facetfield + "-count", countList); counts.remove("facet_fields"); counts.add("facet_fields", facetFieldsNamedList); } rb.rsp.add("facet_counts", counts); } }
From source file:org.apache.metron.stellar.dsl.functions.HashFunctionsTest.java
@Test public void tlsh_multithread() throws Exception { //we want to ensure that everything is threadsafe, so we'll spin up some random data //generate some hashes and then do it all in parallel and make sure it all matches. Map<Map.Entry<byte[], Map<String, Object>>, String> hashes = new HashMap<>(); Random r = new Random(0); for (int i = 0; i < 20; ++i) { byte[] d = new byte[256]; r.nextBytes(d);/* w w w.j a v a 2s . c o m*/ Map<String, Object> config = new HashMap<String, Object>() { { put(TLSHHasher.Config.BUCKET_SIZE.key, r.nextBoolean() ? 128 : 256); put(TLSHHasher.Config.CHECKSUM.key, r.nextBoolean() ? 1 : 3); } }; String hash = (String) run("HASH(data, 'tlsh', config)", ImmutableMap.of("config", config, "data", d)); Assert.assertNotNull(hash); hashes.put(new AbstractMap.SimpleEntry<>(d, config), hash); } ForkJoinPool forkJoinPool = new ForkJoinPool(5); forkJoinPool.submit(() -> hashes.entrySet().parallelStream().forEach(kv -> { Map<String, Object> config = kv.getKey().getValue(); byte[] data = kv.getKey().getKey(); String hash = (String) run("HASH(data, 'tlsh', config)", ImmutableMap.of("config", config, "data", data)); Assert.assertEquals(hash, kv.getValue()); })); }
From source file:io.stallion.settings.Settings.java
public void assignDefaults() { if (getLocalMode() == null) { if (empty(System.getenv().getOrDefault("STALLION_DEPLOY_TIME", ""))) { setLocalMode(true);//from ww w . j a v a2 s.co m } else { setLocalMode(false); } } if (bundleDebug == null) { bundleDebug = getLocalMode(); } if (getDebug() == null) { if (getEnv().equals("prod") && !getLocalMode()) { setDebug(false); } else { setDebug(true); } } if (timeZone == null) { timeZone = ZoneId.systemDefault().toString(); } if (timeZoneId == null) { timeZoneId = ZoneId.of(timeZone); } if (logFile == null) { String nowString = DateUtils.formatNow("yyyy-MM-dd-HHmmss"); String base = ""; try { if (!empty(siteUrl)) { base = new URL(siteUrl.replace(":{port}", "")).getHost(); } } catch (IOException e) { Log.exception(e, "Error parsing siteUrl " + siteUrl); } logFile = "/tmp/log/stallion/" + base + "-" + nowString + "-" + StringUtils.strip(GeneralUtils.slugify(targetFolder), "-") + ".log"; } if (logToConsole == null) { logToConsole = getLocalMode(); } if (logToFile == null) { logToFile = !logToConsole; } if (getEmailErrors() == null) { if ((getEnv().equals("prod") || getEnv().equals("qa")) && !getLocalMode()) { setEmailErrors(true); } else { setEmailErrors(false); } } if (getStrictnessLevel() == null) { if (getEnv().equals("prod") && !getLocalMode()) { setStrictnessLevel(StrictnessLevel.LAX); } else { setStrictnessLevel(StrictnessLevel.STRICT); } } if (!empty(secondaryDomains)) { secondaryDomainByDomain = map(); for (SecondaryDomain d : secondaryDomains) { secondaryDomainByDomain.put(d.getDomain(), d); } } if (!StringUtils.isEmpty(getDataDirectory())) { if (!getDataDirectory().startsWith("/")) { setDataDirectory(targetFolder + "/" + getDataDirectory()); } } else { setDataDirectory(targetFolder + "/app-data"); } if (getDataDirectory().endsWith("/")) { setDataDirectory(getDataDirectory().substring(0, getDataDirectory().length() - 1)); } if (getRewrites() != null) { // THe Toml library has a bug whereby if a map key is quoted, it keeps the // quotes as part of the key, rather than using the String inside the quotes Set<String> keys = new HashSet<>(getRewrites().keySet()); for (String key : keys) { if (key.startsWith("\"") && key.endsWith("\"")) { getRewrites().put(key.substring(1, key.length() - 1), getRewrites().get(key)); } } } if (getRedirects() != null) { // THe Toml library has a bug whereby if a map key is quoted, it keeps the // quotes as part of the key, rather than using the String inside the quotes Set<String> keys = new HashSet<>(getRedirects().keySet()); for (String key : keys) { if (key.startsWith("\"") && key.endsWith("\"")) { getRedirects().put(key.substring(1, key.length() - 1), getRedirects().get(key)); } } } if (getRewritePatterns() != null && getRewritePatterns().size() > 0) { if (rewriteCompiledPatterns == null) { rewriteCompiledPatterns = new ArrayList(); } for (String[] entry : getRewritePatterns()) { if (entry.length != 2) { Log.warn("Invalid rewritePatterns entry, size should be 2 but is {0} {1}", entry.length, entry); } Pattern pattern = Pattern.compile(entry[0]); Map.Entry<Pattern, String> kv = new AbstractMap.SimpleEntry<Pattern, String>(pattern, entry[1]); getRewriteCompiledPatterns().add(kv); } } if (getEmail() != null) { // By default, in debug mode, we do not want to send real emails to people if (getEmail().getRestrictOutboundEmails() == null) { getEmail().setRestrictOutboundEmails(getDebug()); } if (getEmail().getOutboundEmailTestAddress() == null) { if (getEmail().getAdminEmails() != null && getEmail().getAdminEmails().size() > 0) { getEmail().setOutboundEmailTestAddress(getEmail().getAdminEmails().get(0)); } } if (!empty(getEmail().getAllowedTestingOutboundEmailPatterns())) { if (getEmail().getAllowedTestingOutboundEmailCompiledPatterns() == null) { getEmail().setAllowedTestingOutboundEmailCompiledPatterns(new ArrayList<>()); } for (String emailPattern : getEmail().getAllowedTestingOutboundEmailPatterns()) { getEmail().getAllowedTestingOutboundEmailCompiledPatterns().add(Pattern.compile(emailPattern)); } } } if (getSecrets() == null) { setSecrets(new SecretsSettings()); } if (new File(targetFolder + "/pages").isDirectory()) { if (folders == null) { folders = new ArrayList<>(); } folders.add(new ContentFolder().setPath(targetFolder + "/pages").setType("markdown") .setItemTemplate(getPageTemplate())); } if (userUploads != null && empty(userUploads.getUploadsDirectory())) { userUploads.setUploadsDirectory(getDataDirectory() + "/st-user-file-uploads"); } }
From source file:org.languagetool.dev.bigdata.ProhibitedCompoundRuleEvaluator.java
private List<Map.Entry<Sentence, Map.Entry<Integer, Integer>>> getSentencesFromSource(List<String> inputs, String token, int maxSentences, SentenceSource sentenceSource) { List<Map.Entry<Sentence, Map.Entry<Integer, Integer>>> sentences = new ArrayList<>(); Pattern pattern = Pattern.compile("(?iu)\\b(" + token.toLowerCase() + ")\\p{Alpha}+\\b|\\b\\p{Alpha}+(" + token.toLowerCase() + ")\\b"); while (sentenceSource.hasNext()) { Sentence sentence = sentenceSource.next(); Matcher matcher = pattern.matcher(sentence.getText()); if (matcher.find() && Character.isUpperCase(matcher.group().charAt(0))) { Map.Entry<Integer, Integer> range = new AbstractMap.SimpleEntry<>( // -1 if group did not match anything -> max gets result from group that matched Math.max(matcher.start(1), matcher.start(2)), Math.max(matcher.end(1), matcher.end(2))); sentences.add(new AbstractMap.SimpleEntry<>(sentence, range)); //if (sentences.size() % 250 == 0) { // println("Loaded sentence " + sentences.size() + " with '" + token + "' from " + inputs); //}/* www .j ava 2 s. c o m*/ if (sentences.size() >= maxSentences) { break; } } } println("Loaded " + sentences.size() + " sentences with '" + token + "' from " + inputs); return sentences; }
From source file:fr.juanwolf.mysqlbinlogreplicator.service.MySQLEventListenerTest.java
@Test public void onEvent_should_update_the_object_from_the_event_received_if_the_table_is_concerned() throws ReflectiveOperationException { // given//from ww w . j a va 2s . co m String emailExpected = "test@test.com"; when(eventHeader.getEventType()).thenReturn(EventType.UPDATE_ROWS); StubRepository stubRepository = new StubRepository(); User userToUpdate = new User(); setUpDomainClassAnalyzer(stubRepository, userToUpdate); byte[] types = { (byte) ColumnType.VARCHAR.getCode() }; Object[] columns = { "mail" }; setUpMySqlEventListener(columns, types); UpdateRowsEventData updateRowsEventData = new UpdateRowsEventData(); List<Map.Entry<Serializable[], Serializable[]>> datas = new ArrayList<>(); Serializable[] serializables = { emailExpected }; Serializable[] beforeValues = {}; datas.add(new AbstractMap.SimpleEntry<>(beforeValues, serializables)); updateRowsEventData.setRows(datas); Event event = new Event(eventHeader, updateRowsEventData); // when mySQLEventListener.onEvent(event); // then String emailOfUpdatedAccount = ((User) stubRepository.getElementList().get(0)).getMail(); assertThat(emailOfUpdatedAccount).isEqualTo(emailExpected); }
From source file:apim.restful.importexport.utils.APIExportUtil.java
/** * Retrieve custom sequence details from the registry * * @param sequenceName Name of the sequence * @param type Sequence type/* w w w . j av a2 s.c o m*/ * @param registry Current tenant registry * @return Registry resource name of the sequence and its content * @throws APIExportException If an error occurs while retrieving registry elements */ private static AbstractMap.SimpleEntry<String, OMElement> getCustomSequence(String sequenceName, String type, Registry registry) throws APIExportException { AbstractMap.SimpleEntry<String, OMElement> sequenceDetails; org.wso2.carbon.registry.api.Collection seqCollection = null; try { if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN.equals(type)) { seqCollection = (org.wso2.carbon.registry.api.Collection) registry .get(APIConstants.API_CUSTOM_INSEQUENCE_LOCATION); } else if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT.equals(type)) { seqCollection = (org.wso2.carbon.registry.api.Collection) registry .get(APIConstants.API_CUSTOM_OUTSEQUENCE_LOCATION); } else if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT.equals(type)) { seqCollection = (org.wso2.carbon.registry.api.Collection) registry .get(APIConstants.API_CUSTOM_FAULTSEQUENCE_LOCATION); } if (seqCollection != null) { String[] childPaths = seqCollection.getChildren(); for (int i = 0; i < childPaths.length; i++) { Resource sequence = registry.get(childPaths[i]); OMElement seqElment = APIUtil.buildOMElement(sequence.getContentStream()); if (sequenceName.equals(seqElment.getAttributeValue(new QName("name")))) { String sequenceFileName = sequence.getPath().substring(sequence.getPath().lastIndexOf('/')); sequenceDetails = new AbstractMap.SimpleEntry<String, OMElement>(sequenceFileName, seqElment); return sequenceDetails; } } } } catch (RegistryException e) { log.error("Error while retrieving sequence from the registry " + e.getMessage()); throw new APIExportException("Error while retrieving sequence from the registry", e); } catch (Exception e) { //APIUtil.buildOMElement() throws a generic exception log.error("Error while reading sequence content " + e.getMessage()); throw new APIExportException("Error while reading sequence content", e); } return null; }
From source file:com.redhat.lightblue.metadata.rdbms.converter.Translator.java
protected void recursiveTranslateNaryLogicalExpression(TranslationContext translationContext, NaryLogicalExpression naryLogicalExpression) { String ops = NARY_TO_SQL.get(naryLogicalExpression.getOp()); boolean noStatement = translationContext.logicalStmt.size() == 0; translationContext.logicalStmt//from w w w . j ava 2s . co m .add(new AbstractMap.SimpleEntry<String, List<String>>(ops, new ArrayList<String>())); for (QueryExpression queryExpression : naryLogicalExpression.getQueries()) { recursiveTranslateQuery(translationContext, queryExpression); } Map.Entry<String, List<String>> remove = translationContext.logicalStmt .remove(translationContext.logicalStmt.size() - 1); String op = remove.getKey() + " "; StringBuilder conditionalStringBuilder = new StringBuilder(); if (!noStatement || !translationContext.baseStmt.getWhereConditionals().isEmpty()) { conditionalStringBuilder.append("("); } for (int i = 0; i < remove.getValue().size(); i++) { String value = remove.getValue().get(i); if (i == (remove.getValue().size() - 1)) { conditionalStringBuilder.append(value); if (!noStatement || !translationContext.baseStmt.getWhereConditionals().isEmpty()) { conditionalStringBuilder.append(") "); } } else { conditionalStringBuilder.append(value).append(" ").append(op); } } if (noStatement) { translationContext.baseStmt.getWhereConditionals().add(conditionalStringBuilder.toString()); } else { translationContext.logicalStmt.get(translationContext.logicalStmt.size() - 1).getValue() .add(conditionalStringBuilder.toString()); } }
From source file:de.domjos.schooltools.activities.MainActivity.java
private void addEvents() { this.eventAdapter.clear(); if (this.llToday.getVisibility() == View.VISIBLE) { List<TimerEvent> timerEvents = MainActivity.globals.getSqLite().getTimerEvents(""); for (TimerEvent event : timerEvents) { if (Helper.compareDateWithCurrentDate(event.getEventDate())) { this.eventAdapter.add(new AbstractMap.SimpleEntry<>(this.getString(R.string.main_nav_timer), event.getTitle())); }//w ww . j av a 2 s .co m } List<Memory> memories = MainActivity.globals.getSqLite().getCurrentMemories(); for (Memory memory : memories) { try { if (Helper.compareDateWithCurrentDate(Converter.convertStringToDate(memory.getDate()))) { this.eventAdapter.add(new AbstractMap.SimpleEntry<>( "Er.(" + memory.getStringType(this.getApplicationContext()) + ")", memory.getTitle())); } } catch (Exception ex) { Helper.printException(this.getApplicationContext(), ex); } } if (this.eventAdapter.isEmpty()) { this.eventAdapter.add(new AbstractMap.SimpleEntry<>(this.getString(R.string.main_noEntry), "")); } } }
From source file:com.activecq.tools.errorpagehandler.impl.ErrorPageHandlerImpl.java
/** * Util for parsing Service properties in the form >value<>separator<>value< * * @param value//from ww w. ja v a 2s .c o m * @param separator * @return */ private AbstractMap.SimpleEntry toSimpleEntry(String value, String separator) { String[] tmp = StringUtils.split(value, separator); if (tmp == null) { return null; } if (tmp.length == 2) { return new AbstractMap.SimpleEntry(tmp[0], tmp[1]); } else { return null; } }
From source file:com.skelril.skree.content.world.wilderness.WildernessWorldWrapper.java
public Set<Map.Entry<Player, WildernessPlayerMeta>> getMetaInformation() { Set<Map.Entry<Player, WildernessPlayerMeta>> resultSets = new HashSet<>(); for (Map.Entry<UUID, WildernessPlayerMeta> entry : playerMetaMap.entrySet()) { Optional<Player> optPlayer = Sponge.getServer().getPlayer(entry.getKey()); if (!optPlayer.isPresent()) { continue; }/*from w w w . j av a2 s. c o m*/ Player player = optPlayer.get(); if (!player.isOnline()) { continue; } resultSets.add(new AbstractMap.SimpleEntry<>(player, entry.getValue())); } return resultSets; }