Java Examples for com.umeng.socialize.bean.SHARE_MEDIA

The following java examples will help you to understand the usage of com.umeng.socialize.bean.SHARE_MEDIA. These source code samples are taken from different open source projects.

Example 1
Project: KnowWeather-master  File: ShareHolder.java View source code
@OnClick(R.id.share_container)
public void onClick() {
    final UMImage umImage;
    Bitmap screenBitmap = null;
    ShareAction shareAction = new ShareAction((Activity) getContext()).setPlatform(SHAREMEDIAS[mPosition]).withTitle("知天气,天气尽在掌握之中").withText("简洁,实用,美观的天气应用,你的专属天气");
    if (mShareData.mIsWeather) {
        screenBitmap = UIUtil.takeScreenShot((Activity) getContext());
        if (screenBitmap == null) {
            Toast.makeText(getContext(), "抱歉,分享失败", Toast.LENGTH_LONG).show();
            return;
        }
        umImage = new UMImage(getContext(), screenBitmap);
        shareAction.withMedia(umImage);
    } else {
        umImage = new UMImage(getContext(), R.mipmap.icon);
        shareAction.withMedia(umImage).withTargetUrl("https://beta.bugly.qq.com/knowweather");
    }
    final Bitmap finalScreenBitmap = screenBitmap;
    shareAction.setCallback(new UMShareListener() {

        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(getContext(), "分享成功", Toast.LENGTH_SHORT).show();
            umImage.asBitmap().recycle();
            if (finalScreenBitmap != null) {
                finalScreenBitmap.recycle();
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            if (t != null) {
                Toast.makeText(getContext(), "抱歉,分享失败", Toast.LENGTH_LONG).show();
            }
            umImage.asBitmap().recycle();
            if (finalScreenBitmap != null) {
                finalScreenBitmap.recycle();
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            umImage.asBitmap().recycle();
            if (finalScreenBitmap != null) {
                finalScreenBitmap.recycle();
            }
        }
    });
    shareAction.share();
    mShareData.mShareDialog.dismiss();
}
Example 2
Project: weishijie-develop-master  File: MainActivity.java View source code
@Override
public boolean onProfileChanged(View view, IProfile profile, boolean current) {
    /*  if (profile instanceof IDrawerItem && ((IDrawerItem) profile).getIdentifier() == PROFILE_SETTING) {
                            int count = 100 + headerResult.getProfiles().size() + 1;
                            IProfile newProfile = new ProfileDrawerItem().withNameShown(true).withName("Batman" + count).withEmail("batman" + count + "@gmail.com").withIcon(R.drawable.profile5).withIdentifier(count);
                            if (headerResult.getProfiles() != null) {
                                //we know that there are 2 setting elements. set the new profile above them ;)
                                headerResult.addProfile(newProfile, headerResult.getProfiles().size() - 2);
                            } else {
                                headerResult.addProfiles(newProfile);
                                headerResult.setActiveProfile();
                            }
                        }*/
    if (UserManager.getInstance().isLogin())
        return true;
    View login_dialog = ContextUtils.inflate(MainActivity.this, R.layout.login_dialog);
    final CustomDialog dialog = new CustomDialog(MainActivity.this, login_dialog, ScreenUtils.getInstance(MainActivity.this).getWidth() - ContextUtils.dip2px(MainActivity.this, 40), ContextUtils.dip2px(MainActivity.this, 260), Gravity.CENTER);
    ButterKnife.findById(login_dialog, R.id.login_qq).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
            ((MainPresenter) mPresenter).login(MainActivity.this, SHARE_MEDIA.QQ);
        }
    });
    ButterKnife.findById(login_dialog, R.id.login_sina).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
            ((MainPresenter) mPresenter).login(MainActivity.this, SHARE_MEDIA.SINA);
        }
    });
    ButterKnife.findById(login_dialog, R.id.cancle).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    });
    dialog.show();
    return true;
}
Example 3
Project: UmengUtil-master  File: UmengUtil.java View source code
public static void init(Context context1, String sinaCallbackUrl, boolean degbug, SHARE_MEDIA... shareMediaList) {
    context = context1;
    // UMShareAPI.get(context1);
    //http://sns.whalecloud.com/sina2/callback
    Config.REDIRECT_URL = sinaCallbackUrl;
    shareMedias = shareMediaList;
    Config.isJumptoAppStore = true;
    Config.DEBUG = degbug;
    umShareAPI = UMShareAPI.get(context1);
    //对应平台没有安装的时候跳转转到应用商店下载,其中qq 微信会跳转到下载界面进行下载,其他应用会跳到应用商店进行下载
    //友盟统计
    MobclickAgent.setScenarioType(context, MobclickAgent.EScenarioType.E_UM_NORMAL);
}
Example 4
Project: Todayinformation-master  File: LoginActivity.java View source code
@Override
public void onClick(View v) {
    switch(v.getId()) {
        case // 获取手机号发送请求向手机发送验证码
        R.id.get_code:
            hideSoftInput(this, phone);
            if (countSeconds != 60) {
                showToast("您的验证码已发送!");
                return;
            }
            String phoneStr = phone.getText().toString();
            if (CharCheckUtil.isPhoneNum(phoneStr)) {
                showProgressDialog();
                showToast("发送成功");
                startCountBack();
            } else {
                showToast("输入的手机号码有误!");
            }
            break;
        case R.id.login:
            hideSoftInput(this, vCode);
            if (LoginCheck()) {
                User user = new User();
                user.name = "资讯爱好者";
                user.uId = "111842201";
                user.gender = 1;
                user.birthday = System.currentTimeMillis() / 1000;
                user.phone = phone.getText().toString();
                Toast.makeText(mContext, "您好," + user.name, Toast.LENGTH_SHORT).show();
                mUserController.saveUserInfo(user);
                Intent intent = new Intent(mContext, MyInfoActivity.class);
                startActivity(intent);
                finish();
            }
            break;
        case R.id.exit:
            finish();
            break;
        case R.id.input_delete:
            phone.setText("");
            delete.setVisibility(View.GONE);
            break;
        case //是否勾选用户协议
        R.id.check:
            if (flag) {
                flag = false;
                login.setEnabled(false);
                login.setBackgroundResource(R.color.C8C8C8);
                check.setImageResource(R.drawable.check_2);
            } else {
                flag = true;
                login.setEnabled(true);
                login.setBackgroundColor(Color.WHITE);
                check.setImageResource(R.drawable.check_1);
            }
            break;
        //用户协议
        case R.id.user_ll:
        case R.id.user_tx:
            Intent intent = new Intent(this, AboutActivity.class);
            startActivity(intent);
            break;
        case //QQ登录
        R.id.login_qq:
            QQLogin(SHARE_MEDIA.QQ);
            break;
        case //微博登录
        R.id.login_weibo:
            SinaLogin(SHARE_MEDIA.SINA);
            break;
        default:
            break;
    }
}
Example 5
Project: small_video-master  File: ShareDialog.java View source code
/**
	 * 初始化平台map
	 */
private void initPlatformMap() {
    mPlatformsMap.put("微信好友", SHARE_MEDIA.WEIXIN);
    mPlatformsMap.put("朋友圈", SHARE_MEDIA.WEIXIN_CIRCLE);
    mPlatformsMap.put("QQ好友", SHARE_MEDIA.QQ);
    mPlatformsMap.put("QQ空间", SHARE_MEDIA.QZONE);
    mPlatformsMap.put("新浪微博", SHARE_MEDIA.SINA);
    mPlatformsMap.put("腾讯微博", SHARE_MEDIA.TENCENT);
}
Example 6
Project: ijoyplus-android-master  File: Setting.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.setting);
    //		com.umeng.socom.Log.LOG = true;
    app = (App) getApplication();
    aq = new AQuery(this);
    mContext = this;
    UMFeedbackService.enableNewReplyNotification(this, NotificationType.AlertDialog);
    //		 appRecommend();
    ViewGroup fatherLayout = (ViewGroup) findViewById(R.id.ad);
    InnerListView listView = (InnerListView) this.findViewById(R.id.list);
    listView.setMaxHeight(400);
    scrollView = (ScrollView) findViewById(R.id.scrollView1);
    listView.setParentScrollView(scrollView);
    // 赋值preloadDataService,添加newTips 回调
    preloadDataService = new ExchangeDataService();
    preloadDataService.preloadData(Setting.this, new NTipsChangedListener() {

        @Override
        public void onChanged(int flag) {
            // root.findViewById(R.id.umeng_example_xp_container_tips);
            if (flag == -1) {
            // 没有new广告
            } else if (flag > 1) {
            // 第一页new广告数量
            } else if (flag == 0) {
            // 第一页全部为new 广告
            }
        }

        ;
    }, ExchangeConstants.type_container);
    ExchangeDataService exchangeDataService = preloadDataService != null ? preloadDataService : new ExchangeDataService("");
    ExchangeViewManager exchangeViewManager = new ExchangeViewManager(this, new ExchangeDataService());
    exchangeViewManager.addView(fatherLayout, listView);
    MobclickAgent.onEventBegin(mContext, RECOMMAND_APP);
    aq.id(R.id.button7).gone();
    controller = UMServiceFactory.getUMSocialService(DESCRIPTOR, RequestType.SOCIAL);
    // 关注我们
    SocializeConfig config = new SocializeConfig();
    // 添加关注对象
    config.addFollow(SHARE_MEDIA.SINA, "3058636171");
    // 添加follow 时的回调
    config.setOauthDialogFollowListener(new MulStatusListener() {

        @Override
        public void onStart() {
            Log.d("TestData", "Follow Start");
        }

        @Override
        public void onComplete(MultiStatus multiStatus, int st, SocializeEntity entity) {
            if (// follow 成功
            st == 200) {
                Map<String, Integer> allChildren = multiStatus.getAllChildren();
                Set<String> set = allChildren.keySet();
                for (String fid : set) Log.i("TestData", fid + "    " + allChildren.get(fid));
            }
        }
    });
    // 更新config
    controller.setConfig(config);
}
Example 7
Project: v2ex-android-master  File: ShareHelper.java View source code
@Override
public void onPlatformClick(int id) {
    switch(id) {
        case R.id.ly_share_weichat_circle:
            shareToWeiChatCircle();
            break;
        case R.id.ly_share_weichat:
            shareToWeiChat();
            break;
        case R.id.ly_share_sina_weibo:
            shareToSinaWeibo();
            break;
        case R.id.ly_share_qq:
            shareToQQ(SHARE_MEDIA.QQ);
            break;
        case R.id.ly_share_copy_link:
            copyTextToBoard(mUrl);
            break;
        case R.id.ly_share_more_option:
            shareContentWithSystem();
            break;
        default:
            break;
    }
    dialog.dismiss();
}
Example 8
Project: GitClub-master  File: RepoPageActivity.java View source code
@Override
public void onClick(View v) {
    switch(v.getId()) {
        case R.id.iv_owner:
            PersonalHomePageActivity.launch(this, repo.getOwner().getLogin());
            break;
        case R.id.btn_watch:
            presenter.toWatch(mOwner, mRepo, btnWatchToggleHelper.toggle(btnWatch));
            break;
        case R.id.btn_fork:
            presenter.toFork(mOwner, mRepo);
            break;
        case R.id.btn_star:
            boolean checked = btnStarToggleHelper.toggle(btnStar);
            presenter.toStar(mOwner, mRepo, checked);
            btnShineStar.setChecked(checked, true);
            break;
        case R.id.btn_toStar:
            presenter.toStar(mOwner, mRepo, btnShineStar.isChecked());
            btnStarToggleHelper.setState(btnStar, btnShineStar.isChecked());
            break;
        case R.id.btn_source:
        case R.id.btn_source_code:
            drawerLayout.closeDrawer(drawerView);
            RepoSourceActivity.launch(this, mOwner, mRepo);
            break;
        case R.id.btn_share:
            drawerLayout.closeDrawer(drawerView);
            if (repo == null) {
                Note.show("Fail to get Repository info, please load again.");
                return;
            }
            new ShareAction(RepoPageActivity.this).setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.WEIXIN_FAVORITE, SHARE_MEDIA.EVERNOTE, SHARE_MEDIA.POCKET, SHARE_MEDIA.FACEBOOK, SHARE_MEDIA.EMAIL, SHARE_MEDIA.YNOTE, SHARE_MEDIA.MORE).withTitle("Repository from Github").withText("Repository from Github: " + repo.getHtml_url()).withTargetUrl(repo.getHtml_url()).setCallback(new UmengShareCallback()).open();
            break;
        case R.id.btn_open_in_browser:
            drawerLayout.closeDrawer(drawerView);
            String url = webViewHelper.getUrl();
            if (TextUtils.isEmpty(url))
                break;
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
            startActivity(intent);
            break;
        case R.id.btn_contributors:
            drawerLayout.closeDrawer(drawerView);
            ListContributorActivity.launch(repo.getOwner().getLogin(), repo.getName(), this);
            break;
        case R.id.btn_stargazers:
            drawerLayout.closeDrawer(drawerView);
            ListStargazerActivity.launch(repo.getOwner().getLogin(), repo.getName(), this);
            break;
        case R.id.btn_watchers:
            drawerLayout.closeDrawer(drawerView);
            ListWatcherActivity.launch(repo.getOwner().getLogin(), repo.getName(), this);
            break;
        case R.id.btn_forkers:
            drawerLayout.closeDrawer(drawerView);
            ListForkerActivity.launch(repo.getOwner().getLogin(), repo.getName(), this);
            break;
    }
}
Example 9
Project: FingerColoring-Android-master  File: UmengLoginUtil.java View source code
@Override
public void onComplete(final Bundle value, SHARE_MEDIA platform) {
    StringBuilder sb = new StringBuilder();
    Set<String> keys = value.keySet();
    for (String key : keys) {
        sb.append(key + "=" + value.get(key).toString() + "\r\n");
    }
    L.d("TestData2", sb.toString());
    //获取相关授权信息
    mController.getPlatformInfo(context, SHARE_MEDIA.QQ, new SocializeListeners.UMDataListener() {

        @Override
        public void onStart() {
        }

        @Override
        public void onComplete(int status, Map<String, Object> info) {
            if (status == 200 && info != null) {
                StringBuilder sb = new StringBuilder();
                Set<String> keys = info.keySet();
                for (String key : keys) {
                    sb.append(key + "=" + info.get(key).toString() + "\r\n");
                }
                //do register or login
                registerToServer(LoginMethod.QQ, value, info);
                L.d("TestData", sb.toString());
            } else {
                L.d("TestData", "发生错误:" + status);
            }
        }
    });
}
Example 10
Project: Coding-Android-master  File: CustomShareBoard.java View source code
@Override
public void onClick(View v) {
    int id = v.getId();
    switch(id) {
        case R.id.wechat:
            umengEvent(UmengEvent.MAOPAO, "分享到微信");
            addWX();
            performShare(SHARE_MEDIA.WEIXIN);
            break;
        case R.id.wechat_circle:
            umengEvent(UmengEvent.MAOPAO, "分享到朋友圈");
            addWXCircle();
            performShare(SHARE_MEDIA.WEIXIN_CIRCLE);
            break;
        case R.id.qq:
            umengEvent(UmengEvent.MAOPAO, "分享到qq");
            addQQ();
            performShare(SHARE_MEDIA.QQ);
            break;
        case R.id.qzone:
            umengEvent(UmengEvent.MAOPAO, "分享到qq空间");
            addQQZone();
            performShare(SHARE_MEDIA.QZONE);
            break;
        case R.id.sinaWeibo:
            umengEvent(UmengEvent.MAOPAO, "分享到sina");
            if (mActivity instanceof MainActivity_ && !OauthHelper.isAuthenticatedAndTokenNotExpired(mActivity, SHARE_MEDIA.SINA)) {
                Intent intent = new Intent(mActivity, ShareSinaHelpActivity.class);
                intent.putExtra(ShareSinaHelpActivity.EXTRA_SHARE_DATA, mShareData);
                mActivity.startActivity(intent);
            } else {
                addSinaWeibo();
                performShare(SHARE_MEDIA.SINA);
            }
            break;
        case R.id.evernote:
            umengEvent(UmengEvent.MAOPAO, "分享到evernote");
            addEvernote();
            performShare(SHARE_MEDIA.EVERNOTE);
            break;
        case R.id.codingFriend:
            umengEvent(UmengEvent.MAOPAO, "分享到好友");
            UsersListActivity_.intent(mActivity).type(UsersListActivity.Friend.Follow).hideFollowButton(true).relayString(mShareData.link).start();
            dismiss();
            break;
        case R.id.linkCopy:
            umengEvent(UmengEvent.MAOPAO, "复制链接");
            Global.copy(mActivity, mShareData.link);
            Toast.makeText(mActivity, "链接已复制 " + mShareData.link, Toast.LENGTH_SHORT).show();
            break;
        case R.id.buttonsLayout:
            return;
        default:
            break;
    }
    dismiss();
}
Example 11
Project: SmallCredit-master  File: ShowSelectFractionActivity.java View source code
@Override
public void onClick(View v) {
    switch(v.getId()) {
        case R.id.second_payfen_back:
            this.finish();
            break;
        case R.id.second_shenfen_img2:
            showAllSubject();
            break;
        case R.id.second_payfen_rl1:
            // ��ת��fragment
            if (SharedPreferencesUtils.getString(ShowSelectFractionActivity.this, "userid", null) == null) {
                Intent intent = new Intent(ShowSelectFractionActivity.this, BeginActivity.class);
                startActivity(intent);
            } else {
                Intent it = new Intent(ShowSelectFractionActivity.this, MainActivity.class);
                it.putExtra("tab3", 0);
                startActivity(it);
            }
            break;
        case R.id.second_payfen_rl2:
            ToastUtil.show(ShowSelectFractionActivity.this, "�����ڴ�...");
            break;
        case R.id.second_payfen_share:
            mController.getConfig().setPlatforms(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QQ, SHARE_MEDIA.EMAIL, SHARE_MEDIA.SINA, SHARE_MEDIA.QZONE, SHARE_MEDIA.FACEBOOK, SHARE_MEDIA.SMS, SHARE_MEDIA.RENREN, SHARE_MEDIA.FACEBOOK);
            mController.openShare(ShowSelectFractionActivity.this, false);
            break;
    }
}
Example 12
Project: love_reading-master  File: Bookthink.java View source code
@Override
public void onClick(DialogInterface dialogInterface, int which) {
    switch(which) {
        case 0:
            mController.doOauthVerify(Bookthink.this, SHARE_MEDIA.QZONE, new UMAuthListener() {

                @Override
                public void onStart(SHARE_MEDIA platform) {
                    Toast.makeText(Bookthink.this, "��Ȩ��ʼ", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onError(SocializeException e, SHARE_MEDIA platform) {
                    Toast.makeText(Bookthink.this, "��Ȩ����", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onComplete(Bundle value, SHARE_MEDIA platform) {
                    Toast.makeText(Bookthink.this, "��Ȩ���", Toast.LENGTH_SHORT).show();
                    //��ȡ�����Ȩ��Ϣ������ת���Զ���ķ���༭ҳ��
                    String uid = value.getString("uid");
                }

                @Override
                public void onCancel(SHARE_MEDIA platform) {
                    Toast.makeText(Bookthink.this, "��Ȩȡ��", Toast.LENGTH_SHORT).show();
                }
            });
            mController.directShare(Bookthink.this, SHARE_MEDIA.QZONE, new SnsPostListener() {

                @Override
                public void onStart() {
                    Toast.makeText(Bookthink.this, "����ʼ", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onComplete(SHARE_MEDIA platform, int eCode, SocializeEntity entity) {
                    if (eCode == StatusCode.ST_CODE_SUCCESSED) {
                        Toast.makeText(Bookthink.this, "����ɹ�", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        Toast.makeText(Bookthink.this, "����ʧ��", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                }
            });
            break;
        case 1:
            mController.doOauthVerify(Bookthink.this, SHARE_MEDIA.TENCENT, new UMAuthListener() {

                @Override
                public void onStart(SHARE_MEDIA platform) {
                    Toast.makeText(Bookthink.this, "��Ȩ��ʼ", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onError(SocializeException e, SHARE_MEDIA platform) {
                    Toast.makeText(Bookthink.this, "��Ȩ����", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onComplete(Bundle value, SHARE_MEDIA platform) {
                    Toast.makeText(Bookthink.this, "��Ȩ���", Toast.LENGTH_SHORT).show();
                    //��ȡ�����Ȩ��Ϣ������ת���Զ���ķ���༭ҳ��
                    String uid = value.getString("uid");
                }

                @Override
                public void onCancel(SHARE_MEDIA platform) {
                    Toast.makeText(Bookthink.this, "��Ȩȡ��", Toast.LENGTH_SHORT).show();
                }
            });
            mController.directShare(Bookthink.this, SHARE_MEDIA.TENCENT, new SnsPostListener() {

                @Override
                public void onStart() {
                    Toast.makeText(Bookthink.this, "����ʼ", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onComplete(SHARE_MEDIA platform, int eCode, SocializeEntity entity) {
                    if (eCode == StatusCode.ST_CODE_SUCCESSED) {
                        Toast.makeText(Bookthink.this, "����ɹ�", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        Toast.makeText(Bookthink.this, "����ʧ��", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                }
            });
            break;
        case 2:
            mController.doOauthVerify(Bookthink.this, SHARE_MEDIA.SINA, new UMAuthListener() {

                @Override
                public void onStart(SHARE_MEDIA platform) {
                    Toast.makeText(Bookthink.this, "��Ȩ��ʼ", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onError(SocializeException e, SHARE_MEDIA platform) {
                    Toast.makeText(Bookthink.this, "��Ȩ����", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onComplete(Bundle value, SHARE_MEDIA platform) {
                    Toast.makeText(Bookthink.this, "��Ȩ���", Toast.LENGTH_SHORT).show();
                    //��ȡ�����Ȩ��Ϣ������ת���Զ���ķ���༭ҳ��
                    String uid = value.getString("uid");
                }

                @Override
                public void onCancel(SHARE_MEDIA platform) {
                    Toast.makeText(Bookthink.this, "��Ȩȡ��", Toast.LENGTH_SHORT).show();
                }
            });
            mController.directShare(Bookthink.this, SHARE_MEDIA.SINA, new SnsPostListener() {

                @Override
                public void onStart() {
                    Toast.makeText(Bookthink.this, "����ʼ", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onComplete(SHARE_MEDIA platform, int eCode, SocializeEntity entity) {
                    if (eCode == StatusCode.ST_CODE_SUCCESSED) {
                        Toast.makeText(Bookthink.this, "����ɹ�", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        Toast.makeText(Bookthink.this, "����ʧ��", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                }
            });
            break;
        case 3:
            mController.doOauthVerify(Bookthink.this, SHARE_MEDIA.DOUBAN, new UMAuthListener() {

                @Override
                public void onStart(SHARE_MEDIA platform) {
                    Toast.makeText(Bookthink.this, "��Ȩ��ʼ", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onError(SocializeException e, SHARE_MEDIA platform) {
                    Toast.makeText(Bookthink.this, "��Ȩ����", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onComplete(Bundle value, SHARE_MEDIA platform) {
                    Toast.makeText(Bookthink.this, "��Ȩ���", Toast.LENGTH_SHORT).show();
                    //��ȡ�����Ȩ��Ϣ������ת���Զ���ķ���༭ҳ��
                    String uid = value.getString("uid");
                }

                @Override
                public void onCancel(SHARE_MEDIA platform) {
                    Toast.makeText(Bookthink.this, "��Ȩȡ��", Toast.LENGTH_SHORT).show();
                }
            });
            mController.directShare(Bookthink.this, SHARE_MEDIA.DOUBAN, new SnsPostListener() {

                @Override
                public void onStart() {
                    Toast.makeText(Bookthink.this, "����ʼ", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onComplete(SHARE_MEDIA platform, int eCode, SocializeEntity entity) {
                    if (eCode == StatusCode.ST_CODE_SUCCESSED) {
                        Toast.makeText(Bookthink.this, "����ɹ�", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        Toast.makeText(Bookthink.this, "����ʧ��", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                }
            });
            break;
    }
}
Example 13
Project: git-osc-analysis-master  File: UIHelper.java View source code
/**
	 * 显示分享操作
	 * 
	 * @param context
	 * @param shareContent
	 * @param shareImage
	 */
public static void showShareOption(Activity context, String title, String url, String shareContent, Bitmap shareImage) {
//		UMImage mUMImgBitmap = new UMImage(context, shareImage);
//		// 首先在您的Activity中添加如下成员变量
//		final UMSocialService mController = UMServiceFactory
//				.getUMSocialService("com.umeng.share");
//
//		// appID是你在微信开发平台注册应用的AppID, 这里需要替换成你注册的AppID
//		String appID = "wx850b854f6aad6764";
//		// 添加微信平台
//		UMWXHandler wxHandler = new UMWXHandler(context, appID);
//		wxHandler.addToSocialSDK();
//		// 设置分享到微信的内容
//		WeiXinShareContent weixinContent = new WeiXinShareContent(mUMImgBitmap);
//		weixinContent.setShareContent(shareContent);
//		weixinContent.setTitle(title);
//		weixinContent.setTargetUrl(url);
//		weixinContent.setShareImage(mUMImgBitmap);
//		wxHandler.mShareMedia = weixinContent;
//		mController.setShareMedia(weixinContent);
//
//		// 支持微信朋友圈
//		UMWXHandler wxCircleHandler = new UMWXHandler(context, appID);
//		// 设置朋友圈分享的内容
//		CircleShareContent circleMedia = new CircleShareContent();
//		circleMedia.setShareContent(shareContent);
//		circleMedia.setShareImage(mUMImgBitmap);
//		circleMedia.setTargetUrl(url);
//		circleMedia.setTitle(title);
//		wxCircleHandler.mShareMedia = circleMedia;
//		mController.setShareMedia(circleMedia);
//		wxCircleHandler.setToCircle(true);
//		wxCircleHandler.addToSocialSDK();
//
//		// 参数1为当前Activity,参数2为开发者在QQ互联申请的APP ID,参数3为开发者在QQ互联申请的APP kEY.
//		UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(context, "1101982202",
//				"GJxJGse5cu9iH4NM");
//		QQShareContent qqShareContent = new QQShareContent();
//		qqShareContent.setTitle(title);
//		qqShareContent.setShareContent(shareContent);
//		qqShareContent.setShareImage(mUMImgBitmap);
//		qqShareContent.setTargetUrl(url);
//		qqSsoHandler.mShareMedia = mUMImgBitmap;
//		mController.setShareMedia(qqShareContent);
//		qqSsoHandler.addToSocialSDK();
//
//		SinaSsoHandler sinaSsoHandler = new SinaSsoHandler();
//		SinaShareContent sinaShareContent = new SinaShareContent();
//		String form = "  分享自GitOSC移动客户端,好项目尽在https://git.oschina.net";
//		sinaShareContent.setShareContent(shareContent + " " + url + form);
//		sinaShareContent.setTargetUrl(url);
//		sinaShareContent.setShareImage(mUMImgBitmap);
//		sinaShareContent.setTitle(title);
//		mController.setShareMedia(sinaShareContent);
//		mController.getConfig().setSsoHandler(sinaSsoHandler);
//		// 移除人人分享操作
//		mController.getConfig().removePlatform(SHARE_MEDIA.RENREN,
//				SHARE_MEDIA.DOUBAN, SHARE_MEDIA.TENCENT);
//
//		mController.openShare(context, false);
}
Example 14
Project: phphub-android-master  File: TopicDetailsActivity.java View source code
public void onShareItemSelected() {
    final UMSocialService socialService = UMServiceFactory.getUMSocialService("com.umeng.share");
    // Remove Tencent Weibo and QZone from share panel.
    socialService.getConfig().removePlatform(SHARE_MEDIA.TENCENT);
    socialService.getConfig().removePlatform(SHARE_MEDIA.QZONE);
    String webLink = this.topicInfo.getLinks().getWebURL();
    String shareContent = this.topicInfo.getTitle() + " " + webLink;
    String title = getString(R.string.share_topic, this.topicInfo.getUser().getData().getName());
    socialService.setShareContent(shareContent);
    if (!BuildConfig.QQ_APPID.isEmpty() && !BuildConfig.QQ_APPKEY.isEmpty()) {
        // Add QQ
        UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(this, BuildConfig.QQ_APPID, BuildConfig.QQ_APPKEY);
        qqSsoHandler.addToSocialSDK();
        QQShareContent qqShareContent = new QQShareContent();
        qqShareContent.setShareContent(shareContent);
        qqShareContent.setTitle(title);
        qqShareContent.setTargetUrl(this.topicInfo.getLinks().getWebURL());
        socialService.setShareMedia(qqShareContent);
    } else {
        socialService.getConfig().removePlatform(SHARE_MEDIA.QQ);
    }
    if (!BuildConfig.WX_APPID.isEmpty() && !BuildConfig.WX_SECRET.isEmpty()) {
        // Add WeiChat
        UMWXHandler wxHandler = new UMWXHandler(this, BuildConfig.WX_APPID, BuildConfig.WX_SECRET);
        wxHandler.addToSocialSDK();
        // Add WeChat Circle
        UMWXHandler wxCircleHandler = new UMWXHandler(this, BuildConfig.WX_APPID, BuildConfig.WX_SECRET);
        wxCircleHandler.setToCircle(true);
        wxCircleHandler.addToSocialSDK();
        //设置微信分享内容
        WeiXinShareContent weixinContent = new WeiXinShareContent();
        weixinContent.setShareContent(shareContent);
        weixinContent.setTitle(title);
        weixinContent.setTargetUrl(this.topicInfo.getLinks().getWebURL());
        weixinContent.setShareImage(new UMImage(this, topicInfo.getUser().getData().getAvatar()));
        socialService.setShareMedia(weixinContent);
        Logger.d(topicInfo.getUser().getData().getAvatar());
        //设置微信朋友圈分享内容
        CircleShareContent circleMedia = new CircleShareContent();
        circleMedia.setShareContent(shareContent);
        circleMedia.setTitle(title);
        circleMedia.setTargetUrl(this.topicInfo.getLinks().getWebURL());
        circleMedia.setShareImage(new UMImage(this, topicInfo.getUser().getData().getAvatar()));
        socialService.setShareMedia(circleMedia);
    } else {
        socialService.getConfig().removePlatform(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE);
    }
    socialService.openShare(this, false);
}
Example 15
Project: hplookball-master  File: HupuBaseActivity.java View source code
@Override
public void onComplete(SHARE_MEDIA platform, int eCode, SocializeEntity entity) {
    HupuLog.e("papa", "code==" + eCode);
    if (eCode == 200) {
        HupuLog.d("分享成功.");
        showToast("分享成功");
        //分享成功回调服务器
        initParameter();
        mParams.put("token", mToken);
        mParams.put("url", shareURL);
        sendRequest(HuPuRes.REQ_METHOD_POST_TASK_SHARE, mParams, new HupuHttpHandler(HupuBaseActivity.this));
    } else {
        String eMsg = "分享失败";
        if (eCode == -101) {
            eMsg = "没有授权";
        }
        HupuLog.d("分享失败[" + eCode + "] " + eMsg);
        showToast(eMsg);
    }
}
Example 16
Project: umeng_community_android-master  File: MainActivity.java View source code
/**
     * 初始化分享相关的平台
     * 
     * @param activity
     */
private void initPlatforms(Activity activity) {
    // 添加QQ
    UMQQSsoHandler qqHandler = new UMQQSsoHandler(activity, "1104606393", "X4BAsJAVKtkDQ1zQ");
    qqHandler.addToSocialSDK();
    // 添加QZone平台
    QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(activity, "1104606393", "X4BAsJAVKtkDQ1zQ");
    qZoneSsoHandler.addToSocialSDK();
    // 添加微信平台
    UMWXHandler wechatHandler = new UMWXHandler(activity, "wx96110a1e3af63a39", "c60e3d3ff109a5d17013df272df99199");
    wechatHandler.addToSocialSDK();
    // 添加微信朋友圈平台
    UMWXHandler circleHandler = new UMWXHandler(activity, "wx96110a1e3af63a39", "c60e3d3ff109a5d17013df272df99199");
    circleHandler.setToCircle(true);
    circleHandler.addToSocialSDK();
    UMShareServiceFactory.getSocialService().getConfig().setPlatforms(SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.QZONE, SHARE_MEDIA.QQ, SHARE_MEDIA.SINA);
    UMShareServiceFactory.getSocialService().getConfig().setPlatformOrder(SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.QZONE, SHARE_MEDIA.QQ, SHARE_MEDIA.SINA);
}
Example 17
Project: UUCampus-master  File: LoginActivity.java View source code
@Override
public void onComplete(Bundle bundle, SHARE_MEDIA share_media) {
    Log.d("TestData", "compete");
    if (bundle != null && !TextUtils.isEmpty(bundle.getString("uid"))) {
        showToast("授权成功~");
        showToast("获取用户数据----");
        //获取access_token及用户资料
        mController.getPlatformInfo(LoginActivity.this, SHARE_MEDIA.SINA, new SocializeListeners.UMDataListener() {

            @Override
            public void onStart() {
                showToast("获取平台数据开始~~~~");
            }

            @Override
            public void onComplete(int i, Map<String, Object> map) {
                if (i == 200 && map != null) {
                    StringBuilder sb = new StringBuilder();
                    Set<String> keys = map.keySet();
                    for (String key : keys) {
                        sb.append(key + "=" + map.get(key).toString() + "\r\n");
                    }
                    Log.d("TestData", sb.toString());
                } else {
                    Log.d("TestData", "发生错误:" + i);
                }
            }
        });
    } else {
        showToast("授权失败!");
    }
}
Example 18
Project: umeng_shake_demo-master  File: MainActivity.java View source code
/**
     * @Title: registerShake
     * @Description: 注册摇一摇截屏分享
     * @throws
     */
private void registerShake() {
    // 最多支持5个平台, 如果多于5个,则取前5个
    List<SHARE_MEDIA> platforms = new ArrayList<SHARE_MEDIA>();
    platforms.add(SHARE_MEDIA.SINA);
    platforms.add(SHARE_MEDIA.QZONE);
    platforms.add(SHARE_MEDIA.WEIXIN);
    platforms.add(SHARE_MEDIA.WEIXIN_CIRCLE);
    platforms.add(SHARE_MEDIA.SMS);
    // 设置摇一摇分享的文字内容
    mShakeController.setShareContent("精彩瞬间,摇摇分享 -- 来自友盟社会化组件." + new Date().toString());
    // 注册摇一摇截屏分享, 自定义的VitamioAdapter,
    mShakeController.registerShakeListender(MainActivity.this, new VitamioAdapter(), platforms, new VitamioListener());
}
Example 19
Project: zprojects-master  File: AuthQQActivity.java View source code
public void onDeletAuth() {
    SHARE_MEDIA platform = SHARE_MEDIA.QQ;
    /**begin invoke umeng api**/
    mShareAPI.deleteOauth(AuthQQActivity.this, platform, umdelAuthListener);
}

Java Examples for org.apache.avro.mapreduce.AvroKeyOutputFormat

The following java examples will help you to understand the usage of org.apache.avro.mapreduce.AvroKeyOutputFormat. These source code samples are taken from different open source projects.

Example 1
Project: camus-master  File: CamusSweeperAvroKeyJob.java View source code
@Override
public void configureJob(String topic, Job job) {
    boolean skipNameValidation = RelaxedSchemaUtils.skipNameValidation(job.getConfiguration());
    if (skipNameValidation) {
        RelaxedAvroSerialization.addToConfiguration(job.getConfiguration());
    }
    // setting up our input format and map output types
    super.configureInput(job, AvroKeyCombineFileInputFormat.class, AvroKeyMapper.class, AvroKey.class, AvroValue.class);
    // setting up our output format and output types
    super.configureOutput(job, skipNameValidation ? RelaxedAvroKeyOutputFormat.class : AvroKeyOutputFormat.class, AvroKeyReducer.class, AvroKey.class, NullWritable.class);
    // finding the newest file from our input. this file will contain the newest version of our avro
    // schema.
    Schema schema;
    try {
        schema = getNewestSchemaFromSource(job);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    // checking if we have a key schema used for deduping. if we don't then we make this a map only
    // job and set the key schema
    // to the newest input schema
    String keySchemaStr = getConfValue(job, topic, "camus.sweeper.avro.key.schema");
    Schema keySchema;
    if (job.getConfiguration().getBoolean("camus.sweeper.use.all.attributes", false)) {
        log.info("Using all attributes in the schema (except Map fields) for deduping");
        keySchema = getAllFieldsExceptMap(schema);
    } else if (keySchemaStr == null || keySchemaStr.isEmpty() || job.getConfiguration().getBoolean("second.stage", false)) {
        job.setNumReduceTasks(0);
        keySchema = schema;
    } else {
        keySchema = RelaxedSchemaUtils.parseSchema(keySchemaStr, job.getConfiguration());
        keySchema = duplicateRecord(keySchema, schema);
        if (!validateKeySchema(schema, keySchema)) {
            log.info("topic:" + topic + " key invalid, using map only job");
            job.setNumReduceTasks(0);
            keySchema = schema;
        }
    }
    setupSchemas(topic, job, schema, keySchema);
    // setting the compression level. Only used if compression is enabled. default is 6
    job.getConfiguration().setInt(AvroOutputFormat.DEFLATE_LEVEL_KEY, job.getConfiguration().getInt(AvroOutputFormat.DEFLATE_LEVEL_KEY, 6));
}
Example 2
Project: avro-sorting-master  File: AvroWritableKeySort.java View source code
public boolean runMapReduce(final Job job, Path inputPath, Path outputPath) throws Exception {
    FileInputFormat.setInputPaths(job, inputPath);
    job.setInputFormatClass(AvroKeyInputFormat.class);
    AvroJob.setInputKeySchema(job, Weather.SCHEMA$);
    job.setMapperClass(SortMapper.class);
    AvroJob.setMapOutputValueSchema(job, Weather.SCHEMA$);
    job.setMapOutputKeyClass(WeatherSubset.class);
    job.setReducerClass(SortReducer.class);
    AvroJob.setOutputKeySchema(job, Weather.SCHEMA$);
    job.setOutputFormatClass(AvroKeyOutputFormat.class);
    FileOutputFormat.setOutputPath(job, outputPath);
    job.setPartitionerClass(WeatherPartitioner.class);
    job.setGroupingComparatorClass(WeatherSubsetGroupingComparator.class);
    job.setSortComparatorClass(WeatherSubsetSortComparator.class);
    return job.waitForCompletion(true);
}
Example 3
Project: etl-by-example-master  File: Driver.java View source code
@Override
public int run(String[] args) throws Exception {
    Path mrInput, mrOutput;
    if (args.length == 2) {
        mrInput = new Path(args[0]);
        mrOutput = new Path(args[1] + directoryFormat.format(new Date()));
    } else {
        System.err.println("Parameter missing!");
        return 1;
    }
    /** configure Job **/
    Job job = new Job(getConf(), "DataIngest Example");
    job.setJarByClass(Driver.class);
    job.setUserClassesTakesPrecedence(true);
    FileInputFormat.setInputPaths(job, mrInput);
    FileOutputFormat.setOutputPath(job, mrOutput);
    job.setMapperClass(MapperRawToAvro.class);
    job.setReducerClass(ReducerByDateTime.class);
    AvroJob.setMapOutputKeySchema(job, Schema.create(Schema.Type.LONG));
    AvroJob.setMapOutputValueSchema(job, SampleRecord.SCHEMA$);
    AvroKeyOutputFormat.setCompressOutput(job, true);
    AvroKeyOutputFormat.setOutputCompressorClass(job, DeflateCodec.class);
    AvroMultipleOutputs.addNamedOutput(job, "sampleRecord", AvroKeyOutputFormat.class, SampleRecord.SCHEMA$);
    MultipleOutputs.setCountersEnabled(job, true);
    if (job.waitForCompletion(true)) {
        return 0;
    } else {
        return 1;
    }
}
Example 4
Project: cdap-master  File: DynamicPartitioningOutputFormat.java View source code
private boolean isAvroOutputFormat(FileOutputFormat<K, V> fileOutputFormat) {
    String className = fileOutputFormat.getClass().getName();
    // use class name String in order avoid having a dependency on the Avro libraries here
    return "org.apache.avro.mapreduce.AvroKeyOutputFormat".equals(className) || "org.apache.avro.mapreduce.AvroKeyValueOutputFormat".equals(className);
}
Example 5
Project: hpg-bigdata-master  File: Bam2AvroMR.java View source code
public static int run(String input, String output, String codecName, boolean adjQuality, Configuration conf) throws Exception {
    // read header, and save sequence index/name in conf
    final Path p = new Path(input);
    final SeekableStream seekableStream = WrapSeekable.openPath(conf, p);
    final SamReader reader = SamReaderFactory.make().open(SamInputResource.of(seekableStream));
    final SAMFileHeader header = reader.getFileHeader();
    int i = 0;
    SAMSequenceRecord sr;
    while ((sr = header.getSequence(i)) != null) {
        conf.set("" + i, sr.getSequenceName());
        i++;
    }
    Job job = Job.getInstance(conf, "Bam2AvroMR");
    job.setJarByClass(Bam2AvroMR.class);
    // Avro problem fix
    job.getConfiguration().set("mapreduce.job.user.classpath.first", "true");
    job.getConfiguration().set(ADJUST_QUALITY, Boolean.toString(adjQuality));
    // We call setOutputSchema first so we can override the configuration
    // parameters it sets
    AvroJob.setOutputKeySchema(job, ReadAlignment.getClassSchema());
    job.setOutputValueClass(NullWritable.class);
    AvroJob.setMapOutputValueSchema(job, ReadAlignment.getClassSchema());
    // point to input data
    FileInputFormat.setInputPaths(job, new Path(input));
    job.setInputFormatClass(AnySAMInputFormat.class);
    // set the output format
    FileOutputFormat.setOutputPath(job, new Path(output));
    if (codecName != null) {
        FileOutputFormat.setCompressOutput(job, true);
        FileOutputFormat.setOutputCompressorClass(job, CompressionUtils.getHadoopCodec(codecName));
    }
    job.setOutputFormatClass(AvroKeyOutputFormat.class);
    job.setMapOutputKeyClass(AvroKey.class);
    job.setMapOutputValueClass(Void.class);
    job.setMapperClass(Bam2GaMapper.class);
    job.setNumReduceTasks(0);
    job.waitForCompletion(true);
    // write header
    Path headerPath = new Path(output + "/part-m-00000.avro.header");
    FileSystem fs = FileSystem.get(conf);
    BufferedWriter br = new BufferedWriter(new OutputStreamWriter(fs.create(headerPath, true)));
    br.write(header.getTextHeader());
    br.close();
    return 0;
}
Example 6
Project: iis-master  File: SparkPipeMapReduce.java View source code
//------------------------ LOGIC --------------------------
public static void main(String[] args) throws IOException, ClassNotFoundException {
    SparkPipeMapReduceParameters params = parseParameters(args);
    SparkConf conf = new SparkConf();
    conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer");
    conf.set("spark.kryo.registrator", "pl.edu.icm.sparkutils.avro.AvroCompatibleKryoRegistrator");
    Class<? extends GenericRecord> outputAvroClass = Class.forName(params.outputAvroSchemaClass).asSubclass(GenericRecord.class);
    Schema inputSchema = AvroUtils.toSchema(params.inputAvroSchemaClass);
    Schema outputSchema = AvroUtils.toSchema(params.outputAvroSchemaClass);
    Job job = Job.getInstance();
    AvroJob.setInputKeySchema(job, inputSchema);
    AvroJob.setOutputKeySchema(job, outputSchema);
    try (JavaSparkContext sc = new JavaSparkContext(conf)) {
        sc.addFile(params.mapperScript);
        sc.addFile(params.reducerScript);
        String mapperScriptName = new File(params.mapperScript).getName();
        String reducerScriptName = new File(params.reducerScript).getName();
        SparkPipeExecutor pipeExecutor = new SparkPipeExecutor();
        @SuppressWarnings("unchecked") JavaPairRDD<AvroKey<GenericRecord>, NullWritable> inputRecords = (JavaPairRDD<AvroKey<GenericRecord>, NullWritable>) sc.newAPIHadoopFile(params.inputAvroPath, AvroKeyInputFormat.class, GenericRecord.class, NullWritable.class, job.getConfiguration());
        JavaPairRDD<String, String> mappedRecords = pipeExecutor.doMap(inputRecords, mapperScriptName, params.mapperScriptArgs);
        JavaPairRDD<AvroKey<GenericRecord>, NullWritable> reducedRecords = pipeExecutor.doReduce(mappedRecords, reducerScriptName, params.reducerScriptArgs, outputAvroClass);
        reducedRecords.saveAsNewAPIHadoopFile(params.outputAvroPath, AvroKey.class, NullWritable.class, AvroKeyOutputFormat.class, job.getConfiguration());
    }
}
Example 7
Project: hiped2-master  File: BloomFilterCreator.java View source code
/**
   * The MapReduce driver - setup and launch the job.
   *
   * @param args the command-line arguments
   * @return the process exit code
   * @throws Exception if something goes wrong
   */
public int run(final String[] args) throws Exception {
    Cli cli = Cli.builder().setArgs(args).addOptions(ReplicatedJoin.UserOptions.values()).build();
    int result = cli.runCmd();
    if (result != 0) {
        return result;
    }
    Path usersPath = new Path(cli.getArgValueAsString(ReplicatedJoin.UserOptions.USERS));
    Path outputPath = new Path(cli.getArgValueAsString(ReplicatedJoin.UserOptions.OUTPUT));
    Configuration conf = super.getConf();
    Job job = new Job(conf);
    job.setJarByClass(BloomFilterCreator.class);
    job.setMapperClass(Map.class);
    job.setReducerClass(Reduce.class);
    AvroJob.setOutputKeySchema(job, AvroBytesRecord.SCHEMA);
    job.getConfiguration().set(AvroJob.CONF_OUTPUT_CODEC, SnappyCodec.class.getName());
    job.setOutputFormatClass(AvroKeyOutputFormat.class);
    job.setMapOutputKeyClass(NullWritable.class);
    job.setMapOutputValueClass(BloomFilter.class);
    FileInputFormat.setInputPaths(job, usersPath);
    FileOutputFormat.setOutputPath(job, outputPath);
    job.setNumReduceTasks(1);
    return job.waitForCompletion(true) ? 0 : 1;
}
Example 8
Project: KOSHIK-master  File: EnglishPipeline.java View source code
@SuppressWarnings("static-access")
@Override
public int run(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("path,...").hasArg().withDescription("input path[s]").create(OPTION_INPUTPATHS));
    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("output path").create(OPTION_OUTPUTPATH));
    CommandLine commandLine;
    CommandLineParser commandLineParser = new GnuParser();
    commandLine = commandLineParser.parse(options, args);
    if (!commandLine.hasOption(OPTION_INPUTPATHS) || !commandLine.hasOption(OPTION_OUTPUTPATH)) {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp(getClass().getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        return -1;
    }
    String inputPaths = commandLine.getOptionValue(OPTION_INPUTPATHS);
    Path outputPath = new Path(commandLine.getOptionValue(OPTION_OUTPUTPATH));
    LOGGER.info("Utility name: " + this.getClass().getName());
    LOGGER.info(" - input path: " + inputPaths);
    LOGGER.info(" - output path: " + outputPath);
    Job job = new Job(getConf(), getClass().getName());
    job.setJarByClass(getClass());
    FileInputFormat.setInputPaths(job, inputPaths);
    FileOutputFormat.setOutputPath(job, outputPath);
    job.setInputFormatClass(AvroKeyInputFormat.class);
    //job.setMapperClass(DocumentSelectMapper.class);
    AvroJob.setInputKeySchema(job, AvroDocument.SCHEMA$);
    AvroJob.setMapOutputKeySchema(job, AvroDocument.SCHEMA$);
    job.setMapOutputValueClass(NullWritable.class);
    job.setReducerClass(EnglishPipelineReducer.class);
    AvroJob.setOutputKeySchema(job, AvroDocument.SCHEMA$);
    job.setOutputValueClass(NullWritable.class);
    job.setOutputFormatClass(AvroKeyOutputFormat.class);
    return job.waitForCompletion(true) ? 0 : 1;
}
Example 9
Project: opencga-master  File: VariantTableExportDriver.java View source code
@Override
protected void initMapReduceJob(String inTable, Job job, Scan scan, boolean addDependencyJar) throws IOException {
    super.initMapReduceJob(inTable, job, scan, addDependencyJar);
    // set Path
    FileOutputFormat.setOutputPath(job, new Path(this.outFile));
    // compression
    FileOutputFormat.setOutputCompressorClass(job, GzipCodec.class);
    switch(this.type) {
        case AVRO:
            job.setOutputFormatClass(AvroKeyOutputFormat.class);
            // Set schema
            AvroJob.setOutputKeySchema(job, VariantAvro.getClassSchema());
            break;
        case VCF:
            job.setOutputFormatClass(HadoopVcfOutputFormat.class);
            break;
        default:
            throw new IllegalStateException("Type not known: " + this.type);
    }
    job.setNumReduceTasks(0);
}
Example 10
Project: aegisthus-master  File: SSTableExport.java View source code
@Override
public int run(String[] args) throws Exception {
    Job job = Job.getInstance(getConf());
    job.setJarByClass(SSTableExport.class);
    CommandLine cl = getOptions(args);
    if (cl == null) {
        return 1;
    }
    // Check all of the paths and load the sstable version from the input filenames
    List<Path> paths = Lists.newArrayList();
    if (cl.hasOption(Feature.CMD_ARG_INPUT_FILE)) {
        for (String input : cl.getOptionValues(Feature.CMD_ARG_INPUT_FILE)) {
            checkVersionFromFilename(input);
            paths.add(new Path(input));
        }
    }
    if (cl.hasOption(Feature.CMD_ARG_INPUT_DIR)) {
        paths.addAll(getDataFiles(job.getConfiguration(), cl.getOptionValue(Feature.CMD_ARG_INPUT_DIR)));
    }
    String avroSchemaString = getAvroSchema(cl.getOptionValue(Feature.CMD_ARG_AVRO_SCHEMA_FILE), job.getConfiguration());
    Schema avroSchema = new Schema.Parser().parse(avroSchemaString);
    // At this point we have the version of sstable that we can use for this run
    job.getConfiguration().set(Aegisthus.Feature.CONF_SSTABLE_VERSION, version.toString());
    if (job.getConfiguration().get(Aegisthus.Feature.CONF_CQL_SCHEMA) != null) {
        setConfigurationFromCql(job.getConfiguration());
    }
    job.setInputFormatClass(AegisthusInputFormat.class);
    job.setMapperClass(CQLMapper.class);
    job.setOutputFormatClass(AvroKeyOutputFormat.class);
    AvroJob.setOutputKeySchema(job, avroSchema);
    // Map-only job
    job.setNumReduceTasks(0);
    TextInputFormat.setInputPaths(job, paths.toArray(new Path[paths.size()]));
    FileOutputFormat.setOutputPath(job, new Path(cl.getOptionValue(Feature.CMD_ARG_OUTPUT_DIR)));
    job.submit();
    System.out.println(job.getJobID());
    System.out.println(job.getTrackingURL());
    boolean success = job.waitForCompletion(true);
    return success ? 0 : 1;
}
Example 11
Project: white-elephant-master  File: ParseJobConfs.java View source code
public void execute(StagedOutputJobExecutor executor) throws IOException, InterruptedException, ExecutionException {
    for (String clusterName : _clusterNames.split(",")) {
        System.out.println("Processing cluster " + clusterName);
        List<JobStatsProcessing.ProcessingTask> processingTasks = JobStatsProcessing.getTasks(_fs, _logsRoot, clusterName, _confsOutputPathRoot, "xml", _incremental, _numDays, _numDaysForced);
        for (JobStatsProcessing.ProcessingTask task : processingTasks) {
            List<String> inputPaths = new ArrayList<String>();
            inputPaths.add(task.inputPathFormat);
            String outputPath = task.outputPath;
            final StagedOutputJob job = StagedOutputJob.createStagedJob(_props, _name + "-parse-confs-" + task.id, inputPaths, "/tmp" + outputPath, outputPath, _log);
            job.getConfiguration().set("jobs.output.path", _confsOutputPathRoot);
            job.getConfiguration().set("logs.cluster.name", clusterName);
            job.setOutputKeyClass(BytesWritable.class);
            job.setOutputValueClass(NullWritable.class);
            job.setInputFormatClass(CombineDocumentFileFormat.class);
            job.setOutputFormatClass(AvroKeyOutputFormat.class);
            AvroJob.setOutputKeySchema(job, JobConf.SCHEMA$);
            job.setNumReduceTasks(0);
            job.setMapperClass(ParseJobConfs.TheMapper.class);
            executor.submit(job);
        }
        executor.waitForCompletion();
    }
}
Example 12
Project: geowave-master  File: VectorMRExportJobRunner.java View source code
/**
	 * Main method to execute the MapReduce analytic.
	 */
public int runJob() throws CQLException, IOException, InterruptedException, ClassNotFoundException {
    Configuration conf = super.getConf();
    if (conf == null) {
        conf = new Configuration();
        setConf(conf);
    }
    GeoWaveConfiguratorBase.setRemoteInvocationParams(hdfsHostPort, mrOptions.getResourceManagerHostPort(), conf);
    final QueryOptions options = new QueryOptions();
    final List<String> adapterIds = mrOptions.getAdapterIds();
    final AdapterStore adapterStore = storeOptions.createAdapterStore();
    if ((adapterIds != null) && !adapterIds.isEmpty()) {
        options.setAdapters(Lists.transform(adapterIds, new Function<String, DataAdapter<?>>() {

            @Override
            public DataAdapter<?> apply(final String input) {
                return adapterStore.getAdapter(new ByteArrayId(input));
            }
        }));
    }
    conf.setInt(BATCH_SIZE_KEY, mrOptions.getBatchSize());
    if (mrOptions.getIndexId() != null) {
        final Index index = storeOptions.createIndexStore().getIndex(new ByteArrayId(mrOptions.getIndexId()));
        if (index == null) {
            JCommander.getConsole().println("Unable to find index '" + mrOptions.getIndexId() + "' in store");
            return -1;
        }
        if (index instanceof PrimaryIndex) {
            options.setIndex((PrimaryIndex) index);
        } else {
            JCommander.getConsole().println("Index '" + mrOptions.getIndexId() + "' is not a primary index");
            return -1;
        }
    }
    if (mrOptions.getCqlFilter() != null) {
        if ((adapterIds == null) || (adapterIds.size() != 1)) {
            JCommander.getConsole().println("Exactly one type is expected when using CQL filter");
            return -1;
        }
        final String adapterId = adapterIds.get(0);
        final DataAdapter<?> adapter = storeOptions.createAdapterStore().getAdapter(new ByteArrayId(adapterId));
        if (adapter == null) {
            JCommander.getConsole().println("Type '" + adapterId + "' not found");
            return -1;
        }
        if (!(adapter instanceof GeotoolsFeatureDataAdapter)) {
            JCommander.getConsole().println("Type '" + adapterId + "' does not support vector export");
            return -1;
        }
        GeoWaveInputFormat.setQuery(conf, (DistributableQuery) CQLQuery.createOptimalQuery(mrOptions.getCqlFilter(), (GeotoolsFeatureDataAdapter) adapter, options.getIndex(), null));
    }
    GeoWaveInputFormat.setStoreOptions(conf, storeOptions);
    // the above code is a temporary placeholder until this gets merged with
    // the new commandline options
    GeoWaveInputFormat.setQueryOptions(conf, options);
    final Job job = new Job(conf);
    job.setJarByClass(this.getClass());
    job.setJobName("Exporting to " + hdfsPath);
    FileOutputFormat.setCompressOutput(job, true);
    FileOutputFormat.setOutputPath(job, new Path(hdfsPath));
    job.setMapperClass(VectorExportMapper.class);
    job.setInputFormatClass(GeoWaveInputFormat.class);
    job.setOutputFormatClass(AvroKeyOutputFormat.class);
    job.setMapOutputKeyClass(AvroKey.class);
    job.setMapOutputValueClass(NullWritable.class);
    job.setOutputKeyClass(AvroKey.class);
    job.setOutputValueClass(NullWritable.class);
    job.setNumReduceTasks(0);
    AvroJob.setOutputKeySchema(job, AvroSimpleFeatureCollection.SCHEMA$);
    AvroJob.setMapOutputKeySchema(job, AvroSimpleFeatureCollection.SCHEMA$);
    GeoWaveInputFormat.setMinimumSplitCount(job.getConfiguration(), mrOptions.getMinSplits());
    GeoWaveInputFormat.setMaximumSplitCount(job.getConfiguration(), mrOptions.getMaxSplits());
    boolean retVal = false;
    try {
        retVal = job.waitForCompletion(true);
    } catch (final IOException ex) {
        LOGGER.error("Error waiting for map reduce tile resize job: ", ex);
    }
    return retVal ? 0 : 1;
}
Example 13
Project: pinot-master  File: DerivedColumnTransformationPhaseJob.java View source code
public Job run() throws Exception {
    Job job = Job.getInstance(getConf());
    job.setJobName(name);
    job.setJarByClass(DerivedColumnTransformationPhaseJob.class);
    Configuration configuration = job.getConfiguration();
    FileSystem fs = FileSystem.get(configuration);
    // Input Path
    String inputPathDir = getAndSetConfiguration(configuration, DERIVED_COLUMN_TRANSFORMATION_PHASE_INPUT_PATH);
    LOGGER.info("Input path dir: " + inputPathDir);
    for (String inputPath : inputPathDir.split(",")) {
        LOGGER.info("Adding input:" + inputPath);
        Path input = new Path(inputPath);
        FileInputFormat.addInputPath(job, input);
    }
    // Topk path
    String topkPath = getAndSetConfiguration(configuration, DERIVED_COLUMN_TRANSFORMATION_PHASE_TOPK_PATH);
    LOGGER.info("Topk path : " + topkPath);
    // Output path
    Path outputPath = new Path(getAndSetConfiguration(configuration, DERIVED_COLUMN_TRANSFORMATION_PHASE_OUTPUT_PATH));
    LOGGER.info("Output path dir: " + outputPath.toString());
    if (fs.exists(outputPath)) {
        fs.delete(outputPath, true);
    }
    FileOutputFormat.setOutputPath(job, outputPath);
    // Schema
    Schema avroSchema = ThirdeyeAvroUtils.getSchema(inputPathDir);
    LOGGER.info("Schema : {}", avroSchema.toString(true));
    // ThirdEyeConfig
    String metricTypesProperty = ThirdeyeAvroUtils.getMetricTypesProperty(props.getProperty(ThirdEyeConfigProperties.THIRDEYE_METRIC_NAMES.toString()), props.getProperty(ThirdEyeConfigProperties.THIRDEYE_METRIC_TYPES.toString()), avroSchema);
    props.setProperty(ThirdEyeConfigProperties.THIRDEYE_METRIC_TYPES.toString(), metricTypesProperty);
    ThirdEyeConfig thirdeyeConfig = ThirdEyeConfig.fromProperties(props);
    job.getConfiguration().set(DERIVED_COLUMN_TRANSFORMATION_PHASE_THIRDEYE_CONFIG.toString(), OBJECT_MAPPER.writeValueAsString(thirdeyeConfig));
    LOGGER.info("ThirdEyeConfig {}", thirdeyeConfig.encode());
    // New schema
    Schema outputSchema = newSchema(thirdeyeConfig);
    job.getConfiguration().set(DERIVED_COLUMN_TRANSFORMATION_PHASE_OUTPUT_SCHEMA.toString(), outputSchema.toString());
    // Map config
    job.setMapperClass(DerivedColumnTransformationPhaseMapper.class);
    job.setInputFormatClass(AvroKeyInputFormat.class);
    job.setMapOutputKeyClass(AvroKey.class);
    job.setMapOutputValueClass(NullWritable.class);
    AvroJob.setOutputKeySchema(job, outputSchema);
    LazyOutputFormat.setOutputFormatClass(job, AvroKeyOutputFormat.class);
    AvroMultipleOutputs.addNamedOutput(job, "avro", AvroKeyOutputFormat.class, outputSchema);
    job.setNumReduceTasks(0);
    job.waitForCompletion(true);
    return job;
}
Example 14
Project: hadcom.utils-master  File: ConvertEnvMultiTable2MultiAvro2.java View source code
private static void addSchema(String outputPath, Job job, BufferedReader br) throws IOException {
    String line;
    StringBuilder strBuilder = new StringBuilder();
    // read the file
    while ((line = br.readLine()) != null) {
        strBuilder.append(line);
    }
    String schemaStr = strBuilder.toString();
    // get the schema name and make a hdfs directory out
    // of
    // it.
    Schema schema;
    try {
        schema = new Schema.Parser().parse(schemaStr);
    } catch (Exception e) {
        throw new RuntimeException("Unable to parse schema file: " + schemaStr, e);
    }
    getNamedOutputsList(job);
    job.getConfiguration().set(SCHEMA_PRE_CONF + schema.getName(), schemaStr);
    AvroMultipleOutputs.addNamedOutput(job, schema.getName(), AvroKeyOutputFormat.class, schema);
    // clear the builder
    strBuilder.delete(0, strBuilder.length());
}
Example 15
Project: kiji-mapreduce-master  File: AvroKeyMapReduceJobOutput.java View source code
/** {@inheritDoc} */
@Override
protected Class<? extends OutputFormat> getOutputFormatClass() {
    return AvroKeyOutputFormat.class;
}

Java Examples for com.intellij.psi.stubs.StubOutputStream

The following java examples will help you to understand the usage of com.intellij.psi.stubs.StubOutputStream. These source code samples are taken from different open source projects.

Example 1
Project: old-gosu-repo-master  File: GosuStubFileElementType.java View source code
@Override
public void serialize(@NotNull final GosuFileStub stub, @NotNull final StubOutputStream dataStream) throws IOException {
    IModule rootModule = stub.getPsi() != null ? GosuModuleUtil.getGlobalModule(stub.getProject()) : null;
    if (rootModule != null) {
        TypeSystem.pushModule(rootModule);
    }
    try {
        dataStream.writeName(stub.getPackageName().toString());
        dataStream.writeName(stub.getName().toString());
        dataStream.writeName(stub.getExt().toString());
    } finally {
        if (rootModule != null) {
            TypeSystem.popModule(rootModule);
        }
    }
}
Example 2
Project: intellij-community-master  File: JavaClassElementType.java View source code
@Override
public void serialize(@NotNull PsiClassStub stub, @NotNull StubOutputStream dataStream) throws IOException {
    dataStream.writeByte(((PsiClassStubImpl) stub).getFlags());
    if (!stub.isAnonymous()) {
        dataStream.writeName(stub.getName());
        dataStream.writeName(stub.getQualifiedName());
        dataStream.writeName(stub.getSourceFileName());
    } else {
        dataStream.writeName(stub.getBaseClassReferenceText());
    }
}
Example 3
Project: intellij-elixir-master  File: Stub.java View source code
public static <T extends Stubbic> void serializeStubbic(@NotNull T stub, @NotNull StubOutputStream dataStream) throws IOException {
    dataStream.writeName(stub.resolvedModuleName());
    dataStream.writeName(stub.resolvedFunctionName());
    dataStream.writeInt(stub.resolvedFinalArity());
    dataStream.writeBoolean(stub.hasDoBlockOrKeyword());
    dataStream.writeName(stub.getName());
    writeNameSet(dataStream, stub.canonicalNameSet());
}
Example 4
Project: kotlin-master  File: IdeStubIndexService.java View source code
@Override
public void serializeFileStub(@NotNull KotlinFileStub stub, @NotNull StubOutputStream dataStream) throws IOException {
    KotlinFileStubForIde fileStub = (KotlinFileStubForIde) stub;
    dataStream.writeName(fileStub.getPackageFqName().asString());
    dataStream.writeBoolean(fileStub.isScript());
    dataStream.writeName(StringRef.toString(fileStub.getFacadeSimpleName()));
    dataStream.writeName(StringRef.toString(fileStub.getPartSimpleName()));
    List<StringRef> facadePartNames = fileStub.getFacadePartSimpleNames();
    if (facadePartNames == null) {
        dataStream.writeInt(0);
    } else {
        dataStream.writeInt(facadePartNames.size());
        for (StringRef partName : facadePartNames) {
            dataStream.writeName(StringRef.toString(partName));
        }
    }
}
Example 5
Project: intellij-haskell-master  File: HaskellConidStubElementType.java View source code
@Override
public void serialize(@NotNull HaskellConidStub stub, @NotNull StubOutputStream dataStream) throws IOException {
    dataStream.writeName(stub.getName());
}
Example 6
Project: webtoper-master  File: NlsStubElementType.java View source code
@Override
public void serialize(StubT stub, StubOutputStream dataStream) throws IOException {
}
Example 7
Project: intellij-erlang-master  File: ErlangRecordDefinitionElementType.java View source code
@Override
public void serialize(@NotNull ErlangRecordDefinitionStub stub, @NotNull StubOutputStream dataStream) throws IOException {
    dataStream.writeName(stub.getName());
}
Example 8
Project: fan4idea-master  File: FanTypeDefinitionElementType.java View source code
public void serialize(final FanTypeDefinitionStub stub, final StubOutputStream dataStream) throws IOException {
    dataStream.writeName(stub.getName());
    dataStream.writeName(stub.getPodName());
}
Example 9
Project: la-clojure-master  File: ClNsElementTypeBase.java View source code
public void serialize(ClNsStub stub, StubOutputStream dataStream) throws IOException {
    dataStream.writeName(stub.getName());
    dataStream.writeInt(stub.getTextOffset());
}
Example 10
Project: consulo-csharp-master  File: CSharpIndexMethodStubElementType.java View source code
@Override
public void serialize(@NotNull CSharpIndexMethodDeclStub methodStub, @NotNull StubOutputStream stubOutputStream) throws IOException {
    stubOutputStream.writeName(methodStub.getParentQName());
}
Example 11
Project: go-lang-idea-plugin-master  File: GoTypeStubElementType.java View source code
@Override
public void serialize(@NotNull GoTypeStub stub, @NotNull StubOutputStream dataStream) throws IOException {
    dataStream.writeName(stub.getText());
}
Example 12
Project: intellij-plugins-master  File: CfmlFileElementType.java View source code
@Override
public void serialize(@NotNull CfmlFileStub stub, @NotNull StubOutputStream dataStream) throws IOException {
    dataStream.writeName(stub.getName().toString());
}
Example 13
Project: consulo-unity3d-master  File: ShaderDefStubElementType.java View source code
@Override
public void serialize(@NotNull ShaderDefStub stub, @NotNull StubOutputStream dataStream) throws IOException {
    dataStream.writeName(stub.getName());
}
Example 14
Project: IDLua-master  File: LuaStubUtils.java View source code
public static void serializeCollectionsArray(StubOutputStream dataStream, Set<String>[] collArray) throws IOException {
    dataStream.writeByte(collArray.length);
    for (Set<String> namedParameterSet : collArray) {
        dataStream.writeByte(namedParameterSet.size());
        for (String namepParameter : namedParameterSet) {
            dataStream.writeUTF(namepParameter);
        }
    }
}
Example 15
Project: jstestdriver-idea-plugin-master  File: DirectiveElementType.java View source code
public void serialize(DirectiveStub stub, StubOutputStream dataStream) throws IOException {
    dataStream.writeName(stub.getName());
    dataStream.writeUTFFast(stub.getValue());
}
Example 16
Project: smali-master  File: SmaliClassStatementElementType.java View source code
@Override
public void serialize(@NotNull SmaliClassStatementStub stub, @NotNull StubOutputStream dataStream) throws IOException {
    dataStream.writeName(stub.getQualifiedName());
}
Example 17
Project: Wolfram-Language-Parser-master  File: JavaMethodElementType.java View source code
@Override
public void serialize(@NotNull final PsiMethodStub stub, @NotNull final StubOutputStream dataStream) throws IOException {
    dataStream.writeName(stub.getName());
    TypeInfo.writeTYPE(dataStream, stub.getReturnTypeText(false));
    dataStream.writeByte(((PsiMethodStubImpl) stub).getFlags());
    if (stub.isAnnotationMethod()) {
        dataStream.writeName(stub.getDefaultValueText());
    }
}

Java Examples for com.baidu.mapapi.map.MKEvent

The following java examples will help you to understand the usage of com.baidu.mapapi.map.MKEvent. These source code samples are taken from different open source projects.

Example 1
Project: gyz-master  File: BMapApiApp.java View source code
@Override
public void onGetPermissionState(int iError) {
    Log.d("MyGeneralListener", "onGetPermissionState error is " + iError);
    if (iError == MKEvent.ERROR_PERMISSION_DENIED) {
        // ��ȨKey����
        Toast.makeText(BMapApiApp.mDemoApp.getApplicationContext(), "baidu key error", Toast.LENGTH_LONG).show();
        BMapApiApp.mDemoApp.m_bKeyRight = false;
    }
}
Example 2
Project: YikuairAndroid-master  File: LocationEngine.java View source code
@Override
public void onGetNetworkState(int iError) {
    if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
        Log.e("yikuair", "BaiduLocation says network error" + "error number is: " + iError);
    } else if (iError == MKEvent.ERROR_NETWORK_DATA) {
        Log.e("yikuair", "BaiduLocation says network data error" + "error number is: " + iError);
    }
// ...
}
Example 3
Project: ChangYou-master  File: MyRenren.java View source code
@Override
public void onGetNetworkState(int iError) {
    if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
        Toast.makeText(MyRenren.getInstance().getApplicationContext(), "您的网络出错啦!", Toast.LENGTH_LONG).show();
    } else if (iError == MKEvent.ERROR_NETWORK_DATA) {
        Toast.makeText(MyRenren.getInstance().getApplicationContext(), "输入正确的检索条件!", Toast.LENGTH_LONG).show();
    }
// ...
}
Example 4
Project: My_Android_fzbmzxc-master  File: Location.java View source code
@Override
public void onGetNetworkState(int iError) {
    if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
        Toast.makeText(Location.getInstance().getApplicationContext(), "您的网络出错啦!", Toast.LENGTH_LONG).show();
    } else if (iError == MKEvent.ERROR_NETWORK_DATA) {
        Toast.makeText(Location.getInstance().getApplicationContext(), "输入正确的检索条件!", Toast.LENGTH_LONG).show();
    }
// ...
}
Example 5
Project: com.mzeat-master  File: ShoppingDetailActivity.java View source code
@Override
public void onGetPermissionState(int iError) {
    // TODO Auto-generated method stub
    if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
        Log.e("iError", String.valueOf(iError));
        Toast.makeText(MzeatApplication.getInstance().getApplicationContext(), "您的网络出错啦!", Toast.LENGTH_LONG).show();
    } else if (iError == MKEvent.ERROR_NETWORK_DATA) {
        Toast.makeText(MzeatApplication.getInstance().getApplicationContext(), "输入正确的检索条件!", Toast.LENGTH_LONG).show();
    }
}
Example 6
Project: searchhealth-master  File: BDrugStoreRoute.java View source code
public void onGetDrivingRouteResult(MKDrivingRouteResult res, int error) {
    async_begin.setVisibility(View.GONE);
    // �����յ������壬��Ҫѡ�����ij����б���ַ�б�
    if (error == MKEvent.ERROR_ROUTE_ADDR) {
        // res.getAddrResult().mEndCityList;
        return;
    }
    // ����ſɲο�MKEvent�еĶ���
    if (error != 0 || res == null) {
        Toast.makeText(BDrugStoreRoute.this, "��Ǹ��δ�ҵ����", Toast.LENGTH_SHORT).show();
        return;
    }
    searchType = 0;
    if (routeOverlay == null) {
        routeOverlay = new RouteOverlay(BDrugStoreRoute.this, mMapView);
        // ���·��ͼ��
        mMapView.getOverlays().add(routeOverlay);
    }
    // �˴���չʾһ��������Ϊʾ��
    routeOverlay.setData(res.getPlan(0).getRoute(0));
    // ִ��ˢ��ʹ��Ч
    mMapView.refresh();
    /*// ʹ��zoomToSpan()���ŵ�ͼ��ʹ·������ȫ��ʾ�ڵ�ͼ��
			mMapView.getController().zoomToSpan(routeOverlay.getLatSpanE6(),
					routeOverlay.getLonSpanE6());*/
    // �ƶ���ͼ�����
    mMapView.getController().animateTo(res.getStart().pt);
    // ��·�����ݱ����ȫ�ֱ���
    route = res.getPlan(0).getRoute(0);
    // ����·�߽ڵ��������ڵ����ʱʹ��
    nodeIndex = -1;
    mBtnPre.setVisibility(View.VISIBLE);
    mBtnNext.setVisibility(View.VISIBLE);
    isRouted = true;
}
Example 7
Project: like_googleplus_layout-master  File: LocationActivity.java View source code
@Override
public void onGetDrivingRouteResult(MKDrivingRouteResult res, int error) {
    // 起点或终点有歧义,需要选择具体的城市列表或地址列表
    if (error == MKEvent.ERROR_ROUTE_ADDR) {
        return;
    }
    // 错误号可参考MKEvent中的定义
    if (error != 0 || res == null) {
        Toast.makeText(LocationActivity.this, "抱歉,未找到结果", Toast.LENGTH_SHORT).show();
        return;
    }
    // 将路线数据保存给全局变量
    mDividerRoute = res.getPlan(0).getRoute(0);
    getRouteInfo(res);
    mRouteOverlay = new RouteOverlay(LocationActivity.this, mMapView);
    if (mSelfRoute) {
        mDividerRoute.customizeRoute(mStartGeoPoint, mEndGeoPoint, dummyData());
    }
    // 此处仅展示一个方案作为示例
    mRouteOverlay.setData(mDividerRoute);
    // 清除其他图层
    // mMapView.getOverlays().clear();
    // 添加定位地点图层
    // mMapView.getOverlays().add(mLocationOverlay);
    // 添加路线图层
    mMapView.getOverlays().add(mRouteOverlay);
    // 执行刷新使生效
    mMapView.refresh();
    // 使用zoomToSpan()绽放地图,使路线能完全显示在地图上
    mMapView.getController().zoomToSpan(mRouteOverlay.getLatSpanE6(), mRouteOverlay.getLonSpanE6());
    // 移动地图到起点
    mMapView.getController().animateTo(res.getStart().pt);
// 重置路线节点索引,节点浏览时使用
}
Example 8
Project: pub_Android-master  File: CommonApplication.java View source code
@Override
public void onGetNetworkState(int iError) {
    if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
    // Toast.makeText(CommonApplication.getInstance(), "您的网络出错啦!",
    // Toast.LENGTH_SHORT).show();
    } else if (iError == MKEvent.ERROR_NETWORK_DATA) {
    // Toast.makeText(CommonApplication.getInstance(), "输入正确的检索条件!",
    // Toast.LENGTH_SHORT).show();
    }
}
Example 9
Project: Wawc-master  File: SearchMapActivity.java View source code
@Override
public void onGetPoiResult(MKPoiResult res, int type, int error) {
    Log.d(TAG, "onGetPoiResult: error = " + error + " , " + "type = " + type);
    if (error == MKEvent.ERROR_RESULT_NOT_FOUND) {
        Toast.makeText(SearchMapActivity.this, R.string.search_result_not_found, Toast.LENGTH_SHORT).show();
        return;
    } else if (error != 0 || res == null) {
        Toast.makeText(SearchMapActivity.this, R.string.search_error, Toast.LENGTH_SHORT).show();
        return;
    }
    // 用户判断是否已经收藏
    String str = "";
    for (MKPoiInfo mkPoiInfo : res.getAllPoi()) {
        int distance = (int) DistanceUtil.getDistance(point, mkPoiInfo.pt);
        AdressData adressData = new AdressData();
        adressData.setName(mkPoiInfo.name);
        adressData.setAdress(mkPoiInfo.address);
        adressData.setPhone(mkPoiInfo.phoneNum);
        adressData.setLat(mkPoiInfo.pt.getLatitudeE6() / 1e6);
        adressData.setLon(mkPoiInfo.pt.getLongitudeE6() / 1e6);
        adressData.setDistance(distance);
        adressDatas.add(adressData);
        str = str + mkPoiInfo.name + ",";
    }
    Log.d(TAG, "str = " + str);
    // 排序
    Collections.sort(adressDatas, new Comparator());
    adressAdapter.notifyDataSetChanged();
    for (int i = 0; i < adressDatas.size(); i++) {
        GeoPoint point1 = new GeoPoint((int) (adressDatas.get(i).getLat() * 1E6), (int) (adressDatas.get(i).getLon() * 1E6));
        OverlayItem item = new OverlayItem(point1, "item2", "item2");
        overlayCar.addItem(item);
    }
    mMapView.refresh();
    // 判断是否收藏
    String url;
    try {
        url = Constant.BaseUrl + "favorite/is_collect?auth_code=" + Variable.auth_code + "&names=" + URLEncoder.encode(str, "UTF-8") + "&cust_id=" + Variable.cust_id;
        new Thread(new NetThread.GetDataThread(handler, url, getIsCollect)).start();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}
Example 10
Project: TripGuide_XiDian-master  File: MapBase.java View source code
@Override
public void onGetNetworkState(int iError) {
    if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
        Log.i("axlecho", "您的网络出错啦!");
    } else if (iError == MKEvent.ERROR_NETWORK_DATA) {
        Log.i("axlecho", "输入正确的检索条件!");
    }
}
Example 11
Project: zaina-master  File: BaiduMapActivity.java View source code
@Override
public void onGetNetworkState(int iError) {
    if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
        Toast.makeText(BaiduMapActivity.this, "您的网络出错啦!", Toast.LENGTH_LONG).show();
    } else if (iError == MKEvent.ERROR_NETWORK_DATA) {
        Toast.makeText(BaiduMapActivity.this, "输入正确的检索条件!", Toast.LENGTH_LONG).show();
    }
// ...
}

Java Examples for org.eclipse.xsd.XSDEnumerationFacet

The following java examples will help you to understand the usage of org.eclipse.xsd.XSDEnumerationFacet. These source code samples are taken from different open source projects.

Example 1
Project: turmeric-eclipse-master  File: XSDUtils.java View source code
/**
	 * process XSDSimpleTypeDefinition instance
	 * 
	 * @param complex
	 * @return
	 * @throws ImportTypeException
	 */
private ImportTypeModel processSimpleTypeDef(XSDSimpleTypeDefinition simple) throws ImportTypeException {
    TypeParamModel model = null;
    EList<XSDEnumerationFacet> enums = simple.getEnumerationFacets();
    if (enums == null || enums.size() == 0) {
        model = new SimpleTypeParamModel();
        SOAXSDTemplateSubType simpleType = SOAXSDTemplateSubType.SIMPLE;
        model.setTemplateCategory(simpleType);
        model.setTemplateName(getTemplateFile(simpleType));
    } else {
        EnumTypeParamModel enummodel = new EnumTypeParamModel();
        model = enummodel;
        SOAXSDTemplateSubType enumType = SOAXSDTemplateSubType.ENUM;
        model.setTemplateCategory(enumType);
        String templateFile = getTemplateFile(enumType);
        model.setTemplateName(templateFile);
        EnumTableModel[] enumItems = new EnumTableModel[enums.size()];
        for (int i = 0; i < enums.size(); i++) {
            XSDEnumerationFacet facet = enums.get(i);
            enumItems[i] = new EnumTableModel();
            enumItems[i].setEnumValue(facet.getLexicalValue());
            String description = getDescriptionFromAnnotation(facet.getAnnotation());
            enumItems[i].setEnumDesc(description);
        }
        enummodel.setEnumTableModel(enumItems);
    }
    String typeName = simple.getName();
    if (typeName == null) {
        typeName = "";
    }
    // String version = simple.getSchema().getVersion();
    XSDTypeDefinition typeDef = simple.getBaseType();
    String baseType = typeDef.getName();
    String namespace = simple.getTargetNamespace();
    String description = getDescriptionFromAnnotations(simple.getAnnotations());
    model.setTypeName(typeName);
    // model.setVersion(version);
    model.setBaseType(baseType);
    model.setDescription(description);
    model.setNamespace(namespace);
    ImportTypeModel importModel = new ImportTypeModel(model);
    return importModel;
}
Example 2
Project: webtools.sourceediting-master  File: XSDImpl.java View source code
private static void getEnumeratedValuesForSimpleType(XSDTypeDefinition type, List result) {
    List enumerationFacets = ((XSDSimpleTypeDefinition) type).getEnumerationFacets();
    for (Iterator i = enumerationFacets.iterator(); i.hasNext(); ) {
        XSDEnumerationFacet enumFacet = (XSDEnumerationFacet) i.next();
        List values = enumFacet.getValue();
        for (Iterator j = values.iterator(); j.hasNext(); ) {
            Object o = j.next();
            if (o != null) {
                if (!result.contains(o)) {
                    result.add(o.toString());
                }
            }
        }
    }
}
Example 3
Project: rinzo-xml-editor-master  File: XSDAttributeDefinition.java View source code
public Collection<String> getAcceptableValues() {
    Collection<String> result = new ArrayList<String>();
    for (Iterator iterator = this.attribute.getTypeDefinition().getFacetContents().iterator(); iterator.hasNext(); ) {
        Object next = iterator.next();
        if (next instanceof XSDEnumerationFacet) {
            XSDEnumerationFacet enumerationElement = (XSDEnumerationFacet) next;
            result.add(enumerationElement.getLexicalValue());
        }
    }
    return result;
}
Example 4
Project: teiid-designer-master  File: FacetHelper.java View source code
/**
     * Sets the core value of the specified facet. If facet cannot be properly modified to match fv, facets will be added or
     * removed as necessary to make it work. This occurs when a min or max value is changed from inclusive to exclusive, and when
     * dealing with patterns and enumerations.
     * 
     * @param facet
     * @param fv
     */
private static XSDConstrainingFacet setMainFacetValue(XSDSimpleTypeDefinition type, XSDConstrainingFacet facet, Object value) {
    int facetClassifierID = facet.eClass().getClassifierID();
    switch(facetClassifierID) {
        case XSDPackage.XSD_LENGTH_FACET:
            {
                XSDLengthFacet lf = (XSDLengthFacet) facet;
                if (value instanceof Integer) {
                    Integer i = (Integer) value;
                    lf.setLexicalValue(i.toString());
                } else if (value instanceof InclusiveInteger) {
                    InclusiveInteger ii = (InclusiveInteger) value;
                    lf.setLexicalValue(Integer.toString(ii.value));
                }
            // endif
            }
            break;
        case XSDPackage.XSD_MAX_LENGTH_FACET:
            {
                XSDMaxLengthFacet mf = (XSDMaxLengthFacet) facet;
                if (value instanceof Integer) {
                    Integer i = (Integer) value;
                    mf.setLexicalValue(i.toString());
                } else if (value instanceof InclusiveInteger) {
                    InclusiveInteger ii = (InclusiveInteger) value;
                    mf.setLexicalValue(Integer.toString(ii.value));
                }
            // endif
            }
            break;
        case XSDPackage.XSD_MIN_LENGTH_FACET:
            {
                XSDMinLengthFacet mf = (XSDMinLengthFacet) facet;
                if (value instanceof Integer) {
                    Integer i = (Integer) value;
                    mf.setLexicalValue(i.toString());
                } else if (value instanceof InclusiveInteger) {
                    InclusiveInteger ii = (InclusiveInteger) value;
                    mf.setLexicalValue(Integer.toString(ii.value));
                }
            // endif
            }
            break;
        case XSDPackage.XSD_PATTERN_FACET:
            {
                XSDPatternFacet pf = (XSDPatternFacet) facet;
                pf.setLexicalValue((String) value);
            }
            break;
        case XSDPackage.XSD_ENUMERATION_FACET:
            {
                XSDEnumerationFacet ef = (XSDEnumerationFacet) facet;
                ef.setLexicalValue((String) value);
            }
            break;
        case XSDPackage.XSD_WHITE_SPACE_FACET:
            {
                XSDWhiteSpaceFacet wf = (XSDWhiteSpaceFacet) facet;
                if (value instanceof String) {
                    String white = (String) value;
                    wf.setLexicalValue(white);
                }
            // endif
            }
            break;
        case XSDPackage.XSD_MIN_EXCLUSIVE_FACET:
        case XSDPackage.XSD_MIN_INCLUSIVE_FACET:
            {
                XSDMinFacet mf = (XSDMinFacet) facet;
                if (value instanceof Integer) {
                    Integer i = (Integer) value;
                    mf.setLexicalValue(i.toString());
                } else if (value instanceof InclusiveInteger) {
                    InclusiveInteger ii = (InclusiveInteger) value;
                    if (ii.isInclusive == mf.isInclusive()) {
                        // same inclusive types, don't need to do anything crazy
                        mf.setLexicalValue(Integer.toString(ii.value));
                    } else {
                        XSDMinFacet mf2;
                        if (ii.isInclusive) {
                            mf2 = XSDFactory.eINSTANCE.createXSDMinInclusiveFacet();
                        } else {
                            mf2 = XSDFactory.eINSTANCE.createXSDMinExclusiveFacet();
                        }
                        // endif
                        mf2.setLexicalValue(Integer.toString(ii.value));
                        try {
                            // remove old:
                            ModelerCore.getModelEditor().removeValue(type, mf, type.getFacetContents());
                            // add the copy:
                            ModelerCore.getModelEditor().addValue(type, mf2, type.getFacetContents());
                            // update the return value:
                            facet = mf2;
                        } catch (ModelerCoreException err) {
                            ModelerXsdUiConstants.Util.log(err);
                        }
                        return mf2;
                    }
                // endif -- same inclusive
                }
            // endif -- integer or iinteger
            }
            break;
        case XSDPackage.XSD_MAX_EXCLUSIVE_FACET:
        case XSDPackage.XSD_MAX_INCLUSIVE_FACET:
            {
                XSDMaxFacet mf = (XSDMaxFacet) facet;
                if (value instanceof Integer) {
                    Integer i = (Integer) value;
                    mf.setLexicalValue(i.toString());
                } else if (value instanceof InclusiveInteger) {
                    InclusiveInteger ii = (InclusiveInteger) value;
                    if (ii.isInclusive == mf.isInclusive()) {
                        // same inclusive types, don't need to do anything crazy
                        mf.setLexicalValue(Integer.toString(ii.value));
                    } else {
                        XSDMaxFacet mf2;
                        if (ii.isInclusive) {
                            mf2 = XSDFactory.eINSTANCE.createXSDMaxInclusiveFacet();
                        } else {
                            mf2 = XSDFactory.eINSTANCE.createXSDMaxExclusiveFacet();
                        }
                        // endif
                        mf2.setLexicalValue(Integer.toString(ii.value));
                        try {
                            // remove old:
                            ModelerCore.getModelEditor().removeValue(type, mf, type.getFacetContents());
                            // add the copy:
                            ModelerCore.getModelEditor().addValue(type, mf2, type.getFacetContents());
                            // update the return value:
                            facet = mf2;
                        } catch (ModelerCoreException err) {
                            ModelerXsdUiConstants.Util.log(err);
                        }
                        return mf2;
                    }
                // endif -- same inclusive
                }
            // endif -- integer or iinteger
            }
            break;
        case XSDPackage.XSD_FRACTION_DIGITS_FACET:
            {
                XSDFractionDigitsFacet ff = (XSDFractionDigitsFacet) facet;
                if (value instanceof Integer) {
                    Integer i = (Integer) value;
                    ff.setLexicalValue(i.toString());
                } else if (value instanceof InclusiveInteger) {
                    InclusiveInteger ii = (InclusiveInteger) value;
                    ff.setLexicalValue(Integer.toString(ii.value));
                }
            // endif
            }
            break;
        case XSDPackage.XSD_TOTAL_DIGITS_FACET:
            {
                XSDTotalDigitsFacet tf = (XSDTotalDigitsFacet) facet;
                if (value instanceof Integer) {
                    Integer i = (Integer) value;
                    tf.setLexicalValue(i.toString());
                } else if (value instanceof InclusiveInteger) {
                    InclusiveInteger ii = (InclusiveInteger) value;
                    tf.setLexicalValue(Integer.toString(ii.value));
                }
            // endif
            }
            break;
        default:
            ModelerXsdUiConstants.Util.log(ModelerXsdUiConstants.Util.getString(ERROR_KEY_UNUSABLE_FACET, facet));
            break;
    }
    return facet;
}
Example 5
Project: org.eclipse.wst.sse.sieditor-master  File: SetBaseTypeCommand.java View source code
private void updateSimpleTypeFacets(final XSDSimpleTypeDefinition type, final XSDSimpleTypeDefinition baseType) {
    final List<XSDConstrainingFacet> facets = type.getFacetContents();
    if (!getSimpleTypeFacets().areLengthFacetsSupported(baseType)) {
        removeFacet(facets, type.getLengthFacet());
        removeFacet(facets, type.getMinLengthFacet());
        removeFacet(facets, type.getMaxLengthFacet());
    }
    if (!getSimpleTypeFacets().areInclusiveFacetsSupported(baseType)) {
        removeFacet(facets, type.getMinInclusiveFacet());
        removeFacet(facets, type.getMaxInclusiveFacet());
    }
    if (!getSimpleTypeFacets().areExclusiveFacetsSupported(baseType)) {
        removeFacet(facets, type.getMinExclusiveFacet());
        removeFacet(facets, type.getMaxExclusiveFacet());
    }
    if (!getSimpleTypeFacets().isFractionDigitsFacetSupported(baseType)) {
        removeFacet(facets, type.getFractionDigitsFacet());
    }
    if (!getSimpleTypeFacets().isTotalDigitsFacetSupported(baseType)) {
        removeFacet(facets, type.getTotalDigitsFacet());
    }
    if (!getSimpleTypeFacets().isEnumerationFacetSupported(baseType)) {
        for (final Iterator<XSDConstrainingFacet> it = facets.iterator(); it.hasNext(); ) {
            if (it.next() instanceof XSDEnumerationFacet) {
                it.remove();
            }
        }
    }
    if (!getSimpleTypeFacets().isWhitespaceFacetSupported(baseType)) {
        removeFacet(facets, type.getWhiteSpaceFacet());
    }
}
Example 6
Project: geotools_trunk-master  File: ParseExecutor.java View source code
/**
     * Pre-parses the instance compontent checking the following:
     * <p>
     *
     * </p>
     * @param instance
     */
protected Object preParse(InstanceComponent instance) {
    // we only preparse text, so simple types
    XSDSimpleTypeDefinition type = null;
    if (instance.getTypeDefinition() instanceof XSDSimpleTypeDefinition) {
        type = (XSDSimpleTypeDefinition) instance.getTypeDefinition();
    } else {
        XSDComplexTypeDefinition complexType = (XSDComplexTypeDefinition) instance.getTypeDefinition();
        if (complexType.getContentType() instanceof XSDSimpleTypeDefinition) {
            type = (XSDSimpleTypeDefinition) complexType.getContentType();
        }
    }
    String text = instance.getText();
    if (type != null) {
        //first base on variety
        if (type.getVariety() == XSDVariety.LIST_LITERAL) {
            //list, whiteSpace is fixed to "COLLAPSE 
            text = Whitespace.COLLAPSE.preparse(text);
            //lists are seperated by spaces
            String[] list = text.split(" +");
            // 4. enumeration
            if (type.getLengthFacet() != null) {
                XSDLengthFacet length = type.getLengthFacet();
                if (list.length != length.getValue()) {
                //validation exception
                }
            }
            if (type.getMaxLengthFacet() != null) {
                XSDMaxLengthFacet length = type.getMaxLengthFacet();
                if (list.length > length.getValue()) {
                //validation exception
                }
            }
            if (type.getMinLengthFacet() != null) {
                XSDMinLengthFacet length = type.getMinLengthFacet();
                if (list.length < length.getValue()) {
                //validation exception
                }
            }
            if (!type.getEnumerationFacets().isEmpty()) {
                //gather up all teh possible values
                Set values = new HashSet();
                for (Iterator e = type.getEnumerationFacets().iterator(); e.hasNext(); ) {
                    XSDEnumerationFacet enumeration = (XSDEnumerationFacet) e.next();
                    for (Iterator v = enumeration.getValue().iterator(); v.hasNext(); ) {
                        values.add(v.next());
                    }
                }
                for (int i = 0; i < list.length; i++) {
                    if (!values.contains(list[i])) {
                    //validation exception
                    }
                }
            }
            //now we must parse the items up
            final XSDSimpleTypeDefinition itemType = type.getItemTypeDefinition();
            List parsed = new ArrayList();
            //create a pseudo declaration
            final XSDElementDeclaration element = XSDFactory.eINSTANCE.createXSDElementDeclaration();
            element.setTypeDefinition(itemType);
            if (instance.getName() != null) {
                element.setName(instance.getName());
            }
            if (instance.getNamespace() != null) {
                element.setTargetNamespace(instance.getNamespace());
            }
            //create a new instance of the specified type
            InstanceComponentImpl theInstance = new InstanceComponentImpl() {

                public XSDTypeDefinition getTypeDefinition() {
                    return itemType;
                }

                public XSDNamedComponent getDeclaration() {
                    return element;
                }

                ;
            };
            for (int i = 0; i < list.length; i++) {
                theInstance.setText(list[i]);
                //perform the parse
                ParseExecutor executor = new ParseExecutor(theInstance, null, context, parser);
                parser.getBindingWalker().walk(element, executor, context);
                parsed.add(executor.getValue());
            }
            return parsed;
        } else if (type.getVariety() == XSDVariety.UNION_LITERAL) {
            // datatypes
            return text;
        } else {
            //walk through the facets and preparse as necessary 
            for (Iterator f = type.getFacets().iterator(); f.hasNext(); ) {
                XSDFacet facet = (XSDFacet) f.next();
                //white space
                if (facet instanceof XSDWhiteSpaceFacet) {
                    XSDWhiteSpaceFacet whitespace = (XSDWhiteSpaceFacet) facet;
                    if (whitespace.getValue() == XSDWhiteSpace.REPLACE_LITERAL) {
                        text = Whitespace.REPLACE.preparse(text);
                    }
                    if (whitespace.getValue() == XSDWhiteSpace.COLLAPSE_LITERAL) {
                        text = Whitespace.COLLAPSE.preparse(text);
                    }
                    if (whitespace.getValue() == XSDWhiteSpace.PRESERVE_LITERAL) {
                    //do nothing
                    }
                }
            }
            return text;
        }
    } else {
        // for mixed
        if (instance.getTypeDefinition() instanceof XSDComplexTypeDefinition && ((XSDComplexTypeDefinition) instance.getTypeDefinition()).isMixed()) {
            //collape the text
            text = Whitespace.COLLAPSE.preparse(text);
        }
    }
    return text;
}
Example 7
Project: org.eclipse.bpel-master  File: XSD2XMLGenerator.java View source code
/**
		 * This was stolen directly from XSDImpl. It builds a list of the enumeration
		 * values for the given XSD type definition.
		 * 
		 * @param type - an XSD type definition (presumably determined from a CMNode)
		 * @param result - List to which we will add our results
		 */
public void getEnumeratedValuesForSimpleType(XSDTypeDefinition type, List result) {
    List enumerationFacets = ((XSDSimpleTypeDefinition) type).getEnumerationFacets();
    for (Iterator i = enumerationFacets.iterator(); i.hasNext(); ) {
        XSDEnumerationFacet enumFacet = (XSDEnumerationFacet) i.next();
        List values = enumFacet.getValue();
        for (Iterator j = values.iterator(); j.hasNext(); ) {
            Object o = j.next();
            if (o != null) {
                if (!result.contains(o)) {
                    result.add(o.toString());
                }
            }
        }
    }
}
Example 8
Project: tmdm-studio-se-master  File: DataModelMainPage.java View source code
private int getElementType(Object decl) {
    if (Util.getParent(decl) == decl) {
        if (Util.checkConcept((XSDElementDeclaration) decl)) {
            return 0;
        }
        return 1;
    }
    if (decl instanceof XSDComplexTypeDefinition) {
        return 2;
    }
    if (decl instanceof XSDIdentityConstraintDefinition) {
        return 3;
    }
    if (decl instanceof XSDXPathDefinition) {
        return 4;
    }
    if (decl instanceof XSDSimpleTypeDefinition) {
        return 5;
    }
    if (decl instanceof XSDAnnotation) {
        return 6;
    }
    if (decl instanceof XSDParticle) {
        return 7;
    }
    if (decl instanceof XSDModelGroup) {
        return 8;
    }
    if (decl instanceof XSDWhiteSpaceFacet) {
        return 201;
    }
    if (decl instanceof XSDLengthFacet) {
        return 202;
    }
    if (decl instanceof XSDMinLengthFacet) {
        return 203;
    }
    if (decl instanceof XSDMaxLengthFacet) {
        return 204;
    }
    if (decl instanceof XSDTotalDigitsFacet) {
        return 205;
    }
    if (decl instanceof XSDFractionDigitsFacet) {
        return 206;
    }
    if (decl instanceof XSDMaxInclusiveFacet) {
        return 207;
    }
    if (decl instanceof XSDMaxExclusiveFacet) {
        return 208;
    }
    if (decl instanceof XSDMinInclusiveFacet) {
        return 209;
    }
    if (decl instanceof XSDMinExclusiveFacet) {
        return 210;
    }
    if (decl instanceof XSDPatternFacet) {
        return 211;
    }
    if (decl instanceof XSDEnumerationFacet) {
        return 212;
    }
    if (decl instanceof Element) {
        Element e = (Element) decl;
        if (e.getLocalName().equals("appinfo")) {
        //$NON-NLS-1$
        }
        //$NON-NLS-1$
        String source = e.getAttribute("source");
        if (source != null) {
            if (source.startsWith("X_Label_")) {
                //$NON-NLS-1$
                return 101;
            } else if (source.equals("X_ForeignKey")) {
                //$NON-NLS-1$
                return 102;
            } else if (source.equals("X_ForeignKeyInfo")) {
                //$NON-NLS-1$
                return 103;
            } else if (source.equals("X_SourceSystem")) {
                //$NON-NLS-1$
                return 104;
            } else if (source.equals("X_TargetSystem")) {
                //$NON-NLS-1$
                return 105;
            } else if (source.startsWith("X_Description_")) {
                //$NON-NLS-1$
                return 106;
            } else if (source.equals("X_Write")) {
                //$NON-NLS-1$
                return 107;
            } else if (source.equals("X_Hide")) {
                //$NON-NLS-1$
                return 108;
            } else if (source.equals("X_Schematron")) {
                //$NON-NLS-1$
                return 109;
            } else if (source.startsWith("X_Facet_")) {
                //$NON-NLS-1$
                return 110;
            } else if (source.startsWith("X_Workflow")) {
                //$NON-NLS-1$
                return 111;
            } else if (source.startsWith("X_ForeignKey_Filter")) {
                //$NON-NLS-1$
                return 112;
            } else if (source.startsWith("X_Display_Format_")) {
                //$NON-NLS-1$
                return 113;
            } else if (source.equals("X_Lookup_Field")) {
                //$NON-NLS-1$
                return 114;
            } else if (source.equals("X_PrimaryKeyInfo")) {
                //$NON-NLS-1$
                return 115;
            } else if (source.equals("X_Visible_Rule")) {
                //$NON-NLS-1$
                return 116;
            } else if (source.equals("X_Default_Value_Rule")) {
                //$NON-NLS-1$
                return 117;
            } else if (source.equals("X_Deny_Create")) {
                //$NON-NLS-1$
                return 118;
            } else if (source.equals("X_Deny_PhysicalDelete")) {
                //$NON-NLS-1$
                return 119;
            } else if (source.equals("X_Deny_LogicalDelete")) {
                //$NON-NLS-1$
                return 120;
            } else if (source.equals("X_FKIntegrity")) {
                //$NON-NLS-1$
                return 121;
            } else if (source.equals("X_FKIntegrity_Override")) {
                //$NON-NLS-1$
                return 122;
            } else if (source.equals("X_ForeignKeyInfoFormat")) {
                //$NON-NLS-1$
                return 123;
            }
        }
    }
    return -1;
}
Example 9
Project: modeshape-master  File: XsdReader.java View source code
protected void processTypeFacets(XSDSimpleTypeDefinition type, Node typeNode, XSDTypeDefinition baseType) throws RepositoryException {
    if (baseType == null) {
        baseType = type.getBaseType();
    }
    if (baseType == type) {
        // The base type is the anytype ...
        baseType = type.getSchema().getSchemaForSchema().resolveSimpleTypeDefinition("http://www.w3.org/2001/XMLSchema", "anyType");
    }
    if (baseType != null) {
        typeNode.setProperty(XsdLexicon.BASE_TYPE_NAME, baseType.getName());
        typeNode.setProperty(XsdLexicon.BASE_TYPE_NAMESPACE, baseType.getTargetNamespace());
        setReference(typeNode, XsdLexicon.BASE_TYPE_REFERENCE, TYPE_DEFINITIONS, baseType.getTargetNamespace(), baseType.getName());
    }
    processFacet(type.getEffectiveMaxLengthFacet(), typeNode, XsdLexicon.MAX_LENGTH, PropertyType.LONG);
    processFacet(type.getMaxLengthFacet(), typeNode, XsdLexicon.MAX_LENGTH, PropertyType.LONG);
    processFacet(type.getEffectiveMinLengthFacet(), typeNode, XsdLexicon.MIN_LENGTH, PropertyType.LONG);
    processFacet(type.getMinLengthFacet(), typeNode, XsdLexicon.MIN_LENGTH, PropertyType.LONG);
    processFacet(type.getEffectiveMaxFacet(), typeNode, XsdLexicon.MAX_VALUE_EXCLUSIVE, PropertyType.LONG);
    processFacet(type.getMaxExclusiveFacet(), typeNode, XsdLexicon.MAX_VALUE_EXCLUSIVE, PropertyType.LONG);
    processFacet(type.getEffectiveMinFacet(), typeNode, XsdLexicon.MIN_VALUE_EXCLUSIVE, PropertyType.LONG);
    processFacet(type.getMinExclusiveFacet(), typeNode, XsdLexicon.MIN_VALUE_EXCLUSIVE, PropertyType.LONG);
    processFacet(type.getMaxInclusiveFacet(), typeNode, XsdLexicon.MAX_VALUE_INCLUSIVE, PropertyType.LONG);
    processFacet(type.getMinInclusiveFacet(), typeNode, XsdLexicon.MIN_VALUE_INCLUSIVE, PropertyType.LONG);
    processFacet(type.getEffectiveTotalDigitsFacet(), typeNode, XsdLexicon.TOTAL_DIGITS, PropertyType.LONG);
    processFacet(type.getTotalDigitsFacet(), typeNode, XsdLexicon.TOTAL_DIGITS, PropertyType.LONG);
    processFacet(type.getEffectiveFractionDigitsFacet(), typeNode, XsdLexicon.FRACTION_DIGITS, PropertyType.LONG);
    processFacet(type.getFractionDigitsFacet(), typeNode, XsdLexicon.FRACTION_DIGITS, PropertyType.LONG);
    processFacet(type.getEffectiveWhiteSpaceFacet(), typeNode, XsdLexicon.WHITESPACE, PropertyType.STRING);
    processFacet(type.getWhiteSpaceFacet(), typeNode, XsdLexicon.WHITESPACE, PropertyType.STRING);
    processFacet(type.getEffectivePatternFacet(), typeNode, XsdLexicon.PATTERN, PropertyType.STRING);
    @SuppressWarnings("unchecked") List<XSDPatternFacet> patternFacets = type.getPatternFacets();
    processFacetsList(patternFacets, typeNode, XsdLexicon.PATTERN);
    processFacet(type.getEffectiveEnumerationFacet(), typeNode, XsdLexicon.ENUMERATED_VALUES, PropertyType.STRING);
    @SuppressWarnings("unchecked") List<XSDEnumerationFacet> enumFacets = type.getEnumerationFacets();
    processFacetsList(enumFacets, typeNode, XsdLexicon.ENUMERATED_VALUES);
    @SuppressWarnings("unchecked") List<XSDSimpleFinal> finalFacets2 = type.getFinal();
    processEnumerators(finalFacets2, typeNode, XsdLexicon.FINAL);
    processAnnotation(type.getAnnotation(), typeNode);
}
Example 10
Project: mappingtools-master  File: XSDStructure.java View source code
//------------------------------------------------------------------------------------------------------
//                             Getting Enumeration values of simple types
//------------------------------------------------------------------------------------------------------
/**
          * @param simpleTypeName the name of a simple type
          * @return a list of its enumerated values, if it has any; otherwise an empty list
          * @throws MapperException if there is no such simple type
          */
public Vector<String> getSimpleTypeEnumeratedValues(String simpleTypeName) throws MapperException {
    Vector<String> values = new Vector<String>();
    XSDSimpleTypeDefinition theType = null;
    EList<XSDTypeDefinition> types = schema.getTypeDefinitions();
    for (Iterator<XSDTypeDefinition> it = types.iterator(); it.hasNext(); ) {
        XSDTypeDefinition next = it.next();
        if (theType == null) {
            if ((next instanceof XSDSimpleTypeDefinition) && (next.getName().equals(simpleTypeName)))
                theType = (XSDSimpleTypeDefinition) next;
            if ((theType != null) && (theType.getEnumerationFacets() != null)) {
                int size = theType.getEnumerationFacets().size();
                if (size > 0) {
                    for (Iterator<XSDEnumerationFacet> iu = theType.getEnumerationFacets().iterator(); iu.hasNext(); ) {
                        XSDEnumerationFacet facet = iu.next();
                        EList<Object> valueSet = facet.getValue();
                        if ((valueSet != null) && (valueSet.size() == 1)) {
                            Object value = valueSet.get(0);
                            if (value instanceof String)
                                values.add((String) value);
                        }
                    }
                }
            }
        }
    }
    if (theType == null)
        throw new MapperException("Simple type '" + simpleTypeName + "' not found.");
    return values;
}
Example 11
Project: geotools-tike-master  File: ParseExecutor.java View source code
/**
     * Pre-parses the instance compontent checking the following:
     * <p>
     *
     * </p>
     * @param instance
     */
protected Object preParse(InstanceComponent instance) {
    // we only preparse text, so simple types
    XSDSimpleTypeDefinition type = null;
    if (instance.getTypeDefinition() instanceof XSDSimpleTypeDefinition) {
        type = (XSDSimpleTypeDefinition) instance.getTypeDefinition();
    } else {
        XSDComplexTypeDefinition complexType = (XSDComplexTypeDefinition) instance.getTypeDefinition();
        if (complexType.getContentType() instanceof XSDSimpleTypeDefinition) {
            type = (XSDSimpleTypeDefinition) complexType.getContentType();
        }
    }
    String text = instance.getText();
    if (type != null) {
        //first base on variety
        if (type.getVariety() == XSDVariety.LIST_LITERAL) {
            //list, whiteSpace is fixed to "COLLAPSE 
            text = Whitespace.COLLAPSE.preparse(text);
            //lists are seperated by spaces
            String[] list = text.split(" +");
            // 4. enumeration
            if (type.getLengthFacet() != null) {
                XSDLengthFacet length = type.getLengthFacet();
                if (list.length != length.getValue()) {
                //validation exception
                }
            }
            if (type.getMaxLengthFacet() != null) {
                XSDMaxLengthFacet length = type.getMaxLengthFacet();
                if (list.length > length.getValue()) {
                //validation exception
                }
            }
            if (type.getMinLengthFacet() != null) {
                XSDMinLengthFacet length = type.getMinLengthFacet();
                if (list.length < length.getValue()) {
                //validation exception
                }
            }
            if (!type.getEnumerationFacets().isEmpty()) {
                //gather up all teh possible values
                Set values = new HashSet();
                for (Iterator e = type.getEnumerationFacets().iterator(); e.hasNext(); ) {
                    XSDEnumerationFacet enumeration = (XSDEnumerationFacet) e.next();
                    for (Iterator v = enumeration.getValue().iterator(); v.hasNext(); ) {
                        values.add(v.next());
                    }
                }
                for (int i = 0; i < list.length; i++) {
                    if (!values.contains(list[i])) {
                    //validation exception
                    }
                }
            }
            //now we must parse the items up
            final XSDSimpleTypeDefinition itemType = type.getItemTypeDefinition();
            List parsed = new ArrayList();
            for (int i = 0; i < list.length; i++) {
                //create a pseudo declaration
                final XSDElementDeclaration element = XSDFactory.eINSTANCE.createXSDElementDeclaration();
                element.setTypeDefinition(itemType);
                if (instance.getName() != null) {
                    element.setName(instance.getName());
                }
                if (instance.getNamespace() != null) {
                    element.setTargetNamespace(instance.getNamespace());
                }
                //create a new instance of the specified type
                InstanceComponentImpl theInstance = new InstanceComponentImpl() {

                    public XSDTypeDefinition getTypeDefinition() {
                        return itemType;
                    }

                    public XSDNamedComponent getDeclaration() {
                        return element;
                    }

                    ;
                };
                theInstance.setText(list[i]);
                //perform the parse
                ParseExecutor executor = new ParseExecutor(theInstance, null, context, parser);
                parser.getBindingWalker().walk(element, executor, context);
                parsed.add(executor.getValue());
            }
            return parsed;
        } else if (type.getVariety() == XSDVariety.UNION_LITERAL) {
            // datatypes
            return text;
        } else {
            //walk through the facets and preparse as necessary 
            for (Iterator f = type.getFacets().iterator(); f.hasNext(); ) {
                XSDFacet facet = (XSDFacet) f.next();
                //white space
                if (facet instanceof XSDWhiteSpaceFacet) {
                    XSDWhiteSpaceFacet whitespace = (XSDWhiteSpaceFacet) facet;
                    if (whitespace.getValue() == XSDWhiteSpace.REPLACE_LITERAL) {
                        text = Whitespace.REPLACE.preparse(text);
                    }
                    if (whitespace.getValue() == XSDWhiteSpace.COLLAPSE_LITERAL) {
                        text = Whitespace.COLLAPSE.preparse(text);
                    }
                    if (whitespace.getValue() == XSDWhiteSpace.PRESERVE_LITERAL) {
                    //do nothing
                    }
                }
            }
            return text;
        }
    } else {
        // for mixed
        if (instance.getTypeDefinition() instanceof XSDComplexTypeDefinition && ((XSDComplexTypeDefinition) instance.getTypeDefinition()).isMixed()) {
            //collape the text
            text = Whitespace.COLLAPSE.preparse(text);
        }
    }
    return text;
}
Example 12
Project: geotools-master  File: ParseExecutor.java View source code
/**
     * Pre-parses the instance compontent checking the following:
     * <p>
     *
     * </p>
     * @param instance
     */
protected Object preParse(InstanceComponent instance) {
    // we only preparse text, so simple types
    XSDSimpleTypeDefinition type = null;
    if (instance.getTypeDefinition() instanceof XSDSimpleTypeDefinition) {
        type = (XSDSimpleTypeDefinition) instance.getTypeDefinition();
    } else {
        XSDComplexTypeDefinition complexType = (XSDComplexTypeDefinition) instance.getTypeDefinition();
        if (complexType.getContentType() instanceof XSDSimpleTypeDefinition) {
            type = (XSDSimpleTypeDefinition) complexType.getContentType();
        }
    }
    String text = instance.getText();
    if (type != null) {
        //first base on variety
        if (type.getVariety() == XSDVariety.LIST_LITERAL) {
            //list, whiteSpace is fixed to "COLLAPSE 
            text = Whitespace.COLLAPSE.preparse(text);
            //lists are seperated by spaces
            String[] list = text.split(" +");
            // 4. enumeration
            if (type.getLengthFacet() != null) {
                XSDLengthFacet length = type.getLengthFacet();
                if (list.length != length.getValue()) {
                //validation exception
                }
            }
            if (type.getMaxLengthFacet() != null) {
                XSDMaxLengthFacet length = type.getMaxLengthFacet();
                if (list.length > length.getValue()) {
                //validation exception
                }
            }
            if (type.getMinLengthFacet() != null) {
                XSDMinLengthFacet length = type.getMinLengthFacet();
                if (list.length < length.getValue()) {
                //validation exception
                }
            }
            if (!type.getEnumerationFacets().isEmpty()) {
                //gather up all teh possible values
                Set values = new HashSet();
                for (Iterator e = type.getEnumerationFacets().iterator(); e.hasNext(); ) {
                    XSDEnumerationFacet enumeration = (XSDEnumerationFacet) e.next();
                    for (Iterator v = enumeration.getValue().iterator(); v.hasNext(); ) {
                        values.add(v.next());
                    }
                }
                for (int i = 0; i < list.length; i++) {
                    if (!values.contains(list[i])) {
                    //validation exception
                    }
                }
            }
            //now we must parse the items up
            final XSDSimpleTypeDefinition itemType = type.getItemTypeDefinition();
            List parsed = new ArrayList();
            //create a pseudo declaration
            final XSDElementDeclaration element = XSDFactory.eINSTANCE.createXSDElementDeclaration();
            element.setTypeDefinition(itemType);
            if (instance.getName() != null) {
                element.setName(instance.getName());
            }
            if (instance.getNamespace() != null) {
                element.setTargetNamespace(instance.getNamespace());
            }
            //create a new instance of the specified type
            InstanceComponentImpl theInstance = new InstanceComponentImpl() {

                public XSDTypeDefinition getTypeDefinition() {
                    return itemType;
                }

                public XSDNamedComponent getDeclaration() {
                    return element;
                }

                ;
            };
            for (int i = 0; i < list.length; i++) {
                theInstance.setText(list[i]);
                //perform the parse
                ParseExecutor executor = new ParseExecutor(theInstance, null, context, parser);
                parser.getBindingWalker().walk(element, executor, context);
                parsed.add(executor.getValue());
            }
            return parsed;
        } else if (type.getVariety() == XSDVariety.UNION_LITERAL) {
            // datatypes
            return text;
        } else {
            //walk through the facets and preparse as necessary 
            for (Iterator f = type.getFacets().iterator(); f.hasNext(); ) {
                XSDFacet facet = (XSDFacet) f.next();
                //white space
                if (facet instanceof XSDWhiteSpaceFacet) {
                    XSDWhiteSpaceFacet whitespace = (XSDWhiteSpaceFacet) facet;
                    if (whitespace.getValue() == XSDWhiteSpace.REPLACE_LITERAL) {
                        text = Whitespace.REPLACE.preparse(text);
                    }
                    if (whitespace.getValue() == XSDWhiteSpace.COLLAPSE_LITERAL) {
                        text = Whitespace.COLLAPSE.preparse(text);
                    }
                    if (whitespace.getValue() == XSDWhiteSpace.PRESERVE_LITERAL) {
                    //do nothing
                    }
                }
            }
            return text;
        }
    } else {
        // for mixed
        if (instance.getTypeDefinition() instanceof XSDComplexTypeDefinition && ((XSDComplexTypeDefinition) instance.getTypeDefinition()).isMixed()) {
            //collape the text
            text = Whitespace.COLLAPSE.preparse(text);
        }
    }
    return text;
}
Example 13
Project: geotools-2.7.x-master  File: ParseExecutor.java View source code
/**
     * Pre-parses the instance compontent checking the following:
     * <p>
     *
     * </p>
     * @param instance
     */
protected Object preParse(InstanceComponent instance) {
    // we only preparse text, so simple types
    XSDSimpleTypeDefinition type = null;
    if (instance.getTypeDefinition() instanceof XSDSimpleTypeDefinition) {
        type = (XSDSimpleTypeDefinition) instance.getTypeDefinition();
    } else {
        XSDComplexTypeDefinition complexType = (XSDComplexTypeDefinition) instance.getTypeDefinition();
        if (complexType.getContentType() instanceof XSDSimpleTypeDefinition) {
            type = (XSDSimpleTypeDefinition) complexType.getContentType();
        }
    }
    String text = instance.getText();
    if (type != null) {
        //first base on variety
        if (type.getVariety() == XSDVariety.LIST_LITERAL) {
            //list, whiteSpace is fixed to "COLLAPSE 
            text = Whitespace.COLLAPSE.preparse(text);
            //lists are seperated by spaces
            String[] list = text.split(" +");
            // 4. enumeration
            if (type.getLengthFacet() != null) {
                XSDLengthFacet length = type.getLengthFacet();
                if (list.length != length.getValue()) {
                //validation exception
                }
            }
            if (type.getMaxLengthFacet() != null) {
                XSDMaxLengthFacet length = type.getMaxLengthFacet();
                if (list.length > length.getValue()) {
                //validation exception
                }
            }
            if (type.getMinLengthFacet() != null) {
                XSDMinLengthFacet length = type.getMinLengthFacet();
                if (list.length < length.getValue()) {
                //validation exception
                }
            }
            if (!type.getEnumerationFacets().isEmpty()) {
                //gather up all teh possible values
                Set values = new HashSet();
                for (Iterator e = type.getEnumerationFacets().iterator(); e.hasNext(); ) {
                    XSDEnumerationFacet enumeration = (XSDEnumerationFacet) e.next();
                    for (Iterator v = enumeration.getValue().iterator(); v.hasNext(); ) {
                        values.add(v.next());
                    }
                }
                for (int i = 0; i < list.length; i++) {
                    if (!values.contains(list[i])) {
                    //validation exception
                    }
                }
            }
            //now we must parse the items up
            final XSDSimpleTypeDefinition itemType = type.getItemTypeDefinition();
            List parsed = new ArrayList();
            //create a pseudo declaration
            final XSDElementDeclaration element = XSDFactory.eINSTANCE.createXSDElementDeclaration();
            element.setTypeDefinition(itemType);
            if (instance.getName() != null) {
                element.setName(instance.getName());
            }
            if (instance.getNamespace() != null) {
                element.setTargetNamespace(instance.getNamespace());
            }
            //create a new instance of the specified type
            InstanceComponentImpl theInstance = new InstanceComponentImpl() {

                public XSDTypeDefinition getTypeDefinition() {
                    return itemType;
                }

                public XSDNamedComponent getDeclaration() {
                    return element;
                }

                ;
            };
            for (int i = 0; i < list.length; i++) {
                theInstance.setText(list[i]);
                //perform the parse
                ParseExecutor executor = new ParseExecutor(theInstance, null, context, parser);
                parser.getBindingWalker().walk(element, executor, context);
                parsed.add(executor.getValue());
            }
            return parsed;
        } else if (type.getVariety() == XSDVariety.UNION_LITERAL) {
            // datatypes
            return text;
        } else {
            //walk through the facets and preparse as necessary 
            for (Iterator f = type.getFacets().iterator(); f.hasNext(); ) {
                XSDFacet facet = (XSDFacet) f.next();
                //white space
                if (facet instanceof XSDWhiteSpaceFacet) {
                    XSDWhiteSpaceFacet whitespace = (XSDWhiteSpaceFacet) facet;
                    if (whitespace.getValue() == XSDWhiteSpace.REPLACE_LITERAL) {
                        text = Whitespace.REPLACE.preparse(text);
                    }
                    if (whitespace.getValue() == XSDWhiteSpace.COLLAPSE_LITERAL) {
                        text = Whitespace.COLLAPSE.preparse(text);
                    }
                    if (whitespace.getValue() == XSDWhiteSpace.PRESERVE_LITERAL) {
                    //do nothing
                    }
                }
            }
            return text;
        }
    } else {
        // for mixed
        if (instance.getTypeDefinition() instanceof XSDComplexTypeDefinition && ((XSDComplexTypeDefinition) instance.getTypeDefinition()).isMixed()) {
            //collape the text
            text = Whitespace.COLLAPSE.preparse(text);
        }
    }
    return text;
}
Example 14
Project: geotools-old-master  File: ParseExecutor.java View source code
/**
     * Pre-parses the instance compontent checking the following:
     * <p>
     *
     * </p>
     * @param instance
     */
protected Object preParse(InstanceComponent instance) {
    // we only preparse text, so simple types
    XSDSimpleTypeDefinition type = null;
    if (instance.getTypeDefinition() instanceof XSDSimpleTypeDefinition) {
        type = (XSDSimpleTypeDefinition) instance.getTypeDefinition();
    } else {
        XSDComplexTypeDefinition complexType = (XSDComplexTypeDefinition) instance.getTypeDefinition();
        if (complexType.getContentType() instanceof XSDSimpleTypeDefinition) {
            type = (XSDSimpleTypeDefinition) complexType.getContentType();
        }
    }
    String text = instance.getText();
    if (type != null) {
        //first base on variety
        if (type.getVariety() == XSDVariety.LIST_LITERAL) {
            //list, whiteSpace is fixed to "COLLAPSE 
            text = Whitespace.COLLAPSE.preparse(text);
            //lists are seperated by spaces
            String[] list = text.split(" +");
            // 4. enumeration
            if (type.getLengthFacet() != null) {
                XSDLengthFacet length = type.getLengthFacet();
                if (list.length != length.getValue()) {
                //validation exception
                }
            }
            if (type.getMaxLengthFacet() != null) {
                XSDMaxLengthFacet length = type.getMaxLengthFacet();
                if (list.length > length.getValue()) {
                //validation exception
                }
            }
            if (type.getMinLengthFacet() != null) {
                XSDMinLengthFacet length = type.getMinLengthFacet();
                if (list.length < length.getValue()) {
                //validation exception
                }
            }
            if (!type.getEnumerationFacets().isEmpty()) {
                //gather up all teh possible values
                Set values = new HashSet();
                for (Iterator e = type.getEnumerationFacets().iterator(); e.hasNext(); ) {
                    XSDEnumerationFacet enumeration = (XSDEnumerationFacet) e.next();
                    for (Iterator v = enumeration.getValue().iterator(); v.hasNext(); ) {
                        values.add(v.next());
                    }
                }
                for (int i = 0; i < list.length; i++) {
                    if (!values.contains(list[i])) {
                    //validation exception
                    }
                }
            }
            //now we must parse the items up
            final XSDSimpleTypeDefinition itemType = type.getItemTypeDefinition();
            List parsed = new ArrayList();
            //create a pseudo declaration
            final XSDElementDeclaration element = XSDFactory.eINSTANCE.createXSDElementDeclaration();
            element.setTypeDefinition(itemType);
            if (instance.getName() != null) {
                element.setName(instance.getName());
            }
            if (instance.getNamespace() != null) {
                element.setTargetNamespace(instance.getNamespace());
            }
            //create a new instance of the specified type
            InstanceComponentImpl theInstance = new InstanceComponentImpl() {

                public XSDTypeDefinition getTypeDefinition() {
                    return itemType;
                }

                public XSDNamedComponent getDeclaration() {
                    return element;
                }

                ;
            };
            for (int i = 0; i < list.length; i++) {
                theInstance.setText(list[i]);
                //perform the parse
                ParseExecutor executor = new ParseExecutor(theInstance, null, context, parser);
                parser.getBindingWalker().walk(element, executor, context);
                parsed.add(executor.getValue());
            }
            return parsed;
        } else if (type.getVariety() == XSDVariety.UNION_LITERAL) {
            // datatypes
            return text;
        } else {
            //walk through the facets and preparse as necessary 
            for (Iterator f = type.getFacets().iterator(); f.hasNext(); ) {
                XSDFacet facet = (XSDFacet) f.next();
                //white space
                if (facet instanceof XSDWhiteSpaceFacet) {
                    XSDWhiteSpaceFacet whitespace = (XSDWhiteSpaceFacet) facet;
                    if (whitespace.getValue() == XSDWhiteSpace.REPLACE_LITERAL) {
                        text = Whitespace.REPLACE.preparse(text);
                    }
                    if (whitespace.getValue() == XSDWhiteSpace.COLLAPSE_LITERAL) {
                        text = Whitespace.COLLAPSE.preparse(text);
                    }
                    if (whitespace.getValue() == XSDWhiteSpace.PRESERVE_LITERAL) {
                    //do nothing
                    }
                }
            }
            return text;
        }
    } else {
        // for mixed
        if (instance.getTypeDefinition() instanceof XSDComplexTypeDefinition && ((XSDComplexTypeDefinition) instance.getTypeDefinition()).isMixed()) {
            //collape the text
            text = Whitespace.COLLAPSE.preparse(text);
        }
    }
    return text;
}
Example 15
Project: bpel-master  File: XSD2XMLGenerator.java View source code
/**
		 * This was stolen directly from XSDImpl. It builds a list of the enumeration
		 * values for the given XSD type definition.
		 * 
		 * @param type - an XSD type definition (presumably determined from a CMNode)
		 * @param result - List to which we will add our results
		 */
public void getEnumeratedValuesForSimpleType(XSDTypeDefinition type, List result) {
    List enumerationFacets = ((XSDSimpleTypeDefinition) type).getEnumerationFacets();
    for (Iterator i = enumerationFacets.iterator(); i.hasNext(); ) {
        XSDEnumerationFacet enumFacet = (XSDEnumerationFacet) i.next();
        List values = enumFacet.getValue();
        for (Iterator j = values.iterator(); j.hasNext(); ) {
            Object o = j.next();
            if (o != null) {
                if (!result.contains(o)) {
                    result.add(o.toString());
                }
            }
        }
    }
}