List of usage examples for java.util Locale toString
@Override public final String toString()
Locale
object, consisting of language, country, variant, script, and extensions as below: language + "_" + country + "_" + (variant + "_#" | "#") + script + "_" + extensionsLanguage is always lower case, country is always upper case, script is always title case, and extensions are always lower case.
From source file:org.alfresco.solr.query.Solr4QueryParser.java
@SuppressWarnings("unchecked") protected Query getFieldQueryImpl(String field, String queryText, AnalysisMode analysisMode, LuceneFunction luceneFunction) throws ParseException, IOException { // make sure the field exists or return a dummy query so we have no error ....ACE-3231 SchemaField schemaField = schema.getFieldOrNull(field); boolean isNumeric = false; if (schemaField == null) { return new TermQuery(new Term("_dummy_", "_miss_")); } else {//from www. j a v a2s .com isNumeric = (schemaField.getType().getNumericType() != null); } // Use the analyzer to get all the tokens, and then build a TermQuery, // PhraseQuery, or noth // TODO: Untokenised columns with functions require special handling if (luceneFunction != LuceneFunction.FIELD) { throw new UnsupportedOperationException( "Field queries are not supported on lucene functions (UPPER, LOWER, etc)"); } // if the incoming string already has a language identifier we strip it iff and addit back on again String localePrefix = ""; String toTokenise = queryText; if (queryText.startsWith("{")) { int position = queryText.indexOf("}"); if (position > 0) { String language = queryText.substring(0, position + 1); Locale locale = new Locale(queryText.substring(1, position)); String token = queryText.substring(position + 1); boolean found = false; for (Locale current : Locale.getAvailableLocales()) { if (current.toString().equalsIgnoreCase(locale.toString())) { found = true; break; } } if (found) { localePrefix = language; toTokenise = token; } else { //toTokenise = token; } } } String testText = toTokenise; boolean requiresMLTokenDuplication = false; String localeString = null; if (isPropertyField(field) && (localePrefix.length() == 0)) { if ((queryText.length() > 0) && (queryText.charAt(0) == '\u0000')) { int position = queryText.indexOf("\u0000", 1); testText = queryText.substring(position + 1); requiresMLTokenDuplication = true; localeString = queryText.substring(1, position); } } // find the positions of any escaped * and ? and ignore them Set<Integer> wildcardPoistions = getWildcardPositions(testText); TokenStream source = null; ArrayList<org.apache.lucene.analysis.Token> list = new ArrayList<org.apache.lucene.analysis.Token>(); boolean severalTokensAtSamePosition = false; org.apache.lucene.analysis.Token nextToken; int positionCount = 0; try { org.apache.lucene.analysis.Token reusableToken = new org.apache.lucene.analysis.Token(); source = getAnalyzer().tokenStream(field, new StringReader(toTokenise)); source.reset(); while (source.incrementToken()) { CharTermAttribute cta = source.getAttribute(CharTermAttribute.class); OffsetAttribute offsetAtt = source.getAttribute(OffsetAttribute.class); TypeAttribute typeAtt = null; if (source.hasAttribute(TypeAttribute.class)) { typeAtt = source.getAttribute(TypeAttribute.class); } PositionIncrementAttribute posIncAtt = null; if (source.hasAttribute(PositionIncrementAttribute.class)) { posIncAtt = source.getAttribute(PositionIncrementAttribute.class); } nextToken = new Token(cta.buffer(), 0, cta.length(), offsetAtt.startOffset(), offsetAtt.endOffset()); if (typeAtt != null) { nextToken.setType(typeAtt.type()); } if (posIncAtt != null) { nextToken.setPositionIncrement(posIncAtt.getPositionIncrement()); } list.add(nextToken); if (nextToken.getPositionIncrement() != 0) positionCount += nextToken.getPositionIncrement(); else severalTokensAtSamePosition = true; } } catch (SolrException e) { // MNT-15336 // Text against a numeric field should fail silently rather then tell you it is not possible. if (isNumeric && e.getMessage() != null && e.getMessage().startsWith("Invalid Number:")) { // Generate a query that does not match any document - rather than nothing return createNoMatchQuery(); } else { throw e; } } finally { try { if (source != null) { source.close(); } } catch (IOException e) { // ignore } } // add any alpha numeric wildcards that have been missed // Fixes most stop word and wild card issues for (int index = 0; index < testText.length(); index++) { char current = testText.charAt(index); if (((current == '*') || (current == '?')) && wildcardPoistions.contains(index)) { StringBuilder pre = new StringBuilder(10); if (index == 0) { // "*" and "?" at the start boolean found = false; for (int j = 0; j < list.size(); j++) { org.apache.lucene.analysis.Token test = list.get(j); if ((test.startOffset() <= 0) && (0 < test.endOffset())) { found = true; break; } } if (!found && (list.size() == 0)) { // Add new token followed by * not given by the tokeniser org.apache.lucene.analysis.Token newToken = new org.apache.lucene.analysis.Token("", 0, 0); newToken.setType("ALPHANUM"); if (requiresMLTokenDuplication) { Locale locale = I18NUtil.parseLocale(localeString); MLTokenDuplicator duplicator = new MLTokenDuplicator(locale, MLAnalysisMode.EXACT_LANGUAGE); Iterator<org.apache.lucene.analysis.Token> it = duplicator.buildIterator(newToken); if (it != null) { int count = 0; while (it.hasNext()) { list.add(it.next()); count++; if (count > 1) { severalTokensAtSamePosition = true; } } } } // content else { list.add(newToken); } } } else if (index > 0) { // Add * and ? back into any tokens from which it has been removed boolean tokenFound = false; for (int j = 0; j < list.size(); j++) { org.apache.lucene.analysis.Token test = list.get(j); if ((test.startOffset() <= index) && (index < test.endOffset())) { if (requiresMLTokenDuplication) { String termText = test.toString(); int position = termText.indexOf("}"); String language = termText.substring(0, position + 1); String token = termText.substring(position + 1); if (index >= test.startOffset() + token.length()) { test.setEmpty(); test.append(language + token + current); } } else { if (index >= test.startOffset() + test.length()) { test.setEmpty(); test.append(test.toString() + current); } } tokenFound = true; break; } } if (!tokenFound) { for (int i = index - 1; i >= 0; i--) { char c = testText.charAt(i); if (Character.isLetterOrDigit(c)) { boolean found = false; for (int j = 0; j < list.size(); j++) { org.apache.lucene.analysis.Token test = list.get(j); if ((test.startOffset() <= i) && (i < test.endOffset())) { found = true; break; } } if (found) { break; } else { pre.insert(0, c); } } else { break; } } if (pre.length() > 0) { // Add new token followed by * not given by the tokeniser org.apache.lucene.analysis.Token newToken = new org.apache.lucene.analysis.Token( pre.toString(), index - pre.length(), index); newToken.setType("ALPHANUM"); if (requiresMLTokenDuplication) { Locale locale = I18NUtil.parseLocale(localeString); MLTokenDuplicator duplicator = new MLTokenDuplicator(locale, MLAnalysisMode.EXACT_LANGUAGE); Iterator<org.apache.lucene.analysis.Token> it = duplicator.buildIterator(newToken); if (it != null) { int count = 0; while (it.hasNext()) { list.add(it.next()); count++; if (count > 1) { severalTokensAtSamePosition = true; } } } } // content else { list.add(newToken); } } } } StringBuilder post = new StringBuilder(10); if (index > 0) { for (int i = index + 1; i < testText.length(); i++) { char c = testText.charAt(i); if (Character.isLetterOrDigit(c)) { boolean found = false; for (int j = 0; j < list.size(); j++) { org.apache.lucene.analysis.Token test = list.get(j); if ((test.startOffset() <= i) && (i < test.endOffset())) { found = true; break; } } if (found) { break; } else { post.append(c); } } else { break; } } if (post.length() > 0) { // Add new token followed by * not given by the tokeniser org.apache.lucene.analysis.Token newToken = new org.apache.lucene.analysis.Token( post.toString(), index + 1, index + 1 + post.length()); newToken.setType("ALPHANUM"); if (requiresMLTokenDuplication) { Locale locale = I18NUtil.parseLocale(localeString); MLTokenDuplicator duplicator = new MLTokenDuplicator(locale, MLAnalysisMode.EXACT_LANGUAGE); Iterator<org.apache.lucene.analysis.Token> it = duplicator.buildIterator(newToken); if (it != null) { int count = 0; while (it.hasNext()) { list.add(it.next()); count++; if (count > 1) { severalTokensAtSamePosition = true; } } } } // content else { list.add(newToken); } } } } } // Put in real position increments as we treat them correctly int curentIncrement = -1; for (org.apache.lucene.analysis.Token c : list) { if (curentIncrement == -1) { curentIncrement = c.getPositionIncrement(); } else if (c.getPositionIncrement() > 0) { curentIncrement = c.getPositionIncrement(); } else { c.setPositionIncrement(curentIncrement); } } // Remove small bits already covered in larger fragments list = getNonContained(list); Collections.sort(list, new Comparator<org.apache.lucene.analysis.Token>() { public int compare(Token o1, Token o2) { int dif = o1.startOffset() - o2.startOffset(); return dif; } }); // Combined * and ? based strings - should redo the tokeniser // Build tokens by position LinkedList<LinkedList<org.apache.lucene.analysis.Token>> tokensByPosition = new LinkedList<LinkedList<org.apache.lucene.analysis.Token>>(); LinkedList<org.apache.lucene.analysis.Token> currentList = null; int lastStart = 0; for (org.apache.lucene.analysis.Token c : list) { if (c.startOffset() == lastStart) { if (currentList == null) { currentList = new LinkedList<org.apache.lucene.analysis.Token>(); tokensByPosition.add(currentList); } currentList.add(c); } else { currentList = new LinkedList<org.apache.lucene.analysis.Token>(); tokensByPosition.add(currentList); currentList.add(c); } lastStart = c.startOffset(); } // Build all the token sequences and see which ones get strung together OrderedHashSet<LinkedList<org.apache.lucene.analysis.Token>> allTokenSequencesSet = new OrderedHashSet<LinkedList<org.apache.lucene.analysis.Token>>(); for (LinkedList<org.apache.lucene.analysis.Token> tokensAtPosition : tokensByPosition) { OrderedHashSet<LinkedList<org.apache.lucene.analysis.Token>> positionalSynonymSequencesSet = new OrderedHashSet<LinkedList<org.apache.lucene.analysis.Token>>(); OrderedHashSet<LinkedList<org.apache.lucene.analysis.Token>> newAllTokenSequencesSet = new OrderedHashSet<LinkedList<org.apache.lucene.analysis.Token>>(); FOR_FIRST_TOKEN_AT_POSITION_ONLY: for (org.apache.lucene.analysis.Token t : tokensAtPosition) { org.apache.lucene.analysis.Token replace = new org.apache.lucene.analysis.Token(t, t.startOffset(), t.endOffset()); replace.setType(t.type()); replace.setPositionIncrement(t.getPositionIncrement()); boolean tokenFoundSequence = false; for (LinkedList<org.apache.lucene.analysis.Token> tokenSequence : allTokenSequencesSet) { LinkedList<org.apache.lucene.analysis.Token> newEntry = new LinkedList<org.apache.lucene.analysis.Token>(); newEntry.addAll(tokenSequence); if ((newEntry.getLast().endOffset() == replace.endOffset()) && replace.type().equals(SynonymFilter.TYPE_SYNONYM)) { if ((newEntry.getLast().startOffset() == replace.startOffset()) && newEntry.getLast().type().equals(SynonymFilter.TYPE_SYNONYM)) { positionalSynonymSequencesSet.add(tokenSequence); newEntry.add(replace); tokenFoundSequence = true; } else if (newEntry.getLast().type().equals(CommonGramsFilter.GRAM_TYPE)) { if (newEntry.toString().endsWith(replace.toString())) { // already in the gram positionalSynonymSequencesSet.add(tokenSequence); tokenFoundSequence = true; } else { // need to replace the synonym in the current gram tokenFoundSequence = true; StringBuffer old = new StringBuffer(newEntry.getLast().toString()); old.replace(replace.startOffset() - newEntry.getLast().startOffset(), replace.endOffset() - newEntry.getLast().startOffset(), replace.toString()); Token newToken = new org.apache.lucene.analysis.Token(old.toString(), newEntry.getLast().startOffset(), newEntry.getLast().endOffset()); newEntry.removeLast(); newEntry.add(newToken); } } } else if ((newEntry.getLast().startOffset() < replace.startOffset()) && (newEntry.getLast().endOffset() < replace.endOffset())) { if (newEntry.getLast().type().equals(SynonymFilter.TYPE_SYNONYM) && replace.type().equals(SynonymFilter.TYPE_SYNONYM)) { positionalSynonymSequencesSet.add(tokenSequence); } newEntry.add(replace); tokenFoundSequence = true; } newAllTokenSequencesSet.add(newEntry); } if (false == tokenFoundSequence) { for (LinkedList<org.apache.lucene.analysis.Token> tokenSequence : newAllTokenSequencesSet) { LinkedList<org.apache.lucene.analysis.Token> newEntry = new LinkedList<org.apache.lucene.analysis.Token>(); newEntry.addAll(tokenSequence); if ((newEntry.getLast().endOffset() == replace.endOffset()) && replace.type().equals(SynonymFilter.TYPE_SYNONYM)) { if ((newEntry.getLast().startOffset() == replace.startOffset()) && newEntry.getLast().type().equals(SynonymFilter.TYPE_SYNONYM)) { positionalSynonymSequencesSet.add(tokenSequence); newEntry.add(replace); tokenFoundSequence = true; } else if (newEntry.getLast().type().equals(CommonGramsFilter.GRAM_TYPE)) { if (newEntry.toString().endsWith(replace.toString())) { // already in the gram positionalSynonymSequencesSet.add(tokenSequence); tokenFoundSequence = true; } else { // need to replace the synonym in the current gram tokenFoundSequence = true; StringBuffer old = new StringBuffer(newEntry.getLast().toString()); old.replace(replace.startOffset() - newEntry.getLast().startOffset(), replace.endOffset() - newEntry.getLast().startOffset(), replace.toString()); Token newToken = new org.apache.lucene.analysis.Token(old.toString(), newEntry.getLast().startOffset(), newEntry.getLast().endOffset()); newEntry.removeLast(); newEntry.add(newToken); positionalSynonymSequencesSet.add(newEntry); } } } else if ((newEntry.getLast().startOffset() < replace.startOffset()) && (newEntry.getLast().endOffset() < replace.endOffset())) { if (newEntry.getLast().type().equals(SynonymFilter.TYPE_SYNONYM) && replace.type().equals(SynonymFilter.TYPE_SYNONYM)) { positionalSynonymSequencesSet.add(tokenSequence); newEntry.add(replace); tokenFoundSequence = true; } } } } if (false == tokenFoundSequence) { LinkedList<org.apache.lucene.analysis.Token> newEntry = new LinkedList<org.apache.lucene.analysis.Token>(); newEntry.add(replace); newAllTokenSequencesSet.add(newEntry); } // Limit the max number of permutations we consider if (newAllTokenSequencesSet.size() > 64) { break FOR_FIRST_TOKEN_AT_POSITION_ONLY; } } allTokenSequencesSet = newAllTokenSequencesSet; allTokenSequencesSet.addAll(positionalSynonymSequencesSet); } LinkedList<LinkedList<org.apache.lucene.analysis.Token>> allTokenSequences = new LinkedList<LinkedList<org.apache.lucene.analysis.Token>>( allTokenSequencesSet); // build the unique LinkedList<LinkedList<org.apache.lucene.analysis.Token>> fixedTokenSequences = new LinkedList<LinkedList<org.apache.lucene.analysis.Token>>(); for (LinkedList<org.apache.lucene.analysis.Token> tokenSequence : allTokenSequences) { LinkedList<org.apache.lucene.analysis.Token> fixedTokenSequence = new LinkedList<org.apache.lucene.analysis.Token>(); fixedTokenSequences.add(fixedTokenSequence); org.apache.lucene.analysis.Token replace = null; for (org.apache.lucene.analysis.Token c : tokenSequence) { if (replace == null) { StringBuilder prefix = new StringBuilder(); for (int i = c.startOffset() - 1; i >= 0; i--) { char test = testText.charAt(i); if (((test == '*') || (test == '?')) && wildcardPoistions.contains(i)) { prefix.insert(0, test); } else { break; } } String pre = prefix.toString(); if (requiresMLTokenDuplication) { String termText = c.toString(); int position = termText.indexOf("}"); String language = termText.substring(0, position + 1); String token = termText.substring(position + 1); replace = new org.apache.lucene.analysis.Token(language + pre + token, c.startOffset() - pre.length(), c.endOffset()); replace.setType(c.type()); replace.setPositionIncrement(c.getPositionIncrement()); } else { String termText = c.toString(); replace = new org.apache.lucene.analysis.Token(pre + termText, c.startOffset() - pre.length(), c.endOffset()); replace.setType(c.type()); replace.setPositionIncrement(c.getPositionIncrement()); } } else { StringBuilder prefix = new StringBuilder(); StringBuilder postfix = new StringBuilder(); StringBuilder builder = prefix; for (int i = c.startOffset() - 1; i >= replace.endOffset(); i--) { char test = testText.charAt(i); if (((test == '*') || (test == '?')) && wildcardPoistions.contains(i)) { builder.insert(0, test); } else { builder = postfix; postfix.setLength(0); } } String pre = prefix.toString(); String post = postfix.toString(); // Does it bridge? if ((pre.length() > 0) && (replace.endOffset() + pre.length()) == c.startOffset()) { String termText = c.toString(); if (requiresMLTokenDuplication) { int position = termText.indexOf("}"); @SuppressWarnings("unused") String language = termText.substring(0, position + 1); String token = termText.substring(position + 1); int oldPositionIncrement = replace.getPositionIncrement(); String replaceTermText = replace.toString(); replace = new org.apache.lucene.analysis.Token(replaceTermText + pre + token, replace.startOffset(), c.endOffset()); replace.setType(replace.type()); replace.setPositionIncrement(oldPositionIncrement); } else { int oldPositionIncrement = replace.getPositionIncrement(); String replaceTermText = replace.toString(); replace = new org.apache.lucene.analysis.Token(replaceTermText + pre + termText, replace.startOffset(), c.endOffset()); replace.setType(replace.type()); replace.setPositionIncrement(oldPositionIncrement); } } else { String termText = c.toString(); if (requiresMLTokenDuplication) { int position = termText.indexOf("}"); String language = termText.substring(0, position + 1); String token = termText.substring(position + 1); String replaceTermText = replace.toString(); org.apache.lucene.analysis.Token last = new org.apache.lucene.analysis.Token( replaceTermText + post, replace.startOffset(), replace.endOffset() + post.length()); last.setType(replace.type()); last.setPositionIncrement(replace.getPositionIncrement()); fixedTokenSequence.add(last); replace = new org.apache.lucene.analysis.Token(language + pre + token, c.startOffset() - pre.length(), c.endOffset()); replace.setType(c.type()); replace.setPositionIncrement(c.getPositionIncrement()); } else { String replaceTermText = replace.toString(); org.apache.lucene.analysis.Token last = new org.apache.lucene.analysis.Token( replaceTermText + post, replace.startOffset(), replace.endOffset() + post.length()); last.setType(replace.type()); last.setPositionIncrement(replace.getPositionIncrement()); fixedTokenSequence.add(last); replace = new org.apache.lucene.analysis.Token(pre + termText, c.startOffset() - pre.length(), c.endOffset()); replace.setType(c.type()); replace.setPositionIncrement(c.getPositionIncrement()); } } } } // finish last if (replace != null) { StringBuilder postfix = new StringBuilder(); if ((replace.endOffset() >= 0) && (replace.endOffset() < testText.length())) { for (int i = replace.endOffset(); i < testText.length(); i++) { char test = testText.charAt(i); if (((test == '*') || (test == '?')) && wildcardPoistions.contains(i)) { postfix.append(test); } else { break; } } } String post = postfix.toString(); int oldPositionIncrement = replace.getPositionIncrement(); String replaceTermText = replace.toString(); replace = new org.apache.lucene.analysis.Token(replaceTermText + post, replace.startOffset(), replace.endOffset() + post.length()); replace.setType(replace.type()); replace.setPositionIncrement(oldPositionIncrement); fixedTokenSequence.add(replace); } } // rebuild fixed list ArrayList<org.apache.lucene.analysis.Token> fixed = new ArrayList<org.apache.lucene.analysis.Token>(); for (LinkedList<org.apache.lucene.analysis.Token> tokenSequence : fixedTokenSequences) { for (org.apache.lucene.analysis.Token token : tokenSequence) { fixed.add(token); } } // reorder by start position and increment Collections.sort(fixed, new Comparator<org.apache.lucene.analysis.Token>() { public int compare(Token o1, Token o2) { int dif = o1.startOffset() - o2.startOffset(); if (dif != 0) { return dif; } else { return o1.getPositionIncrement() - o2.getPositionIncrement(); } } }); // make sure we remove any tokens we have duplicated @SuppressWarnings("rawtypes") OrderedHashSet unique = new OrderedHashSet(); unique.addAll(fixed); fixed = new ArrayList<org.apache.lucene.analysis.Token>(unique); list = fixed; // add any missing locales back to the tokens if (localePrefix.length() > 0) { for (int j = 0; j < list.size(); j++) { org.apache.lucene.analysis.Token currentToken = list.get(j); String termText = currentToken.toString(); currentToken.setEmpty(); currentToken.append(localePrefix + termText); } } SchemaField sf = schema.getField(field); TokenizerChain tokenizerChain = (sf.getType().getQueryAnalyzer() instanceof TokenizerChain) ? ((TokenizerChain) sf.getType().getQueryAnalyzer()) : null; boolean isShingled = false; if (tokenizerChain != null) { for (TokenFilterFactory factory : tokenizerChain.getTokenFilterFactories()) { if (factory instanceof ShingleFilterFactory) { isShingled = true; break; } } } AlfrescoAnalyzerWrapper analyzerWrapper = (sf.getType() .getQueryAnalyzer() instanceof AlfrescoAnalyzerWrapper) ? ((AlfrescoAnalyzerWrapper) sf.getType().getQueryAnalyzer()) : null; if (analyzerWrapper != null) { // assume if there are no term positions it is shingled .... isShingled = true; } boolean forceConjuncion = rerankPhase == RerankPhase.QUERY_PHASE; if (list.size() == 0) return null; else if (list.size() == 1) { nextToken = list.get(0); String termText = nextToken.toString(); if (!isNumeric && (termText.contains("*") || termText.contains("?"))) { return newWildcardQuery(new Term(field, termText)); } else { return newTermQuery(new Term(field, termText)); } } else { if (severalTokensAtSamePosition) { if (positionCount == 1) { // no phrase query: BooleanQuery q = newBooleanQuery(true); for (int i = 0; i < list.size(); i++) { Query currentQuery; nextToken = list.get(i); String termText = nextToken.toString(); if (termText.contains("*") || termText.contains("?")) { currentQuery = newWildcardQuery(new Term(field, termText)); } else { currentQuery = newTermQuery(new Term(field, termText)); } q.add(currentQuery, BooleanClause.Occur.SHOULD); } return q; } else if (forceConjuncion) { BooleanQuery or = new BooleanQuery(); for (LinkedList<org.apache.lucene.analysis.Token> tokenSequence : fixedTokenSequences) { BooleanQuery and = new BooleanQuery(); for (int i = 0; i < tokenSequence.size(); i++) { nextToken = (org.apache.lucene.analysis.Token) tokenSequence.get(i); String termText = nextToken.toString(); Term term = new Term(field, termText); if ((termText != null) && (termText.contains("*") || termText.contains("?"))) { org.apache.lucene.search.WildcardQuery wildQuery = new org.apache.lucene.search.WildcardQuery( term); and.add(wildQuery, Occur.MUST); } else { TermQuery termQuery = new TermQuery(term); and.add(termQuery, Occur.MUST); } } if (and.clauses().size() > 0) { or.add(and, Occur.SHOULD); } } return or; } // shingle else if (sf.omitPositions() && isShingled) { ArrayList<org.apache.lucene.analysis.Token> nonContained = getNonContained(list); Query currentQuery; BooleanQuery weakPhrase = new BooleanQuery(); for (org.apache.lucene.analysis.Token shingleToken : nonContained) { String termText = shingleToken.toString(); Term term = new Term(field, termText); if ((termText != null) && (termText.contains("*") || termText.contains("?"))) { currentQuery = new org.apache.lucene.search.WildcardQuery(term); } else { currentQuery = new TermQuery(term); } weakPhrase.add(currentQuery, Occur.MUST); } return weakPhrase; } // Consider if we can use a multi-phrase query (e.g for synonym use rather then WordDelimiterFilterFactory) else if (canUseMultiPhraseQuery(fixedTokenSequences)) { // phrase query: MultiPhraseQuery mpq = newMultiPhraseQuery(); mpq.setSlop(internalSlop); ArrayList<Term> multiTerms = new ArrayList<Term>(); int position = 0; for (int i = 0; i < list.size(); i++) { nextToken = list.get(i); String termText = nextToken.toString(); Term term = new Term(field, termText); if ((termText != null) && (termText.contains("*") || termText.contains("?"))) { throw new IllegalStateException("Wildcards are not allowed in multi phrase anymore"); } else { multiTerms.add(term); } if (nextToken.getPositionIncrement() > 0 && multiTerms.size() > 0) { if (getEnablePositionIncrements()) { mpq.add(multiTerms.toArray(new Term[0]), position); } else { mpq.add(multiTerms.toArray(new Term[0])); } checkTermCount(field, queryText, mpq); multiTerms.clear(); } position += nextToken.getPositionIncrement(); } if (getEnablePositionIncrements()) { if (multiTerms.size() > 0) { mpq.add(multiTerms.toArray(new Term[0]), position); } // else // { // mpq.add(new Term[] { new Term(field, "\u0000") }, position); // } } else { if (multiTerms.size() > 0) { mpq.add(multiTerms.toArray(new Term[0])); } // else // { // mpq.add(new Term[] { new Term(field, "\u0000") }); // } } checkTermCount(field, queryText, mpq); return mpq; } // Word delimiter factory and other odd things generate complex token patterns // Smart skip token sequences with small tokens that generate toomany wildcards // Fall back to the larger pattern // e.g Site1* will not do (S ite 1*) or (Site 1*) if 1* matches too much (S ite1*) and (Site1*) will still be OK // If we skip all (for just 1* in the input) this is still an issue. else { return generateSpanOrQuery(field, fixedTokenSequences); } } else { if (forceConjuncion) { BooleanQuery or = new BooleanQuery(); for (LinkedList<org.apache.lucene.analysis.Token> tokenSequence : fixedTokenSequences) { BooleanQuery and = new BooleanQuery(); for (int i = 0; i < tokenSequence.size(); i++) { nextToken = (org.apache.lucene.analysis.Token) tokenSequence.get(i); String termText = nextToken.toString(); Term term = new Term(field, termText); if ((termText != null) && (termText.contains("*") || termText.contains("?"))) { org.apache.lucene.search.WildcardQuery wildQuery = new org.apache.lucene.search.WildcardQuery( term); and.add(wildQuery, Occur.MUST); } else { TermQuery termQuery = new TermQuery(term); and.add(termQuery, Occur.MUST); } } if (and.clauses().size() > 0) { or.add(and, Occur.SHOULD); } } return or; } else { SpanQuery spanQuery = null; SpanOrQuery atSamePosition = new SpanOrQuery(); int gap = 0; for (int i = 0; i < list.size(); i++) { nextToken = list.get(i); String termText = nextToken.toString(); Term term = new Term(field, termText); if (getEnablePositionIncrements()) { SpanQuery nextSpanQuery; if ((termText != null) && (termText.contains("*") || termText.contains("?"))) { org.apache.lucene.search.WildcardQuery wildQuery = new org.apache.lucene.search.WildcardQuery( term); SpanMultiTermQueryWrapper wrapper = new SpanMultiTermQueryWrapper<>(wildQuery); wrapper.setRewriteMethod( new TopTermsSpanBooleanQueryRewrite(topTermSpanRewriteLimit)); nextSpanQuery = wrapper; } else { nextSpanQuery = new SpanTermQuery(term); } if (gap == 0) { atSamePosition.addClause(nextSpanQuery); } else { if (atSamePosition.getClauses().length == 0) { if (spanQuery == null) { spanQuery = nextSpanQuery; } else { spanQuery = new SpanNearQuery(new SpanQuery[] { spanQuery, nextSpanQuery }, (gap - 1) + internalSlop, internalSlop < 2); } atSamePosition = new SpanOrQuery(); } else if (atSamePosition.getClauses().length == 1) { if (spanQuery == null) { spanQuery = atSamePosition.getClauses()[0]; } else { spanQuery = new SpanNearQuery( new SpanQuery[] { spanQuery, atSamePosition.getClauses()[0] }, (gap - 1) + internalSlop, internalSlop < 2); } atSamePosition = new SpanOrQuery(); atSamePosition.addClause(nextSpanQuery); } else { if (spanQuery == null) { spanQuery = atSamePosition; } else { spanQuery = new SpanNearQuery(new SpanQuery[] { spanQuery, atSamePosition }, (gap - 1) + internalSlop, internalSlop < 2); } atSamePosition = new SpanOrQuery(); atSamePosition.addClause(nextSpanQuery); } } gap = nextToken.getPositionIncrement(); } else { SpanQuery nextSpanQuery; if ((termText != null) && (termText.contains("*") || termText.contains("?"))) { org.apache.lucene.search.WildcardQuery wildQuery = new org.apache.lucene.search.WildcardQuery( term); SpanMultiTermQueryWrapper wrapper = new SpanMultiTermQueryWrapper<>(wildQuery); wrapper.setRewriteMethod( new TopTermsSpanBooleanQueryRewrite(topTermSpanRewriteLimit)); nextSpanQuery = wrapper; } else { nextSpanQuery = new SpanTermQuery(term); } if (spanQuery == null) { spanQuery = new SpanOrQuery(); ((SpanOrQuery) spanQuery).addClause(nextSpanQuery); } else { ((SpanOrQuery) spanQuery).addClause(nextSpanQuery); } } } if (atSamePosition.getClauses().length == 0) { return spanQuery; } else if (atSamePosition.getClauses().length == 1) { if (spanQuery == null) { spanQuery = atSamePosition.getClauses()[0]; } else { spanQuery = new SpanNearQuery( new SpanQuery[] { spanQuery, atSamePosition.getClauses()[0] }, (gap - 1) + internalSlop, internalSlop < 2); } return spanQuery; } else { if (spanQuery == null) { spanQuery = atSamePosition; } else { spanQuery = new SpanNearQuery(new SpanQuery[] { spanQuery, atSamePosition }, (gap - 1) + internalSlop, internalSlop < 2); } return spanQuery; } } } } }
From source file:org.jahia.services.content.JCRNodeWrapperImpl.java
@Override public Node getI18N(Locale locale, boolean fallback) throws RepositoryException { //getSession().getLocale() if (i18NobjectNodes == null) { i18NobjectNodes = new HashMap<Locale, Node>(); }// w ww . j a va2 s. co m Node node; if (i18NobjectNodes.containsKey(locale)) { node = i18NobjectNodes.get(locale); if (node != null) { return node; } } else { final String translationNodeName = getTranslationNodeName(locale); if (objectNode.hasNode(translationNodeName)) { node = objectNode.getNode(translationNodeName); if (!Constants.LIVE_WORKSPACE.equals(session.getWorkspace().getName()) || !node.hasProperty(Constants.PUBLISHED) || node.getProperty(Constants.PUBLISHED).getBoolean()) { i18NobjectNodes.put(locale, node); return node; } } } if (fallback) { final Locale fallbackLocale = getSession().getFallbackLocale(); if (fallbackLocale != null && fallbackLocale != locale) { return getI18N(fallbackLocale); } } throw new ItemNotFoundException(locale.toString()); }
From source file:com.aurel.track.report.dashboard.AverageTimeToCloseItem.java
@Override protected String encodeJSONExtraData(Integer dashboardID, Map<String, Object> session, Map<String, String> parameters, Integer projectID, Integer releaseID, Map<String, String> ajaxParams) throws TooManyItemsToLoadException { TPersonBean user = (TPersonBean) session.get(Constants.USER_KEY); Locale locale = user.getLocale(); DashboardDescriptor dashboardDescriptor = getDescriptor(); String bundleName = dashboardDescriptor.getBundleName(); StringBuilder sb = new StringBuilder(); String sessionPrefix = "dashboard" + "." + dashboardID; //the name where configParameters are stored String theParams = sessionPrefix + "Params"; //to avoid caching if IE String userEnteredTitle = parameters.get("title"); if (userEnteredTitle == null || "".equals(userEnteredTitle.trim())) { userEnteredTitle = "burnDownChart.label"; }//from w w w . j av a2s . com int height = parseInteger(parameters, CONFIGURATION_PARAMETERS.Y_AXE, DEFAULT_HEIGHT); Map<String, Object> configParameters = new HashMap<String, Object>(); Iterator<String> it = parameters.keySet().iterator(); while (it.hasNext()) { String key = it.next(); configParameters.put(key, parameters.get(key)); } //used in preparing the locale specific chart configParameters.put("locale", locale); configParameters.put("personBean", user); configParameters.put("projectID", projectID); configParameters.put("releaseID", releaseID); session.put(theParams, configParameters); JSONUtility.appendIntegerValue(sb, "height", height); dateTo = null; dateFrom = null; if ((configParameters.get("dateTo") != null && configParameters.get("dateTo") != null && !configParameters.get("dateTo").equals("null") && !configParameters.get("dateFrom").equals("null")) || (configParameters.get("daysBefore") != null)) { SimpleDateFormat dateFormat; dateFormat = new SimpleDateFormat("yyyy-MM-dd"); if (configParameters.get("daysBefore") != null) { Calendar calendar = Calendar.getInstance(); int daysBefore = BasePluginDashboardBL.parseIntegerValue(configParameters, TIMEPERIOD_PARAMETERS.DAYS_BEFORE, 0); dateTo = calendar.getTime(); dateFrom = calendar.getTime(); if (daysBefore != 0) { calendar.add(Calendar.DATE, -daysBefore); dateFrom = calendar.getTime(); } } else { try { dateFrom = dateFormat.parse(configParameters.get("dateFrom").toString()); dateTo = dateFormat.parse(configParameters.get("dateTo").toString()); } catch (Exception ex) { LOGGER.error(ExceptionUtils.getStackTrace(ex), ex); } } JSONUtility.appendStringValue(sb, "dateTo", dateFormat.format(dateTo).toString()); JSONUtility.appendStringValue(sb, "dateFrom", dateFormat.format(dateFrom).toString()); String chartData = generateJSONResponse(configParameters, user, locale); boolean chartDataIsEmpty = false; if (chartData == null || "[]".equals(chartData)) { chartData = "[]"; chartDataIsEmpty = true; } JSONUtility.appendJSONValue(sb, "chartData", chartData); JSONUtility.appendBooleanValue(sb, "empty", chartDataIsEmpty); String xAxesLabel = ""; if (Integer .parseInt(configParameters.get("reportingInterval").toString()) == REPORTING_INTERVAL.WEEKLY) { xAxesLabel = LocalizeUtil.getLocalizedText("burnDownChart.xAxesLabelWeekly", locale, bundleName); } else { xAxesLabel = LocalizeUtil.getLocalizedText("burnDownChart.xAxesLabel", locale, bundleName); } int selectedTimeFormat = parseIntegerValue(configParameters, CONFIGURATION_PARAMETERS.TIME_FORMAT, 0); String yAxesLabel = ""; if (selectedTimeFormat == TIME_FORMAT.WORKING_DAY) { yAxesLabel = LocalizeUtil.getLocalizedText("averageTimeToCloseItem.yAxesLabel.working.day", locale, bundleName); } else { yAxesLabel = LocalizeUtil.getLocalizedText("averageTimeToCloseItem.yAxesLabel.working.hours", locale, bundleName); } JSONUtility.appendStringValue(sb, "xAxesLabel", xAxesLabel); JSONUtility.appendStringValue(sb, "yAxesLabel", yAxesLabel); JSONUtility.appendStringValue(sb, "reportingInterval", configParameters.get("reportingInterval").toString()); JSONUtility.appendStringValue(sb, "locale", locale.toString()); } else { JSONUtility.appendBooleanValue(sb, "empty", true); LOGGER.debug("Burn-Down Chart not configured yet!"); } return sb.toString(); }
From source file:com.aurel.track.report.dashboard.BurnDownChart.java
@Override protected String encodeJSONExtraData(Integer dashboardID, Map<String, Object> session, Map<String, String> parameters, Integer projectID, Integer releaseID, Map<String, String> ajaxParams) throws TooManyItemsToLoadException { TPersonBean user = (TPersonBean) session.get(Constants.USER_KEY); Locale locale = user.getLocale(); DashboardDescriptor dashboardDescriptor = getDescriptor(); String bundleName = dashboardDescriptor.getBundleName(); StringBuilder sb = new StringBuilder(); String sessionPrefix = "dashboard" + "." + dashboardID; //the name where configParameters are stored String theParams = sessionPrefix + "Params"; //to avoid caching if IE String userEnteredTitle = parameters.get("title"); if (userEnteredTitle == null || "".equals(userEnteredTitle.trim())) { userEnteredTitle = "burnDownChart.label"; }/* ww w. jav a 2s. com*/ int height = parseInteger(parameters, CONFIGURATION_PARAMETERS.Y_AXE, DEFAULT_HEIGHT); Map<String, Object> configParameters = new HashMap<String, Object>(); Iterator<String> it = parameters.keySet().iterator(); while (it.hasNext()) { String key = it.next(); configParameters.put(key, parameters.get(key)); } //used in preparing the locale specific chart configParameters.put("locale", locale); configParameters.put("personBean", user); configParameters.put("projectID", projectID); configParameters.put("releaseID", releaseID); session.put(theParams, configParameters); JSONUtility.appendIntegerValue(sb, "height", height); dateTo = null; dateFrom = null; if ((configParameters.get("dateTo") != null && configParameters.get("dateTo") != null && !configParameters.get("dateTo").equals("null") && !configParameters.get("dateFrom").equals("null")) || (configParameters.get("daysBefore") != null)) { SimpleDateFormat dateFormat; dateFormat = new SimpleDateFormat("yyyy-MM-dd"); if (configParameters.get("daysBefore") != null) { Calendar calendar = Calendar.getInstance(); int daysBefore = BasePluginDashboardBL.parseIntegerValue(configParameters, TIMEPERIOD_PARAMETERS.DAYS_BEFORE, 0); dateTo = calendar.getTime(); dateFrom = calendar.getTime(); if (daysBefore != 0) { calendar.add(Calendar.DATE, -daysBefore); dateFrom = calendar.getTime(); } } else { try { dateFrom = dateFormat.parse(configParameters.get("dateFrom").toString()); dateTo = dateFormat.parse(configParameters.get("dateTo").toString()); } catch (Exception ex) { LOGGER.error(ExceptionUtils.getStackTrace(ex), ex); } } JSONUtility.appendStringValue(sb, "dateTo", dateFormat.format(dateTo).toString()); JSONUtility.appendStringValue(sb, "dateFrom", dateFormat.format(dateFrom).toString()); String chartData = generateJSONResponse(configParameters, user, locale); boolean chartDataIsEmpty = false; if (chartData == null) { chartData = "[]"; chartDataIsEmpty = true; } JSONUtility.appendJSONValue(sb, "chartData", chartData); JSONUtility.appendBooleanValue(sb, "empty", chartDataIsEmpty); String xAxesLabel = ""; if (Integer .parseInt(configParameters.get("reportingInterval").toString()) == REPORTING_INTERVAL.WEEKLY) { xAxesLabel = LocalizeUtil.getLocalizedText("burnDownChart.xAxesLabelWeekly", locale, bundleName); } else { xAxesLabel = LocalizeUtil.getLocalizedText("burnDownChart.xAxesLabel", locale, bundleName); } Integer selectedEffortType = Integer .parseInt(parameters.get(CONFIGURATION_PARAMETERS.EFFORT_TYPE).toString()); customFieldIDForStoryPoint = parseInteger(parameters, CONFIGURATION_PARAMETERS.CUSTOM_FIELD_FOR_STORY_POINT, -1); String yAxesLabel = ""; if (selectedEffortType == EFFORT_TYPE.NR_OF_ITEMS_IN_INTERVAL) { yAxesLabel = LocalizeUtil.getLocalizedText("burnDownChart.yAxesLabel.no.of.item", locale, bundleName); } else if (selectedEffortType == EFFORT_TYPE.STORY_POINTS) { yAxesLabel = LocalizeUtil.getLocalizedText("burnDownChart.yAxesLabel.story.point", locale, bundleName); } else if (selectedEffortType == EFFORT_TYPE.TIME) { yAxesLabel = LocalizeUtil.getLocalizedText("burnDownChart.yAxesLabel.effort", locale, bundleName); } JSONUtility.appendIntegerValue(sb, CONFIGURATION_PARAMETERS.SELECTED_EFFORT_TYPE, selectedEffortType); JSONUtility.appendIntegerValue(sb, CONFIGURATION_PARAMETERS.SELECTED_CUSTOM_FIELD_FOR_STORY_POINT, customFieldIDForStoryPoint); JSONUtility.appendStringValue(sb, "xAxesLabel", xAxesLabel); JSONUtility.appendStringValue(sb, "yAxesLabel", yAxesLabel); JSONUtility.appendStringValue(sb, "reportingInterval", configParameters.get("reportingInterval").toString()); JSONUtility.appendStringValue(sb, "locale", locale.toString()); } else { JSONUtility.appendBooleanValue(sb, "empty", true); LOGGER.debug("Burn-Down Chart not configured yet!"); } return sb.toString(); }
From source file:org.apache.maven.plugin.javadoc.AbstractJavadocMojo.java
/** * Checks for the validity of the Javadoc options used by the user. * * @throws MavenReportException if error */// w w w. j a v a2 s . c o m private void validateJavadocOptions() throws MavenReportException { // encoding if (StringUtils.isNotEmpty(getEncoding()) && !JavadocUtil.validateEncoding(getEncoding())) { throw new MavenReportException("Unsupported option <encoding/> '" + getEncoding() + "'"); } // locale if (StringUtils.isNotEmpty(this.locale)) { StringTokenizer tokenizer = new StringTokenizer(this.locale, "_"); final int maxTokens = 3; if (tokenizer.countTokens() > maxTokens) { throw new MavenReportException( "Unsupported option <locale/> '" + this.locale + "', should be language_country_variant."); } Locale localeObject = null; if (tokenizer.hasMoreTokens()) { String language = tokenizer.nextToken().toLowerCase(Locale.ENGLISH); if (!Arrays.asList(Locale.getISOLanguages()).contains(language)) { throw new MavenReportException( "Unsupported language '" + language + "' in option <locale/> '" + this.locale + "'"); } localeObject = new Locale(language); if (tokenizer.hasMoreTokens()) { String country = tokenizer.nextToken().toUpperCase(Locale.ENGLISH); if (!Arrays.asList(Locale.getISOCountries()).contains(country)) { throw new MavenReportException( "Unsupported country '" + country + "' in option <locale/> '" + this.locale + "'"); } localeObject = new Locale(language, country); if (tokenizer.hasMoreTokens()) { String variant = tokenizer.nextToken(); localeObject = new Locale(language, country, variant); } } } if (localeObject == null) { throw new MavenReportException( "Unsupported option <locale/> '" + this.locale + "', should be language_country_variant."); } this.locale = localeObject.toString(); final List<Locale> availableLocalesList = Arrays.asList(Locale.getAvailableLocales()); if (StringUtils.isNotEmpty(localeObject.getVariant()) && !availableLocalesList.contains(localeObject)) { StringBuilder sb = new StringBuilder(); sb.append("Unsupported option <locale/> with variant '").append(this.locale); sb.append("'"); localeObject = new Locale(localeObject.getLanguage(), localeObject.getCountry()); this.locale = localeObject.toString(); sb.append(", trying to use <locale/> without variant, i.e. '").append(this.locale).append("'"); if (getLog().isWarnEnabled()) { getLog().warn(sb.toString()); } } if (!availableLocalesList.contains(localeObject)) { throw new MavenReportException("Unsupported option <locale/> '" + this.locale + "'"); } } }
From source file:com.aurel.track.report.dashboard.StatusOverTimeGraph.java
@Override protected String encodeJSONExtraData(Integer dashboardID, Map<String, Object> session, Map<String, String> parameters, Integer projectID, Integer releaseID, Map<String, String> ajaxParams) throws TooManyItemsToLoadException { TPersonBean user = (TPersonBean) session.get(Constants.USER_KEY); Locale locale = user.getLocale(); DashboardDescriptor dashboardDescriptor = getDescriptor(); String bundleName = dashboardDescriptor.getBundleName(); StringBuilder sb = new StringBuilder(); String sessionPrefix = "dashboard" + "." + dashboardID; //the name where the ImageProvider implementation is stored in the session String theProvider = sessionPrefix; //the name where configParameters are stored String theParams = sessionPrefix + "Params"; //to avoid caching if IE Long actualTime = new Long(new Date().getTime()); Integer selectedCalculationMode = parseInteger(parameters, CONFIGURATION_PARAMETERS.SELECTED_CALCULATION_MODE, CALCULATION_MODE.NEW); //for ftl//from w ww .j a va 2s . co m String userEnteredTitle = parameters.get("title"); if (userEnteredTitle == null || "".equals(userEnteredTitle.trim())) { //title="statusOverTime.title." + getCalculationModeSuffix(selectedCalculationMode)); } // int width=BasePluginDashboardBL.parseIntegerValue(parameters, CONFIGURATION_PARAMETERS.X_AXE, DEFAULT_WIDTH); int height = parseInteger(parameters, CONFIGURATION_PARAMETERS.Y_AXE, DEFAULT_HEIGHT); Map<String, Object> configParameters = new HashMap<String, Object>(); Iterator<String> it = parameters.keySet().iterator(); while (it.hasNext()) { String key = it.next(); configParameters.put(key, parameters.get(key)); } //used in preparing the locale specific chart configParameters.put("locale", locale); configParameters.put("personBean", user); configParameters.put("projectID", projectID); configParameters.put("releaseID", releaseID); configParameters.put(SESSION_PARAMETERS.PROVIDER_LINK, theProvider); configParameters.put(SESSION_PARAMETERS.PROVIDER_PARAMS, theParams); //to avoid caching if IE configParameters.put("actualTime", new Long(new Date().getTime())); // configParameters.put("width",width); configParameters.put("height", height); //save the theProvider ImageProvider and the configParameters map into the session //they will be used in the .ftl to call the corresponding image provider action session.put(theProvider, this); session.put(theParams, configParameters); String url = "imageServerAction!loadJSON.action?imageProviderKey=" + theProvider + "&imageProviderParams=" + theParams + "&date=" + actualTime; JSONUtility.appendStringValue(sb, "url", url); // JSONUtility.appendIntegerValue(sb, "width",width); JSONUtility.appendIntegerValue(sb, "height", height); if ((configParameters.get("dateTo") != null && configParameters.get("dateTo") != null && !configParameters.get("dateTo").equals("null") && !configParameters.get("dateFrom").equals("null")) || (configParameters.get("daysBefore") != null)) { JSONUtility.appendBooleanValue(sb, "empty", false); String JSONResponse = generateJSONResponse(configParameters); JSONUtility.appendJSONValue(sb, "chartData", JSONResponse); if (configParameters.get("daysBefore") != null) { SimpleDateFormat dateFormat; dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Calendar calendar = Calendar.getInstance(); int daysBefore = BasePluginDashboardBL.parseIntegerValue(configParameters, TIMEPERIOD_PARAMETERS.DAYS_BEFORE, 0); Date dateTo = calendar.getTime(); Date dateFrom = calendar.getTime(); if (daysBefore != 0) { calendar.add(Calendar.DATE, -daysBefore); dateFrom = calendar.getTime(); } JSONUtility.appendStringValue(sb, "dateTo", dateFormat.format(dateTo).toString()); JSONUtility.appendStringValue(sb, "dateFrom", dateFormat.format(dateFrom).toString()); } else { JSONUtility.appendStringValue(sb, "dateTo", configParameters.get("dateTo").toString()); JSONUtility.appendStringValue(sb, "dateFrom", configParameters.get("dateFrom").toString()); } String xAxesLabel = ""; if (configParameters.get("selectedTimeInterval").toString().equals("2")) { xAxesLabel = LocalizeUtil.getLocalizedText("statusOverTime.xAxesLabelMonthly", locale, bundleName); } else { xAxesLabel = LocalizeUtil.getLocalizedText("statusOverTime.xAxesLabel", locale, bundleName); } String yAxesLabel = LocalizeUtil.getLocalizedText( "statusOverTime.yAxesLabel." + getCalculationModeSuffix(selectedCalculationMode), locale, bundleName); JSONUtility.appendStringValue(sb, "xAxesLabel", xAxesLabel); JSONUtility.appendStringValue(sb, "yAxesLabel", yAxesLabel); JSONUtility.appendStringValue(sb, "selectedTimeInterval", configParameters.get("selectedTimeInterval").toString()); JSONUtility.appendStringValue(sb, "locale", locale.toString()); if (configParameters.get("selectedStatus") != null) { JSONUtility.appendStringValue(sb, "selectedStatus", configParameters.get("selectedStatus").toString()); } if (configParameters.get("selectedStatusSecond") != null) { JSONUtility.appendStringValue(sb, "selectedStatusSecond", configParameters.get("selectedStatusSecond").toString()); } if (configParameters.get("selectedStatusThird") != null) { JSONUtility.appendStringValue(sb, "selectedStatusThird", configParameters.get("selectedStatusThird").toString()); } JSONUtility.appendILabelBeanList(sb, CONFIGURATION_PARAMETERS.STATUSES, StatusBL.loadAll(locale)); LOGGER.debug(("Status over time config parameters: " + configParameters.toString())); LOGGER.debug(("Status over time JSON Response: " + JSONResponse)); } else { JSONUtility.appendBooleanValue(sb, "empty", true); LOGGER.debug("Status over time chart not configured yet!"); } JSONUtility.appendIntegerValue(sb, CONFIGURATION_PARAMETERS.SELECTED_CHART_TYPE, parseInteger(parameters, CONFIGURATION_PARAMETERS.SELECTED_CHART_TYPE, CHART_TYPE.LINE)); if (parameters.get(CONFIGURATION_PARAMETERS.FILLED) != null) { JSONUtility.appendBooleanValue(sb, CONFIGURATION_PARAMETERS.FILLED, true); } else { JSONUtility.appendBooleanValue(sb, CONFIGURATION_PARAMETERS.FILLED, false); } if (parameters.get(CONFIGURATION_PARAMETERS.GROUPING) != null) { JSONUtility.appendBooleanValue(sb, CONFIGURATION_PARAMETERS.GROUPING, true); } else { JSONUtility.appendBooleanValue(sb, CONFIGURATION_PARAMETERS.GROUPING, false); } if (parameters.get(CONFIGURATION_PARAMETERS.GROUP_FIRST_NAME) != null) { JSONUtility.appendStringValue(sb, CONFIGURATION_PARAMETERS.GROUP_FIRST_NAME, configParameters.get(CONFIGURATION_PARAMETERS.GROUP_FIRST_NAME).toString()); } if (parameters.get(CONFIGURATION_PARAMETERS.GROUP_SECOND_NAME) != null) { JSONUtility.appendStringValue(sb, CONFIGURATION_PARAMETERS.GROUP_SECOND_NAME, configParameters.get(CONFIGURATION_PARAMETERS.GROUP_SECOND_NAME).toString()); } if (parameters.get(CONFIGURATION_PARAMETERS.GROUP_THIRD_NAME) != null) { JSONUtility.appendStringValue(sb, CONFIGURATION_PARAMETERS.GROUP_THIRD_NAME, configParameters.get(CONFIGURATION_PARAMETERS.GROUP_THIRD_NAME).toString()); } return sb.toString(); }
From source file:com.liferay.portal.service.impl.UserLocalServiceImpl.java
/** * Updates a user account that was automatically created when a guest user * participated in an action (e.g. posting a comment) and only provided his * name and email address.//from w w w . j av a 2 s. c om * * @param creatorUserId the primary key of the creator * @param companyId the primary key of the user's company * @param autoPassword whether a password should be automatically generated * for the user * @param password1 the user's password * @param password2 the user's password confirmation * @param autoScreenName whether a screen name should be automatically * generated for the user * @param screenName the user's screen name * @param emailAddress the user's email address * @param facebookId the user's facebook ID * @param openId the user's OpenID * @param locale the user's locale * @param firstName the user's first name * @param middleName the user's middle name * @param lastName the user's last name * @param prefixId the user's name prefix ID * @param suffixId the user's name suffix ID * @param male whether the user is male * @param birthdayMonth the user's birthday month (0-based, meaning 0 for * January) * @param birthdayDay the user's birthday day * @param birthdayYear the user's birthday year * @param jobTitle the user's job title * @param updateUserInformation whether to update the user's information * @param sendEmail whether to send the user an email notification about * their new account * @param serviceContext the user's service context (optionally * <code>null</code>). Can set expando bridge attributes for the * user. * @return the user * @throws PortalException if the user's information was invalid * @throws SystemException if a system exception occurred */ public User updateIncompleteUser(long creatorUserId, long companyId, boolean autoPassword, String password1, String password2, boolean autoScreenName, String screenName, String emailAddress, long facebookId, String openId, Locale locale, String firstName, String middleName, String lastName, int prefixId, int suffixId, boolean male, int birthdayMonth, int birthdayDay, int birthdayYear, String jobTitle, boolean updateUserInformation, boolean sendEmail, ServiceContext serviceContext) throws PortalException, SystemException { User user = getUserByEmailAddress(companyId, emailAddress); if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) { throw new PortalException("Invalid user status"); } User defaultUser = getDefaultUser(companyId); if (updateUserInformation) { autoScreenName = false; if (PrefsPropsUtil.getBoolean(companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) { autoScreenName = true; } validate(companyId, user.getUserId(), autoPassword, password1, password2, autoScreenName, screenName, emailAddress, firstName, middleName, lastName, null); if (!autoPassword) { if (Validator.isNull(password1) || Validator.isNull(password2)) { throw new UserPasswordException(UserPasswordException.PASSWORD_INVALID); } } if (autoScreenName) { ScreenNameGenerator screenNameGenerator = ScreenNameGeneratorFactory.getInstance(); try { screenName = screenNameGenerator.generate(companyId, user.getUserId(), emailAddress); } catch (Exception e) { throw new SystemException(e); } } FullNameGenerator fullNameGenerator = FullNameGeneratorFactory.getInstance(); String fullName = fullNameGenerator.getFullName(firstName, middleName, lastName); String greeting = LanguageUtil.format(locale, "welcome-x", " " + fullName, false); if (Validator.isNotNull(password1)) { user.setPassword(PwdEncryptor.encrypt(password1)); user.setPasswordUnencrypted(password1); } user.setPasswordEncrypted(true); PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy(); if (passwordPolicy.isChangeable() && passwordPolicy.isChangeRequired()) { user.setPasswordReset(true); } else { user.setPasswordReset(false); } user.setScreenName(screenName); user.setFacebookId(facebookId); user.setOpenId(openId); user.setLanguageId(locale.toString()); user.setTimeZoneId(defaultUser.getTimeZoneId()); user.setGreeting(greeting); user.setFirstName(firstName); user.setMiddleName(middleName); user.setLastName(lastName); user.setJobTitle(jobTitle); user.setExpandoBridgeAttributes(serviceContext); Date birthday = PortalUtil.getDate(birthdayMonth, birthdayDay, birthdayYear, ContactBirthdayException.class); Contact contact = user.getContact(); contact.setFirstName(firstName); contact.setMiddleName(middleName); contact.setLastName(lastName); contact.setPrefixId(prefixId); contact.setSuffixId(suffixId); contact.setMale(male); contact.setBirthday(birthday); contact.setJobTitle(jobTitle); contactPersistence.update(contact, false, serviceContext); // Indexer Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class); indexer.reindex(user); } user.setStatus(WorkflowConstants.STATUS_DRAFT); userPersistence.update(user, false, serviceContext); // Workflow long workflowUserId = creatorUserId; if (workflowUserId == user.getUserId()) { workflowUserId = defaultUser.getUserId(); } ServiceContext workflowServiceContext = serviceContext; if (workflowServiceContext == null) { workflowServiceContext = new ServiceContext(); } workflowServiceContext.setAttribute("autoPassword", autoPassword); workflowServiceContext.setAttribute("sendEmail", sendEmail); WorkflowHandlerRegistryUtil.startWorkflowInstance(companyId, workflowUserId, User.class.getName(), user.getUserId(), user, workflowServiceContext); return getUserByEmailAddress(companyId, emailAddress); }
From source file:com.liferay.portal.service.impl.UserLocalServiceImpl.java
/** * Adds a user with workflow.// ww w. j a v a 2 s . c om * * <p> * This method handles the creation and bookkeeping of the user including * its resources, metadata, and internal data structures. It is not * necessary to make subsequent calls to any methods to setup default * groups, resources, etc. * </p> * * @param creatorUserId the primary key of the creator * @param companyId the primary key of the user's company * @param autoPassword whether a password should be automatically generated * for the user * @param password1 the user's password * @param password2 the user's password confirmation * @param autoScreenName whether a screen name should be automatically * generated for the user * @param screenName the user's screen name * @param emailAddress the user's email address * @param facebookId the user's facebook ID * @param openId the user's OpenID * @param locale the user's locale * @param firstName the user's first name * @param middleName the user's middle name * @param lastName the user's last name * @param prefixId the user's name prefix ID * @param suffixId the user's name suffix ID * @param male whether the user is male * @param birthdayMonth the user's birthday month (0-based, meaning 0 for * January) * @param birthdayDay the user's birthday day * @param birthdayYear the user's birthday year * @param jobTitle the user's job title * @param groupIds the primary keys of the user's groups * @param organizationIds the primary keys of the user's organizations * @param roleIds the primary keys of the roles this user possesses * @param userGroupIds the primary keys of the user's user groups * @param sendEmail whether to send the user an email notification about * their new account * @param serviceContext the user's service context (optionally * <code>null</code>). Can set the universally unique identifier * (with the <code>uuid</code> attribute), asset category IDs, asset * tag names, and expando bridge attributes for the user. * @return the new user * @throws PortalException if the user's information was invalid * @throws SystemException if a system exception occurred */ @SuppressWarnings("deprecation") public User addUserWithWorkflow(long creatorUserId, long companyId, boolean autoPassword, String password1, String password2, boolean autoScreenName, String screenName, String emailAddress, long facebookId, String openId, Locale locale, String firstName, String middleName, String lastName, int prefixId, int suffixId, boolean male, int birthdayMonth, int birthdayDay, int birthdayYear, String jobTitle, long[] groupIds, long[] organizationIds, long[] roleIds, long[] userGroupIds, boolean sendEmail, ServiceContext serviceContext) throws PortalException, SystemException { // User Company company = companyPersistence.findByPrimaryKey(companyId); screenName = getScreenName(screenName); emailAddress = emailAddress.trim().toLowerCase(); openId = openId.trim(); Date now = new Date(); if (PrefsPropsUtil.getBoolean(companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) { autoScreenName = true; } long userId = counterLocalService.increment(); EmailAddressGenerator emailAddressGenerator = EmailAddressGeneratorFactory.getInstance(); if (emailAddressGenerator.isGenerated(emailAddress)) { emailAddress = StringPool.BLANK; } if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED && Validator.isNull(emailAddress)) { emailAddress = emailAddressGenerator.generate(companyId, userId); } validate(companyId, userId, autoPassword, password1, password2, autoScreenName, screenName, emailAddress, firstName, middleName, lastName, organizationIds); if (!autoPassword) { if (Validator.isNull(password1) || Validator.isNull(password2)) { throw new UserPasswordException(UserPasswordException.PASSWORD_INVALID); } } if (autoScreenName) { ScreenNameGenerator screenNameGenerator = ScreenNameGeneratorFactory.getInstance(); try { screenName = screenNameGenerator.generate(companyId, userId, emailAddress); } catch (Exception e) { throw new SystemException(e); } } User defaultUser = getDefaultUser(companyId); FullNameGenerator fullNameGenerator = FullNameGeneratorFactory.getInstance(); String fullName = fullNameGenerator.getFullName(firstName, middleName, lastName); String greeting = LanguageUtil.format(locale, "welcome-x", " " + fullName, false); User user = userPersistence.create(userId); if (serviceContext != null) { String uuid = serviceContext.getUuid(); if (Validator.isNotNull(uuid)) { user.setUuid(uuid); } } user.setCompanyId(companyId); user.setCreateDate(now); user.setModifiedDate(now); user.setDefaultUser(false); user.setContactId(counterLocalService.increment()); if (Validator.isNotNull(password1)) { user.setPassword(PwdEncryptor.encrypt(password1)); user.setPasswordUnencrypted(password1); } user.setPasswordEncrypted(true); PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy(); if ((passwordPolicy != null) && passwordPolicy.isChangeable() && passwordPolicy.isChangeRequired()) { user.setPasswordReset(true); } else { user.setPasswordReset(false); } user.setDigest(StringPool.BLANK); user.setScreenName(screenName); user.setEmailAddress(emailAddress); user.setFacebookId(facebookId); user.setOpenId(openId); user.setLanguageId(locale.toString()); user.setTimeZoneId(defaultUser.getTimeZoneId()); user.setGreeting(greeting); user.setFirstName(firstName); user.setMiddleName(middleName); user.setLastName(lastName); user.setJobTitle(jobTitle); user.setStatus(WorkflowConstants.STATUS_DRAFT); user.setExpandoBridgeAttributes(serviceContext); userPersistence.update(user, false, serviceContext); // Resources String creatorUserName = StringPool.BLANK; if (creatorUserId <= 0) { creatorUserId = user.getUserId(); // Don't grab the full name from the User object because it doesn't // have a corresponding Contact object yet //creatorUserName = user.getFullName(); } else { User creatorUser = userPersistence.findByPrimaryKey(creatorUserId); creatorUserName = creatorUser.getFullName(); } resourceLocalService.addResources(companyId, 0, creatorUserId, User.class.getName(), user.getUserId(), false, false, false); // Contact Date birthday = PortalUtil.getDate(birthdayMonth, birthdayDay, birthdayYear, ContactBirthdayException.class); Contact contact = contactPersistence.create(user.getContactId()); contact.setCompanyId(user.getCompanyId()); contact.setUserId(creatorUserId); contact.setUserName(creatorUserName); contact.setCreateDate(now); contact.setModifiedDate(now); contact.setAccountId(company.getAccountId()); contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID); contact.setFirstName(firstName); contact.setMiddleName(middleName); contact.setLastName(lastName); contact.setPrefixId(prefixId); contact.setSuffixId(suffixId); contact.setMale(male); contact.setBirthday(birthday); contact.setJobTitle(jobTitle); contactPersistence.update(contact, false, serviceContext); // Group try { String friendlyURL = StringPool.SLASH + URIUtil.encodeQuery(screenName, "UTF-8"); groupLocalService.addGroup(user.getUserId(), User.class.getName(), user.getUserId(), null, null, 0, friendlyURL, false, true, null); } catch (URIException e) { _log.error(e); } // Groups if (groupIds != null) { groupLocalService.addUserGroups(userId, groupIds); } addDefaultGroups(userId); // Organizations updateOrganizations(userId, organizationIds, false); // Roles if (roleIds != null) { roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds); userPersistence.setRoles(userId, roleIds); } addDefaultRoles(userId); // User groups if (userGroupIds != null) { if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) { for (long userGroupId : userGroupIds) { userGroupLocalService.copyUserGroupLayouts(userGroupId, new long[] { userId }); } } userPersistence.setUserGroups(userId, userGroupIds); } addDefaultUserGroups(userId); // Asset if (serviceContext != null) { updateAsset(creatorUserId, user, serviceContext.getAssetCategoryIds(), serviceContext.getAssetTagNames()); } // Indexer if ((serviceContext == null) || serviceContext.isIndexingEnabled()) { reindex(user); } // Workflow long workflowUserId = creatorUserId; if (workflowUserId == userId) { workflowUserId = defaultUser.getUserId(); } ServiceContext workflowServiceContext = serviceContext; if (workflowServiceContext == null) { workflowServiceContext = new ServiceContext(); } workflowServiceContext.setAttribute("autoPassword", autoPassword); workflowServiceContext.setAttribute("sendEmail", sendEmail); WorkflowHandlerRegistryUtil.startWorkflowInstance(companyId, workflowUserId, User.class.getName(), userId, user, workflowServiceContext); if (serviceContext != null) { String passwordUnencrypted = (String) serviceContext.getAttribute("passwordUnencrypted"); if (Validator.isNotNull(passwordUnencrypted)) { user.setPasswordUnencrypted(passwordUnencrypted); } } return user; }
From source file:org.ounl.lifelonglearninghub.mediaplayer.cast.refplayer.NFCVideoBrowserActivity.java
/** * Build NDEF text record for given parameters * //from ww w. j ava 2 s. co m * @param text * @param locale * @param encodeInUtf8 * @return */ private NdefRecord buildTextRecord(String text, Locale locale, boolean encodeInUtf8) { Log.d(CLASSNAME, "buildTextRecord is called Text:" + text + " Locale:" + locale.toString() + " encodeinUtf8:" + encodeInUtf8); byte[] langBytes = locale.getLanguage().getBytes(Charset.forName("US-ASCII")); Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset.forName("UTF-16"); byte[] textBytes = text.getBytes(utfEncoding); int utfBit = encodeInUtf8 ? 0 : (1 << 7); char status = (char) (utfBit + langBytes.length); byte[] data = new byte[1 + langBytes.length + textBytes.length]; data[0] = (byte) status; System.arraycopy(langBytes, 0, data, 1, langBytes.length); System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length); return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data); }