while (orgBitmap.getHeight() * orgBitmap.getRowBytes() >= 32 * 1024) {
            tmp = Bitmap.createScaledBitmap(orgBitmap, orgBitmap.getWidth() * 2 / 3, orgBitmap.getHeight() * 2 / 3, true);
            orgBitmap.recycle();
            orgBitmap = tmp;
        }

package io.dcloud.share.mm;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Display;
import android.widget.Toast;
import com.nostra13.dcloudimageloader.core.DisplayImageOptions;
import com.nostra13.dcloudimageloader.core.ImageLoaderL;
import com.nostra13.dcloudimageloader.core.assist.ImageScaleType;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.modelmsg.WXMusicObject;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.modelmsg.WXVideoObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import io.dcloud.ProcessMediator;
import io.dcloud.RInformation;
import io.dcloud.common.DHInterface.FeatureMessageDispatcher;
import io.dcloud.common.DHInterface.FeatureMessageDispatcher.MessageListener;
import io.dcloud.common.DHInterface.IActivityHandler;
import io.dcloud.common.DHInterface.ISysEventListener;
import io.dcloud.common.DHInterface.IWebview;
import io.dcloud.common.adapter.util.AndroidResources;
import io.dcloud.common.adapter.util.Logger;
import io.dcloud.common.adapter.util.PlatformUtil;
import io.dcloud.common.constant.DOMException;
import io.dcloud.common.constant.StringConst;
import io.dcloud.common.util.JSONUtil;
import io.dcloud.common.util.JSUtil;
import io.dcloud.common.util.PdrUtil;
import io.dcloud.common.util.StringUtil;
import io.dcloud.share.IFShareApi;

/**
 *
Description:微信api管理者

 *
 * @author cuidengfeng Email:example@nnthink.com
 * @version 1.0
 * @Date 2013-6-13 下午3:09:14 created.
 *

 *

ModifiedLog:

 * Log ID: 1.0 (Log编号 依次递增)
 * Modified By: cuidengfeng Email:cuidengfeng@dcloud.io at 2013-6-13 下午3:09:14

 */
public class WeiXinApiManager implements IFShareApi {

    private static final String WEIXIN_DES = "微信";

    public static final String WEIXIN_ID = "weixin";

    public static final String KEY_APPID = "appid";

    public static final int THUMB_SIZE = 150;

    private static final String TAG = "WeiXinApiManager";

    private IWXAPI api;

    private static String APPID;

    private static int ERROR_NOTYPE = -100;

    private static int ERROR_NOT_COMPLETE = -101;

    @Override
    public void initConfig() {
        initData();
    }

    public void initData() {
        // AndroidManifest.xml中配置多个相同meta-data数据时使用后边的
        APPID = AndroidResources.getMetaValue("WX_APPID");
    }

    private boolean hasFullConfigData() {
        return !TextUtils.isEmpty(APPID);
    }

    // 返回false时则继续
    private boolean hasGeneralError(IWebview pWebViewImpl, String pCallbackId) {
        if (!hasFullConfigData()) {
            String msg = StringUtil.format(DOMException.JSON_ERROR_INFO, DOMException.CODE_BUSINESS_PARAMETER_HAS_NOT, DOMException.toString(DOMException.MSG_BUSINESS_PARAMETER_HAS_NOT));
            JSUtil.execCallback(pWebViewImpl, pCallbackId, msg, JSUtil.ERROR, true, false);
            return true;
        } else if (!PlatformUtil.isAppInstalled(pWebViewImpl.getContext(), "com.tencent.mm")) {
            String msg = StringUtil.format(DOMException.JSON_ERROR_INFO, DOMException.CODE_CLIENT_UNINSTALLED, DOMException.toString(DOMException.MSG_CLIENT_UNINSTALLED));
            JSUtil.execCallback(pWebViewImpl, pCallbackId, msg, JSUtil.ERROR, true, false);
            return true;
        }
        return false;
    }

    @Override
    public String getId() {
        return WEIXIN_ID;
    }

    Object[] sendCallbackMsg = null;

    private void registerSendCallbackMsg(Object[] args) {
        sendCallbackMsg = args;
    }

    void executeSendCallbackMsg(BaseResp resp) {
        if (sendCallbackMsg != null) {
            IWebview pWebViewImpl = (IWebview) sendCallbackMsg[0];
            String pCallbackId = (String) sendCallbackMsg[1];
            if (resp != null) {
                onSendCallBack(pWebViewImpl, pCallbackId, resp.errCode);
            }
        }
    }

    MessageListener sSendCallbackMessageListener = new MessageListener() {

        @Override
        public void onReceiver(Object msg) {
            if (msg instanceof BaseResp) {
                executeSendCallbackMsg((BaseResp) msg);
                FeatureMessageDispatcher.unregisterListener(sSendCallbackMessageListener);
            }
        }
    };

    // @Override
    public void send(final IWebview pWebViewImpl, final String pCallbackId, final String pShareMsg) {
        if (hasGeneralError(pWebViewImpl, pCallbackId)) {
            return;
        }
        new Thread() {

            public void run() {
                try {
                    JSONObject _msg = new JSONObject(pShareMsg);
                    String type = _msg.optString("type");
                    String _content = _msg.optString("content");
                    String _title = _msg.optString("title");
                    String href = JSONUtil.getString(_msg, "href");
                    String media = _msg.optString("media");
                    JSONArray _thumbs = _msg.optJSONArray("thumbs");
                    JSONArray _pictures = _msg.optJSONArray("pictures");
                    JSONObject extraInfo = JSONUtil.getJSONObject(_msg, "extra");
                    SendMessageToWX.Req req = new SendMessageToWX.Req();
                    // 默认分享到朋友圈
                    req.scene = SendMessageToWX.Req.WXSceneTimeline;
                    // 是否同步到朋友圈WXSceneTimeline 默认为不同步WXSceneSession，只有4.2以上的微信客户端才支持同步朋友圈
                    if (extraInfo != null && !extraInfo.isNull("scene")) {
                        String senceValue = JSONUtil.getString(extraInfo, "scene");
                        if ("WXSceneSession".equals(senceValue)) {
                            // 会话
                            req.scene = SendMessageToWX.Req.WXSceneSession;
                        } else if ("WXSceneFavorite".equals(senceValue)) {
                            // 收藏
                            req.scene = SendMessageToWX.Req.WXSceneFavorite;
                        }
                    }
                    boolean isContinue = false;
                    String pImg = null;
                    String pThumbImg = null;
                    String AbsFullPath = null;
                    String AbsFullPathThumb = null;
                    int mRunningMode = 0;
                    try {
                        if (!TextUtils.isEmpty(type)) {
                            if (type.equals("text")) {
                                isContinue = reqTextMsg(req, _content, _title);
                            } else if (type.equals("image")) {
                                if (_pictures == null || _pictures.length() == 0) {
                                    onSendCallBack(pWebViewImpl, pCallbackId, ERROR_NOT_COMPLETE);
                                    return;
                                }
                                isContinue = reqImageMsg(pWebViewImpl, req, _pictures, _thumbs, _title);
                            } else if (type.equals("music")) {
                                if (PdrUtil.isEmpty(media)) {
                                    onSendCallBack(pWebViewImpl, pCallbackId, ERROR_NOT_COMPLETE);
                                    return;
                                }
                                isContinue = reqMusicMsg(pWebViewImpl, req, media, _thumbs != null ? _thumbs.optString(0, null) : null, _content, _title);
                            } else if (type.equals("video")) {
                                if (PdrUtil.isEmpty(media)) {
                                    onSendCallBack(pWebViewImpl, pCallbackId, ERROR_NOT_COMPLETE);
                                    return;
                                }
                                isContinue = reqVideoMsg(pWebViewImpl, req, media, _thumbs != null ? _thumbs.optString(0, null) : null, _content, _title);
                            } else if (type.equals("web")) {
                                if (PdrUtil.isEmpty(href)) {
                                    onSendCallBack(pWebViewImpl, pCallbackId, ERROR_NOT_COMPLETE);
                                    return;
                                }
                                isContinue = reqWebPageMsg(pWebViewImpl, req, href, _thumbs != null ? _thumbs.optString(0, null) : null, _content, _title);
                            } else if (type.equals("miniProgram")) {
                                JSONObject miniProgram = _msg.optJSONObject("miniProgram");
                                if (miniProgram == null) {
                                    onSendCallBack(pWebViewImpl, pCallbackId, ERROR_NOT_COMPLETE);
                                    return;
                                }
                                isContinue = reqMiniMsg(pWebViewImpl, req, (_thumbs != null ? _thumbs.optString(0, null) : null), _content, _title, miniProgram);
                            } else {
                                onSendCallBack(pWebViewImpl, pCallbackId, ERROR_NOTYPE);
                                return;
                            }
                        } else if (!PdrUtil.isEmpty(href)) {
                            isContinue = reqWebPageMsg(pWebViewImpl, req, href, _thumbs != null ? _thumbs.optString(0, null) : null, _content, _title);
                        } else if (_pictures != null && _pictures.length() > 0) {
                            pImg = _pictures.optString(0);
                            pThumbImg = _thumbs == null || _thumbs.isNull(0) ? pImg : _thumbs.optString(0);
                            AbsFullPath = pWebViewImpl.obtainFrameView().obtainApp().convert2AbsFullPath(pWebViewImpl.obtainFullUrl(), pImg);
                            AbsFullPathThumb = pWebViewImpl.obtainFrameView().obtainApp().convert2AbsFullPath(pWebViewImpl.obtainFullUrl(), pThumbImg);
                            mRunningMode = pWebViewImpl.obtainFrameView().obtainApp().obtainRunningAppMode();
                            isContinue = reqImageMsg(pWebViewImpl, req, _pictures, _thumbs, _title);
                        } else {
                            isContinue = reqTextMsg(req, _content, _title);
                        }
                    } catch (Exception e) {
                        // 如遇到异常需要执行错误回调
                        e.printStackTrace();
                    }
                    if (!isContinue) {
                        pWebViewImpl.obtainWindowView().postDelayed(new Runnable() {

                            @Override
                            public void run() {
                                onSendCallBack(pWebViewImpl, pCallbackId, BaseResp.ErrCode.ERR_OK);
                            }
                        }, 500);
                        return;
                    }
                    if (pWebViewImpl.getActivity() instanceof IActivityHandler && ((IActivityHandler) pWebViewImpl.getActivity()).isMultiProcessMode()) {
                        // 多进程模式
                        startWeiXinMediator(pWebViewImpl, pCallbackId, req, pImg, pThumbImg, AbsFullPath, AbsFullPathThumb, mRunningMode);
                        return;
                    }
                    final boolean suc = api.sendReq(req);
                    if (suc && hasWXEntryActivity(pWebViewImpl.getContext())) {
                        FeatureMessageDispatcher.registerListener(sSendCallbackMessageListener);
                        registerSendCallbackMsg(new Object[] { pWebViewImpl, pCallbackId });
                    } else {
                        pWebViewImpl.obtainWindowView().postDelayed(new Runnable() {

                            @Override
                            public void run() {
                                onSendCallBack(pWebViewImpl, pCallbackId, BaseResp.ErrCode.ERR_SENT_FAILED);
                            }
                        }, 500);
                    }
                } catch (Exception e) {
                    // code ShareApiManager.SHARE_CONTENT_ERROR
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void startWeiXinMediator(final IWebview pWebViewImpl, final String pCallbackId, SendMessageToWX.Req req, String pImg, String pThumbImg, String absFullPath, String AbsFullPathThumb, int mRunningMode) {
        Intent intent = new Intent();
        intent.putExtra(ProcessMediator.LOGIC_CLASS, WeiXinMediator.class.getName());
        Bundle bundle = new Bundle();
        req.toBundle(bundle);
        bundle.putString("pImg", pImg);
        bundle.putString("pThumbImg", pThumbImg);
        bundle.putString("absFullPath", absFullPath);
        bundle.putString("AbsFullPathThumb", AbsFullPathThumb);
        bundle.putInt("mRunningMode", mRunningMode);
        intent.putExtra(ProcessMediator.REQ_DATA, bundle);
        intent.setClassName(pWebViewImpl.getActivity(), ProcessMediator.class.getName());
        pWebViewImpl.getActivity().startActivityForResult(intent, ProcessMediator.CODE_REQUEST);
        pWebViewImpl.getActivity().overridePendingTransition(0, 0);
        pWebViewImpl.obtainApp().registerSysEventListener(new ISysEventListener() {

            @Override
            public boolean onExecute(SysEventType pEventType, Object pArgs) {
                Object[] _args = (Object[]) pArgs;
                int requestCode = (Integer) _args[0];
                int resultCode = (Integer) _args[1];
                Intent data = (Intent) _args[2];
                if (pEventType == SysEventType.onActivityResult && requestCode == ProcessMediator.CODE_REQUEST) {
                    Bundle bundle = data.getBundleExtra(ProcessMediator.RESULT_DATA);
                    if (bundle == null) {
                        onSendCallBack(pWebViewImpl, pCallbackId, BaseResp.ErrCode.ERR_SENT_FAILED);
                    } else {
                        String s = bundle.getString(ProcessMediator.STYLE_DATA);
                        if ("BaseResp".equals(s)) {
                            SendMessageToWX.Resp resp = new SendMessageToWX.Resp();
                            resp.fromBundle(bundle);
                            onSendCallBack(pWebViewImpl, pCallbackId, resp.errCode);
                        } else if ("BaseReq".equals(s)) {
                        }
                    }
                }
                return false;
            }
        }, ISysEventListener.SysEventType.onActivityResult);
    }

    /**
     * 供原生代码分享调用
     *
     * @param activity
     * @param msg      flag 1是朋友圈，0是好友
     */
    public void send(final Activity activity, final String msg) {
        try {
            JSONObject msgJs = new JSONObject(msg);
            String content = msgJs.getString("content");
            String href = msgJs.getString("href");
            String thumbs = msgJs.optString("thumbs");
            int flag = msgJs.getInt("flag");
            initData();
            if (api == null) {
                api = WXAPIFactory.createWXAPI(activity.getApplicationContext(), APPID, true);
            }
            api.registerApp(APPID);
            if (!api.isWXAppInstalled()) {
                Toast.makeText(activity.getApplicationContext(), "您还未安装微信客户端", Toast.LENGTH_SHORT).show();
                return;
            }
            WXWebpageObject webpage = new WXWebpageObject();
            webpage.webpageUrl = href;
            WXMediaMessage wxmsg = new WXMediaMessage(webpage);
            wxmsg.description = content;
            wxmsg.title = content;
            Bitmap thumb = null;
            if (!TextUtils.isEmpty(thumbs) && new File(thumbs).exists()) {
                thumb = BitmapFactory.decodeFile(thumbs);
            }
            // 如果图标为null，默认用App的图标。
            if (null == thumb) {
                thumb = BitmapFactory.decodeResource(activity.getResources(), RInformation.DRAWABLE_ICON);
            }
            wxmsg.setThumbImage(thumb);
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = String.valueOf(System.currentTimeMillis());
            req.message = wxmsg;
            req.scene = flag;
            api.sendReq(req);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return;
        }
    }

    /**
     * 供原生代码分享调用-分享图片
     *
     * @param activity
     * @param msg      flag 1是朋友圈，0是好友
     */
    public void sendImage(final Activity activity, final String msg) {
        try {
            JSONObject msgJs = new JSONObject(msg);
            String image = msgJs.optString("image");
            String thumbs = msgJs.optString("thumbs");
            String textToImage = msgJs.optString("textToImage");
            int flag = msgJs.optInt("flag");
            initData();
            if (api == null) {
                api = WXAPIFactory.createWXAPI(activity.getApplicationContext(), APPID, true);
            }
            api.registerApp(APPID);
            if (!api.isWXAppInstalled()) {
                Toast.makeText(activity.getApplicationContext(), "您还未安装微信客户端", Toast.LENGTH_SHORT).show();
                return;
            }
            Bitmap imageBitmap = null;
            if (!TextUtils.isEmpty(image) && new File(image).exists()) {
                imageBitmap = BitmapFactory.decodeFile(image);
            }
            if (null == imageBitmap) {
                if (!TextUtils.isEmpty(textToImage)) {
                    imageBitmap = StringUtil.textToBitmap(activity, textToImage);
                }
            }
            if (null == imageBitmap) {
                return;
            }
            WXImageObject imageObject = new WXImageObject(imageBitmap);
            WXMediaMessage wxmsg = new WXMediaMessage(imageObject);
            wxmsg.mediaObject = imageObject;
            Bitmap thumb = null;
            if (!TextUtils.isEmpty(thumbs) && new File(thumbs).exists()) {
                thumb = BitmapFactory.decodeFile(thumbs);
            }
            // 如果图标为null，默认用App的图标。
            if (null == thumb) {
                thumb = BitmapFactory.decodeResource(activity.getResources(), RInformation.DRAWABLE_ICON);
            }
            wxmsg.setThumbImage(thumb);
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = String.valueOf(System.currentTimeMillis());
            req.message = wxmsg;
            req.scene = flag;
            api.sendReq(req);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return;
        }
    }

    /**
     * 供原生代码分享调用-分享文本
     *
     * @param activity
     * @param msg      flag 1是朋友圈，0是好友
     */
    public void sendText(final Activity activity, final String msg) {
        try {
            JSONObject msgJs = new JSONObject(msg);
            String text = msgJs.optString("text");
            int flag = msgJs.optInt("flag");
            initData();
            if (api == null) {
                api = WXAPIFactory.createWXAPI(activity.getApplicationContext(), APPID, true);
            }
            api.registerApp(APPID);
            if (!api.isWXAppInstalled()) {
                Toast.makeText(activity.getApplicationContext(), "您还未安装微信客户端", Toast.LENGTH_SHORT).show();
                return;
            }
            WXTextObject textObject = new WXTextObject();
            textObject.text = text;
            WXMediaMessage wxmsg = new WXMediaMessage(textObject);
            wxmsg.mediaObject = textObject;
            wxmsg.description = text;
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = String.valueOf(System.currentTimeMillis());
            req.message = wxmsg;
            req.scene = flag;
            api.sendReq(req);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }

    private void onSendCallBack(final IWebview pWebViewImpl, final String pCallbackId, int code) {
        boolean suc = false;
        String errorMsg = DOMException.MSG_SHARE_SEND_ERROR;
        if (code == BaseResp.ErrCode.ERR_OK) {
            suc = true;
        } else if (code == BaseResp.ErrCode.ERR_AUTH_DENIED) {
            errorMsg = "Authentication failed";
        } else if (code == BaseResp.ErrCode.ERR_COMM) {
            errorMsg = "General errors";
        } else if (code == BaseResp.ErrCode.ERR_SENT_FAILED) {
            errorMsg = "Unable to send";
        } else if (code == BaseResp.ErrCode.ERR_UNSUPPORT) {
            errorMsg = "Unsupport error";
        } else if (code == BaseResp.ErrCode.ERR_USER_CANCEL) {
            errorMsg = "User canceled";
        } else if (code == ERROR_NOT_COMPLETE) {
            errorMsg = "参数不完整无法正确send";
        } else if (code == ERROR_NOTYPE) {
            errorMsg = "type参数无法正确识别，请按规范范围填写";
        }
        if (suc) {
            // 由于调用微信发送接口，会立马回复true，而不是真正分享成功，甚至连微信界面都没有启动，在此延迟回调，以增强体验
            JSUtil.execCallback(pWebViewImpl, pCallbackId, "", JSUtil.OK, false, false);
        } else {
            String msg = StringUtil.format(DOMException.JSON_ERROR_INFO, DOMException.CODE_BUSINESS_INTERNAL_ERROR, DOMException.toString(code, "Share微信分享", errorMsg, mLink));
            JSUtil.execCallback(pWebViewImpl, pCallbackId, msg, JSUtil.ERROR, true, false);
        }
    }

    private boolean reqTextMsg(SendMessageToWX.Req req, String pText, String pTitle) {
        // 初始化一个WXTextObject对象
        WXTextObject textObj = new WXTextObject();
        textObj.text = pText;
        // 用WXTextObject对象初始化一个WXMediaMessage对象
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = textObj;
        if (!PdrUtil.isEmpty(pTitle)) {
            msg.title = pTitle;
        } else if (req.scene == SendMessageToWX.Req.WXSceneTimeline && !TextUtils.isEmpty(pText)) {
            // 如果为朋友圈分享 title为空 则使用_content未标题
            msg.title = pText;
        }
        msg.description = pText;
        // 构造一个Req
        // transaction字段用于唯一标识一个请求
        req.transaction = buildTransaction("text");
        req.message = msg;
        return true;
    }

    private boolean reqImageMsg(IWebview pWebViewImpl, SendMessageToWX.Req req, JSONArray pImgs, JSONArray pThumbImgs, String pTitle) {
        WXMediaMessage msg = new WXMediaMessage();
        // 判断个数，分享情形
        boolean mul = pImgs.length() > 1;
        // 暂只处理单个图片
        mul = false;
        if (!mul) {
            // 单个图片
            // pImg 内容大小不超过10MB  http://example.com
            if (!(pWebViewImpl.getActivity() instanceof IActivityHandler && ((IActivityHandler) pWebViewImpl.getActivity()).isMultiProcessMode())) {
                // 多进程模式
                String pImg = pImgs.optString(0);
                String pThumbImg = pThumbImgs == null || pThumbImgs.isNull(0) ? pImg : pThumbImgs.optString(0);
                if (PdrUtil.isNetPath(pImg)) {
                    WXImageObject imgObj = new WXImageObject();
                    try {
                        Bitmap bmp = BitmapFactory.decodeStream(new URL(pImg).openStream());
                        // content size within 10MB.
                        imgObj.imageData = bmpToByteArray(bmp, true);
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    msg.mediaObject = imgObj;
                    pThumbImg = PdrUtil.isEmpty(pThumbImg) ? pImg : pThumbImg;
                    msg.thumbData = buildThumbData(pWebViewImpl, pThumbImg);
                } else {
                    // imagePath The length should be within 10KB and content size within 10MB.
                    String AbsFullPath = pWebViewImpl.obtainFrameView().obtainApp().convert2LocalFullPath(pWebViewImpl.obtainFullUrl(), pImg);
                    WXImageObject imgObj = new WXImageObject();
                    // 适配AndroidQ，"content://"文件（如相册获取）
                    if (AbsFullPath.startsWith("content://")) {
                        Uri contentUri = Uri.parse(AbsFullPath);
                        InputStream inputStream = null;
                        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                        int nRead;
                        try {
                            inputStream = pWebViewImpl.getContext().getContentResolver().openInputStream(contentUri);
                            byte[] data = new byte[16384];
                            while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
                                buffer.write(data, 0, nRead);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        byte[] fileByteArr = buffer.toByteArray();
                        imgObj.imageData = fileByteArr;
                    } else {
                        imgObj.imagePath = AbsFullPath;
                    }
                    msg.mediaObject = imgObj;
                    msg.thumbData = buildThumbData(pWebViewImpl, pThumbImg);
                }
            }
        } else {
            String clssName = "com.tencent.mm.ui.tools.ShareToTimeLineUI";
            switch(req.scene) {
                case SendMessageToWX.Req.WXSceneSession:
                    clssName = "com.tencent.mm.ui.chatting.ChattingUI";
                    break;
                case // 朋友圈
                SendMessageToWX.Req.WXSceneTimeline:
                    clssName = "com.tencent.mm.ui.tools.ShareToTimeLineUI";
                    break;
                case // 收藏
                SendMessageToWX.Req.WXSceneFavorite:
                    clssName = "com.tencent.mm.plugin.favorite.ui.FavoriteIndexUI";
                    break;
            }
            ArrayList<Uri> localArrayList = new ArrayList<Uri>();
            for (int i = 0; i < pImgs.length(); i++) {
                String pic = pImgs.optString(i);
                if (PdrUtil.isNetPath(pic)) {
                    try {
                        Bitmap bmp = BitmapFactory.decodeStream(new URL(pic).openStream());
                        String t_path = pWebViewImpl.obtainApp().obtainAppTempPath() + System.currentTimeMillis() + ".png";
                        PdrUtil.saveBitmapToFile(bmp, t_path);
                        localArrayList.add(Uri.fromFile(new File(t_path)));
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    pic = pWebViewImpl.obtainApp().convert2LocalFullPath(pWebViewImpl.obtainFullUrl(), pic);
                    localArrayList.add(Uri.fromFile(new File(pic)));
                }
            }
            sedMultiplePic(pWebViewImpl.getActivity(), localArrayList, clssName);
            return false;
        }
        if (!PdrUtil.isEmpty(pTitle)) {
            // The length should be within 512Bytes
            msg.title = pTitle;
        }
        req.transaction = buildTransaction("img");
        req.message = msg;
        return true;
    }

    private boolean reqWebPageMsg(IWebview pWebViewImpl, SendMessageToWX.Req req, String webPage, String pThumbImg, String pText, String pTitle) {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = webPage;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        if (!PdrUtil.isEmpty(pTitle)) {
            // The length should be within 512Bytes
            msg.title = pTitle;
        } else if (req.scene == SendMessageToWX.Req.WXSceneTimeline && !TextUtils.isEmpty(pText)) {
            // 如果为朋友圈分享 title为空 则使用_content未标题
            msg.title = pText;
        }
        // The length should be within 1KB
        msg.description = pText;
        if (!PdrUtil.isEmpty(pThumbImg)) {
            msg.thumbData = buildThumbData(pWebViewImpl, pThumbImg);
        }
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        return true;
    }

    private boolean reqMusicMsg(IWebview pWebViewImpl, SendMessageToWX.Req req, String musicUrl, String pThumbImg, String pText, String pTitle) {
        WXMusicObject music = new WXMusicObject();
        music.musicUrl = musicUrl;
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = music;
        if (!PdrUtil.isEmpty(pTitle)) {
            msg.title = pTitle;
        } else if (req.scene == SendMessageToWX.Req.WXSceneTimeline && !TextUtils.isEmpty(pText)) {
            // 如果为朋友圈分享 title为空 则使用_content未标题
            msg.title = pText;
        }
        if (!PdrUtil.isEmpty(pThumbImg)) {
            msg.thumbData = buildThumbData(pWebViewImpl, pThumbImg);
        }
        msg.description = pText;
        req.transaction = buildTransaction("music");
        req.message = msg;
        return true;
    }

    private boolean reqVideoMsg(IWebview pWebViewImpl, SendMessageToWX.Req req, String videoUrl, String pThumbImg, String pText, String pTitle) {
        WXVideoObject video = new WXVideoObject();
        video.videoUrl = videoUrl;
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = video;
        if (!PdrUtil.isEmpty(pTitle)) {
            msg.title = pTitle;
        } else if (req.scene == SendMessageToWX.Req.WXSceneTimeline && !TextUtils.isEmpty(pText)) {
            // 如果为朋友圈分享 title为空 则使用_content未标题
            msg.title = pText;
        }
        if (!PdrUtil.isEmpty(pThumbImg)) {
            msg.thumbData = buildThumbData(pWebViewImpl, pThumbImg);
        }
        msg.description = pText;
        req.transaction = buildTransaction("video");
        req.message = msg;
        return true;
    }

    private boolean reqMiniMsg(IWebview pWebViewImpl, SendMessageToWX.Req req, String pThumbImg, String pText, String pTitle, JSONObject miniProgram) {
        WXMiniProgramObject miniProgramObj = new WXMiniProgramObject();
        miniProgramObj.webpageUrl = miniProgram.optString("webUrl");
        miniProgramObj.miniprogramType = miniProgram.optInt("type");
        // 小程序原始id
        miniProgramObj.userName = miniProgram.optString("id");
        // 小程序页面路径
        miniProgramObj.path = miniProgram.optString("path");
        WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
        if (!PdrUtil.isEmpty(pTitle)) {
            msg.title = pTitle;
        } else if (req.scene == SendMessageToWX.Req.WXSceneTimeline && !TextUtils.isEmpty(pText)) {
            // 如果为朋友圈分享 title为空 则使用_content未标题
            msg.title = pText;
        }
        // 目前支持会话
        req.scene = SendMessageToWX.Req.WXSceneSession;
        if (!PdrUtil.isEmpty(pThumbImg)) {
            msg.thumbData = getMiniThumbaData(pWebViewImpl, pThumbImg);
        }
        msg.description = pText;
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        return true;
    }

    private byte[] getMiniThumbaData(IWebview pWebViewImpl, String thumeImgPath) {
        byte[] ret = null;
        Bitmap bitmap = null;
        InputStream is = null;
        String AbsFullPath = pWebViewImpl.obtainFrameView().obtainApp().convert2LocalFullPath(pWebViewImpl.obtainFullUrl(), thumeImgPath);
        // The thumeImg size should be within 128KB * 1024 = 131072
        int maxSize = 131072;
        boolean isCompress = false;
        try {
            if (PdrUtil.isNetPath(thumeImgPath)) {
                // 是网络地址
                try {
                    is = new URL(thumeImgPath).openStream();
                    isCompress = is.available() > maxSize;
                    if (is != null) {
                        bitmap = BitmapFactory.decodeStream(is);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (is != null)
                        is.close();
                }
            } else {
                InputStream stream = new FileInputStream(AbsFullPath);
                isCompress = stream.available() > maxSize;
                bitmap = BitmapFactory.decodeStream(stream);
                if (stream != null)
                    stream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Logger.e("buildThumbData Exception=" + e);
        }
        if (bitmap == null) {
            bitmap = BitmapFactory.decodeResource(pWebViewImpl.getActivity().getResources(), RInformation.DRAWABLE_ICON);
        }
        if (bitmap != null) {
            if (isCompress) {
                bitmap = cpBitmap(bitmap);
            }
        }
        // 设置缩略图
        ret = bmpToByteArray(bitmap, true);
        return ret;
    }

    public Bitmap scaleLoadPic(IWebview pWebViewImpl, String path) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        // 默认为false，设为true，则decoder返回null，
        // 但会返回图片的参数的信息到Options对象里
        // 不解析图片到内存里
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, opts);
        // 获取图片的宽，高
        int imageWidth = opts.outWidth;
        int imageHeigth = opts.outHeight;
        // 获取屏幕的高宽
        Display dp = pWebViewImpl.getActivity().getWindowManager().getDefaultDisplay();
        // 在高版本里有新的方法获取，但图片加载是常用功能，要兼容低版本，所以过时了也用
        int screenWidth = dp.getWidth();
        int screenHeight = dp.getHeight();
        // 计算缩放比例
        int scale = 1;
        int scaleWidth = imageWidth / screenWidth;
        int scaleHeight = imageHeigth / screenHeight;
        // 取缩放比例，取那个大的值
        if (scaleWidth >= scaleHeight && scaleWidth >= 1) {
            scale = scaleWidth;
        } else if (scaleWidth < scaleHeight && scaleHeight >= 1) {
            scale = scaleHeight;
        }
        // 设置缩放比例
        opts.inSampleSize = scale;
        opts.inJustDecodeBounds = false;
        Bitmap bm = null;
        // 适配AndroidQ，"content://"文件（如相册获取）
        if (path.startsWith("content://")) {
            Uri contentUri = Uri.parse(path);
            Cursor cursor = pWebViewImpl.getContext().getContentResolver().query(contentUri, null, null, null, null);
            if (cursor != null) {
                InputStream inputStream = null;
                try {
                    inputStream = pWebViewImpl.getContext().getContentResolver().openInputStream(contentUri);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                cursor.moveToFirst();
                bm = BitmapFactory.decodeStream(inputStream, null, opts);
                // TO 成功
                cursor.close();
            }
        } else {
            bm = BitmapFactory.decodeFile(path, opts);
        }
        return bm;
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    private static Bitmap cpBitmap(Bitmap orgBitmap) {
        if (PdrUtil.isEmpty(orgBitmap)) {
            return null;
        }
        Bitmap tmp;

        return orgBitmap;
    }

    private byte[] buildThumbData(IWebview pWebViewImpl, String thumeImgPath) {
        byte[] ret = null;
        Bitmap bitmap = null;
        InputStream is = null;
        String AbsFullPath = pWebViewImpl.obtainFrameView().obtainApp().convert2LocalFullPath(pWebViewImpl.obtainFullUrl(), thumeImgPath);
        try {
            // The thumeImg size should be within 32KB * 1024 = 32768
            if (PdrUtil.isNetPath(thumeImgPath)) {
                // 是网络地址
                DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder().cacheOnDisc(false).cacheInMemory(false).imageScaleType(ImageScaleType.NONE).bitmapConfig(Bitmap.Config.RGB_565).showImageOnLoading(new ColorDrawable(Color.TRANSPARENT)).build();
                bitmap = ImageLoaderL.getInstance().loadImageSync(thumeImgPath, displayImageOptions);
            } else {
                bitmap = scaleLoadPic(pWebViewImpl, AbsFullPath);
            }
        } catch (Exception e) {
            Logger.e("buildThumbData Exception=" + e);
        }
        if (bitmap == null) {
            bitmap = BitmapFactory.decodeResource(pWebViewImpl.getActivity().getResources(), RInformation.DRAWABLE_ICON);
        }
        if (bitmap != null) {
            bitmap = cpBitmap(bitmap);
        }
        // 设置缩略图
        ret = bmpToByteArray(bitmap, true);
        return ret;
    }

    private void sedMultiplePic(Activity act, ArrayList<Uri> localArrayList, String activityClassName) {
        Intent intent = new Intent();
        // com.tencent.mm.ui.chatting.ChattingUI
        // com.tencent.mm.plugin.favorite.ui.FavoriteIndexUI
        // com.tencent.mm.ui.tools.ShareToTimeLineUI
        ComponentName localComponentName = new ComponentName("com.tencent.mm", activityClassName);
        intent.setComponent(localComponentName);
        intent.setAction("android.intent.action.SEND_MULTIPLE");
        intent.setType("image/*");
        intent.putParcelableArrayListExtra("android.intent.extra.STREAM", localArrayList);
        act.startActivity(intent);
    }

    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(CompressFormat.JPEG, 80, output);
        if (needRecycle) {
            bmp.recycle();
        }
        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public void forbid(IWebview pWebViewImpl) {
        if (api == null) {
            api = WXAPIFactory.createWXAPI(pWebViewImpl.getActivity().getApplicationContext(), APPID, true);
        }
        api.unregisterApp();
    }

    public static final String AUTHORIZE_TEMPLATE = "{authenticated:%s,accessToken:'%s'}";

    @Override
    public void authorize(IWebview pWebViewImpl, String pCallbackId, String options) {
        JSONObject jsonOptions = JSONUtil.createJSONObject(options);
        if (jsonOptions != null) {
            APPID = jsonOptions.optString(KEY_APPID, APPID);
            Logger.e(TAG, "authorize: appId" + APPID);
        }
        if (hasGeneralError(pWebViewImpl, pCallbackId)) {
            return;
        }
        boolean ret = register(pWebViewImpl);
        if (ret) {
            String msg = String.format(AUTHORIZE_TEMPLATE, ret, "");
            JSUtil.execCallback(pWebViewImpl, pCallbackId, msg, JSUtil.OK, true, false);
        } else {
            String msg = DOMException.toJSON(DOMException.CODE_BUSINESS_INTERNAL_ERROR, DOMException.toString(BaseResp.ErrCode.ERR_AUTH_DENIED, "Share微信分享", "授权失败", mLink));
            JSUtil.execCallback(pWebViewImpl, pCallbackId, msg, JSUtil.ERROR, true, false);
        }
    }

    private boolean register(IWebview pWebViewImpl) {
        if (api == null) {
            api = WXAPIFactory.createWXAPI(pWebViewImpl.getActivity().getApplicationContext(), APPID, true);
        }
        boolean ret = false;
        // 将该app注册到微信
        if (!PdrUtil.isEmpty(APPID)) {
            ret = api.registerApp(APPID);
        }
        return ret;
    }

    @Override
    public String getJsonObject(IWebview pWebViewImpl) {
        String _json = null;
        try {
            JSONObject _weiXinObj = new JSONObject();
            _weiXinObj.put(StringConst.JSON_SHARE_ID, WEIXIN_ID);
            _weiXinObj.put(StringConst.JSON_SHARE_DESCRIPTION, WEIXIN_DES);
            _weiXinObj.put(StringConst.JSON_SHARE_AUTHENTICATED, register(pWebViewImpl));
            _weiXinObj.put(StringConst.JSON_SHARE_ACCESSTOKEN, "");
            _weiXinObj.put(StringConst.JSON_SHARE_NATIVECLIENT, api.isWXAppInstalled());
            _json = _weiXinObj.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return _json;
    }

    private boolean hasWXEntryActivity(Context context) {
        String clsName = context.getPackageName() + ".wxapi.WXEntryActivity";
        try {
            Class.forName(clsName);
            return true;
        } catch (ClassNotFoundException e) {
            return false;
        }
    }

    /**
     * 打开微信小程序
     * 此方法会反射调用 查看shareApiManager.java
     * @param pOptions
     */
    public void launchMiniProgram(String pOptions) {
        try {
            JSONObject optionsJson = new JSONObject(pOptions);
            String id = optionsJson.optString("id");
            String path = optionsJson.optString("path");
            int type = optionsJson.optInt("type", 0);
            WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
            req.userName = id;
            req.path = path;
            req.miniprogramType = type;
            api.sendReq(req);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void dispose() {
        if (null != api) {
            api.unregisterApp();
            api.detach();
        }
        api = null;
    }
}


private void loadFile(String vtsPath) {
        if (reader == null) {
            reader = new vtkXMLStructuredGridReader();
        }
        reader.SetFileName(vtsPath);
        reader.Update();
    }

package starfish.gui.viewer;

import starfish.core.common.Starfish;
import starfish.core.domain.Mesh;
import starfish.core.io.OutputModule;
import starfish.core.io.VTKWriter;
import starfish.gui.runner.SimulationRunner;
import vtk.*;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class SimulationResultViewer extends JPanel {

    private SimulationRunner simRunner;

    private File vtkTempFile;

    private vtkXMLStructuredGridReader reader;

    private VTKWriter vtkWriter;

    // Pane that contains the vtkPanel and settings panel
    private final ViewerWrapper main;

    public SimulationResultViewer() {
        this(null);
    }

    public SimulationResultViewer(SimulationRunner simRunner) {
        super(new BorderLayout());
        this.simRunner = simRunner;
        createToolbar();
        main = new ViewerWrapper();
        main.getViewerSettings().setOnFormUpdate(arg0 -> updateVTKPanel());
        add(main, BorderLayout.CENTER);
    }

    private void createToolbar() {
        JButton loadFile = new JButton("Load file");
        loadFile.addActionListener(arg0 -> loadUserSelectedFile());
        JButton refreshVtkViewer = new JButton("Show current sim");
        refreshVtkViewer.addActionListener(arg0 -> loadCurrentlyRunningSimulation());
        JToolBar toolBar = new JToolBar();
        toolBar.setFloatable(false);
        toolBar.add(loadFile);
        toolBar.add(refreshVtkViewer);
        add(toolBar, BorderLayout.NORTH);
    }

    private vtkActor previousActor = null;

    private static vtkScalarBarActor scalarBarActor = new vtkScalarBarActor();

    /**
     * Updates the VTK preview to display the currently loaded file using the settings set by the user in the
     * settings panel
     */
    private void updateVTKPanel() {
        if (fileIsLoaded() && main.getVtkPanel() != null) {
            String selectedVar = main.getViewerSettings().getSelectedVar();
            vtkStructuredGrid structuredGrid = reader.GetOutput();
            structuredGrid.GetPointData().SetActiveScalars(selectedVar);
            vtkDataSetMapper mapper = new vtkDataSetMapper();
            mapper.SetInputData(structuredGrid);
            mapper.SetScalarVisibility(1);
            mapper.SetScalarModeToUsePointData();
            mapper.SetColorModeToMapScalars();
            vtkLookupTable lookupTable = main.getViewerSettings().getLookupTable(selectedVar);
            mapper.SetLookupTable(lookupTable);
            mapper.SetUseLookupTableScalarRange(1);
            scalarBarActor.SetLookupTable(lookupTable);
            scalarBarActor.SetNumberOfLabels(4);
            vtkActor actor = new vtkActor();
            if (previousActor != null) {
                previousActor.Delete();
            }
            previousActor = actor;
            actor.SetMapper(mapper);
            vtkPanel vtkPanel = main.getVtkPanel();
            vtkPanel.GetRenderer().SetBackground(.5, .5, .5);
            vtkPanel.GetRenderer().RemoveAllViewProps();
            vtkPanel.GetRenderer().AddActor(actor);
            vtkPanel.GetRenderer().AddActor2D(scalarBarActor);
            vtkPanel.repaint();
        }
    }

    /**
     * Prompts the user to select a .vts file, and then shows it in the preview
     */
    public void loadUserSelectedFile() {
        File selectedFile = promptForVTKFile();
        if (selectedFile != null) {
            loadAndUpdateEverything(selectedFile.getAbsolutePath());
        }
    }

    /**
     * Shows the state of the current simulation
     */
    public void loadCurrentlyRunningSimulation() {
        if (simRunner.getSim() != null && Starfish.getMeshList().size() > 0) {
            createVTKWriter();
            Mesh mesh = Starfish.getMeshList().get(Starfish.getMeshList().size() - 1);
            vtkWriter.write2DToFile(mesh, vtkTempFile.getAbsolutePath(), VTKWriter.VTK_Type.STRUCT);
            loadAndUpdateEverything(vtkTempFile.getAbsolutePath());
        } else {
            JOptionPane.showMessageDialog(this, "Start simulation to see preview");
        }
    }

    /**
     * Rewrites {@code vtkWriter} as a new vtkWriter to a new temp file
     */
    private void createVTKWriter() {
        try {
            vtkTempFile = File.createTempFile("StarfishViewer", ".vts");
            vtkTempFile.deleteOnExit();
            vtkWriter = new VTKWriter(vtkTempFile.getParent(), VTKWriter.OutputFormat.ASCII);
            String[] scalars = OutputModule.getAllScalars().toArray(new String[0]);
            List<String[]> vectors = new ArrayList<>(OutputModule.getAllVectors());
            String[] cellData = OutputModule.getAllCellData().toArray(new String[0]);
            vtkWriter.init2D(scalars, vectors, cellData, null);
        } catch (IOException e) {
        }
    }

    /**
     * Loads the file into {@code reader}, then updates the {@code vtkPanel}, updates the variables in the menu, etc.
     * @param vtkPath absolute path to .vts file
     */
    private void loadAndUpdateEverything(String vtkPath) {
        loadFile(vtkPath);
        updateVarChoices();
        updateVTKPanel();
        if (!main.isShowingVTKPanel()) {
            main.showVTKPanel();
        }
    }

    /**
     * Updates the choices for what variable to color with in the drop down menu using whatever file is loaded by
     * {@code reader}
     * precondition: file is already loaded in {@code reader}
     */
    private void updateVarChoices() {
        if (fileIsLoaded()) {
            String[] vars = getPointArrayVarNames();
            vtkPointData data = reader.GetOutputAsDataSet().GetPointData();
            for (String varName : vars) {
                main.getViewerSettings().putVar(varName, data.GetArray(varName));
            }
            main.getViewerSettings().setActiveVars(vars);
        }
    }

    private String[] getPointArrayVarNames() {
        int pointArrays = reader.GetNumberOfPointArrays();
        String[] vars = new String[pointArrays];
        for (int i = 0; i < pointArrays; i++) {
            String varName = reader.GetPointArrayName(i);
            vars[i] = varName;
        }
        return vars;
    }

    /**
     * Loads a VTS file into {@code reader}
     * @param vtsPath absolute path to .vts file
     */

    private boolean fileIsLoaded() {
        return reader != null;
    }

    /**
     * Shows GUI dialog prompting user to select a .vts file
     * @return File object of selected file, null if no file selected
     */
    private File promptForVTKFile() {
        JFileChooser fileChooser;
        if (Starfish.options == null || Starfish.options.wd == null) {
            fileChooser = new JFileChooser();
        } else {
            fileChooser = new JFileChooser(Starfish.options.wd);
        }
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.addChoosableFileFilter(new FileNameExtensionFilter(".vts files", "vts"));
        fileChooser.setAcceptAllFileFilterUsed(true);
        int result = fileChooser.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
            return selectedFile;
        }
        return null;
    }
}


public static TypeInfo getDTDTypeInfo(String name) {
        TypeInfo t = (TypeInfo) dtdCache.get(name);
        if (t == null)
            throw new IllegalArgumentException("Unknown DTD datatype " + name);
        return t;
    }

package com.sun.org.apache.xerces.internal.util;

import java.util.Hashtable;
import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
import org.w3c.dom.TypeInfo;

/**
 * Straight-forward implementation of {@link TypeInfo}.
 *
 *

 * This class is immutable.
 *
 * @author
 *     Kohsuke Kawaguchi (example@nnthink.com)
 */
public class TypeInfoImpl implements TypeInfo {

    private final String typeNamespace;

    private final String typeName;

    private final static String dtdNamespaceURI = "http://www.w3.org/TR/REC-xml";

    public TypeInfoImpl() {
        typeNamespace = null;
        typeName = null;
    }

    public TypeInfoImpl(String typeNamespace, String typeName) {
        this.typeNamespace = typeNamespace;
        this.typeName = typeName;
    }

    public TypeInfoImpl(XSTypeDefinition t) {
        this(t.getNamespace(), t.getName());
    }

    public String getTypeName() {
        return typeName;
    }

    public String getTypeNamespace() {
        return typeNamespace;
    }

    public boolean isDerivedFrom(String typeNamespaceArg, String typeNameArg, int derivationMethod) {
        return false;
    }

    /**
     * Map from DTD type name ({@link String}) to {@link TypeInfo}.
     */
    private static final Hashtable dtdCache = new Hashtable();

    /**
     * Obtains a {@link TypeInfo} object from the DTD type name.
     *

     * Since DTD has a very limited type names, we can actually
     * cache the {@link TypeInfo} objects.
     */

    static {
        String[] typeNames = new String[] { "CDATA", "ID", "IDREF", "IDREFS", "NMTOKEN", "NMTOKENS", "ENTITY", "ENTITIES", "NOTATION" };
        for (int i = 0; i < typeNames.length; i++) dtdCache.put(typeNames[i], new TypeInfoImpl(dtdNamespaceURI, typeNames[i]));
    }
}


public void init(int WindowNo, FormFrame frame) {
        log.info("");
        m_WindowNo = WindowNo;
        m_frame = frame;
        try {
            dynParameter();
            jbInit();
            dynInit();
            frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
            frame.getContentPane().add(statusBar, BorderLayout.SOUTH);
        } catch (Exception ex) {
            log.log(Level.SEVERE, "", ex);
        }
    }

/**
 * ***************************************************************************
 *  Product: Adempiere ERP & CRM Smart Business Solution                       *
 *  For the text or an alternative of this public license, you may reach us    *
 *  ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA        *
 *  or via example@nnthink.com or http://example.com           *
 * ***************************************************************************
 */
package org.compiere.apps.form;

import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.VetoableChangeListener;
import java.sql.Timestamp;
import java.util.Properties;
import java.util.logging.Level;
import javax.swing.JLabel;
import org.compiere.apps.AEnv;
import org.compiere.apps.AWindow;
import org.compiere.apps.ConfirmPanel;
import org.compiere.apps.StatusBar;
import org.compiere.grid.GridController;
import org.compiere.grid.ed.VDate;
import org.compiere.grid.ed.VLocator;
import org.compiere.grid.ed.VLookup;
import org.compiere.model.MLocatorLookup;
import org.compiere.model.MLookup;
import org.compiere.model.MLookupFactory;
import org.compiere.plaf.CompiereColor;
import org.compiere.swing.CPanel;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.Msg;

/**
 * Material Transaction History
 *
 * @author Jorg Janke
 * @version $Id: VTrxMaterial.java,v 1.3 2006/07/30 00:51:28 jjanke Exp $
 */
public class VTrxMaterial extends TrxMaterial implements FormPanel, ActionListener, VetoableChangeListener {

    private CPanel panel = new CPanel();

    /**
     * 	FormFrame
     */
    private FormFrame m_frame;

    /**
     * Grid Controller
     */
    private GridController m_gridController;

    private CPanel mainPanel = new CPanel();

    private BorderLayout mainLayout = new BorderLayout();

    private CPanel parameterPanel = new CPanel();

    private JLabel orgLabel = new JLabel();

    private VLookup orgField;

    private JLabel locatorLabel = new JLabel();

    private VLocator locatorField;

    private JLabel productLabel = new JLabel();

    private VLookup productField;

    private JLabel dateFLabel = new JLabel();

    private VDate dateFField;

    private JLabel dateTLabel = new JLabel();

    private VDate dateTField;

    private JLabel mtypeLabel = new JLabel();

    private VLookup mtypeField;

    private GridBagLayout parameterLayout = new GridBagLayout();

    private CPanel southPanel = new CPanel();

    private BorderLayout southLayout = new BorderLayout();

    private ConfirmPanel confirmPanel = new ConfirmPanel(true, true, false, false, false, true, true);

    private StatusBar statusBar = new StatusBar();

    /**
     * 	Initialize Panel
     *   @param WindowNo window
     *   @param frame frame
     */

    // init
    /**
     *  Static Init
     *  @throws Exception
     */
    void jbInit() throws Exception {
        CompiereColor.setBackground(panel);
        mainPanel.setLayout(mainLayout);
        mainLayout.setVgap(10);
        parameterPanel.setLayout(parameterLayout);
        orgLabel.setText(Msg.translate(Env.getCtx(), "AD_Org_ID"));
        locatorLabel.setText(Msg.translate(Env.getCtx(), "M_Locator_ID"));
        productLabel.setText(Msg.translate(Env.getCtx(), "Product"));
        dateFLabel.setText(Msg.translate(Env.getCtx(), "DateFrom"));
        dateTLabel.setText(Msg.translate(Env.getCtx(), "DateTo"));
        mtypeLabel.setText(Msg.translate(Env.getCtx(), "MovementType"));
        mainPanel.add(parameterPanel, BorderLayout.NORTH);
        parameterPanel.add(orgLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 0, 5), 0, 0));
        parameterPanel.add(orgField, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 0, 0, 5), 0, 0));
        parameterPanel.add(mtypeLabel, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 0, 5), 0, 0));
        parameterPanel.add(mtypeField, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 0, 0, 5), 0, 0));
        parameterPanel.add(dateFLabel, new GridBagConstraints(4, 0, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 0, 5), 0, 0));
        parameterPanel.add(dateFField, new GridBagConstraints(5, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 0, 0, 5), 0, 0));
        parameterPanel.add(locatorLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 0, 5), 0, 0));
        parameterPanel.add(locatorField, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 0, 0, 5), 0, 0));
        parameterPanel.add(productLabel, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 0, 5), 0, 0));
        parameterPanel.add(productField, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 0, 0, 5), 0, 0));
        parameterPanel.add(dateTLabel, new GridBagConstraints(4, 1, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 0, 5), 0, 0));
        parameterPanel.add(dateTField, new GridBagConstraints(5, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 0, 0, 5), 0, 0));
        southPanel.setLayout(southLayout);
        southPanel.add(confirmPanel, BorderLayout.NORTH);
        southPanel.add(statusBar, BorderLayout.SOUTH);
        mainPanel.add(southPanel, BorderLayout.SOUTH);
    }

    // jbInit
    /**
     *  Initialize Parameter fields
     *  @throws Exception if Lookups cannot be initialized
     */
    private void dynParameter() throws Exception {
        Properties ctx = Env.getCtx();
        // Organization
        MLookup orgLookup = MLookupFactory.get(ctx, m_WindowNo, 0, 3660, DisplayType.TableDir);
        orgField = new VLookup("AD_Org_ID", false, false, true, orgLookup);
        // Locator
        MLocatorLookup locatorLookup = new MLocatorLookup(ctx, m_WindowNo);
        locatorField = new VLocator("M_Locator_ID", false, false, true, locatorLookup, m_WindowNo);
        // Product
        MLookup productLookup = MLookupFactory.get(ctx, m_WindowNo, 0, 3668, DisplayType.Search);
        productField = new VLookup("M_Product_ID", false, false, true, productLookup);
        productField.addVetoableChangeListener(this);
        // Movement Type
        MLookup mtypeLookup = MLookupFactory.get(ctx, m_WindowNo, 0, 3666, DisplayType.List);
        mtypeField = new VLookup("MovementType", false, false, true, mtypeLookup);
        // Dates
        dateFField = new VDate("DateFrom", false, false, true, DisplayType.Date, Msg.getMsg(Env.getCtx(), "DateFrom"));
        dateTField = new VDate("DateTo", false, false, true, DisplayType.Date, Msg.getMsg(Env.getCtx(), "DateTo"));
        confirmPanel.addActionListener(this);
        statusBar.setStatusLine("");
    }

    // dynParameter
    /**
     *  Dynamic Layout (Grid).
     * 	Based on AD_Window: Material Transactions
     */
    private void dynInit() {
        super.dynInit(statusBar);
        m_gridController = new GridController();
        m_gridController.initGrid(m_mTab, true, m_WindowNo, null, null);
        mainPanel.add(m_gridController, BorderLayout.CENTER);
    }

    // dynInit
    public void dispose() {
        if (m_gridController != null)
            m_gridController.dispose();
        m_gridController = null;
        m_mTab = null;
        if (m_mWindow != null)
            m_mWindow.dispose();
        m_mWindow = null;
        orgField = null;
        locatorField = null;
        productField = null;
        mtypeField = null;
        dateFField = null;
        dateTField = null;
        if (m_frame != null)
            m_frame.dispose();
        m_frame = null;
    }

    // dispose
    /**
     * ***********************************************************************
     *   Action Listener
     *   @param e event
     */
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL))
            dispose();
        else if (e.getActionCommand().equals(ConfirmPanel.A_REFRESH) || e.getActionCommand().equals(ConfirmPanel.A_OK))
            refresh();
        else if (e.getActionCommand().equals(ConfirmPanel.A_ZOOM))
            zoom();
    }

    // actionPerformed
    /**
     * ***********************************************************************
     *   Property Listener
     *   @param e event
     */
    public void vetoableChange(PropertyChangeEvent e) {
        if (e.getPropertyName().equals("M_Product_ID"))
            productField.setValue(e.getNewValue());
    }

    // vetoableChange
    /**
     * ***********************************************************************
     *   Refresh - Create Query and refresh grid
     */
    private void refresh() {
        Object organization = orgField.getValue();
        Object locator = locatorField.getValue();
        Object product = productField.getValue();
        Object movementType = mtypeField.getValue();
        Timestamp movementDateFrom = (Timestamp) dateFField.getValue();
        Timestamp movementDateTo = (Timestamp) dateTField.getValue();
        panel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        refresh(organization, locator, product, movementType, movementDateFrom, movementDateTo, statusBar);
        panel.setCursor(Cursor.getDefaultCursor());
    }

    // refresh
    public void zoom() {
        super.zoom();
        // Zoom
        panel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        AWindow frame = new AWindow();
        if (!frame.initWindow(AD_Window_ID, query)) {
            panel.setCursor(Cursor.getDefaultCursor());
            return;
        }
        AEnv.addToWindowManager(frame);
        AEnv.showCenterScreen(frame);
        frame = null;
        panel.setCursor(Cursor.getDefaultCursor());
    }
    // zoom
}
// VTrxMaterial


public void setIdLote(String value) {
        this.idLote = value;
    }

// Este arquivo foi gerado pela Arquitetura JavaTM para Implementação de Referência (JAXB) de Bind XML, v2.2.8-b130911.1802
// Todas as modificações neste arquivo serão perdidas após a recompilação do esquema de origem.
package br.com.swconsultoria.cte.schema_300.procCTeOS;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 * Tipo Pedido de Concessão de Autorização da CT-e
 *
 *
Classe Java de TEnviCTe complex type.
 *
 *
O seguinte fragmento do esquema especifica o conteúdo esperado contido dentro desta classe.
 *
 *

 * <complexType name="TEnviCTe">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="idLote" type="{http://www.portalfiscal.inf.br/cte}TIdLote"/>
 *         <element name="CTe" type="{http://www.portalfiscal.inf.br/cte}TCTe" maxOccurs="50"/>
 *       </sequence>
 *       <attribute name="versao" use="required" type="{http://www.portalfiscal.inf.br/cte}TVerCTe" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TEnviCTe", namespace = "http://example.com", propOrder = { "idLote", "cTe" })
public class TEnviCTe {

    @XmlElement(namespace = "http://www.portalfiscal.inf.br/cte", required = true)
    protected String idLote;

    @XmlElement(name = "CTe", namespace = "http://www.portalfiscal.inf.br/cte", required = true)
    protected List<TCTe> cTe;

    @XmlAttribute(name = "versao", required = true)
    protected String versao;

    public String getIdLote() {
        return idLote;
    }

    /**
     * Define o valor da propriedade idLote.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     */

/**
     * Gets the value of the cTe property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the cTe property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getCTe().add(newItem);
     *

     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link TCTe }
     */
    public List<TCTe> getCTe() {
        if (cTe == null) {
            cTe = new ArrayList<TCTe>();
        }
        return this.cTe;
    }

    public String getVersao() {
        return versao;
    }

    /**
     * Define o valor da propriedade versao.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     */
    public void setVersao(String value) {
        this.versao = value;
    }
}


public void initialize() {
        mRecords = new HitRecord[mNumReads];
    }

/*
 *
 * Use of this source code is bound by the Real Time Genomics Limited Software Licence Agreement
 *
 * If you did not receive a license accompanying this file, a copy must first be obtained by email
 * from example@nnthink.com.  On downloading, using and/or continuing to use this source
 * be made from time to time by Real Time Genomics Limited.
 */
package com.rtg.ngs;

import java.util.Random;

public class PairedTopRandomImplementation {

    private HitRecord[] mRecords;

    private final Random mRandom;

    private final int mNumReads;

    /*
   * We do not want to add any unnecessary fields into this class, as there will
   * be NUM_READS of them, and every byte will cause considerable memory usage
   */
    static final class HitRecord {

        int mTemplateId;

        int mZeroBasedTemplateStart;

        boolean mReverse;

        int mZeroBasedMateTemplateStart;

        boolean mMateReverse;

        int mComboScore;

        // maybe add score here to make re-alignment more efficient
        private HitRecord() {
        }
    }

    /**
     * @param numReads number of read pairs
     */
    public PairedTopRandomImplementation(int numReads) {
        mNumReads = numReads;
        mRandom = new Random();
    }

    PairedTopRandomImplementation(int numReads, long seed) {
        mNumReads = numReads;
        mRandom = new Random(seed);
    }

    /**
     * Initialise the Top Random implementation
     */

/**
     * Update top random structure with a 1/n probability.
     * @param readId the read id
     * @param templateId the template id of the sequence this read maps to.
     * @param zeroBasedTemplateStart start position (0-based) of first (sequencing wise) arm
     * @param reverse true if first arm was mapped reverse complement
     * @param zeroBasedMateTemplateStart start position (0-based) of second (sequencing wise) arm
     * @param mateReverse true if second arm was mapped reverse complement
     * @param comboScore the score of this combo. Used to avoid race conditions.
     * @param n number of records seen at alignments current combo score
     */
    public void update(int readId, int templateId, int zeroBasedTemplateStart, boolean reverse, int zeroBasedMateTemplateStart, boolean mateReverse, int comboScore, int n) {
        // protect against race condition
        if (mRecords[readId] != null && comboScore > mRecords[readId].mComboScore) {
            return;
        }
        if (n != 1) {
            if (mRandom.nextInt(n) != 0) {
                return;
            }
        }
        final HitRecord rec = getRecord(readId);
        rec.mReverse = reverse;
        rec.mTemplateId = templateId;
        rec.mZeroBasedTemplateStart = zeroBasedTemplateStart;
        rec.mZeroBasedMateTemplateStart = zeroBasedMateTemplateStart;
        rec.mMateReverse = mateReverse;
        rec.mComboScore = comboScore;
    }

    private HitRecord getRecord(int index) {
        if (mRecords[index] == null) {
            mRecords[index] = new HitRecord();
        }
        return mRecords[index];
    }

    HitRecord[] getRecords() {
        return mRecords;
    }

    void finish() {
        mRecords = null;
    }
}


public abstract void attachPropertyChangeListener(SwingWorker<?, ?> sw);

package com.link_intersystems.blog.mvc.controller;

import java.beans.PropertyChangeListener;
import javax.swing.BoundedRangeModel;
import javax.swing.SwingWorker;

/**
 * An interface that insures that a {@link PropertyChangeListener} that must be
 * attached to a {@link SwingWorker} can only be attached to a
 * {@link SwingWorker}. This interface therefore provides type-safety for a
 * {@link PropertyChangeListener}.
 *
 * @author René Link <a
 *         href="mailto:example@nnthink.com">[rene.link@link-
 *         intersystems.com]</a>
 */
public interface SwingWorkerPropertyChangeListener {

    /**
     * Attaches this {@link SwingWorkerProgressModel} as an
     * {@link PropertyChangeListener} to the given {@link SwingWorker} so that
     * the {@link SwingWorker}'s progress events will update this
     * {@link BoundedRangeModel}.
     *
     * @param sw
     *            the {@link SwingWorker} to attach this {@link SwingWorker}'s
     *            {@link PropertyChangeListener} adater from.
     */

    /**
     * Detaches this {@link SwingWorkerProgressModel}'s
     * {@link PropertyChangeListener} adapter from the given {@link SwingWorker}
     * so that no progress events will update this {@link BoundedRangeModel}
     * anymore.
     *
     * @param sw
     *            the {@link SwingWorker} to dettach this {@link SwingWorker}'s
     *            {@link PropertyChangeListener} adater from.
     */
    public abstract void detachPropertyChangeListener(SwingWorker<?, ?> sw);
}


switch(keyName) {
            case "common-tasks":
                return TaskListOrder.INSTANCE;
            case "license-header":
                return LicenseOrder.INSTANCE;
            case "built-in-tasks":
                return TaskListOrder.INSTANCE;
            default:
                return DefaultConfigNodeProperty.INSTANCE;
        }

package org.netbeans.gradle.project.properties;

import java.util.List;
import java.util.Map;
import org.netbeans.gradle.project.api.config.ConfigTree;

final class CompatibleRootNodeProperty extends AbstractFixedOrderNodeProperty {

    private static final String[] ROOT_KEYS = { "source-encoding", "target-platform-name", "target-platform", "source-level", "common-tasks", "script-platform", "gradle-home", "license-header", "built-in-tasks" };

    public static final ConfigNodeProperty INSTANCE = new CompatibleRootNodeProperty();

    private CompatibleRootNodeProperty() {
        super(ROOT_KEYS);
    }

    @Override
    public boolean ignoreValue() {
        return true;
    }

    @Override
    public ConfigNodeProperty getChildSorter(String keyName) {

    }

    private static final class IgnoreValueProperty extends AbstractConfigNodeProperty {

        public static final ConfigNodeProperty INSTANCE = new IgnoreValueProperty();

        @Override
        public boolean ignoreValue() {
            return true;
        }
    }

    private static abstract class AbstractFixedOrderNodePropertyWithoutValue extends AbstractFixedOrderNodeProperty {

        public AbstractFixedOrderNodePropertyWithoutValue(String... order) {
            super(order);
        }

        @Override
        public boolean ignoreValue() {
            return true;
        }
    }

    private static final class TaskOrder extends AbstractFixedOrderNodePropertyWithoutValue {

        private static final String TASK_ARGS = "task-args";

        private static final String TASK_JVM_ARGS = "task-jvm-args";

        private static final String[] TASK_KEYS = { "display-name", "non-blocking", "task-names", TASK_ARGS, TASK_JVM_ARGS };

        public static final ConfigNodeProperty INSTANCE = new TaskOrder();

        public TaskOrder() {
            super(TASK_KEYS);
        }

        @Override
        public ConfigNodeProperty getChildSorter(String keyName) {
            switch(keyName) {
                case TASK_ARGS:
                    return IgnoreValueProperty.INSTANCE;
                case TASK_JVM_ARGS:
                    return IgnoreValueProperty.INSTANCE;
                default:
                    return DefaultConfigNodeProperty.INSTANCE;
            }
        }

        @Override
        public ConfigTree adjustNodes(ConfigTree actualTree) {
            Map<String, List<ConfigTree>> children = actualTree.getChildTrees();
            boolean hasTaskArgs = children.containsKey(TASK_ARGS);
            boolean hasTasJvmArgs = actualTree.getChildTrees().containsKey(TASK_JVM_ARGS);
            if (hasTaskArgs && hasTasJvmArgs) {
                return actualTree;
            }
            // We set their values, so that they will remain in the tree
            ConfigTree.Builder result = new ConfigTree.Builder(actualTree);
            result.getChildBuilder(TASK_ARGS).setValue("");
            result.getChildBuilder(TASK_JVM_ARGS).setValue("");
            return result.create();
        }
    }

    private static final class LicenseOrder extends AbstractFixedOrderNodePropertyWithoutValue {

        private static final String[] LICENSE_KEYS = { "name", "template", "property" };

        public static final ConfigNodeProperty INSTANCE = new LicenseOrder();

        public LicenseOrder() {
            super(LICENSE_KEYS);
        }

        @Override
        public ConfigNodeProperty getChildSorter(String keyName) {
            return DefaultConfigNodeProperty.INSTANCE;
        }
    }

    private static final class TaskListOrder extends AbstractFixedOrderNodePropertyWithoutValue {

        public static final ConfigNodeProperty INSTANCE = new TaskListOrder();

        public TaskListOrder() {
            super();
        }

        @Override
        public ConfigNodeProperty getChildSorter(String keyName) {
            if ("task".equals(keyName)) {
                return TaskOrder.INSTANCE;
            } else {
                return DefaultConfigNodeProperty.INSTANCE;
            }
        }
    }
}