对于想了解搜索引擎成果页面的读者,本文将提供新的信息,我们将详细介绍Searchengineresultspage,SERP,并且为您提供关于android.hardware.fingerprint.
对于想了解搜索引擎成果页面的读者,本文将提供新的信息,我们将详细介绍Searchengineresultspage,SERP,并且为您提供关于android.hardware.fingerprint.FingerprintManager.AuthenticationResult的实例源码、C#编写了一个基于Lucene.Net的搜索引擎查询通用工具类:SearchEngineUtil、com.google.zxing.client.result.CalendarParsedResult的实例源码、com.google.zxing.client.result.ResultParser的实例源码的有价值信息。
本文目录一览:- 搜索引擎成果页面(Searchengineresultspage,SERP)(搜索引擎结果)
- android.hardware.fingerprint.FingerprintManager.AuthenticationResult的实例源码
- C#编写了一个基于Lucene.Net的搜索引擎查询通用工具类:SearchEngineUtil
- com.google.zxing.client.result.CalendarParsedResult的实例源码
- com.google.zxing.client.result.ResultParser的实例源码
搜索引擎成果页面(Searchengineresultspage,SERP)(搜索引擎结果)
SearchEngineResuitsPage的缩写,意思是查找引擎成果页面,用户输入要害词后,点击查找按钮后,查找引擎回来显现的成果页面。
SERP是为特定查找显现的列表或成果,SERP有时分界说为查找引擎成果的安排(placement),依据本系列的意图,我将其称为页面而不是安排,在SEO领域中,在SERP中取得杰出的表现就是全部。
android.hardware.fingerprint.FingerprintManager.AuthenticationResult的实例源码
private static android.hardware.fingerprint.FingerprintManager.AuthenticationCallback wrapCallback(final AuthenticationCallback callback) { return new android.hardware.fingerprint.FingerprintManager.AuthenticationCallback() { public void onAuthenticationError(int errMsgid,CharSequence errString) { callback.onAuthenticationError(errMsgid,errString); } public void onAuthenticationHelp(int helpMsgid,CharSequence helpString) { callback.onAuthenticationHelp(helpMsgid,helpString); } public void onAuthenticationSucceeded(AuthenticationResult result) { callback.onAuthenticationSucceeded(new AuthenticationResultInternal(FingerprintManagerCompatApi23.unwrapCryptoObject(result.getCryptoObject()))); } public void onAuthenticationFailed() { callback.onAuthenticationFailed(); } }; }
@Override protected void onAuthenticationSucceeded(ObservableEmitter<FingerprintEncryptionResult> emitter,AuthenticationResult result) { try { Cipher cipher = result.getCryptoObject().getCipher(); byte[] encryptedBytes = cipher.doFinal(toEncrypt.getBytes("UTF-8")); byte[] ivBytes = cipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV(); String encryptedString = CryptoData.fromBytes(encodingProvider,encryptedBytes,ivBytes).toString(); CryptoData.verifyCryptoDataString(encryptedString); emitter.onNext(new FingerprintEncryptionResult(FingerprintResult.AUTHENTICATED,null,encryptedString)); emitter.onComplete(); } catch (Exception e) { emitter.onError(cipherProvider.mapCipherFinalOperationException(e)); } }
private AuthenticationCallback createAuthenticationCallback(final ObservableEmitter<T> emitter) { return new AuthenticationCallback() { @Override public void onAuthenticationError(int errMsgid,CharSequence errString) { if (!emitter.isdisposed()) { emitter.onError(new FingerprintAuthenticationException(errString)); } } @Override public void onAuthenticationFailed() { FingerprintObservable.this.onAuthenticationFailed(emitter); } @Override public void onAuthenticationHelp(int helpMsgid,CharSequence helpString) { FingerprintObservable.this.onAuthenticationHelp(emitter,helpMsgid,helpString.toString()); } @Override public void onAuthenticationSucceeded(AuthenticationResult result) { FingerprintObservable.this.onAuthenticationSucceeded(emitter,result); } }; }
@Test public void testAuthenticationSuccessful() throws Exception { when(fingerprintApiWrapper.isUnavailable()).thenReturn(false); when(fingerprintApiWrapper.getFingerprintManager()).thenReturn(fingerprintManager); AuthenticationResult result = mock(AuthenticationResult.class); TestObserver<FingerprintAuthenticationResult> testObserver = observable.test(); ArgumentCaptor<FingerprintManager.AuthenticationCallback> callbackCaptor = ArgumentCaptor.forClass(FingerprintManager.AuthenticationCallback.class); verify(fingerprintManager).authenticate(any(CryptoObject.class),any(CancellationSignal.class),anyInt(),callbackCaptor.capture(),any(Handler.class)); callbackCaptor.getValue().onAuthenticationSucceeded(result); testObserver.awaitTerminalEvent(); testObserver.assertNoErrors(); testObserver.assertComplete(); testObserver.assertValueCount(1); FingerprintAuthenticationResult fingerprintAuthenticationResult = testObserver.values().get(0); assertTrue("Authentication should be successful",fingerprintAuthenticationResult.isSuccess()); assertTrue("Result should be equal AUTHENTICATED",fingerprintAuthenticationResult.getResult().equals(FingerprintResult.AUTHENTICATED)); assertTrue("Should contain no message",fingerprintAuthenticationResult.getMessage() == null); }
public final void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult paramAuthenticationResult) { this.mIcon.setimageResource(2130837767); this.mStatusTextView.setTextColor(this.mStatusTextView.getResources().getColor(2131689543,null)); updateAndAnnounceTextView(this.mStatusTextView.getResources().getString(2131362156)); this.mStatusTextView.postDelayed(this.mSuccessRunnable,300L); }
@Override protected void onAuthenticationSucceeded(ObservableEmitter<FingerprintDecryptionResult> emitter,AuthenticationResult result) { try { CryptoData cryptoData = CryptoData.fromString(encodingProvider,encryptedString); Cipher cipher = result.getCryptoObject().getCipher(); String decrypted = new String(cipher.doFinal(cryptoData.getMessage())); emitter.onNext(new FingerprintDecryptionResult(FingerprintResult.AUTHENTICATED,decrypted)); emitter.onComplete(); } catch (Exception e) { emitter.onError(cipherProvider.mapCipherFinalOperationException(e)); } }
@Override protected void onAuthenticationSucceeded(ObservableEmitter<FingerprintDecryptionResult> emitter,AuthenticationResult result) { try { Cipher cipher = result.getCryptoObject().getCipher(); byte[] bytes = cipher.doFinal(encodingProvider.decode(encryptedString)); String decrypted = new String(bytes,"UTF-8"); emitter.onNext(new FingerprintDecryptionResult(FingerprintResult.AUTHENTICATED,decrypted)); emitter.onComplete(); } catch (Exception e) { Logger.error("Unable to decrypt given value. RxFingerprint is only able to decrypt values prevIoUsly encrypted by RxFingerprint with the same encryption mode.",e); emitter.onError(cipherProvider.mapCipherFinalOperationException(e)); } }
@Test public void testAuthenticationSuccessfulOnSecondTry() throws Exception { when(fingerprintApiWrapper.isUnavailable()).thenReturn(false); when(fingerprintApiWrapper.getFingerprintManager()).thenReturn(fingerprintManager); TestObserver<FingerprintAuthenticationResult> testObserver = observable.test(); ArgumentCaptor<FingerprintManager.AuthenticationCallback> callbackCaptor = ArgumentCaptor.forClass(FingerprintManager.AuthenticationCallback.class); verify(fingerprintManager).authenticate(any(CryptoObject.class),any(Handler.class)); callbackCaptor.getValue().onAuthenticationHelp(0,MESSAGE_HELP); testObserver.assertNotterminated(); testObserver.assertNoErrors(); testObserver.assertNotComplete(); testObserver.assertValueCount(1); FingerprintAuthenticationResult helpResult = testObserver.values().get(0); assertTrue("Authentication should not be successful",!helpResult.isSuccess()); assertTrue("Result should be equal HELP",helpResult.getResult().equals(FingerprintResult.HELP)); assertTrue("Should contain help message",helpResult.getMessage().equals(MESSAGE_HELP)); callbackCaptor.getValue().onAuthenticationSucceeded(mock(AuthenticationResult.class)); testObserver.awaitTerminalEvent(); testObserver.assertNoErrors(); testObserver.assertComplete(); testObserver.assertValueCount(2); FingerprintAuthenticationResult successResult = testObserver.values().get(1); assertTrue("Authentication should be successful",successResult.isSuccess()); assertTrue("Result should be equal AUTHENTICATED",successResult.getResult().equals(FingerprintResult.AUTHENTICATED)); assertTrue("Should contain no message",successResult.getMessage() == null); }
@Override public void onAuthenticationSucceeded(AuthenticationResult result) { startActivity(getFingerIdFromresult(result)); restartListeningDelayed(1000); }
@Override protected void onAuthenticationSucceeded(ObservableEmitter<FingerprintAuthenticationResult> emitter,AuthenticationResult result) { emitter.onNext(new FingerprintAuthenticationResult(FingerprintResult.AUTHENTICATED,null)); emitter.onComplete(); }
/** * Action to execute when fingerprint authentication was successful. * Should return the needed result via the given {@link Emitter}. * <p/> * Should call {@link Emitter#onComplete()}. * * @param emitter current subscriber * @param result result of the successful fingerprint authentication */ protected abstract void onAuthenticationSucceeded(ObservableEmitter<T> emitter,AuthenticationResult result);
C#编写了一个基于Lucene.Net的搜索引擎查询通用工具类:SearchEngineUtil
最近由于工作原因,一直忙于公司的各种项目(大部份都是基于spring cloud的微服务项目),故有一段时间没有与大家分享总结最近的技术研究成果的,其实最近我一直在不断的深入研究学习Spring、Spring Boot、Spring Cloud的各种框架原理,同时也随时关注着.NET CORE的发展情况及最新技术点,也在极客时间上订阅相关的专栏,只要下班有空我都会去认真阅读观看,纸质书箱也买了一些,总之近一年都是在通过:微信技术公众号(.NET、JAVA、算法、前端等技术方向)、极客时间、技术书箱 不断的吸取、借鉴他人之精华,从而不断的充实提高自己的技术水平,所谓:学如逆水行舟,不进则退,工作中学习,学习后工作中运用,当然写文章分享是一种总结,同时也是“温故而知新”的最佳应用。
前面废话说得有点多了,就直奔本文的主题内容,编写一个基于Lucene.Net的搜索引擎查询通用工具类:SearchEngineUtil,Lucene是什么,见百度百科 ,重点是:Lucene是一个全文检索引擎的架构,提供了完整的查询引擎和索引引擎,Lucene.NET是C#及.NET运行时下的另一种语言的实现,官网地址:http://lucenenet.apache.org/ ,具体用法就不多说了,官网以及网上都有很多,但由于Lucene.Net的原生SDK中的API比较复杂,用起来不太方便,故我进行了适当的封装,把常用的增、删、改、查(分页查)在保证灵活度的情况下进行了封装,使得操作Lucene.Net变得相对简单一些,代码本身也不复杂,贴出完整的SearchEngineUtil代码如下:
using Lucene.Net.Analysis.PanGu;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using Lucene.Net.Store;
using NLog;
using PanGu;
using PanGu.HighLight;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace CN.Zuowenjun.Blog.Common
{
/// <summary>
/// Lucene 搜索引擎实用工具类
/// Author:zuowenjun
/// </summary>
public class SearchEngineUtil
{
/// <summary>
/// 创建并添加索引记录
/// </summary>
/// <typeparam name="TIndex"></typeparam>
/// <param name="indexDir"></param>
/// <param name="indexData"></param>
/// <param name="setDocFiledsAction"></param>
public static void AddIndex<TIndex>(string indexDir, TIndex indexData, Action<Document, TIndex> setDocFiledsAction)
{
//创建索引目录
if (!System.IO.Directory.Exists(indexDir))
{
System.IO.Directory.CreateDirectory(indexDir);
}
FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexDir), new NativeFSLockFactory());
bool isUpdate = IndexReader.IndexExists(directory);
if (isUpdate)
{
//如果索引目录被锁定(比如索引过程中程序异常退出),则首先解锁
if (IndexWriter.IsLocked(directory))
{
IndexWriter.Unlock(directory);
}
}
using (IndexWriter writer = new IndexWriter(directory, new PanGuAnalyzer(), !isUpdate, IndexWriter.MaxFieldLength.UNLIMITED))
{
Document document = new Document();
setDocFiledsAction(document, indexData);
writer.AddDocument(document);
writer.Optimize();//优化索引
}
}
/// <summary>
/// 删除索引记录
/// </summary>
/// <param name="indexDir"></param>
/// <param name="keyFiledName"></param>
/// <param name="keyFileValue"></param>
public static void DeleteIndex(string indexDir, string keyFiledName, object keyFileValue)
{
FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexDir), new NativeFSLockFactory());
if (!IndexReader.IndexExists(directory))
{
return;
}
using (IndexWriter iw = new IndexWriter(directory, new PanGuAnalyzer(), IndexWriter.MaxFieldLength.UNLIMITED))
{
iw.DeleteDocuments(new Term(keyFiledName, keyFileValue.ToString()));
iw.Optimize();//删除文件后并非从磁盘中移除,而是生成一个.del的文件,需要调用Optimize方法来清除。在清除文件前可以使用UndeleteAll方法恢复
}
}
/// <summary>
/// 更新索引记录
/// </summary>
/// <param name="indexDir"></param>
/// <param name="keyFiledName"></param>
/// <param name="keyFileValue"></param>
/// <param name="doc"></param>
public static void UpdateIndex(string indexDir, string keyFiledName, object keyFileValue, Document doc)
{
FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexDir), new NativeFSLockFactory());
if (!IndexReader.IndexExists(directory))
{
return;
}
using (IndexWriter iw = new IndexWriter(directory, new PanGuAnalyzer(), IndexWriter.MaxFieldLength.UNLIMITED))
{
iw.UpdateDocument(new Term(keyFiledName, keyFileValue.ToString()), doc);
iw.Optimize();
}
}
/// <summary>
/// 是否存在指定的索引文档
/// </summary>
/// <param name="indexDir"></param>
/// <param name="keyFiledName"></param>
/// <param name="keyFileValue"></param>
/// <returns></returns>
public static bool ExistsDocument(string indexDir, string keyFiledName, object keyFileValue)
{
FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexDir), new NativeFSLockFactory());
if (!IndexReader.IndexExists(directory))
{
return false;
}
var reader = IndexReader.Open(directory, true);
return reader.DocFreq(new Term(keyFiledName, keyFileValue.ToString())) > 0;
}
/// <summary>
/// 查询索引匹配到的记录
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="indexDir"></param>
/// <param name="buildQueryAction"></param>
/// <param name="getSortFieldsFunc"></param>
/// <param name="buildResultFunc"></param>
/// <param name="topCount"></param>
/// <param name="needHighlight"></param>
/// <returns></returns>
public static List<TResult> SearchIndex<TResult>(string indexDir, Func<BooleanQuery, IDictionary<string, string>> buildQueryAction,
Func<IEnumerable<SortField>> getSortFieldsFunc, Func<Document, TResult> buildResultFunc, bool needHighlight = true, int topCount = 0)
{
FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexDir), new NoLockFactory());
if (!IndexReader.IndexExists(directory))
{
return new List<TResult>();
}
IndexReader reader = IndexReader.Open(directory, true);
IndexSearcher searcher = new IndexSearcher(reader);
BooleanQuery bQuery = new BooleanQuery();
var keyWords = buildQueryAction(bQuery);
Sort sort = null;
var sortFields = getSortFieldsFunc();
if (sortFields != null)
{
sort = new Sort();
sort.SetSort(sortFields.ToArray());
}
topCount = topCount > 0 ? topCount : int.MaxValue;//当未指定TOP值,则设置最大值以表示获取全部
TopDocs resultDocs = null;
if (sort != null)
{
resultDocs = searcher.Search(bQuery, null, topCount, sort);
}
else
{
resultDocs = searcher.Search(bQuery, null, topCount);
}
if (topCount > resultDocs.TotalHits)
{
topCount = resultDocs.TotalHits;
}
Dictionary<string, PropertyInfo> highlightProps = null;
List<TResult> results = new List<TResult>();
if (resultDocs != null)
{
for (int i = 0; i < topCount; i++)
{
Document doc = searcher.Doc(resultDocs.ScoreDocs[i].Doc);
var model = buildResultFunc(doc);
if (needHighlight)
{
model = SetHighlighter(keyWords, model, ref highlightProps);
}
results.Add(model);
}
}
return results;
}
/// <summary>
/// 分页查询索引匹配到的记录
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="indexDir"></param>
/// <param name="buildQueryAction"></param>
/// <param name="getSortFieldsFunc"></param>
/// <param name="buildResultFunc"></param>
/// <param name="pageSize"></param>
/// <param name="page"></param>
/// <param name="totalCount"></param>
/// <param name="needHighlight"></param>
/// <returns></returns>
public static List<TResult> SearchIndexByPage<TResult>(string indexDir, Func<BooleanQuery, IDictionary<string, string>> buildQueryAction,
Func<IEnumerable<SortField>> getSortFieldsFunc, Func<Document, TResult> buildResultFunc, int pageSize, int page, out int totalCount, bool needHighlight = true)
{
FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexDir), new NoLockFactory());
if (!IndexReader.IndexExists(directory))
{
totalCount = 0;
return new List<TResult>();
}
IndexReader reader = IndexReader.Open(directory, true);
IndexSearcher searcher = new IndexSearcher(reader);
BooleanQuery bQuery = new BooleanQuery();
var keyWords = buildQueryAction(bQuery);
Sort sort = null;
var sortFields = getSortFieldsFunc();
if (sortFields != null)
{
sort = new Sort();
sort.SetSort(sortFields.ToArray());
}
TopScoreDocCollector docCollector = TopScoreDocCollector.Create(1, true);
searcher.Search(bQuery, docCollector);
totalCount = docCollector.TotalHits;
if (totalCount <= 0) return null;
TopDocs resultDocs = searcher.Search(bQuery, null, pageSize * page, sort);
Dictionary<string, PropertyInfo> highlightProps = null;
List<TResult> results = new List<TResult>();
int indexStart = (page - 1) * pageSize;
int indexEnd = indexStart + pageSize;
if (totalCount < indexEnd) indexEnd = totalCount;
if (resultDocs != null)
{
for (int i = indexStart; i < indexEnd; i++)
{
Document doc = searcher.Doc(resultDocs.ScoreDocs[i].Doc);
var model = buildResultFunc(doc);
if (needHighlight)
{
model = SetHighlighter(keyWords, model, ref highlightProps);
}
results.Add(model);
}
}
return results;
}
/// <summary>
/// 设置结果高亮
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dicKeywords"></param>
/// <param name="model"></param>
/// <param name="props"></param>
/// <returns></returns>
private static T SetHighlighter<T>(IDictionary<string, string> dicKeywords, T model, ref Dictionary<string, PropertyInfo> props)
{
SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter("<font color=\"red\">", "</font>");
Highlighter highlighter = new Highlighter(simpleHTMLFormatter, new Segment());
highlighter.FragmentSize = 250;
Type modelType = typeof(T);
foreach (var item in dicKeywords)
{
if (!string.IsNullOrWhiteSpace(item.Value))
{
if (props == null)
{
props = new Dictionary<string, PropertyInfo>();
}
if (!props.ContainsKey(item.Key))
{
props[item.Key] = modelType.GetProperty(item.Key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
}
var modelProp = props[item.Key];
if (modelProp.PropertyType == typeof(string))
{
string newValue = highlighter.GetBestFragment(item.Value, modelProp.GetValue(model).ToString());
if (!string.IsNullOrEmpty(newValue))
{
modelProp.SetValue(model, newValue);
}
}
}
}
return model;
}
/// <summary>
/// 拆分关键词
/// </summary>
/// <param name="keywords"></param>
/// <returns></returns>
public static string GetKeyWordsSplitBySpace(string keyword)
{
PanGuTokenizer ktTokenizer = new PanGuTokenizer();
StringBuilder result = new StringBuilder();
ICollection<WordInfo> words = ktTokenizer.SegmentToWordInfos(keyword);
foreach (WordInfo word in words)
{
if (word == null)
{
continue;
}
result.AppendFormat("{0}^{1}.0 ", word.Word, (int)Math.Pow(3, word.Rank));
}
return result.ToString().Trim();
}
/// <summary>
/// 【辅助方法】创建盘古查询对象
/// </summary>
/// <param name="field"></param>
/// <param name="keyword"></param>
/// <returns></returns>
public static Query CreatePanGuQuery(string field, string keyword, bool needSplit = true)
{
if (needSplit)
{
keyword = GetKeyWordsSplitBySpace(keyword);
}
QueryParser parse = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, field, new PanGuAnalyzer());
parse.DefaultOperator = QueryParser.Operator.OR;
Query query = parse.Parse(keyword);
return query;
}
/// <summary>
/// 【辅助方法】创建盘古多字段查询对象
/// </summary>
/// <param name="keyword"></param>
/// <param name="fields"></param>
/// <returns></returns>
public static Query CreatePanGuMultiFieldQuery(string keyword, bool needSplit, params string[] fields)
{
if (needSplit)
{
keyword = GetKeyWordsSplitBySpace(keyword);
}
QueryParser parse = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_30, fields, new PanGuAnalyzer());
parse.DefaultOperator = QueryParser.Operator.OR;
Query query = parse.Parse(keyword);
return query;
}
}
}
里面除了使用了Lucene.Net nuget包,还单独引用了PanGu分词器及其相关组件,因为大多数情况下我们的内容会包含中文。如上代码就不再细讲了,注释得比较清楚了。下面贴出一些实际的用法:
创建索引:
SearchEngineUtil.AddIndex(GetSearchIndexDir(), post, (doc, data) => BuildPostSearchDocument(data, doc));
private Document BuildPostSearchDocument(Post post, Document doc = null)
{
if (doc == null)
{
doc = new Document();//创建Document
}
doc.Add(new Field("Id", post.Id.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.Add(new Field("Title", post.Title, Field.Store.YES, Field.Index.ANALYZED));
doc.Add(new Field("Summary", post.Summary, Field.Store.YES, Field.Index.ANALYZED));
doc.Add(new Field("CreateTime", post.CreateTime.ToString("yyyy/MM/dd HH:mm"), Field.Store.YES, Field.Index.NO));
doc.Add(new Field("Author", post.IsOriginal ? (post.Creator ?? userQueryService.FindByName(post.CreateBy)).NickName : post.SourceBy, Field.Store.YES, Field.Index.NO));
return doc;
}
删除索引:
SearchEngineUtil.DeleteIndex(GetSearchIndexDir(), "Id", post.Id);
更新索引:
SearchEngineUtil.UpdateIndex(GetSearchIndexDir(), "Id", post.Id, BuildPostSearchDocument(post));
分页查询:
var keyword = SearchEngineUtil.GetKeyWordsSplitBySpace("梦在旅途 中国梦");
var searchResult = SearchEngineUtil.SearchIndexByPage(indexDir, (bQuery) =>
{
var query = SearchEngineUtil.CreatePanGuMultiFieldQuery(keyword, false, "Title", "Summary");
bQuery.Add(query, Occur.SHOULD);
return new Dictionary<string, string> {
{ "Title",keyword},{"Summary",keyword}
};
}, () =>
{
return new[] { new SortField("Id", SortField.INT, true) };
}, doc =>
{
return new PostSearchInfoDto
{
Id = doc.Get("Id"),
Title = doc.Get("Title"),
Summary = doc.Get("Summary"),
Author = doc.Get("Author"),
CreateTime = doc.Get("CreateTime")
};
}, pageSize, pageNo, out totalCount);
其它的还有:判断索引中的指定文档记录存不存在、查询符合条件的索引文档等在此没有列出,大家有兴趣的可以COPY到自己的项目中测试一下。
这里可以看一下我在自己的项目中(个人全新改版的自己博客,还在开发中)应用搜索场景的效果:
最后说明的是:Lucene并不是一个完整的全文检索引擎,但了解它对于学习elasticsearch、solr还是有一定的帮助,目前一般应用于实际的生产项目中,多半是使用更高层的elasticsearch、solr。
(本文中的代码我是今年很早前就写好了,只是今天才分享出来)
我喜欢对一些常用的组件进行封装,比如过往封装有:
基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类)
基于RabbitMQ.Client组件实现RabbitMQ可复用的 ConnectionPool(连接池)
com.google.zxing.client.result.CalendarParsedResult的实例源码
@Override public void handleButtonPress(int index) { if (index == 0) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,put in description if (description == null) { description = organizer; } else { description = description + '\n' + organizer; } } addCalendarEvent(calendarResult.getSummary(),calendarResult.getStart(),calendarResult.isstartAllDay(),calendarResult.getEnd(),calendarResult.getLocation(),description,calendarResult.getAttendees()); } }
@Override public void handleButtonPress(int index) { if (index == 0) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,calendarResult.getAttendees()); } }
@Override public void handleButtonPress(int index) { if (index == 0) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,calendarResult.getAttendees()); } }
@Override public void handleButtonPress(int index) { if (index == 0) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,calendarResult.getAttendees()); } }
@Override public void handleButtonPress(int index) { if (index == 0) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,put in // description if (description == null) { description = organizer; } else { description = description + '\n' + organizer; } } addCalendarEvent(calendarResult.getSummary(),calendarResult.getAttendees()); } }
@Override public void handleButtonPress(int index) { if (index == 0) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,put in description if (description == null) { description = organizer; } else { description = description + '\n' + organizer; } } addCalendarEvent(calendarResult.getSummary(),calendarResult.getAttendees()); } }
@Override public void handleButtonPress(int index) { if (index == 0) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,calendarResult.getAttendees()); } }
@Override public void handleButtonPress(int index) { if (index == 0) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,calendarResult.getAttendees()); } }
@Override public void handleButtonPress(int index) { if (index == 0) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,calendarResult.getAttendees()); } }
@Override public void handleButtonPress(int index) { if (index == 0) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,calendarResult.getAttendees()); } }
@Override public void handleButtonPress(int index) { if (index == 0) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,calendarResult.getAttendees()); } }
@Override public void handleButtonPress(int index) { if (index == 0) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,calendarResult.getAttendees()); } }
@Override public void handleButtonPress(int index) { if (index == 0) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,calendarResult.getAttendees()); } }
@Override public void handleButtonPress(int index) { if (index == 0) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,calendarResult.getAttendees()); } }
@Override public void handleButtonPress(int index) { if (index == 0) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,calendarResult.getAttendees()); } }
@Override public void handleClick(int buttonID) { if (buttonID == R.id.button_add_calendar) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,calendarResult.getAttendees()); } }
@Override public void handleButtonPress(int index) { if (index == 0) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,calendarResult.getAttendees()); } }
@Override public void handleButtonPress(int index) { if (index == 0) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,calendarResult.getAttendees()); } }
@Override public void handleButtonPress(int index) { if (index == 0) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,calendarResult.getAttendees()); } }
@Override public void handleButtonPress(int index) { if (index == 0) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,calendarResult.getAttendees()); } }
@Override public CharSequence getdisplayContents() { CalendarParsedResult calResult = (CalendarParsedResult) getResult(); StringBuilder result = new StringBuilder(100); ParsedResult.maybeAppend(calResult.getSummary(),result); Date start = calResult.getStart(); String startString = start.toGMTString(); appendTime(startString,result,false,false); Date end = calResult.getEnd(); String endString = end.toGMTString(); if (endString != null) { boolean sameStartEnd = startString.equals(endString); appendTime(endString,true,sameStartEnd); } ParsedResult.maybeAppend(calResult.getLocation(),result); ParsedResult.maybeAppend(calResult.getAttendees(),result); ParsedResult.maybeAppend(calResult.getDescription(),result); return result.toString(); }
@Override public void handleButtonPress(int index) { if (index == 0) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,calendarResult.getAttendees()); } }
@Override public void handleButtonPress(int index) { if (index == 0) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,calendarResult.getAttendees()); } }
@Override public void handleButtonPress(int index) { if (index == 0) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,calendarResult.getAttendees()); } }
@Override public CharSequence getdisplayContents() { CalendarParsedResult calResult = (CalendarParsedResult) getResult(); StringBuilder result = new StringBuilder(100); ParsedResult.maybeAppend(calResult.getSummary(),result); return result.toString(); }
@Override public CharSequence getdisplayContents() { CalendarParsedResult calResult = (CalendarParsedResult) getResult(); StringBuffer result = new StringBuffer(100); ParsedResult.maybeAppend(calResult.getSummary(),result); appendTime(calResult.getStart(),result); // The end can be null if the event has no duration,so use the start time. String endString = calResult.getEnd(); if (endString == null) { endString = calResult.getStart(); } appendTime(endString,result); ParsedResult.maybeAppend(calResult.getLocation(),result); ParsedResult.maybeAppend(calResult.getAttendee(),result); ParsedResult.maybeAppend(calResult.getDescription(),result); return result.toString(); }
@Override public void handleButtonPress(int index) { if (index == 0) { CalendarParsedResult calendarResult = (CalendarParsedResult) getResult(); String description = calendarResult.getDescription(); String organizer = calendarResult.getorganizer(); if (organizer != null) { // No separate Intent key,calendarResult.getAttendees()); } }
@Override public CharSequence getdisplayContents() { CalendarParsedResult calResult = (CalendarParsedResult) getResult(); StringBuilder result = new StringBuilder(100); ParsedResult.maybeAppend(calResult.getSummary(),result); Date start = calResult.getStart(); ParsedResult.maybeAppend(format(calResult.isstartAllDay(),start),result); Date end = calResult.getEnd(); if (end != null) { if (calResult.isEndAllDay() && !start.equals(end)) { // Show only year/month/day // if it's all-day and this is the end date,it's exclusive,so show the user // that it ends on the day before to make more intuitive sense. // But don't do it if the event already (incorrectly?) specifies the same start/end end = new Date(end.getTime() - 24 * 60 * 60 * 1000); } ParsedResult.maybeAppend(format(calResult.isEndAllDay(),end),result); } ParsedResult.maybeAppend(calResult.getLocation(),result); ParsedResult.maybeAppend(calResult.getorganizer(),result); ParsedResult.maybeAppend(calResult.getAttendees(),result); return result.toString(); }
@Override public CharSequence getdisplayContents() { CalendarParsedResult calResult = (CalendarParsedResult) getResult(); StringBuilder result = new StringBuilder(100); ParsedResult.maybeAppend(calResult.getSummary(),result); Date start = calResult.getStart(); ParsedResult.maybeAppend(format(calResult.isstartAllDay(),result); Date end = calResult.getEnd(); if (end != null) { if (calResult.isEndAllDay() && !start.equals(end)) { // Show only year/month/day // if it's all-day and this is the end date,so // show the user // that it ends on the day before to make more intuitive sense. // But don't do it if the event already (incorrectly?) specifies // the same start/end end = new Date(end.getTime() - 24 * 60 * 60 * 1000); } ParsedResult.maybeAppend(format(calResult.isEndAllDay(),result); } ParsedResult.maybeAppend(calResult.getLocation(),result); ParsedResult.maybeAppend(calResult.getorganizer(),result); return result.toString(); }
@Override public CharSequence getdisplayContents() { CalendarParsedResult calResult = (CalendarParsedResult) getResult(); StringBuilder result = new StringBuilder(100); ParsedResult.maybeAppend(calResult.getSummary(),so show the user // that it ends on the day before to make more intuitive sense. // But don't do it if the event already (incorrectly?) specifies the same start/end end = new Date(end.getTime() - 24 * 60 * 60 * 1000); } ParsedResult.maybeAppend(format(calResult.isEndAllDay(),result); return result.toString(); }
@Override public CharSequence getdisplayContents() { CalendarParsedResult calResult = (CalendarParsedResult) getResult(); StringBuilder result = new StringBuilder(100); ParsedResult.maybeAppend(calResult.getSummary(),result); return result.toString(); }
@Override public CharSequence getdisplayContents() { CalendarParsedResult calResult = (CalendarParsedResult) getResult(); StringBuilder result = new StringBuilder(100); ParsedResult.maybeAppend(calResult.getSummary(),result); return result.toString(); }
com.google.zxing.client.result.ResultParser的实例源码
final String fillInCustomSearchURL(String text) { if (customProductSearch == null) { return text; // ? } try { text = URLEncoder.encode(text,"UTF-8"); } catch (UnsupportedEncodingException e) { // can't happen; UTF-8 is always supported. Continue,I guess,without encoding } String url = customProductSearch.replace("%s",text); if (rawResult != null) { url = url.replace("%f",rawResult.getBarcodeFormat().toString()); if (url.contains("%t")) { ParsedResult parsedResultAgain = ResultParser.parseResult(rawResult); url = url.replace("%t",parsedResultAgain.getType().toString()); } } return url; }
final String fillInCustomSearchURL(String text) { if (customProductSearch == null) { return text; // ? } try { text = URLEncoder.encode(text,without encoding } String url = customProductSearch; if (rawResult != null) { // Replace %f but only if it doesn't seem to be a hex escape sequence. This remains // problematic but avoids the more surprising problem of breaking escapes url = url.replaceFirst("%f(?![0-9a-f])",parsedResultAgain.getType().toString()); } } // Replace %s last as it might contain itself %f or %t return url.replace("%s",text); }
final String fillInCustomSearchURL(String text) { if (customProductSearch == null) { return text; // ? } try { text = URLEncoder.encode(text,"UTF-8"); } catch (UnsupportedEncodingException e) { // can't happen; UTF-8 is always supported. Continue,without encoding } String url = customProductSearch; if (rawResult != null) { // Replace %f but only if it doesn't seem to be a hex escape sequence. This remains // problematic but avoids the more surprising problem of breaking escapes url = url.replaceFirst("%f(?![0-9a-f])",rawResult.getBarcodeFormat().toString()); if (url.contains("%t")) { ParsedResult parsedResultAgain = ResultParser.parseResult(rawResult); url = url.replace("%t",parsedResultAgain.getType().toString()); } } // Replace %s last as it might contain itself %f or %t return url.replace("%s",text); }
final String fillInCustomSearchURL(String text) { if (customProductSearch == null) { return text; // ? } try { text = URLEncoder.encode(text,text); }
final String fillInCustomSearchURL(String text) { if (customProductSearch == null) { return text; // ? } try { text = URLEncoder.encode(text,parsedResultAgain.getType().toString()); } } return url; }
final String fillInCustomSearchURL(String text) { if (customProductSearch == null) { return text; // ? } try { text = URLEncoder.encode(text,// without encoding } String url = customProductSearch; if (rawResult != null) { // Replace %f but only if it doesn't seem to be a hex escape // sequence. This remains // problematic but avoids the more surprising problem of breaking // escapes url = url.replaceFirst("%f(?![0-9a-f])",text); }
final String fillInCustomSearchURL(String text) { if (customProductSearch == null) { return text; // ? } try { text = URLEncoder.encode(text,text); }
final String fillInCustomSearchURL(String text) { if (customProductSearch == null) { return text; // ? } try { text = URLEncoder.encode(text,text); }
final String fillInCustomSearchURL(String text) { if (customProductSearch == null) { return text; // ? } try { text = URLEncoder.encode(text,text); }
public void handleDecode(Result rawResult,Bitmap barcode,float scaleFactor) { // 重新计时 inactivityTimer.onActivity(); lastResult = rawResult; // 把图片画到扫描框 viewfinderView.drawResultBitmap(barcode); beepManager.playBeepSoundAndVibrate(); // ////////////////////////////////////////////////////////////////////////////////////////////////////// Intent mIntent = new Intent(); mIntent.putExtra("describe",ResultParser.parseResult(rawResult) .toString()); setResult(1001,mIntent); finish(); }
final String fillInCustomSearchURL(String text) { if (customProductSearch == null) { return text; // ? } try { text = URLEncoder.encode(text,parsedResultAgain.getType().toString()); } } return url; }
/** * A valid barcode has been found,so give an indication of success and show * the results. * * @param rawResult * The contents of the barcode. * @param scaleFactor * amount by which thumbnail was scaled * @param barcode * A greyscale bitmap of the camera data which was decoded. */ public void handleDecode(Result rawResult,float scaleFactor) { lastResult = rawResult; // ResultHandler resultHandler = // ResultHandlerFactory.makeResultHandler(this,rawResult); ResultHandler resultHandler = new ResultHandler(this,ResultParser.parseResult(rawResult)); boolean fromLiveScan = barcode != null; if (fromLiveScan) { // Then not from history,so beep/vibrate and we have an image to // draw on beepManager.playBeepSoundAndVibrate(); //drawResultPoints(barcode,scaleFactor,rawResult); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (fromLiveScan && prefs.getBoolean(PreferencesSettings.KEY_BULK_MODE,false)) { Toast.makeText(getApplicationContext(),getResources().getString(R.string.msg_bulk_mode_scanned) + " (" + rawResult.getText() + ')',Toast.LENGTH_SHORT).show(); // Wait a moment or else it will scan the same barcode continuously // about 3 times restartPreviewAfterDelay(BULK_MODE_SCAN_DELAY_MS); } else { handleDecodeInternally(rawResult,resultHandler,barcode); } }
private void handleDecodeInternally(Result rawResult,Bitmap barcode) { Uri imageUri = null; String imageName = IMAGE_PREFIX + System.currentTimeMillis() + ".png"; Log.v(TAG,"Saving image as: " + imageName); try { imageUri = mImageManager.saveImage(imageName,barcode); } catch (IOException e) { Log.e(TAG,"Failed to save image!",e); } ResultProcessor<?> processor = new ResultProcessor<ParsedResult>( this,ResultParser.parseResult(rawResult),rawResult,imageUri); // ***** CultureGlass entry point ***** //Original BarcodeEye path //startActivity(ResultsActivity.newIntent(this,processor.getCardResults())); ParsedResult result = processor.getParsedResult(); startActivity(new Intent(this,LoadingActivity.class) .putExtra(EXTRA_CODE,result.getdisplayResult()) .putExtra(EXTRA_TYPE,result.getType().toString())); }
/** * A valid barcode has been found,so give an indication of success and show the results. * * @param rawResult * The contents of the barcode. * @param scaleFactor * amount by which thumbnail was scaled * @param barcode * A greyscale bitmap of the camera data which was decoded. */ public void handleDecode(Result rawResult,float scaleFactor) { // 重新计时 inactivityTimer.onActivity(); lastResult = rawResult; // 把图片画到扫描框 viewfinderView.drawResultBitmap(barcode); beepManager.playBeepSoundAndVibrate(); Toast.makeText(this,"识别结果:" + ResultParser.parseResult(rawResult).toString(),Toast.LENGTH_SHORT).show(); // Intent intent = new Intent(); // intent.putExtra("result",ResultParser.parseResult(rawResult) // .toString()); // setResult(RESULT_OK,intent); // finish(); // String result = ResultParser.parseResult(rawResult).toString() // + "&appkey=peixunduoduo"; // Intent intent = new Intent(); // Bundle bundle = new Bundle(); // bundle.putString("title","扫一扫检录"); // intent.setData(Uri.parse("traindd://" + result)); // intent.putExtra("initValues",bundle); // startActivity(intent); }
final String fillInCustomSearchURL(String text) { if (customProductSearch == null) { return text; // ? } try { text = URLEncoder.encode(text,without encoding } String url = customProductSearch.replace("%s",text); if (rawResult != null) { url = url.replace("%f",parsedResultAgain.getType().toString()); } } return url; }
public static AddressBookParsedResult getContactDetailsFromUri( Context context,Uri contactUri) { try { byte[] vcard; String vcardString; InputStream stream; stream = context.getContentResolver().openInputStream(contactUri); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int bytesRead; while ((bytesRead = stream.read(buffer)) > 0) { baos.write(buffer,bytesRead); } vcard = baos.toByteArray(); vcardString = new String(vcard,vcard.length,"UTF-8"); Result result = new Result(vcardString,vcard,null,BarcodeFormat.QR_CODE); ParsedResult parsedResult = ResultParser.parseResult(result); return (AddressBookParsedResult) parsedResult; } catch (Exception e) { return null; } }
final String fillInCustomSearchURL(String text) { if (customProductSearch == null) { return text; // ? } try { text = URLEncoder.encode(text,text); }
private static void assertCorrectimage2result(String fileName,ExpandedProductParsedResult expected) throws IOException,NotFoundException { Path path = AbstractBlackBoxTestCase.buildTestBase("src/test/resources/blackBox/RSSexpanded-1/").resolve(fileName); BufferedImage image = ImageIO.read(path.toFile()); BinaryBitmap binaryMap = new BinaryBitmap(new GlobalHistogramBinarizer(new BufferedImageluminanceSource(image))); int rowNumber = binaryMap.getHeight() / 2; BitArray row = binaryMap.getBlackRow(rowNumber,null); Result theResult; try { RSSExpandedReader RSSExpandedReader = new RSSExpandedReader(); theResult = RSSExpandedReader.decodeRow(rowNumber,row,null); } catch (ReaderException re) { fail(re.toString()); return; } assertSame(BarcodeFormat.RSS_EXPANDED,theResult.getBarcodeFormat()); ParsedResult result = ResultParser.parseResult(theResult); assertEquals(expected,result); }
final String fillInCustomSearchURL(String text) { if (customProductSearch == null) { return text; // ? } try { text = URLEncoder.encode(text,without encoding } String url = text; if (rawResult != null) { // Replace %f but only if it doesn't seem to be a hex escape sequence. This remains // problematic but avoids the more surprising problem of breaking escapes url = url.replace("%f(?![0-9a-f])",parsedResultAgain.getType().toString()); } } // Replace %s last as it might contain itself %f or %t url = customProductSearch.replace("%s",url); return url; }
private static void assertCorrectimage2result(String path,NotFoundException { RSSExpandedReader RSSExpandedReader = new RSSExpandedReader(); File file = new File(path); if (!file.exists()) { // Support running from project root too file = new File("core",path); } BufferedImage image = ImageIO.read(file); BinaryBitmap binaryMap = new BinaryBitmap(new GlobalHistogramBinarizer(new BufferedImageluminanceSource(image))); int rowNumber = binaryMap.getHeight() / 2; BitArray row = binaryMap.getBlackRow(rowNumber,null); Result theResult = RSSExpandedReader.decodeRow(rowNumber,null); assertSame(BarcodeFormat.RSS_EXPANDED,result); }
final String fillInCustomSearchURL(String text) { if (customProductSearch == null) { return text; // ? } try { text = URLEncoder.encode(text,text); }
private void encodeFromStreamExtra(Intent intent) throws WriterException { format = BarcodeFormat.QR_CODE; Bundle bundle = intent.getExtras(); if (bundle == null) { throw new WriterException("No extras"); } Uri uri = bundle.getParcelable(Intent.EXTRA_STREAM); if (uri == null) { throw new WriterException("No EXTRA_STREAM"); } byte[] vcard; String vcardString; try { InputStream stream = activity.getContentResolver().openInputStream(uri); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int bytesRead; while ((bytesRead = stream.read(buffer)) > 0) { baos.write(buffer,bytesRead); } vcard = baos.toByteArray(); vcardString = new String(vcard,"UTF-8"); } catch (IOException ioe) { throw new WriterException(ioe); } Log.d(TAG,"Encoding share intent content:"); Log.d(TAG,vcardString); Result result = new Result(vcardString,BarcodeFormat.QR_CODE); ParsedResult parsedResult = ResultParser.parseResult(result); if (!(parsedResult instanceof AddressBookParsedResult)) { throw new WriterException("Result was not an address"); } encodeQRCodeContents((AddressBookParsedResult) parsedResult); if (contents == null || contents.isEmpty()) { throw new WriterException("No content to encode"); } }
String fillInCustomSearchURL(String text) { if (customProductSearch == null) { return text; // ? } String url = customProductSearch.replace("%s",parsedResultAgain.getType().toString()); } } return url; }
private void encodeFromStreamExtra(Intent intent) throws WriterException { format = BarcodeFormat.QR_CODE; Bundle bundle = intent.getExtras(); if (bundle == null) { throw new WriterException("No extras"); } Uri uri = bundle.getParcelable(Intent.EXTRA_STREAM); if (uri == null) { throw new WriterException("No EXTRA_STREAM"); } byte[] vcard; String vcardString; try { InputStream stream = activity.getContentResolver().openInputStream(uri); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int bytesRead; while ((bytesRead = stream.read(buffer)) > 0) { baos.write(buffer,BarcodeFormat.QR_CODE); ParsedResult parsedResult = ResultParser.parseResult(result); if (!(parsedResult instanceof AddressBookParsedResult)) { throw new WriterException("Result was not an address"); } encodeQRCodeContents((AddressBookParsedResult) parsedResult); if (contents == null || contents.isEmpty()) { throw new WriterException("No content to encode"); } }
private void handleDecodeInternally(Result rawResult,Bitmap barcode) { /* mTimer.cancel(); */ String parsedResult = ResultParser.parseResult(rawResult).toString(); /* Intent intent = new Intent(this,MainGlassActivity.class); intent.putExtra("qr_type",parsedResult.getType().toString()); intent.putExtra("qr_data",parsedResult.toString()); startActivityForResult(intent,2); */ List<String> ar; parsedResult = parsedResult.replaceAll("[^-?0-9]+"," "); ar = Arrays.asList(parsedResult.trim().split(" ")); if (ar.size() > 0){ mViewfinderView.resultText = getLocationDescription(ar.get(0)); } else { Log.d(TAG,"No valid Id was found in the QR Code."); } this.onPause(); SurfaceView surfaceView = (SurfaceView) tmpConvertView.findViewById(R.id.preview_view); SurfaceHolder surfaceHolder = surfaceView.getHolder(); if (mHasSurface) { // The activity was paused but not stopped,so the surface still exists. Therefore // surfaceCreated() won't be called,so init the camera here. initCamera(surfaceHolder); } else { // Install the callback and wait for surfaceCreated() to init the camera. surfaceHolder.addCallback(CaptureActivity.this); } this.onResume(); }
private void encodeFromStreamExtra(Intent intent) throws WriterException { format = BarcodeFormat.QR_CODE; Bundle bundle = intent.getExtras(); if (bundle == null) { throw new WriterException("No extras"); } Uri uri = (Uri) bundle.getParcelable(Intent.EXTRA_STREAM); if (uri == null) { throw new WriterException("No EXTRA_STREAM"); } byte[] vcard; String vcardString; try { InputStream stream = activity.getContentResolver().openInputStream(uri); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int bytesRead; while ((bytesRead = stream.read(buffer)) > 0) { baos.write(buffer,BarcodeFormat.QR_CODE); ParsedResult parsedResult = ResultParser.parseResult(result); if (!(parsedResult instanceof AddressBookParsedResult)) { throw new WriterException("Result was not an address"); } encodeQRCodeContents((AddressBookParsedResult) parsedResult); if (contents == null || contents.length() == 0) { throw new WriterException("No content to encode"); } }
String fillInCustomSearchURL(String text) { if (customProductSearch == null) { return text; // ? } String url = customProductSearch.replace("%s",parsedResultAgain.getType().toString()); } } return url; }
private void encodeFromStreamExtra(Intent intent) throws WriterException { format = BarcodeFormat.QR_CODE; Bundle bundle = intent.getExtras(); if (bundle == null) { throw new WriterException("No extras"); } Uri uri = bundle.getParcelable(Intent.EXTRA_STREAM); if (uri == null) { throw new WriterException("No EXTRA_STREAM"); } byte[] vcard; String vcardString; try { InputStream stream = activity.getContentResolver().openInputStream(uri); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int bytesRead; while ((bytesRead = stream.read(buffer)) > 0) { baos.write(buffer,BarcodeFormat.QR_CODE); ParsedResult parsedResult = ResultParser.parseResult(result); if (!(parsedResult instanceof AddressBookParsedResult)) { throw new WriterException("Result was not an address"); } encodeQRCodeContents((AddressBookParsedResult) parsedResult); if (contents == null || contents.isEmpty()) { throw new WriterException("No content to encode"); } }
private void encodeFromStreamExtra(Intent intent) throws WriterException { format = BarcodeFormat.QR_CODE; Bundle bundle = intent.getExtras(); if (bundle == null) { throw new WriterException("No extras"); } Uri uri = bundle.getParcelable(Intent.EXTRA_STREAM); if (uri == null) { throw new WriterException("No EXTRA_STREAM"); } byte[] vcard; String vcardString; try { InputStream stream = activity.getContentResolver().openInputStream(uri); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int bytesRead; while ((bytesRead = stream.read(buffer)) > 0) { baos.write(buffer,"UTF-8"); } catch (IOException ioe) { throw new WriterException(ioe); } Log.d(TAG,"Encoding share intent content:"); Log.d(TAG,vcardString); Result result = new Result(vcardString,BarcodeFormat.QR_CODE); ParsedResult parsedResult = ResultParser.parseResult(result); if (!(parsedResult instanceof AddressBookParsedResult)) { throw new WriterException("Result was not an address"); } encodeQRCodeContents((AddressBookParsedResult) parsedResult); if (contents == null || contents.length() == 0) { throw new WriterException("No content to encode"); } }
private void encodeFromStreamExtra(Intent intent) throws WriterException { format = BarcodeFormat.QR_CODE; Bundle bundle = intent.getExtras(); if (bundle == null) { throw new WriterException("No extras"); } Uri uri = (Uri) bundle.getParcelable(Intent.EXTRA_STREAM); if (uri == null) { throw new WriterException("No EXTRA_STREAM"); } byte[] vcard; String vcardString; try { InputStream stream = activity.getContentResolver().openInputStream(uri); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int bytesRead; while ((bytesRead = stream.read(buffer)) > 0) { baos.write(buffer,BarcodeFormat.QR_CODE); ParsedResult parsedResult = ResultParser.parseResult(result); if (!(parsedResult instanceof AddressBookParsedResult)) { throw new WriterException("Result was not an address"); } encodeQRCodeContents((AddressBookParsedResult) parsedResult); if (contents == null || contents.length() == 0) { throw new WriterException("No content to encode"); } }
String fillInCustomSearchURL(String text) { if (customProductSearch == null) { return text; // ? } String url = customProductSearch.replace("%s",parsedResultAgain.getType().toString()); } } return url; }
private void encodeFromStreamExtra(Intent intent) throws WriterException { format = BarcodeFormat.QR_CODE; Bundle bundle = intent.getExtras(); if (bundle == null) { throw new WriterException("No extras"); } Uri uri = (Uri) bundle.getParcelable(Intent.EXTRA_STREAM); if (uri == null) { throw new WriterException("No EXTRA_STREAM"); } byte[] vcard; String vcardString; try { InputStream stream = activity.getContentResolver().openInputStream(uri); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int bytesRead; while ((bytesRead = stream.read(buffer)) > 0) { baos.write(buffer,BarcodeFormat.QR_CODE); ParsedResult parsedResult = ResultParser.parseResult(result); if (!(parsedResult instanceof AddressBookParsedResult)) { throw new WriterException("Result was not an address"); } encodeQRCodeContents((AddressBookParsedResult) parsedResult); if (contents == null || contents.length() == 0) { throw new WriterException("No content to encode"); } }
String fillInCustomSearchURL(String text) { if (customProductSearch == null) { return text; // ? } String url = customProductSearch.replace("%s",parsedResultAgain.getType().toString()); } } return url; }
@Override public void onResult(ZxingScanView scanView,Result result,float scaleFactor) { ParsedResult parsedResult = ResultParser.parseResult(result); final String format = "格式:" + result.getBarcodeFormat().toString(); final String type = "类型:" + parsedResult.getType().toString(); DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT); final String date = "时间:" + formatter.format(new Date(result.getTimestamp())); String Meta = ""; Map<ResultMetadataType,Object> Metadata = result.getResultMetadata(); if (Metadata != null) { StringBuilder MetadataText = new StringBuilder(20); for (Map.Entry<ResultMetadataType,Object> entry : Metadata.entrySet()) { if (disPLAYABLE_MetaDATA_TYPES.contains(entry.getKey())) { MetadataText.append(entry.getValue()).append('\n'); } } if (MetadataText.length() > 0) { MetadataText.setLength(MetadataText.length() - 1); Meta = MetadataText.toString(); } } CharSequence displayContents = parsedResult.getdisplayResult(); Toast.makeText(this,format + "\n" + type + "\n" + date + "\n" + Meta + "\n" + displayContents,Toast.LENGTH_SHORT).show(); // 重新扫描 scanView.restartScanDelay(3000); }
public static ResultProcessor<? extends ParsedResult> makeResultProcessor( Context context,Uri photoUri) { ParsedResult parsedResult = ResultParser.parseResult(result); switch (parsedResult.getType()) { /*case PRODUCT: return new ProductResultProcessor(context,(ProductParsedResult) parsedResult,result,photoUri);*/ case URI: return new UriResultProcessor(context,(URIParsedResult) parsedResult,photoUri); /*case ISBN: return new IsbnResultProcessor(context,(ISBNParsedResult) parsedResult,photoUri);*/ case SMS: case GEO: case TEL: case CALENDAR: case ADDRESSBOOK: case EMAIL_ADDRESS: case WIFI: // currently unsupported so we let them fall through default: return new TextResultProcessor(context,parsedResult,photoUri); } }
关于搜索引擎成果页面和Searchengineresultspage,SERP的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于android.hardware.fingerprint.FingerprintManager.AuthenticationResult的实例源码、C#编写了一个基于Lucene.Net的搜索引擎查询通用工具类:SearchEngineUtil、com.google.zxing.client.result.CalendarParsedResult的实例源码、com.google.zxing.client.result.ResultParser的实例源码的相关信息,请在本站寻找。
本文标签: