在本文中,我们将为您详细介绍com.sun.jersey.api.client.AsyncWebResource的实例源码的相关知识,并且为您解答关于jasperreport源码解读的疑问,此外,我们
在本文中,我们将为您详细介绍com.sun.jersey.api.client.AsyncWebResource的实例源码的相关知识,并且为您解答关于jasperreport源码解读的疑问,此外,我们还会提供一些关于android.webkit.WebResourceResponse的实例源码、com.facebook.common.references.ResourceReleaser的实例源码、com.google.gwt.user.client.ui.ImageResourceRenderer的实例源码、com.google.zxing.client.j2se.BufferedImageLuminanceSource的实例源码的有用信息。
本文目录一览:- com.sun.jersey.api.client.AsyncWebResource的实例源码(jasperreport源码解读)
- android.webkit.WebResourceResponse的实例源码
- com.facebook.common.references.ResourceReleaser的实例源码
- com.google.gwt.user.client.ui.ImageResourceRenderer的实例源码
- com.google.zxing.client.j2se.BufferedImageLuminanceSource的实例源码
com.sun.jersey.api.client.AsyncWebResource的实例源码(jasperreport源码解读)
public RestClientImpl(Client client,WebResource webResource,AsyncWebResource asyncWebResource,String url) { this.client = client; this.client.setReadTimeout(READ_TIMEOUT); this.webResource = webResource; this.asyncWebResource = asyncWebResource; this.url = url; }
/** * Make HTTP GET call to the given url * * @param url */ public void get(String url) { ClientConfig cc = new DefaultNonBlockingClientConfig(); Client c = NonBlockingClient.create(cc); AsyncWebResource awr = c.asyncResource(url); // makes HTTP GET call awr.get(new TypeListener<ClientResponse>(ClientResponse.class) { public void onComplete(Future<ClientResponse> f) throws InterruptedException { try { System.out.println("Got Response. HTTP Code = " + f.get().getStatus()); } catch (ExecutionException e) { System.out.println("Something went wrong!"); } } }); System.out.println("Continued to execute..."); System.out.println("Done!"); }
public void buildAsync(TypeListener<ClientResponse> listener) { AsyncWebResource.Builder builder = getAsyncWR(protocol,url,ajaxUsage); if(mediaType != null) { builder = builder.type(mediaType); } switch(method) { case GET : builder.get(listener); break; case POST : builder.post(listener,requestEntity); break; case DELETE : builder.delete(listener); break; default : throw new PinterestRuntimeException("UnkNown HTTP method"); } }
protected AsyncWebResource.Builder getAsyncWR(Protocol protocol,String url,boolean useAJAX) { if(asyncclient == null) { asyncclient = NonBlockingClient.create(getClientConfig()); } AsyncWebResource.Builder wr = null; String requestURL = String.format("%s://%s/%s",protocol.name().toLowerCase(PINTEREST_LOCALE),PINTEREST_DOMAIN,url); wr = asyncclient.asyncResource(UriBuilder.fromUri(requestURL).build()).getRequestBuilder(); wr.header("Referer","https://pinterest.com/"); if(accesstoken != null) { wr = wr.header(COOKIE_HEADER_NAME,accesstoken.generateCookieHeader()); wr = wr.header("X-CSrftoken",accesstoken.getCsrftoken().getValue()); if(useAJAX) { wr = wr.header("X-Requested-With","XMLHttpRequest"); } } return wr; }
public <T> Future<T> process(String url,final ITypeListener<T> listener,WebServicesAsyncHandler<T> handler) throws IOException { AsyncWebResource wr = client.asyncResource(url); return process(wr,listener,handler); }
public <T> Future<T> process(final AsyncWebResource wr,final WebServicesAsyncHandler<T> handler) throws IOException { return SecureExecutor.execute(new SecureExecutor.WorkLoad<Future<T>>() { @Override public Future<T> run() { return handler.process(wr,listener); } }); }
@Override public Future<T> process(AsyncWebResource webResource,ITypeListener<T> listener) { return webResource.get(listener); }
@Override public Future<T> process(AsyncWebResource webResource,ITypeListener<T> listener) { return webResource.delete(listener); }
/** * Returns jersey HTTP resource to access to the remote replication servers * * @param nexusUrl URL of the Remote Server * @param login Username on the Remote Server * @param password User's password * @return Jersey HTTP client */ private AsyncWebResource.Builder getService(String nexusUrl,String login,String password) { Client client = getClient(login,password); client.setExecutorService(jerseyHttpClientExecutor); AsyncWebResource webResource = client.asyncResource(UriBuilder.fromUri(nexusUrl).build()); webResource = webResource.path("service").path("local").path("artifact").path("maven").path("update"); return webResource.accept(MediaType.APPLICATION_XML_TYPE) .type(MediaType.APPLICATION_XML_TYPE); }
/** * Obtains a class that can be used to call a remote resource asynchronously. * * @param uri the URI of the resource,not null * @return a class that can be used to call a remote resource,not null */ public AsyncWebResource accessAsync(final URI uri) { return getClient().asyncResource(uri); }
public abstract Future<T> process(AsyncWebResource webResource,ITypeListener<T> listener);
android.webkit.WebResourceResponse的实例源码
@Override public WebResourceResponse shouldInterceptRequest(WebView view,String url) { // Intercept requests for private images and add the WP.com authorization header if (mIsPrivatePost && !TextUtils.isEmpty(mToken) && UrlUtils.isImageUrl(url)) { try { URL imageUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection(); conn.setReadTimeout(WPRestClient.REST_TIMEOUT_MS); conn.setConnectTimeout(WPRestClient.REST_TIMEOUT_MS); conn.setRequestProperty("Authorization","Bearer " + mToken); conn.setRequestProperty("User-Agent",wordpress.getUserAgent()); conn.setRequestProperty("Connection","Keep-Alive"); conn.connect(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream inputStream = new BufferedInputStream(conn.getInputStream()); return new WebResourceResponse(conn.getContentType(),"UTF-8",inputStream); } } catch (IOException e) { AppLog.e(AppLog.T.READER,e); } } return null; }
@Override public WebResourceResponse shouldInterceptRequest(WebView view,WebResourceRequest request) { /* ByteArrayInputStream EMPTY = new ByteArrayInputStream("".getBytes()); if (mAdBlock.isAd(request.getUrl().getHost())) { return new WebResourceResponse("text/plain","utf-8",EMPTY); } if(request.getUrl().getHost().indexOf("127.0.0.1")>=0){ //ToastUtil.showMessage("this site is insecure"); return new WebResourceResponse("text/plain",EMPTY); } */ return super.shouldInterceptRequest(view,request); }
public WebResourceResponse getResource(String path) { int index = path.lastIndexOf("."); if (index == -1) { return null; } String ext = path.substring(index); Log.d("wlx",ext); String mini = (String) this.minitype.get(ext); if (mini == null) { return null; } try { return new WebResourceResponse(mini,new FileInputStream(this.resource + path)); } catch (FileNotFoundException e) { e.printstacktrace(); return null; } }
@Override public WebResourceResponse shouldInterceptRequest(WebView view,String url) { WebResourceResponse webResourceResponse = null; if (mCustomWebViewClient!=null){ webResourceResponse = mCustomWebViewClient.shouldInterceptRequest(view,url); } if (webResourceResponse != null){ return webResourceResponse; } if (!mIsEnableCache){ return null; } return mWebViewCache.getWebResourceResponse(this,url,mCacheStrategy,mEncoding,mCacheInterceptor); }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public WebResourceResponse shouldInterceptRequest(WebView view,WebResourceRequest request) { WebResourceResponse webResourceResponse = null; if (mCustomWebViewClient!=null){ webResourceResponse = mCustomWebViewClient.shouldInterceptRequest(view,request); } if (webResourceResponse != null){ return webResourceResponse; } if (!mIsEnableCache){ return null; } return mWebViewCache.getWebResourceResponse(this,request.getUrl().toString(),mCacheInterceptor); }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public WebResourceResponse shouldInterceptRequest(WebView view,WebResourceRequest request) { //此处对文件资源,js,css等请求资源进行拦截,替换 Log.d(TAG,"shouldInterceptRequest: request = \n" + "\nurl = " + request.getUrl().toString() + "\nmethod = " + request.getmethod() + "\nheaders = " + request.getRequestHeaders().toString()); // String url = request.getUrl().toString(); // if ((url.startsWith("https://") || url.startsWith("http://")) && (url.endsWith(".png") || url.endsWith(".jpg"))) { // Log.d(TAG,"拦截资源 :" + url); // try { // WebResourceResponse response = new WebResourceResponse(MimeTypeMap.getFileExtensionFromUrl(".jpg"),FileUtils.getInputStreamFromAssets("img/dog.jpg")); // return response; // } catch (IOException e) { // e.printstacktrace(); // } // } return super.shouldInterceptRequest(view,request); }
@Override public WebResourceResponse shouldInterceptRequest(WebView view,request); }
@Override public WebResourceResponse shouldInterceptRequest(WebView view,String url) { // Uses cache to determine if the url is ad,// and returns an empty resource for ads. boolean ad; if (!mloadedUrls.containsKey(url)) { ad = mAdBlocker.isAd(url); mloadedUrls.put(url,ad); } else { ad = mloadedUrls.get(url); } // Verbose blocked or passed urls Log.v(getClass().getSimpleName(),(ad ? "Blocked" : "Pass") + ": " + Uri.parse(url).getHost()); // Return appropriate response if(ad) { return mAdBlocker.createEmptyResource(); } return super.shouldInterceptRequest(view,url); }
/** * 获取本地资源 */ @Nullable private WebResourceResponse getWebResourceResponse(String url) { try { // 如果是图片且本地有缓存 if (isImageSuffix(url) || isgifSuffix(url)) { FileInputStream inputStream = mCache.getStream(url); if (null != inputStream) { return new WebResourceResponse(getMimeType(url),"base64",inputStream); } } } catch (Exception e) { e.printstacktrace(); } return null; }
@TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override public WebResourceResponse shouldInterceptRequest(WebView view,String url) { if (prefs.getBoolean("adblock",true)) { boolean ad; if (!loadedUrls.containsKey(url)) { ad = AdBlocker.isAd(url); loadedUrls.put(url,ad); } else { ad = loadedUrls.get(url); } return ad ? AdBlocker.createEmptyResource() : super.shouldInterceptRequest(view,url); } return super.shouldInterceptRequest(view,url); }
@Override public WebResourceResponse shouldInterceptRequest(WebView view,WebResourceRequest request) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (mAdBlock.isAd(request.getUrl().toString())) { String stweb = "\n \n \n \n BLOCKED BY AD-BLOCKER" + "\n" + "\n" + " \n" + " \n" + " \n - TO disABLE AD-BLOCKER GO TO SETTINGS/GENEARL SETTING"; ByteArrayInputStream EMPTY = new ByteArrayInputStream(stweb.getBytes()); return new WebResourceResponse("text/plain",EMPTY); } } return super.shouldInterceptRequest(view,request); }
@SuppressLint("NewApi") public WebResourceResponse shouldInterceptRequest (WebView view,WebResourceRequest request) { String url = request.getUrl().toString(); try { URL urlData = new URL(url); String path = urlData.getPath().substring(1); if (!path.endsWith(".js") && !path.endsWith(".css")) { return null; } Log.d("BasicWebViewClient","Find " + path + " from asset."); InputStream localStream = assetMgr.open(path); Log.d("BasicWebViewClient",url + " found,try load from asset."); return new WebResourceResponse((path.endsWith(".js") ? "text/javascript" : "text/css"),localStream); } catch (Exception e) { return null; } }
@SuppressWarnings("deprecation") @Override public WebResourceResponse shouldInterceptRequest(WebView view,String url) { try { URL urlData = new URL(url); String path = urlData.getPath().substring(1); if (!path.endsWith(".js") && !path.endsWith(".css")) { return null; } Log.d("BasicWebViewClient",try load from asset."); return new WebResourceResponse((url.contains(".js") ? "text/javascript" : "text/css"),localStream); } catch (Exception e) { return null; } }
/** * Attempt to retrieve the WebResourceResponse associated with the given <code>url</code>. * This method should be invoked from within * {@link android.webkit.WebViewClient#shouldInterceptRequest(android.webkit.WebView,String)}. * * @param url the url to process. * @return a response if the request URL had a matching handler,null if no handler was found. */ public WebResourceResponse shouldInterceptRequest(String url) { PathHandler handler = null; Uri uri = parseAndVerifyUrl(url); if (uri != null) { synchronized (uriMatcher) { handler = (PathHandler) uriMatcher.match(uri); } } if (handler == null) return null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { return new WebResourceResponse(handler.getMimeType(),handler.getEncoding(),new LegacyLazyInputStream(handler,uri)); } else { InputStream is = handler.handle(uri); return new WebResourceResponse(handler.getMimeType(),is); } }
public void testHostAssets() { final String testHtmlContents = "<body><div>hah</div></body>"; WebViewLocalServer assetServer = new WebViewLocalServer(new MockProtocolHandler() { @Override public InputStream openAsset(String path) throws IOException { if (path.equals("/www/test.html")) { return new ByteArrayInputStream(testHtmlContents.getBytes("utf-8")); } return null; } }); WebViewLocalServer.AssetHostingDetails details = assetServer.hostAssets("androidplatform.net","/www","/assets",true,true); assertEquals(details.getHttpPrefix(),Uri.parse("http://androidplatform.net/assets")); assertEquals(details.getHttpsPrefix(),Uri.parse("https://androidplatform.net/assets")); WebResourceResponse response = assetServer.shouldInterceptRequest("http://androidplatform.net/assets/test.html"); assertNotNull(response); assertEquals(testHtmlContents,readAsstring(response.getData(),"utf-8")); }
private WebResourceResponse loadFromAssets( String url,String assetPath,String mimeType,String encoding ) { AssetManager assetManager = this.activity.getAssets(); InputStream input = null; try { Log.d(LOG_TAG,"Loading from assets: " + assetPath); input = assetManager.open("/images/logo.png"); WebResourceResponse response = new WebResourceResponse(mimeType,encoding,input); return response; } catch (IOException e) { Log.e("WEB-APP","Error loading " + assetPath + " from assets: " + e.getMessage(),e); } return null; }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public WebResourceResponse shouldInterceptRequest(WebView aWebView,WebResourceRequest request) { String strMimeType = getFileMimeType(request.getUrl().toString()); if (strMimeType != null) { String lowerCaseUrl = strMimeType.toLowerCase(); if (lowerCaseUrl.contains("png") || lowerCaseUrl.contains("jpg") || lowerCaseUrl.contains("jpeg")) { return handleImageRequest(aWebView,request,strMimeType); } } return super.shouldInterceptRequest(aWebView,request); }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) private WebResourceResponse handleImageRequest(final WebView aWebView,final WebResourceRequest request,String strMimeType) { KCWebView webView = (KCWebView) aWebView; if (mImageDownloader == null) mImageDownloader = new KCWebImageDownloader(webView.getContext(),webView.getWebPath()); if (mWebImageHandler==null) mWebImageHandler = new KCWebImageHandler(mWebImageListener); KCWebImage webImage = mImageDownloader.downloadImageFile(request.getUrl().toString(),mWebImageHandler.add(request.getUrl().toString())); InputStream stream = webImage.getInputStream(); if (stream == null) { Log.e("image","current stream is null,download image from net"); return null; } return new WebResourceResponse(strMimeType,stream); }
@TargetApi(Build.VERSION_CODES.HONEYCOMB) private WebResourceResponse handleImageRequest(final WebView aWebView,final String aUrl,String strMimeType) { KCWebView webView = (KCWebView) aWebView; if (mImageDownloader == null) mImageDownloader = new KCWebImageDownloader(aWebView.getContext(),webView.getWebPath()); if (mWebImageHandler==null) mWebImageHandler = new KCWebImageHandler(mWebImageListener); KCWebImage webImage = mImageDownloader.downloadImageFile(aUrl,mWebImageHandler.add(aUrl)); InputStream stream = webImage.getInputStream(); if (stream == null) { Log.e("image",stream); }
@Override public WebResourceResponse loadUrl(String url) { NetflixUrl netflixUrl = new NetflixUrl(url); // note due to shouldOverrideUrlLoading,no /watch url ever gets here,so no need to cater for it if (netflixUrl.isNetflixUrl()) { client.getParams().setParameter(AllClientPNames.USER_AGENT,UserAgents.Mobile); if (netflixUrl.isTitle()) { client.getParams().setParameter(AllClientPNames.USER_AGENT,UserAgents.Desktop); return doLoadUrl(url); } else if (netflixUrl.isbrowse() || netflixUrl.isDefault()) { return doLoadUrl(url); } } // else return null; }
@SuppressWarnings("deprecation") @Override public WebResourceResponse shouldInterceptRequest(WebView view,String url) { if (url.startsWith("http://") || url.startsWith("https://")) { if (url.endsWith("//127.0.0.1/image.jpeg")) { InputStream inputStream = null; try { inputStream = fileHolder.openInputStream(); return new WebResourceResponse(fileHolder.getimageType() == FileHolder.ImageType.IMAGE_SVG ? "image/svg+xml" : "image/jpeg",null,inputStream); } catch (IOException e) { IoUtils.close(inputStream); } } return new WebResourceResponse("text/html",null); } else { return null; } }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public WebResourceResponse shouldInterceptRequest(@NonNull WebView view,@NonNull WebResourceRequest request) { String url = request.getUrl().toString(); if (url.contains("ads.js") || url.contains("f.js") || url.contains("pop.js") || url.contains("syndication.exoclick.com")) { return new WebResourceResponse("text/plain",nothing); } else if (url.contains("main.js")) { return getWebResourceResponseFromAsset(getSite(),"main.js",TYPE.JS); } else if (url.contains("exoclick.com") || url.contains("juicyadultads.com")) { return new WebResourceResponse("text/plain",nothing); } else { return super.shouldInterceptRequest(view,request); } }
@TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override public WebResourceResponse shouldInterceptRequest(WebView view,String url) { try { // Check the against the whitelist and lock out access to the WebView directory // Changing this will cause problems for your application if (!parentEngine.pluginManager.shouldAllowRequest(url)) { LOG.w(TAG,"URL blocked by whitelist: " + url); // Results in a 404. return new WebResourceResponse("text/plain",null); } CordovaResourceApi resourceApi = parentEngine.resourceApi; Uri origUri = Uri.parse(url); // Allow plugins to intercept WebView requests. Uri remappedUri = resourceApi.remapUri(origUri); if (!origUri.equals(remappedUri) || needsspecialsInAssetUrlFix(origUri) || needsKitKatContentUrlFix(origUri)) { CordovaResourceApi.OpenForReadResult result = resourceApi.openForRead(remappedUri,true); return new WebResourceResponse(result.mimeType,result.inputStream); } // If we don't need to special-case the request,let the browser load it. return null; } catch (IOException e) { if (!(e instanceof FileNotFoundException)) { LOG.e(TAG,"Error occurred while loading a file (returning a 404).",e); } // Results in a 404. return new WebResourceResponse("text/plain",null); } }
protected WebResourceResponse shouldInterceptRequest(WebView webView,Uri uri) { if (!CID_SCHEME.equals(uri.getScheme())) { return RESULT_DO_NOT_INTERCEPT; } if (attachmentResolver == null) { return RESULT_DUMMY_RESPONSE; } String cid = uri.getSchemeSpecificPart(); if (TextUtils.isEmpty(cid)) { return RESULT_DUMMY_RESPONSE; } Uri attachmentUri = attachmentResolver.getAttachmentUriForContentId(cid); if (attachmentUri == null) { return RESULT_DUMMY_RESPONSE; } Context context = webView.getContext(); ContentResolver contentResolver = context.getContentResolver(); try { String mimeType = contentResolver.getType(attachmentUri); InputStream inputStream = contentResolver.openInputStream(attachmentUri); WebResourceResponse webResourceResponse = new WebResourceResponse(mimeType,inputStream); addCacheControlHeader(webResourceResponse); return webResourceResponse; } catch (Exception e) { Timber.e(e,"Error while intercepting URI: %s",uri); return RESULT_DUMMY_RESPONSE; } }
@Override public WebResourceResponse shouldInterceptRequest(WebView view,String url) { url = url.toLowerCase(); if(!url.contains(homeurl)){ if (!ADFilterTool.hasAd(context,url)) { return super.shouldInterceptRequest(view,url); }else{ return new WebResourceResponse(null,null); } }else{ return super.shouldInterceptRequest(view,url); }}
@TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override public WebResourceResponse shouldInterceptRequest(WebView view,null); } }
@Override public Object createWebResourceResponse(String mimeType,String encoding,InputStream data,Map<String,String> headers) { WebResourceResponse resourceResponse = new WebResourceResponse(mimeType,data); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { resourceResponse.setResponseHeaders(headers); } return resourceResponse; }
@Override public WebResourceResponse shouldInterceptRequest(WebView view,String url) { if (sonicSession != null) { return (WebResourceResponse) sonicSession.getSessionClient().requestResource(url); } return null; }
@Deprecated public WebResourceResponse shouldInterceptRequest(WebView view,String url) { if(mWebViewClient!=null){ return mWebViewClient.shouldInterceptRequest(view,url); } return super.shouldInterceptRequest(view,url); }
public WebResourceResponse shouldInterceptRequest(WebView view,WebResourceRequest request) { if(mWebViewClient!=null){ return mWebViewClient.shouldInterceptRequest(view,request); } return super.shouldInterceptRequest(view,request); }
public void onReceivedHttpError( WebView view,WebResourceRequest request,WebResourceResponse errorResponse) { if(mWebViewClient!=null){ mWebViewClient.onReceivedHttpError(view,errorResponse); return; } super.onReceivedHttpError(view,errorResponse); }
@Override public WebResourceResponse shouldInterceptRequest(WebView view,String url) { if (mAdBlock.isAd(url)) { ByteArrayInputStream EMPTY = new ByteArrayInputStream("".getBytes()); return new WebResourceResponse("text/plain",EMPTY); } return null; }
/** * 加载资源 * android5.0以下支持,注意:5.0+系统也会执行该方法 * * @param view * @param url * @return */ @Override public WebResourceResponse shouldInterceptRequest(WebView view,String url) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { return super.shouldInterceptRequest(view,url); } else { return loadPage.shouldInterceptRequest(view,url); } }
/** * 加载资源 * android5.0+支持 * * @param view * @param request * @return */ @Override public WebResourceResponse shouldInterceptRequest(WebView view,WebResourceRequest request) { WebResourceResponse resourceResponse = null; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { resourceResponse = loadPage.shouldInterceptRequest(view,request.getUrl().toString()); } if (resourceResponse == null) { return super.shouldInterceptRequest(view,request); } else { return resourceResponse; } }
@Override public Object createWebResourceResponse(String mimeType,String> headers) { WebResourceResponse resourceResponse = new WebResourceResponse(mimeType,data); if (SysUtils.hasLollipop()) { resourceResponse.setResponseHeaders(headers); } return resourceResponse; }
@Override public WebResourceResponse shouldInterceptRequest(WebView view,String url) { if (sonicSession != null) { return (WebResourceResponse) sonicSession.getSessionClient().requestResource(url); } return null; }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public WebResourceResponse shouldInterceptRequest(WebView view,WebResourceRequest request) { Uri url = request.getUrl(); if ("https://www.fengshihao.com/user.js".indexOf(url.toString()) == 0) { final WebResourceResponse userjs = new WebResourceResponse("text/javascript",new ByteArrayInputStream("console.log('hello user js');".getBytes())); return userjs; } return super.shouldInterceptRequest(view,request); }
@TargetApi(21) public WebResourceResponse shouldInterceptRequest(WebView view,WebResourceRequest request) { LogInfo.log("ZSM sFromNative shouldInterceptRequest == " + NativeWebViewUtils.getInstance().getFromNative() + " request == " + request.getUrl().toString()); if (!NativeWebViewUtils.getInstance().getFromNative()) { return super.shouldInterceptRequest(view,request); } super.shouldInterceptRequest(view,request); return NativeWebViewUtils.getInstance().getResource(request.getUrl().toString()); }
@Override public void onReceivedHttpError(WebView view,WebResourceResponse errorResponse) { if (mCustomWebViewClient!=null){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { mCustomWebViewClient.onReceivedHttpError(view,errorResponse); } return; } super.onReceivedHttpError(view,errorResponse); }
com.facebook.common.references.ResourceReleaser的实例源码
@Test public void testWidthAndHeightWithRotatedImage() { // Reverse width and height as the rotation angle should put them back again mBitmap = Bitmap.createBitmap(HEIGHT,WIDTH,Bitmap.Config.ARGB_8888); ResourceReleaser<Bitmap> releaser = SimpleBitmapReleaser.getInstance(); mCloseableStaticBitmap = new CloseableStaticBitmap( mBitmap,releaser,ImmutableQualityInfo.FULL_QUALITY,90,ExifInterface.ORIENTATION_ROTATE_90); assertthat(mCloseableStaticBitmap.getWidth()).isEqualTo(WIDTH); assertthat(mCloseableStaticBitmap.getHeight()).isEqualTo(HEIGHT); }
@Test public void testWidthAndHeightWithInvertedOrientationImage() { // Reverse width and height as the inverted orienvation should put them back again mBitmap = Bitmap.createBitmap(HEIGHT,ExifInterface.ORIENTATION_TRANSPOSE); assertthat(mCloseableStaticBitmap.getWidth()).isEqualTo(WIDTH); assertthat(mCloseableStaticBitmap.getHeight()).isEqualTo(HEIGHT); }
public BitmapCounter(int maxCount,int maxSize) { Preconditions.checkArgument(maxCount > 0); Preconditions.checkArgument(maxSize > 0); mMaxCount = maxCount; mMaxSize = maxSize; mUnpooledBitmapsReleaser = new ResourceReleaser<Bitmap>() { @Override public void release(Bitmap value) { try { decrease(value); } finally { value.recycle(); } } }; }
public SharedByteArray( MemoryTrimmableRegistry memoryTrimmableRegistry,PoolParams params) { Preconditions.checkNotNull(memoryTrimmableRegistry); Preconditions.checkArgument(params.minBucketSize > 0); Preconditions.checkArgument(params.maxBucketSize >= params.minBucketSize); mMaxByteArraySize = params.maxBucketSize; mMinByteArraySize = params.minBucketSize; mByteArraySoftRef = new OOMSoftReference<byte[]>(); mSemaphore = new Semaphore(1); mResourceReleaser = new ResourceReleaser<byte[]>() { @Override public void release(byte[] unused) { mSemaphore.release(); } }; memoryTrimmableRegistry.registerMemoryTrimmable(this); }
@Test public void testWidthAndHeightWithRotatedImage() { // Reverse width and height as the rotation angle should put them back again mBitmap = Bitmap.createBitmap(HEIGHT,ExifInterface.ORIENTATION_ROTATE_90); assertthat(mCloseableStaticBitmap.getWidth()).isEqualTo(WIDTH); assertthat(mCloseableStaticBitmap.getHeight()).isEqualTo(HEIGHT); }
@Test public void testWidthAndHeightWithInvertedOrientationImage() { // Reverse width and height as the inverted orienvation should put them back again mBitmap = Bitmap.createBitmap(HEIGHT,ExifInterface.ORIENTATION_TRANSPOSE); assertthat(mCloseableStaticBitmap.getWidth()).isEqualTo(WIDTH); assertthat(mCloseableStaticBitmap.getHeight()).isEqualTo(HEIGHT); }
public BitmapCounter(int maxCount,int maxSize) { Preconditions.checkArgument(maxCount > 0); Preconditions.checkArgument(maxSize > 0); mMaxCount = maxCount; mMaxSize = maxSize; mUnpooledBitmapsReleaser = new ResourceReleaser<Bitmap>() { @Override public void release(Bitmap value) { try { decrease(value); } finally { value.recycle(); } } }; }
public SharedByteArray( MemoryTrimmableRegistry memoryTrimmableRegistry,PoolParams params) { Preconditions.checkNotNull(memoryTrimmableRegistry); Preconditions.checkArgument(params.minBucketSize > 0); Preconditions.checkArgument(params.maxBucketSize >= params.minBucketSize); mMaxByteArraySize = params.maxBucketSize; mMinByteArraySize = params.minBucketSize; mByteArraySoftRef = new OOMSoftReference<byte[]>(); mSemaphore = new Semaphore(1); mResourceReleaser = new ResourceReleaser<byte[]>() { @Override public void release(byte[] unused) { mSemaphore.release(); } }; memoryTrimmableRegistry.registerMemoryTrimmable(this); }
public PooledByteArrayBufferedInputStream( InputStream inputStream,byte[] byteArray,ResourceReleaser<byte[]> resourceReleaser) { mInputStream = Preconditions.checkNotNull(inputStream); mByteArray = Preconditions.checkNotNull(byteArray); mResourceReleaser = Preconditions.checkNotNull(resourceReleaser); mBufferedSize = 0; mBufferOffset = 0; mClosed = false; }
/** Creates a new reference for the client. */ private synchronized CloseableReference<V> newClientReference(final Entry<K,V> entry) { increaseClientCount(entry); return CloseableReference.of( entry.valueRef.get(),new ResourceReleaser<V>() { @Override public void release(V unused) { releaseClientReference(entry); } }); }
/** * Creates a new instance of a CloseableStaticBitmap. * * @param bitmap the bitmap to wrap * @param resourceReleaser ResourceReleaser to release the bitmap to */ public CloseableStaticBitmap( Bitmap bitmap,ResourceReleaser<Bitmap> resourceReleaser,QualityInfo qualityInfo,int rotationAngle) { this(bitmap,resourceReleaser,qualityInfo,rotationAngle,ExifInterface.ORIENTATION_UNDEFINED); }
/** * Creates a new instance of a CloseableStaticBitmap. * * @param bitmap the bitmap to wrap * @param resourceReleaser ResourceReleaser to release the bitmap to */ public CloseableStaticBitmap( Bitmap bitmap,int rotationAngle,int exifOrientation) { mBitmap = Preconditions.checkNotNull(bitmap); mBitmapReference = CloseableReference.of( mBitmap,Preconditions.checkNotNull(resourceReleaser)); mQualityInfo = qualityInfo; mRotationAngle = rotationAngle; mExifOrientation = exifOrientation; }
@Before public void setUp() { mBitmap = Bitmap.createBitmap(WIDTH,HEIGHT,ExifInterface.ORIENTATION_norMAL); }
public FlexByteArrayPool( MemoryTrimmableRegistry memoryTrimmableRegistry,PoolParams params) { Preconditions.checkArgument(params.maxnumThreads > 0); mDelegatePool = new SoftRefByteArrayPool( memoryTrimmableRegistry,params,NoOpPoolStatsTracker.getInstance()); mResourceReleaser = new ResourceReleaser<byte[]>() { @Override public void release(byte[] unused) { FlexByteArrayPool.this.release(unused); } }; }
@Before public void setUp() { MockitoAnnotations.initMocks(this); mResourceReleaser = mock(ResourceReleaser.class); mResultRef1 = CloseableReference.of(new Object(),mResourceReleaser); mResultRef2 = CloseableReference.of(new Object(),mResourceReleaser); mResultRef3 = CloseableReference.of(new Object(),mResourceReleaser); mException = mock(Exception.class); mDataSubscriber1 = mock(DataSubscriber.class); mDataSubscriber2 = mock(DataSubscriber.class); mSettableProducerContext = mock(SettableProducerContext.class); when(mSettableProducerContext.getId()).thenReturn(mRequestId); when(mSettableProducerContext.isPrefetch()).thenReturn(false); mProducer = mock(Producer.class); mDataSource = CloseableProducerToDataSourceAdapter.create( mProducer,mSettableProducerContext,mRequestListener); ArgumentCaptor<Consumer> captor = ArgumentCaptor.forClass(Consumer.class); verify(mRequestListener).onRequestStart( mSettableProducerContext.getimageRequest(),mSettableProducerContext.getCallerContext(),mRequestId,mSettableProducerContext.isPrefetch()); verify(mProducer).produceResults(captor.capture(),any(SettableProducerContext.class)); mInternalConsumer = captor.getValue(); mDataSource.subscribe(mDataSubscriber1,CallerThreadExecutor.getInstance()); }
@Before public void setUp() { mBitmap = MockBitmapFactory.create(); mBitmapCounter = new BitmapCounter(MAX_BITMAP_COUNT,MAX_BITMAP_SIZE); mockStatic(BitmapCounterProvider.class); when(BitmapCounterProvider.get()).thenReturn(mBitmapCounter); mockStatic(BitmapFactory.class); when(BitmapFactory.decodeFileDescriptor( any(FileDescriptor.class),any(Rect.class),any(BitmapFactory.Options.class))) .thenReturn(mBitmap); mInputBuf = new byte[LENGTH]; PooledByteBuffer input = new TrivialPooledByteBuffer(mInputBuf,POINTER); mByteBufferRef = CloseableReference.of(input); mEncodedImage = new EncodedImage(mByteBufferRef); mDecodeBuf = new byte[LENGTH + 2]; mDecodeBufRef = CloseableReference.of(mDecodeBuf,mock(ResourceReleaser.class)); mockStatic(Bitmaps.class); mGingerbreadPurgeableDecoder = new GingerbreadPurgeableDecoder(); }
@Before public void setUp() { mFlexByteArrayPool = mock(FlexByteArrayPool.class); mBitmap = MockBitmapFactory.create(); mBitmapCounter = new BitmapCounter(MAX_BITMAP_COUNT,MAX_BITMAP_SIZE); mockStatic(BitmapCounterProvider.class); when(BitmapCounterProvider.get()).thenReturn(mBitmapCounter); mockStatic(BitmapFactory.class); when(BitmapFactory.decodeByteArray( any(byte[].class),anyInt(),mock(ResourceReleaser.class)); when(mFlexByteArrayPool.get(Integer.valueOf(LENGTH))).thenReturn(mDecodeBufRef); mockStatic(Bitmaps.class); mKitKatPurgeableDecoder = new KitKatPurgeableDecoder(mFlexByteArrayPool); }
@Before public void setUp() { mResourceReleaser = mock(ResourceReleaser.class); final byte[] bytes = new byte[256]; for (int i = 0; i < 256; ++i) { bytes[i] = (byte) i; } InputStream unbufferedStream = new ByteArrayInputStream(bytes); mBuffer = new byte[10]; mPooledByteArrayBufferedInputStream = new PooledByteArrayBufferedInputStream( unbufferedStream,mBuffer,mResourceReleaser); }
public PooledByteArrayBufferedInputStream( InputStream inputStream,ResourceReleaser<byte[]> resourceReleaser) { mInputStream = Preconditions.checkNotNull(inputStream); mByteArray = Preconditions.checkNotNull(byteArray); mResourceReleaser = Preconditions.checkNotNull(resourceReleaser); mBufferedSize = 0; mBufferOffset = 0; mClosed = false; }
/** Creates a new reference for the client. */ private synchronized CloseableReference<V> newClientReference(final Entry<K,new ResourceReleaser<V>() { @Override public void release(V unused) { releaseClientReference(entry); } }); }
/** * Creates a new instance of a CloseableStaticBitmap. * * @param bitmap the bitmap to wrap * @param resourceReleaser ResourceReleaser to release the bitmap to */ public CloseableStaticBitmap( Bitmap bitmap,ExifInterface.ORIENTATION_UNDEFINED); }
/** * Creates a new instance of a CloseableStaticBitmap. * * @param bitmap the bitmap to wrap * @param resourceReleaser ResourceReleaser to release the bitmap to */ public CloseableStaticBitmap( Bitmap bitmap,Preconditions.checkNotNull(resourceReleaser)); mQualityInfo = qualityInfo; mRotationAngle = rotationAngle; mExifOrientation = exifOrientation; }
@Before public void setUp() { mBitmap = Bitmap.createBitmap(WIDTH,ExifInterface.ORIENTATION_norMAL); }
public FlexByteArrayPool( MemoryTrimmableRegistry memoryTrimmableRegistry,NoOpPoolStatsTracker.getInstance()); mResourceReleaser = new ResourceReleaser<byte[]>() { @Override public void release(byte[] unused) { FlexByteArrayPool.this.release(unused); } }; }
@Before public void setUp() { MockitoAnnotations.initMocks(this); mResourceReleaser = mock(ResourceReleaser.class); mResultRef1 = CloseableReference.of(new Object(),CallerThreadExecutor.getInstance()); }
@Before public void setUp() { mBitmap = MockBitmapFactory.create(); mBitmapCounter = new BitmapCounter(MAX_BITMAP_COUNT,mock(ResourceReleaser.class)); mockStatic(Bitmaps.class); mGingerbreadPurgeableDecoder = new GingerbreadPurgeableDecoder(); }
@Before public void setUp() { mFlexByteArrayPool = mock(FlexByteArrayPool.class); mBitmap = MockBitmapFactory.create(); mBitmapCounter = new BitmapCounter(MAX_BITMAP_COUNT,mock(ResourceReleaser.class)); when(mFlexByteArrayPool.get(Integer.valueOf(LENGTH))).thenReturn(mDecodeBufRef); mockStatic(Bitmaps.class); mKitKatPurgeableDecoder = new KitKatPurgeableDecoder(mFlexByteArrayPool); }
@Before public void setUp() { mResourceReleaser = mock(ResourceReleaser.class); final byte[] bytes = new byte[256]; for (int i = 0; i < 256; ++i) { bytes[i] = (byte) i; } InputStream unbufferedStream = new ByteArrayInputStream(bytes); mBuffer = new byte[10]; mPooledByteArrayBufferedInputStream = new PooledByteArrayBufferedInputStream( unbufferedStream,mResourceReleaser); }
public ResourceReleaser<Bitmap> getReleaser() { return mUnpooledBitmapsReleaser; }
public ResourceReleaser<Bitmap> getReleaser() { return mUnpooledBitmapsReleaser; }
com.google.gwt.user.client.ui.ImageResourceRenderer的实例源码
private void columnDeleteRestore(SafeHtmlBuilder sb,FileInfo info) { sb.openTd().setStyleName(R.css().restoreDelete()); if (hasUser) { if (!Patch.isMagic(info.path())) { boolean editable = isEditable(info); sb.openDiv() .openElement("button") .setAttribute("title",Resources.C.restoreFileInline()) .setAttribute("onclick",RESTORE + "(event," + info._row() + ")") .append(new ImageResourceRenderer().render(Gerrit.RESOURCES.editUndo())) .closeElement("button"); if (editable) { sb.openElement("button") .setAttribute("title",Resources.C.removeFileInline()) .setAttribute("onclick",DELETE + "(event," + info._row() + ")") .append(new ImageResourceRenderer().render(Gerrit.RESOURCES.rednot())) .closeElement("button"); } sb.closeDiv(); } } sb.closeTd(); }
@UiConstructor public MyMenuItem(String text,ImageResource res) { super(SafeHtmlUtils.fromString(text)); ImageResourceRenderer renderer = new ImageResourceRenderer(); setHTML(renderer.render(res).asstring() + " " + text); }
void populate(int row,PluginInfo plugin) { if (plugin.disabled() || plugin.indexUrl() == null) { table.setText(row,1,plugin.name()); } else { table.setWidget( row,new Anchor(plugin.name(),Gerrit.selfRedirect(plugin.indexUrl()),"_blank")); if (new ExtensionScreen(plugin.name() + "/settings").isFound()) { InlineHyperlink adminScreenLink = new InlineHyperlink(); adminScreenLink.setHTML(new ImageResourceRenderer().render(Gerrit.RESOURCES.gear())); adminScreenLink.setTargetHistoryToken("/x/" + plugin.name() + "/settings"); adminScreenLink.setTitle(AdminConstants.I.pluginSettingsToolTip()); table.setWidget(row,2,adminScreenLink); } } table.setText(row,3,plugin.version()); table.setText( row,4,plugin.disabled() ? AdminConstants.I.plugindisabled() : AdminConstants.I.pluginEnabled()); final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.addStyleName(row,Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row,Gerrit.RESOURCES.css().dataCell()); setRowItem(row,plugin); }
private List<InlineHyperlink> getUnifiedDiffLink() { InlineHyperlink toUnifiedDiffLink = new InlineHyperlink(); toUnifiedDiffLink.setHTML(new ImageResourceRenderer().render(Gerrit.RESOURCES.unifiedDiff())); toUnifiedDiffLink.setTargetHistoryToken( dispatcher.toUnified(getProject(),base,revision,path)); toUnifiedDiffLink.setTitle(PatchUtil.C.unifiedDiff()); return Collections.singletonList(toUnifiedDiffLink); }
private Widget createEditIcon() { PatchSet.Id id = idActive.isBaSEOrAutoMerge() ? other.idActive.asPatchSetId() : idActive.asPatchSetId(); Anchor anchor = new Anchor( new ImageResourceRenderer().render(Gerrit.RESOURCES.edit()),"#" + dispatcher.toEditScreen(project,id,path)); anchor.setTitle(PatchUtil.C.edit()); return anchor; }
private Anchor createDownloadLink() { DiffObject diffObject = idActive.isBaSEOrAutoMerge() ? other.idActive : idActive; String sideURL = idActive.isBaSEOrAutoMerge() ? "1" : "0"; String base = GWT.getHostPageBaseURL() + "cat/"; Anchor anchor = new Anchor( new ImageResourceRenderer().render(Gerrit.RESOURCES.downloadIcon()),base + KeyUtil.encode(diffObject.asPatchSetId() + "," + path) + "^" + sideURL); anchor.setTitle(PatchUtil.C.download()); return anchor; }
private List<InlineHyperlink> getSideBySideDiffLink() { InlineHyperlink toSideBySideDiffLink = new InlineHyperlink(); toSideBySideDiffLink.setHTML( new ImageResourceRenderer().render(Gerrit.RESOURCES.sideBySideDiff())); toSideBySideDiffLink.setTargetHistoryToken( dispatcher.toSideBySide(getProject(),path)); toSideBySideDiffLink.setTitle(PatchUtil.C.sideBySideDiff()); return Collections.singletonList(toSideBySideDiffLink); }
private SafeHtmlBuilder formatHashtags(JsArrayString hashtags) { SafeHtmlBuilder html = new SafeHtmlBuilder(); Iterator<String> itr = Natives.asList(hashtags).iterator(); while (itr.hasNext()) { String hashtagName = itr.next(); html.openSpan() .setAttribute(DATA_ID,hashtagName) .setStyleName(style.hashtagName()) .openAnchor() .setAttribute("href","#" + PageLinks.tochangeQuery("hashtag:\"" + hashtagName + "\"")) .setAttribute("role","listitem") .openSpan() .setStyleName(style.hashtagIcon()) .append(new ImageResourceRenderer().render(Gerrit.RESOURCES.hashtag())) .closeSpan() .append(" ") .append(hashtagName) .closeAnchor(); if (canEdit) { html.openElement("button") .setAttribute("title","Remove hashtag") .setAttribute("onclick",REMOVE + "(event)") .append("×") .closeElement("button"); } html.closeSpan(); if (itr.hasNext()) { html.append(' '); } } return html; }
private void renderLinksToDiff() { InlineHyperlink sbs = new InlineHyperlink(); sbs.setHTML(new ImageResourceRenderer().render(Gerrit.RESOURCES.sideBySideDiff())); sbs.setTargetHistoryToken( dispatcher.toPatch(projectKey,"sidebyside",null,new Patch.Key(revision,path))); sbs.setTitle(PatchUtil.C.sideBySideDiff()); linkPanel.add(sbs); InlineHyperlink unified = new InlineHyperlink(); unified.setHTML(new ImageResourceRenderer().render(Gerrit.RESOURCES.unifiedDiff())); unified.setTargetHistoryToken( dispatcher.toPatch(projectKey,"unified",path))); unified.setTitle(PatchUtil.C.unifiedDiff()); linkPanel.add(unified); }
private Anchor createblameIcon() { Anchor anchor = new Anchor(new ImageResourceRenderer().render(Gerrit.RESOURCES.blame())); anchor.setTitle(PatchUtil.C.blame()); return anchor; }
public FerriesRouteSchedulesViewGwtImpl() { pullToRefresh = new PullPanel(); pullArrowHeader = new PullArrowHeader(); pullToRefresh.setHeader(pullArrowHeader); cellList = new CellList<FerriesRouteItem>( new FerriesRouteSchedulesCell<FerriesRouteItem>() { private ImageResourceRenderer imageRenderer = new ImageResourceRenderer(); @Override public String getDescription(FerriesRouteItem model) { return model.getDescription(); } @Override public String getLastUpdated(FerriesRouteItem model) { return ParserUtils.relativeTime(model.getCacheDate(),"MMMM d,yyyy h:mm a",false); } @Override public SafeHtml getAlertimage(FerriesRouteItem model) { boolean hasAlerts = false; if (!model.getRoutealert().equals("[]")) hasAlerts = true; SafeHtml image = imageRenderer.render(AppBundle.INSTANCE.btnAlertPNG()); return hasAlerts ? image : SafeHtmlUtils.fromString(""); } @Override public String getCrossingTime(FerriesRouteItem model) { try { if (model.getCrossingTime().equalsIgnoreCase("null")) { return ""; } else { return "Crossing Time: ~ " + model.getCrossingTime() + " min"; } } catch (Exception e) { return ""; } } }); initWidget(uiBinder.createAndBindUi(this)); accessibilityPrepare(); if (MGWT.getosDetection().isAndroid()) { leftFlexSpacer.setVisible(false); } }
com.google.zxing.client.j2se.BufferedImageLuminanceSource的实例源码
/** * @param srcImgFilePath * 要解码的图片地址 * @return {Result} */ @SuppressWarnings("finally") public static Result decode(String srcImgFilePath) { Result result = null; BufferedImage image; try { File srcFile = new File(srcImgFilePath); image = ImageIO.read(srcFile); if (null != image) { luminanceSource source = new BufferedImageluminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Hashtable<DecodeHintType,String> hints = new Hashtable<DecodeHintType,String>(); hints.put(DecodeHintType.CHaraCTER_SET,"UTF-8"); result = new MultiFormatReader().decode(bitmap,hints); } else { throw new IllegalArgumentException ("Could not decode image."); } } catch (Exception e) { e.printstacktrace(); } finally { return result; } }
/** * 条形码解码 */ public static String decode(BufferedImage image) { Result result = null; try { if (image == null) { System.out.println("the decode image may be not exit."); } luminanceSource source = new BufferedImageluminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); result = new MultiFormatReader().decode(bitmap,null); return result.getText(); } catch (Exception e) { e.printstacktrace(); } return null; }
/** * 解析二维码 * * @param file 二维码图片 * @return * @throws Exception */ public static String decode(File file) throws Exception { BufferedImage image; image = ImageIO.read(file); if (image == null) { return null; } BufferedImageluminanceSource source = new BufferedImageluminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Result result; Hashtable<DecodeHintType,Object> hints = new Hashtable<DecodeHintType,Object>(); hints.put(DecodeHintType.CHaraCTER_SET,CHARSET); result = new MultiFormatReader().decode(bitmap,hints); String resultStr = result.getText(); return resultStr; }
public static String decodeQr(String filePath) { String retStr = ""; if ("".equalsIgnoreCase(filePath) && filePath.length() == 0) { return "图片路径为空!"; } try { BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filePath)); luminanceSource source = new BufferedImageluminanceSource(bufferedImage); Binarizer binarizer = new HybridBinarizer(source); BinaryBitmap bitmap = new BinaryBitmap(binarizer); HashMap<DecodeHintType,Object> hintTypeObjectHashMap = new HashMap<>(); hintTypeObjectHashMap.put(DecodeHintType.CHaraCTER_SET,"UTF-8"); Result result = new MultiFormatReader().decode(bitmap,hintTypeObjectHashMap); retStr = result.getText(); } catch (Exception e) { logger.error("",e); } return retStr; }
public static String decodeQr(String filePath) { String retStr = ""; if ("".equalsIgnoreCase(filePath) && filePath.length() == 0) { return "图片路径为空!"; } try { BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filePath)); luminanceSource source = new BufferedImageluminanceSource(bufferedImage); Binarizer binarizer = new HybridBinarizer(source); BinaryBitmap bitmap = new BinaryBitmap(binarizer); HashMap<DecodeHintType,hintTypeObjectHashMap); retStr = result.getText(); } catch (Exception e) { e.printstacktrace(); } return retStr; }
/** * 解析条形码 */ public static String decodes(String imgPath) { BufferedImage image = null; Result result = null; try { image = ImageIO.read(new File(imgPath)); if (image == null) { System.out.println("the decode image may be not exit."); } luminanceSource source = new BufferedImageluminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); result = new MultiFormatReader().decode(bitmap,null); return result.getText(); } catch (Exception e) { e.printstacktrace(); } return null; }
public static String decodeQr(String filePath) { String retStr = ""; if ("".equalsIgnoreCase(filePath) && filePath.length() == 0) { return "图片路径为空!"; } try { BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filePath)); luminanceSource source = new BufferedImageluminanceSource(bufferedImage); Binarizer binarizer = new HybridBinarizer(source); BinaryBitmap bitmap = new BinaryBitmap(binarizer); HashMap<DecodeHintType,hintTypeObjectHashMap); retStr = result.getText(); } catch (Exception e) { e.printstacktrace(); } return retStr; }
/** * 条形码解码 * * @param imgPath 文件路径 * @return String string */ public static String decode(String imgPath) { BufferedImage image; Result result; try { image = ImageIO.read(new File(imgPath)); if (image == null) { LOGGER.error("the decode image may be not exit."); return null; } luminanceSource source = new BufferedImageluminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); result = new MultiFormatReader().decode(bitmap,null); return result.getText(); } catch (Exception e) { LOGGER.error("条形码解析错误",e); } return null; }
/** * 二维码解码 * * @param imgPath 文件路径 * @return String string */ public static String decode2(String imgPath) { BufferedImage image; Result result; try { image = ImageIO.read(new File(imgPath)); if (image == null) { LOGGER.error("the decode image may be not exit."); return null; } luminanceSource source = new BufferedImageluminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); EnumMap<DecodeHintType,Object> hints = new EnumMap<>(DecodeHintType.class); hints.put(DecodeHintType.CHaraCTER_SET,"GBK"); result = new MultiFormatReader().decode(bitmap,hints); return result.getText(); } catch (Exception e) { LOGGER.error("二维码解码错误",e); } return null; }
/** * 解析条形码 */ public static String decodes(String imgPath) { BufferedImage image = null; Result result = null; try { image = ImageIO.read(new File(imgPath)); if (image == null) { System.out.println("the decode image may be not exit."); } luminanceSource source = new BufferedImageluminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); result = new MultiFormatReader().decode(bitmap,null); return result.getText(); } catch (Exception e) { e.printstacktrace(); } return null; }
/** * 读取二维码 * @param qrCodeFile * @return */ public String readQrCode(File qrCodeFile){ String ret = null; try { QRCodeReader reader = new QRCodeReader(); BufferedImage image = ImageIO.read(qrCodeFile); luminanceSource source = new BufferedImageluminanceSource(image); Binarizer binarizer = new HybridBinarizer(source); BinaryBitmap imageBinaryBitmap = new BinaryBitmap(binarizer); Result result = reader.decode(imageBinaryBitmap); ret = result.getText(); } catch (IOException |NotFoundException | ChecksumException | FormatException e) { Exceptions.printException(e); } return ret; }
/** * 条形码解码 * * @param imgPath * @return String */ public static String decode(String imgPath) { BufferedImage image = null; Result result = null; try { image = ImageIO.read(new File(imgPath)); if (image == null) { System.out.println("the decode image may be not exit."); } luminanceSource source = new BufferedImageluminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); result = new MultiFormatReader().decode(bitmap,null); return result.getText(); } catch (Exception e) { e.printstacktrace(); } return null; }
/** * 二维码解码 * * @param imgPath * @return String */ public static String decode2(String imgPath) { BufferedImage image = null; Result result = null; try { image = ImageIO.read(new File(imgPath)); if (image == null) { System.out.println("the decode image may be not exit."); } luminanceSource source = new BufferedImageluminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Hashtable<DecodeHintType,Object>(); hints.put(DecodeHintType.CHaraCTER_SET,hints); return result.getText(); } catch (Exception e) { e.printstacktrace(); } return null; }
/** * Decode all barcodes in the image */ private String multiple(BufferedImage img) throws NotFoundException,ChecksumException,FormatException { long begin = System.currentTimeMillis(); luminanceSource source = new BufferedImageluminanceSource(img); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); com.google.zxing.Reader reader = new MultiFormatReader(); MultipleBarcodeReader bcReader = new GenericMultipleBarcodeReader(reader); Hashtable<DecodeHintType,Object>(); hints.put(DecodeHintType.TRY_HARDER,Boolean.TRUE); StringBuilder sb = new StringBuilder(); for (Result result : bcReader.decodeMultiple(bitmap,hints)) { sb.append(result.getText()).append(" "); } SystemProfiling.log(null,System.currentTimeMillis() - begin); log.trace("multiple.Time: {}",System.currentTimeMillis() - begin); return sb.toString(); }
/** * @param srcImgFilePath 要解码的图片地址 * @return */ public Result decode(String srcImgFilePath) { Result result = null; BufferedImage image; try { File srcFile = new File(srcImgFilePath); image = ImageIO.read(srcFile); if (null != image) { luminanceSource source = new BufferedImageluminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Hashtable hints = new Hashtable(); hints.put(DecodeHintType.CHaraCTER_SET,hints); } else { log.debug("Could not decode image."); } } catch (Throwable t) { log.error("decode-ex:{}",t); throw Throwables.propagate(t); } finally { return result; } }
/** * Decodes a QR code from a BufferedImage object. * * @param image * @return a Result object containing the decoded data or information about * an unsuccessful decoding attempt * @throws Exception */ private Result decode(BufferedImage image) throws Exception { // create a luminance source from the BufferedImage luminanceSource lumSource = new BufferedImageluminanceSource(image); // create a binary bitmap from the luminance source. a Binarizer // converts luminance data to 1 bit data. BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(lumSource)); // a reader for decoding QRCodeReader reader = new QRCodeReader(); // attempt decoding and return result Hashtable<DecodeHintType,Boolean> hints = new Hashtable<DecodeHintType,Boolean>(); hints.put(DecodeHintType.TRY_HARDER,true); return reader.decode(bitmap,hints); }
public static String decode(BufferedImage image) { // convert the image to a binary bitmap source luminanceSource source = new BufferedImageluminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); // decode the barcode QRCodeReader reader = new QRCodeReader(); try { @SuppressWarnings("rawtypes") Hashtable hints = new Hashtable(); Result result = reader.decode(bitmap,hints); return result.getText(); } catch (ReaderException e) { // the data is improperly formatted } return ""; }
/** * Versucht aus dem �bergeben BufferedImage ein QR Code zu finden und �bersetzt dieses in einen String. * * @param qrcodeImage : BufferedImage * @return String mit dem Inhalt des QRCodes * @throws Exception */ private static String readQRCode(BufferedImage qrcodeImage) throws Exception{ //Die Parameter anlegen Hashtable<DecodeHintType,Object> hintMap = new Hashtable<DecodeHintType,Object>(); hintMap.put(DecodeHintType.TRY_HARDER,Boolean.TRUE); //Bild zu BinaryBitmap verwandeln BufferedImageluminanceSource source = new BufferedImageluminanceSource(qrcodeImage); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); //QR Leser initialisieren... QRCodeReader reader = new QRCodeReader(); Result result; //...und lesen: result = reader.decode(bitmap,hintMap); return result.getText(); }
public String decode(BufferedImage image) throws NotFoundException { /*判断是否是图片*/ if (image == null) { System.out.println("Could not decode image"); } /*解析二维码用到的辅助类*/ luminanceSource source = new BufferedImageluminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Hashtable<DecodeHintType,Object>(); /*解码设置编码方式为:UTF-8*/ hints.put(DecodeHintType.CHaraCTER_SET,"UTF-8"); Result result = new MultiFormatReader().decode(bitmap,hints); String resultStr = result.getText(); return resultStr; }
private void scanQR(BufferedImage i) throws ReaderException,FormatException { Image img = i.getScaledInstance(200,-1,Image.SCALE_SMOOTH); // Create a buffered image with transparency i = new BufferedImage(img.getWidth(null),img.getHeight(null),BufferedImage.TYPE_INT_ARGB); // Draw the image on to the buffered image Graphics2D bGr = i.createGraphics(); bGr.drawImage(img,null); bGr.dispose(); btnDragOrPaste.setIcon(new ImageIcon(i)); BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageluminanceSource(i))); //Hashtable<EncodeHintType,String> hints = new Hashtable<EncodeHintType,String>(2); //hints.put(EncodeHintType.CHaraCTER_SET,"ISO-8859-1"); //Vector decodeFormats = new Vector<BarcodeFormat>(); //decodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS); //Hashtable hints = new Hashtable<DecodeHintType,Object>(3); //hints.put(DecodeHintType.POSSIBLE_FORMATS,decodeFormats); Result result = new QRCodeReader().decode(binaryBitmap);//,hints); //System.out.println("QR Code : "+result.getText()); textField.setText(result.getText()); //System.out.println( s ); }
private void scanQR(BufferedImage i) throws ReaderException,null); bGr.dispose(); setIcon(new ImageIcon(i)); BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageluminanceSource(i))); //Hashtable<EncodeHintType,hints); //System.out.println("QR Code : "+result.getText()); scannedQRText = result.getText(); fireEvent(); //System.out.println( s ); }
/** * Try decoding standard QR code without any of the * sequence information inserted into payload. */ @Test public void testDecodeQrWithNoSequenceInfo() { // Decode qr code received from transmitter as screenshot String filename = "fooScreenshot_noreservedBits.png"; String expectedText = "foo"; BufferedImage b = getimageResourceAndCheckNotNull(filename); luminanceSource lumSrc = new BufferedImageluminanceSource(b); assertNotNull("Unable to convert BufferedImage to luminanceSrc",lumSrc); try { Result result = Receive.decodeSingle(lumSrc); assertEquals("Expect decoded result to match expected",expectedText,result.getText()); } catch (NotFoundException e) { fail("Unable to find QR in image,"+filename + ". " + e.getMessage()); } }
public String decode(BufferedImage image) { // convert the image to a binary bitmap source luminanceSource source = new BufferedImageluminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); // decode the barcode QRCodeReader reader = new QRCodeReader(); try { @SuppressWarnings("rawtypes") Hashtable hints = new Hashtable(); Result result = reader.decode(bitmap,hints); log.info("Decoded image successfully,result was : '" + result.getText() + "'"); return result.getText(); } catch (ReaderException e) { // the data is improperly formatted log.debug(e.getMessage()); log.error("Error while decoding image",e); } return ""; }
private static String readQrcode(BufferedImage image){ MultiFormatReader formatReader = new MultiFormatReader(); BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageluminanceSource(image))); HashMap hints = new HashMap();//创建属性 hints.put(EncodeHintType.AZTEC_LAYERS,"utf-8");//设置编码 Result result = null; try { result = formatReader.decode(binaryBitmap,hints); } catch (NotFoundException e) { e.printstacktrace(); } System.out.println("结果 "+result.toString()); return result.toString(); }
public static String readQRCode(String filePath,String charset,Map hintMap) throws FileNotFoundException,IOException,NotFoundException { BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer( new BufferedImageluminanceSource( ImageIO.read(new FileInputStream(filePath))))); Result qrCodeResult = new MultiFormatReader().decode(binaryBitmap,hintMap); return qrCodeResult.getText(); }
public static String decode(InputStream input) throws IOException,NotFoundException { BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer( new BufferedImageluminanceSource( ImageIO.read(input)))); Result qrCodeResult = new MultiFormatReader().decode(binaryBitmap); return qrCodeResult.getText(); }
@Override public String read(InputStream inputStream) { try { String string = reader.decode(new BinaryBitmap(new HybridBinarizer(new BufferedImageluminanceSource(ImageIO.read(inputStream))))).getText(); inputStream.close(); return string; } catch (Throwable e) { logger.warn(e,"读取二维码图片内容时发生异常!"); return null; } }
private static void parse() throws IOException,NotFoundException,FormatException { BufferedImage image = ImageReader.readImage(Paths.get("d:/qr.png").toUri()); luminanceSource source = new BufferedImageluminanceSource(image); Binarizer bin = new HybridBinarizer(source); BinaryBitmap bitmap = new BinaryBitmap(bin); Result result = new QRCodeReader().decode(bitmap); System.out.println(result.toString()); }
/** * 解码 QRCode 图片,解析出其内容 * * @param imageURI QRCode 图片 URI * @return 解析后的内容 * @throws IOException */ public static String decodeQRCodeImage(URI imageURI) throws IOException { BufferedImage bufferedImage = ImageReader.readImage(imageURI); luminanceSource source = new BufferedImageluminanceSource(bufferedImage); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); QRCodeReader reader = new QRCodeReader(); try { Result result = reader.decode(bitmap); return result.getText(); } catch (ReaderException e) { e.printstacktrace(); } return ""; }
/** * Decode only one barcode */ @SuppressWarnings("unused") private String simple(BufferedImage img) throws NotFoundException,FormatException { long begin = System.currentTimeMillis(); luminanceSource source = new BufferedImageluminanceSource(img); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); com.google.zxing.Reader reader = new MultiFormatReader(); Result result = reader.decode(bitmap); SystemProfiling.log(null,System.currentTimeMillis() - begin); log.trace("simple.Time: {}",System.currentTimeMillis() - begin); return result.getText(); }
/** * Reads the message from a code. */ private String readImage(final Exchange exchange,final InputStream stream) throws Exception { final MultiFormatReader reader = new MultiFormatReader(); final BufferedInputStream in = exchange.getContext() .getTypeConverter() .mandatoryConvertTo(BufferedInputStream.class,stream); final BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageluminanceSource(ImageIO.read(in)))); final Result result = reader.decode(bitmap,readerHintMap); // write the found barcode format into the header exchange.getout().setHeader(Barcode.BARCODE_FORMAT,result.getBarcodeFormat()); return result.getText(); }
private void checkFormat(File file,BarcodeFormat format) throws IOException { Reader reader = new MultiFormatReader(); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageluminanceSource(ImageIO.read(file)))); Result result; try { result = reader.decode(bitmap); } catch (ReaderException ex) { throw new IOException(ex); } assertEquals(format,result.getBarcodeFormat()); }
/** * 解析QRCode二维码 */ @SuppressWarnings("unchecked") public static void decode(File file) { try { BufferedImage image; try { image = ImageIO.read(file); if (image == null) { System.out.println("Could not decode image"); } luminanceSource source = new BufferedImageluminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Result result; @SuppressWarnings("rawtypes") Hashtable hints = new Hashtable(); //解码设置编码方式为:utf-8 hints.put(DecodeHintType.CHaraCTER_SET,"utf-8"); result = new MultiFormatReader().decode(bitmap,hints); String resultStr = result.getText(); System.out.println("解析后内容:" + resultStr); } catch (IOException ioe) { System.out.println(ioe.toString()); } catch (ReaderException re) { System.out.println(re.toString()); } } catch (Exception ex) { System.out.println(ex.toString()); } }
@Override public IplImage processImage(IplImage in) { luminanceSource source = new BufferedImageluminanceSource( in.getBufferedImage()); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Result result; try { result = new MultiFormatReader().decode(bitmap); lastResult = result.getText(); lastFoundTime = System.currentTimeMillis(); fire(result.getText()); } catch (NotFoundException e) { // that's ok if (!lastResult.equals("")) // if result was not empty,clear old // result { long mt1 = System.currentTimeMillis(); if (mt1 - lastFoundTime > CLEAR_RESULT_TIMEOUT) { lastFoundTime = mt1; fire(""); lastResult = ""; } } } return in; }
private static String getQRCodeImageRawText(Path path) throws IOException,NotFoundException { Map<DecodeHintType,StandardCharsets.UTF_8.name()); try(FileInputStream fis = new FileInputStream(path.toFile())) { BufferedImage bi = ImageIO.read(fis); BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageluminanceSource(bi))); Result result = new MultiFormatReader().decode(binaryBitmap,hints); return result.getText(); } }
/** * 加载二维码图片得到Result对象 * @param bufferedImage 二维码图片 * @return */ public static Result loadResult(BufferedImage bufferedImage){ luminanceSource source = new BufferedImageluminanceSource(bufferedImage); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Hashtable<DecodeHintType,String>(); hints.put(DecodeHintType.CHaraCTER_SET,"UTF-8"); Result result = null; try { result = new MultiFormatReader().decode(bitmap,hints); } catch (NotFoundException e) { e.printstacktrace(); } return result; }
@Test public void testEncodeThenDecode() throws IOException { Transmit t = new Transmit(350,350); byte[] inputBytes = "foo".getBytes(Charsets.ISO_8859_1); // Generate some QR codes from input string Iterable<BitmapImage> qrCodes = null; try { qrCodes = t.encodeQRCodes(inputBytes); } catch (TransmitException e) { fail("Encoding Failed "+ e.getMessage()); } Iterator<BitmapImage> iter = qrCodes.iterator(); assertTrue("QR encoding Failed to return at least one element",iter.hasNext()); BitmapImage encodedQRImage = iter.next(); // Convert them to images so we can run QR decoder on them BufferedImage b = UtilsTest.toBufferedImage(encodedQRImage); luminanceSource lumSrc = new BufferedImageluminanceSource(b); Result result = decodeAndCheckValidQR(lumSrc,null); PartialMessage m = PartialMessage.createFromresult(result,Integer.MAX_VALUE); // Expect this small input will generate and decode a single QR code. assertNotNull("Expected QR code to be formatted for QRLib",m); assertEquals("Should only have 1 chunk",1,m.getTotalChunks()); assertEquals("Unexpected chunkId",m.getChunkId()); assertArrayEquals("Original input does not match decoded result",inputBytes,m.getPayload()); }
/** * Opens a test file in resources directory and converts it to ZXing's * luminanceSource image type. Causes unit tests to fail if conversion fails. * * @param filename The image file that will be converted. */ private luminanceSource getluminanceImgAndCheckNotNull(String filename) { BufferedImage b = getimageResourceAndCheckNotNull(filename); luminanceSource lumSrc = new BufferedImageluminanceSource(b); assertNotNull("Unable to convert BufferedImage to luminanceSrc",lumSrc); return lumSrc; }
/** * Convert from Java's BufferedImage type to ZXing's BitMatrix type. * Returns null when there is no QR code found in the image. * * @param img The BufferedImage to convert to BitMatrix * @return The BitMatrix of the QR code found in img */ private static BitMatrix toBitMatrix (BufferedImage img){ BufferedImageluminanceSource lumSrc = new BufferedImageluminanceSource(img); HybridBinarizer hb = new HybridBinarizer(lumSrc); try { return hb.getBlackMatrix(); } catch (NotFoundException e) { // Ok to ignore,returning null when QR code not found. // PMD complained about empty catch block return null; } }
关于com.sun.jersey.api.client.AsyncWebResource的实例源码和jasperreport源码解读的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于android.webkit.WebResourceResponse的实例源码、com.facebook.common.references.ResourceReleaser的实例源码、com.google.gwt.user.client.ui.ImageResourceRenderer的实例源码、com.google.zxing.client.j2se.BufferedImageLuminanceSource的实例源码等相关内容,可以在本站寻找。
本文标签: