code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
<%@ page contentType="text/html;charset=GBK"%>
<%@ include file="/login/common/common_taglibs.jsp" %>
<html>
<head>
<%@ include file="/login/common/head_common_element.jsp"%>
</head>
<frameset cols="200,*" frameborder="no" border="1" framespacing="0" >
<frame src="${ctx}/cms/manager/menu.do?method=tree" name="leftFrame" id="leftFrame"/>
<frame src="${ctx}/cms/manager/menu.do?method=create&parentMenuId=0" name="mainFrame" id="mainFrame" />
</frameset>
<noframes>
<body>
</body>
</html> | 100gd-compare | trunk/WebContent/login/cms/cms_manager_menu_index.jsp | Java Server Pages | epl | 512 |
<%@ page contentType="text/html;charset=GBK"%>
<%@ include file="/login/common/common_taglibs.jsp" %>
<html>
<head>
<%@ include file="/login/common/head_common_element.jsp"%>
</head>
<frameset cols="200,*" frameborder="no" border="1" framespacing="0" >
<frame src="${ctx}/cms/link/config.do?method=tree" name="leftFrame" id="leftFrame"/>
<frame src="${ctx}/cms/link/config.do?method=list&groupId=0" name="mainFrame" id="mainFrame" />
</frameset>
<noframes>
<body>
</body>
</html> | 100gd-compare | trunk/WebContent/login/cms/cms_link_config_index.jsp | Java Server Pages | epl | 503 |
<%@ page contentType="text/html;charset=GBK"%>
<%@ include file="/login/common/common_taglibs.jsp" %>
<html>
<head>
<%@ include file="/login/common/head_common_element.jsp"%>
</head>
<frameset cols="200,*" frameborder="no" border="1" framespacing="0" >
<frame src="${ctx}/cms/link/group.do?method=tree" name="leftFrame" id="leftFrame"/>
<frame src="${ctx}/cms/link/group.do?method=create&parentGroupId=0" name="mainFrame" id="mainFrame" />
</frameset>
<noframes>
<body>
</body>
</html> | 100gd-compare | trunk/WebContent/login/cms/cms_link_group_index.jsp | Java Server Pages | epl | 509 |
<%@ page contentType="text/html;charset=GBK"%>
<%@ include file="/login/common/common_taglibs.jsp" %>
<html>
<head>
<%@ include file="/login/common/head_common_element.jsp"%>
</head>
<frameset cols="200,*" frameborder="no" border="1" framespacing="0" >
<frame src="${ctx}/cms/menu/user.do?method=tree" name="leftFrame" id="leftFrame"/>
<frame src="${ctx}/cms/menu/user.do?method=list&menuId=0" name="mainFrame" id="mainFrame" />
</frameset>
<noframes>
<body>
</body>
</html> | 100gd-compare | trunk/WebContent/login/cms/cms_menu_user_index.jsp | Java Server Pages | epl | 498 |
<%@ page contentType="text/html;charset=GBK"%>
<%@ include file="/login/common/common_taglibs.jsp" %>
<html>
<head>
<%@ include file="/login/common/head_common_element.jsp"%>
</head>
<frameset cols="200,*" frameborder="no" border="1" framespacing="0" >
<frame src="${ctx}/cms/manager/channel.do?method=tree" name="leftFrame" id="leftFrame"/>
<frame src="${ctx}/cms/manager/channel.do?method=create&parentChannelId=0" name="mainFrame" id="mainFrame" />
</frameset>
<noframes>
<body>
</body>
</html> | 100gd-compare | trunk/WebContent/login/cms/channel/cms_manager_channel_index.jsp | Java Server Pages | epl | 521 |
<%@ page contentType="text/html;charset=GBK"%>
<%@ include file="/login/common/common_taglibs.jsp" %>
<html>
<head>
<%@ include file="/login/common/head_common_element.jsp"%>
</head>
<frameset cols="260,*" frameborder="no" border="1" framespacing="0" >
<frame src="${ctx}/cms/video/mng.do?method=tree" name="leftFrame" id="leftFrame"/>
<frame src="${ctx}/cms/video/mng.do?method=list&menuId=0" name="mainFrame" id="mainFrame" />
</frameset>
<noframes>
<body>
</body>
</html> | 100gd-compare | trunk/WebContent/login/cms/cms_video_mng_index.jsp | Java Server Pages | epl | 498 |
<%@ page contentType="text/html;charset=GBK"%>
<%@ include file="/login/common/common_taglibs.jsp" %>
<html>
<head>
<%@ include file="/login/common/head_common_element.jsp"%>
</head>
<body>
</body>
</html>
| 100gd-compare | trunk/WebContent/login/cms/cms_common_index.jsp | Java Server Pages | epl | 229 |
body {
color:#000;
background-color:white;
font:15px Georgia, "Lucida Grande", Arial, sans-serif;
letter-spacing:0.01em;
margin:15px;
}
#controlPanel,#resultPanel{
width:700px;
margin:20px auto;
padding:25px;
border:3px solid gray;
-moz-border-radius:10px;
background:#f8f8f8;
}
#errorArea{
width:400px;
margin:20px auto;
padding:25px;
border:3px solid gray;
-moz-border-radius:10px;
background:red;
}
#normalMessageArea{
width:400px;
margin:20px auto;
padding:25px;
border:3px solid gray;
-moz-border-radius:10px;
background:yellow;
}
#progressBar { padding-top: 5px; }
#totalProgressBarBox {
width: 350px;
height: 20px;
border: 1px inset;
background: #eee;
}
#totalProgressBarBoxContent {
width: 0;
height: 20px;
border-right: 1px solid #444;
background: #9ACB34;
} | 100gd-compare | trunk/WebContent/login/js/fileupload/fileUpload.css | CSS | epl | 875 |
<%@ page contentType="text/html;charset=GBK"%>
<%@ include file="/login/system/system_taglibs.jsp" %>
<html>
<head>
<%@ include file="/login/common/head_common_element.jsp"%>
</head>
<frameset cols="200,*" frameborder="no" border="1" framespacing="0" >
<frame src="${ctx}/system/menu.do?method=tree" name="leftFrame" id="leftFrame"/>
<frame src="${ctx}/system/menu.do?method=create" name="mainFrame" id="mainFrame" />
</frameset>
<noframes>
<body>
</body>
</html> | 100gd-compare | trunk/WebContent/login/system/system_menu_index.jsp | Java Server Pages | epl | 489 |
<%@ include file="/login/common/taglibs.jsp" %>
<%@ include file="/login/system/system_admin_login_check.jsp" %> | 100gd-compare | trunk/WebContent/login/system/system_taglibs.jsp | Java Server Pages | epl | 113 |
<%@ page contentType="text/html;charset=GBK"%>
<%@ include file="/login/system/system_taglibs.jsp" %>
<html>
<head>
<%@ include file="/login/common/head_common_element.jsp"%>
</head>
<frameset cols="200,*" frameborder="no" border="1" framespacing="0" >
<frame src="${ctx}/system/dept.do?method=tree" name="leftFrame" id="leftFrame"/>
<frame src="${ctx}/system/dept.do?method=create" name="mainFrame" id="mainFrame" />
</frameset>
<noframes>
<body>
</body>
</html> | 100gd-compare | trunk/WebContent/login/system/system_dept_index.jsp | Java Server Pages | epl | 489 |
<%@ page contentType="text/html;charset=GBK"%>
<%@ include file="/login/system/system_taglibs.jsp" %>
<html>
<head>
<%@ include file="/login/common/head_common_element.jsp"%>
</head>
<frameset cols="200,*" frameborder="no" border="1" framespacing="0" >
<frame src="${ctx}/system/user.do?method=deptTree" name="leftFrame" id="leftFrame"/>
<frame src="${ctx}/system/user.do?method=list&deptId=0" name="mainFrame" id="mainFrame" />
</frameset>
<noframes>
<body>
</body>
</html> | 100gd-compare | trunk/WebContent/login/system/system_user_index.jsp | Java Server Pages | epl | 500 |
<%@ page contentType="text/html;charset=GBK"%>
<%@ include file="/login/common/common_taglibs.jsp" %>
<html>
<head>
<%@ include file="/login/common/head_common_element.jsp"%>
<link rel="stylesheet" href="${ctx}/login/main/css/common.css" type="text/css" />
</head>
<frameset rows="22,*" cols="*" frameborder="no" border="0" framespacing="0">
<frame src="${ctx}/lg/submit.do?method=header" name="topFrame" frameborder="no" scrolling="No" noresize="noresize" id="topFrame" title="topFrame" />
<frameset name="myFrame" cols="199,7,*" frameborder="no" border="0" framespacing="0">
<frame src="${ctx}/lg/submit.do?method=leftMenuFrame" name="leftFrame" frameborder="no" scrolling="No" noresize="noresize" id="leftFrame" title="leftFrame" />
<frame src="${ctx}/lg/submit.do?method=switchFrame" name="midFrame" frameborder="no" scrolling="No" noresize="noresize" id="midFrame" title="midFrame" />
<frameset rows="32,*" cols="*" frameborder="no" border="0" framespacing="0">
<frame src="${ctx}/lg/submit.do?method=topMenuFrame" name="mainFrame" frameborder="no" scrolling="No" noresize="noresize" id="mainFrame" title="mainFrame" />
<!-- <frame src="#" name="manFrame" frameborder="no" scrolling="auto" id="manFrame" title="manFrame" /> -->
<frameset name="manFrame" rows="18,*" cols="*" frameborder="no" border="0" framespacing="0">
<frame src="#" name="manFrameTop" noresize="noresize" frameborder="no" scrolling="no" id="manFrameTop" title="manFrameTop" />
<frame src="#" name="manFrameEnd" noresize="noresize" frameborder="no" scrolling="auto" id="manFrameEnd" title="manFrameEnd" />
</frameset>
</frameset>
</frameset>
</frameset>
<noframes>
<body>
</body>
</noframes>
</html>
| 100gd-compare | trunk/WebContent/login/main/system_frame.jsp | Java Server Pages | epl | 1,767 |
body {
padding-left: 0px;
padding-right: 0px;
padding-top: 0px;
padding-bottom: 0px;
margin: 0px;
}
.abody {
width:98%;
}
html {
background-color: #F9F9F9;
padding-left: 0px;
padding-right: 0px;
padding-top: 0px;
padding-bottom: 0px;
margin: 0px;
}
body {
background-color: #F9F9F9;
font-family: Verdana, Arial,Vrinda,Tahoma;
line-height: 175%;
font-size:12px;
color:#666;
}
a {
color: #555;
text-decoration:none;
}
a:hover {
color: #0099CC;
}
img {
border-top-width: 0px;
border-right-width: 0px;
border-bottom-width: 0px;
border-left-width: 0px;
display:inline;
}
ul{
margin:0;
padding:0;
list-style-position: outside;
list-style-type: none;
}
li{
margin:0;
padding:0;
}
div{
margin:0;
padding:0;
}
.header_content {
margin: 0 auto;
padding:0px;
width: 100%;
}
.header_content .logo {
height: 10px;
width: 20%;
float: left;
}
.header_content .right_nav {
float: right;
width: 80%;
height: 10px;
}
.right_nav .text_left {
float: left;
width: 20%;
padding: 0 0 0 0;
color: #CC3300;
}
.right_nav .text_right {
float: right;
width: 80%;
display: inline;
padding: 0 0 0 0;
text-align: right;
}
.nav_list a {
display: inline;
color:#3399CC;
}
.nav_list li {
display:inline;
}
.nav_return a {
display: inline;
color:#3399CC;
}
.nav_return li {
display: inline;
}
#left_content {
clear: both;
width: 199px;
}
#left_content #user_info {
background-image: url(../images/manage_r2_c1.jpg);
background-repeat: no-repeat;
height: 55px;
padding: 10px 0 0 55px;
}
#left_content #user_info a{
color:#0099CC;
}
#left_content #main_nav {
width: 199px;
background-image: url(../images/left_nav_bg.jpg);
background-repeat: repeat-y;
}
#left_main_nav {
float: left;
width: 25px;
line-height: 13px;
color:#0099CC;
}
#left_main_nav li{
height:69px;
width:12px;
text-align: center;
padding: 7px 6px 0 7px;
}
.left_back{
background-image: url(../images/manage_r7_c2.jpg);
background-repeat: no-repeat;
cursor:pointer;
}
.left_back_onclick{
background-image: url(../images/manage_r6_c2.jpg);
background-repeat: no-repeat;
color:#333333;
}
#left_main_nav a{
color:#0099CC;
}
#right_main_nav {
width: 173px;
border-top-width: 1px;
border-bottom-width: 1px;
border-top-style: solid;
border-bottom-style: solid;
border-top-color: #B4C9C6;
border-bottom-color: #B4C9C6;
float: right;
background-color: #FFFFFF;
border-right-width: 1px;
border-right-style: solid;
border-right-color: #B4C9C6;
height: 500px;
text-align: left;
}
.list_tilte {
background-image: url(../images/list_title.gif);
background-repeat: no-repeat;
margin: 0 auto;
clear: both;
height: 22px;
width: 155px;
padding-left: 30px;
font-weight: bold;
color: #0099CC;
margin-top: 9px;
cursor:pointer;
}
.list_tilte_onclick {
background-image: url(../images/list_title_onclick.gif);
background-repeat: no-repeat;
margin: 0 auto;
clear: both;
height: 22px;
width: 155px;
padding-left: 30px;
font-weight: bold;
color: #0099CC;
margin-top: 9px;
cursor:pointer;
}
.list_detail {
margin: 0 auto;
}
.list_detail li{
list-style-image: url(../images/direct_blue.gif);
list-style-position: inside;
padding: 0 0 0 4px;
}
#switchpic {
width: 6px;
cursor:pointer;
clear: both;
vertical-align: bottom;
margin-top: 220px;
}
#nav {
width:100%;
float:left;
background-image: url(../images/nav_bg.jpg);
}
#nav ul {
margin:0;
list-style:none;
padding: 0;
}
#nav li {
float:left;
margin:0;
padding:2px 35px 0 30px;
line-height:24px;
font-weight:bold;
}
.bg_image{
background: url(../images/manage_r2_c14.jpg) no-repeat;
cursor:pointer;
}
.bg_image_onclick{
background: url(../images/manage_r2_c13.jpg) no-repeat;
color:#0099CC;
}
#sub_info {
width: 99%;
float:left;
background-image: url(../images/manage_r3_c11.jpg);
border-right-width: 1px;
border-bottom-width: 1px;
border-left-width: 1px;
border-right-style: solid;
border-bottom-style: solid;
border-left-style: solid;
border-right-color: #B4C9C6;
border-bottom-color: #B4C9C6;
border-left-color: #B4C9C6;
height: 27px;
background-repeat: repeat-x;
padding: 5px 0 0 0;
}
#man_zone {
height: 100%;
width: 100%;
border: 1px solid #B4C9C6;
margin: 0 0 0 0;
background-color:#FFFFFF;
padding: 5px 0 5px 0;
overflow: auto;
}
#man_zone table{
background-color:#DBE6E3;
}
#man_zone table tr{
background-color:#fff;
}
.left_title_1 {
background-color: #F3F8F7;
color:#73938E;
font-weight:bold;
line-height:30px;
text-align:right
}
.left_title_2 {
background-color: #fff;
color:#73938E;
font-weight:bold;
line-height:30px;
text-align:right;
}
| 100gd-compare | trunk/WebContent/login/main/css/common.css | CSS | epl | 4,906 |
body {
padding-left: 0px;
padding-right: 0px;
padding-top: 0px;
padding-bottom: 0px;
margin: 0px;
}
.abody {
width:98%;
}
html {
background-color: #F9F9F9;
padding-left: 0px;
padding-right: 0px;
padding-top: 0px;
padding-bottom: 0px;
margin: 0px;
}
body {
background-color: #F9F9F9;
font-family: Verdana, Arial,Vrinda,Tahoma;
line-height: 175%;
font-size:12px;
color:#666;
}
a {
color: #555;
text-decoration:none;
}
a:hover {
color: #0099CC;
}
img {
border-top-width: 0px;
border-right-width: 0px;
border-bottom-width: 0px;
border-left-width: 0px;
display:inline;
}
ul{
margin:0;
padding:0;
list-style-position: outside;
list-style-type: none;
}
li{
margin:0;
padding:0;
}
div{
margin:0;
padding:0;
}
.header_content {
margin: 0 auto;
padding:0px;
width: 100%;
}
.header_content .logo {
height: 10px;
width: 20%;
float: left;
}
.header_content .right_nav {
float: right;
width: 80%;
height: 10px;
}
.right_nav .text_left {
float: left;
width: 20%;
padding: 0 0 0 0;
color: #CC3300;
}
.right_nav .text_right {
float: right;
width: 80%;
display: inline;
padding: 0 0 0 0;
text-align: right;
}
.nav_list a {
display: inline;
color:#3399CC;
}
.nav_list li {
display:inline;
}
.nav_return a {
display: inline;
color:#3399CC;
}
.nav_return li {
display: inline;
}
#left_content {
clear: both;
width: 199px;
}
#left_content #user_info {
background-image: url(../images/manage_r2_c1.jpg);
background-repeat: no-repeat;
height: 55px;
padding: 10px 0 0 55px;
}
#left_content #user_info a{
color:#0099CC;
}
#left_content #main_nav {
width: 199px;
background-image: url(../images/left_nav_bg.jpg);
background-repeat: repeat-y;
}
#left_main_nav {
float: left;
width: 25px;
line-height: 13px;
color:#0099CC;
}
#left_main_nav li{
height:69px;
width:12px;
text-align: center;
padding: 7px 6px 0 7px;
}
.left_back{
background-image: url(../images/manage_r7_c2.jpg);
background-repeat: no-repeat;
cursor:pointer;
}
.left_back_onclick{
background-image: url(../images/manage_r6_c2.jpg);
background-repeat: no-repeat;
color:#333333;
}
#left_main_nav a{
color:#0099CC;
}
#right_main_nav {
width: 173px;
border-top-width: 1px;
border-bottom-width: 1px;
border-top-style: solid;
border-bottom-style: solid;
border-top-color: #B4C9C6;
border-bottom-color: #B4C9C6;
float: right;
background-color: #FFFFFF;
border-right-width: 1px;
border-right-style: solid;
border-right-color: #B4C9C6;
height: 500px;
text-align: left;
}
.list_tilte {
background-image: url(../images/list_title.gif);
background-repeat: no-repeat;
margin: 0 auto;
clear: both;
height: 22px;
width: 140px;
padding-left: 30px;
font-weight: bold;
color: #0099CC;
margin-top: 9px;
cursor:pointer;
}
.list_tilte_onclick {
background-image: url(../images/list_title_onclick.gif);
background-repeat: no-repeat;
margin: 0 auto;
clear: both;
height: 22px;
width: 140px;
padding-left: 30px;
font-weight: bold;
color: #0099CC;
margin-top: 9px;
cursor:pointer;
}
.list_detail {
margin: 0 auto;
}
.list_detail li{
list-style-image: url(../images/direct_blue.gif);
list-style-position: inside;
padding: 0 0 0 4px;
}
#switchpic {
width: 6px;
cursor:pointer;
clear: both;
vertical-align: bottom;
margin-top: 220px;
}
#nav {
width:100%;
float:left;
background-image: url(../images/nav_bg.jpg);
}
#nav ul {
margin:0;
list-style:none;
padding: 0;
}
#nav li {
float:left;
margin:0;
padding:2px 35px 0 30px;
line-height:24px;
font-weight:bold;
}
.bg_image{
background: url(../images/manage_r2_c14.jpg) no-repeat;
cursor:pointer;
}
.bg_image_onclick{
background: url(../images/manage_r2_c13.jpg) no-repeat;
color:#0099CC;
}
#sub_info {
width: 99%;
float:left;
background-image: url(../images/manage_r3_c11.jpg);
border-right-width: 1px;
border-bottom-width: 1px;
border-left-width: 1px;
border-right-style: solid;
border-bottom-style: solid;
border-left-style: solid;
border-right-color: #B4C9C6;
border-bottom-color: #B4C9C6;
border-left-color: #B4C9C6;
height: 27px;
background-repeat: repeat-x;
padding: 5px 0 0 0;
}
#man_zone {
height: 100%;
width: 100%;
border: 1px solid #B4C9C6;
margin: 0 0 0 0;
background-color:#FFFFFF;
padding: 5px 0 5px 0;
overflow: auto;
}
#man_zone table{
background-color:#DBE6E3;
}
#man_zone table tr{
background-color:#fff;
}
.left_title_1 {
background-color: #F3F8F7;
color:#73938E;
font-weight:bold;
line-height:30px;
text-align:right
}
.left_title_2 {
background-color: #fff;
color:#73938E;
font-weight:bold;
line-height:30px;
text-align:right;
}
| 100gd-compare | trunk/WebContent/login/css/common.css | CSS | epl | 4,906 |
<%@ page contentType="text/html;charset=GBK"%>
<%@ page contentType="text/html;charset=GBK"%>
<%@ page import="com.busi.system.model.SystemMenu"%>
<%@ page import="java.util.Set"%>
<%@ page import="java.util.Iterator"%>
<%@ page import="com.busi.framework.base.CC"%>
<%
SystemMenu sm = (SystemMenu)request.getAttribute("sm");
Set secMenuIdInSession = (Set)request.getSession().getAttribute(CC.SET_SEC_MENU_ID);
Set thrMenuIdInSession = (Set)request.getSession().getAttribute(CC.SET_THR_MENU_ID);
%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
<title></title>
<style type="text/css">
<!--
body {
margin-left: 0px;
margin-top: 0px;
margin-right: 0px;
margin-bottom: 0px;
}
.STYLE1 {
font-size: 12px;
color: #FFFFFF;
}
.STYLE3 {
font-size: 12px;
color: #033d61;
}
.menu_title SPAN {
FONT-WEIGHT: bold; LEFT: 3px; COLOR: #ffffff; POSITION: relative; TOP: 2px
}
.menu_title2 SPAN {
FONT-WEIGHT: bold; LEFT: 3px; COLOR: #FFCC00; POSITION: relative; TOP: 2px
}
.tronclickbg1 {
background: #fff;
}
.tronclickbg2 {
background: #79D0FF;
}
-->
</style>
<script>
var he=document.body.clientHeight-105
document.write("<div id=tt style=height:"+he+";overflow:hidden>")
</script>
<body style="overflow:hidden">
<table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0" style="table-layout:fixed;">
<tr>
<td width="171" id=frmTitle noWrap name="fmTitle" align="center" valign="top"><table width="171" height="100%" border="0" cellpadding="0" cellspacing="0" style="table-layout:fixed;">
<tr>
<td bgcolor="#1873aa" style="width:6px;"></td>
<td width="165">
<table width="165" height="100%" border="0" cellpadding="0" cellspacing="0" style="background: #fff;">
<tr>
<td height="28" background="${ctx}/login/frame/images/main_40.gif"><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="100%" height="20" align="center"><span class="STYLE1"><%=sm.getCn_name()%></span></td>
</tr>
</table></td>
</tr>
<tr>
<td valign="top">
<table width="151" border="0" align="center" cellpadding="0" cellspacing="0">
<%
Set setSecMenu = sm.getSetChildMenu();
Iterator itrSecMenu = setSecMenu.iterator();
while(itrSecMenu.hasNext()){
SystemMenu secMenu = (SystemMenu)itrSecMenu.next();
if(!CC.CHECK_LEVEL.equals("0")){
if(secMenuIdInSession.contains(secMenu.getId())){
%>
<tr>
<td>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td height="23" background="${ctx}/login/frame/images/main_47.gif" id="imgmenu<%=secMenu.getId()%>" class="menu_title" onMouseOver="this.className='menu_title2';" onClick="showsubmenu(<%=secMenu.getId()%>)" onMouseOut="this.className='menu_title';" style="cursor:hand"><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="18%"> </td>
<td width="82%" class="STYLE1"><%=secMenu.getCn_name()%></td>
</tr>
</table></td>
</tr>
<tr>
<td background="${ctx}/login/frame/images/main_51.gif" id="submenu<%=secMenu.getId()%>">
<div class="sec_menu" >
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><table width="90%" border="0" align="center" cellpadding="0" cellspacing="0">
<%
Set setThrMenu = secMenu.getSetChildMenu();
Iterator itrThrMenu = setThrMenu.iterator();
while(itrThrMenu.hasNext()){
SystemMenu thrMenu = (SystemMenu)itrThrMenu.next();
if(thrMenuIdInSession.contains(thrMenu.getId())){
%>
<tr id="tabletd<%=thrMenu.getId()%>" class="tronclickbg1">
<td width="16%" height="23"><div align="center"><img src="${ctx}/login/frame/images/left.gif" width="10" height="10" /></div></td>
<td width="84%" height="23">
<table width="95%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td height="20" style="cursor:hand;" onclick="toRightFrame('<%=thrMenu.getLink_forward()%>','<%=thrMenu.getId()%>')" onmouseover="this.style.borderStyle='solid';this.style.borderWidth='1';borderColor='#7bc4d3'; "onmouseout="this.style.borderStyle='none'"><span class="STYLE3"><%=thrMenu.getCn_name()%></span></td>
</tr>
</table></td>
</tr>
<%
}
}
%>
</table></td>
</tr>
<tr>
<td height="5"><img src="${ctx}/login/frame/images/main_52.gif" width="151" height="5" /></td>
</tr>
</table></div></td>
</tr>
</table></td>
</tr>
<%
}
}
}
%>
</table></td>
</tr>
<tr>
<td height="4" background="${ctx}/login/frame/images/main_58.gif">
</td>
</tr>
</table>
</td>
</tr>
</table> </td>
</tr>
</table>
</body>
</html>
<script>
function showsubmenu(sid){
whichEl = eval("submenu" + sid);
imgmenu = eval("imgmenu" + sid);
if (whichEl.style.display == "none")
{
eval("submenu" + sid + ".style.display=\"\";");
imgmenu.background="${ctx}/login/frame/images/main_47.gif";
}
else
{
eval("submenu" + sid + ".style.display=\"none\";");
imgmenu.background="${ctx}/login/frame/images/main_48.gif";
}
}
var lastMenuId = 0;
function toRightFrame(linkforward , id){
if(lastMenuId != 0){
var tabletr = document.getElementById("tabletd"+lastMenuId);
tabletr.className ="tronclickbg1";
}
var tabletr = document.getElementById("tabletd"+id);
tabletr.className ="tronclickbg2";
lastMenuId = id;
window.top.frames['midFrame'].location = linkforward;
}
var curSecMenuUrl = "<%=sm.getLink_forward()%>";
window.top.frames['midFrame'].location = curSecMenuUrl;
</script> | 100gd-compare | trunk/WebContent/login/frame/left.jsp | Java Server Pages | epl | 6,114 |
<%@ page contentType="text/html;charset=GBK"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
<title></title>
<style type="text/css">
<!--
body {
margin-left: 0px;
margin-top: 0px;
margin-right: 0px;
margin-bottom: 0px;
}
-->
</style></head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="6" background="${ctx}/login/frame/images/main_59.gif" style="line-height:6px;"><img src="${ctx}/login/frame/images/main_59.gif" width="6" height="6" ></td>
<td background="${ctx}/login/frame/images/main_61.gif" style="line-height:6px;"> </td>
<td width="6" background="${ctx}/login/frame/images/main_61.gif" style="line-height:6px;"><img src="${ctx}/login/frame/images/main_62.gif" width="6" height="6" ></td>
</tr>
</table>
</body>
</html>
| 100gd-compare | trunk/WebContent/login/frame/down.jsp | Java Server Pages | epl | 896 |
<html>
<BODY
<table>
<tr>
<td> </td>
</tr>
</table>
</BODY>
</html>
| 100gd-compare | trunk/WebContent/login/common/body.jsp | Java Server Pages | epl | 83 |
<%@ include file="/login/common/taglibs.jsp" %>
<%@ include file="/login/common/common_login_check.jsp" %> | 100gd-compare | trunk/WebContent/login/common/common_taglibs.jsp | Java Server Pages | epl | 107 |
<%@ include file="/common/taglib.jsp" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="bean" uri="http://jakarta.apache.org/struts/tags-bean"%>
<%@ taglib prefix="html" uri="http://jakarta.apache.org/struts/tags-html"%>
<%@ taglib prefix="logic" uri="http://jakarta.apache.org/struts/tags-logic"%>
<%@ taglib prefix="tiles" uri="http://jakarta.apache.org/struts/tags-tiles"%>
<%@ taglib prefix="role" uri="/WEB-INF/classes/com/busi/system/role.tld"%>
| 100gd-compare | trunk/WebContent/login/common/taglibs.jsp | Java Server Pages | epl | 569 |
<%@ page contentType="text/html;charset=GBK"%>
<%@ include file="/login/common/meta.jsp"%>
<title></title>
<%@ include file="/login/common/fenyeqi.jsp" %>
<script src="${ctx}/common/js/jquery-1.3.2.js" type="text/javascript"></script>
<script src="${ctx}/common/js/commonJs.js" type="text/javascript"></script>
<script src="${ctx}/login/js/msgEffect/prototype.js" type="text/javascript"></script>
<script src="${ctx}/login/js/msgEffect/effects.js" type="text/javascript"></script>
<script src="${ctx}/login/js/gen_validator.js" type="text/javascript"></script>
<script src="${ctx}/components/DatePicker/WdatePicker.js" language="JavaScript" type="text/javascript" ></script>
<link rel="stylesheet" href="${ctx}/login/css/login.css" type="text/css">
<script src="${ctx}/login/js/login.js" type="text/javascript"></script>
| 100gd-compare | trunk/WebContent/login/common/head_common_element.jsp | Java Server Pages | epl | 834 |
<%@ page import="org.apache.commons.lang.StringUtils" %>
<%@ page import="com.busi.framework.base.CC" %>
<%
String strPageNo = request.getParameter("pageNo");
Integer pageNo = 1;
if(StringUtils.isNotBlank(strPageNo)){
try{
pageNo = Integer.valueOf(strPageNo);
}catch(Exception e){}
}
Integer startIndex = CC.PAGE_SIZE * (pageNo -1);
%>
| 100gd-compare | trunk/WebContent/login/common/fenyeqi.jsp | Java Server Pages | epl | 387 |
<%@page import="org.apache.commons.lang.StringUtils"%>
<%@page import="com.busi.utils.tools.NumberTools"%>
<%
Integer recordBegin;
String strPn = request.getParameter("pageNo");
if(StringUtils.isEmpty(strPn)){
recordBegin = 0;
}else{
recordBegin = (NumberTools.formatObject2IntDefaultZeroNoExp(strPn)-1)*CC.PAGE_SIZE;
}
%> | 100gd-compare | trunk/WebContent/login/common/list_common.jsp | Java Server Pages | epl | 342 |
<!-- message -->
<div class="message" id="message">
<logic:messagesPresent message="true">
<html:messages id="message" message="true">
<font color="blue"><bean:write name="message"/></font>
</html:messages>
</logic:messagesPresent>
</div>
<script language="JavaScript">
window.setTimeout("Effect.Fade('message')", 3000);
</script>
<!-- message --> | 100gd-compare | trunk/WebContent/login/common/message.jsp | Java Server Pages | epl | 362 |
<%@ page contentType="text/html;charset=GBK"%>
<%@ page import="com.busi.framework.base.CC" %>
<%
String loginId = (String)session.getAttribute(CC.LOGIN_ID);
%> | 100gd-compare | trunk/WebContent/login/common/common_login_check.jsp | Java Server Pages | epl | 172 |
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
var hexcase = 0;
var b64pad = "";
var chrsz= 8;
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }
function md5_vm_test()
{
return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}
function core_md5(x, len)
{
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for(var i = 0; i < x.length; i += 16)
{
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return Array(a, b, c, d);
}
function md5_cmn(q, a, b, x, s, t)
{
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
function core_hmac_md5(key, data)
{
var bkey = str2binl(key);
if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);
var ipad = Array(16), opad = Array(16);
for(var i = 0; i < 16; i++)
{
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
return core_md5(opad.concat(hash), 512 + 128);
}
function safe_add(x, y)
{
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
function bit_rol(num, cnt)
{
return (num << cnt) | (num >>> (32 - cnt));
}
function str2binl(str)
{
var bin = Array();
var mask = (1 << chrsz) - 1;
for(var i = 0; i < str.length * chrsz; i += chrsz)
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
return bin;
}
function binl2str(bin)
{
var str = "";
var mask = (1 << chrsz) - 1;
for(var i = 0; i < bin.length * 32; i += chrsz)
str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
return str;
}
function binl2hex(binarray)
{
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for(var i = 0; i < binarray.length * 4; i++)
{
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
}
return str;
}
function binl2b64(binarray)
{
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var str = "";
for(var i = 0; i < binarray.length * 4; i += 3)
{
var triplet = (((binarray[i>> 2] >> 8 * ( i%4)) & 0xFF) << 16)
| (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
| ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
for(var j = 0; j < 4; j++)
{
if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
}
}
return str;
}
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
var hexcase = 0;
var b64pad = "";
var chrsz= 8;
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }
function md5_vm_test()
{
return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}
function core_md5(x, len)
{
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for(var i = 0; i < x.length; i += 16)
{
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return Array(a, b, c, d);
}
function md5_cmn(q, a, b, x, s, t)
{
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
function core_hmac_md5(key, data)
{
var bkey = str2binl(key);
if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);
var ipad = Array(16), opad = Array(16);
for(var i = 0; i < 16; i++)
{
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
return core_md5(opad.concat(hash), 512 + 128);
}
function safe_add(x, y)
{
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
function bit_rol(num, cnt)
{
return (num << cnt) | (num >>> (32 - cnt));
}
function str2binl(str)
{
var bin = Array();
var mask = (1 << chrsz) - 1;
for(var i = 0; i < str.length * chrsz; i += chrsz)
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
return bin;
}
function binl2str(bin)
{
var str = "";
var mask = (1 << chrsz) - 1;
for(var i = 0; i < bin.length * 32; i += chrsz)
str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
return str;
}
function binl2hex(binarray)
{
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for(var i = 0; i < binarray.length * 4; i++)
{
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
}
return str;
}
function binl2b64(binarray)
{
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var str = "";
for(var i = 0; i < binarray.length * 4; i += 3)
{
var triplet = (((binarray[i>> 2] >> 8 * ( i%4)) & 0xFF) << 16)
| (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
| ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
for(var j = 0; j < 4; j++)
{
if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
}
}
return str;
} | 100gd-compare | trunk/WebContent/common/js/md5.js | JavaScript | epl | 14,366 |
<%@ page contentType="text/html;charset=GBK"%>
<%@ taglib prefix="oscache" uri="http://www.opensymphony.com/oscache"%> | 100gd-compare | trunk/WebContent/common/taglib.jsp | Java Server Pages | epl | 119 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is RSJ Software GmbH code.
*
* The Initial Developer of the Original Code is
* RSJ Software GmbH.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributors:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
BOOL TestAuthorization (NPP Instance,
int16 ArgC,
char *ArgN[],
char *ArgV[],
const char *MimeType); | 007slmg-ff-activex-host | ff-activex-host/ffactivex/authorize.h | C | lgpl | 2,050 |
#pragma once
// The following macros define the minimum required platform. The minimum required platform
// is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run
// your application. The macros work by enabling all features available on platform versions up to and
// including the version specified.
// Modify the following defines if you have to target a platform prior to the ones specified below.
// Refer to MSDN for the latest info on corresponding values for different platforms.
#ifndef WINVER // Specifies that the minimum required platform is Windows Vista.
#define WINVER 0x0600 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista.
#define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINDOWS // Specifies that the minimum required platform is Windows 98.
#define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later.
#endif
#ifndef _WIN32_IE // Specifies that the minimum required platform is Internet Explorer 7.0.
#define _WIN32_IE 0x0700 // Change this to the appropriate value to target other versions of IE.
#endif
| 007slmg-ff-activex-host | ff-activex-host/ffactivex/targetver.h | C | lgpl | 1,428 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include <map>
#include <vector>
#include <atlbase.h>
#include <comdef.h>
#include <npapi.h>
#include <npfunctions.h>
#include <npruntime.h>
#include "variants.h"
extern NPNetscapeFuncs NPNFuncs;
extern NPClass GenericNPObjectClass;
typedef bool (*DefaultInvoker)(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result);
struct ltnum
{
bool operator()(long n1, long n2) const
{
return n1 < n2;
}
};
struct ltstr
{
bool operator()(const char* s1, const char* s2) const
{
return strcmp(s1, s2) < 0;
}
};
bool toString(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result);
class GenericNPObject: public NPObject
{
private:
GenericNPObject(const GenericNPObject &);
bool invalid;
DefaultInvoker defInvoker;
void *defInvokerObject;
std::vector<NPVariant> numeric_mapper;
// the members of alpha mapper can be reassigned to anything the user wishes
std::map<const char *, NPVariant, ltstr> alpha_mapper;
// these cannot accept other types than they are initially defined with
std::map<const char *, NPVariant, ltstr> immutables;
public:
friend bool toString(void *, const NPVariant *, uint32_t, NPVariant *);
GenericNPObject(NPP instance);
GenericNPObject(NPP instance, bool isMethodObj);
~GenericNPObject();
void Invalidate() {invalid = true;}
void SetDefaultInvoker(DefaultInvoker di, void *context) {
defInvoker = di;
defInvokerObject = context;
}
static bool _HasMethod(NPObject *npobj, NPIdentifier name) {
return ((GenericNPObject *)npobj)->HasMethod(name);
}
static bool _Invoke(NPObject *npobj, NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result) {
return ((GenericNPObject *)npobj)->Invoke(methodName, args, argCount, result);
}
static bool _InvokeDefault(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) {
if (((GenericNPObject *)npobj)->defInvoker) {
return (((GenericNPObject *)npobj)->InvokeDefault)(args, argCount, result);
}
else {
return false;
}
}
static bool _HasProperty(NPObject *npobj, NPIdentifier name) {
return ((GenericNPObject *)npobj)->HasProperty(name);
}
static bool _GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result) {
return ((GenericNPObject *)npobj)->GetProperty(name, result);
}
static bool _SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value) {
return ((GenericNPObject *)npobj)->SetProperty(name, value);
}
static bool _RemoveProperty(NPObject *npobj, NPIdentifier name) {
return ((GenericNPObject *)npobj)->RemoveProperty(name);
}
static bool _Enumerate(NPObject *npobj, NPIdentifier **identifiers, uint32_t *identifierCount) {
return ((GenericNPObject *)npobj)->Enumerate(identifiers, identifierCount);
}
bool HasMethod(NPIdentifier name);
bool Invoke(NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result);
bool InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result);
bool HasProperty(NPIdentifier name);
bool GetProperty(NPIdentifier name, NPVariant *result);
bool SetProperty(NPIdentifier name, const NPVariant *value);
bool RemoveProperty(NPIdentifier name);
bool Enumerate(NPIdentifier **identifiers, uint32_t *identifierCount);
};
| 007slmg-ff-activex-host | ff-activex-host/ffactivex/GenericNPObject.h | C++ | lgpl | 5,100 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
class CAxHost {
private:
CAxHost(const CAxHost &);
NPP instance;
bool isValidClsID;
bool isKnown;
protected:
// The window handle to our plugin area in the browser
HWND Window;
WNDPROC OldProc;
// The class/prog id of the control
CLSID ClsID;
LPCWSTR CodeBaseUrl;
CControlEventSinkInstance *Sink;
public:
CAxHost(NPP inst);
~CAxHost();
CControlSiteInstance *Site;
PropertyList Props;
void setWindow(HWND win);
HWND getWinfow();
void UpdateRect(RECT rcPos);
bool verifyClsID(LPOLESTR oleClsID);
bool setClsID(const char *clsid);
bool setClsIDFromProgID(const char *progid);
void setCodeBaseUrl(LPCWSTR clsid);
bool hasValidClsID();
bool CreateControl(bool subscribeToEvents);
bool AddEventHandler(wchar_t *name, wchar_t *handler);
int16 HandleEvent(void *event);
NPObject *GetScriptableObject();
};
| 007slmg-ff-activex-host | ff-activex-host/ffactivex/axhost.h | C++ | lgpl | 2,570 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
#include "npapi.h"
#include <npfunctions.h>
#include <prtypes.h>
#include "targetver.h"
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit
#include <atlbase.h>
#include <atlstr.h>
#include <atlcom.h>
#include <atlctl.h>
#include <varargs.h>
#include "variants.h"
#include "common/PropertyList.h"
#include "common/PropertyBag.h"
#include "common/ItemContainer.h"
#include "common/ControlSite.h"
#include "common/ControlSiteIPFrame.h"
#include "common/ControlEventSink.h"
extern NPNetscapeFuncs NPNFuncs;
//#define NO_REGISTRY_AUTHORIZE
static const char PARAM_CLSID[] = "clsid";
static const char PARAM_PROGID[] = "progid";
static const char PARAM_DEBUG[] = "debugLevel";
static const char PARAM_LOGGER[] = "logger";
static const char PARAM_CODEBASEURL [] = "codeBaseUrl";
static const char PARAM_ONEVENT[] = "Event_";
static const char PARAM_PARAM[] = "PARAM_";
void *ffax_calloc(unsigned int size);
void ffax_free(void *ptr);
void log(NPP instance, unsigned int level, char *message, ...);
NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char *argn[], char *argv[], NPSavedData *saved);
NPError NPP_Destroy(NPP instance, NPSavedData **save);
NPError NPP_SetWindow(NPP instance, NPWindow *window);
| 007slmg-ff-activex-host | ff-activex-host/ffactivex/ffactivex.h | C | lgpl | 3,257 |
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by ffactivex.rc
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| 007slmg-ff-activex-host | ff-activex-host/ffactivex/resource.h | C | lgpl | 403 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// dllmain.cpp : Defines the entry point for the DLL application.
#include "ffactivex.h"
#include "axhost.h"
CComModule _Module;
NPNetscapeFuncs NPNFuncs;
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
// ==============================
// ! Scriptability related code !
// ==============================
//
// here the plugin is asked by Mozilla to tell if it is scriptable
// we should return a valid interface id and a pointer to
// nsScriptablePeer interface which we should have implemented
// and which should be defined in the corressponding *.xpt file
// in the bin/components folder
NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPError rv = NPERR_NO_ERROR;
if(instance == NULL)
return NPERR_GENERIC_ERROR;
CAxHost *host = (CAxHost *)instance->pdata;
if(host == NULL)
return NPERR_GENERIC_ERROR;
switch (variable) {
case NPPVpluginNameString:
*((char **)value) = "ITSTActiveX";
break;
case NPPVpluginDescriptionString:
*((char **)value) = "IT Structures ActiveX for Firefox";
break;
case NPPVpluginScriptableNPObject:
*(NPObject **)value = host->GetScriptableObject();
break;
default:
rv = NPERR_GENERIC_ERROR;
}
return rv;
}
NPError NPP_NewStream(NPP instance,
NPMIMEType type,
NPStream* stream,
NPBool seekable,
uint16* stype)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPError rv = NPERR_NO_ERROR;
return rv;
}
int32_t NPP_WriteReady (NPP instance, NPStream *stream)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
int32 rv = 0x0fffffff;
return rv;
}
int32_t NPP_Write (NPP instance, NPStream *stream, int32_t offset, int32_t len, void *buffer)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
int32 rv = len;
return rv;
}
NPError NPP_DestroyStream (NPP instance, NPStream *stream, NPError reason)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPError rv = NPERR_NO_ERROR;
return rv;
}
void NPP_StreamAsFile (NPP instance, NPStream* stream, const char* fname)
{
if(instance == NULL)
return;
}
void NPP_Print (NPP instance, NPPrint* printInfo)
{
if(instance == NULL)
return;
}
void NPP_URLNotify(NPP instance, const char* url, NPReason reason, void* notifyData)
{
if(instance == NULL)
return;
}
NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPError rv = NPERR_NO_ERROR;
return rv;
}
int16 NPP_HandleEvent(NPP instance, void* event)
{
if(instance == NULL)
return 0;
int16 rv = 0;
CAxHost *host = (CAxHost *)instance->pdata;
if (host)
rv = host->HandleEvent(event);
return rv;
}
NPError OSCALL NP_GetEntryPoints(NPPluginFuncs* pFuncs)
{
if(pFuncs == NULL)
return NPERR_INVALID_FUNCTABLE_ERROR;
if(pFuncs->size < sizeof(NPPluginFuncs))
return NPERR_INVALID_FUNCTABLE_ERROR;
pFuncs->version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR;
pFuncs->newp = NPP_New;
pFuncs->destroy = NPP_Destroy;
pFuncs->setwindow = NPP_SetWindow;
pFuncs->newstream = NPP_NewStream;
pFuncs->destroystream = NPP_DestroyStream;
pFuncs->asfile = NPP_StreamAsFile;
pFuncs->writeready = NPP_WriteReady;
pFuncs->write = NPP_Write;
pFuncs->print = NPP_Print;
pFuncs->event = NPP_HandleEvent;
pFuncs->urlnotify = NPP_URLNotify;
pFuncs->getvalue = NPP_GetValue;
pFuncs->setvalue = NPP_SetValue;
pFuncs->javaClass = NULL;
return NPERR_NO_ERROR;
}
#define MIN(x, y) ((x) < (y)) ? (x) : (y)
/*
* Initialize the plugin. Called the first time the browser comes across a
* MIME Type this plugin is registered to handle.
*/
NPError OSCALL NP_Initialize(NPNetscapeFuncs* pFuncs)
{
// _asm {int 3};
if(pFuncs == NULL)
return NPERR_INVALID_FUNCTABLE_ERROR;
#ifdef NDEF
// The following statements prevented usage of newer Mozilla sources than installed browser at runtime
if(HIBYTE(pFuncs->version) > NP_VERSION_MAJOR)
return NPERR_INCOMPATIBLE_VERSION_ERROR;
if(pFuncs->size < sizeof(NPNetscapeFuncs))
return NPERR_INVALID_FUNCTABLE_ERROR;
#endif
if (!AtlAxWinInit()) {
return NPERR_GENERIC_ERROR;
}
CoInitialize(NULL);
_pAtlModule = &_Module;
memset(&NPNFuncs, 0, sizeof(NPNetscapeFuncs));
memcpy(&NPNFuncs, pFuncs, MIN(pFuncs->size, sizeof(NPNetscapeFuncs)));
return NPERR_NO_ERROR;
}
/*
* Shutdown the plugin. Called when no more instanced of this plugin exist and
* the browser wants to unload it.
*/
NPError OSCALL NP_Shutdown(void)
{
AtlAxWinTerm();
return NPERR_NO_ERROR;
}
| 007slmg-ff-activex-host | ff-activex-host/ffactivex/dllmain.cpp | C++ | lgpl | 6,973 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include <atlbase.h>
#include <comdef.h>
#include <npapi.h>
#include <npfunctions.h>
#include <npruntime.h>
#include "variants.h"
extern NPNetscapeFuncs NPNFuncs;
extern NPClass ScriptableNPClass;
class Scriptable: public NPObject
{
private:
Scriptable(const Scriptable &);
// This method iterates all members of the current interface, looking for the member with the
// id of member_id. If not found within this interface, it will iterate all base interfaces
// recursively, until a match is found, or all the hierarchy was searched.
bool find_member(ITypeInfoPtr info, TYPEATTR *attr, DISPID member_id, unsigned int invKind) {
bool found = false;
unsigned int i = 0;
FUNCDESC *fDesc;
for (i = 0;
(i < attr->cFuncs)
&& !found;
++i) {
HRESULT hr = info->GetFuncDesc(i, &fDesc);
if ( SUCCEEDED(hr)
&& fDesc
&& (fDesc->memid == member_id)) {
if (invKind & fDesc->invkind)
found = true;
}
info->ReleaseFuncDesc(fDesc);
}
if (!found && (invKind & ~INVOKE_FUNC)) {
VARDESC *vDesc;
for (i = 0;
(i < attr->cVars)
&& !found;
++i) {
HRESULT hr = info->GetVarDesc(i, &vDesc);
if ( SUCCEEDED(hr)
&& vDesc
&& (vDesc->memid == member_id)) {
found = true;
}
info->ReleaseVarDesc(vDesc);
}
}
if (!found) {
// iterate inherited interfaces
HREFTYPE refType = NULL;
for (i = 0; (i < attr->cImplTypes) && !found; ++i) {
ITypeInfoPtr baseInfo;
TYPEATTR *baseAttr;
if (FAILED(info->GetRefTypeOfImplType(0, &refType))) {
continue;
}
if (FAILED(info->GetRefTypeInfo(refType, &baseInfo))) {
continue;
}
if (FAILED(baseInfo->GetTypeAttr(&baseAttr))) {
continue;
}
found = find_member(baseInfo, baseAttr, member_id, invKind);
baseInfo->ReleaseTypeAttr(baseAttr);
}
}
return found;
}
DISPID ResolveName(NPIdentifier name, unsigned int invKind) {
bool found = false;
DISPID dID = -1;
USES_CONVERSION;
if (!name || !invKind) {
return -1;
}
if (!NPNFuncs.identifierisstring(name)) {
return -1;
}
NPUTF8 *npname = NPNFuncs.utf8fromidentifier(name);
LPOLESTR oleName = A2W(npname);
IDispatchPtr disp = control.GetInterfacePtr();
if (!disp) {
return -1;
}
disp->GetIDsOfNames(IID_NULL, &oleName, 1, LOCALE_SYSTEM_DEFAULT, &dID);
if (dID != -1) {
ITypeInfoPtr info;
disp->GetTypeInfo(0, LOCALE_SYSTEM_DEFAULT, &info);
if (!info) {
return -1;
}
TYPEATTR *attr;
if (FAILED(info->GetTypeAttr(&attr))) {
return -1;
}
found = find_member(info, attr, dID, invKind);
info->ReleaseTypeAttr(attr);
}
return found ? dID : -1;
}
bool InvokeControl(DISPID id, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult) {
IDispatchPtr disp = control.GetInterfacePtr();
if (!disp) {
return false;
}
HRESULT hr = disp->Invoke(id, IID_NULL, LOCALE_SYSTEM_DEFAULT, wFlags, pDispParams, pVarResult, NULL, NULL);
return (SUCCEEDED(hr)) ? true : false;
}
IUnknownPtr control;
NPP instance;
bool invalid;
public:
Scriptable():
invalid(false),
control(NULL),
instance(NULL) {
}
~Scriptable() {control->Release();}
void setControl(IUnknown *unk) {control = unk;}
void setControl(IDispatch *disp) {disp->QueryInterface(IID_IUnknown, (void **)&control);}
void setInstance(NPP inst) {instance = inst;}
void Invalidate() {invalid = true;}
static bool _HasMethod(NPObject *npobj, NPIdentifier name) {
return ((Scriptable *)npobj)->HasMethod(name);
}
static bool _Invoke(NPObject *npobj, NPIdentifier name,
const NPVariant *args, uint32_t argCount,
NPVariant *result) {
return ((Scriptable *)npobj)->Invoke(name, args, argCount, result);
}
static bool _HasProperty(NPObject *npobj, NPIdentifier name) {
return ((Scriptable *)npobj)->HasProperty(name);
}
static bool _GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result) {
return ((Scriptable *)npobj)->GetProperty(name, result);
}
static bool _SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value) {
return ((Scriptable *)npobj)->SetProperty(name, value);
}
bool HasMethod(NPIdentifier name) {
if (invalid) return false;
DISPID id = ResolveName(name, INVOKE_FUNC);
return (id != -1) ? true : false;
}
bool Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) {
if (invalid) return false;
DISPID id = ResolveName(name, INVOKE_FUNC);
if (-1 == id) {
return false;
}
VARIANT *vArgs = NULL;
if (argCount) {
vArgs = new VARIANT[argCount];
if (!vArgs) {
return false;
}
for (unsigned int i = 0; i < argCount; ++i) {
// copy the arguments in reverse order
NPVar2Variant(&args[i], &vArgs[argCount - i - 1], instance);
}
}
DISPPARAMS params = {NULL, NULL, 0, 0};
params.cArgs = argCount;
params.cNamedArgs = 0;
params.rgdispidNamedArgs = NULL;
params.rgvarg = vArgs;
VARIANT vResult;
bool rc = InvokeControl(id, DISPATCH_METHOD, ¶ms, &vResult);
if (vArgs) delete[] vArgs;
if (!rc) {
return false;
}
Variant2NPVar(&vResult, result, instance);
return true;
}
bool HasProperty(NPIdentifier name) {
if (invalid) return false;
DISPID id = ResolveName(name, INVOKE_PROPERTYGET | INVOKE_PROPERTYPUT);
return (id != -1) ? true : false;
}
bool GetProperty(NPIdentifier name, NPVariant *result) {
if (invalid) return false;
DISPID id = ResolveName(name, INVOKE_PROPERTYGET);
if (-1 == id) {
return false;
}
DISPPARAMS params;
params.cArgs = 0;
params.cNamedArgs = 0;
params.rgdispidNamedArgs = NULL;
params.rgvarg = NULL;
VARIANT vResult;
if (!InvokeControl(id, DISPATCH_PROPERTYGET, ¶ms, &vResult)) {
return false;
}
Variant2NPVar(&vResult, result, instance);
return true;
}
bool SetProperty(NPIdentifier name, const NPVariant *value) {
if (invalid) return false;
DISPID id = ResolveName(name, INVOKE_PROPERTYPUT);
if (-1 == id) {
return false;
}
VARIANT val;
NPVar2Variant(value, &val, instance);
DISPPARAMS params;
// Special initialization needed when using propery put.
DISPID dispidNamed = DISPID_PROPERTYPUT;
params.cNamedArgs = 1;
params.rgdispidNamedArgs = &dispidNamed;
params.cArgs = 1;
params.rgvarg = &val;
VARIANT vResult;
if (!InvokeControl(id, DISPATCH_PROPERTYPUT, ¶ms, &vResult)) {
return false;
}
return true;
}
};
| 007slmg-ff-activex-host | ff-activex-host/ffactivex/scriptable.h | C++ | lgpl | 8,523 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit
#include <atlbase.h>
#include <atlstr.h>
// TODO: reference additional headers your program requires here
| 007slmg-ff-activex-host | ff-activex-host/ffactivex/stdafx.h | C | lgpl | 2,218 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@eircom.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef PROPERTYLIST_H
#define PROPERTYLIST_H
// A simple array class for managing name/value pairs typically fed to controls
// during initialization by IPersistPropertyBag
class PropertyList
{
struct Property {
BSTR bstrName;
VARIANT vValue;
} *mProperties;
unsigned long mListSize;
unsigned long mMaxListSize;
bool EnsureMoreSpace()
{
// Ensure enough space exists to accomodate a new item
const unsigned long kGrowBy = 10;
if (!mProperties)
{
mProperties = (Property *) malloc(sizeof(Property) * kGrowBy);
if (!mProperties)
return false;
mMaxListSize = kGrowBy;
}
else if (mListSize == mMaxListSize)
{
Property *pNewProperties;
pNewProperties = (Property *) realloc(mProperties, sizeof(Property) * (mMaxListSize + kGrowBy));
if (!pNewProperties)
return false;
mProperties = pNewProperties;
mMaxListSize += kGrowBy;
}
return true;
}
public:
PropertyList() :
mProperties(NULL),
mListSize(0),
mMaxListSize(0)
{
}
~PropertyList()
{
}
void Clear()
{
if (mProperties)
{
for (unsigned long i = 0; i < mListSize; i++)
{
SysFreeString(mProperties[i].bstrName); // Safe even if NULL
VariantClear(&mProperties[i].vValue);
}
free(mProperties);
mProperties = NULL;
}
mListSize = 0;
mMaxListSize = 0;
}
unsigned long GetSize() const
{
return mListSize;
}
const BSTR GetNameOf(unsigned long nIndex) const
{
if (nIndex > mListSize)
{
return NULL;
}
return mProperties[nIndex].bstrName;
}
const VARIANT *GetValueOf(unsigned long nIndex) const
{
if (nIndex > mListSize)
{
return NULL;
}
return &mProperties[nIndex].vValue;
}
bool AddOrReplaceNamedProperty(const BSTR bstrName, const VARIANT &vValue)
{
if (!bstrName)
return false;
for (unsigned long i = 0; i < GetSize(); i++)
{
// Case insensitive
if (wcsicmp(mProperties[i].bstrName, bstrName) == 0)
{
return SUCCEEDED(
VariantCopy(&mProperties[i].vValue, const_cast<VARIANT *>(&vValue)));
}
}
return AddNamedProperty(bstrName, vValue);
}
bool AddNamedProperty(const BSTR bstrName, const VARIANT &vValue)
{
if (!bstrName || !EnsureMoreSpace())
return false;
Property *pProp = &mProperties[mListSize];
pProp->bstrName = ::SysAllocString(bstrName);
if (!pProp->bstrName)
{
return false;
}
VariantInit(&pProp->vValue);
if (FAILED(VariantCopy(&pProp->vValue, const_cast<VARIANT *>(&vValue))))
{
SysFreeString(pProp->bstrName);
return false;
}
mListSize++;
return true;
}
};
#endif | 007slmg-ff-activex-host | ff-activex-host/ffactivex/common/PropertyList.h | C++ | lgpl | 5,004 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@eircom.net>
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently,
// but are changed infrequently
#if !defined(AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED_)
#define AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
// under MSVC shut off copious warnings about debug symbol too long
#ifdef _MSC_VER
#pragma warning( disable: 4786 )
#endif
//#include "jstypes.h"
//#include "prtypes.h"
// Mozilla headers
//#include "jscompat.h"
//#include "prthread.h"
//#include "prprf.h"
//#include "nsID.h"
//#include "nsIComponentManager.h"
//#include "nsIServiceManager.h"
//#include "nsStringAPI.h"
//#include "nsCOMPtr.h"
//#include "nsComponentManagerUtils.h"
//#include "nsServiceManagerUtils.h"
//#include "nsIDocument.h"
//#include "nsIDocumentObserver.h"
//#include "nsVoidArray.h"
//#include "nsIDOMNode.h"
//#include "nsIDOMNodeList.h"
//#include "nsIDOMDocument.h"
//#include "nsIDOMDocumentType.h"
//#include "nsIDOMElement.h"
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
#define _ATL_APARTMENT_THREADED
//#define _ATL_STATIC_REGISTRY
// #define _ATL_DEBUG_INTERFACES
// ATL headers
// The ATL headers that come with the platform SDK have bad for scoping
#if _MSC_VER >= 1400
#pragma conform(forScope, push, atlhack, off)
#endif
#include <atlbase.h>
//You may derive a class from CComModule and use it if you want to override
//something, but do not change the name of _Module
extern CComModule _Module;
#include <atlcom.h>
#include <atlctl.h>
#if _MSC_VER >= 1400
#pragma conform(forScope, pop, atlhack)
#endif
#include <mshtml.h>
#include <mshtmhst.h>
#include <docobj.h>
//#include <winsock2.h>
#include <comdef.h>
#include <vector>
#include <list>
#include <string>
// New winsock2.h doesn't define this anymore
typedef long int32;
#define NS_SCRIPTABLE
#include "nscore.h"
#include "npapi.h"
//#include "npupp.h"
#include "npfunctions.h"
#include "nsID.h"
#include <npruntime.h>
#include "../variants.h"
#include "PropertyList.h"
#include "PropertyBag.h"
#include "ItemContainer.h"
#include "ControlSite.h"
#include "ControlSiteIPFrame.h"
#include "ControlEventSink.h"
extern NPNetscapeFuncs NPNFuncs;
// Turn off warnings about debug symbols for templates being too long
#pragma warning(disable : 4786)
#define TRACE_METHOD(fn) \
{ \
ATLTRACE(_T("0x%04x %s()\n"), (int) GetCurrentThreadId(), _T(#fn)); \
}
#define TRACE_METHOD_ARGS(fn, pattern, args) \
{ \
ATLTRACE(_T("0x%04x %s(") _T(pattern) _T(")\n"), (int) GetCurrentThreadId(), _T(#fn), args); \
}
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#define NS_ASSERTION(x, y)
#endif // !defined(AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED)
| 007slmg-ff-activex-host | ff-activex-host/ffactivex/common/StdAfx.h | C++ | lgpl | 5,055 |
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@eircom.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ITEMCONTAINER_H
#define ITEMCONTAINER_H
// typedef std::map<tstring, CIUnkPtr> CNamedObjectList;
// Class for managing a list of named objects.
class CItemContainer : public CComObjectRootEx<CComSingleThreadModel>,
public IOleItemContainer
{
// CNamedObjectList m_cNamedObjectList;
public:
CItemContainer();
virtual ~CItemContainer();
BEGIN_COM_MAP(CItemContainer)
COM_INTERFACE_ENTRY_IID(IID_IParseDisplayName, IOleItemContainer)
COM_INTERFACE_ENTRY_IID(IID_IOleContainer, IOleItemContainer)
COM_INTERFACE_ENTRY_IID(IID_IOleItemContainer, IOleItemContainer)
END_COM_MAP()
// IParseDisplayName implementation
virtual HRESULT STDMETHODCALLTYPE ParseDisplayName(/* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ LPOLESTR pszDisplayName, /* [out] */ ULONG __RPC_FAR *pchEaten, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmkOut);
// IOleContainer implementation
virtual HRESULT STDMETHODCALLTYPE EnumObjects(/* [in] */ DWORD grfFlags, /* [out] */ IEnumUnknown __RPC_FAR *__RPC_FAR *ppenum);
virtual HRESULT STDMETHODCALLTYPE LockContainer(/* [in] */ BOOL fLock);
// IOleItemContainer implementation
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetObject(/* [in] */ LPOLESTR pszItem, /* [in] */ DWORD dwSpeedNeeded, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetObjectStorage(/* [in] */ LPOLESTR pszItem, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvStorage);
virtual HRESULT STDMETHODCALLTYPE IsRunning(/* [in] */ LPOLESTR pszItem);
};
typedef CComObject<CItemContainer> CItemContainerInstance;
#endif | 007slmg-ff-activex-host | ff-activex-host/ffactivex/common/ItemContainer.h | C++ | lgpl | 3,631 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "StdAfx.h"
#include "PropertyBag.h"
CPropertyBag::CPropertyBag()
{
}
CPropertyBag::~CPropertyBag()
{
}
///////////////////////////////////////////////////////////////////////////////
// IPropertyBag implementation
HRESULT STDMETHODCALLTYPE CPropertyBag::Read(/* [in] */ LPCOLESTR pszPropName, /* [out][in] */ VARIANT __RPC_FAR *pVar, /* [in] */ IErrorLog __RPC_FAR *pErrorLog)
{
if (pszPropName == NULL)
{
return E_INVALIDARG;
}
if (pVar == NULL)
{
return E_INVALIDARG;
}
VARTYPE vt = pVar->vt;
VariantInit(pVar);
for (unsigned long i = 0; i < m_PropertyList.GetSize(); i++)
{
if (wcsicmp(m_PropertyList.GetNameOf(i), pszPropName) == 0)
{
const VARIANT *pvSrc = m_PropertyList.GetValueOf(i);
if (!pvSrc)
{
return E_FAIL;
}
CComVariant vNew;
HRESULT hr = (vt == VT_EMPTY) ?
vNew.Copy(pvSrc) : vNew.ChangeType(vt, pvSrc);
if (FAILED(hr))
{
return E_FAIL;
}
// Copy the new value
vNew.Detach(pVar);
return S_OK;
}
}
// Property does not exist in the bag
return E_FAIL;
}
HRESULT STDMETHODCALLTYPE CPropertyBag::Write(/* [in] */ LPCOLESTR pszPropName, /* [in] */ VARIANT __RPC_FAR *pVar)
{
if (pszPropName == NULL)
{
return E_INVALIDARG;
}
if (pVar == NULL)
{
return E_INVALIDARG;
}
CComBSTR bstrName(pszPropName);
m_PropertyList.AddOrReplaceNamedProperty(bstrName, *pVar);
return S_OK;
}
| 007slmg-ff-activex-host | ff-activex-host/ffactivex/common/PropertyBag.cpp | C++ | lgpl | 3,426 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@netscape.com>
* Brent Booker
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "StdAfx.h"
#include <Objsafe.h>
#include "ControlSite.h"
#include "PropertyBag.h"
#include "ControlSiteIPFrame.h"
class CDefaultControlSiteSecurityPolicy : public CControlSiteSecurityPolicy
{
// Test if the specified class id implements the specified category
BOOL ClassImplementsCategory(const CLSID & clsid, const CATID &catid, BOOL &bClassExists);
public:
// Test if the class is safe to host
virtual BOOL IsClassSafeToHost(const CLSID & clsid);
// Test if the specified class is marked safe for scripting
virtual BOOL IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists);
// Test if the instantiated object is safe for scripting on the specified interface
virtual BOOL IsObjectSafeForScripting(IUnknown *pObject, const IID &iid);
};
BOOL
CDefaultControlSiteSecurityPolicy::ClassImplementsCategory(const CLSID &clsid, const CATID &catid, BOOL &bClassExists)
{
bClassExists = FALSE;
// Test if there is a CLSID entry. If there isn't then obviously
// the object doesn't exist and therefore doesn't implement any category.
// In this situation, the function returns REGDB_E_CLASSNOTREG.
CRegKey key;
if (key.Open(HKEY_CLASSES_ROOT, _T("CLSID"), KEY_READ) != ERROR_SUCCESS)
{
// Must fail if we can't even open this!
return FALSE;
}
LPOLESTR szCLSID = NULL;
if (FAILED(StringFromCLSID(clsid, &szCLSID)))
{
return FALSE;
}
USES_CONVERSION;
CRegKey keyCLSID;
LONG lResult = keyCLSID.Open(key, W2CT(szCLSID), KEY_READ);
CoTaskMemFree(szCLSID);
if (lResult != ERROR_SUCCESS)
{
// Class doesn't exist
return FALSE;
}
keyCLSID.Close();
// CLSID exists, so try checking what categories it implements
bClassExists = TRUE;
CComQIPtr<ICatInformation> spCatInfo;
HRESULT hr = CoCreateInstance(CLSID_StdComponentCategoriesMgr, NULL, CLSCTX_INPROC_SERVER, IID_ICatInformation, (LPVOID*) &spCatInfo);
if (spCatInfo == NULL)
{
// Must fail if we can't open the category manager
return FALSE;
}
// See what categories the class implements
CComQIPtr<IEnumCATID> spEnumCATID;
if (FAILED(spCatInfo->EnumImplCategoriesOfClass(clsid, &spEnumCATID)))
{
// Can't enumerate classes in category so fail
return FALSE;
}
// Search for matching categories
BOOL bFound = FALSE;
CATID catidNext = GUID_NULL;
while (spEnumCATID->Next(1, &catidNext, NULL) == S_OK)
{
if (::IsEqualCATID(catid, catidNext))
{
return TRUE;
}
}
return FALSE;
}
// Test if the class is safe to host
BOOL CDefaultControlSiteSecurityPolicy::IsClassSafeToHost(const CLSID & clsid)
{
return TRUE;
}
// Test if the specified class is marked safe for scripting
BOOL CDefaultControlSiteSecurityPolicy::IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists)
{
// Test the category the object belongs to
return ClassImplementsCategory(clsid, CATID_SafeForScripting, bClassExists);
}
// Test if the instantiated object is safe for scripting on the specified interface
BOOL CDefaultControlSiteSecurityPolicy::IsObjectSafeForScripting(IUnknown *pObject, const IID &iid)
{
if (!pObject) {
return FALSE;
}
// Ask the control if its safe for scripting
CComQIPtr<IObjectSafety> spObjectSafety = pObject;
if (!spObjectSafety)
{
return FALSE;
}
DWORD dwSupported = 0; // Supported options (mask)
DWORD dwEnabled = 0; // Enabled options
// Assume scripting via IDispatch
if (FAILED(spObjectSafety->GetInterfaceSafetyOptions(
iid, &dwSupported, &dwEnabled)))
{
// Interface is not safe or failure.
return FALSE;
}
// Test if safe for scripting
if (!(dwEnabled & dwSupported) & INTERFACESAFE_FOR_UNTRUSTED_CALLER)
{
// Object says it is not set to be safe, but supports unsafe calling,
// try enabling it and asking again.
if(!(dwSupported & INTERFACESAFE_FOR_UNTRUSTED_CALLER) ||
FAILED(spObjectSafety->SetInterfaceSafetyOptions(
iid, INTERFACESAFE_FOR_UNTRUSTED_CALLER, INTERFACESAFE_FOR_UNTRUSTED_CALLER)) ||
FAILED(spObjectSafety->GetInterfaceSafetyOptions(
iid, &dwSupported, &dwEnabled)) ||
!(dwEnabled & dwSupported) & INTERFACESAFE_FOR_UNTRUSTED_CALLER)
{
return FALSE;
}
}
return TRUE;
}
///////////////////////////////////////////////////////////////////////////////
// Constructor
CControlSite::CControlSite()
{
TRACE_METHOD(CControlSite::CControlSite);
m_hWndParent = NULL;
m_CLSID = CLSID_NULL;
m_bSetClientSiteFirst = FALSE;
m_bVisibleAtRuntime = TRUE;
memset(&m_rcObjectPos, 0, sizeof(m_rcObjectPos));
m_bInPlaceActive = FALSE;
m_bUIActive = FALSE;
m_bInPlaceLocked = FALSE;
m_bWindowless = FALSE;
m_bSupportWindowlessActivation = TRUE;
m_bSafeForScriptingObjectsOnly = FALSE;
m_pSecurityPolicy = GetDefaultControlSecurityPolicy();
// Initialise ambient properties
m_nAmbientLocale = 0;
m_clrAmbientForeColor = ::GetSysColor(COLOR_WINDOWTEXT);
m_clrAmbientBackColor = ::GetSysColor(COLOR_WINDOW);
m_bAmbientUserMode = true;
m_bAmbientShowHatching = true;
m_bAmbientShowGrabHandles = true;
m_bAmbientAppearance = true; // 3d
// Windowless variables
m_hDCBuffer = NULL;
m_hRgnBuffer = NULL;
m_hBMBufferOld = NULL;
m_hBMBuffer = NULL;
}
// Destructor
CControlSite::~CControlSite()
{
TRACE_METHOD(CControlSite::~CControlSite);
Detach();
}
// Create the specified control, optionally providing properties to initialise
// it with and a name.
HRESULT CControlSite::Create(REFCLSID clsid, PropertyList &pl,
LPCWSTR szCodebase, IBindCtx *pBindContext)
{
TRACE_METHOD(CControlSite::Create);
m_CLSID = clsid;
m_ParameterList = pl;
// See if security policy will allow the control to be hosted
if (m_pSecurityPolicy && !m_pSecurityPolicy->IsClassSafeToHost(clsid))
{
return E_FAIL;
}
// See if object is script safe
BOOL checkForObjectSafety = FALSE;
if (m_pSecurityPolicy && m_bSafeForScriptingObjectsOnly)
{
BOOL bClassExists = FALSE;
BOOL bIsSafe = m_pSecurityPolicy->IsClassMarkedSafeForScripting(clsid, bClassExists);
if (!bClassExists && szCodebase)
{
// Class doesn't exist, so allow code below to fetch it
}
else if (!bIsSafe)
{
// The class is not flagged as safe for scripting, so
// we'll have to create it to ask it if its safe.
checkForObjectSafety = TRUE;
}
}
//Now Check if the control version needs to be updated.
BOOL bUpdateControlVersion = FALSE;
wchar_t *szURL = NULL;
DWORD dwFileVersionMS = 0xffffffff;
DWORD dwFileVersionLS = 0xffffffff;
if(szCodebase)
{
HKEY hk = NULL;
wchar_t wszKey[60] = L"";
wchar_t wszData[MAX_PATH];
LPWSTR pwszClsid = NULL;
DWORD dwSize = 255;
DWORD dwHandle, dwLength, dwRegReturn;
DWORD dwExistingFileVerMS = 0xffffffff;
DWORD dwExistingFileVerLS = 0xffffffff;
BOOL bFoundLocalVerInfo = FALSE;
StringFromCLSID(clsid, (LPOLESTR*)&pwszClsid);
swprintf(wszKey, L"%s%s%s\0", L"CLSID\\", pwszClsid, L"\\InprocServer32");
if ( RegOpenKeyExW( HKEY_CLASSES_ROOT, wszKey, 0, KEY_READ, &hk ) == ERROR_SUCCESS )
{
dwRegReturn = RegQueryValueExW( hk, L"", NULL, NULL, (LPBYTE)wszData, &dwSize );
RegCloseKey( hk );
}
if(dwRegReturn == ERROR_SUCCESS)
{
VS_FIXEDFILEINFO *pFileInfo;
UINT uLen;
dwLength = GetFileVersionInfoSizeW( wszData , &dwHandle );
LPBYTE lpData = new BYTE[dwLength];
GetFileVersionInfoW(wszData, 0, dwLength, lpData );
bFoundLocalVerInfo = VerQueryValueW( lpData, L"\\", (LPVOID*)&pFileInfo, &uLen );
if(bFoundLocalVerInfo)
{
dwExistingFileVerMS = pFileInfo->dwFileVersionMS;
dwExistingFileVerLS = pFileInfo->dwFileVersionLS;
}
delete [] lpData;
}
// Test if the code base ends in #version=a,b,c,d
const wchar_t *szHash = wcsrchr(szCodebase, wchar_t('#'));
if (szHash)
{
if (wcsnicmp(szHash, L"#version=", 9) == 0)
{
int a, b, c, d;
if (swscanf(szHash + 9, L"%d,%d,%d,%d", &a, &b, &c, &d) == 4)
{
dwFileVersionMS = MAKELONG(b,a);
dwFileVersionLS = MAKELONG(d,c);
//If local version info was found compare it
if(bFoundLocalVerInfo)
{
if(dwFileVersionMS > dwExistingFileVerMS)
bUpdateControlVersion = TRUE;
if((dwFileVersionMS == dwExistingFileVerMS) && (dwFileVersionLS > dwExistingFileVerLS))
bUpdateControlVersion = TRUE;
}
}
}
szURL = _wcsdup(szCodebase);
// Terminate at the hash mark
if (szURL)
szURL[szHash - szCodebase] = wchar_t('\0');
}
else
{
szURL = _wcsdup(szCodebase);
}
}
CComPtr<IUnknown> spObject;
HRESULT hr;
//If the control needs to be updated do not call CoCreateInstance otherwise you will lock files
//and force a reboot on CoGetClassObjectFromURL
if(!bUpdateControlVersion)
{
// Create the object
hr = CoCreateInstance(clsid, NULL, CLSCTX_ALL, IID_IUnknown, (void **) &spObject);
if (SUCCEEDED(hr) && checkForObjectSafety)
{
// Assume scripting via IDispatch
if (!m_pSecurityPolicy->IsObjectSafeForScripting(spObject, __uuidof(IDispatch)))
{
return E_FAIL;
}
// Drop through, success!
}
}
// Do we need to download the control?
if ((FAILED(hr) && szCodebase) || (bUpdateControlVersion))
{
if (!szURL)
return E_OUTOFMEMORY;
CComPtr<IBindCtx> spBindContext;
CComPtr<IBindStatusCallback> spBindStatusCallback;
CComPtr<IBindStatusCallback> spOldBSC;
// Create our own bind context or use the one provided?
BOOL useInternalBSC = FALSE;
if (!pBindContext)
{
useInternalBSC = TRUE;
hr = CreateBindCtx(0, &spBindContext);
if (FAILED(hr))
{
free(szURL);
return hr;
}
spBindStatusCallback = dynamic_cast<IBindStatusCallback *>(this);
hr = RegisterBindStatusCallback(spBindContext, spBindStatusCallback, &spOldBSC, 0);
if (FAILED(hr))
{
free(szURL);
return hr;
}
}
else
{
spBindContext = pBindContext;
}
//If the version from the CODEBASE value is greater than the installed control
//Call CoGetClassObjectFromURL with CLSID_NULL to prevent system change reboot prompt
if(bUpdateControlVersion)
{
hr = CoGetClassObjectFromURL(CLSID_NULL, szCodebase, dwFileVersionMS, dwFileVersionLS,
NULL, spBindContext,
CLSCTX_INPROC_HANDLER | CLSCTX_INPROC_SERVER,
0, IID_IClassFactory, NULL);
}
else
{
hr = CoGetClassObjectFromURL(clsid, szURL, dwFileVersionMS, dwFileVersionLS,
NULL, spBindContext, CLSCTX_ALL, NULL, IID_IUnknown,
NULL);
}
free(szURL);
// Handle the internal binding synchronously so the object exists
// or an error code is available when the method returns.
if (useInternalBSC)
{
if (MK_S_ASYNCHRONOUS == hr)
{
m_bBindingInProgress = TRUE;
m_hrBindResult = E_FAIL;
// Spin around waiting for binding to complete
HANDLE hFakeEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL);
while (m_bBindingInProgress)
{
MSG msg;
// Process pending messages
while (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
{
if (!::GetMessage(&msg, NULL, 0, 0))
{
m_bBindingInProgress = FALSE;
break;
}
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
if (!m_bBindingInProgress)
break;
// Sleep for a bit or the next msg to appear
::MsgWaitForMultipleObjects(1, &hFakeEvent, FALSE, 500, QS_ALLEVENTS);
}
::CloseHandle(hFakeEvent);
// Set the result
hr = m_hrBindResult;
}
// Destroy the bind status callback & context
if (spBindStatusCallback)
{
RevokeBindStatusCallback(spBindContext, spBindStatusCallback);
spBindStatusCallback.Release();
spBindContext.Release();
}
}
//added to create control
if (SUCCEEDED(hr))
{
// Create the object
hr = CoCreateInstance(clsid, NULL, CLSCTX_ALL, IID_IUnknown, (void **) &spObject);
if (SUCCEEDED(hr) && checkForObjectSafety)
{
// Assume scripting via IDispatch
if (!m_pSecurityPolicy->IsObjectSafeForScripting(spObject, __uuidof(IDispatch)))
{
hr = E_FAIL;
}
}
}
//EOF test code
}
if (spObject)
{
m_spObject = spObject;
}
return hr;
}
// Attach the created control to a window and activate it
HRESULT CControlSite::Attach(HWND hwndParent, const RECT &rcPos, IUnknown *pInitStream)
{
TRACE_METHOD(CControlSite::Attach);
if (hwndParent == NULL)
{
NS_ASSERTION(0, "No parent hwnd");
return E_INVALIDARG;
}
m_hWndParent = hwndParent;
m_rcObjectPos = rcPos;
// Object must have been created
if (m_spObject == NULL)
{
return E_UNEXPECTED;
}
m_spIViewObject = m_spObject;
m_spIOleObject = m_spObject;
if (m_spIOleObject == NULL)
{
return E_FAIL;
}
DWORD dwMiscStatus;
m_spIOleObject->GetMiscStatus(DVASPECT_CONTENT, &dwMiscStatus);
if (dwMiscStatus & OLEMISC_SETCLIENTSITEFIRST)
{
m_bSetClientSiteFirst = TRUE;
}
if (dwMiscStatus & OLEMISC_INVISIBLEATRUNTIME)
{
m_bVisibleAtRuntime = FALSE;
}
// Some objects like to have the client site as the first thing
// to be initialised (for ambient properties and so forth)
if (m_bSetClientSiteFirst)
{
m_spIOleObject->SetClientSite(this);
}
// If there is a parameter list for the object and no init stream then
// create one here.
CPropertyBagInstance *pPropertyBag = NULL;
if (pInitStream == NULL && m_ParameterList.GetSize() > 0)
{
CPropertyBagInstance::CreateInstance(&pPropertyBag);
pPropertyBag->AddRef();
for (unsigned long i = 0; i < m_ParameterList.GetSize(); i++)
{
pPropertyBag->Write(m_ParameterList.GetNameOf(i),
const_cast<VARIANT *>(m_ParameterList.GetValueOf(i)));
}
pInitStream = (IPersistPropertyBag *) pPropertyBag;
}
// Initialise the control from store if one is provided
if (pInitStream)
{
CComQIPtr<IPropertyBag, &IID_IPropertyBag> spPropertyBag = pInitStream;
CComQIPtr<IStream, &IID_IStream> spStream = pInitStream;
CComQIPtr<IPersistStream, &IID_IPersistStream> spIPersistStream = m_spIOleObject;
CComQIPtr<IPersistPropertyBag, &IID_IPersistPropertyBag> spIPersistPropertyBag = m_spIOleObject;
if (spIPersistPropertyBag && spPropertyBag)
{
spIPersistPropertyBag->Load(spPropertyBag, NULL);
}
else if (spIPersistStream && spStream)
{
spIPersistStream->Load(spStream);
}
}
else
{
// Initialise the object if possible
CComQIPtr<IPersistStreamInit, &IID_IPersistStreamInit> spIPersistStreamInit = m_spIOleObject;
if (spIPersistStreamInit)
{
spIPersistStreamInit->InitNew();
}
}
m_spIOleInPlaceObject = m_spObject;
m_spIOleInPlaceObjectWindowless = m_spObject;
if (m_spIOleInPlaceObject)
{
SetPosition(m_rcObjectPos);
}
// In-place activate the object
if (m_bVisibleAtRuntime)
{
DoVerb(OLEIVERB_INPLACEACTIVATE);
}
// For those objects which haven't had their client site set yet,
// it's done here.
if (!m_bSetClientSiteFirst)
{
m_spIOleObject->SetClientSite(this);
}
return S_OK;
}
// Unhook the control from the window and throw it all away
HRESULT CControlSite::Detach()
{
TRACE_METHOD(CControlSite::Detach);
if (m_spIOleInPlaceObjectWindowless)
{
m_spIOleInPlaceObjectWindowless.Release();
}
if (m_spIOleInPlaceObject)
{
m_spIOleInPlaceObject->InPlaceDeactivate();
m_spIOleInPlaceObject.Release();
}
if (m_spIOleObject)
{
m_spIOleObject->Close(OLECLOSE_NOSAVE);
m_spIOleObject->SetClientSite(NULL);
m_spIOleObject.Release();
}
m_spIViewObject.Release();
m_spObject.Release();
return S_OK;
}
// Return the IUnknown of the contained control
HRESULT CControlSite::GetControlUnknown(IUnknown **ppObject)
{
*ppObject = NULL;
if (m_spObject)
{
m_spObject->QueryInterface(IID_IUnknown, (void **) ppObject);
}
return S_OK;
}
// Subscribe to an event sink on the control
HRESULT CControlSite::Advise(IUnknown *pIUnkSink, const IID &iid, DWORD *pdwCookie)
{
if (m_spObject == NULL)
{
return E_UNEXPECTED;
}
if (pIUnkSink == NULL || pdwCookie == NULL)
{
return E_INVALIDARG;
}
return AtlAdvise(m_spObject, pIUnkSink, iid, pdwCookie);
}
// Unsubscribe event sink from the control
HRESULT CControlSite::Unadvise(const IID &iid, DWORD dwCookie)
{
if (m_spObject == NULL)
{
return E_UNEXPECTED;
}
return AtlUnadvise(m_spObject, iid, dwCookie);
}
// Draw the control
HRESULT CControlSite::Draw(HDC hdc)
{
TRACE_METHOD(CControlSite::Draw);
// Draw only when control is windowless or deactivated
if (m_spIViewObject)
{
if (m_bWindowless || !m_bInPlaceActive)
{
RECTL *prcBounds = (m_bWindowless) ? NULL : (RECTL *) &m_rcObjectPos;
m_spIViewObject->Draw(DVASPECT_CONTENT, -1, NULL, NULL, NULL, hdc, prcBounds, NULL, NULL, 0);
}
}
else
{
// Draw something to indicate no control is there
HBRUSH hbr = CreateSolidBrush(RGB(200,200,200));
FillRect(hdc, &m_rcObjectPos, hbr);
DeleteObject(hbr);
}
return S_OK;
}
// Execute the specified verb
HRESULT CControlSite::DoVerb(LONG nVerb, LPMSG lpMsg)
{
TRACE_METHOD(CControlSite::DoVerb);
if (m_spIOleObject == NULL)
{
return E_FAIL;
}
return m_spIOleObject->DoVerb(nVerb, lpMsg, this, 0, m_hWndParent, &m_rcObjectPos);
}
// Set the position on the control
HRESULT CControlSite::SetPosition(const RECT &rcPos)
{
HWND hwnd;
TRACE_METHOD(CControlSite::SetPosition);
m_rcObjectPos = rcPos;
if (m_spIOleInPlaceObject && SUCCEEDED(m_spIOleInPlaceObject->GetWindow(&hwnd)))
{
m_spIOleInPlaceObject->SetObjectRects(&m_rcObjectPos, &m_rcObjectPos);
}
return S_OK;
}
void CControlSite::FireAmbientPropertyChange(DISPID id)
{
if (m_spObject)
{
CComQIPtr<IOleControl> spControl = m_spObject;
if (spControl)
{
spControl->OnAmbientPropertyChange(id);
}
}
}
void CControlSite::SetAmbientUserMode(BOOL bUserMode)
{
bool bNewMode = bUserMode ? true : false;
if (m_bAmbientUserMode != bNewMode)
{
m_bAmbientUserMode = bNewMode;
FireAmbientPropertyChange(DISPID_AMBIENT_USERMODE);
}
}
///////////////////////////////////////////////////////////////////////////////
// CControlSiteSecurityPolicy implementation
CControlSiteSecurityPolicy *CControlSite::GetDefaultControlSecurityPolicy()
{
static CDefaultControlSiteSecurityPolicy defaultControlSecurityPolicy;
return &defaultControlSecurityPolicy;
}
// Test if the class is safe to host
BOOL CControlSite::IsClassSafeToHost(const CLSID & clsid)
{
if (m_pSecurityPolicy)
return m_pSecurityPolicy->IsClassSafeToHost(clsid);
return TRUE;
}
// Test if the specified class is marked safe for scripting
BOOL CControlSite::IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists)
{
if (m_pSecurityPolicy)
return m_pSecurityPolicy->IsClassMarkedSafeForScripting(clsid, bClassExists);
return TRUE;
}
// Test if the instantiated object is safe for scripting on the specified interface
BOOL CControlSite::IsObjectSafeForScripting(IUnknown *pObject, const IID &iid)
{
if (m_pSecurityPolicy)
return m_pSecurityPolicy->IsObjectSafeForScripting(pObject, iid);
return TRUE;
}
BOOL CControlSite::IsObjectSafeForScripting(const IID &iid)
{
return IsObjectSafeForScripting(m_spObject, iid);
}
///////////////////////////////////////////////////////////////////////////////
// IServiceProvider implementation
HRESULT STDMETHODCALLTYPE CControlSite::QueryService(REFGUID guidService, REFIID riid, void** ppv)
{
if (m_spServiceProvider)
return m_spServiceProvider->QueryService(guidService, riid, ppv);
return E_NOINTERFACE;
}
///////////////////////////////////////////////////////////////////////////////
// IDispatch implementation
HRESULT STDMETHODCALLTYPE CControlSite::GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr)
{
if (wFlags & DISPATCH_PROPERTYGET)
{
CComVariant vResult;
switch (dispIdMember)
{
case DISPID_AMBIENT_APPEARANCE:
vResult = CComVariant(m_bAmbientAppearance);
break;
case DISPID_AMBIENT_FORECOLOR:
vResult = CComVariant((long) m_clrAmbientForeColor);
break;
case DISPID_AMBIENT_BACKCOLOR:
vResult = CComVariant((long) m_clrAmbientBackColor);
break;
case DISPID_AMBIENT_LOCALEID:
vResult = CComVariant((long) m_nAmbientLocale);
break;
case DISPID_AMBIENT_USERMODE:
vResult = CComVariant(m_bAmbientUserMode);
break;
case DISPID_AMBIENT_SHOWGRABHANDLES:
vResult = CComVariant(m_bAmbientShowGrabHandles);
break;
case DISPID_AMBIENT_SHOWHATCHING:
vResult = CComVariant(m_bAmbientShowHatching);
break;
default:
return DISP_E_MEMBERNOTFOUND;
}
VariantCopy(pVarResult, &vResult);
return S_OK;
}
return E_FAIL;
}
///////////////////////////////////////////////////////////////////////////////
// IAdviseSink implementation
void STDMETHODCALLTYPE CControlSite::OnDataChange(/* [unique][in] */ FORMATETC __RPC_FAR *pFormatetc, /* [unique][in] */ STGMEDIUM __RPC_FAR *pStgmed)
{
}
void STDMETHODCALLTYPE CControlSite::OnViewChange(/* [in] */ DWORD dwAspect, /* [in] */ LONG lindex)
{
// Redraw the control
InvalidateRect(NULL, FALSE);
}
void STDMETHODCALLTYPE CControlSite::OnRename(/* [in] */ IMoniker __RPC_FAR *pmk)
{
}
void STDMETHODCALLTYPE CControlSite::OnSave(void)
{
}
void STDMETHODCALLTYPE CControlSite::OnClose(void)
{
}
///////////////////////////////////////////////////////////////////////////////
// IAdviseSink2 implementation
void STDMETHODCALLTYPE CControlSite::OnLinkSrcChange(/* [unique][in] */ IMoniker __RPC_FAR *pmk)
{
}
///////////////////////////////////////////////////////////////////////////////
// IAdviseSinkEx implementation
void STDMETHODCALLTYPE CControlSite::OnViewStatusChange(/* [in] */ DWORD dwViewStatus)
{
}
///////////////////////////////////////////////////////////////////////////////
// IOleWindow implementation
HRESULT STDMETHODCALLTYPE CControlSite::GetWindow(/* [out] */ HWND __RPC_FAR *phwnd)
{
*phwnd = m_hWndParent;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::ContextSensitiveHelp(/* [in] */ BOOL fEnterMode)
{
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
// IOleClientSite implementation
HRESULT STDMETHODCALLTYPE CControlSite::SaveObject(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetMoniker(/* [in] */ DWORD dwAssign, /* [in] */ DWORD dwWhichMoniker, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmk)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetContainer(/* [out] */ IOleContainer __RPC_FAR *__RPC_FAR *ppContainer)
{
if (!ppContainer) return E_INVALIDARG;
*ppContainer = m_spContainer;
if (*ppContainer)
{
(*ppContainer)->AddRef();
}
return (*ppContainer) ? S_OK : E_NOINTERFACE;
}
HRESULT STDMETHODCALLTYPE CControlSite::ShowObject(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnShowWindow(/* [in] */ BOOL fShow)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::RequestNewObjectLayout(void)
{
return E_NOTIMPL;
}
///////////////////////////////////////////////////////////////////////////////
// IOleInPlaceSite implementation
HRESULT STDMETHODCALLTYPE CControlSite::CanInPlaceActivate(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceActivate(void)
{
m_bInPlaceActive = TRUE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnUIActivate(void)
{
m_bUIActive = TRUE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetWindowContext(/* [out] */ IOleInPlaceFrame __RPC_FAR *__RPC_FAR *ppFrame, /* [out] */ IOleInPlaceUIWindow __RPC_FAR *__RPC_FAR *ppDoc, /* [out] */ LPRECT lprcPosRect, /* [out] */ LPRECT lprcClipRect, /* [out][in] */ LPOLEINPLACEFRAMEINFO lpFrameInfo)
{
*lprcPosRect = m_rcObjectPos;
*lprcClipRect = m_rcObjectPos;
CControlSiteIPFrameInstance *pIPFrame = NULL;
CControlSiteIPFrameInstance::CreateInstance(&pIPFrame);
pIPFrame->AddRef();
*ppFrame = (IOleInPlaceFrame *) pIPFrame;
*ppDoc = NULL;
lpFrameInfo->fMDIApp = FALSE;
lpFrameInfo->hwndFrame = NULL;
lpFrameInfo->haccel = NULL;
lpFrameInfo->cAccelEntries = 0;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::Scroll(/* [in] */ SIZE scrollExtant)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnUIDeactivate(/* [in] */ BOOL fUndoable)
{
m_bUIActive = FALSE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceDeactivate(void)
{
m_bInPlaceActive = FALSE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::DiscardUndoState(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::DeactivateAndUndo(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnPosRectChange(/* [in] */ LPCRECT lprcPosRect)
{
if (lprcPosRect == NULL)
{
return E_INVALIDARG;
}
SetPosition(m_rcObjectPos);
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
// IOleInPlaceSiteEx implementation
HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceActivateEx(/* [out] */ BOOL __RPC_FAR *pfNoRedraw, /* [in] */ DWORD dwFlags)
{
m_bInPlaceActive = TRUE;
if (pfNoRedraw)
{
*pfNoRedraw = FALSE;
}
if (dwFlags & ACTIVATE_WINDOWLESS)
{
if (!m_bSupportWindowlessActivation)
{
return E_INVALIDARG;
}
m_bWindowless = TRUE;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceDeactivateEx(/* [in] */ BOOL fNoRedraw)
{
m_bInPlaceActive = FALSE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::RequestUIActivate(void)
{
return S_FALSE;
}
///////////////////////////////////////////////////////////////////////////////
// IOleInPlaceSiteWindowless implementation
HRESULT STDMETHODCALLTYPE CControlSite::CanWindowlessActivate(void)
{
// Allow windowless activation?
return (m_bSupportWindowlessActivation) ? S_OK : S_FALSE;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetCapture(void)
{
// TODO capture the mouse for the object
return S_FALSE;
}
HRESULT STDMETHODCALLTYPE CControlSite::SetCapture(/* [in] */ BOOL fCapture)
{
// TODO capture the mouse for the object
return S_FALSE;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetFocus(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::SetFocus(/* [in] */ BOOL fFocus)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetDC(/* [in] */ LPCRECT pRect, /* [in] */ DWORD grfFlags, /* [out] */ HDC __RPC_FAR *phDC)
{
if (phDC == NULL)
{
return E_INVALIDARG;
}
// Can't do nested painting
if (m_hDCBuffer != NULL)
{
return E_UNEXPECTED;
}
m_rcBuffer = m_rcObjectPos;
if (pRect != NULL)
{
m_rcBuffer = *pRect;
}
m_hBMBuffer = NULL;
m_dwBufferFlags = grfFlags;
// See if the control wants a DC that is onscreen or offscreen
if (m_dwBufferFlags & OLEDC_OFFSCREEN)
{
m_hDCBuffer = CreateCompatibleDC(NULL);
if (m_hDCBuffer == NULL)
{
// Error
return E_OUTOFMEMORY;
}
long cx = m_rcBuffer.right - m_rcBuffer.left;
long cy = m_rcBuffer.bottom - m_rcBuffer.top;
m_hBMBuffer = CreateCompatibleBitmap(m_hDCBuffer, cx, cy);
m_hBMBufferOld = (HBITMAP) SelectObject(m_hDCBuffer, m_hBMBuffer);
SetViewportOrgEx(m_hDCBuffer, m_rcBuffer.left, m_rcBuffer.top, NULL);
// TODO When OLEDC_PAINTBKGND we must draw every site behind this one
}
else
{
// TODO When OLEDC_PAINTBKGND we must draw every site behind this one
// Get the window DC
m_hDCBuffer = GetWindowDC(m_hWndParent);
if (m_hDCBuffer == NULL)
{
// Error
return E_OUTOFMEMORY;
}
// Clip the control so it can't trash anywhere it isn't allowed to draw
if (!(m_dwBufferFlags & OLEDC_NODRAW))
{
m_hRgnBuffer = CreateRectRgnIndirect(&m_rcBuffer);
// TODO Clip out opaque areas of sites behind this one
SelectClipRgn(m_hDCBuffer, m_hRgnBuffer);
}
}
*phDC = m_hDCBuffer;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::ReleaseDC(/* [in] */ HDC hDC)
{
// Release the DC
if (hDC == NULL || hDC != m_hDCBuffer)
{
return E_INVALIDARG;
}
// Test if the DC was offscreen or onscreen
if ((m_dwBufferFlags & OLEDC_OFFSCREEN) &&
!(m_dwBufferFlags & OLEDC_NODRAW))
{
// BitBlt the buffer into the control's object
SetViewportOrgEx(m_hDCBuffer, 0, 0, NULL);
HDC hdc = GetWindowDC(m_hWndParent);
long cx = m_rcBuffer.right - m_rcBuffer.left;
long cy = m_rcBuffer.bottom - m_rcBuffer.top;
BitBlt(hdc, m_rcBuffer.left, m_rcBuffer.top, cx, cy, m_hDCBuffer, 0, 0, SRCCOPY);
::ReleaseDC(m_hWndParent, hdc);
}
else
{
// TODO If OLEDC_PAINTBKGND is set draw the DVASPECT_CONTENT of every object above this one
}
// Clean up settings ready for next drawing
if (m_hRgnBuffer)
{
SelectClipRgn(m_hDCBuffer, NULL);
DeleteObject(m_hRgnBuffer);
m_hRgnBuffer = NULL;
}
SelectObject(m_hDCBuffer, m_hBMBufferOld);
if (m_hBMBuffer)
{
DeleteObject(m_hBMBuffer);
m_hBMBuffer = NULL;
}
// Delete the DC
if (m_dwBufferFlags & OLEDC_OFFSCREEN)
{
::DeleteDC(m_hDCBuffer);
}
else
{
::ReleaseDC(m_hWndParent, m_hDCBuffer);
}
m_hDCBuffer = NULL;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::InvalidateRect(/* [in] */ LPCRECT pRect, /* [in] */ BOOL fErase)
{
// Clip the rectangle against the object's size and invalidate it
RECT rcI = { 0, 0, 0, 0 };
if (pRect == NULL)
{
rcI = m_rcObjectPos;
}
else
{
IntersectRect(&rcI, &m_rcObjectPos, pRect);
}
::InvalidateRect(m_hWndParent, &rcI, fErase);
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::InvalidateRgn(/* [in] */ HRGN hRGN, /* [in] */ BOOL fErase)
{
if (hRGN == NULL)
{
::InvalidateRect(m_hWndParent, &m_rcObjectPos, fErase);
}
else
{
// Clip the region with the object's bounding area
HRGN hrgnClip = CreateRectRgnIndirect(&m_rcObjectPos);
if (CombineRgn(hrgnClip, hrgnClip, hRGN, RGN_AND) != ERROR)
{
::InvalidateRgn(m_hWndParent, hrgnClip, fErase);
}
DeleteObject(hrgnClip);
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::ScrollRect(/* [in] */ INT dx, /* [in] */ INT dy, /* [in] */ LPCRECT pRectScroll, /* [in] */ LPCRECT pRectClip)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::AdjustRect(/* [out][in] */ LPRECT prc)
{
if (prc == NULL)
{
return E_INVALIDARG;
}
// Clip the rectangle against the object position
RECT rcI = { 0, 0, 0, 0 };
IntersectRect(&rcI, &m_rcObjectPos, prc);
*prc = rcI;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnDefWindowMessage(/* [in] */ UINT msg, /* [in] */ WPARAM wParam, /* [in] */ LPARAM lParam, /* [out] */ LRESULT __RPC_FAR *plResult)
{
if (plResult == NULL)
{
return E_INVALIDARG;
}
// Pass the message to the windowless control
if (m_bWindowless && m_spIOleInPlaceObjectWindowless)
{
return m_spIOleInPlaceObjectWindowless->OnWindowMessage(msg, wParam, lParam, plResult);
}
else if (m_spIOleInPlaceObject) {
HWND wnd;
if (SUCCEEDED(m_spIOleInPlaceObject->GetWindow(&wnd)))
SendMessage(wnd, msg, wParam, lParam);
}
return S_FALSE;
}
///////////////////////////////////////////////////////////////////////////////
// IOleControlSite implementation
HRESULT STDMETHODCALLTYPE CControlSite::OnControlInfoChanged(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::LockInPlaceActive(/* [in] */ BOOL fLock)
{
m_bInPlaceLocked = fLock;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetExtendedControl(/* [out] */ IDispatch __RPC_FAR *__RPC_FAR *ppDisp)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::TransformCoords(/* [out][in] */ POINTL __RPC_FAR *pPtlHimetric, /* [out][in] */ POINTF __RPC_FAR *pPtfContainer, /* [in] */ DWORD dwFlags)
{
HRESULT hr = S_OK;
if (pPtlHimetric == NULL)
{
return E_INVALIDARG;
}
if (pPtfContainer == NULL)
{
return E_INVALIDARG;
}
HDC hdc = ::GetDC(m_hWndParent);
::SetMapMode(hdc, MM_HIMETRIC);
POINT rgptConvert[2];
rgptConvert[0].x = 0;
rgptConvert[0].y = 0;
if (dwFlags & XFORMCOORDS_HIMETRICTOCONTAINER)
{
rgptConvert[1].x = pPtlHimetric->x;
rgptConvert[1].y = pPtlHimetric->y;
::LPtoDP(hdc, rgptConvert, 2);
if (dwFlags & XFORMCOORDS_SIZE)
{
pPtfContainer->x = (float)(rgptConvert[1].x - rgptConvert[0].x);
pPtfContainer->y = (float)(rgptConvert[0].y - rgptConvert[1].y);
}
else if (dwFlags & XFORMCOORDS_POSITION)
{
pPtfContainer->x = (float)rgptConvert[1].x;
pPtfContainer->y = (float)rgptConvert[1].y;
}
else
{
hr = E_INVALIDARG;
}
}
else if (dwFlags & XFORMCOORDS_CONTAINERTOHIMETRIC)
{
rgptConvert[1].x = (int)(pPtfContainer->x);
rgptConvert[1].y = (int)(pPtfContainer->y);
::DPtoLP(hdc, rgptConvert, 2);
if (dwFlags & XFORMCOORDS_SIZE)
{
pPtlHimetric->x = rgptConvert[1].x - rgptConvert[0].x;
pPtlHimetric->y = rgptConvert[0].y - rgptConvert[1].y;
}
else if (dwFlags & XFORMCOORDS_POSITION)
{
pPtlHimetric->x = rgptConvert[1].x;
pPtlHimetric->y = rgptConvert[1].y;
}
else
{
hr = E_INVALIDARG;
}
}
else
{
hr = E_INVALIDARG;
}
::ReleaseDC(m_hWndParent, hdc);
return hr;
}
HRESULT STDMETHODCALLTYPE CControlSite::TranslateAccelerator(/* [in] */ MSG __RPC_FAR *pMsg, /* [in] */ DWORD grfModifiers)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnFocus(/* [in] */ BOOL fGotFocus)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::ShowPropertyFrame(void)
{
return E_NOTIMPL;
}
///////////////////////////////////////////////////////////////////////////////
// IBindStatusCallback implementation
HRESULT STDMETHODCALLTYPE CControlSite::OnStartBinding(DWORD dwReserved,
IBinding __RPC_FAR *pib)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetPriority(LONG __RPC_FAR *pnPriority)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnLowResource(DWORD reserved)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnProgress(ULONG ulProgress,
ULONG ulProgressMax,
ULONG ulStatusCode,
LPCWSTR szStatusText)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnStopBinding(HRESULT hresult, LPCWSTR szError)
{
m_bBindingInProgress = FALSE;
m_hrBindResult = hresult;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetBindInfo(DWORD __RPC_FAR *pgrfBINDF,
BINDINFO __RPC_FAR *pbindInfo)
{
*pgrfBINDF = BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE |
BINDF_GETNEWESTVERSION | BINDF_NOWRITECACHE;
pbindInfo->cbSize = sizeof(BINDINFO);
pbindInfo->szExtraInfo = NULL;
memset(&pbindInfo->stgmedData, 0, sizeof(STGMEDIUM));
pbindInfo->grfBindInfoF = 0;
pbindInfo->dwBindVerb = 0;
pbindInfo->szCustomVerb = NULL;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnDataAvailable(DWORD grfBSCF,
DWORD dwSize,
FORMATETC __RPC_FAR *pformatetc,
STGMEDIUM __RPC_FAR *pstgmed)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnObjectAvailable(REFIID riid,
IUnknown __RPC_FAR *punk)
{
return S_OK;
}
// IWindowForBindingUI
HRESULT STDMETHODCALLTYPE CControlSite::GetWindow(
/* [in] */ REFGUID rguidReason,
/* [out] */ HWND *phwnd)
{
*phwnd = NULL;
return S_OK;
}
| 007slmg-ff-activex-host | ff-activex-host/ffactivex/common/ControlSite.cpp | C++ | lgpl | 44,015 |
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@eircom.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef IOLECOMMANDIMPL_H
#define IOLECOMMANDIMPL_H
// Implementation of the IOleCommandTarget interface. The template is
// reasonably generic and reusable which is a good thing given how needlessly
// complicated this interface is. Blame Microsoft for that and not me.
//
// To use this class, derive your class from it like this:
//
// class CComMyClass : public IOleCommandTargetImpl<CComMyClass>
// {
// ... Ensure IOleCommandTarget is listed in the interface map ...
// BEGIN_COM_MAP(CComMyClass)
// COM_INTERFACE_ENTRY(IOleCommandTarget)
// // etc.
// END_COM_MAP()
// ... And then later on define the command target table ...
// BEGIN_OLECOMMAND_TABLE()
// OLECOMMAND_MESSAGE(OLECMDID_PRINT, NULL, ID_PRINT, L"Print", L"Print the page")
// OLECOMMAND_MESSAGE(OLECMDID_SAVEAS, NULL, 0, L"SaveAs", L"Save the page")
// OLECOMMAND_HANDLER(IDM_EDITMODE, &CGID_MSHTML, EditModeHandler, L"EditMode", L"Switch to edit mode")
// END_OLECOMMAND_TABLE()
// ... Now the window that OLECOMMAND_MESSAGE sends WM_COMMANDs to ...
// HWND GetCommandTargetWindow() const
// {
// return m_hWnd;
// }
// ... Now procedures that OLECOMMAND_HANDLER calls ...
// static HRESULT _stdcall EditModeHandler(CMozillaBrowser *pThis, const GUID *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT *pvaIn, VARIANT *pvaOut);
// }
//
// The command table defines which commands the object supports. Commands are
// defined by a command id and a command group plus a WM_COMMAND id or procedure,
// and a verb and short description.
//
// Notice that there are two macros for handling Ole Commands. The first,
// OLECOMMAND_MESSAGE sends a WM_COMMAND message to the window returned from
// GetCommandTargetWindow() (that the derived class must implement if it uses
// this macro).
//
// The second, OLECOMMAND_HANDLER calls a static handler procedure that
// conforms to the OleCommandProc typedef. The first parameter, pThis means
// the static handler has access to the methods and variables in the class
// instance.
//
// The OLECOMMAND_HANDLER macro is generally more useful when a command
// takes parameters or needs to return a result to the caller.
//
template< class T >
class IOleCommandTargetImpl : public IOleCommandTarget
{
struct OleExecData
{
const GUID *pguidCmdGroup;
DWORD nCmdID;
DWORD nCmdexecopt;
VARIANT *pvaIn;
VARIANT *pvaOut;
};
public:
typedef HRESULT (_stdcall *OleCommandProc)(T *pT, const GUID *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT *pvaIn, VARIANT *pvaOut);
struct OleCommandInfo
{
ULONG nCmdID;
const GUID *pCmdGUID;
ULONG nWindowsCmdID;
OleCommandProc pfnCommandProc;
wchar_t *szVerbText;
wchar_t *szStatusText;
};
// Query the status of the specified commands (test if is it supported etc.)
virtual HRESULT STDMETHODCALLTYPE QueryStatus(const GUID __RPC_FAR *pguidCmdGroup, ULONG cCmds, OLECMD __RPC_FAR prgCmds[], OLECMDTEXT __RPC_FAR *pCmdText)
{
T* pT = static_cast<T*>(this);
if (prgCmds == NULL)
{
return E_INVALIDARG;
}
OleCommandInfo *pCommands = pT->GetCommandTable();
ATLASSERT(pCommands);
BOOL bCmdGroupFound = FALSE;
BOOL bTextSet = FALSE;
// Iterate through list of commands and flag them as supported/unsupported
for (ULONG nCmd = 0; nCmd < cCmds; nCmd++)
{
// Unsupported by default
prgCmds[nCmd].cmdf = 0;
// Search the support command list
for (int nSupported = 0; pCommands[nSupported].pCmdGUID != &GUID_NULL; nSupported++)
{
OleCommandInfo *pCI = &pCommands[nSupported];
if (pguidCmdGroup && pCI->pCmdGUID && memcmp(pguidCmdGroup, pCI->pCmdGUID, sizeof(GUID)) == 0)
{
continue;
}
bCmdGroupFound = TRUE;
if (pCI->nCmdID != prgCmds[nCmd].cmdID)
{
continue;
}
// Command is supported so flag it and possibly enable it
prgCmds[nCmd].cmdf = OLECMDF_SUPPORTED;
if (pCI->nWindowsCmdID != 0)
{
prgCmds[nCmd].cmdf |= OLECMDF_ENABLED;
}
// Copy the status/verb text for the first supported command only
if (!bTextSet && pCmdText)
{
// See what text the caller wants
wchar_t *pszTextToCopy = NULL;
if (pCmdText->cmdtextf & OLECMDTEXTF_NAME)
{
pszTextToCopy = pCI->szVerbText;
}
else if (pCmdText->cmdtextf & OLECMDTEXTF_STATUS)
{
pszTextToCopy = pCI->szStatusText;
}
// Copy the text
pCmdText->cwActual = 0;
memset(pCmdText->rgwz, 0, pCmdText->cwBuf * sizeof(wchar_t));
if (pszTextToCopy)
{
// Don't exceed the provided buffer size
size_t nTextLen = wcslen(pszTextToCopy);
if (nTextLen > pCmdText->cwBuf)
{
nTextLen = pCmdText->cwBuf;
}
wcsncpy(pCmdText->rgwz, pszTextToCopy, nTextLen);
pCmdText->cwActual = nTextLen;
}
bTextSet = TRUE;
}
break;
}
}
// Was the command group found?
if (!bCmdGroupFound)
{
OLECMDERR_E_UNKNOWNGROUP;
}
return S_OK;
}
// Execute the specified command
virtual HRESULT STDMETHODCALLTYPE Exec(const GUID __RPC_FAR *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT __RPC_FAR *pvaIn, VARIANT __RPC_FAR *pvaOut)
{
T* pT = static_cast<T*>(this);
BOOL bCmdGroupFound = FALSE;
OleCommandInfo *pCommands = pT->GetCommandTable();
ATLASSERT(pCommands);
// Search the support command list
for (int nSupported = 0; pCommands[nSupported].pCmdGUID != &GUID_NULL; nSupported++)
{
OleCommandInfo *pCI = &pCommands[nSupported];
if (pguidCmdGroup && pCI->pCmdGUID && memcmp(pguidCmdGroup, pCI->pCmdGUID, sizeof(GUID)) == 0)
{
continue;
}
bCmdGroupFound = TRUE;
if (pCI->nCmdID != nCmdID)
{
continue;
}
// Send ourselves a WM_COMMAND windows message with the associated
// identifier and exec data
OleExecData cData;
cData.pguidCmdGroup = pguidCmdGroup;
cData.nCmdID = nCmdID;
cData.nCmdexecopt = nCmdexecopt;
cData.pvaIn = pvaIn;
cData.pvaOut = pvaOut;
if (pCI->pfnCommandProc)
{
pCI->pfnCommandProc(pT, pCI->pCmdGUID, pCI->nCmdID, nCmdexecopt, pvaIn, pvaOut);
}
else if (pCI->nWindowsCmdID != 0 && nCmdexecopt != OLECMDEXECOPT_SHOWHELP)
{
HWND hwndTarget = pT->GetCommandTargetWindow();
if (hwndTarget)
{
::SendMessage(hwndTarget, WM_COMMAND, LOWORD(pCI->nWindowsCmdID), (LPARAM) &cData);
}
}
else
{
// Command supported but not implemented
continue;
}
return S_OK;
}
// Was the command group found?
if (!bCmdGroupFound)
{
OLECMDERR_E_UNKNOWNGROUP;
}
return OLECMDERR_E_NOTSUPPORTED;
}
};
// Macros to be placed in any class derived from the IOleCommandTargetImpl
// class. These define what commands are exposed from the object.
#define BEGIN_OLECOMMAND_TABLE() \
OleCommandInfo *GetCommandTable() \
{ \
static OleCommandInfo s_aSupportedCommands[] = \
{
#define OLECOMMAND_MESSAGE(id, group, cmd, verb, desc) \
{ id, group, cmd, NULL, verb, desc },
#define OLECOMMAND_HANDLER(id, group, handler, verb, desc) \
{ id, group, 0, handler, verb, desc },
#define END_OLECOMMAND_TABLE() \
{ 0, &GUID_NULL, 0, NULL, NULL, NULL } \
}; \
return s_aSupportedCommands; \
};
#endif | 007slmg-ff-activex-host | ff-activex-host/ffactivex/common/IOleCommandTargetImpl.h | C++ | lgpl | 10,589 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef CONTROLSITE_H
#define CONTROLSITE_H
#include "IOleCommandTargetImpl.h"
#include "PropertyList.h"
// If you created a class derived from CControlSite, use the following macro
// in the interface map of the derived class to include all the necessary
// interfaces.
#define CCONTROLSITE_INTERFACES() \
COM_INTERFACE_ENTRY(IOleWindow) \
COM_INTERFACE_ENTRY(IOleClientSite) \
COM_INTERFACE_ENTRY(IOleInPlaceSite) \
COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSite, IOleInPlaceSiteWindowless) \
COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSiteEx, IOleInPlaceSiteWindowless) \
COM_INTERFACE_ENTRY(IOleControlSite) \
COM_INTERFACE_ENTRY(IDispatch) \
COM_INTERFACE_ENTRY_IID(IID_IAdviseSink, IAdviseSinkEx) \
COM_INTERFACE_ENTRY_IID(IID_IAdviseSink2, IAdviseSinkEx) \
COM_INTERFACE_ENTRY_IID(IID_IAdviseSinkEx, IAdviseSinkEx) \
COM_INTERFACE_ENTRY(IOleCommandTarget) \
COM_INTERFACE_ENTRY(IServiceProvider) \
COM_INTERFACE_ENTRY(IBindStatusCallback) \
COM_INTERFACE_ENTRY(IWindowForBindingUI)
// Temoporarily removed by bug 200680. Stops controls misbehaving and calling
// windowless methods when they shouldn't.
// COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSiteWindowless, IOleInPlaceSiteWindowless) \
// Class that defines the control's security policy with regards to
// what controls it hosts etc.
class CControlSiteSecurityPolicy
{
public:
// Test if the class is safe to host
virtual BOOL IsClassSafeToHost(const CLSID & clsid) = 0;
// Test if the specified class is marked safe for scripting
virtual BOOL IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists) = 0;
// Test if the instantiated object is safe for scripting on the specified interface
virtual BOOL IsObjectSafeForScripting(IUnknown *pObject, const IID &iid) = 0;
};
//
// Class for hosting an ActiveX control
//
// This class supports both windowed and windowless classes. The normal
// steps to hosting a control are this:
//
// CControlSiteInstance *pSite = NULL;
// CControlSiteInstance::CreateInstance(&pSite);
// pSite->AddRef();
// pSite->Create(clsidControlToCreate);
// pSite->Attach(hwndParentWindow, rcPosition);
//
// Where propertyList is a named list of values to initialise the new object
// with, hwndParentWindow is the window in which the control is being created,
// and rcPosition is the position in window coordinates where the control will
// be rendered.
//
// Destruction is this:
//
// pSite->Detach();
// pSite->Release();
// pSite = NULL;
class CControlSite : public CComObjectRootEx<CComSingleThreadModel>,
public CControlSiteSecurityPolicy,
public IOleClientSite,
public IOleInPlaceSiteWindowless,
public IOleControlSite,
public IAdviseSinkEx,
public IDispatch,
public IServiceProvider,
public IOleCommandTargetImpl<CControlSite>,
public IBindStatusCallback,
public IWindowForBindingUI
{
public:
// Site management values
// Handle to parent window
HWND m_hWndParent;
// Position of the site and the contained object
RECT m_rcObjectPos;
// Flag indicating if client site should be set early or late
unsigned m_bSetClientSiteFirst:1;
// Flag indicating whether control is visible or not
unsigned m_bVisibleAtRuntime:1;
// Flag indicating if control is in-place active
unsigned m_bInPlaceActive:1;
// Flag indicating if control is UI active
unsigned m_bUIActive:1;
// Flag indicating if control is in-place locked and cannot be deactivated
unsigned m_bInPlaceLocked:1;
// Flag indicating if the site allows windowless controls
unsigned m_bSupportWindowlessActivation:1;
// Flag indicating if control is windowless (after being created)
unsigned m_bWindowless:1;
// Flag indicating if only safely scriptable controls are allowed
unsigned m_bSafeForScriptingObjectsOnly:1;
// Pointer to an externally registered service provider
CComPtr<IServiceProvider> m_spServiceProvider;
// Pointer to the OLE container
CComPtr<IOleContainer> m_spContainer;
// Return the default security policy object
static CControlSiteSecurityPolicy *GetDefaultControlSecurityPolicy();
protected:
// Pointers to object interfaces
// Raw pointer to the object
CComPtr<IUnknown> m_spObject;
// Pointer to objects IViewObject interface
CComQIPtr<IViewObject, &IID_IViewObject> m_spIViewObject;
// Pointer to object's IOleObject interface
CComQIPtr<IOleObject, &IID_IOleObject> m_spIOleObject;
// Pointer to object's IOleInPlaceObject interface
CComQIPtr<IOleInPlaceObject, &IID_IOleInPlaceObject> m_spIOleInPlaceObject;
// Pointer to object's IOleInPlaceObjectWindowless interface
CComQIPtr<IOleInPlaceObjectWindowless, &IID_IOleInPlaceObjectWindowless> m_spIOleInPlaceObjectWindowless;
// CLSID of the control
CLSID m_CLSID;
// Parameter list
PropertyList m_ParameterList;
// Pointer to the security policy
CControlSiteSecurityPolicy *m_pSecurityPolicy;
// Binding variables
// Flag indicating whether binding is in progress
unsigned m_bBindingInProgress;
// Result from the binding operation
HRESULT m_hrBindResult;
// Double buffer drawing variables used for windowless controls
// Area of buffer
RECT m_rcBuffer;
// Bitmap to buffer
HBITMAP m_hBMBuffer;
// Bitmap to buffer
HBITMAP m_hBMBufferOld;
// Device context
HDC m_hDCBuffer;
// Clipping area of site
HRGN m_hRgnBuffer;
// Flags indicating how the buffer was painted
DWORD m_dwBufferFlags;
// Ambient properties
// Locale ID
LCID m_nAmbientLocale;
// Foreground colour
COLORREF m_clrAmbientForeColor;
// Background colour
COLORREF m_clrAmbientBackColor;
// Flag indicating if control should hatch itself
bool m_bAmbientShowHatching:1;
// Flag indicating if control should have grab handles
bool m_bAmbientShowGrabHandles:1;
// Flag indicating if control is in edit/user mode
bool m_bAmbientUserMode:1;
// Flag indicating if control has a 3d border or not
bool m_bAmbientAppearance:1;
protected:
// Notifies the attached control of a change to an ambient property
virtual void FireAmbientPropertyChange(DISPID id);
public:
// Construction and destruction
// Constructor
CControlSite();
// Destructor
virtual ~CControlSite();
BEGIN_COM_MAP(CControlSite)
CCONTROLSITE_INTERFACES()
END_COM_MAP()
BEGIN_OLECOMMAND_TABLE()
END_OLECOMMAND_TABLE()
// Returns the window used when processing ole commands
HWND GetCommandTargetWindow()
{
return NULL; // TODO
}
// Object creation and management functions
// Creates and initialises an object
virtual HRESULT Create(REFCLSID clsid, PropertyList &pl = PropertyList(),
LPCWSTR szCodebase = NULL, IBindCtx *pBindContext = NULL);
// Attaches the object to the site
virtual HRESULT Attach(HWND hwndParent, const RECT &rcPos, IUnknown *pInitStream = NULL);
// Detaches the object from the site
virtual HRESULT Detach();
// Returns the IUnknown pointer for the object
virtual HRESULT GetControlUnknown(IUnknown **ppObject);
// Sets the bounding rectangle for the object
virtual HRESULT SetPosition(const RECT &rcPos);
// Draws the object using the provided DC
virtual HRESULT Draw(HDC hdc);
// Performs the specified action on the object
virtual HRESULT DoVerb(LONG nVerb, LPMSG lpMsg = NULL);
// Sets an advise sink up for changes to the object
virtual HRESULT Advise(IUnknown *pIUnkSink, const IID &iid, DWORD *pdwCookie);
// Removes an advise sink
virtual HRESULT Unadvise(const IID &iid, DWORD dwCookie);
// Register an external service provider object
virtual void SetServiceProvider(IServiceProvider *pSP)
{
m_spServiceProvider = pSP;
}
virtual void SetContainer(IOleContainer *pContainer)
{
m_spContainer = pContainer;
}
// Set the security policy object. Ownership of this object remains with the caller and the security
// policy object is meant to exist for as long as it is set here.
virtual void SetSecurityPolicy(CControlSiteSecurityPolicy *pSecurityPolicy)
{
m_pSecurityPolicy = pSecurityPolicy;
}
virtual CControlSiteSecurityPolicy *GetSecurityPolicy() const
{
return m_pSecurityPolicy;
}
// Methods to set ambient properties
virtual void SetAmbientUserMode(BOOL bUser);
// Inline helper methods
// Returns the object's CLSID
virtual const CLSID &GetObjectCLSID() const
{
return m_CLSID;
}
// Tests if the object is valid or not
virtual BOOL IsObjectValid() const
{
return (m_spObject) ? TRUE : FALSE;
}
// Returns the parent window to this one
virtual HWND GetParentWindow() const
{
return m_hWndParent;
}
// Returns the inplace active state of the object
virtual BOOL IsInPlaceActive() const
{
return m_bInPlaceActive;
}
// CControlSiteSecurityPolicy
// Test if the class is safe to host
virtual BOOL IsClassSafeToHost(const CLSID & clsid);
// Test if the specified class is marked safe for scripting
virtual BOOL IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists);
// Test if the instantiated object is safe for scripting on the specified interface
virtual BOOL IsObjectSafeForScripting(IUnknown *pObject, const IID &iid);
// Test if the instantiated object is safe for scripting on the specified interface
virtual BOOL IsObjectSafeForScripting(const IID &iid);
// IServiceProvider
virtual HRESULT STDMETHODCALLTYPE QueryService(REFGUID guidService, REFIID riid, void** ppv);
// IDispatch
virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo);
virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo);
virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId);
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr);
// IAdviseSink implementation
virtual /* [local] */ void STDMETHODCALLTYPE OnDataChange(/* [unique][in] */ FORMATETC __RPC_FAR *pFormatetc, /* [unique][in] */ STGMEDIUM __RPC_FAR *pStgmed);
virtual /* [local] */ void STDMETHODCALLTYPE OnViewChange(/* [in] */ DWORD dwAspect, /* [in] */ LONG lindex);
virtual /* [local] */ void STDMETHODCALLTYPE OnRename(/* [in] */ IMoniker __RPC_FAR *pmk);
virtual /* [local] */ void STDMETHODCALLTYPE OnSave(void);
virtual /* [local] */ void STDMETHODCALLTYPE OnClose(void);
// IAdviseSink2
virtual /* [local] */ void STDMETHODCALLTYPE OnLinkSrcChange(/* [unique][in] */ IMoniker __RPC_FAR *pmk);
// IAdviseSinkEx implementation
virtual /* [local] */ void STDMETHODCALLTYPE OnViewStatusChange(/* [in] */ DWORD dwViewStatus);
// IOleWindow implementation
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetWindow(/* [out] */ HWND __RPC_FAR *phwnd);
virtual HRESULT STDMETHODCALLTYPE ContextSensitiveHelp(/* [in] */ BOOL fEnterMode);
// IOleClientSite implementation
virtual HRESULT STDMETHODCALLTYPE SaveObject(void);
virtual HRESULT STDMETHODCALLTYPE GetMoniker(/* [in] */ DWORD dwAssign, /* [in] */ DWORD dwWhichMoniker, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmk);
virtual HRESULT STDMETHODCALLTYPE GetContainer(/* [out] */ IOleContainer __RPC_FAR *__RPC_FAR *ppContainer);
virtual HRESULT STDMETHODCALLTYPE ShowObject(void);
virtual HRESULT STDMETHODCALLTYPE OnShowWindow(/* [in] */ BOOL fShow);
virtual HRESULT STDMETHODCALLTYPE RequestNewObjectLayout(void);
// IOleInPlaceSite implementation
virtual HRESULT STDMETHODCALLTYPE CanInPlaceActivate(void);
virtual HRESULT STDMETHODCALLTYPE OnInPlaceActivate(void);
virtual HRESULT STDMETHODCALLTYPE OnUIActivate(void);
virtual HRESULT STDMETHODCALLTYPE GetWindowContext(/* [out] */ IOleInPlaceFrame __RPC_FAR *__RPC_FAR *ppFrame, /* [out] */ IOleInPlaceUIWindow __RPC_FAR *__RPC_FAR *ppDoc, /* [out] */ LPRECT lprcPosRect, /* [out] */ LPRECT lprcClipRect, /* [out][in] */ LPOLEINPLACEFRAMEINFO lpFrameInfo);
virtual HRESULT STDMETHODCALLTYPE Scroll(/* [in] */ SIZE scrollExtant);
virtual HRESULT STDMETHODCALLTYPE OnUIDeactivate(/* [in] */ BOOL fUndoable);
virtual HRESULT STDMETHODCALLTYPE OnInPlaceDeactivate(void);
virtual HRESULT STDMETHODCALLTYPE DiscardUndoState(void);
virtual HRESULT STDMETHODCALLTYPE DeactivateAndUndo(void);
virtual HRESULT STDMETHODCALLTYPE OnPosRectChange(/* [in] */ LPCRECT lprcPosRect);
// IOleInPlaceSiteEx implementation
virtual HRESULT STDMETHODCALLTYPE OnInPlaceActivateEx(/* [out] */ BOOL __RPC_FAR *pfNoRedraw, /* [in] */ DWORD dwFlags);
virtual HRESULT STDMETHODCALLTYPE OnInPlaceDeactivateEx(/* [in] */ BOOL fNoRedraw);
virtual HRESULT STDMETHODCALLTYPE RequestUIActivate(void);
// IOleInPlaceSiteWindowless implementation
virtual HRESULT STDMETHODCALLTYPE CanWindowlessActivate(void);
virtual HRESULT STDMETHODCALLTYPE GetCapture(void);
virtual HRESULT STDMETHODCALLTYPE SetCapture(/* [in] */ BOOL fCapture);
virtual HRESULT STDMETHODCALLTYPE GetFocus(void);
virtual HRESULT STDMETHODCALLTYPE SetFocus(/* [in] */ BOOL fFocus);
virtual HRESULT STDMETHODCALLTYPE GetDC(/* [in] */ LPCRECT pRect, /* [in] */ DWORD grfFlags, /* [out] */ HDC __RPC_FAR *phDC);
virtual HRESULT STDMETHODCALLTYPE ReleaseDC(/* [in] */ HDC hDC);
virtual HRESULT STDMETHODCALLTYPE InvalidateRect(/* [in] */ LPCRECT pRect, /* [in] */ BOOL fErase);
virtual HRESULT STDMETHODCALLTYPE InvalidateRgn(/* [in] */ HRGN hRGN, /* [in] */ BOOL fErase);
virtual HRESULT STDMETHODCALLTYPE ScrollRect(/* [in] */ INT dx, /* [in] */ INT dy, /* [in] */ LPCRECT pRectScroll, /* [in] */ LPCRECT pRectClip);
virtual HRESULT STDMETHODCALLTYPE AdjustRect(/* [out][in] */ LPRECT prc);
virtual HRESULT STDMETHODCALLTYPE OnDefWindowMessage(/* [in] */ UINT msg, /* [in] */ WPARAM wParam, /* [in] */ LPARAM lParam, /* [out] */ LRESULT __RPC_FAR *plResult);
// IOleControlSite implementation
virtual HRESULT STDMETHODCALLTYPE OnControlInfoChanged(void);
virtual HRESULT STDMETHODCALLTYPE LockInPlaceActive(/* [in] */ BOOL fLock);
virtual HRESULT STDMETHODCALLTYPE GetExtendedControl(/* [out] */ IDispatch __RPC_FAR *__RPC_FAR *ppDisp);
virtual HRESULT STDMETHODCALLTYPE TransformCoords(/* [out][in] */ POINTL __RPC_FAR *pPtlHimetric, /* [out][in] */ POINTF __RPC_FAR *pPtfContainer, /* [in] */ DWORD dwFlags);
virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator(/* [in] */ MSG __RPC_FAR *pMsg, /* [in] */ DWORD grfModifiers);
virtual HRESULT STDMETHODCALLTYPE OnFocus(/* [in] */ BOOL fGotFocus);
virtual HRESULT STDMETHODCALLTYPE ShowPropertyFrame( void);
// IBindStatusCallback
virtual HRESULT STDMETHODCALLTYPE OnStartBinding(/* [in] */ DWORD dwReserved, /* [in] */ IBinding __RPC_FAR *pib);
virtual HRESULT STDMETHODCALLTYPE GetPriority(/* [out] */ LONG __RPC_FAR *pnPriority);
virtual HRESULT STDMETHODCALLTYPE OnLowResource(/* [in] */ DWORD reserved);
virtual HRESULT STDMETHODCALLTYPE OnProgress(/* [in] */ ULONG ulProgress, /* [in] */ ULONG ulProgressMax, /* [in] */ ULONG ulStatusCode, /* [in] */ LPCWSTR szStatusText);
virtual HRESULT STDMETHODCALLTYPE OnStopBinding(/* [in] */ HRESULT hresult, /* [unique][in] */ LPCWSTR szError);
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetBindInfo( /* [out] */ DWORD __RPC_FAR *grfBINDF, /* [unique][out][in] */ BINDINFO __RPC_FAR *pbindinfo);
virtual /* [local] */ HRESULT STDMETHODCALLTYPE OnDataAvailable(/* [in] */ DWORD grfBSCF, /* [in] */ DWORD dwSize, /* [in] */ FORMATETC __RPC_FAR *pformatetc, /* [in] */ STGMEDIUM __RPC_FAR *pstgmed);
virtual HRESULT STDMETHODCALLTYPE OnObjectAvailable(/* [in] */ REFIID riid, /* [iid_is][in] */ IUnknown __RPC_FAR *punk);
// IWindowForBindingUI
virtual HRESULT STDMETHODCALLTYPE GetWindow(/* [in] */ REFGUID rguidReason, /* [out] */ HWND *phwnd);
};
typedef CComObject<CControlSite> CControlSiteInstance;
#endif | 007slmg-ff-activex-host | ff-activex-host/ffactivex/common/ControlSite.h | C++ | lgpl | 18,659 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "StdAfx.h"
#include "ControlEventSink.h"
CControlEventSink::CControlEventSink() :
m_dwEventCookie(0),
m_bSubscribed(false),
m_EventIID(GUID_NULL),
events()
{
}
CControlEventSink::~CControlEventSink()
{
UnsubscribeFromEvents();
}
BOOL
CControlEventSink::GetEventSinkIID(IUnknown *pControl, IID &iid, ITypeInfo **typeInfo)
{
iid = GUID_NULL;
if (!pControl)
{
return E_INVALIDARG;
}
// IProvideClassInfo2 way is easiest
// CComQIPtr<IProvideClassInfo2> classInfo2 = pControl;
// if (classInfo2)
// {
// classInfo2->GetGUID(GUIDKIND_DEFAULT_SOURCE_DISP_IID, &iid);
// if (!::IsEqualIID(iid, GUID_NULL))
// {
// return TRUE;
// }
// }
// Yuck, the hard way
CComQIPtr<IProvideClassInfo> classInfo = pControl;
if (!classInfo)
{
return FALSE;
}
// Search the class type information for the default source interface
// which is the outgoing event sink.
CComPtr<ITypeInfo> classTypeInfo;
classInfo->GetClassInfo(&classTypeInfo);
if (!classTypeInfo)
{
return FALSE;
}
TYPEATTR *classAttr = NULL;
if (FAILED(classTypeInfo->GetTypeAttr(&classAttr)))
{
return FALSE;
}
INT implFlags = 0;
for (UINT i = 0; i < classAttr->cImplTypes; i++)
{
// Search for the interface with the [default, source] attr
if (SUCCEEDED(classTypeInfo->GetImplTypeFlags(i, &implFlags)) &&
implFlags == (IMPLTYPEFLAG_FDEFAULT | IMPLTYPEFLAG_FSOURCE))
{
CComPtr<ITypeInfo> eventSinkTypeInfo;
HREFTYPE hRefType;
if (SUCCEEDED(classTypeInfo->GetRefTypeOfImplType(i, &hRefType)) &&
SUCCEEDED(classTypeInfo->GetRefTypeInfo(hRefType, &eventSinkTypeInfo)))
{
TYPEATTR *eventSinkAttr = NULL;
if (SUCCEEDED(eventSinkTypeInfo->GetTypeAttr(&eventSinkAttr)))
{
iid = eventSinkAttr->guid;
if (typeInfo)
{
*typeInfo = eventSinkTypeInfo.p;
(*typeInfo)->AddRef();
}
eventSinkTypeInfo->ReleaseTypeAttr(eventSinkAttr);
}
}
break;
}
}
classTypeInfo->ReleaseTypeAttr(classAttr);
return (!::IsEqualIID(iid, GUID_NULL));
}
void CControlEventSink::UnsubscribeFromEvents()
{
if (m_bSubscribed)
{
DWORD tmpCookie = m_dwEventCookie;
m_dwEventCookie = 0;
m_bSubscribed = false;
// Unsubscribe and reset - This seems to complete release and destroy us...
m_spEventCP->Unadvise(tmpCookie);
// Unadvise handles the Release
//m_spEventCP.Release();
}
}
HRESULT CControlEventSink::SubscribeToEvents(IUnknown *pControl)
{
if (!pControl)
{
return E_INVALIDARG;
}
// Throw away any existing connections
UnsubscribeFromEvents();
// Grab the outgoing event sink IID which will be used to subscribe
// to events via the connection point container.
IID iidEventSink;
CComPtr<ITypeInfo> typeInfo;
if (!GetEventSinkIID(pControl, iidEventSink, &typeInfo))
{
return E_FAIL;
}
// Get the connection point
CComQIPtr<IConnectionPointContainer> ccp = pControl;
CComPtr<IConnectionPoint> cp;
if (!ccp)
{
return E_FAIL;
}
// Custom IID
m_EventIID = iidEventSink;
DWORD dwCookie = 0;
if (!ccp ||
FAILED(ccp->FindConnectionPoint(m_EventIID, &cp)) ||
FAILED(cp->Advise(this, &dwCookie)))
{
return E_FAIL;
}
m_bSubscribed = true;
m_spEventCP = cp;
m_dwEventCookie = dwCookie;
m_spEventSinkTypeInfo = typeInfo;
return S_OK;
}
HRESULT
CControlEventSink::InternalInvoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr)
{
USES_CONVERSION;
if (DISPATCH_METHOD != wFlags) {
// any other reason to call us?!
return S_FALSE;
}
EventMap::iterator cur = events.find(dispIdMember);
if (events.end() != cur) {
// invoke this event handler
NPVariant result;
NPVariant *args = NULL;
if (pDispParams->cArgs > 0) {
args = (NPVariant *)calloc(pDispParams->cArgs, sizeof(NPVariant));
if (!args) {
return S_FALSE;
}
for (unsigned int i = 0; i < pDispParams->cArgs; ++i) {
// convert the arguments in reverse order
Variant2NPVar(&pDispParams->rgvarg[i], &args[pDispParams->cArgs - i - 1], instance);
}
}
NPObject *globalObj = NULL;
NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj);
NPIdentifier handler = NPNFuncs.getstringidentifier(W2A((*cur).second));
bool success = NPNFuncs.invoke(instance, globalObj, handler, args, pDispParams->cArgs, &result);
NPNFuncs.releaseobject(globalObj);
for (unsigned int i = 0; i < pDispParams->cArgs; ++i) {
// convert the arguments
if (args[i].type == NPVariantType_String) {
// was allocated earlier by Variant2NPVar
NPNFuncs.memfree((void *)args[i].value.stringValue.UTF8Characters);
}
}
if (!success) {
return S_FALSE;
}
if (pVarResult) {
// set the result
NPVar2Variant(&result, pVarResult, instance);
}
NPNFuncs.releasevariantvalue(&result);
}
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
// IDispatch implementation
HRESULT STDMETHODCALLTYPE CControlEventSink::GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlEventSink::GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlEventSink::GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlEventSink::Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr)
{
return InternalInvoke(dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
}
| 007slmg-ff-activex-host | ff-activex-host/ffactivex/common/ControlEventSink.cpp | C++ | lgpl | 8,596 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef CONTROLEVENTSINK_H
#define CONTROLEVENTSINK_H
#include <map>
// This class listens for events from the specified control
class CControlEventSink :
public CComObjectRootEx<CComSingleThreadModel>,
public IDispatch
{
public:
CControlEventSink();
// Current event connection point
CComPtr<IConnectionPoint> m_spEventCP;
CComPtr<ITypeInfo> m_spEventSinkTypeInfo;
DWORD m_dwEventCookie;
IID m_EventIID;
typedef std::map<DISPID, wchar_t *> EventMap;
EventMap events;
NPP instance;
protected:
virtual ~CControlEventSink();
bool m_bSubscribed;
static HRESULT WINAPI SinkQI(void* pv, REFIID riid, LPVOID* ppv, DWORD dw)
{
CControlEventSink *pThis = (CControlEventSink *) pv;
if (!IsEqualIID(pThis->m_EventIID, GUID_NULL) &&
IsEqualIID(pThis->m_EventIID, riid))
{
return pThis->QueryInterface(__uuidof(IDispatch), ppv);
}
return E_NOINTERFACE;
}
public:
BEGIN_COM_MAP(CControlEventSink)
COM_INTERFACE_ENTRY(IDispatch)
COM_INTERFACE_ENTRY_FUNC_BLIND(0, SinkQI)
END_COM_MAP()
virtual HRESULT SubscribeToEvents(IUnknown *pControl);
virtual void UnsubscribeFromEvents();
virtual BOOL GetEventSinkIID(IUnknown *pControl, IID &iid, ITypeInfo **typeInfo);
virtual HRESULT InternalInvoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr);
// IDispatch
virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo);
virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo);
virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId);
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr);
};
typedef CComObject<CControlEventSink> CControlEventSinkInstance;
#endif | 007slmg-ff-activex-host | ff-activex-host/ffactivex/common/ControlEventSink.h | C++ | lgpl | 4,193 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef CONTROLSITEIPFRAME_H
#define CONTROLSITEIPFRAME_H
class CControlSiteIPFrame : public CComObjectRootEx<CComSingleThreadModel>,
public IOleInPlaceFrame
{
public:
CControlSiteIPFrame();
virtual ~CControlSiteIPFrame();
HWND m_hwndFrame;
BEGIN_COM_MAP(CControlSiteIPFrame)
COM_INTERFACE_ENTRY_IID(IID_IOleWindow, IOleInPlaceFrame)
COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceUIWindow, IOleInPlaceFrame)
COM_INTERFACE_ENTRY(IOleInPlaceFrame)
END_COM_MAP()
// IOleWindow
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetWindow(/* [out] */ HWND __RPC_FAR *phwnd);
virtual HRESULT STDMETHODCALLTYPE ContextSensitiveHelp(/* [in] */ BOOL fEnterMode);
// IOleInPlaceUIWindow implementation
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetBorder(/* [out] */ LPRECT lprectBorder);
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE RequestBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths);
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths);
virtual HRESULT STDMETHODCALLTYPE SetActiveObject(/* [unique][in] */ IOleInPlaceActiveObject __RPC_FAR *pActiveObject, /* [unique][string][in] */ LPCOLESTR pszObjName);
// IOleInPlaceFrame implementation
virtual HRESULT STDMETHODCALLTYPE InsertMenus(/* [in] */ HMENU hmenuShared, /* [out][in] */ LPOLEMENUGROUPWIDTHS lpMenuWidths);
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetMenu(/* [in] */ HMENU hmenuShared, /* [in] */ HOLEMENU holemenu, /* [in] */ HWND hwndActiveObject);
virtual HRESULT STDMETHODCALLTYPE RemoveMenus(/* [in] */ HMENU hmenuShared);
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetStatusText(/* [in] */ LPCOLESTR pszStatusText);
virtual HRESULT STDMETHODCALLTYPE EnableModeless(/* [in] */ BOOL fEnable);
virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator(/* [in] */ LPMSG lpmsg, /* [in] */ WORD wID);
};
typedef CComObject<CControlSiteIPFrame> CControlSiteIPFrameInstance;
#endif | 007slmg-ff-activex-host | ff-activex-host/ffactivex/common/ControlSiteIPFrame.h | C++ | lgpl | 3,891 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "stdafx.h"
#include "ControlSiteIPFrame.h"
CControlSiteIPFrame::CControlSiteIPFrame()
{
m_hwndFrame = NULL;
}
CControlSiteIPFrame::~CControlSiteIPFrame()
{
}
///////////////////////////////////////////////////////////////////////////////
// IOleWindow implementation
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::GetWindow(/* [out] */ HWND __RPC_FAR *phwnd)
{
if (phwnd == NULL)
{
return E_INVALIDARG;
}
*phwnd = m_hwndFrame;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::ContextSensitiveHelp(/* [in] */ BOOL fEnterMode)
{
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
// IOleInPlaceUIWindow implementation
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::GetBorder(/* [out] */ LPRECT lprectBorder)
{
return INPLACE_E_NOTOOLSPACE;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::RequestBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths)
{
return INPLACE_E_NOTOOLSPACE;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetActiveObject(/* [unique][in] */ IOleInPlaceActiveObject __RPC_FAR *pActiveObject, /* [unique][string][in] */ LPCOLESTR pszObjName)
{
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
// IOleInPlaceFrame implementation
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::InsertMenus(/* [in] */ HMENU hmenuShared, /* [out][in] */ LPOLEMENUGROUPWIDTHS lpMenuWidths)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetMenu(/* [in] */ HMENU hmenuShared, /* [in] */ HOLEMENU holemenu, /* [in] */ HWND hwndActiveObject)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::RemoveMenus(/* [in] */ HMENU hmenuShared)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetStatusText(/* [in] */ LPCOLESTR pszStatusText)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::EnableModeless(/* [in] */ BOOL fEnable)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::TranslateAccelerator(/* [in] */ LPMSG lpmsg, /* [in] */ WORD wID)
{
return E_NOTIMPL;
}
| 007slmg-ff-activex-host | ff-activex-host/ffactivex/common/ControlSiteIPFrame.cpp | C++ | lgpl | 4,105 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@eircom.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef PROPERTYBAG_H
#define PROPERTYBAG_H
#include "PropertyList.h"
// Object wrapper for property list. This class can be set up with a
// list of properties and used to initialise a control with them
class CPropertyBag : public CComObjectRootEx<CComSingleThreadModel>,
public IPropertyBag
{
// List of properties in the bag
PropertyList m_PropertyList;
public:
// Constructor
CPropertyBag();
// Destructor
virtual ~CPropertyBag();
BEGIN_COM_MAP(CPropertyBag)
COM_INTERFACE_ENTRY(IPropertyBag)
END_COM_MAP()
// IPropertyBag methods
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Read(/* [in] */ LPCOLESTR pszPropName, /* [out][in] */ VARIANT __RPC_FAR *pVar, /* [in] */ IErrorLog __RPC_FAR *pErrorLog);
virtual HRESULT STDMETHODCALLTYPE Write(/* [in] */ LPCOLESTR pszPropName, /* [in] */ VARIANT __RPC_FAR *pVar);
};
typedef CComObject<CPropertyBag> CPropertyBagInstance;
#endif | 007slmg-ff-activex-host | ff-activex-host/ffactivex/common/PropertyBag.h | C++ | lgpl | 2,769 |
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@eircom.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "StdAfx.h"
#include "ItemContainer.h"
CItemContainer::CItemContainer()
{
}
CItemContainer::~CItemContainer()
{
}
///////////////////////////////////////////////////////////////////////////////
// IParseDisplayName implementation
HRESULT STDMETHODCALLTYPE CItemContainer::ParseDisplayName(/* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ LPOLESTR pszDisplayName, /* [out] */ ULONG __RPC_FAR *pchEaten, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmkOut)
{
// TODO
return E_NOTIMPL;
}
///////////////////////////////////////////////////////////////////////////////
// IOleContainer implementation
HRESULT STDMETHODCALLTYPE CItemContainer::EnumObjects(/* [in] */ DWORD grfFlags, /* [out] */ IEnumUnknown __RPC_FAR *__RPC_FAR *ppenum)
{
HRESULT hr = E_NOTIMPL;
/*
if (ppenum == NULL)
{
return E_POINTER;
}
*ppenum = NULL;
typedef CComObject<CComEnumOnSTL<IEnumUnknown, &IID_IEnumUnknown, IUnknown*, _CopyInterface<IUnknown>, CNamedObjectList > > enumunk;
enumunk* p = NULL;
p = new enumunk;
if(p == NULL)
{
return E_OUTOFMEMORY;
}
hr = p->Init();
if (SUCCEEDED(hr))
{
hr = p->QueryInterface(IID_IEnumUnknown, (void**) ppenum);
}
if (FAILED(hRes))
{
delete p;
}
*/
return hr;
}
HRESULT STDMETHODCALLTYPE CItemContainer::LockContainer(/* [in] */ BOOL fLock)
{
// TODO
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
// IOleItemContainer implementation
HRESULT STDMETHODCALLTYPE CItemContainer::GetObject(/* [in] */ LPOLESTR pszItem, /* [in] */ DWORD dwSpeedNeeded, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject)
{
if (pszItem == NULL)
{
return E_INVALIDARG;
}
if (ppvObject == NULL)
{
return E_INVALIDARG;
}
*ppvObject = NULL;
return MK_E_NOOBJECT;
}
HRESULT STDMETHODCALLTYPE CItemContainer::GetObjectStorage(/* [in] */ LPOLESTR pszItem, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvStorage)
{
// TODO
return MK_E_NOOBJECT;
}
HRESULT STDMETHODCALLTYPE CItemContainer::IsRunning(/* [in] */ LPOLESTR pszItem)
{
// TODO
return MK_E_NOOBJECT;
}
| 007slmg-ff-activex-host | ff-activex-host/ffactivex/common/ItemContainer.cpp | C++ | lgpl | 4,191 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is RSJ Software GmbH code.
*
* The Initial Developer of the Original Code is
* RSJ Software GmbH.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributors:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <stdio.h>
#include <windows.h>
#include <winreg.h>
#include "ffactivex.h"
#include "common/stdafx.h"
#include "axhost.h"
#include "atlutil.h"
#include "authorize.h"
// ----------------------------------------------------------------------------
#define SUB_KEY L"SOFTWARE\\MozillaPlugins\\@itstructures.com/ffactivex\\MimeTypes\\application/x-itst-activex"
// ----------------------------------------------------------------------------
BOOL TestExplicitAuthorizationUTF8 (const char *MimeType,
const char *AuthorizationType,
const char *DocumentUrl,
const char *ProgramId);
BOOL TestExplicitAuthorization (const wchar_t *MimeType,
const wchar_t *AuthorizationType,
const wchar_t *DocumentUrl,
const wchar_t *ProgramId);
BOOL WildcardMatch (const wchar_t *Mask,
const wchar_t *Value);
HKEY FindKey (const wchar_t *MimeType,
const wchar_t *AuthorizationType);
// ---------------------------------------------------------------------------
HKEY BaseKeys[] = {
HKEY_CURRENT_USER,
HKEY_LOCAL_MACHINE
};
// ----------------------------------------------------------------------------
BOOL TestAuthorization (NPP Instance,
int16 ArgC,
char *ArgN[],
char *ArgV[],
const char *MimeType)
{
BOOL ret = FALSE;
NPObject *globalObj = NULL;
NPIdentifier identifier;
NPVariant varLocation;
NPVariant varHref;
bool rc = false;
int16 i;
char *wrkHref;
#ifdef NDEF
_asm{int 3};
#endif
if (Instance == NULL) {
return (FALSE);
}
// Determine owning document
// Get the window object.
NPNFuncs.getvalue(Instance,
NPNVWindowNPObject,
&globalObj);
// Create a "location" identifier.
identifier = NPNFuncs.getstringidentifier("location");
// Get the location property from the window object (which is another object).
rc = NPNFuncs.getproperty(Instance,
globalObj,
identifier,
&varLocation);
NPNFuncs.releaseobject(globalObj);
if (!rc){
log(Instance, 0, "AxHost.TestAuthorization: could not get the location from the global object");
return false;
}
// Get a pointer to the "location" object.
NPObject *locationObj = varLocation.value.objectValue;
// Create a "href" identifier.
identifier = NPNFuncs.getstringidentifier("href");
// Get the location property from the location object.
rc = NPNFuncs.getproperty(Instance,
locationObj,
identifier,
&varHref);
NPNFuncs.releasevariantvalue(&varLocation);
if (!rc) {
log(Instance, 0, "AxHost.TestAuthorization: could not get the href from the location property");
return false;
}
ret = TRUE;
wrkHref = (char *) alloca(varHref.value.stringValue.UTF8Length + 1);
memcpy(wrkHref,
varHref.value.stringValue.UTF8Characters,
varHref.value.stringValue.UTF8Length);
wrkHref[varHref.value.stringValue.UTF8Length] = 0x00;
NPNFuncs.releasevariantvalue(&varHref);
for (i = 0;
i < ArgC;
++i) {
// search for any needed information: clsid, event handling directives, etc.
if (0 == strnicmp(ArgN[i], PARAM_CLSID, strlen(PARAM_CLSID))) {
ret &= TestExplicitAuthorizationUTF8(MimeType,
PARAM_CLSID,
wrkHref,
ArgV[i]);
} else if (0 == strnicmp(ArgN[i], PARAM_PROGID, strlen(PARAM_PROGID))) {
// The class id of the control we are asked to load
ret &= TestExplicitAuthorizationUTF8(MimeType,
PARAM_PROGID,
wrkHref,
ArgV[i]);
} else if( 0 == strnicmp(ArgN[i], PARAM_CODEBASEURL, strlen(PARAM_CODEBASEURL))) {
ret &= TestExplicitAuthorizationUTF8(MimeType,
PARAM_CODEBASEURL,
wrkHref,
ArgV[i]);
}
}
log(Instance, 1, "AxHost.TestAuthorization: returning %s", ret ? "True" : "False");
return (ret);
}
// ----------------------------------------------------------------------------
BOOL TestExplicitAuthorizationUTF8 (const char *MimeType,
const char *AuthorizationType,
const char *DocumentUrl,
const char *ProgramId)
{
USES_CONVERSION;
BOOL ret;
ret = TestExplicitAuthorization(A2W(MimeType),
A2W(AuthorizationType),
A2W(DocumentUrl),
A2W(ProgramId));
return (ret);
}
// ----------------------------------------------------------------------------
BOOL TestExplicitAuthorization (const wchar_t *MimeType,
const wchar_t *AuthorizationType,
const wchar_t *DocumentUrl,
const wchar_t *ProgramId)
{
BOOL ret = FALSE;
#ifndef NO_REGISTRY_AUTHORIZE
HKEY hKey;
HKEY hSubKey;
ULONG i;
ULONG j;
ULONG keyNameLen;
ULONG valueNameLen;
wchar_t keyName[_MAX_PATH];
wchar_t valueName[_MAX_PATH];
if (DocumentUrl == NULL) {
return (FALSE);
}
if (ProgramId == NULL) {
return (FALSE);
}
#ifdef NDEF
MessageBox(NULL,
DocumentUrl,
ProgramId,
MB_OK);
#endif
if ((hKey = FindKey(MimeType,
AuthorizationType)) != NULL) {
for (i = 0;
!ret;
i++) {
keyNameLen = sizeof(keyName);
if (RegEnumKey(hKey,
i,
keyName,
keyNameLen) == ERROR_SUCCESS) {
if (WildcardMatch(keyName,
DocumentUrl)) {
if (RegOpenKeyEx(hKey,
keyName,
0,
KEY_QUERY_VALUE,
&hSubKey) == ERROR_SUCCESS) {
for (j = 0;
;
j++) {
valueNameLen = sizeof(valueName);
if (RegEnumValue(hSubKey,
j,
valueName,
&valueNameLen,
NULL,
NULL,
NULL,
NULL) != ERROR_SUCCESS) {
break;
}
if (WildcardMatch(valueName,
ProgramId)) {
ret = TRUE;
break;
}
}
RegCloseKey(hSubKey);
}
if (ret) {
break;
}
}
} else {
break;
}
}
RegCloseKey(hKey);
}
#endif
return (ret);
}
// ----------------------------------------------------------------------------
BOOL WildcardMatch (const wchar_t *Mask,
const wchar_t *Value)
{
size_t i;
size_t j = 0;
size_t maskLen;
size_t valueLen;
maskLen = wcslen(Mask);
valueLen = wcslen(Value);
for (i = 0;
i < maskLen + 1;
i++) {
if (Mask[i] == '?') {
j++;
continue;
}
if (Mask[i] == '*') {
for (;
j < valueLen + 1;
j++) {
if (WildcardMatch(Mask + i + 1,
Value + j)) {
return (TRUE);
}
}
return (FALSE);
}
if ((j <= valueLen) &&
(Mask[i] == tolower(Value[j]))) {
j++;
continue;
}
return (FALSE);
}
return (TRUE);
}
// ----------------------------------------------------------------------------
HKEY FindKey (const wchar_t *MimeType,
const wchar_t *AuthorizationType)
{
HKEY ret = NULL;
HKEY plugins;
wchar_t searchKey[_MAX_PATH];
wchar_t pluginName[_MAX_PATH];
DWORD j;
size_t i;
for (i = 0;
i < ARRAYSIZE(BaseKeys);
i++) {
if (RegOpenKeyEx(BaseKeys[i],
L"SOFTWARE\\MozillaPlugins",
0,
KEY_ENUMERATE_SUB_KEYS,
&plugins) == ERROR_SUCCESS) {
for (j = 0;
ret == NULL;
j++) {
if (RegEnumKey(plugins,
j,
pluginName,
sizeof(pluginName)) != ERROR_SUCCESS) {
break;
}
wsprintf(searchKey,
L"%s\\MimeTypes\\%s\\%s",
pluginName,
MimeType,
AuthorizationType);
if (RegOpenKeyEx(plugins,
searchKey,
0,
KEY_ENUMERATE_SUB_KEYS,
&ret) == ERROR_SUCCESS) {
break;
}
ret = NULL;
}
RegCloseKey(plugins);
if (ret != NULL) {
break;
}
}
}
return (ret);
}
| 007slmg-ff-activex-host | ff-activex-host/ffactivex/authorize.cpp | C++ | lgpl | 10,024 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <comdef.h>
#include "ffactivex.h"
#include "scriptable.h"
#include "axhost.h"
#ifdef NO_REGISTRY_AUTHORIZE
static const char *WellKnownProgIds[] = {
NULL
};
static const char *WellKnownClsIds[] = {
NULL
};
#endif
static const bool AcceptOnlyWellKnown = false;
static const bool TrustWellKnown = true;
static bool
isWellKnownProgId(const char *progid)
{
#ifdef NO_REGISTRY_AUTHORIZE
unsigned int i = 0;
if (!progid) {
return false;
}
while (WellKnownProgIds[i]) {
if (!strnicmp(WellKnownProgIds[i], progid, strlen(WellKnownProgIds[i])))
return true;
++i;
}
return false;
#else
return true;
#endif
}
static bool
isWellKnownClsId(const char *clsid)
{
#ifdef NO_REGISTRY_AUTHORIZE
unsigned int i = 0;
if (!clsid) {
return false;
}
while (WellKnownClsIds[i]) {
if (!strnicmp(WellKnownClsIds[i], clsid, strlen(WellKnownClsIds[i])))
return true;
++i;
}
return false;
#else
return true;
#endif
}
static LRESULT CALLBACK AxHostWinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
LRESULT result;
CAxHost *host = (CAxHost *)GetWindowLong(hWnd, GWL_USERDATA);
if (!host) {
return DefWindowProc(hWnd, msg, wParam, lParam);
}
switch (msg)
{
case WM_SETFOCUS:
case WM_KILLFOCUS:
case WM_SIZE:
if (host->Site) {
host->Site->OnDefWindowMessage(msg, wParam, lParam, &result);
return result;
}
else {
return DefWindowProc(hWnd, msg, wParam, lParam);
}
// Window being destroyed
case WM_DESTROY:
break;
default:
return DefWindowProc(hWnd, msg, wParam, lParam);
}
return true;
}
CAxHost::~CAxHost()
{
log(instance, 0, "AxHost.~AXHost: destroying the control...");
if (Window){
if (OldProc)
::SetWindowLong(Window, GWL_WNDPROC, (LONG)OldProc);
::SetWindowLong(Window, GWL_USERDATA, (LONG)NULL);
}
if (Sink) {
Sink->UnsubscribeFromEvents();
Sink->Release();
}
if (Site) {
Site->Detach();
Site->Release();
}
CoFreeUnusedLibraries();
}
CAxHost::CAxHost(NPP inst):
instance(inst),
ClsID(CLSID_NULL),
isValidClsID(false),
Sink(NULL),
Site(NULL),
Window(NULL),
OldProc(NULL),
Props(),
isKnown(false),
CodeBaseUrl(NULL)
{
}
void
CAxHost::setWindow(HWND win)
{
if (win != Window) {
if (win) {
// subclass window so we can intercept window messages and
// do our drawing to it
OldProc = (WNDPROC)::SetWindowLong(win, GWL_WNDPROC, (LONG)AxHostWinProc);
// associate window with our CAxHost object so we can access
// it in the window procedure
::SetWindowLong(win, GWL_USERDATA, (LONG)this);
}
else {
if (OldProc)
::SetWindowLong(Window, GWL_WNDPROC, (LONG)OldProc);
::SetWindowLong(Window, GWL_USERDATA, (LONG)NULL);
}
Window = win;
}
}
HWND
CAxHost::getWinfow()
{
return Window;
}
void
CAxHost::UpdateRect(RECT rcPos)
{
HRESULT hr = -1;
if (Site && Window) {
if (Site->GetParentWindow() == NULL) {
hr = Site->Attach(Window, rcPos, NULL);
if (FAILED(hr)) {
log(instance, 0, "AxHost.UpdateRect: failed to attach control");
}
}
else {
Site->SetPosition(rcPos);
}
// Ensure clipping on parent to keep child controls happy
::SetWindowLong(Window, GWL_STYLE, ::GetWindowLong(Window, GWL_STYLE) | WS_CLIPCHILDREN);
}
}
bool
CAxHost::verifyClsID(LPOLESTR oleClsID)
{
CRegKey keyExplorer;
if (ERROR_SUCCESS == keyExplorer.Open(HKEY_LOCAL_MACHINE,
_T("SOFTWARE\\Microsoft\\Internet Explorer\\ActiveX Compatibility"),
KEY_READ)) {
CRegKey keyCLSID;
if (ERROR_SUCCESS == keyCLSID.Open(keyExplorer, W2T(oleClsID), KEY_READ)) {
DWORD dwType = REG_DWORD;
DWORD dwFlags = 0;
DWORD dwBufSize = sizeof(dwFlags);
if (ERROR_SUCCESS == ::RegQueryValueEx(keyCLSID,
_T("Compatibility Flags"),
NULL,
&dwType,
(LPBYTE)
&dwFlags,
&dwBufSize)) {
// Flags for this reg key
const DWORD kKillBit = 0x00000400;
if (dwFlags & kKillBit) {
log(instance, 0, "AxHost.verifyClsID: the control is marked as unsafe by IE kill bits");
return false;
}
}
}
}
log(instance, 1, "AxHost.verifyClsID: verified successfully");
return true;
}
bool
CAxHost::setClsID(const char *clsid)
{
HRESULT hr = -1;
USES_CONVERSION;
LPOLESTR oleClsID = A2OLE(clsid);
if (isWellKnownClsId(clsid)) {
isKnown = true;
}
else if (AcceptOnlyWellKnown) {
log(instance, 0, "AxHost.setClsID: the requested CLSID is not on the Well Known list");
return false;
}
// Check the Internet Explorer list of vulnerable controls
if (oleClsID && verifyClsID(oleClsID)) {
hr = CLSIDFromString(oleClsID, &ClsID);
if (SUCCEEDED(hr) && !::IsEqualCLSID(ClsID, CLSID_NULL)) {
isValidClsID = true;
log(instance, 1, "AxHost.setClsID: CLSID %s set", clsid);
return true;
}
}
log(instance, 0, "AxHost.setClsID: failed to set the requested clsid");
return false;
}
void CAxHost::setCodeBaseUrl(LPCWSTR codeBaseUrl)
{
CodeBaseUrl = codeBaseUrl;
}
bool
CAxHost::setClsIDFromProgID(const char *progid)
{
HRESULT hr = -1;
CLSID clsid = CLSID_NULL;
USES_CONVERSION;
LPOLESTR oleClsID = NULL;
LPOLESTR oleProgID = A2OLE(progid);
if (AcceptOnlyWellKnown) {
if (isWellKnownProgId(progid)) {
isKnown = true;
}
else {
log(instance, 0, "AxHost.setClsIDFromProgID: the requested PROGID is not on the Well Known list");
return false;
}
}
hr = CLSIDFromProgID(oleProgID, &clsid);
if (FAILED(hr)) {
log(instance, 0, "AxHost.setClsIDFromProgID: could not resolve PROGID");
return false;
}
hr = StringFromCLSID(clsid, &oleClsID);
// Check the Internet Explorer list of vulnerable controls
if ( SUCCEEDED(hr)
&& oleClsID
&& verifyClsID(oleClsID)) {
ClsID = clsid;
if (!::IsEqualCLSID(ClsID, CLSID_NULL)) {
isValidClsID = true;
log(instance, 1, "AxHost.setClsIDFromProgID: PROGID %s resolved and set", progid);
return true;
}
}
log(instance, 0, "AxHost.setClsIDFromProgID: failed to set the resolved CLSID");
return false;
}
bool
CAxHost::hasValidClsID()
{
return isValidClsID;
}
bool
CAxHost::CreateControl(bool subscribeToEvents)
{
if (!isValidClsID) {
log(instance, 0, "AxHost.CreateControl: current location is not trusted");
return false;
}
// Create the control site
CControlSiteInstance::CreateInstance(&Site);
if (Site == NULL) {
log(instance, 0, "AxHost.CreateControl: CreateInstance failed");
return false;
}
Site->m_bSupportWindowlessActivation = false;
if (TrustWellKnown && isKnown) {
Site->SetSecurityPolicy(NULL);
Site->m_bSafeForScriptingObjectsOnly = false;
}
else {
Site->m_bSafeForScriptingObjectsOnly = true;
}
Site->AddRef();
// Create the object
HRESULT hr;
hr = Site->Create(ClsID, Props, CodeBaseUrl);
if (FAILED(hr)) {
LPSTR lpMsgBuf;
DWORD dw = GetLastError();
FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR) &lpMsgBuf,
0,
NULL );
log(instance, 0, lpMsgBuf);
log(instance, 0, "AxHost.CreateControl: failed to create site");
return false;
}
IUnknown *control = NULL;
Site->GetControlUnknown(&control);
if (!control) {
log(instance, 0, "AxHost.CreateControl: failed to create control (was it just downloaded?)");
return false;
}
// Create the event sink
CControlEventSinkInstance::CreateInstance(&Sink);
Sink->AddRef();
Sink->instance = instance;
hr = Sink->SubscribeToEvents(control);
control->Release();
if (FAILED(hr) && subscribeToEvents) {
LPSTR lpMsgBuf;
DWORD dw = GetLastError();
FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR) &lpMsgBuf,
0,
NULL );
log(instance, 0, lpMsgBuf);
log(instance, 0, "AxHost.CreateControl: SubscribeToEvents failed");
return false;
}
log(instance, 1, "AxHost.CreateControl: control created successfully");
return true;
}
bool
CAxHost::AddEventHandler(wchar_t *name, wchar_t *handler)
{
HRESULT hr;
DISPID id = 0;
USES_CONVERSION;
LPOLESTR oleName = name;
if (!Sink) {
log(instance, 0, "AxHost.AddEventHandler: no valid sink");
return false;
}
hr = Sink->m_spEventSinkTypeInfo->GetIDsOfNames(&oleName, 1, &id);
if (FAILED(hr)) {
log(instance, 0, "AxHost.AddEventHandler: GetIDsOfNames failed to resolve event name");
return false;
}
Sink->events[id] = handler;
log(instance, 1, "AxHost.AddEventHandler: handler %S set for event %S", handler, name);
return true;
}
int16
CAxHost::HandleEvent(void *event)
{
NPEvent *npEvent = (NPEvent *)event;
LRESULT result = 0;
if (!npEvent) {
return 0;
}
// forward all events to the hosted control
return (int16)Site->OnDefWindowMessage(npEvent->event, npEvent->wParam, npEvent->lParam, &result);
}
NPObject *
CAxHost::GetScriptableObject()
{
IUnknown *unk;
NPObject *obj = NPNFuncs.createobject(instance, &ScriptableNPClass);
Site->GetControlUnknown(&unk);
((Scriptable *)obj)->setControl(unk);
((Scriptable *)obj)->setInstance(instance);
return obj;
}
| 007slmg-ff-activex-host | ff-activex-host/ffactivex/axhost.cpp | C++ | lgpl | 11,705 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <algorithm>
#include <string>
#include "GenericNPObject.h"
static NPObject*
AllocateGenericNPObject(NPP npp, NPClass *aClass)
{
return new GenericNPObject(npp, false);
}
static NPObject*
AllocateMethodNPObject(NPP npp, NPClass *aClass)
{
return new GenericNPObject(npp, true);
}
static void
DeallocateGenericNPObject(NPObject *obj)
{
if (!obj) {
return;
}
GenericNPObject *m = (GenericNPObject *)obj;
delete m;
}
static void
InvalidateGenericNPObject(NPObject *obj)
{
if (!obj) {
return;
}
((GenericNPObject *)obj)->Invalidate();
}
NPClass GenericNPObjectClass = {
/* version */ NP_CLASS_STRUCT_VERSION,
/* allocate */ AllocateGenericNPObject,
/* deallocate */ DeallocateGenericNPObject,
/* invalidate */ InvalidateGenericNPObject,
/* hasMethod */ GenericNPObject::_HasMethod,
/* invoke */ GenericNPObject::_Invoke,
/* invokeDefault */ GenericNPObject::_InvokeDefault,
/* hasProperty */ GenericNPObject::_HasProperty,
/* getProperty */ GenericNPObject::_GetProperty,
/* setProperty */ GenericNPObject::_SetProperty,
/* removeProperty */ GenericNPObject::_RemoveProperty,
/* enumerate */ GenericNPObject::_Enumerate,
/* construct */ NULL
};
NPClass MethodNPObjectClass = {
/* version */ NP_CLASS_STRUCT_VERSION,
/* allocate */ AllocateMethodNPObject,
/* deallocate */ DeallocateGenericNPObject,
/* invalidate */ InvalidateGenericNPObject,
/* hasMethod */ GenericNPObject::_HasMethod,
/* invoke */ GenericNPObject::_Invoke,
/* invokeDefault */ GenericNPObject::_InvokeDefault,
/* hasProperty */ GenericNPObject::_HasProperty,
/* getProperty */ GenericNPObject::_GetProperty,
/* setProperty */ GenericNPObject::_SetProperty,
/* removeProperty */ GenericNPObject::_RemoveProperty,
/* enumerate */ GenericNPObject::_Enumerate,
/* construct */ NULL
};
// Some standard JavaScript methods
bool toString(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result) {
GenericNPObject *map = (GenericNPObject *)object;
if (!map || map->invalid) return false;
// no args expected or cared for...
std::string out;
std::vector<NPVariant>::iterator it;
for (it = map->numeric_mapper.begin(); it < map->numeric_mapper.end(); ++it) {
if (NPVARIANT_IS_VOID(*it)) {
out += ",";
}
else if (NPVARIANT_IS_NULL(*it)) {
out += ",";
}
else if (NPVARIANT_IS_BOOLEAN(*it)) {
if ((*it).value.boolValue) {
out += "true,";
}
else {
out += "false,";
}
}
else if (NPVARIANT_IS_INT32(*it)) {
char tmp[50];
memset(tmp, 0, sizeof(tmp));
_snprintf(tmp, 49, "%d,", (*it).value.intValue);
out += tmp;
}
else if (NPVARIANT_IS_DOUBLE(*it)) {
char tmp[50];
memset(tmp, 0, sizeof(tmp));
_snprintf(tmp, 49, "%f,", (*it).value.doubleValue);
out += tmp;
}
else if (NPVARIANT_IS_STRING(*it)) {
out += (*it).value.stringValue.UTF8Characters;
out += ",";
}
else if (NPVARIANT_IS_OBJECT(*it)) {
out += "[object],";
}
}
// calculate how much space we need
std::string::size_type size = out.length();
char *s = (char *)NPNFuncs.memalloc(size * sizeof(char));
if (NULL == s) {
return false;
}
memcpy(s, out.c_str(), size);
s[size - 1] = 0; // overwrite the last ","
STRINGZ_TO_NPVARIANT(s, (*result));
return true;
}
// Some helpers
static void free_numeric_element(NPVariant elem) {
NPNFuncs.releasevariantvalue(&elem);
}
static void free_alpha_element(std::pair<const char *, NPVariant> elem) {
NPNFuncs.releasevariantvalue(&(elem.second));
}
// And now the GenericNPObject implementation
GenericNPObject::GenericNPObject(NPP instance, bool isMethodObj):
invalid(false), defInvoker(NULL), defInvokerObject(NULL) {
NPVariant val;
INT32_TO_NPVARIANT(0, val);
immutables["length"] = val;
if (!isMethodObj) {
NPObject *obj = NULL;
obj = NPNFuncs.createobject(instance, &MethodNPObjectClass);
if (NULL == obj) {
throw NULL;
}
((GenericNPObject *)obj)->SetDefaultInvoker(&toString, this);
OBJECT_TO_NPVARIANT(obj, val);
immutables["toString"] = val;
}
}
GenericNPObject::~GenericNPObject() {
for_each(immutables.begin(), immutables.end(), free_alpha_element);
for_each(alpha_mapper.begin(), alpha_mapper.end(), free_alpha_element);
for_each(numeric_mapper.begin(), numeric_mapper.end(), free_numeric_element);
}
bool GenericNPObject::HasMethod(NPIdentifier name) {
if (invalid) return false;
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (immutables.count(key) > 0) {
if (NPVARIANT_IS_OBJECT(immutables[key])) {
return (NULL != immutables[key].value.objectValue->_class->invokeDefault);
}
}
else if (alpha_mapper.count(key) > 0) {
if (NPVARIANT_IS_OBJECT(alpha_mapper[key])) {
return (NULL != alpha_mapper[key].value.objectValue->_class->invokeDefault);
}
}
}
return false;
}
bool GenericNPObject::Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) {
if (invalid) return false;
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (immutables.count(key) > 0) {
if ( NPVARIANT_IS_OBJECT(immutables[key])
&& immutables[key].value.objectValue->_class->invokeDefault) {
return immutables[key].value.objectValue->_class->invokeDefault(immutables[key].value.objectValue, args, argCount, result);
}
}
else if (alpha_mapper.count(key) > 0) {
if ( NPVARIANT_IS_OBJECT(alpha_mapper[key])
&& alpha_mapper[key].value.objectValue->_class->invokeDefault) {
return alpha_mapper[key].value.objectValue->_class->invokeDefault(alpha_mapper[key].value.objectValue, args, argCount, result);
}
}
}
return true;
}
bool GenericNPObject::InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result) {
if (invalid) return false;
if (defInvoker) {
defInvoker(defInvokerObject, args, argCount, result);
}
return true;
}
// This method is also called before the JS engine attempts to add a new
// property, most likely it's trying to check that the key is supported.
// It only returns false if the string name was not found, or does not
// hold a callable object
bool GenericNPObject::HasProperty(NPIdentifier name) {
if (invalid) return false;
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (immutables.count(key) > 0) {
if (NPVARIANT_IS_OBJECT(immutables[key])) {
return (NULL == immutables[key].value.objectValue->_class->invokeDefault);
}
}
else if (alpha_mapper.count(key) > 0) {
if (NPVARIANT_IS_OBJECT(alpha_mapper[key])) {
return (NULL == alpha_mapper[key].value.objectValue->_class->invokeDefault);
}
}
return false;
}
return true;
}
static bool CopyNPVariant(NPVariant *dst, const NPVariant *src)
{
dst->type = src->type;
if (NPVARIANT_IS_STRING(*src)) {
NPUTF8 *str = (NPUTF8 *)NPNFuncs.memalloc((src->value.stringValue.UTF8Length + 1) * sizeof(NPUTF8));
if (NULL == str) {
return false;
}
dst->value.stringValue.UTF8Length = src->value.stringValue.UTF8Length;
memcpy(str, src->value.stringValue.UTF8Characters, src->value.stringValue.UTF8Length);
str[dst->value.stringValue.UTF8Length] = 0;
dst->value.stringValue.UTF8Characters = str;
}
else if (NPVARIANT_IS_OBJECT(*src)) {
NPNFuncs.retainobject(NPVARIANT_TO_OBJECT(*src));
dst->value.objectValue = src->value.objectValue;
}
else {
dst->value = src->value;
}
return true;
}
#define MIN(x, y) ((x) < (y)) ? (x) : (y)
bool GenericNPObject::GetProperty(NPIdentifier name, NPVariant *result) {
if (invalid) return false;
try {
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (immutables.count(key) > 0) {
if (!CopyNPVariant(result, &(immutables[key]))) {
return false;
}
}
else if (alpha_mapper.count(key) > 0) {
if (!CopyNPVariant(result, &(alpha_mapper[key]))) {
return false;
}
}
}
else {
// assume int...
unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name);
if (numeric_mapper.size() > key) {
if (!CopyNPVariant(result, &(numeric_mapper[key]))) {
return false;
}
}
}
}
catch (...) {
}
return true;
}
bool GenericNPObject::SetProperty(NPIdentifier name, const NPVariant *value) {
if (invalid) return false;
try {
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (immutables.count(key) > 0) {
// the key is already defined as immutable, check the new value type
if (value->type != immutables[key].type) {
return false;
}
// Seems ok, copy the new value
if (!CopyNPVariant(&(immutables[key]), value)) {
return false;
}
}
else if (!CopyNPVariant(&(alpha_mapper[key]), value)) {
return false;
}
}
else {
// assume int...
NPVariant var;
if (!CopyNPVariant(&var, value)) {
return false;
}
unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name);
if (key >= numeric_mapper.size()) {
// there's a gap we need to fill
NPVariant pad;
VOID_TO_NPVARIANT(pad);
numeric_mapper.insert(numeric_mapper.end(), key - numeric_mapper.size() + 1, pad);
}
numeric_mapper.at(key) = var;
NPVARIANT_TO_INT32(immutables["length"])++;
}
}
catch (...) {
}
return true;
}
bool GenericNPObject::RemoveProperty(NPIdentifier name) {
if (invalid) return false;
try {
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (alpha_mapper.count(key) > 0) {
NPNFuncs.releasevariantvalue(&(alpha_mapper[key]));
alpha_mapper.erase(key);
}
}
else {
// assume int...
unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name);
if (numeric_mapper.size() > key) {
NPNFuncs.releasevariantvalue(&(numeric_mapper[key]));
numeric_mapper.erase(numeric_mapper.begin() + key);
}
NPVARIANT_TO_INT32(immutables["length"])--;
}
}
catch (...) {
}
return true;
}
bool GenericNPObject::Enumerate(NPIdentifier **identifiers, uint32_t *identifierCount) {
if (invalid) return false;
try {
*identifiers = (NPIdentifier *)NPNFuncs.memalloc(sizeof(NPIdentifier) * numeric_mapper.size());
if (NULL == *identifiers) {
return false;
}
*identifierCount = 0;
std::vector<NPVariant>::iterator it;
unsigned int i = 0;
char str[10] = "";
for (it = numeric_mapper.begin(); it < numeric_mapper.end(); ++it, ++i) {
// skip empty (padding) elements
if (NPVARIANT_IS_VOID(*it)) continue;
_snprintf(str, sizeof(str), "%u", i);
(*identifiers)[(*identifierCount)++] = NPNFuncs.getstringidentifier(str);
}
}
catch (...) {
}
return true;
}
| 007slmg-ff-activex-host | ff-activex-host/ffactivex/GenericNPObject.cpp | C++ | lgpl | 12,906 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "scriptable.h"
static NPObject*
AllocateScriptable(NPP npp, NPClass *aClass)
{
return new Scriptable();
}
static void
DeallocateScriptable(NPObject *obj)
{
if (!obj) {
return;
}
Scriptable *s = (Scriptable *)obj;
delete s;
}
static void
InvalidateScriptable(NPObject *obj)
{
if (!obj) {
return;
}
((Scriptable *)obj)->Invalidate();
}
NPClass ScriptableNPClass = {
/* version */ NP_CLASS_STRUCT_VERSION,
/* allocate */ AllocateScriptable,
/* deallocate */ DeallocateScriptable,
/* invalidate */ InvalidateScriptable,
/* hasMethod */ Scriptable::_HasMethod,
/* invoke */ Scriptable::_Invoke,
/* invokeDefault */ NULL,
/* hasProperty */ Scriptable::_HasProperty,
/* getProperty */ Scriptable::_GetProperty,
/* setProperty */ Scriptable::_SetProperty,
/* removeProperty */ NULL,
/* enumerate */ NULL,
/* construct */ NULL
};
| 007slmg-ff-activex-host | ff-activex-host/ffactivex/scriptable.cpp | C++ | lgpl | 2,691 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// ffactivex.cpp : Defines the exported functions for the DLL application.
//
#include "ffactivex.h"
#include "common/stdafx.h"
#include "axhost.h"
#include "atlutil.h"
#include "authorize.h"
// A list of trusted domains
// Each domain name may start with a '*' to specify that sub domains are
// trusted as well
// Note that a '.' is not enforced after the '*'
static const char *TrustedLocations[] = {NULL};
static const unsigned int numTrustedLocations = 0;
static const char *LocalhostName = "localhost";
static const bool TrustLocalhost = true;
void *
ffax_calloc(unsigned int size)
{
void *ptr = NULL;
ptr = NPNFuncs.memalloc(size);
if (ptr) {
memset(ptr, 0, size);
}
return ptr;
}
void
ffax_free(void *ptr)
{
if (ptr)
NPNFuncs.memfree(ptr);
}
//
// Gecko API
//
static unsigned int log_level = 0;
static char *logger = NULL;
void
log(NPP instance, unsigned int level, char *message, ...)
{
NPVariant result;
NPVariant args;
NPObject *globalObj = NULL;
bool rc = false;
char *formatted = NULL;
char *new_formatted = NULL;
int buff_len = 0;
int size = 0;
va_list list;
if (!logger || (level > log_level)) {
return;
}
buff_len = strlen(message);
buff_len += buff_len / 10;
formatted = (char *)calloc(1, buff_len);
while (true) {
va_start(list, message);
size = vsnprintf_s(formatted, buff_len, _TRUNCATE, message, list);
va_end(list);
if (size > -1 && size < buff_len)
break;
buff_len *= 2;
new_formatted = (char *)realloc(formatted, buff_len);
if (NULL == new_formatted) {
free(formatted);
return;
}
formatted = new_formatted;
new_formatted = NULL;
}
NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj);
NPIdentifier handler = NPNFuncs.getstringidentifier(logger);
STRINGZ_TO_NPVARIANT(formatted, args);
bool success = NPNFuncs.invoke(instance, globalObj, handler, &args, 1, &result);
NPNFuncs.releasevariantvalue(&result);
NPNFuncs.releaseobject(globalObj);
free(formatted);
}
static bool
MatchURL2TrustedLocations(NPP instance, LPCTSTR matchUrl)
{
USES_CONVERSION;
bool rc = false;
CUrl url;
if (!numTrustedLocations) {
return true;
}
rc = url.CrackUrl(matchUrl, ATL_URL_DECODE);
if (!rc) {
log(instance, 0, "AxHost.MatchURL2TrustedLocations: failed to parse the current location URL");
return false;
}
if ( (url.GetScheme() == ATL_URL_SCHEME_FILE)
|| (!strncmp(LocalhostName, W2A(url.GetHostName()), strlen(LocalhostName)))){
return TrustLocalhost;
}
for (unsigned int i = 0; i < numTrustedLocations; ++i) {
if (TrustedLocations[i][0] == '*') {
// sub domains are trusted
unsigned int len = strlen(TrustedLocations[i]);
bool match = 0;
if (url.GetHostNameLength() < len) {
// can't be a match
continue;
}
--len; // skip the '*'
match = strncmp(W2A(url.GetHostName()) + (url.GetHostNameLength() - len), // anchor the comparison to the end of the domain name
TrustedLocations[i] + 1, // skip the '*'
len) == 0 ? true : false;
if (match) {
return true;
}
}
else if (!strncmp(W2A(url.GetHostName()), TrustedLocations[i], url.GetHostNameLength())) {
return true;
}
}
return false;
}
static bool
VerifySiteLock(NPP instance)
{
USES_CONVERSION;
NPObject *globalObj = NULL;
NPIdentifier identifier;
NPVariant varLocation;
NPVariant varHref;
bool rc = false;
// Get the window object.
NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj);
// Create a "location" identifier.
identifier = NPNFuncs.getstringidentifier("location");
// Get the location property from the window object (which is another object).
rc = NPNFuncs.getproperty(instance, globalObj, identifier, &varLocation);
NPNFuncs.releaseobject(globalObj);
if (!rc){
log(instance, 0, "AxHost.VerifySiteLock: could not get the location from the global object");
return false;
}
// Get a pointer to the "location" object.
NPObject *locationObj = varLocation.value.objectValue;
// Create a "href" identifier.
identifier = NPNFuncs.getstringidentifier("href");
// Get the location property from the location object.
rc = NPNFuncs.getproperty(instance, locationObj, identifier, &varHref);
NPNFuncs.releasevariantvalue(&varLocation);
if (!rc) {
log(instance, 0, "AxHost.VerifySiteLock: could not get the href from the location property");
return false;
}
rc = MatchURL2TrustedLocations(instance, A2W(varHref.value.stringValue.UTF8Characters));
NPNFuncs.releasevariantvalue(&varHref);
if (false == rc) {
log(instance, 0, "AxHost.VerifySiteLock: current location is not trusted");
}
return rc;
}
/*
* Create a new plugin instance, most probably through an embed/object HTML
* element.
*
* Any private data we want to keep for this instance can be saved into
* [instance->pdata].
* [saved] might hold information a previous instance that was invoked from the
* same URL has saved for us.
*/
NPError
NPP_New(NPMIMEType pluginType,
NPP instance, uint16 mode,
int16 argc, char *argn[],
char *argv[], NPSavedData *saved)
{
NPError rc = NPERR_NO_ERROR;
NPObject *browser = NULL;
CAxHost *host = NULL;
PropertyList events;
int16 i = 0;
USES_CONVERSION;
//_asm {int 3};
if (!instance || (0 == NPNFuncs.size)) {
return NPERR_INVALID_PARAM;
}
#ifdef NO_REGISTRY_AUTHORIZE
// Verify that we're running from a trusted location
if (!VerifySiteLock(instance)) {
return NPERR_GENERIC_ERROR;
}
#endif
instance->pdata = NULL;
#ifndef NO_REGISTRY_AUTHORIZE
if (!TestAuthorization (instance,
argc,
argn,
argv,
pluginType)) {
return NPERR_GENERIC_ERROR;
}
#endif
// TODO: Check the pluginType to make sure we're being called with the rigth MIME Type
do {
// Create a plugin instance, the actual control will be created once we
// are given a window handle
host = new CAxHost(instance);
if (!host) {
rc = NPERR_OUT_OF_MEMORY_ERROR;
log(instance, 0, "AxHost.NPP_New: failed to allocate memory for a new host");
break;
}
// Iterate over the arguments we've been passed
for (i = 0;
(i < argc) && (NPERR_NO_ERROR == rc);
++i) {
// search for any needed information: clsid, event handling directives, etc.
if (0 == strnicmp(argn[i], PARAM_CLSID, strlen(PARAM_CLSID))) {
// The class id of the control we are asked to load
host->setClsID(argv[i]);
}
else if (0 == strnicmp(argn[i], PARAM_PROGID, strlen(PARAM_PROGID))) {
// The class id of the control we are asked to load
host->setClsIDFromProgID(argv[i]);
}
else if (0 == strnicmp(argn[i], PARAM_DEBUG, strlen(PARAM_DEBUG))) {
// Logging verbosity
log_level = atoi(argv[i]);
log(instance, 0, "AxHost.NPP_New: debug level set to %d", log_level);
}
else if (0 == strnicmp(argn[i], PARAM_LOGGER, strlen(PARAM_LOGGER))) {
// Logger function
logger = strdup(argv[i]);
}
else if (0 == strnicmp(argn[i], PARAM_ONEVENT, strlen(PARAM_ONEVENT))) {
// A request to handle one of the activex's events in JS
events.AddOrReplaceNamedProperty(A2W(argn[i] + strlen(PARAM_ONEVENT)), CComVariant(A2W(argv[i])));
}
else if (0 == strnicmp(argn[i], PARAM_PARAM, strlen(PARAM_PARAM))) {
CComBSTR paramName = argn[i] + strlen(PARAM_PARAM);
CComBSTR paramValue(Utf8StringToBstr(argv[i], strlen(argv[i])));
// Check for existing params with the same name
BOOL bFound = FALSE;
for (unsigned long j = 0; j < host->Props.GetSize(); j++) {
if (wcscmp(host->Props.GetNameOf(j), (BSTR) paramName) == 0) {
bFound = TRUE;
break;
}
}
// If the parameter already exists, don't add it to the
// list again.
if (bFound) {
continue;
}
// Add named parameter to list
CComVariant v(paramValue);
host->Props.AddNamedProperty(paramName, v);
}
else if(0 == strnicmp(argn[i], PARAM_CODEBASEURL, strlen(PARAM_CODEBASEURL))) {
if (MatchURL2TrustedLocations(instance, A2W(argv[i]))) {
host->setCodeBaseUrl(A2W(argv[i]));
}
else {
log(instance, 0, "AxHost.NPP_New: codeBaseUrl contains an untrusted location");
}
}
}
if (NPERR_NO_ERROR != rc)
break;
// Make sure we have all the information we need to initialize a new instance
if (!host->hasValidClsID()) {
rc = NPERR_INVALID_PARAM;
log(instance, 0, "AxHost.NPP_New: no valid CLSID or PROGID");
break;
}
instance->pdata = host;
// if no events were requested, don't fail if subscribing fails
if (!host->CreateControl(events.GetSize() ? true : false)) {
rc = NPERR_GENERIC_ERROR;
log(instance, 0, "AxHost.NPP_New: failed to create the control");
break;
}
for (unsigned int j = 0; j < events.GetSize(); j++) {
if (!host->AddEventHandler(events.GetNameOf(j), events.GetValueOf(j)->bstrVal)) {
//rc = NPERR_GENERIC_ERROR;
//break;
}
}
if (NPERR_NO_ERROR != rc)
break;
} while (0);
if (NPERR_NO_ERROR != rc) {
delete host;
}
return rc;
}
/*
* Destroy an existing plugin instance.
*
* [save] can be used to save information for a future instance of our plugin
* that'll be invoked by the same URL.
*/
NPError
NPP_Destroy(NPP instance, NPSavedData **save)
{
// _asm {int 3};
if (!instance || !instance->pdata) {
return NPERR_INVALID_PARAM;
}
log(instance, 0, "NPP_Destroy: destroying the control...");
CAxHost *host = (CAxHost *)instance->pdata;
delete host;
instance->pdata = NULL;
return NPERR_NO_ERROR;
}
/*
* Sets an instance's window parameters.
*/
NPError
NPP_SetWindow(NPP instance, NPWindow *window)
{
CAxHost *host = NULL;
RECT rcPos;
if (!instance || !instance->pdata) {
return NPERR_INVALID_PARAM;
}
host = (CAxHost *)instance->pdata;
host->setWindow((HWND)window->window);
rcPos.left = 0;
rcPos.top = 0;
rcPos.right = window->width;
rcPos.bottom = window->height;
host->UpdateRect(rcPos);
return NPERR_NO_ERROR;
}
| 007slmg-ff-activex-host | ff-activex-host/ffactivex/ffactivex.cpp | C++ | lgpl | 12,205 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <atlbase.h>
#include <atlsafe.h>
#include <npapi.h>
#include <npfunctions.h>
#include <prtypes.h>
#include <npruntime.h>
#include "scriptable.h"
#include "GenericNPObject.h"
#include "variants.h"
extern NPNetscapeFuncs NPNFuncs;
BSTR
Utf8StringToBstr(LPCSTR szStr, int iSize)
{
BSTR bstrVal;
// Chars required for string
int iReq = 0;
if (iSize > 0) {
if ((iReq = MultiByteToWideChar(CP_UTF8, 0, szStr, iSize, 0, 0)) == 0) {
return (0);
}
}
// Account for terminating 0.
if (iReq != -1) {
++iReq;
}
if ((bstrVal = ::SysAllocStringLen(0, iReq)) == 0) {
return (0);
}
memset(bstrVal, 0, iReq * sizeof(wchar_t));
if (iSize > 0) {
// Convert into the buffer.
if (MultiByteToWideChar(CP_UTF8, 0, szStr, iSize, bstrVal, iReq) == 0) {
::SysFreeString(bstrVal);
return 0;
}
}
return (bstrVal);
}
void
BSTR2NPVar(BSTR bstr, NPVariant *npvar, NPP instance)
{
USES_CONVERSION;
char *npStr = NULL;
size_t sourceLen;
size_t bytesNeeded;
sourceLen = lstrlenW(bstr);
bytesNeeded = WideCharToMultiByte(CP_UTF8,
0,
bstr,
sourceLen,
NULL,
0,
NULL,
NULL);
bytesNeeded += 1;
// complete lack of documentation on Mozilla's part here, I have no
// idea how this string is supposed to be freed
npStr = (char *)NPNFuncs.memalloc(bytesNeeded);
if (npStr) {
memset(npStr, 0, bytesNeeded);
WideCharToMultiByte(CP_UTF8,
0,
bstr,
sourceLen,
npStr,
bytesNeeded - 1,
NULL,
NULL);
STRINGZ_TO_NPVARIANT(npStr, (*npvar));
}
else {
STRINGZ_TO_NPVARIANT(NULL, (*npvar));
}
}
void
Dispatch2NPVar(IDispatch *disp, NPVariant *npvar, NPP instance)
{
NPObject *obj = NULL;
obj = NPNFuncs.createobject(instance, &ScriptableNPClass);
((Scriptable *)obj)->setControl(disp);
((Scriptable *)obj)->setInstance(instance);
OBJECT_TO_NPVARIANT(obj, (*npvar));
}
void
Unknown2NPVar(IUnknown *unk, NPVariant *npvar, NPP instance)
{
NPObject *obj = NULL;
obj = NPNFuncs.createobject(instance, &ScriptableNPClass);
((Scriptable *)obj)->setControl(unk);
((Scriptable *)obj)->setInstance(instance);
OBJECT_TO_NPVARIANT(obj, (*npvar));
}
NPObject *
SafeArray2NPObject(SAFEARRAY *parray, unsigned short dim, unsigned long *pindices, NPP instance)
{
unsigned long *indices = pindices;
NPObject *obj = NULL;
bool rc = true;
if (!parray || !instance) {
return NULL;
}
obj = NPNFuncs.createobject(instance, &GenericNPObjectClass);
if (NULL == obj) {
return NULL;
}
do {
if (NULL == indices) {
// just getting started
SafeArrayLock(parray);
indices = (unsigned long *)calloc(1, parray->cDims * sizeof(unsigned long));
if (NULL == indices) {
rc = false;
break;
}
}
NPIdentifier id = NULL;
NPVariant val;
VOID_TO_NPVARIANT(val);
for(indices[dim] = 0; indices[dim] < parray->rgsabound[dim].cElements; indices[dim]++) {
if (dim == (parray->cDims - 1)) {
// single dimension (or the bottom of the recursion)
if (parray->fFeatures & FADF_VARIANT) {
VARIANT variant;
VariantInit(&variant);
if(FAILED(SafeArrayGetElement(parray, (long *)indices, &variant))) {
rc = false;
break;
}
Variant2NPVar(&variant, &val, instance);
VariantClear(&variant);
}
else if (parray->fFeatures & FADF_BSTR) {
BSTR bstr;
if(FAILED(SafeArrayGetElement(parray, (long *)indices, &bstr))) {
rc = false;
break;
}
BSTR2NPVar(bstr, &val, instance);
}
else if (parray->fFeatures & FADF_DISPATCH) {
IDispatch *disp;
if(FAILED(SafeArrayGetElement(parray, (long *)indices, &disp))) {
rc = false;
break;
}
Dispatch2NPVar(disp, &val, instance);
}
else if (parray->fFeatures & FADF_UNKNOWN) {
IUnknown *unk;
if(FAILED(SafeArrayGetElement(parray, (long *)indices, &unk))) {
rc = false;
break;
}
Unknown2NPVar(unk, &val, instance);
}
}
else {
// recurse
NPObject *o = SafeArray2NPObject(parray, dim + 1, indices, instance);
if (NULL == o) {
rc = false;
break;
}
OBJECT_TO_NPVARIANT(o, val);
}
id = NPNFuncs.getintidentifier(parray->rgsabound[dim].lLbound + indices[dim]);
// setproperty will call retainobject or copy the internal string, we should
// release variant
NPNFuncs.setproperty(instance, obj, id, &val);
NPNFuncs.releasevariantvalue(&val);
VOID_TO_NPVARIANT(val);
}
} while (0);
if (false == rc) {
if (!pindices && indices) {
free(indices);
indices = NULL;
SafeArrayUnlock(parray);
}
if (obj) {
NPNFuncs.releaseobject(obj);
obj = NULL;
}
}
return obj;
}
#define GETVALUE(var, val) (((var->vt) & VT_BYREF) ? *(var->p##val) : (var->val))
void
Variant2NPVar(const VARIANT *var, NPVariant *npvar, NPP instance)
{
NPObject *obj = NULL;
SAFEARRAY *parray = NULL;
if (!var || !npvar) {
return;
}
VOID_TO_NPVARIANT(*npvar);
switch (var->vt & ~VT_BYREF) {
case VT_EMPTY:
VOID_TO_NPVARIANT((*npvar));
break;
case VT_NULL:
NULL_TO_NPVARIANT((*npvar));
break;
case VT_LPSTR:
// not sure it can even appear in a VARIANT, but...
STRINGZ_TO_NPVARIANT(var->pcVal, (*npvar));
break;
case VT_BSTR:
BSTR2NPVar(GETVALUE(var, bstrVal), npvar, instance);
break;
case VT_I1:
INT32_TO_NPVARIANT((int32)GETVALUE(var, cVal), (*npvar));
break;
case VT_I2:
INT32_TO_NPVARIANT((int32)GETVALUE(var, iVal), (*npvar));
break;
case VT_I4:
INT32_TO_NPVARIANT((int32)GETVALUE(var, lVal), (*npvar));
break;
case VT_UI1:
INT32_TO_NPVARIANT((int32)GETVALUE(var, bVal), (*npvar));
break;
case VT_UI2:
INT32_TO_NPVARIANT((int32)GETVALUE(var, uiVal), (*npvar));
break;
case VT_UI4:
INT32_TO_NPVARIANT((int32)GETVALUE(var, ulVal), (*npvar));
break;
case VT_BOOL:
BOOLEAN_TO_NPVARIANT((GETVALUE(var, boolVal) == VARIANT_TRUE) ? true : false, (*npvar));
break;
case VT_R4:
DOUBLE_TO_NPVARIANT((double)GETVALUE(var, fltVal), (*npvar));
break;
case VT_R8:
DOUBLE_TO_NPVARIANT(GETVALUE(var, dblVal), (*npvar));
break;
case VT_DISPATCH:
Dispatch2NPVar(GETVALUE(var, pdispVal), npvar, instance);
break;
case VT_UNKNOWN:
Unknown2NPVar(GETVALUE(var, punkVal), npvar, instance);
break;
case VT_CY:
DOUBLE_TO_NPVARIANT((double)GETVALUE(var, cyVal).int64 / 10000, (*npvar));
break;
case VT_DATE:
BSTR bstrVal;
VarBstrFromDate(GETVALUE(var, date), 0, 0, &bstrVal);
BSTR2NPVar(bstrVal, npvar, instance);
break;
default:
if (var->vt & VT_ARRAY) {
obj = SafeArray2NPObject(GETVALUE(var, parray), 0, NULL, instance);
OBJECT_TO_NPVARIANT(obj, (*npvar));
}
break;
}
}
#undef GETVALUE
void
NPVar2Variant(const NPVariant *npvar, VARIANT *var, NPP instance)
{
USES_CONVERSION;
if (!var || !npvar) {
return;
}
switch (npvar->type) {
case NPVariantType_Void:
var->vt = VT_VOID;
var->ulVal = 0;
break;
case NPVariantType_Null:
var->vt = VT_PTR;
var->byref = NULL;
break;
case NPVariantType_Bool:
var->vt = VT_BOOL;
var->ulVal = npvar->value.boolValue;
break;
case NPVariantType_Int32:
var->vt = VT_UI4;
var->ulVal = npvar->value.intValue;
break;
case NPVariantType_Double:
var->vt = VT_R8;
var->dblVal = npvar->value.doubleValue;
break;
case NPVariantType_String:
var->vt = VT_BSTR;
var->bstrVal = Utf8StringToBstr(npvar->value.stringValue.UTF8Characters, npvar->value.stringValue.UTF8Length);
break;
case NPVariantType_Object:
NPIdentifier *identifiers = NULL;
uint32_t identifierCount = 0;
NPObject *object = NPVARIANT_TO_OBJECT(*npvar);
if (NPNFuncs.enumerate(instance, object, &identifiers, &identifierCount)) {
CComSafeArray<VARIANT> variants;
for (uint32_t index = 0; index < identifierCount; ++index) {
NPVariant npVariant;
if (NPNFuncs.getproperty(instance, object, identifiers[index], &npVariant)) {
if (npVariant.type != NPVariantType_Object) {
CComVariant variant;
NPVar2Variant(&npVariant, &variant, instance);
variants.Add(variant);
}
NPNFuncs.releasevariantvalue(&npVariant);
}
}
NPNFuncs.memfree(identifiers);
*reinterpret_cast<CComVariant*>(var) = variants;
}
else {
var->vt = VT_VOID;
var->ulVal = 0;
}
break;
}
}
| 007slmg-ff-activex-host | ff-activex-host/ffactivex/variants.cpp | C++ | lgpl | 10,569 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
void Variant2NPVar(const VARIANT *var, NPVariant *npvar, NPP instance);
void NPVar2Variant(const NPVariant *npvar, VARIANT *var, NPP instance);
BSTR Utf8StringToBstr(LPCSTR szStr, int iSize);
| 007slmg-ff-activex-host | ff-activex-host/ffactivex/variants.h | C | lgpl | 1,904 |
// stdafx.cpp : source file that includes just the standard includes
// ffactivex.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| 007slmg-ff-activex-host | ff-activex-host/ffactivex/stdafx.cpp | C++ | lgpl | 296 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is RSJ Software GmbH code.
*
* The Initial Developer of the Original Code is
* RSJ Software GmbH.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributors:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <stdio.h>
#include <windows.h>
#include <winbase.h>
// ----------------------------------------------------------------------------
int main (int ArgC,
char *ArgV[])
{
const char *sourceName;
const char *targetName;
HANDLE targetHandle;
void *versionPtr;
DWORD versionLen;
int lastError;
int ret = 0;
if (ArgC < 3) {
fprintf(stderr,
"Usage: %s <source> <target>\n",
ArgV[0]);
exit (1);
}
sourceName = ArgV[1];
targetName = ArgV[2];
if ((versionLen = GetFileVersionInfoSize(sourceName,
NULL)) == 0) {
fprintf(stderr,
"Could not retrieve version len from %s\n",
sourceName);
exit (2);
}
if ((versionPtr = calloc(1,
versionLen)) == NULL) {
fprintf(stderr,
"Error allocating temp memory\n");
exit (3);
}
if (!GetFileVersionInfo(sourceName,
NULL,
versionLen,
versionPtr)) {
fprintf(stderr,
"Could not retrieve version info from %s\n",
sourceName);
exit (4);
}
if ((targetHandle = BeginUpdateResource(targetName,
FALSE)) == INVALID_HANDLE_VALUE) {
fprintf(stderr,
"Could not begin update of %s\n",
targetName);
free(versionPtr);
exit (5);
}
if (!UpdateResource(targetHandle,
RT_VERSION,
MAKEINTRESOURCE(VS_VERSION_INFO),
MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL),
versionPtr,
versionLen)) {
lastError = GetLastError();
fprintf(stderr,
"Error %d updating resource\n",
lastError);
ret = 6;
}
if (!EndUpdateResource(targetHandle,
FALSE)) {
fprintf(stderr,
"Error finishing update\n");
ret = 7;
}
free(versionPtr);
return (ret);
}
| 007slmg-ff-activex-host | ff-activex-host/transver/transver.cpp | C++ | lgpl | 3,963 |
setlocal
cd install
"c:\Program Files\Inno Setup 5\iscc" /O../dist /dxversion=%1 /dxbasepath=../ ffactivex.iss
cd ..
copy dist\ffactivex-setup.exe dist\ffactivex-setup-%1.exe
endlocal
| 007slmg-ff-activex-host | ff-activex-host/tool/mkinst.cmd | Batchfile | lgpl | 200 |
#ifndef MyAppName
#define MyAppName "Firefox ActiveX Plugin"
#endif
#ifndef MyAppURL
#define MyAppURL "http://code.google.com/p/ff-activex-host/"
#endif
#ifndef xversion
#define xversion "r37"
#endif
#ifndef xbasepath
#define xbasepath "c:\src\ff-activex-host\ff-activex-host\"
#endif
[Setup]
AppId={{97F2985C-B74A-4672-960E-E3769AE5657A}}
AppName={#MyAppName}
AppVerName={#MyAppName} {#xversion}
AppSupportURL={#MyAppURL}
AppUpdatesURL={#MyAppURL}
DefaultDirName={pf}\{#MyAppName}
DefaultGroupName={#MyAppName}
OutputBaseFilename=ffactivex-setup
Compression=lzma
SolidCompression=yes
InternalCompressLevel=ultra
ArchitecturesInstallIn64BitMode=x64 ia64
#include "ffactivex.inc"
[Registry]
Root: HKLM32; Subkey: "SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes\application/x-itst-activex\clsid\*"; ValueType: string; ValueName: "*"; ValueData: true;
Root: HKLM32; Subkey: "SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes\application/x-itst-activex\progid\*"; ValueType: string; ValueName: "*"; ValueData: true;
Root: HKLM32; Subkey: "SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes\application/x-itst-activex\codeBaseUrl\*"; ValueType: string; ValueName: "*"; ValueData: true;
[Files]
Source: {#xbasepath}\Release\transver.exe; DestDir: {app}; DestName: npffax.dll; Flags: overwritereadonly restartreplace uninsrestartdelete
| 007slmg-ff-activex-host | ff-activex-host/install/ffactivex.iss | Inno Setup | lgpl | 1,415 |
[Files]
Source: {#xbasepath}\Release\npffax.dll; DestDir: {app}; DestName: npffax.dll; Flags: overwritereadonly restartreplace uninsrestartdelete
[Registry]
Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; Flags: uninsdeletekey
Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; ValueType: string; ValueName: Description; ValueData: {#MyAppName} {#xversion}
Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; ValueType: string; ValueName: ProductName; ValueData: {#MyAppName} {#xversion}
Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; ValueType: string; ValueName: Path; ValueData: {app}\npffax.dll
Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; ValueType: string; ValueName: Version; ValueData: {#xversion}
Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes
Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes; ValueType: string; ValueName: Dummy; ValueData: {#xversion}
Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes\application/x-itst-activex
Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes\application/x-itst-activex; ValueType: string; ValueName: "Dummy"; ValueData: "{#xversion}" | 007slmg-ff-activex-host | ff-activex-host/install/ffactivex.inc | C++ | lgpl | 1,366 |
<html>
<head>
</head>
<body>
<script language="JavaScript">
function Test() {
var result = plugin.invoke("<QueryStatus />");
alert(result);
}
/* instantiate the plugin */
var plugin = document.createElement("object");
plugin.setAttribute("type", "application/x-itst-activex");
plugin.setAttribute("progid", "prodown.GenRSJ");
document.body.appendChild(plugin);
window.setTimeout("Test()", 100);
</script>
<button onclick="Test()">Test</button>
</body>
</html> | 007slmg-ff-activex-host | ff-activex-host/test.html | HTML | lgpl | 571 |
# Go support for Protocol Buffers - Google's data interchange format
#
# Copyright 2010 The Go Authors. All rights reserved.
# http://code.google.com/p/goprotobuf/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
all: install
install:
go install ./proto
go install ./protoc-gen-go
test:
go test ./proto
make -C protoc-gen-go/testdata test
clean:
go clean ./...
nuke:
go clean -i ./...
regenerate:
make -C protoc-gen-go/descriptor regenerate
make -C protoc-gen-go/plugin regenerate
make -C proto/testdata regenerate
| 109609524-goprotobuf | Makefile | Makefile | bsd | 1,958 |
# Go support for Protocol Buffers - Google's data interchange format
#
# Copyright 2010 The Go Authors. All rights reserved.
# http://code.google.com/p/goprotobuf/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
include $(GOROOT)/src/Make.cmd
test:
cd testdata && make test
| 109609524-goprotobuf | protoc-gen-go/Makefile | Makefile | bsd | 1,705 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/*
A plugin for the Google protocol buffer compiler to generate Go code.
This plugin takes no options and the protocol buffer file syntax does
not yet define any options for Go, so program does no option evaluation.
That may change.
*/
package main
import (
"io/ioutil"
"os"
"code.google.com/p/goprotobuf/proto"
"code.google.com/p/goprotobuf/protoc-gen-go/generator"
)
func main() {
// Begin by allocating a generator. The request and response structures are stored there
// so we can do error handling easily - the response structure contains the field to
// report failure.
g := generator.New()
data, err := ioutil.ReadAll(os.Stdin)
if err != nil {
g.Error(err, "reading input")
}
if err := proto.Unmarshal(data, g.Request); err != nil {
g.Error(err, "parsing input proto")
}
if len(g.Request.FileToGenerate) == 0 {
g.Fail("no files to generate")
}
g.CommandLineParameters(g.Request.GetParameter())
// Create a wrapped version of the Descriptors and EnumDescriptors that
// point to the file that defines them.
g.WrapTypes()
g.SetPackageNames()
g.BuildTypeNameMap()
g.GenerateAllFiles()
// Send back the results.
data, err = proto.Marshal(g.Response)
if err != nil {
g.Error(err, "failed to marshal output proto")
}
_, err = os.Stdout.Write(data)
if err != nil {
g.Error(err, "failed to write output proto")
}
}
| 109609524-goprotobuf | protoc-gen-go/main.go | Go | bsd | 3,041 |
# Go support for Protocol Buffers - Google's data interchange format
#
# Copyright 2010 The Go Authors. All rights reserved.
# http://code.google.com/p/goprotobuf/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
include $(GOROOT)/src/Make.inc
TARG=code.google.com/p/goprotobuf/compiler/generator
GOFILES=\
generator.go\
DEPS=../descriptor ../plugin ../../proto
include $(GOROOT)/src/Make.pkg
| 109609524-goprotobuf | protoc-gen-go/generator/Makefile | Makefile | bsd | 1,825 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/*
The code generator for the plugin for the Google protocol buffer compiler.
It generates Go code from the protocol buffer description files read by the
main routine.
*/
package generator
import (
"bytes"
"fmt"
"go/parser"
"go/printer"
"go/token"
"log"
"os"
"path"
"strconv"
"strings"
"unicode"
"unicode/utf8"
"code.google.com/p/goprotobuf/proto"
"code.google.com/p/goprotobuf/protoc-gen-go/descriptor"
plugin "code.google.com/p/goprotobuf/protoc-gen-go/plugin"
)
// A Plugin provides functionality to add to the output during Go code generation,
// such as to produce RPC stubs.
type Plugin interface {
// Name identifies the plugin.
Name() string
// Init is called once after data structures are built but before
// code generation begins.
Init(g *Generator)
// Generate produces the code generated by the plugin for this file,
// except for the imports, by calling the generator's methods P, In, and Out.
Generate(file *FileDescriptor)
// GenerateImports produces the import declarations for this file.
// It is called after Generate.
GenerateImports(file *FileDescriptor)
}
var plugins []Plugin
// RegisterPlugin installs a (second-order) plugin to be run when the Go output is generated.
// It is typically called during initialization.
func RegisterPlugin(p Plugin) {
plugins = append(plugins, p)
}
// Each type we import as a protocol buffer (other than FileDescriptorProto) needs
// a pointer to the FileDescriptorProto that represents it. These types achieve that
// wrapping by placing each Proto inside a struct with the pointer to its File. The
// structs have the same names as their contents, with "Proto" removed.
// FileDescriptor is used to store the things that it points to.
// The file and package name method are common to messages and enums.
type common struct {
file *descriptor.FileDescriptorProto // File this object comes from.
}
// PackageName is name in the package clause in the generated file.
func (c *common) PackageName() string { return uniquePackageOf(c.file) }
func (c *common) File() *descriptor.FileDescriptorProto { return c.file }
// Descriptor represents a protocol buffer message.
type Descriptor struct {
common
*descriptor.DescriptorProto
parent *Descriptor // The containing message, if any.
nested []*Descriptor // Inner messages, if any.
ext []*ExtensionDescriptor // Extensions, if any.
typename []string // Cached typename vector.
index int // The index into the container, whether the file or another message.
path string // The SourceCodeInfo path as comma-separated integers.
group bool
}
// TypeName returns the elements of the dotted type name.
// The package name is not part of this name.
func (d *Descriptor) TypeName() []string {
if d.typename != nil {
return d.typename
}
n := 0
for parent := d; parent != nil; parent = parent.parent {
n++
}
s := make([]string, n, n)
for parent := d; parent != nil; parent = parent.parent {
n--
s[n] = parent.GetName()
}
d.typename = s
return s
}
// EnumDescriptor describes an enum. If it's at top level, its parent will be nil.
// Otherwise it will be the descriptor of the message in which it is defined.
type EnumDescriptor struct {
common
*descriptor.EnumDescriptorProto
parent *Descriptor // The containing message, if any.
typename []string // Cached typename vector.
index int // The index into the container, whether the file or a message.
path string // The SourceCodeInfo path as comma-separated integers.
}
// TypeName returns the elements of the dotted type name.
// The package name is not part of this name.
func (e *EnumDescriptor) TypeName() (s []string) {
if e.typename != nil {
return e.typename
}
name := e.GetName()
if e.parent == nil {
s = make([]string, 1)
} else {
pname := e.parent.TypeName()
s = make([]string, len(pname)+1)
copy(s, pname)
}
s[len(s)-1] = name
e.typename = s
return s
}
// Everything but the last element of the full type name, CamelCased.
// The values of type Foo.Bar are call Foo_value1... not Foo_Bar_value1... .
func (e *EnumDescriptor) prefix() string {
if e.parent == nil {
// If the enum is not part of a message, the prefix is just the type name.
return CamelCase(*e.Name) + "_"
}
typeName := e.TypeName()
return CamelCaseSlice(typeName[0:len(typeName)-1]) + "_"
}
// The integer value of the named constant in this enumerated type.
func (e *EnumDescriptor) integerValueAsString(name string) string {
for _, c := range e.Value {
if c.GetName() == name {
return fmt.Sprint(c.GetNumber())
}
}
log.Fatal("cannot find value for enum constant")
return ""
}
// ExtensionDescriptor describes an extension. If it's at top level, its parent will be nil.
// Otherwise it will be the descriptor of the message in which it is defined.
type ExtensionDescriptor struct {
common
*descriptor.FieldDescriptorProto
parent *Descriptor // The containing message, if any.
}
// TypeName returns the elements of the dotted type name.
// The package name is not part of this name.
func (e *ExtensionDescriptor) TypeName() (s []string) {
name := e.GetName()
if e.parent == nil {
// top-level extension
s = make([]string, 1)
} else {
pname := e.parent.TypeName()
s = make([]string, len(pname)+1)
copy(s, pname)
}
s[len(s)-1] = name
return s
}
// DescName returns the variable name used for the generated descriptor.
func (e *ExtensionDescriptor) DescName() string {
// The full type name.
typeName := e.TypeName()
// Each scope of the extension is individually CamelCased, and all are joined with "_" with an "E_" prefix.
for i, s := range typeName {
typeName[i] = CamelCase(s)
}
return "E_" + strings.Join(typeName, "_")
}
// ImportedDescriptor describes a type that has been publicly imported from another file.
type ImportedDescriptor struct {
common
o Object
}
func (id *ImportedDescriptor) TypeName() []string { return id.o.TypeName() }
// FileDescriptor describes an protocol buffer descriptor file (.proto).
// It includes slices of all the messages and enums defined within it.
// Those slices are constructed by WrapTypes.
type FileDescriptor struct {
*descriptor.FileDescriptorProto
desc []*Descriptor // All the messages defined in this file.
enum []*EnumDescriptor // All the enums defined in this file.
ext []*ExtensionDescriptor // All the top-level extensions defined in this file.
imp []*ImportedDescriptor // All types defined in files publicly imported by this file.
// Comments, stored as a map of path (comma-separated integers) to the comment.
comments map[string]*descriptor.SourceCodeInfo_Location
// The full list of symbols that are exported,
// as a map from the exported object to its symbols.
// This is used for supporting public imports.
exported map[Object][]symbol
index int // The index of this file in the list of files to generate code for
}
// PackageName is the package name we'll use in the generated code to refer to this file.
func (d *FileDescriptor) PackageName() string { return uniquePackageOf(d.FileDescriptorProto) }
// goPackageName returns the Go package name to use in the
// generated Go file. The result explicit reports whether the name
// came from an option go_package statement. If explicit is false,
// the name was derived from the protocol buffer's package statement
// or the input file name.
func (d *FileDescriptor) goPackageName() (name string, explicit bool) {
// Does the file have a "go_package" option?
if opts := d.Options; opts != nil {
if pkg := opts.GetGoPackage(); pkg != "" {
return pkg, true
}
}
// Does the file have a package clause?
if pkg := d.GetPackage(); pkg != "" {
return pkg, false
}
// Use the file base name.
return baseName(d.GetName()), false
}
func (d *FileDescriptor) addExport(obj Object, sym symbol) {
d.exported[obj] = append(d.exported[obj], sym)
}
// symbol is an interface representing an exported Go symbol.
type symbol interface {
// GenerateAlias should generate an appropriate alias
// for the symbol from the named package.
GenerateAlias(g *Generator, pkg string)
}
type messageSymbol struct {
sym string
hasExtensions, isMessageSet bool
getters []getterSymbol
}
type getterSymbol struct {
name string
typ string
typeName string // canonical name in proto world; empty for proto.Message and similar
genType bool // whether typ is a generated type (message/group/enum)
}
func (ms *messageSymbol) GenerateAlias(g *Generator, pkg string) {
remoteSym := pkg + "." + ms.sym
g.P("type ", ms.sym, " ", remoteSym)
g.P("func (m *", ms.sym, ") Reset() { (*", remoteSym, ")(m).Reset() }")
g.P("func (m *", ms.sym, ") String() string { return (*", remoteSym, ")(m).String() }")
g.P("func (*", ms.sym, ") ProtoMessage() {}")
if ms.hasExtensions {
g.P("func (*", ms.sym, ") ExtensionRangeArray() []", g.Pkg["proto"], ".ExtensionRange ",
"{ return (*", remoteSym, ")(nil).ExtensionRangeArray() }")
g.P("func (m *", ms.sym, ") ExtensionMap() map[int32]", g.Pkg["proto"], ".Extension ",
"{ return (*", remoteSym, ")(m).ExtensionMap() }")
if ms.isMessageSet {
g.P("func (m *", ms.sym, ") Marshal() ([]byte, error) ",
"{ return (*", remoteSym, ")(m).Marshal() }")
g.P("func (m *", ms.sym, ") Unmarshal(buf []byte) error ",
"{ return (*", remoteSym, ")(m).Unmarshal(buf) }")
}
}
for _, get := range ms.getters {
if get.typeName != "" {
g.RecordTypeUse(get.typeName)
}
typ := get.typ
val := "(*" + remoteSym + ")(m)." + get.name + "()"
if get.genType {
// typ will be "*pkg.T" (message/group) or "pkg.T" (enum).
// Either of those might have a "[]" prefix if it is repeated.
// Drop the package qualifier since we have hoisted the type into this package.
rep := strings.HasPrefix(typ, "[]")
if rep {
typ = typ[2:]
}
star := typ[0] == '*'
typ = typ[strings.Index(typ, ".")+1:]
if star {
typ = "*" + typ
}
if rep {
// Go does not permit conversion between slice types where both
// element types are named. That means we need to generate a bit
// of code in this situation.
// typ is the element type.
// val is the expression to get the slice from the imported type.
ctyp := typ // conversion type expression; "Foo" or "(*Foo)"
if star {
ctyp = "(" + typ + ")"
}
g.P("func (m *", ms.sym, ") ", get.name, "() []", typ, " {")
g.In()
g.P("o := ", val)
g.P("if o == nil {")
g.In()
g.P("return nil")
g.Out()
g.P("}")
g.P("s := make([]", typ, ", len(o))")
g.P("for i, x := range o {")
g.In()
g.P("s[i] = ", ctyp, "(x)")
g.Out()
g.P("}")
g.P("return s")
g.Out()
g.P("}")
continue
}
// Convert imported type into the forwarding type.
val = "(" + typ + ")(" + val + ")"
}
g.P("func (m *", ms.sym, ") ", get.name, "() ", typ, " { return ", val, " }")
}
}
type enumSymbol string
func (es enumSymbol) GenerateAlias(g *Generator, pkg string) {
s := string(es)
g.P("type ", s, " ", pkg, ".", s)
g.P("var ", s, "_name = ", pkg, ".", s, "_name")
g.P("var ", s, "_value = ", pkg, ".", s, "_value")
g.P("func (x ", s, ") Enum() *", s, "{ return (*", s, ")((", pkg, ".", s, ")(x).Enum()) }")
g.P("func (x ", s, ") String() string { return (", pkg, ".", s, ")(x).String() }")
g.P("func (x *", s, ") UnmarshalJSON(data []byte) error { return (*", pkg, ".", s, ")(x).UnmarshalJSON(data) }")
}
type constOrVarSymbol struct {
sym string
typ string // either "const" or "var"
cast string // if non-empty, a type cast is required (used for enums)
}
func (cs constOrVarSymbol) GenerateAlias(g *Generator, pkg string) {
v := pkg + "." + cs.sym
if cs.cast != "" {
v = cs.cast + "(" + v + ")"
}
g.P(cs.typ, " ", cs.sym, " = ", v)
}
// Object is an interface abstracting the abilities shared by enums, messages, extensions and imported objects.
type Object interface {
PackageName() string // The name we use in our output (a_b_c), possibly renamed for uniqueness.
TypeName() []string
File() *descriptor.FileDescriptorProto
}
// Each package name we generate must be unique. The package we're generating
// gets its own name but every other package must have a unique name that does
// not conflict in the code we generate. These names are chosen globally (although
// they don't have to be, it simplifies things to do them globally).
func uniquePackageOf(fd *descriptor.FileDescriptorProto) string {
s, ok := uniquePackageName[fd]
if !ok {
log.Fatal("internal error: no package name defined for " + fd.GetName())
}
return s
}
// Generator is the type whose methods generate the output, stored in the associated response structure.
type Generator struct {
*bytes.Buffer
Request *plugin.CodeGeneratorRequest // The input.
Response *plugin.CodeGeneratorResponse // The output.
Param map[string]string // Command-line parameters.
PackageImportPath string // Go import path of the package we're generating code for
ImportPrefix string // String to prefix to imported package file names.
ImportMap map[string]string // Mapping from import name to generated name
Pkg map[string]string // The names under which we import support packages
packageName string // What we're calling ourselves.
allFiles []*FileDescriptor // All files in the tree
genFiles []*FileDescriptor // Those files we will generate output for.
file *FileDescriptor // The file we are compiling now.
usedPackages map[string]bool // Names of packages used in current file.
typeNameToObject map[string]Object // Key is a fully-qualified name in input syntax.
indent string
}
// New creates a new generator and allocates the request and response protobufs.
func New() *Generator {
g := new(Generator)
g.Buffer = new(bytes.Buffer)
g.Request = new(plugin.CodeGeneratorRequest)
g.Response = new(plugin.CodeGeneratorResponse)
return g
}
// Error reports a problem, including an error, and exits the program.
func (g *Generator) Error(err error, msgs ...string) {
s := strings.Join(msgs, " ") + ":" + err.Error()
log.Print("protoc-gen-go: error:", s)
os.Exit(1)
}
// Fail reports a problem and exits the program.
func (g *Generator) Fail(msgs ...string) {
s := strings.Join(msgs, " ")
log.Print("protoc-gen-go: error:", s)
os.Exit(1)
}
// CommandLineParameters breaks the comma-separated list of key=value pairs
// in the parameter (a member of the request protobuf) into a key/value map.
// It then sets file name mappings defined by those entries.
func (g *Generator) CommandLineParameters(parameter string) {
g.Param = make(map[string]string)
for _, p := range strings.Split(parameter, ",") {
if i := strings.Index(p, "="); i < 0 {
g.Param[p] = ""
} else {
g.Param[p[0:i]] = p[i+1:]
}
}
g.ImportMap = make(map[string]string)
for k, v := range g.Param {
switch k {
case "import_prefix":
g.ImportPrefix = v
case "import_path":
g.PackageImportPath = v
default:
if len(k) > 0 && k[0] == 'M' {
g.ImportMap[k[1:]] = v
}
}
}
}
// DefaultPackageName returns the package name printed for the object.
// If its file is in a different package, it returns the package name we're using for this file, plus ".".
// Otherwise it returns the empty string.
func (g *Generator) DefaultPackageName(obj Object) string {
pkg := obj.PackageName()
if pkg == g.packageName {
return ""
}
return pkg + "."
}
// For each input file, the unique package name to use, underscored.
var uniquePackageName = make(map[*descriptor.FileDescriptorProto]string)
// Package names already registered. Key is the name from the .proto file;
// value is the name that appears in the generated code.
var pkgNamesInUse = make(map[string]bool)
// Create and remember a guaranteed unique package name for this file descriptor.
// Pkg is the candidate name. If f is nil, it's a builtin package like "proto" and
// has no file descriptor.
func RegisterUniquePackageName(pkg string, f *FileDescriptor) string {
// Convert dots to underscores before finding a unique alias.
pkg = strings.Map(badToUnderscore, pkg)
for i, orig := 1, pkg; pkgNamesInUse[pkg]; i++ {
// It's a duplicate; must rename.
pkg = orig + strconv.Itoa(i)
}
// Install it.
pkgNamesInUse[pkg] = true
if f != nil {
uniquePackageName[f.FileDescriptorProto] = pkg
}
return pkg
}
var isGoKeyword = map[string]bool{
"break": true,
"case": true,
"chan": true,
"const": true,
"continue": true,
"default": true,
"else": true,
"defer": true,
"fallthrough": true,
"for": true,
"func": true,
"go": true,
"goto": true,
"if": true,
"import": true,
"interface": true,
"map": true,
"package": true,
"range": true,
"return": true,
"select": true,
"struct": true,
"switch": true,
"type": true,
"var": true,
}
// defaultGoPackage returns the package name to use,
// derived from the import path of the package we're building code for.
func (g *Generator) defaultGoPackage() string {
p := g.PackageImportPath
if i := strings.LastIndex(p, "/"); i >= 0 {
p = p[i+1:]
}
if p == "" {
return ""
}
p = strings.Map(badToUnderscore, p)
// Identifier must not be keyword: insert _.
if isGoKeyword[p] {
p = "_" + p
}
// Identifier must not begin with digit: insert _.
if r, _ := utf8.DecodeRuneInString(p); unicode.IsDigit(r) {
p = "_" + p
}
return p
}
// SetPackageNames sets the package name for this run.
// The package name must agree across all files being generated.
// It also defines unique package names for all imported files.
func (g *Generator) SetPackageNames() {
// Register the name for this package. It will be the first name
// registered so is guaranteed to be unmodified.
pkg, explicit := g.genFiles[0].goPackageName()
// Check all files for an explicit go_package option.
for _, f := range g.genFiles {
thisPkg, thisExplicit := f.goPackageName()
if thisExplicit {
if !explicit {
// Let this file's go_package option serve for all input files.
pkg, explicit = thisPkg, true
} else if thisPkg != pkg {
g.Fail("inconsistent package names:", thisPkg, pkg)
}
}
}
// If we don't have an explicit go_package option but we have an
// import path, use that.
if !explicit {
p := g.defaultGoPackage()
if p != "" {
pkg, explicit = p, true
}
}
// If there was no go_package and no import path to use,
// double-check that all the inputs have the same implicit
// Go package name.
if !explicit {
for _, f := range g.genFiles {
thisPkg, _ := f.goPackageName()
if thisPkg != pkg {
g.Fail("inconsistent package names:", thisPkg, pkg)
}
}
}
g.packageName = RegisterUniquePackageName(pkg, g.genFiles[0])
// Register the support package names. They might collide with the
// name of a package we import.
g.Pkg = map[string]string{
"math": RegisterUniquePackageName("math", nil),
"proto": RegisterUniquePackageName("proto", nil),
}
AllFiles:
for _, f := range g.allFiles {
for _, genf := range g.genFiles {
if f == genf {
// In this package already.
uniquePackageName[f.FileDescriptorProto] = g.packageName
continue AllFiles
}
}
// The file is a dependency, so we want to ignore its go_package option
// because that is only relevant for its specific generated output.
pkg := f.GetPackage()
if pkg == "" {
pkg = baseName(*f.Name)
}
RegisterUniquePackageName(pkg, f)
}
}
// WrapTypes walks the incoming data, wrapping DescriptorProtos, EnumDescriptorProtos
// and FileDescriptorProtos into file-referenced objects within the Generator.
// It also creates the list of files to generate and so should be called before GenerateAllFiles.
func (g *Generator) WrapTypes() {
g.allFiles = make([]*FileDescriptor, len(g.Request.ProtoFile))
for i, f := range g.Request.ProtoFile {
// We must wrap the descriptors before we wrap the enums
descs := wrapDescriptors(f)
g.buildNestedDescriptors(descs)
enums := wrapEnumDescriptors(f, descs)
exts := wrapExtensions(f)
imps := wrapImported(f, g)
fd := &FileDescriptor{
FileDescriptorProto: f,
desc: descs,
enum: enums,
ext: exts,
imp: imps,
exported: make(map[Object][]symbol),
}
extractComments(fd)
g.allFiles[i] = fd
}
g.genFiles = make([]*FileDescriptor, len(g.Request.FileToGenerate))
FindFiles:
for i, fileName := range g.Request.FileToGenerate {
// Search the list. This algorithm is n^2 but n is tiny.
for _, file := range g.allFiles {
if fileName == file.GetName() {
g.genFiles[i] = file
file.index = i
continue FindFiles
}
}
g.Fail("could not find file named", fileName)
}
g.Response.File = make([]*plugin.CodeGeneratorResponse_File, len(g.genFiles))
}
// Scan the descriptors in this file. For each one, build the slice of nested descriptors
func (g *Generator) buildNestedDescriptors(descs []*Descriptor) {
for _, desc := range descs {
if len(desc.NestedType) != 0 {
desc.nested = make([]*Descriptor, len(desc.NestedType))
n := 0
for _, nest := range descs {
if nest.parent == desc {
desc.nested[n] = nest
n++
}
}
if n != len(desc.NestedType) {
g.Fail("internal error: nesting failure for", desc.GetName())
}
}
}
}
// Construct the Descriptor
func newDescriptor(desc *descriptor.DescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) *Descriptor {
d := &Descriptor{
common: common{file},
DescriptorProto: desc,
parent: parent,
index: index,
}
if parent == nil {
d.path = fmt.Sprintf("%d,%d", messagePath, index)
} else {
d.path = fmt.Sprintf("%s,%d,%d", parent.path, messageMessagePath, index)
}
// The only way to distinguish a group from a message is whether
// the containing message has a TYPE_GROUP field that matches.
if parent != nil {
parts := d.TypeName()
if file.Package != nil {
parts = append([]string{*file.Package}, parts...)
}
exp := "." + strings.Join(parts, ".")
for _, field := range parent.Field {
if field.GetType() == descriptor.FieldDescriptorProto_TYPE_GROUP && field.GetTypeName() == exp {
d.group = true
break
}
}
}
d.ext = make([]*ExtensionDescriptor, len(desc.Extension))
for i, field := range desc.Extension {
d.ext[i] = &ExtensionDescriptor{common{file}, field, d}
}
return d
}
// Return a slice of all the Descriptors defined within this file
func wrapDescriptors(file *descriptor.FileDescriptorProto) []*Descriptor {
sl := make([]*Descriptor, 0, len(file.MessageType)+10)
for i, desc := range file.MessageType {
sl = wrapThisDescriptor(sl, desc, nil, file, i)
}
return sl
}
// Wrap this Descriptor, recursively
func wrapThisDescriptor(sl []*Descriptor, desc *descriptor.DescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) []*Descriptor {
sl = append(sl, newDescriptor(desc, parent, file, index))
me := sl[len(sl)-1]
for i, nested := range desc.NestedType {
sl = wrapThisDescriptor(sl, nested, me, file, i)
}
return sl
}
// Construct the EnumDescriptor
func newEnumDescriptor(desc *descriptor.EnumDescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) *EnumDescriptor {
ed := &EnumDescriptor{
common: common{file},
EnumDescriptorProto: desc,
parent: parent,
index: index,
}
if parent == nil {
ed.path = fmt.Sprintf("%d,%d", enumPath, index)
} else {
ed.path = fmt.Sprintf("%s,%d,%d", parent.path, messageEnumPath, index)
}
return ed
}
// Return a slice of all the EnumDescriptors defined within this file
func wrapEnumDescriptors(file *descriptor.FileDescriptorProto, descs []*Descriptor) []*EnumDescriptor {
sl := make([]*EnumDescriptor, 0, len(file.EnumType)+10)
// Top-level enums.
for i, enum := range file.EnumType {
sl = append(sl, newEnumDescriptor(enum, nil, file, i))
}
// Enums within messages. Enums within embedded messages appear in the outer-most message.
for _, nested := range descs {
for i, enum := range nested.EnumType {
sl = append(sl, newEnumDescriptor(enum, nested, file, i))
}
}
return sl
}
// Return a slice of all the top-level ExtensionDescriptors defined within this file.
func wrapExtensions(file *descriptor.FileDescriptorProto) []*ExtensionDescriptor {
sl := make([]*ExtensionDescriptor, len(file.Extension))
for i, field := range file.Extension {
sl[i] = &ExtensionDescriptor{common{file}, field, nil}
}
return sl
}
// Return a slice of all the types that are publicly imported into this file.
func wrapImported(file *descriptor.FileDescriptorProto, g *Generator) (sl []*ImportedDescriptor) {
for _, index := range file.PublicDependency {
df := g.fileByName(file.Dependency[index])
for _, d := range df.desc {
sl = append(sl, &ImportedDescriptor{common{file}, d})
}
for _, e := range df.enum {
sl = append(sl, &ImportedDescriptor{common{file}, e})
}
for _, ext := range df.ext {
sl = append(sl, &ImportedDescriptor{common{file}, ext})
}
}
return
}
func extractComments(file *FileDescriptor) {
file.comments = make(map[string]*descriptor.SourceCodeInfo_Location)
for _, loc := range file.GetSourceCodeInfo().GetLocation() {
if loc.LeadingComments == nil {
continue
}
var p []string
for _, n := range loc.Path {
p = append(p, strconv.Itoa(int(n)))
}
file.comments[strings.Join(p, ",")] = loc
}
}
// BuildTypeNameMap builds the map from fully qualified type names to objects.
// The key names for the map come from the input data, which puts a period at the beginning.
// It should be called after SetPackageNames and before GenerateAllFiles.
func (g *Generator) BuildTypeNameMap() {
g.typeNameToObject = make(map[string]Object)
for _, f := range g.allFiles {
// The names in this loop are defined by the proto world, not us, so the
// package name may be empty. If so, the dotted package name of X will
// be ".X"; otherwise it will be ".pkg.X".
dottedPkg := "." + f.GetPackage()
if dottedPkg != "." {
dottedPkg += "."
}
for _, enum := range f.enum {
name := dottedPkg + dottedSlice(enum.TypeName())
g.typeNameToObject[name] = enum
}
for _, desc := range f.desc {
name := dottedPkg + dottedSlice(desc.TypeName())
g.typeNameToObject[name] = desc
}
}
}
// ObjectNamed, given a fully-qualified input type name as it appears in the input data,
// returns the descriptor for the message or enum with that name.
func (g *Generator) ObjectNamed(typeName string) Object {
o, ok := g.typeNameToObject[typeName]
if !ok {
g.Fail("can't find object with type", typeName)
}
// If the file of this object isn't a direct dependency of the current file,
// or in the current file, then this object has been publicly imported into
// a dependency of the current file.
// We should return the ImportedDescriptor object for it instead.
direct := *o.File().Name == *g.file.Name
if !direct {
for _, dep := range g.file.Dependency {
if *g.fileByName(dep).Name == *o.File().Name {
direct = true
break
}
}
}
if !direct {
found := false
Loop:
for _, dep := range g.file.Dependency {
df := g.fileByName(*g.fileByName(dep).Name)
for _, td := range df.imp {
if td.o == o {
// Found it!
o = td
found = true
break Loop
}
}
}
if !found {
log.Printf("protoc-gen-go: WARNING: failed finding publicly imported dependency for %v, used in %v", typeName, *g.file.Name)
}
}
return o
}
// P prints the arguments to the generated output. It handles strings and int32s, plus
// handling indirections because they may be *string, etc.
func (g *Generator) P(str ...interface{}) {
g.WriteString(g.indent)
for _, v := range str {
switch s := v.(type) {
case string:
g.WriteString(s)
case *string:
g.WriteString(*s)
case bool:
g.WriteString(fmt.Sprintf("%t", s))
case *bool:
g.WriteString(fmt.Sprintf("%t", *s))
case int:
g.WriteString(fmt.Sprintf("%d", s))
case *int32:
g.WriteString(fmt.Sprintf("%d", *s))
case *int64:
g.WriteString(fmt.Sprintf("%d", *s))
case float64:
g.WriteString(fmt.Sprintf("%g", s))
case *float64:
g.WriteString(fmt.Sprintf("%g", *s))
default:
g.Fail(fmt.Sprintf("unknown type in printer: %T", v))
}
}
g.WriteByte('\n')
}
// In Indents the output one tab stop.
func (g *Generator) In() { g.indent += "\t" }
// Out unindents the output one tab stop.
func (g *Generator) Out() {
if len(g.indent) > 0 {
g.indent = g.indent[1:]
}
}
// GenerateAllFiles generates the output for all the files we're outputting.
func (g *Generator) GenerateAllFiles() {
// Initialize the plugins
for _, p := range plugins {
p.Init(g)
}
// Generate the output. The generator runs for every file, even the files
// that we don't generate output for, so that we can collate the full list
// of exported symbols to support public imports.
genFileMap := make(map[*FileDescriptor]bool, len(g.genFiles))
for _, file := range g.genFiles {
genFileMap[file] = true
}
i := 0
for _, file := range g.allFiles {
g.Reset()
g.generate(file)
if _, ok := genFileMap[file]; !ok {
continue
}
g.Response.File[i] = new(plugin.CodeGeneratorResponse_File)
g.Response.File[i].Name = proto.String(goFileName(*file.Name))
g.Response.File[i].Content = proto.String(g.String())
i++
}
}
// Run all the plugins associated with the file.
func (g *Generator) runPlugins(file *FileDescriptor) {
for _, p := range plugins {
p.Generate(file)
}
}
// FileOf return the FileDescriptor for this FileDescriptorProto.
func (g *Generator) FileOf(fd *descriptor.FileDescriptorProto) *FileDescriptor {
for _, file := range g.allFiles {
if file.FileDescriptorProto == fd {
return file
}
}
g.Fail("could not find file in table:", fd.GetName())
return nil
}
// Fill the response protocol buffer with the generated output for all the files we're
// supposed to generate.
func (g *Generator) generate(file *FileDescriptor) {
g.file = g.FileOf(file.FileDescriptorProto)
g.usedPackages = make(map[string]bool)
for _, td := range g.file.imp {
g.generateImported(td)
}
for _, enum := range g.file.enum {
g.generateEnum(enum)
}
for _, desc := range g.file.desc {
g.generateMessage(desc)
}
for _, ext := range g.file.ext {
g.generateExtension(ext)
}
g.generateInitFunction()
// Run the plugins before the imports so we know which imports are necessary.
g.runPlugins(file)
// Generate header and imports last, though they appear first in the output.
rem := g.Buffer
g.Buffer = new(bytes.Buffer)
g.generateHeader()
g.generateImports()
g.Write(rem.Bytes())
// Reformat generated code.
fset := token.NewFileSet()
ast, err := parser.ParseFile(fset, "", g, parser.ParseComments)
if err != nil {
g.Fail("bad Go source code was generated:", err.Error())
return
}
g.Reset()
err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(g, fset, ast)
if err != nil {
g.Fail("generated Go source code could not be reformatted:", err.Error())
}
}
// Generate the header, including package definition
func (g *Generator) generateHeader() {
g.P("// Code generated by protoc-gen-go.")
g.P("// source: ", g.file.Name)
g.P("// DO NOT EDIT!")
g.P()
name := g.file.PackageName()
if g.file.index == 0 {
// Generate package docs for the first file in the package.
g.P("/*")
g.P("Package ", name, " is a generated protocol buffer package.")
g.P()
if loc, ok := g.file.comments[strconv.Itoa(packagePath)]; ok {
// not using g.PrintComments because this is a /* */ comment block.
text := strings.TrimSuffix(loc.GetLeadingComments(), "\n")
for _, line := range strings.Split(text, "\n") {
line = strings.TrimPrefix(line, " ")
// ensure we don't escape from the block comment
line = strings.Replace(line, "*/", "* /", -1)
g.P(line)
}
g.P()
}
g.P("It is generated from these files:")
for _, f := range g.genFiles {
g.P("\t", f.Name)
}
g.P()
g.P("It has these top-level messages:")
for _, msg := range g.file.desc {
if msg.parent != nil {
continue
}
g.P("\t", CamelCaseSlice(msg.TypeName()))
}
g.P("*/")
}
g.P("package ", name)
g.P()
}
// PrintComments prints any comments from the source .proto file.
// The path is a comma-separated list of integers.
// See descriptor.proto for its format.
func (g *Generator) PrintComments(path string) {
if loc, ok := g.file.comments[path]; ok {
text := strings.TrimSuffix(loc.GetLeadingComments(), "\n")
for _, line := range strings.Split(text, "\n") {
g.P("// ", strings.TrimPrefix(line, " "))
}
}
}
func (g *Generator) fileByName(filename string) *FileDescriptor {
for _, fd := range g.allFiles {
if fd.GetName() == filename {
return fd
}
}
return nil
}
// weak returns whether the ith import of the current file is a weak import.
func (g *Generator) weak(i int32) bool {
for _, j := range g.file.WeakDependency {
if j == i {
return true
}
}
return false
}
// Generate the imports
func (g *Generator) generateImports() {
// We almost always need a proto import. Rather than computing when we
// do, which is tricky when there's a plugin, just import it and
// reference it later. The same argument applies to the math package,
// for handling bit patterns for floating-point numbers.
g.P("import " + g.Pkg["proto"] + " " + strconv.Quote(g.ImportPrefix+"code.google.com/p/goprotobuf/proto"))
g.P("import " + g.Pkg["math"] + ` "math"`)
for i, s := range g.file.Dependency {
fd := g.fileByName(s)
// Do not import our own package.
if fd.PackageName() == g.packageName {
continue
}
filename := goFileName(s)
if substitution, ok := g.ImportMap[s]; ok {
filename = substitution
}
filename = g.ImportPrefix + filename
if strings.HasSuffix(filename, ".go") {
filename = filename[0 : len(filename)-3]
}
// Skip weak imports.
if g.weak(int32(i)) {
g.P("// skipping weak import ", fd.PackageName(), " ", strconv.Quote(filename))
continue
}
if _, ok := g.usedPackages[fd.PackageName()]; ok {
g.P("import ", fd.PackageName(), " ", strconv.Quote(filename))
} else {
// TODO: Re-enable this when we are more feature-complete.
// For instance, some protos use foreign field extensions, which we don't support.
// Until then, this is just annoying spam.
//log.Printf("protoc-gen-go: discarding unused import from %v: %v", *g.file.Name, s)
g.P("// discarding unused import ", fd.PackageName(), " ", strconv.Quote(filename))
}
}
g.P()
// TODO: may need to worry about uniqueness across plugins
for _, p := range plugins {
p.GenerateImports(g.file)
g.P()
}
g.P("// Reference imports to suppress errors if they are not otherwise used.")
g.P("var _ = ", g.Pkg["proto"], ".Marshal")
g.P("var _ = ", g.Pkg["math"], ".Inf")
g.P()
}
func (g *Generator) generateImported(id *ImportedDescriptor) {
// Don't generate public import symbols for files that we are generating
// code for, since those symbols will already be in this package.
// We can't simply avoid creating the ImportedDescriptor objects,
// because g.genFiles isn't populated at that stage.
tn := id.TypeName()
sn := tn[len(tn)-1]
df := g.FileOf(id.o.File())
filename := *df.Name
for _, fd := range g.genFiles {
if *fd.Name == filename {
g.P("// Ignoring public import of ", sn, " from ", filename)
g.P()
return
}
}
g.P("// ", sn, " from public import ", filename)
g.usedPackages[df.PackageName()] = true
for _, sym := range df.exported[id.o] {
sym.GenerateAlias(g, df.PackageName())
}
g.P()
}
// Generate the enum definitions for this EnumDescriptor.
func (g *Generator) generateEnum(enum *EnumDescriptor) {
// The full type name
typeName := enum.TypeName()
// The full type name, CamelCased.
ccTypeName := CamelCaseSlice(typeName)
ccPrefix := enum.prefix()
g.PrintComments(enum.path)
g.P("type ", ccTypeName, " int32")
g.file.addExport(enum, enumSymbol(ccTypeName))
g.P("const (")
g.In()
for i, e := range enum.Value {
g.PrintComments(fmt.Sprintf("%s,%d,%d", enum.path, enumValuePath, i))
name := ccPrefix + *e.Name
g.P(name, " ", ccTypeName, " = ", e.Number)
g.file.addExport(enum, constOrVarSymbol{name, "const", ccTypeName})
}
g.Out()
g.P(")")
g.P("var ", ccTypeName, "_name = map[int32]string{")
g.In()
generated := make(map[int32]bool) // avoid duplicate values
for _, e := range enum.Value {
duplicate := ""
if _, present := generated[*e.Number]; present {
duplicate = "// Duplicate value: "
}
g.P(duplicate, e.Number, ": ", strconv.Quote(*e.Name), ",")
generated[*e.Number] = true
}
g.Out()
g.P("}")
g.P("var ", ccTypeName, "_value = map[string]int32{")
g.In()
for _, e := range enum.Value {
g.P(strconv.Quote(*e.Name), ": ", e.Number, ",")
}
g.Out()
g.P("}")
g.P("func (x ", ccTypeName, ") Enum() *", ccTypeName, " {")
g.In()
g.P("p := new(", ccTypeName, ")")
g.P("*p = x")
g.P("return p")
g.Out()
g.P("}")
g.P("func (x ", ccTypeName, ") String() string {")
g.In()
g.P("return ", g.Pkg["proto"], ".EnumName(", ccTypeName, "_name, int32(x))")
g.Out()
g.P("}")
g.P("func (x *", ccTypeName, ") UnmarshalJSON(data []byte) error {")
g.In()
g.P("value, err := ", g.Pkg["proto"], ".UnmarshalJSONEnum(", ccTypeName, `_value, data, "`, ccTypeName, `")`)
g.P("if err != nil {")
g.In()
g.P("return err")
g.Out()
g.P("}")
g.P("*x = ", ccTypeName, "(value)")
g.P("return nil")
g.Out()
g.P("}")
g.P()
}
// The tag is a string like "varint,2,opt,name=fieldname,def=7" that
// identifies details of the field for the protocol buffer marshaling and unmarshaling
// code. The fields are:
// wire encoding
// protocol tag number
// opt,req,rep for optional, required, or repeated
// packed whether the encoding is "packed" (optional; repeated primitives only)
// name= the original declared name
// enum= the name of the enum type if it is an enum-typed field.
// def= string representation of the default value, if any.
// The default value must be in a representation that can be used at run-time
// to generate the default value. Thus bools become 0 and 1, for instance.
func (g *Generator) goTag(message *Descriptor, field *descriptor.FieldDescriptorProto, wiretype string) string {
optrepreq := ""
switch {
case isOptional(field):
optrepreq = "opt"
case isRequired(field):
optrepreq = "req"
case isRepeated(field):
optrepreq = "rep"
}
var defaultValue string
if dv := field.DefaultValue; dv != nil { // set means an explicit default
defaultValue = *dv
// Some types need tweaking.
switch *field.Type {
case descriptor.FieldDescriptorProto_TYPE_BOOL:
if defaultValue == "true" {
defaultValue = "1"
} else {
defaultValue = "0"
}
case descriptor.FieldDescriptorProto_TYPE_STRING,
descriptor.FieldDescriptorProto_TYPE_BYTES:
// Nothing to do. Quoting is done for the whole tag.
case descriptor.FieldDescriptorProto_TYPE_ENUM:
// For enums we need to provide the integer constant.
obj := g.ObjectNamed(field.GetTypeName())
if id, ok := obj.(*ImportedDescriptor); ok {
// It is an enum that was publicly imported.
// We need the underlying type.
obj = id.o
}
enum, ok := obj.(*EnumDescriptor)
if !ok {
log.Printf("obj is a %T", obj)
if id, ok := obj.(*ImportedDescriptor); ok {
log.Printf("id.o is a %T", id.o)
}
g.Fail("unknown enum type", CamelCaseSlice(obj.TypeName()))
}
defaultValue = enum.integerValueAsString(defaultValue)
}
defaultValue = ",def=" + defaultValue
}
enum := ""
if *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM {
// We avoid using obj.PackageName(), because we want to use the
// original (proto-world) package name.
obj := g.ObjectNamed(field.GetTypeName())
if id, ok := obj.(*ImportedDescriptor); ok {
obj = id.o
}
enum = ",enum="
if pkg := obj.File().GetPackage(); pkg != "" {
enum += pkg + "."
}
enum += CamelCaseSlice(obj.TypeName())
}
packed := ""
if field.Options != nil && field.Options.GetPacked() {
packed = ",packed"
}
fieldName := field.GetName()
name := fieldName
if *field.Type == descriptor.FieldDescriptorProto_TYPE_GROUP {
// We must use the type name for groups instead of
// the field name to preserve capitalization.
// type_name in FieldDescriptorProto is fully-qualified,
// but we only want the local part.
name = *field.TypeName
if i := strings.LastIndex(name, "."); i >= 0 {
name = name[i+1:]
}
}
if name == CamelCase(fieldName) {
name = ""
} else {
name = ",name=" + name
}
return strconv.Quote(fmt.Sprintf("%s,%d,%s%s%s%s%s",
wiretype,
field.GetNumber(),
optrepreq,
packed,
name,
enum,
defaultValue))
}
func needsStar(typ descriptor.FieldDescriptorProto_Type) bool {
switch typ {
case descriptor.FieldDescriptorProto_TYPE_GROUP:
return false
case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
return false
case descriptor.FieldDescriptorProto_TYPE_BYTES:
return false
}
return true
}
// TypeName is the printed name appropriate for an item. If the object is in the current file,
// TypeName drops the package name and underscores the rest.
// Otherwise the object is from another package; and the result is the underscored
// package name followed by the item name.
// The result always has an initial capital.
func (g *Generator) TypeName(obj Object) string {
return g.DefaultPackageName(obj) + CamelCaseSlice(obj.TypeName())
}
// TypeNameWithPackage is like TypeName, but always includes the package
// name even if the object is in our own package.
func (g *Generator) TypeNameWithPackage(obj Object) string {
return obj.PackageName() + CamelCaseSlice(obj.TypeName())
}
// GoType returns a string representing the type name, and the wire type
func (g *Generator) GoType(message *Descriptor, field *descriptor.FieldDescriptorProto) (typ string, wire string) {
// TODO: Options.
switch *field.Type {
case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
typ, wire = "float64", "fixed64"
case descriptor.FieldDescriptorProto_TYPE_FLOAT:
typ, wire = "float32", "fixed32"
case descriptor.FieldDescriptorProto_TYPE_INT64:
typ, wire = "int64", "varint"
case descriptor.FieldDescriptorProto_TYPE_UINT64:
typ, wire = "uint64", "varint"
case descriptor.FieldDescriptorProto_TYPE_INT32:
typ, wire = "int32", "varint"
case descriptor.FieldDescriptorProto_TYPE_UINT32:
typ, wire = "uint32", "varint"
case descriptor.FieldDescriptorProto_TYPE_FIXED64:
typ, wire = "uint64", "fixed64"
case descriptor.FieldDescriptorProto_TYPE_FIXED32:
typ, wire = "uint32", "fixed32"
case descriptor.FieldDescriptorProto_TYPE_BOOL:
typ, wire = "bool", "varint"
case descriptor.FieldDescriptorProto_TYPE_STRING:
typ, wire = "string", "bytes"
case descriptor.FieldDescriptorProto_TYPE_GROUP:
desc := g.ObjectNamed(field.GetTypeName())
typ, wire = "*"+g.TypeName(desc), "group"
case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
desc := g.ObjectNamed(field.GetTypeName())
typ, wire = "*"+g.TypeName(desc), "bytes"
case descriptor.FieldDescriptorProto_TYPE_BYTES:
typ, wire = "[]byte", "bytes"
case descriptor.FieldDescriptorProto_TYPE_ENUM:
desc := g.ObjectNamed(field.GetTypeName())
typ, wire = g.TypeName(desc), "varint"
case descriptor.FieldDescriptorProto_TYPE_SFIXED32:
typ, wire = "int32", "fixed32"
case descriptor.FieldDescriptorProto_TYPE_SFIXED64:
typ, wire = "int64", "fixed64"
case descriptor.FieldDescriptorProto_TYPE_SINT32:
typ, wire = "int32", "zigzag32"
case descriptor.FieldDescriptorProto_TYPE_SINT64:
typ, wire = "int64", "zigzag64"
default:
g.Fail("unknown type for", field.GetName())
}
if isRepeated(field) {
typ = "[]" + typ
} else if needsStar(*field.Type) {
typ = "*" + typ
}
return
}
func (g *Generator) RecordTypeUse(t string) {
if obj, ok := g.typeNameToObject[t]; ok {
// Call ObjectNamed to get the true object to record the use.
obj = g.ObjectNamed(t)
g.usedPackages[obj.PackageName()] = true
}
}
// Method names that may be generated. Fields with these names get an
// underscore appended.
var methodNames = [...]string{
"Reset",
"String",
"ProtoMessage",
"Marshal",
"Unmarshal",
"ExtensionRangeArray",
"ExtensionMap",
"Descriptor",
}
// Generate the type and default constant definitions for this Descriptor.
func (g *Generator) generateMessage(message *Descriptor) {
// The full type name
typeName := message.TypeName()
// The full type name, CamelCased.
ccTypeName := CamelCaseSlice(typeName)
usedNames := make(map[string]bool)
for _, n := range methodNames {
usedNames[n] = true
}
fieldNames := make(map[*descriptor.FieldDescriptorProto]string)
fieldGetterNames := make(map[*descriptor.FieldDescriptorProto]string)
g.PrintComments(message.path)
g.P("type ", ccTypeName, " struct {")
g.In()
for i, field := range message.Field {
g.PrintComments(fmt.Sprintf("%s,%d,%d", message.path, messageFieldPath, i))
fieldName := CamelCase(*field.Name)
for usedNames[fieldName] {
fieldName += "_"
}
fieldGetterName := fieldName
usedNames[fieldName] = true
typename, wiretype := g.GoType(message, field)
jsonName := *field.Name
tag := fmt.Sprintf("protobuf:%s json:%q", g.goTag(message, field, wiretype), jsonName+",omitempty")
fieldNames[field] = fieldName
fieldGetterNames[field] = fieldGetterName
g.P(fieldName, "\t", typename, "\t`", tag, "`")
g.RecordTypeUse(field.GetTypeName())
}
if len(message.ExtensionRange) > 0 {
g.P("XXX_extensions\t\tmap[int32]", g.Pkg["proto"], ".Extension `json:\"-\"`")
}
g.P("XXX_unrecognized\t[]byte `json:\"-\"`")
g.Out()
g.P("}")
// Reset, String and ProtoMessage methods.
g.P("func (m *", ccTypeName, ") Reset() { *m = ", ccTypeName, "{} }")
g.P("func (m *", ccTypeName, ") String() string { return ", g.Pkg["proto"], ".CompactTextString(m) }")
g.P("func (*", ccTypeName, ") ProtoMessage() {}")
// Extension support methods
var hasExtensions, isMessageSet bool
if len(message.ExtensionRange) > 0 {
hasExtensions = true
// message_set_wire_format only makes sense when extensions are defined.
if opts := message.Options; opts != nil && opts.GetMessageSetWireFormat() {
isMessageSet = true
g.P()
g.P("func (m *", ccTypeName, ") Marshal() ([]byte, error) {")
g.In()
g.P("return ", g.Pkg["proto"], ".MarshalMessageSet(m.ExtensionMap())")
g.Out()
g.P("}")
g.P("func (m *", ccTypeName, ") Unmarshal(buf []byte) error {")
g.In()
g.P("return ", g.Pkg["proto"], ".UnmarshalMessageSet(buf, m.ExtensionMap())")
g.Out()
g.P("}")
g.P("func (m *", ccTypeName, ") MarshalJSON() ([]byte, error) {")
g.In()
g.P("return ", g.Pkg["proto"], ".MarshalMessageSetJSON(m.XXX_extensions)")
g.Out()
g.P("}")
g.P("func (m *", ccTypeName, ") UnmarshalJSON(buf []byte) error {")
g.In()
g.P("return ", g.Pkg["proto"], ".UnmarshalMessageSetJSON(buf, m.XXX_extensions)")
g.Out()
g.P("}")
g.P("// ensure ", ccTypeName, " satisfies proto.Marshaler and proto.Unmarshaler")
g.P("var _ ", g.Pkg["proto"], ".Marshaler = (*", ccTypeName, ")(nil)")
g.P("var _ ", g.Pkg["proto"], ".Unmarshaler = (*", ccTypeName, ")(nil)")
}
g.P()
g.P("var extRange_", ccTypeName, " = []", g.Pkg["proto"], ".ExtensionRange{")
g.In()
for _, r := range message.ExtensionRange {
end := fmt.Sprint(*r.End - 1) // make range inclusive on both ends
g.P("{", r.Start, ", ", end, "},")
}
g.Out()
g.P("}")
g.P("func (*", ccTypeName, ") ExtensionRangeArray() []", g.Pkg["proto"], ".ExtensionRange {")
g.In()
g.P("return extRange_", ccTypeName)
g.Out()
g.P("}")
g.P("func (m *", ccTypeName, ") ExtensionMap() map[int32]", g.Pkg["proto"], ".Extension {")
g.In()
g.P("if m.XXX_extensions == nil {")
g.In()
g.P("m.XXX_extensions = make(map[int32]", g.Pkg["proto"], ".Extension)")
g.Out()
g.P("}")
g.P("return m.XXX_extensions")
g.Out()
g.P("}")
}
// Default constants
defNames := make(map[*descriptor.FieldDescriptorProto]string)
for _, field := range message.Field {
def := field.GetDefaultValue()
if def == "" {
continue
}
fieldname := "Default_" + ccTypeName + "_" + CamelCase(*field.Name)
defNames[field] = fieldname
typename, _ := g.GoType(message, field)
if typename[0] == '*' {
typename = typename[1:]
}
kind := "const "
switch {
case typename == "bool":
case typename == "string":
def = strconv.Quote(def)
case typename == "[]byte":
def = "[]byte(" + strconv.Quote(def) + ")"
kind = "var "
case def == "inf", def == "-inf", def == "nan":
// These names are known to, and defined by, the protocol language.
switch def {
case "inf":
def = "math.Inf(1)"
case "-inf":
def = "math.Inf(-1)"
case "nan":
def = "math.NaN()"
}
if *field.Type == descriptor.FieldDescriptorProto_TYPE_FLOAT {
def = "float32(" + def + ")"
}
kind = "var "
case *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM:
// Must be an enum. Need to construct the prefixed name.
obj := g.ObjectNamed(field.GetTypeName())
var enum *EnumDescriptor
if id, ok := obj.(*ImportedDescriptor); ok {
// The enum type has been publicly imported.
enum, _ = id.o.(*EnumDescriptor)
} else {
enum, _ = obj.(*EnumDescriptor)
}
if enum == nil {
log.Printf("don't know how to generate constant for %s", fieldname)
continue
}
def = g.DefaultPackageName(obj) + enum.prefix() + def
}
g.P(kind, fieldname, " ", typename, " = ", def)
g.file.addExport(message, constOrVarSymbol{fieldname, kind, ""})
}
g.P()
// Field getters
var getters []getterSymbol
for _, field := range message.Field {
fname := fieldNames[field]
typename, _ := g.GoType(message, field)
mname := "Get" + fieldGetterNames[field]
star := ""
if needsStar(*field.Type) && typename[0] == '*' {
typename = typename[1:]
star = "*"
}
// Only export getter symbols for basic types,
// and for messages and enums in the same package.
// Groups are not exported.
// Foreign types can't be hoisted through a public import because
// the importer may not already be importing the defining .proto.
// As an example, imagine we have an import tree like this:
// A.proto -> B.proto -> C.proto
// If A publicly imports B, we need to generate the getters from B in A's output,
// but if one such getter returns something from C then we cannot do that
// because A is not importing C already.
var getter, genType bool
switch *field.Type {
case descriptor.FieldDescriptorProto_TYPE_GROUP:
getter = false
case descriptor.FieldDescriptorProto_TYPE_MESSAGE, descriptor.FieldDescriptorProto_TYPE_ENUM:
// Only export getter if its return type is in this package.
getter = g.ObjectNamed(field.GetTypeName()).PackageName() == message.PackageName()
genType = true
default:
getter = true
}
if getter {
getters = append(getters, getterSymbol{
name: mname,
typ: typename,
typeName: field.GetTypeName(),
genType: genType,
})
}
g.P("func (m *", ccTypeName, ") "+mname+"() "+typename+" {")
g.In()
def, hasDef := defNames[field]
typeDefaultIsNil := false // whether this field type's default value is a literal nil unless specified
switch *field.Type {
case descriptor.FieldDescriptorProto_TYPE_BYTES:
typeDefaultIsNil = !hasDef
case descriptor.FieldDescriptorProto_TYPE_GROUP, descriptor.FieldDescriptorProto_TYPE_MESSAGE:
typeDefaultIsNil = true
}
if isRepeated(field) {
typeDefaultIsNil = true
}
if typeDefaultIsNil {
// A bytes field with no explicit default needs less generated code,
// as does a message or group field, or a repeated field.
g.P("if m != nil {")
g.In()
g.P("return m." + fname)
g.Out()
g.P("}")
g.P("return nil")
g.Out()
g.P("}")
g.P()
continue
}
g.P("if m != nil && m." + fname + " != nil {")
g.In()
g.P("return " + star + "m." + fname)
g.Out()
g.P("}")
if hasDef {
if *field.Type != descriptor.FieldDescriptorProto_TYPE_BYTES {
g.P("return " + def)
} else {
// The default is a []byte var.
// Make a copy when returning it to be safe.
g.P("return append([]byte(nil), ", def, "...)")
}
} else {
switch *field.Type {
case descriptor.FieldDescriptorProto_TYPE_BOOL:
g.P("return false")
case descriptor.FieldDescriptorProto_TYPE_STRING:
g.P(`return ""`)
case descriptor.FieldDescriptorProto_TYPE_ENUM:
// The default default for an enum is the first value in the enum,
// not zero.
obj := g.ObjectNamed(field.GetTypeName())
var enum *EnumDescriptor
if id, ok := obj.(*ImportedDescriptor); ok {
// The enum type has been publicly imported.
enum, _ = id.o.(*EnumDescriptor)
} else {
enum, _ = obj.(*EnumDescriptor)
}
if enum == nil {
log.Printf("don't know how to generate getter for %s", field.GetName())
continue
}
if len(enum.Value) == 0 {
g.P("return 0 // empty enum")
} else {
first := enum.Value[0].GetName()
g.P("return ", g.DefaultPackageName(obj)+enum.prefix()+first)
}
default:
g.P("return 0")
}
}
g.Out()
g.P("}")
g.P()
}
if !message.group {
ms := &messageSymbol{sym: ccTypeName, hasExtensions: hasExtensions, isMessageSet: isMessageSet, getters: getters}
g.file.addExport(message, ms)
}
for _, ext := range message.ext {
g.generateExtension(ext)
}
}
func (g *Generator) generateExtension(ext *ExtensionDescriptor) {
ccTypeName := ext.DescName()
extDesc := g.ObjectNamed(*ext.Extendee).(*Descriptor)
extendedType := "*" + g.TypeName(extDesc)
field := ext.FieldDescriptorProto
fieldType, wireType := g.GoType(ext.parent, field)
tag := g.goTag(extDesc, field, wireType)
g.RecordTypeUse(*ext.Extendee)
if n := ext.FieldDescriptorProto.TypeName; n != nil {
// foreign extension type
g.RecordTypeUse(*n)
}
typeName := ext.TypeName()
// Special case for proto2 message sets: If this extension is extending
// proto2_bridge.MessageSet, and its final name component is "message_set_extension",
// then drop that last component.
mset := false
if extendedType == "*proto2_bridge.MessageSet" && typeName[len(typeName)-1] == "message_set_extension" {
typeName = typeName[:len(typeName)-1]
mset = true
}
// For text formatting, the package must be exactly what the .proto file declares,
// ignoring overrides such as the go_package option, and with no dot/underscore mapping.
extName := strings.Join(typeName, ".")
if g.file.Package != nil {
extName = *g.file.Package + "." + extName
}
g.P("var ", ccTypeName, " = &", g.Pkg["proto"], ".ExtensionDesc{")
g.In()
g.P("ExtendedType: (", extendedType, ")(nil),")
g.P("ExtensionType: (", fieldType, ")(nil),")
g.P("Field: ", field.Number, ",")
g.P(`Name: "`, extName, `",`)
g.P("Tag: ", tag, ",")
g.Out()
g.P("}")
g.P()
if mset {
// Generate a bit more code to register with message_set.go.
g.P("func init() { ")
g.In()
g.P(g.Pkg["proto"], ".RegisterMessageSetType((", fieldType, ")(nil), ", field.Number, ", \"", extName, "\")")
g.Out()
g.P("}")
}
g.file.addExport(ext, constOrVarSymbol{ccTypeName, "var", ""})
}
func (g *Generator) generateInitFunction() {
g.P("func init() {")
g.In()
for _, enum := range g.file.enum {
g.generateEnumRegistration(enum)
}
for _, d := range g.file.desc {
for _, ext := range d.ext {
g.generateExtensionRegistration(ext)
}
}
for _, ext := range g.file.ext {
g.generateExtensionRegistration(ext)
}
g.Out()
g.P("}")
}
func (g *Generator) generateEnumRegistration(enum *EnumDescriptor) {
// // We always print the full (proto-world) package name here.
pkg := enum.File().GetPackage()
if pkg != "" {
pkg += "."
}
// The full type name
typeName := enum.TypeName()
// The full type name, CamelCased.
ccTypeName := CamelCaseSlice(typeName)
g.P(g.Pkg["proto"]+".RegisterEnum(", strconv.Quote(pkg+ccTypeName), ", ", ccTypeName+"_name, ", ccTypeName+"_value)")
}
func (g *Generator) generateExtensionRegistration(ext *ExtensionDescriptor) {
g.P(g.Pkg["proto"]+".RegisterExtension(", ext.DescName(), ")")
}
// And now lots of helper functions.
// Is c an ASCII lower-case letter?
func isASCIILower(c byte) bool {
return 'a' <= c && c <= 'z'
}
// Is c an ASCII digit?
func isASCIIDigit(c byte) bool {
return '0' <= c && c <= '9'
}
// CamelCase returns the CamelCased name.
// If there is an interior underscore followed by a lower case letter,
// drop the underscore and convert the letter to upper case.
// There is a remote possibility of this rewrite causing a name collision,
// but it's so remote we're prepared to pretend it's nonexistent - since the
// C++ generator lowercases names, it's extremely unlikely to have two fields
// with different capitalizations.
// In short, _my_field_name_2 becomes XMyFieldName_2.
func CamelCase(s string) string {
if s == "" {
return ""
}
t := make([]byte, 0, 32)
i := 0
if s[0] == '_' {
// Need a capital letter; drop the '_'.
t = append(t, 'X')
i++
}
// Invariant: if the next letter is lower case, it must be converted
// to upper case.
// That is, we process a word at a time, where words are marked by _ or
// upper case letter. Digits are treated as words.
for ; i < len(s); i++ {
c := s[i]
if c == '_' && i+1 < len(s) && isASCIILower(s[i+1]) {
continue // Skip the underscore in s.
}
if isASCIIDigit(c) {
t = append(t, c)
continue
}
// Assume we have a letter now - if not, it's a bogus identifier.
// The next word is a sequence of characters that must start upper case.
if isASCIILower(c) {
c ^= ' ' // Make it a capital letter.
}
t = append(t, c) // Guaranteed not lower case.
// Accept lower case sequence that follows.
for i+1 < len(s) && isASCIILower(s[i+1]) {
i++
t = append(t, s[i])
}
}
return string(t)
}
// CamelCaseSlice is like CamelCase, but the argument is a slice of strings to
// be joined with "_".
func CamelCaseSlice(elem []string) string { return CamelCase(strings.Join(elem, "_")) }
// dottedSlice turns a sliced name into a dotted name.
func dottedSlice(elem []string) string { return strings.Join(elem, ".") }
// Given a .proto file name, return the output name for the generated Go program.
func goFileName(name string) string {
ext := path.Ext(name)
if ext == ".proto" || ext == ".protodevel" {
name = name[0 : len(name)-len(ext)]
}
return name + ".pb.go"
}
// Is this field optional?
func isOptional(field *descriptor.FieldDescriptorProto) bool {
return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_OPTIONAL
}
// Is this field required?
func isRequired(field *descriptor.FieldDescriptorProto) bool {
return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REQUIRED
}
// Is this field repeated?
func isRepeated(field *descriptor.FieldDescriptorProto) bool {
return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REPEATED
}
// badToUnderscore is the mapping function used to generate Go names from package names,
// which can be dotted in the input .proto file. It replaces non-identifier characters such as
// dot or dash with underscore.
func badToUnderscore(r rune) rune {
if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' {
return r
}
return '_'
}
// baseName returns the last path element of the name, with the last dotted suffix removed.
func baseName(name string) string {
// First, find the last element
if i := strings.LastIndex(name, "/"); i >= 0 {
name = name[i+1:]
}
// Now drop the suffix
if i := strings.LastIndex(name, "."); i >= 0 {
name = name[0:i]
}
return name
}
// The SourceCodeInfo message describes the location of elements of a parsed
// .proto file by way of a "path", which is a sequence of integers that
// describe the route from a FileDescriptorProto to the relevant submessage.
// The path alternates between a field number of a repeated field, and an index
// into that repeated field. The constants below define the field numbers that
// are used.
//
// See descriptor.proto for more information about this.
const (
// tag numbers in FileDescriptorProto
packagePath = 2 // package
messagePath = 4 // message_type
enumPath = 5 // enum_type
// tag numbers in DescriptorProto
messageFieldPath = 2 // field
messageMessagePath = 3 // nested_type
messageEnumPath = 4 // enum_type
// tag numbers in EnumDescriptorProto
enumValuePath = 2 // value
)
| 109609524-goprotobuf | protoc-gen-go/generator/generator.go | Go | bsd | 62,635 |
# Go support for Protocol Buffers - Google's data interchange format
#
# Copyright 2010 The Go Authors. All rights reserved.
# http://code.google.com/p/goprotobuf/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Not stored here, but plugin.proto is in http://code.google.com/p/protobuf
# at protobuf-2.5.0/src/google/protobuf/compiler/plugin.proto
# Also we need to fix an import.
regenerate:
echo WARNING! THIS RULE IS PROBABLY NOT RIGHT FOR YOUR INSTALLATION
cd $(HOME)/src/protobuf-2.5.0/src && \
protoc --go_out=. ./google/protobuf/compiler/plugin.proto && \
cat ./google/protobuf/compiler/plugin.pb.go | \
sed '/^import/s;google/protobuf/descriptor.pb;code.google.com/p/goprotobuf/protoc-gen-go/descriptor;' > $(GOPATH)/src/code.google.com/p/goprotobuf/protoc-gen-go/plugin/plugin.pb.go
restore:
cp plugin.pb.golden plugin.pb.go
preserve:
cp plugin.pb.go plugin.pb.golden
| 109609524-goprotobuf | protoc-gen-go/plugin/Makefile | Makefile | bsd | 2,318 |
# Go support for Protocol Buffers - Google's data interchange format
#
# Copyright 2010 The Go Authors. All rights reserved.
# http://code.google.com/p/goprotobuf/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Not stored here, but descriptor.proto is in http://code.google.com/p/protobuf
# at protobuf-2.5.0/src/google/protobuf/descriptor.proto
regenerate:
echo WARNING! THIS RULE IS PROBABLY NOT RIGHT FOR YOUR INSTALLATION
cd $(HOME)/src/protobuf-2.5.0/src && \
protoc --go_out=. ./google/protobuf/descriptor.proto && \
sed -i 's,^package google_protobuf,package descriptor,' google/protobuf/descriptor.pb.go && \
cp ./google/protobuf/descriptor.pb.go $(GOPATH)/src/code.google.com/p/goprotobuf/protoc-gen-go/descriptor/descriptor.pb.go
restore:
cp descriptor.pb.golden descriptor.pb.go
preserve:
cp descriptor.pb.go descriptor.pb.golden
| 109609524-goprotobuf | protoc-gen-go/descriptor/Makefile | Makefile | bsd | 2,282 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/*
A plugin for the Google protocol buffer compiler to generate Go code.
Run it by building this program and putting it in your path with the name
protoc-gen-go
That word 'go' at the end becomes part of the option string set for the
protocol compiler, so once the protocol compiler (protoc) is installed
you can run
protoc --go_out=output_directory input_directory/file.proto
to generate Go bindings for the protocol defined by file.proto.
With that input, the output will be written to
output_directory/file.pb.go
The generated code is documented in the package comment for
the library.
See the README and documentation for protocol buffers to learn more:
http://code.google.com/p/protobuf/
*/
package documentation
| 109609524-goprotobuf | protoc-gen-go/doc.go | Go | bsd | 2,409 |
# Go support for Protocol Buffers - Google's data interchange format
#
# Copyright 2010 The Go Authors. All rights reserved.
# http://code.google.com/p/goprotobuf/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
install:
go install
test: install generate-test-pbs
go test
generate-test-pbs:
make install && cd testdata && make
| 109609524-goprotobuf | proto/Makefile | Makefile | bsd | 1,762 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package proto
// Functions for parsing the Text protocol buffer format.
// TODO: message sets.
import (
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"unicode/utf8"
)
// textUnmarshaler is implemented by Messages that can unmarshal themsleves.
// It is identical to encoding.TextUnmarshaler, introduced in go 1.2,
// which will eventually replace it.
type textUnmarshaler interface {
UnmarshalText(text []byte) error
}
type ParseError struct {
Message string
Line int // 1-based line number
Offset int // 0-based byte offset from start of input
}
func (p *ParseError) Error() string {
if p.Line == 1 {
// show offset only for first line
return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message)
}
return fmt.Sprintf("line %d: %v", p.Line, p.Message)
}
type token struct {
value string
err *ParseError
line int // line number
offset int // byte number from start of input, not start of line
unquoted string // the unquoted version of value, if it was a quoted string
}
func (t *token) String() string {
if t.err == nil {
return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset)
}
return fmt.Sprintf("parse error: %v", t.err)
}
type textParser struct {
s string // remaining input
done bool // whether the parsing is finished (success or error)
backed bool // whether back() was called
offset, line int
cur token
}
func newTextParser(s string) *textParser {
p := new(textParser)
p.s = s
p.line = 1
p.cur.line = 1
return p
}
func (p *textParser) errorf(format string, a ...interface{}) *ParseError {
pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset}
p.cur.err = pe
p.done = true
return pe
}
// Numbers and identifiers are matched by [-+._A-Za-z0-9]
func isIdentOrNumberChar(c byte) bool {
switch {
case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z':
return true
case '0' <= c && c <= '9':
return true
}
switch c {
case '-', '+', '.', '_':
return true
}
return false
}
func isWhitespace(c byte) bool {
switch c {
case ' ', '\t', '\n', '\r':
return true
}
return false
}
func (p *textParser) skipWhitespace() {
i := 0
for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') {
if p.s[i] == '#' {
// comment; skip to end of line or input
for i < len(p.s) && p.s[i] != '\n' {
i++
}
if i == len(p.s) {
break
}
}
if p.s[i] == '\n' {
p.line++
}
i++
}
p.offset += i
p.s = p.s[i:len(p.s)]
if len(p.s) == 0 {
p.done = true
}
}
func (p *textParser) advance() {
// Skip whitespace
p.skipWhitespace()
if p.done {
return
}
// Start of non-whitespace
p.cur.err = nil
p.cur.offset, p.cur.line = p.offset, p.line
p.cur.unquoted = ""
switch p.s[0] {
case '<', '>', '{', '}', ':', '[', ']', ';', ',':
// Single symbol
p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)]
case '"', '\'':
// Quoted string
i := 1
for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' {
if p.s[i] == '\\' && i+1 < len(p.s) {
// skip escaped char
i++
}
i++
}
if i >= len(p.s) || p.s[i] != p.s[0] {
p.errorf("unmatched quote")
return
}
unq, err := unquoteC(p.s[1:i], rune(p.s[0]))
if err != nil {
p.errorf("invalid quoted string %v", p.s[0:i+1])
return
}
p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)]
p.cur.unquoted = unq
default:
i := 0
for i < len(p.s) && isIdentOrNumberChar(p.s[i]) {
i++
}
if i == 0 {
p.errorf("unexpected byte %#x", p.s[0])
return
}
p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)]
}
p.offset += len(p.cur.value)
}
var (
errBadUTF8 = errors.New("proto: bad UTF-8")
errBadHex = errors.New("proto: bad hexadecimal")
)
func unquoteC(s string, quote rune) (string, error) {
// This is based on C++'s tokenizer.cc.
// Despite its name, this is *not* parsing C syntax.
// For instance, "\0" is an invalid quoted string.
// Avoid allocation in trivial cases.
simple := true
for _, r := range s {
if r == '\\' || r == quote {
simple = false
break
}
}
if simple {
return s, nil
}
buf := make([]byte, 0, 3*len(s)/2)
for len(s) > 0 {
r, n := utf8.DecodeRuneInString(s)
if r == utf8.RuneError && n == 1 {
return "", errBadUTF8
}
s = s[n:]
if r != '\\' {
if r < utf8.RuneSelf {
buf = append(buf, byte(r))
} else {
buf = append(buf, string(r)...)
}
continue
}
ch, tail, err := unescape(s)
if err != nil {
return "", err
}
buf = append(buf, ch...)
s = tail
}
return string(buf), nil
}
func unescape(s string) (ch string, tail string, err error) {
r, n := utf8.DecodeRuneInString(s)
if r == utf8.RuneError && n == 1 {
return "", "", errBadUTF8
}
s = s[n:]
switch r {
case 'a':
return "\a", s, nil
case 'b':
return "\b", s, nil
case 'f':
return "\f", s, nil
case 'n':
return "\n", s, nil
case 'r':
return "\r", s, nil
case 't':
return "\t", s, nil
case 'v':
return "\v", s, nil
case '?':
return "?", s, nil // trigraph workaround
case '\'', '"', '\\':
return string(r), s, nil
case '0', '1', '2', '3', '4', '5', '6', '7', 'x', 'X':
if len(s) < 2 {
return "", "", fmt.Errorf(`\%c requires 2 following digits`, r)
}
base := 8
ss := s[:2]
s = s[2:]
if r == 'x' || r == 'X' {
base = 16
} else {
ss = string(r) + ss
}
i, err := strconv.ParseUint(ss, base, 8)
if err != nil {
return "", "", err
}
return string([]byte{byte(i)}), s, nil
case 'u', 'U':
n := 4
if r == 'U' {
n = 8
}
if len(s) < n {
return "", "", fmt.Errorf(`\%c requires %d digits`, r, n)
}
bs := make([]byte, n/2)
for i := 0; i < n; i += 2 {
a, ok1 := unhex(s[i])
b, ok2 := unhex(s[i+1])
if !ok1 || !ok2 {
return "", "", errBadHex
}
bs[i/2] = a<<4 | b
}
s = s[n:]
return string(bs), s, nil
}
return "", "", fmt.Errorf(`unknown escape \%c`, r)
}
// Adapted from src/pkg/strconv/quote.go.
func unhex(b byte) (v byte, ok bool) {
switch {
case '0' <= b && b <= '9':
return b - '0', true
case 'a' <= b && b <= 'f':
return b - 'a' + 10, true
case 'A' <= b && b <= 'F':
return b - 'A' + 10, true
}
return 0, false
}
// Back off the parser by one token. Can only be done between calls to next().
// It makes the next advance() a no-op.
func (p *textParser) back() { p.backed = true }
// Advances the parser and returns the new current token.
func (p *textParser) next() *token {
if p.backed || p.done {
p.backed = false
return &p.cur
}
p.advance()
if p.done {
p.cur.value = ""
} else if len(p.cur.value) > 0 && p.cur.value[0] == '"' {
// Look for multiple quoted strings separated by whitespace,
// and concatenate them.
cat := p.cur
for {
p.skipWhitespace()
if p.done || p.s[0] != '"' {
break
}
p.advance()
if p.cur.err != nil {
return &p.cur
}
cat.value += " " + p.cur.value
cat.unquoted += p.cur.unquoted
}
p.done = false // parser may have seen EOF, but we want to return cat
p.cur = cat
}
return &p.cur
}
// Return a RequiredNotSetError indicating which required field was not set.
func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError {
st := sv.Type()
sprops := GetProperties(st)
for i := 0; i < st.NumField(); i++ {
if !isNil(sv.Field(i)) {
continue
}
props := sprops.Prop[i]
if props.Required {
return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)}
}
}
return &RequiredNotSetError{fmt.Sprintf("%v.<unknown field name>", st)} // should not happen
}
// Returns the index in the struct for the named field, as well as the parsed tag properties.
func structFieldByName(st reflect.Type, name string) (int, *Properties, bool) {
sprops := GetProperties(st)
i, ok := sprops.decoderOrigNames[name]
if ok {
return i, sprops.Prop[i], true
}
return -1, nil, false
}
// Consume a ':' from the input stream (if the next token is a colon),
// returning an error if a colon is needed but not present.
func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError {
tok := p.next()
if tok.err != nil {
return tok.err
}
if tok.value != ":" {
// Colon is optional when the field is a group or message.
needColon := true
switch props.Wire {
case "group":
needColon = false
case "bytes":
// A "bytes" field is either a message, a string, or a repeated field;
// those three become *T, *string and []T respectively, so we can check for
// this field being a pointer to a non-string.
if typ.Kind() == reflect.Ptr {
// *T or *string
if typ.Elem().Kind() == reflect.String {
break
}
} else if typ.Kind() == reflect.Slice {
// []T or []*T
if typ.Elem().Kind() != reflect.Ptr {
break
}
}
needColon = false
}
if needColon {
return p.errorf("expected ':', found %q", tok.value)
}
p.back()
}
return nil
}
func (p *textParser) readStruct(sv reflect.Value, terminator string) error {
st := sv.Type()
reqCount := GetProperties(st).reqCount
var reqFieldErr error
fieldSet := make(map[string]bool)
// A struct is a sequence of "name: value", terminated by one of
// '>' or '}', or the end of the input. A name may also be
// "[extension]".
for {
tok := p.next()
if tok.err != nil {
return tok.err
}
if tok.value == terminator {
break
}
if tok.value == "[" {
// Looks like an extension.
//
// TODO: Check whether we need to handle
// namespace rooted names (e.g. ".something.Foo").
tok = p.next()
if tok.err != nil {
return tok.err
}
var desc *ExtensionDesc
// This could be faster, but it's functional.
// TODO: Do something smarter than a linear scan.
for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) {
if d.Name == tok.value {
desc = d
break
}
}
if desc == nil {
return p.errorf("unrecognized extension %q", tok.value)
}
// Check the extension terminator.
tok = p.next()
if tok.err != nil {
return tok.err
}
if tok.value != "]" {
return p.errorf("unrecognized extension terminator %q", tok.value)
}
props := &Properties{}
props.Parse(desc.Tag)
typ := reflect.TypeOf(desc.ExtensionType)
if err := p.checkForColon(props, typ); err != nil {
return err
}
rep := desc.repeated()
// Read the extension structure, and set it in
// the value we're constructing.
var ext reflect.Value
if !rep {
ext = reflect.New(typ).Elem()
} else {
ext = reflect.New(typ.Elem()).Elem()
}
if err := p.readAny(ext, props); err != nil {
if _, ok := err.(*RequiredNotSetError); !ok {
return err
}
reqFieldErr = err
}
ep := sv.Addr().Interface().(extendableProto)
if !rep {
SetExtension(ep, desc, ext.Interface())
} else {
old, err := GetExtension(ep, desc)
var sl reflect.Value
if err == nil {
sl = reflect.ValueOf(old) // existing slice
} else {
sl = reflect.MakeSlice(typ, 0, 1)
}
sl = reflect.Append(sl, ext)
SetExtension(ep, desc, sl.Interface())
}
} else {
// This is a normal, non-extension field.
name := tok.value
fi, props, ok := structFieldByName(st, name)
if !ok {
return p.errorf("unknown field name %q in %v", name, st)
}
dst := sv.Field(fi)
// Check that it's not already set if it's not a repeated field.
if !props.Repeated && fieldSet[name] {
return p.errorf("non-repeated field %q was repeated", name)
}
if err := p.checkForColon(props, st.Field(fi).Type); err != nil {
return err
}
// Parse into the field.
fieldSet[name] = true
if err := p.readAny(dst, props); err != nil {
if _, ok := err.(*RequiredNotSetError); !ok {
return err
}
reqFieldErr = err
} else if props.Required {
reqCount--
}
}
// For backward compatibility, permit a semicolon or comma after a field.
tok = p.next()
if tok.err != nil {
return tok.err
}
if tok.value != ";" && tok.value != "," {
p.back()
}
}
if reqCount > 0 {
return p.missingRequiredFieldError(sv)
}
return reqFieldErr
}
func (p *textParser) readAny(v reflect.Value, props *Properties) error {
tok := p.next()
if tok.err != nil {
return tok.err
}
if tok.value == "" {
return p.errorf("unexpected EOF")
}
switch fv := v; fv.Kind() {
case reflect.Slice:
at := v.Type()
if at.Elem().Kind() == reflect.Uint8 {
// Special case for []byte
if tok.value[0] != '"' && tok.value[0] != '\'' {
// Deliberately written out here, as the error after
// this switch statement would write "invalid []byte: ...",
// which is not as user-friendly.
return p.errorf("invalid string: %v", tok.value)
}
bytes := []byte(tok.unquoted)
fv.Set(reflect.ValueOf(bytes))
return nil
}
// Repeated field. May already exist.
flen := fv.Len()
if flen == fv.Cap() {
nav := reflect.MakeSlice(at, flen, 2*flen+1)
reflect.Copy(nav, fv)
fv.Set(nav)
}
fv.SetLen(flen + 1)
// Read one.
p.back()
return p.readAny(fv.Index(flen), props)
case reflect.Bool:
// Either "true", "false", 1 or 0.
switch tok.value {
case "true", "1":
fv.SetBool(true)
return nil
case "false", "0":
fv.SetBool(false)
return nil
}
case reflect.Float32, reflect.Float64:
v := tok.value
// Ignore 'f' for compatibility with output generated by C++, but don't
// remove 'f' when the value is "-inf" or "inf".
if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" {
v = v[:len(v)-1]
}
if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil {
fv.SetFloat(f)
return nil
}
case reflect.Int32:
if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil {
fv.SetInt(x)
return nil
}
if len(props.Enum) == 0 {
break
}
m, ok := enumValueMaps[props.Enum]
if !ok {
break
}
x, ok := m[tok.value]
if !ok {
break
}
fv.SetInt(int64(x))
return nil
case reflect.Int64:
if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil {
fv.SetInt(x)
return nil
}
case reflect.Ptr:
// A basic field (indirected through pointer), or a repeated message/group
p.back()
fv.Set(reflect.New(fv.Type().Elem()))
return p.readAny(fv.Elem(), props)
case reflect.String:
if tok.value[0] == '"' || tok.value[0] == '\'' {
fv.SetString(tok.unquoted)
return nil
}
case reflect.Struct:
var terminator string
switch tok.value {
case "{":
terminator = "}"
case "<":
terminator = ">"
default:
return p.errorf("expected '{' or '<', found %q", tok.value)
}
// TODO: Handle nested messages which implement textUnmarshaler.
return p.readStruct(fv, terminator)
case reflect.Uint32:
if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil {
fv.SetUint(uint64(x))
return nil
}
case reflect.Uint64:
if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil {
fv.SetUint(x)
return nil
}
}
return p.errorf("invalid %v: %v", v.Type(), tok.value)
}
// UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb
// before starting to unmarshal, so any existing data in pb is always removed.
// If a required field is not set and no other error occurs,
// UnmarshalText returns *RequiredNotSetError.
func UnmarshalText(s string, pb Message) error {
if um, ok := pb.(textUnmarshaler); ok {
err := um.UnmarshalText([]byte(s))
return err
}
pb.Reset()
v := reflect.ValueOf(pb)
if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil {
return pe
}
return nil
}
| 109609524-goprotobuf | proto/text_parser.go | Go | bsd | 17,201 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2011 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Protocol buffer deep copy.
// TODO: MessageSet and RawMessage.
package proto
import (
"log"
"reflect"
"strings"
)
// Clone returns a deep copy of a protocol buffer.
func Clone(pb Message) Message {
in := reflect.ValueOf(pb)
if in.IsNil() {
return pb
}
out := reflect.New(in.Type().Elem())
// out is empty so a merge is a deep copy.
mergeStruct(out.Elem(), in.Elem())
return out.Interface().(Message)
}
// Merge merges src into dst.
// Required and optional fields that are set in src will be set to that value in dst.
// Elements of repeated fields will be appended.
// Merge panics if src and dst are not the same type, or if dst is nil.
func Merge(dst, src Message) {
in := reflect.ValueOf(src)
out := reflect.ValueOf(dst)
if out.IsNil() {
panic("proto: nil destination")
}
if in.Type() != out.Type() {
// Explicit test prior to mergeStruct so that mistyped nils will fail
panic("proto: type mismatch")
}
if in.IsNil() {
// Merging nil into non-nil is a quiet no-op
return
}
mergeStruct(out.Elem(), in.Elem())
}
func mergeStruct(out, in reflect.Value) {
for i := 0; i < in.NumField(); i++ {
f := in.Type().Field(i)
if strings.HasPrefix(f.Name, "XXX_") {
continue
}
mergeAny(out.Field(i), in.Field(i))
}
if emIn, ok := in.Addr().Interface().(extendableProto); ok {
emOut := out.Addr().Interface().(extendableProto)
mergeExtension(emOut.ExtensionMap(), emIn.ExtensionMap())
}
uf := in.FieldByName("XXX_unrecognized")
if !uf.IsValid() {
return
}
uin := uf.Bytes()
if len(uin) > 0 {
out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...))
}
}
func mergeAny(out, in reflect.Value) {
if in.Type() == protoMessageType {
if !in.IsNil() {
if out.IsNil() {
out.Set(reflect.ValueOf(Clone(in.Interface().(Message))))
} else {
Merge(out.Interface().(Message), in.Interface().(Message))
}
}
return
}
switch in.Kind() {
case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
reflect.String, reflect.Uint32, reflect.Uint64:
out.Set(in)
case reflect.Ptr:
if in.IsNil() {
return
}
if out.IsNil() {
out.Set(reflect.New(in.Elem().Type()))
}
mergeAny(out.Elem(), in.Elem())
case reflect.Slice:
if in.IsNil() {
return
}
if in.Type().Elem().Kind() == reflect.Uint8 {
// []byte is a scalar bytes field, not a repeated field.
// Make a deep copy.
out.SetBytes(append([]byte(nil), in.Bytes()...))
return
}
n := in.Len()
if out.IsNil() {
out.Set(reflect.MakeSlice(in.Type(), 0, n))
}
switch in.Type().Elem().Kind() {
case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
reflect.String, reflect.Uint32, reflect.Uint64:
out.Set(reflect.AppendSlice(out, in))
default:
for i := 0; i < n; i++ {
x := reflect.Indirect(reflect.New(in.Type().Elem()))
mergeAny(x, in.Index(i))
out.Set(reflect.Append(out, x))
}
}
case reflect.Struct:
mergeStruct(out, in)
default:
// unknown type, so not a protocol buffer
log.Printf("proto: don't know how to copy %v", in)
}
}
func mergeExtension(out, in map[int32]Extension) {
for extNum, eIn := range in {
eOut := Extension{desc: eIn.desc}
if eIn.value != nil {
v := reflect.New(reflect.TypeOf(eIn.value)).Elem()
mergeAny(v, reflect.ValueOf(eIn.value))
eOut.value = v.Interface()
}
if eIn.enc != nil {
eOut.enc = make([]byte, len(eIn.enc))
copy(eOut.enc, eIn.enc)
}
out[extNum] = eOut
}
}
| 109609524-goprotobuf | proto/clone.go | Go | bsd | 5,163 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2011 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Protocol buffer comparison.
// TODO: MessageSet.
package proto
import (
"bytes"
"log"
"reflect"
"strings"
)
/*
Equal returns true iff protocol buffers a and b are equal.
The arguments must both be pointers to protocol buffer structs.
Equality is defined in this way:
- Two messages are equal iff they are the same type,
corresponding fields are equal, unknown field sets
are equal, and extensions sets are equal.
- Two set scalar fields are equal iff their values are equal.
If the fields are of a floating-point type, remember that
NaN != x for all x, including NaN.
- Two repeated fields are equal iff their lengths are the same,
and their corresponding elements are equal (a "bytes" field,
although represented by []byte, is not a repeated field)
- Two unset fields are equal.
- Two unknown field sets are equal if their current
encoded state is equal.
- Two extension sets are equal iff they have corresponding
elements that are pairwise equal.
- Every other combination of things are not equal.
The return value is undefined if a and b are not protocol buffers.
*/
func Equal(a, b Message) bool {
if a == nil || b == nil {
return a == b
}
v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b)
if v1.Type() != v2.Type() {
return false
}
if v1.Kind() == reflect.Ptr {
if v1.IsNil() {
return v2.IsNil()
}
if v2.IsNil() {
return false
}
v1, v2 = v1.Elem(), v2.Elem()
}
if v1.Kind() != reflect.Struct {
return false
}
return equalStruct(v1, v2)
}
// v1 and v2 are known to have the same type.
func equalStruct(v1, v2 reflect.Value) bool {
for i := 0; i < v1.NumField(); i++ {
f := v1.Type().Field(i)
if strings.HasPrefix(f.Name, "XXX_") {
continue
}
f1, f2 := v1.Field(i), v2.Field(i)
if f.Type.Kind() == reflect.Ptr {
if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 {
// both unset
continue
} else if n1 != n2 {
// set/unset mismatch
return false
}
b1, ok := f1.Interface().(raw)
if ok {
b2 := f2.Interface().(raw)
// RawMessage
if !bytes.Equal(b1.Bytes(), b2.Bytes()) {
return false
}
continue
}
f1, f2 = f1.Elem(), f2.Elem()
}
if !equalAny(f1, f2) {
return false
}
}
if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() {
em2 := v2.FieldByName("XXX_extensions")
if !equalExtensions(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) {
return false
}
}
uf := v1.FieldByName("XXX_unrecognized")
if !uf.IsValid() {
return true
}
u1 := uf.Bytes()
u2 := v2.FieldByName("XXX_unrecognized").Bytes()
if !bytes.Equal(u1, u2) {
return false
}
return true
}
// v1 and v2 are known to have the same type.
func equalAny(v1, v2 reflect.Value) bool {
if v1.Type() == protoMessageType {
m1, _ := v1.Interface().(Message)
m2, _ := v2.Interface().(Message)
return Equal(m1, m2)
}
switch v1.Kind() {
case reflect.Bool:
return v1.Bool() == v2.Bool()
case reflect.Float32, reflect.Float64:
return v1.Float() == v2.Float()
case reflect.Int32, reflect.Int64:
return v1.Int() == v2.Int()
case reflect.Ptr:
return equalAny(v1.Elem(), v2.Elem())
case reflect.Slice:
if v1.Type().Elem().Kind() == reflect.Uint8 {
// short circuit: []byte
if v1.IsNil() != v2.IsNil() {
return false
}
return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte))
}
if v1.Len() != v2.Len() {
return false
}
for i := 0; i < v1.Len(); i++ {
if !equalAny(v1.Index(i), v2.Index(i)) {
return false
}
}
return true
case reflect.String:
return v1.Interface().(string) == v2.Interface().(string)
case reflect.Struct:
return equalStruct(v1, v2)
case reflect.Uint32, reflect.Uint64:
return v1.Uint() == v2.Uint()
}
// unknown type, so not a protocol buffer
log.Printf("proto: don't know how to compare %v", v1)
return false
}
// base is the struct type that the extensions are based on.
// em1 and em2 are extension maps.
func equalExtensions(base reflect.Type, em1, em2 map[int32]Extension) bool {
if len(em1) != len(em2) {
return false
}
for extNum, e1 := range em1 {
e2, ok := em2[extNum]
if !ok {
return false
}
m1, m2 := e1.value, e2.value
if m1 != nil && m2 != nil {
// Both are unencoded.
if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2)) {
return false
}
continue
}
// At least one is encoded. To do a semantically correct comparison
// we need to unmarshal them first.
var desc *ExtensionDesc
if m := extensionMaps[base]; m != nil {
desc = m[extNum]
}
if desc == nil {
log.Printf("proto: don't know how to compare extension %d of %v", extNum, base)
continue
}
var err error
if m1 == nil {
m1, err = decodeExtension(e1.enc, desc)
}
if m2 == nil && err == nil {
m2, err = decodeExtension(e2.enc, desc)
}
if err != nil {
// The encoded form is invalid.
log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err)
return false
}
if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2)) {
return false
}
}
return true
}
| 109609524-goprotobuf | proto/equal.go | Go | bsd | 6,793 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2012 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// +build !appengine appenginevm
// This file contains the implementation of the proto field accesses using package unsafe.
package proto
import (
"reflect"
"unsafe"
)
// NOTE: These type_Foo functions would more idiomatically be methods,
// but Go does not allow methods on pointer types, and we must preserve
// some pointer type for the garbage collector. We use these
// funcs with clunky names as our poor approximation to methods.
//
// An alternative would be
// type structPointer struct { p unsafe.Pointer }
// but that does not registerize as well.
// A structPointer is a pointer to a struct.
type structPointer unsafe.Pointer
// toStructPointer returns a structPointer equivalent to the given reflect value.
func toStructPointer(v reflect.Value) structPointer {
return structPointer(unsafe.Pointer(v.Pointer()))
}
// IsNil reports whether p is nil.
func structPointer_IsNil(p structPointer) bool {
return p == nil
}
// Interface returns the struct pointer, assumed to have element type t,
// as an interface value.
func structPointer_Interface(p structPointer, t reflect.Type) interface{} {
return reflect.NewAt(t, unsafe.Pointer(p)).Interface()
}
// A field identifies a field in a struct, accessible from a structPointer.
// In this implementation, a field is identified by its byte offset from the start of the struct.
type field uintptr
// toField returns a field equivalent to the given reflect field.
func toField(f *reflect.StructField) field {
return field(f.Offset)
}
// invalidField is an invalid field identifier.
const invalidField = ^field(0)
// IsValid reports whether the field identifier is valid.
func (f field) IsValid() bool {
return f != ^field(0)
}
// Bytes returns the address of a []byte field in the struct.
func structPointer_Bytes(p structPointer, f field) *[]byte {
return (*[]byte)(unsafe.Pointer(uintptr(p) + uintptr(f)))
}
// BytesSlice returns the address of a [][]byte field in the struct.
func structPointer_BytesSlice(p structPointer, f field) *[][]byte {
return (*[][]byte)(unsafe.Pointer(uintptr(p) + uintptr(f)))
}
// Bool returns the address of a *bool field in the struct.
func structPointer_Bool(p structPointer, f field) **bool {
return (**bool)(unsafe.Pointer(uintptr(p) + uintptr(f)))
}
// BoolSlice returns the address of a []bool field in the struct.
func structPointer_BoolSlice(p structPointer, f field) *[]bool {
return (*[]bool)(unsafe.Pointer(uintptr(p) + uintptr(f)))
}
// String returns the address of a *string field in the struct.
func structPointer_String(p structPointer, f field) **string {
return (**string)(unsafe.Pointer(uintptr(p) + uintptr(f)))
}
// StringSlice returns the address of a []string field in the struct.
func structPointer_StringSlice(p structPointer, f field) *[]string {
return (*[]string)(unsafe.Pointer(uintptr(p) + uintptr(f)))
}
// ExtMap returns the address of an extension map field in the struct.
func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension {
return (*map[int32]Extension)(unsafe.Pointer(uintptr(p) + uintptr(f)))
}
// SetStructPointer writes a *struct field in the struct.
func structPointer_SetStructPointer(p structPointer, f field, q structPointer) {
*(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) = q
}
// GetStructPointer reads a *struct field in the struct.
func structPointer_GetStructPointer(p structPointer, f field) structPointer {
return *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f)))
}
// StructPointerSlice the address of a []*struct field in the struct.
func structPointer_StructPointerSlice(p structPointer, f field) *structPointerSlice {
return (*structPointerSlice)(unsafe.Pointer(uintptr(p) + uintptr(f)))
}
// A structPointerSlice represents a slice of pointers to structs (themselves submessages or groups).
type structPointerSlice []structPointer
func (v *structPointerSlice) Len() int { return len(*v) }
func (v *structPointerSlice) Index(i int) structPointer { return (*v)[i] }
func (v *structPointerSlice) Append(p structPointer) { *v = append(*v, p) }
// A word32 is the address of a "pointer to 32-bit value" field.
type word32 **uint32
// IsNil reports whether *v is nil.
func word32_IsNil(p word32) bool {
return *p == nil
}
// Set sets *v to point at a newly allocated word set to x.
func word32_Set(p word32, o *Buffer, x uint32) {
if len(o.uint32s) == 0 {
o.uint32s = make([]uint32, uint32PoolSize)
}
o.uint32s[0] = x
*p = &o.uint32s[0]
o.uint32s = o.uint32s[1:]
}
// Get gets the value pointed at by *v.
func word32_Get(p word32) uint32 {
return **p
}
// Word32 returns the address of a *int32, *uint32, *float32, or *enum field in the struct.
func structPointer_Word32(p structPointer, f field) word32 {
return word32((**uint32)(unsafe.Pointer(uintptr(p) + uintptr(f))))
}
// A word32Slice is a slice of 32-bit values.
type word32Slice []uint32
func (v *word32Slice) Append(x uint32) { *v = append(*v, x) }
func (v *word32Slice) Len() int { return len(*v) }
func (v *word32Slice) Index(i int) uint32 { return (*v)[i] }
// Word32Slice returns the address of a []int32, []uint32, []float32, or []enum field in the struct.
func structPointer_Word32Slice(p structPointer, f field) *word32Slice {
return (*word32Slice)(unsafe.Pointer(uintptr(p) + uintptr(f)))
}
// word64 is like word32 but for 64-bit values.
type word64 **uint64
func word64_Set(p word64, o *Buffer, x uint64) {
if len(o.uint64s) == 0 {
o.uint64s = make([]uint64, uint64PoolSize)
}
o.uint64s[0] = x
*p = &o.uint64s[0]
o.uint64s = o.uint64s[1:]
}
func word64_IsNil(p word64) bool {
return *p == nil
}
func word64_Get(p word64) uint64 {
return **p
}
func structPointer_Word64(p structPointer, f field) word64 {
return word64((**uint64)(unsafe.Pointer(uintptr(p) + uintptr(f))))
}
// word64Slice is like word32Slice but for 64-bit values.
type word64Slice []uint64
func (v *word64Slice) Append(x uint64) { *v = append(*v, x) }
func (v *word64Slice) Len() int { return len(*v) }
func (v *word64Slice) Index(i int) uint64 { return (*v)[i] }
func structPointer_Word64Slice(p structPointer, f field) *word64Slice {
return (*word64Slice)(unsafe.Pointer(uintptr(p) + uintptr(f)))
}
| 109609524-goprotobuf | proto/pointer_unsafe.go | Go | bsd | 7,915 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package proto
/*
* Support for message sets.
*/
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"reflect"
"sort"
)
// ErrNoMessageTypeId occurs when a protocol buffer does not have a message type ID.
// A message type ID is required for storing a protocol buffer in a message set.
var ErrNoMessageTypeId = errors.New("proto does not have a message type ID")
// The first two types (_MessageSet_Item and MessageSet)
// model what the protocol compiler produces for the following protocol message:
// message MessageSet {
// repeated group Item = 1 {
// required int32 type_id = 2;
// required string message = 3;
// };
// }
// That is the MessageSet wire format. We can't use a proto to generate these
// because that would introduce a circular dependency between it and this package.
//
// When a proto1 proto has a field that looks like:
// optional message<MessageSet> info = 3;
// the protocol compiler produces a field in the generated struct that looks like:
// Info *_proto_.MessageSet `protobuf:"bytes,3,opt,name=info"`
// The package is automatically inserted so there is no need for that proto file to
// import this package.
type _MessageSet_Item struct {
TypeId *int32 `protobuf:"varint,2,req,name=type_id"`
Message []byte `protobuf:"bytes,3,req,name=message"`
}
type MessageSet struct {
Item []*_MessageSet_Item `protobuf:"group,1,rep"`
XXX_unrecognized []byte
// TODO: caching?
}
// Make sure MessageSet is a Message.
var _ Message = (*MessageSet)(nil)
// messageTypeIder is an interface satisfied by a protocol buffer type
// that may be stored in a MessageSet.
type messageTypeIder interface {
MessageTypeId() int32
}
func (ms *MessageSet) find(pb Message) *_MessageSet_Item {
mti, ok := pb.(messageTypeIder)
if !ok {
return nil
}
id := mti.MessageTypeId()
for _, item := range ms.Item {
if *item.TypeId == id {
return item
}
}
return nil
}
func (ms *MessageSet) Has(pb Message) bool {
if ms.find(pb) != nil {
return true
}
return false
}
func (ms *MessageSet) Unmarshal(pb Message) error {
if item := ms.find(pb); item != nil {
return Unmarshal(item.Message, pb)
}
if _, ok := pb.(messageTypeIder); !ok {
return ErrNoMessageTypeId
}
return nil // TODO: return error instead?
}
func (ms *MessageSet) Marshal(pb Message) error {
msg, err := Marshal(pb)
if err != nil {
return err
}
if item := ms.find(pb); item != nil {
// reuse existing item
item.Message = msg
return nil
}
mti, ok := pb.(messageTypeIder)
if !ok {
return ErrNoMessageTypeId
}
mtid := mti.MessageTypeId()
ms.Item = append(ms.Item, &_MessageSet_Item{
TypeId: &mtid,
Message: msg,
})
return nil
}
func (ms *MessageSet) Reset() { *ms = MessageSet{} }
func (ms *MessageSet) String() string { return CompactTextString(ms) }
func (*MessageSet) ProtoMessage() {}
// Support for the message_set_wire_format message option.
func skipVarint(buf []byte) []byte {
i := 0
for ; buf[i]&0x80 != 0; i++ {
}
return buf[i+1:]
}
// MarshalMessageSet encodes the extension map represented by m in the message set wire format.
// It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option.
func MarshalMessageSet(m map[int32]Extension) ([]byte, error) {
if err := encodeExtensionMap(m); err != nil {
return nil, err
}
// Sort extension IDs to provide a deterministic encoding.
// See also enc_map in encode.go.
ids := make([]int, 0, len(m))
for id := range m {
ids = append(ids, int(id))
}
sort.Ints(ids)
ms := &MessageSet{Item: make([]*_MessageSet_Item, 0, len(m))}
for _, id := range ids {
e := m[int32(id)]
// Remove the wire type and field number varint, as well as the length varint.
msg := skipVarint(skipVarint(e.enc))
ms.Item = append(ms.Item, &_MessageSet_Item{
TypeId: Int32(int32(id)),
Message: msg,
})
}
return Marshal(ms)
}
// UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format.
// It is called by generated Unmarshal methods on protocol buffer messages with the message_set_wire_format option.
func UnmarshalMessageSet(buf []byte, m map[int32]Extension) error {
ms := new(MessageSet)
if err := Unmarshal(buf, ms); err != nil {
return err
}
for _, item := range ms.Item {
id := *item.TypeId
msg := item.Message
// Restore wire type and field number varint, plus length varint.
// Be careful to preserve duplicate items.
b := EncodeVarint(uint64(id)<<3 | WireBytes)
if ext, ok := m[id]; ok {
// Existing data; rip off the tag and length varint
// so we join the new data correctly.
// We can assume that ext.enc is set because we are unmarshaling.
o := ext.enc[len(b):] // skip wire type and field number
_, n := DecodeVarint(o) // calculate length of length varint
o = o[n:] // skip length varint
msg = append(o, msg...) // join old data and new data
}
b = append(b, EncodeVarint(uint64(len(msg)))...)
b = append(b, msg...)
m[id] = Extension{enc: b}
}
return nil
}
// MarshalMessageSetJSON encodes the extension map represented by m in JSON format.
// It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option.
func MarshalMessageSetJSON(m map[int32]Extension) ([]byte, error) {
var b bytes.Buffer
b.WriteByte('{')
// Process the map in key order for deterministic output.
ids := make([]int32, 0, len(m))
for id := range m {
ids = append(ids, id)
}
sort.Sort(int32Slice(ids)) // int32Slice defined in text.go
for i, id := range ids {
ext := m[id]
if i > 0 {
b.WriteByte(',')
}
msd, ok := messageSetMap[id]
if !ok {
// Unknown type; we can't render it, so skip it.
continue
}
fmt.Fprintf(&b, `"[%s]":`, msd.name)
x := ext.value
if x == nil {
x = reflect.New(msd.t.Elem()).Interface()
if err := Unmarshal(ext.enc, x.(Message)); err != nil {
return nil, err
}
}
d, err := json.Marshal(x)
if err != nil {
return nil, err
}
b.Write(d)
}
b.WriteByte('}')
return b.Bytes(), nil
}
// UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format.
// It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option.
func UnmarshalMessageSetJSON(buf []byte, m map[int32]Extension) error {
// Common-case fast path.
if len(buf) == 0 || bytes.Equal(buf, []byte("{}")) {
return nil
}
// This is fairly tricky, and it's not clear that it is needed.
return errors.New("TODO: UnmarshalMessageSetJSON not yet implemented")
}
// A global registry of types that can be used in a MessageSet.
var messageSetMap = make(map[int32]messageSetDesc)
type messageSetDesc struct {
t reflect.Type // pointer to struct
name string
}
// RegisterMessageSetType is called from the generated code.
func RegisterMessageSetType(m Message, fieldNum int32, name string) {
messageSetMap[fieldNum] = messageSetDesc{
t: reflect.TypeOf(m),
name: name,
}
}
| 109609524-goprotobuf | proto/message_set.go | Go | bsd | 8,724 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package proto
/*
* Routines for decoding protocol buffer data to construct in-memory representations.
*/
import (
"errors"
"fmt"
"io"
"os"
"reflect"
)
// errOverflow is returned when an integer is too large to be represented.
var errOverflow = errors.New("proto: integer overflow")
// The fundamental decoders that interpret bytes on the wire.
// Those that take integer types all return uint64 and are
// therefore of type valueDecoder.
// DecodeVarint reads a varint-encoded integer from the slice.
// It returns the integer and the number of bytes consumed, or
// zero if there is not enough.
// This is the format for the
// int32, int64, uint32, uint64, bool, and enum
// protocol buffer types.
func DecodeVarint(buf []byte) (x uint64, n int) {
// x, n already 0
for shift := uint(0); shift < 64; shift += 7 {
if n >= len(buf) {
return 0, 0
}
b := uint64(buf[n])
n++
x |= (b & 0x7F) << shift
if (b & 0x80) == 0 {
return x, n
}
}
// The number is too large to represent in a 64-bit value.
return 0, 0
}
// DecodeVarint reads a varint-encoded integer from the Buffer.
// This is the format for the
// int32, int64, uint32, uint64, bool, and enum
// protocol buffer types.
func (p *Buffer) DecodeVarint() (x uint64, err error) {
// x, err already 0
i := p.index
l := len(p.buf)
for shift := uint(0); shift < 64; shift += 7 {
if i >= l {
err = io.ErrUnexpectedEOF
return
}
b := p.buf[i]
i++
x |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
p.index = i
return
}
}
// The number is too large to represent in a 64-bit value.
err = errOverflow
return
}
// DecodeFixed64 reads a 64-bit integer from the Buffer.
// This is the format for the
// fixed64, sfixed64, and double protocol buffer types.
func (p *Buffer) DecodeFixed64() (x uint64, err error) {
// x, err already 0
i := p.index + 8
if i < 0 || i > len(p.buf) {
err = io.ErrUnexpectedEOF
return
}
p.index = i
x = uint64(p.buf[i-8])
x |= uint64(p.buf[i-7]) << 8
x |= uint64(p.buf[i-6]) << 16
x |= uint64(p.buf[i-5]) << 24
x |= uint64(p.buf[i-4]) << 32
x |= uint64(p.buf[i-3]) << 40
x |= uint64(p.buf[i-2]) << 48
x |= uint64(p.buf[i-1]) << 56
return
}
// DecodeFixed32 reads a 32-bit integer from the Buffer.
// This is the format for the
// fixed32, sfixed32, and float protocol buffer types.
func (p *Buffer) DecodeFixed32() (x uint64, err error) {
// x, err already 0
i := p.index + 4
if i < 0 || i > len(p.buf) {
err = io.ErrUnexpectedEOF
return
}
p.index = i
x = uint64(p.buf[i-4])
x |= uint64(p.buf[i-3]) << 8
x |= uint64(p.buf[i-2]) << 16
x |= uint64(p.buf[i-1]) << 24
return
}
// DecodeZigzag64 reads a zigzag-encoded 64-bit integer
// from the Buffer.
// This is the format used for the sint64 protocol buffer type.
func (p *Buffer) DecodeZigzag64() (x uint64, err error) {
x, err = p.DecodeVarint()
if err != nil {
return
}
x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63)
return
}
// DecodeZigzag32 reads a zigzag-encoded 32-bit integer
// from the Buffer.
// This is the format used for the sint32 protocol buffer type.
func (p *Buffer) DecodeZigzag32() (x uint64, err error) {
x, err = p.DecodeVarint()
if err != nil {
return
}
x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31))
return
}
// These are not ValueDecoders: they produce an array of bytes or a string.
// bytes, embedded messages
// DecodeRawBytes reads a count-delimited byte buffer from the Buffer.
// This is the format used for the bytes protocol buffer
// type and for embedded messages.
func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) {
n, err := p.DecodeVarint()
if err != nil {
return
}
nb := int(n)
if nb < 0 {
return nil, fmt.Errorf("proto: bad byte length %d", nb)
}
end := p.index + nb
if end < p.index || end > len(p.buf) {
return nil, io.ErrUnexpectedEOF
}
if !alloc {
// todo: check if can get more uses of alloc=false
buf = p.buf[p.index:end]
p.index += nb
return
}
buf = make([]byte, nb)
copy(buf, p.buf[p.index:])
p.index += nb
return
}
// DecodeStringBytes reads an encoded string from the Buffer.
// This is the format used for the proto2 string type.
func (p *Buffer) DecodeStringBytes() (s string, err error) {
buf, err := p.DecodeRawBytes(false)
if err != nil {
return
}
return string(buf), nil
}
// Skip the next item in the buffer. Its wire type is decoded and presented as an argument.
// If the protocol buffer has extensions, and the field matches, add it as an extension.
// Otherwise, if the XXX_unrecognized field exists, append the skipped data there.
func (o *Buffer) skipAndSave(t reflect.Type, tag, wire int, base structPointer, unrecField field) error {
oi := o.index
err := o.skip(t, tag, wire)
if err != nil {
return err
}
if !unrecField.IsValid() {
return nil
}
ptr := structPointer_Bytes(base, unrecField)
// Add the skipped field to struct field
obuf := o.buf
o.buf = *ptr
o.EncodeVarint(uint64(tag<<3 | wire))
*ptr = append(o.buf, obuf[oi:o.index]...)
o.buf = obuf
return nil
}
// Skip the next item in the buffer. Its wire type is decoded and presented as an argument.
func (o *Buffer) skip(t reflect.Type, tag, wire int) error {
var u uint64
var err error
switch wire {
case WireVarint:
_, err = o.DecodeVarint()
case WireFixed64:
_, err = o.DecodeFixed64()
case WireBytes:
_, err = o.DecodeRawBytes(false)
case WireFixed32:
_, err = o.DecodeFixed32()
case WireStartGroup:
for {
u, err = o.DecodeVarint()
if err != nil {
break
}
fwire := int(u & 0x7)
if fwire == WireEndGroup {
break
}
ftag := int(u >> 3)
err = o.skip(t, ftag, fwire)
if err != nil {
break
}
}
default:
err = fmt.Errorf("proto: can't skip unknown wire type %d for %s", wire, t)
}
return err
}
// Unmarshaler is the interface representing objects that can
// unmarshal themselves. The method should reset the receiver before
// decoding starts. The argument points to data that may be
// overwritten, so implementations should not keep references to the
// buffer.
type Unmarshaler interface {
Unmarshal([]byte) error
}
// Unmarshal parses the protocol buffer representation in buf and places the
// decoded result in pb. If the struct underlying pb does not match
// the data in buf, the results can be unpredictable.
//
// Unmarshal resets pb before starting to unmarshal, so any
// existing data in pb is always removed. Use UnmarshalMerge
// to preserve and append to existing data.
func Unmarshal(buf []byte, pb Message) error {
pb.Reset()
return UnmarshalMerge(buf, pb)
}
// UnmarshalMerge parses the protocol buffer representation in buf and
// writes the decoded result to pb. If the struct underlying pb does not match
// the data in buf, the results can be unpredictable.
//
// UnmarshalMerge merges into existing data in pb.
// Most code should use Unmarshal instead.
func UnmarshalMerge(buf []byte, pb Message) error {
// If the object can unmarshal itself, let it.
if u, ok := pb.(Unmarshaler); ok {
return u.Unmarshal(buf)
}
return NewBuffer(buf).Unmarshal(pb)
}
// Unmarshal parses the protocol buffer representation in the
// Buffer and places the decoded result in pb. If the struct
// underlying pb does not match the data in the buffer, the results can be
// unpredictable.
func (p *Buffer) Unmarshal(pb Message) error {
// If the object can unmarshal itself, let it.
if u, ok := pb.(Unmarshaler); ok {
err := u.Unmarshal(p.buf[p.index:])
p.index = len(p.buf)
return err
}
typ, base, err := getbase(pb)
if err != nil {
return err
}
err = p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), false, base)
if collectStats {
stats.Decode++
}
return err
}
// unmarshalType does the work of unmarshaling a structure.
func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, is_group bool, base structPointer) error {
var state errorState
required, reqFields := prop.reqCount, uint64(0)
var err error
for err == nil && o.index < len(o.buf) {
oi := o.index
var u uint64
u, err = o.DecodeVarint()
if err != nil {
break
}
wire := int(u & 0x7)
if wire == WireEndGroup {
if is_group {
return nil // input is satisfied
}
return fmt.Errorf("proto: %s: wiretype end group for non-group", st)
}
tag := int(u >> 3)
if tag <= 0 {
return fmt.Errorf("proto: %s: illegal tag %d (wire type %d)", st, tag, wire)
}
fieldnum, ok := prop.decoderTags.get(tag)
if !ok {
// Maybe it's an extension?
if prop.extendable {
if e := structPointer_Interface(base, st).(extendableProto); isExtensionField(e, int32(tag)) {
if err = o.skip(st, tag, wire); err == nil {
ext := e.ExtensionMap()[int32(tag)] // may be missing
ext.enc = append(ext.enc, o.buf[oi:o.index]...)
e.ExtensionMap()[int32(tag)] = ext
}
continue
}
}
err = o.skipAndSave(st, tag, wire, base, prop.unrecField)
continue
}
p := prop.Prop[fieldnum]
if p.dec == nil {
fmt.Fprintf(os.Stderr, "proto: no protobuf decoder for %s.%s\n", st, st.Field(fieldnum).Name)
continue
}
dec := p.dec
if wire != WireStartGroup && wire != p.WireType {
if wire == WireBytes && p.packedDec != nil {
// a packable field
dec = p.packedDec
} else {
err = fmt.Errorf("proto: bad wiretype for field %s.%s: got wiretype %d, want %d", st, st.Field(fieldnum).Name, wire, p.WireType)
continue
}
}
decErr := dec(o, p, base)
if decErr != nil && !state.shouldContinue(decErr, p) {
err = decErr
}
if err == nil && p.Required {
// Successfully decoded a required field.
if tag <= 64 {
// use bitmap for fields 1-64 to catch field reuse.
var mask uint64 = 1 << uint64(tag-1)
if reqFields&mask == 0 {
// new required field
reqFields |= mask
required--
}
} else {
// This is imprecise. It can be fooled by a required field
// with a tag > 64 that is encoded twice; that's very rare.
// A fully correct implementation would require allocating
// a data structure, which we would like to avoid.
required--
}
}
}
if err == nil {
if is_group {
return io.ErrUnexpectedEOF
}
if state.err != nil {
return state.err
}
if required > 0 {
// Not enough information to determine the exact field. If we use extra
// CPU, we could determine the field only if the missing required field
// has a tag <= 64 and we check reqFields.
return &RequiredNotSetError{"{Unknown}"}
}
}
return err
}
// Individual type decoders
// For each,
// u is the decoded value,
// v is a pointer to the field (pointer) in the struct
// Sizes of the pools to allocate inside the Buffer.
// The goal is modest amortization and allocation
// on at least 16-byte boundaries.
const (
boolPoolSize = 16
uint32PoolSize = 8
uint64PoolSize = 4
)
// Decode a bool.
func (o *Buffer) dec_bool(p *Properties, base structPointer) error {
u, err := p.valDec(o)
if err != nil {
return err
}
if len(o.bools) == 0 {
o.bools = make([]bool, boolPoolSize)
}
o.bools[0] = u != 0
*structPointer_Bool(base, p.field) = &o.bools[0]
o.bools = o.bools[1:]
return nil
}
// Decode an int32.
func (o *Buffer) dec_int32(p *Properties, base structPointer) error {
u, err := p.valDec(o)
if err != nil {
return err
}
word32_Set(structPointer_Word32(base, p.field), o, uint32(u))
return nil
}
// Decode an int64.
func (o *Buffer) dec_int64(p *Properties, base structPointer) error {
u, err := p.valDec(o)
if err != nil {
return err
}
word64_Set(structPointer_Word64(base, p.field), o, u)
return nil
}
// Decode a string.
func (o *Buffer) dec_string(p *Properties, base structPointer) error {
s, err := o.DecodeStringBytes()
if err != nil {
return err
}
sp := new(string)
*sp = s
*structPointer_String(base, p.field) = sp
return nil
}
// Decode a slice of bytes ([]byte).
func (o *Buffer) dec_slice_byte(p *Properties, base structPointer) error {
b, err := o.DecodeRawBytes(true)
if err != nil {
return err
}
*structPointer_Bytes(base, p.field) = b
return nil
}
// Decode a slice of bools ([]bool).
func (o *Buffer) dec_slice_bool(p *Properties, base structPointer) error {
u, err := p.valDec(o)
if err != nil {
return err
}
v := structPointer_BoolSlice(base, p.field)
*v = append(*v, u != 0)
return nil
}
// Decode a slice of bools ([]bool) in packed format.
func (o *Buffer) dec_slice_packed_bool(p *Properties, base structPointer) error {
v := structPointer_BoolSlice(base, p.field)
nn, err := o.DecodeVarint()
if err != nil {
return err
}
nb := int(nn) // number of bytes of encoded bools
y := *v
for i := 0; i < nb; i++ {
u, err := p.valDec(o)
if err != nil {
return err
}
y = append(y, u != 0)
}
*v = y
return nil
}
// Decode a slice of int32s ([]int32).
func (o *Buffer) dec_slice_int32(p *Properties, base structPointer) error {
u, err := p.valDec(o)
if err != nil {
return err
}
structPointer_Word32Slice(base, p.field).Append(uint32(u))
return nil
}
// Decode a slice of int32s ([]int32) in packed format.
func (o *Buffer) dec_slice_packed_int32(p *Properties, base structPointer) error {
v := structPointer_Word32Slice(base, p.field)
nn, err := o.DecodeVarint()
if err != nil {
return err
}
nb := int(nn) // number of bytes of encoded int32s
fin := o.index + nb
if fin < o.index {
return errOverflow
}
for o.index < fin {
u, err := p.valDec(o)
if err != nil {
return err
}
v.Append(uint32(u))
}
return nil
}
// Decode a slice of int64s ([]int64).
func (o *Buffer) dec_slice_int64(p *Properties, base structPointer) error {
u, err := p.valDec(o)
if err != nil {
return err
}
structPointer_Word64Slice(base, p.field).Append(u)
return nil
}
// Decode a slice of int64s ([]int64) in packed format.
func (o *Buffer) dec_slice_packed_int64(p *Properties, base structPointer) error {
v := structPointer_Word64Slice(base, p.field)
nn, err := o.DecodeVarint()
if err != nil {
return err
}
nb := int(nn) // number of bytes of encoded int64s
fin := o.index + nb
if fin < o.index {
return errOverflow
}
for o.index < fin {
u, err := p.valDec(o)
if err != nil {
return err
}
v.Append(u)
}
return nil
}
// Decode a slice of strings ([]string).
func (o *Buffer) dec_slice_string(p *Properties, base structPointer) error {
s, err := o.DecodeStringBytes()
if err != nil {
return err
}
v := structPointer_StringSlice(base, p.field)
*v = append(*v, s)
return nil
}
// Decode a slice of slice of bytes ([][]byte).
func (o *Buffer) dec_slice_slice_byte(p *Properties, base structPointer) error {
b, err := o.DecodeRawBytes(true)
if err != nil {
return err
}
v := structPointer_BytesSlice(base, p.field)
*v = append(*v, b)
return nil
}
// Decode a group.
func (o *Buffer) dec_struct_group(p *Properties, base structPointer) error {
bas := structPointer_GetStructPointer(base, p.field)
if structPointer_IsNil(bas) {
// allocate new nested message
bas = toStructPointer(reflect.New(p.stype))
structPointer_SetStructPointer(base, p.field, bas)
}
return o.unmarshalType(p.stype, p.sprop, true, bas)
}
// Decode an embedded message.
func (o *Buffer) dec_struct_message(p *Properties, base structPointer) (err error) {
raw, e := o.DecodeRawBytes(false)
if e != nil {
return e
}
bas := structPointer_GetStructPointer(base, p.field)
if structPointer_IsNil(bas) {
// allocate new nested message
bas = toStructPointer(reflect.New(p.stype))
structPointer_SetStructPointer(base, p.field, bas)
}
// If the object can unmarshal itself, let it.
if p.isUnmarshaler {
iv := structPointer_Interface(bas, p.stype)
return iv.(Unmarshaler).Unmarshal(raw)
}
obuf := o.buf
oi := o.index
o.buf = raw
o.index = 0
err = o.unmarshalType(p.stype, p.sprop, false, bas)
o.buf = obuf
o.index = oi
return err
}
// Decode a slice of embedded messages.
func (o *Buffer) dec_slice_struct_message(p *Properties, base structPointer) error {
return o.dec_slice_struct(p, false, base)
}
// Decode a slice of embedded groups.
func (o *Buffer) dec_slice_struct_group(p *Properties, base structPointer) error {
return o.dec_slice_struct(p, true, base)
}
// Decode a slice of structs ([]*struct).
func (o *Buffer) dec_slice_struct(p *Properties, is_group bool, base structPointer) error {
v := reflect.New(p.stype)
bas := toStructPointer(v)
structPointer_StructPointerSlice(base, p.field).Append(bas)
if is_group {
err := o.unmarshalType(p.stype, p.sprop, is_group, bas)
return err
}
raw, err := o.DecodeRawBytes(false)
if err != nil {
return err
}
// If the object can unmarshal itself, let it.
if p.isUnmarshaler {
iv := v.Interface()
return iv.(Unmarshaler).Unmarshal(raw)
}
obuf := o.buf
oi := o.index
o.buf = raw
o.index = 0
err = o.unmarshalType(p.stype, p.sprop, is_group, bas)
o.buf = obuf
o.index = oi
return err
}
| 109609524-goprotobuf | proto/decode.go | Go | bsd | 18,597 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package proto
/*
* Types and routines for supporting protocol buffer extensions.
*/
import (
"errors"
"reflect"
"strconv"
"sync"
)
// ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message.
var ErrMissingExtension = errors.New("proto: missing extension")
// ExtensionRange represents a range of message extensions for a protocol buffer.
// Used in code generated by the protocol compiler.
type ExtensionRange struct {
Start, End int32 // both inclusive
}
// extendableProto is an interface implemented by any protocol buffer that may be extended.
type extendableProto interface {
Message
ExtensionRangeArray() []ExtensionRange
ExtensionMap() map[int32]Extension
}
var extendableProtoType = reflect.TypeOf((*extendableProto)(nil)).Elem()
// ExtensionDesc represents an extension specification.
// Used in generated code from the protocol compiler.
type ExtensionDesc struct {
ExtendedType Message // nil pointer to the type that is being extended
ExtensionType interface{} // nil pointer to the extension type
Field int32 // field number
Name string // fully-qualified name of extension, for text formatting
Tag string // protobuf tag style
}
func (ed *ExtensionDesc) repeated() bool {
t := reflect.TypeOf(ed.ExtensionType)
return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8
}
// Extension represents an extension in a message.
type Extension struct {
// When an extension is stored in a message using SetExtension
// only desc and value are set. When the message is marshaled
// enc will be set to the encoded form of the message.
//
// When a message is unmarshaled and contains extensions, each
// extension will have only enc set. When such an extension is
// accessed using GetExtension (or GetExtensions) desc and value
// will be set.
desc *ExtensionDesc
value interface{}
enc []byte
}
// SetRawExtension is for testing only.
func SetRawExtension(base extendableProto, id int32, b []byte) {
base.ExtensionMap()[id] = Extension{enc: b}
}
// isExtensionField returns true iff the given field number is in an extension range.
func isExtensionField(pb extendableProto, field int32) bool {
for _, er := range pb.ExtensionRangeArray() {
if er.Start <= field && field <= er.End {
return true
}
}
return false
}
// checkExtensionTypes checks that the given extension is valid for pb.
func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error {
// Check the extended type.
if a, b := reflect.TypeOf(pb), reflect.TypeOf(extension.ExtendedType); a != b {
return errors.New("proto: bad extended type; " + b.String() + " does not extend " + a.String())
}
// Check the range.
if !isExtensionField(pb, extension.Field) {
return errors.New("proto: bad extension number; not in declared ranges")
}
return nil
}
// extPropKey is sufficient to uniquely identify an extension.
type extPropKey struct {
base reflect.Type
field int32
}
var extProp = struct {
sync.RWMutex
m map[extPropKey]*Properties
}{
m: make(map[extPropKey]*Properties),
}
func extensionProperties(ed *ExtensionDesc) *Properties {
key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field}
extProp.RLock()
if prop, ok := extProp.m[key]; ok {
extProp.RUnlock()
return prop
}
extProp.RUnlock()
extProp.Lock()
defer extProp.Unlock()
// Check again.
if prop, ok := extProp.m[key]; ok {
return prop
}
prop := new(Properties)
prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil)
extProp.m[key] = prop
return prop
}
// encodeExtensionMap encodes any unmarshaled (unencoded) extensions in m.
func encodeExtensionMap(m map[int32]Extension) error {
for k, e := range m {
if e.value == nil || e.desc == nil {
// Extension is only in its encoded form.
continue
}
// We don't skip extensions that have an encoded form set,
// because the extension value may have been mutated after
// the last time this function was called.
et := reflect.TypeOf(e.desc.ExtensionType)
props := extensionProperties(e.desc)
p := NewBuffer(nil)
// If e.value has type T, the encoder expects a *struct{ X T }.
// Pass a *T with a zero field and hope it all works out.
x := reflect.New(et)
x.Elem().Set(reflect.ValueOf(e.value))
if err := props.enc(p, props, toStructPointer(x)); err != nil {
return err
}
e.enc = p.buf
m[k] = e
}
return nil
}
func sizeExtensionMap(m map[int32]Extension) (n int) {
for _, e := range m {
if e.value == nil || e.desc == nil {
// Extension is only in its encoded form.
n += len(e.enc)
continue
}
// We don't skip extensions that have an encoded form set,
// because the extension value may have been mutated after
// the last time this function was called.
et := reflect.TypeOf(e.desc.ExtensionType)
props := extensionProperties(e.desc)
// If e.value has type T, the encoder expects a *struct{ X T }.
// Pass a *T with a zero field and hope it all works out.
x := reflect.New(et)
x.Elem().Set(reflect.ValueOf(e.value))
n += props.size(props, toStructPointer(x))
}
return
}
// HasExtension returns whether the given extension is present in pb.
func HasExtension(pb extendableProto, extension *ExtensionDesc) bool {
// TODO: Check types, field numbers, etc.?
_, ok := pb.ExtensionMap()[extension.Field]
return ok
}
// ClearExtension removes the given extension from pb.
func ClearExtension(pb extendableProto, extension *ExtensionDesc) {
// TODO: Check types, field numbers, etc.?
delete(pb.ExtensionMap(), extension.Field)
}
// GetExtension parses and returns the given extension of pb.
// If the extension is not present it returns ErrMissingExtension.
func GetExtension(pb extendableProto, extension *ExtensionDesc) (interface{}, error) {
if err := checkExtensionTypes(pb, extension); err != nil {
return nil, err
}
e, ok := pb.ExtensionMap()[extension.Field]
if !ok {
return nil, ErrMissingExtension
}
if e.value != nil {
// Already decoded. Check the descriptor, though.
if e.desc != extension {
// This shouldn't happen. If it does, it means that
// GetExtension was called twice with two different
// descriptors with the same field number.
return nil, errors.New("proto: descriptor conflict")
}
return e.value, nil
}
v, err := decodeExtension(e.enc, extension)
if err != nil {
return nil, err
}
// Remember the decoded version and drop the encoded version.
// That way it is safe to mutate what we return.
e.value = v
e.desc = extension
e.enc = nil
return e.value, nil
}
// decodeExtension decodes an extension encoded in b.
func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) {
o := NewBuffer(b)
t := reflect.TypeOf(extension.ExtensionType)
rep := extension.repeated()
props := extensionProperties(extension)
// t is a pointer to a struct, pointer to basic type or a slice.
// Allocate a "field" to store the pointer/slice itself; the
// pointer/slice will be stored here. We pass
// the address of this field to props.dec.
// This passes a zero field and a *t and lets props.dec
// interpret it as a *struct{ x t }.
value := reflect.New(t).Elem()
for {
// Discard wire type and field number varint. It isn't needed.
if _, err := o.DecodeVarint(); err != nil {
return nil, err
}
if err := props.dec(o, props, toStructPointer(value.Addr())); err != nil {
return nil, err
}
if !rep || o.index >= len(o.buf) {
break
}
}
return value.Interface(), nil
}
// GetExtensions returns a slice of the extensions present in pb that are also listed in es.
// The returned slice has the same length as es; missing extensions will appear as nil elements.
func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) {
epb, ok := pb.(extendableProto)
if !ok {
err = errors.New("proto: not an extendable proto")
return
}
extensions = make([]interface{}, len(es))
for i, e := range es {
extensions[i], err = GetExtension(epb, e)
if err == ErrMissingExtension {
err = nil
}
if err != nil {
return
}
}
return
}
// SetExtension sets the specified extension of pb to the specified value.
func SetExtension(pb extendableProto, extension *ExtensionDesc, value interface{}) error {
if err := checkExtensionTypes(pb, extension); err != nil {
return err
}
typ := reflect.TypeOf(extension.ExtensionType)
if typ != reflect.TypeOf(value) {
return errors.New("proto: bad extension value type")
}
pb.ExtensionMap()[extension.Field] = Extension{desc: extension, value: value}
return nil
}
// A global registry of extensions.
// The generated code will register the generated descriptors by calling RegisterExtension.
var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc)
// RegisterExtension is called from the generated code.
func RegisterExtension(desc *ExtensionDesc) {
st := reflect.TypeOf(desc.ExtendedType).Elem()
m := extensionMaps[st]
if m == nil {
m = make(map[int32]*ExtensionDesc)
extensionMaps[st] = m
}
if _, ok := m[desc.Field]; ok {
panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field)))
}
m[desc.Field] = desc
}
// RegisteredExtensions returns a map of the registered extensions of a
// protocol buffer struct, indexed by the extension number.
// The argument pb should be a nil pointer to the struct type.
func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc {
return extensionMaps[reflect.TypeOf(pb).Elem()]
}
| 109609524-goprotobuf | proto/extensions.go | Go | bsd | 11,256 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package proto
/*
* Routines for encoding data into the wire format for protocol buffers.
*/
import (
"errors"
"fmt"
"reflect"
"sort"
)
// RequiredNotSetError is the error returned if Marshal is called with
// a protocol buffer struct whose required fields have not
// all been initialized. It is also the error returned if Unmarshal is
// called with an encoded protocol buffer that does not include all the
// required fields.
//
// When printed, RequiredNotSetError reports the first unset required field in a
// message. If the field cannot be precisely determined, it is reported as
// "{Unknown}".
type RequiredNotSetError struct {
field string
}
func (e *RequiredNotSetError) Error() string {
return fmt.Sprintf("proto: required field %q not set", e.field)
}
var (
// ErrRepeatedHasNil is the error returned if Marshal is called with
// a struct with a repeated field containing a nil element.
ErrRepeatedHasNil = errors.New("proto: repeated field has nil element")
// ErrNil is the error returned if Marshal is called with nil.
ErrNil = errors.New("proto: Marshal called with nil")
)
// The fundamental encoders that put bytes on the wire.
// Those that take integer types all accept uint64 and are
// therefore of type valueEncoder.
const maxVarintBytes = 10 // maximum length of a varint
// EncodeVarint returns the varint encoding of x.
// This is the format for the
// int32, int64, uint32, uint64, bool, and enum
// protocol buffer types.
// Not used by the package itself, but helpful to clients
// wishing to use the same encoding.
func EncodeVarint(x uint64) []byte {
var buf [maxVarintBytes]byte
var n int
for n = 0; x > 127; n++ {
buf[n] = 0x80 | uint8(x&0x7F)
x >>= 7
}
buf[n] = uint8(x)
n++
return buf[0:n]
}
// EncodeVarint writes a varint-encoded integer to the Buffer.
// This is the format for the
// int32, int64, uint32, uint64, bool, and enum
// protocol buffer types.
func (p *Buffer) EncodeVarint(x uint64) error {
for x >= 1<<7 {
p.buf = append(p.buf, uint8(x&0x7f|0x80))
x >>= 7
}
p.buf = append(p.buf, uint8(x))
return nil
}
func sizeVarint(x uint64) (n int) {
for {
n++
x >>= 7
if x == 0 {
break
}
}
return n
}
// EncodeFixed64 writes a 64-bit integer to the Buffer.
// This is the format for the
// fixed64, sfixed64, and double protocol buffer types.
func (p *Buffer) EncodeFixed64(x uint64) error {
p.buf = append(p.buf,
uint8(x),
uint8(x>>8),
uint8(x>>16),
uint8(x>>24),
uint8(x>>32),
uint8(x>>40),
uint8(x>>48),
uint8(x>>56))
return nil
}
func sizeFixed64(x uint64) int {
return 8
}
// EncodeFixed32 writes a 32-bit integer to the Buffer.
// This is the format for the
// fixed32, sfixed32, and float protocol buffer types.
func (p *Buffer) EncodeFixed32(x uint64) error {
p.buf = append(p.buf,
uint8(x),
uint8(x>>8),
uint8(x>>16),
uint8(x>>24))
return nil
}
func sizeFixed32(x uint64) int {
return 4
}
// EncodeZigzag64 writes a zigzag-encoded 64-bit integer
// to the Buffer.
// This is the format used for the sint64 protocol buffer type.
func (p *Buffer) EncodeZigzag64(x uint64) error {
// use signed number to get arithmetic right shift.
return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func sizeZigzag64(x uint64) int {
return sizeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
// EncodeZigzag32 writes a zigzag-encoded 32-bit integer
// to the Buffer.
// This is the format used for the sint32 protocol buffer type.
func (p *Buffer) EncodeZigzag32(x uint64) error {
// use signed number to get arithmetic right shift.
return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
}
func sizeZigzag32(x uint64) int {
return sizeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
}
// EncodeRawBytes writes a count-delimited byte buffer to the Buffer.
// This is the format used for the bytes protocol buffer
// type and for embedded messages.
func (p *Buffer) EncodeRawBytes(b []byte) error {
p.EncodeVarint(uint64(len(b)))
p.buf = append(p.buf, b...)
return nil
}
func sizeRawBytes(b []byte) int {
return sizeVarint(uint64(len(b))) +
len(b)
}
// EncodeStringBytes writes an encoded string to the Buffer.
// This is the format used for the proto2 string type.
func (p *Buffer) EncodeStringBytes(s string) error {
p.EncodeVarint(uint64(len(s)))
p.buf = append(p.buf, s...)
return nil
}
func sizeStringBytes(s string) int {
return sizeVarint(uint64(len(s))) +
len(s)
}
// Marshaler is the interface representing objects that can marshal themselves.
type Marshaler interface {
Marshal() ([]byte, error)
}
// Marshal takes the protocol buffer
// and encodes it into the wire format, returning the data.
func Marshal(pb Message) ([]byte, error) {
// Can the object marshal itself?
if m, ok := pb.(Marshaler); ok {
return m.Marshal()
}
p := NewBuffer(nil)
err := p.Marshal(pb)
var state errorState
if err != nil && !state.shouldContinue(err, nil) {
return nil, err
}
if p.buf == nil && err == nil {
// Return a non-nil slice on success.
return []byte{}, nil
}
return p.buf, err
}
// Marshal takes the protocol buffer
// and encodes it into the wire format, writing the result to the
// Buffer.
func (p *Buffer) Marshal(pb Message) error {
// Can the object marshal itself?
if m, ok := pb.(Marshaler); ok {
data, err := m.Marshal()
if err != nil {
return err
}
p.buf = append(p.buf, data...)
return nil
}
t, base, err := getbase(pb)
if structPointer_IsNil(base) {
return ErrNil
}
if err == nil {
err = p.enc_struct(t.Elem(), GetProperties(t.Elem()), base)
}
if collectStats {
stats.Encode++
}
return err
}
// Size returns the encoded size of a protocol buffer.
func Size(pb Message) (n int) {
// Can the object marshal itself? If so, Size is slow.
// TODO: add Size to Marshaler, or add a Sizer interface.
if m, ok := pb.(Marshaler); ok {
b, _ := m.Marshal()
return len(b)
}
t, base, err := getbase(pb)
if structPointer_IsNil(base) {
return 0
}
if err == nil {
n = size_struct(t.Elem(), GetProperties(t.Elem()), base)
}
if collectStats {
stats.Size++
}
return
}
// Individual type encoders.
// Encode a bool.
func (o *Buffer) enc_bool(p *Properties, base structPointer) error {
v := *structPointer_Bool(base, p.field)
if v == nil {
return ErrNil
}
x := 0
if *v {
x = 1
}
o.buf = append(o.buf, p.tagcode...)
p.valEnc(o, uint64(x))
return nil
}
func size_bool(p *Properties, base structPointer) int {
v := *structPointer_Bool(base, p.field)
if v == nil {
return 0
}
return len(p.tagcode) + 1 // each bool takes exactly one byte
}
// Encode an int32.
func (o *Buffer) enc_int32(p *Properties, base structPointer) error {
v := structPointer_Word32(base, p.field)
if word32_IsNil(v) {
return ErrNil
}
x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range
o.buf = append(o.buf, p.tagcode...)
p.valEnc(o, uint64(x))
return nil
}
func size_int32(p *Properties, base structPointer) (n int) {
v := structPointer_Word32(base, p.field)
if word32_IsNil(v) {
return 0
}
x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range
n += len(p.tagcode)
n += p.valSize(uint64(x))
return
}
// Encode a uint32.
// Exactly the same as int32, except for no sign extension.
func (o *Buffer) enc_uint32(p *Properties, base structPointer) error {
v := structPointer_Word32(base, p.field)
if word32_IsNil(v) {
return ErrNil
}
x := word32_Get(v)
o.buf = append(o.buf, p.tagcode...)
p.valEnc(o, uint64(x))
return nil
}
func size_uint32(p *Properties, base structPointer) (n int) {
v := structPointer_Word32(base, p.field)
if word32_IsNil(v) {
return 0
}
x := word32_Get(v)
n += len(p.tagcode)
n += p.valSize(uint64(x))
return
}
// Encode an int64.
func (o *Buffer) enc_int64(p *Properties, base structPointer) error {
v := structPointer_Word64(base, p.field)
if word64_IsNil(v) {
return ErrNil
}
x := word64_Get(v)
o.buf = append(o.buf, p.tagcode...)
p.valEnc(o, x)
return nil
}
func size_int64(p *Properties, base structPointer) (n int) {
v := structPointer_Word64(base, p.field)
if word64_IsNil(v) {
return 0
}
x := word64_Get(v)
n += len(p.tagcode)
n += p.valSize(x)
return
}
// Encode a string.
func (o *Buffer) enc_string(p *Properties, base structPointer) error {
v := *structPointer_String(base, p.field)
if v == nil {
return ErrNil
}
x := *v
o.buf = append(o.buf, p.tagcode...)
o.EncodeStringBytes(x)
return nil
}
func size_string(p *Properties, base structPointer) (n int) {
v := *structPointer_String(base, p.field)
if v == nil {
return 0
}
x := *v
n += len(p.tagcode)
n += sizeStringBytes(x)
return
}
// All protocol buffer fields are nillable, but be careful.
func isNil(v reflect.Value) bool {
switch v.Kind() {
case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
return v.IsNil()
}
return false
}
// Encode a message struct.
func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error {
var state errorState
structp := structPointer_GetStructPointer(base, p.field)
if structPointer_IsNil(structp) {
return ErrNil
}
// Can the object marshal itself?
if p.isMarshaler {
m := structPointer_Interface(structp, p.stype).(Marshaler)
data, err := m.Marshal()
if err != nil && !state.shouldContinue(err, nil) {
return err
}
o.buf = append(o.buf, p.tagcode...)
o.EncodeRawBytes(data)
return nil
}
o.buf = append(o.buf, p.tagcode...)
return o.enc_len_struct(p.stype, p.sprop, structp, &state)
}
func size_struct_message(p *Properties, base structPointer) int {
structp := structPointer_GetStructPointer(base, p.field)
if structPointer_IsNil(structp) {
return 0
}
// Can the object marshal itself?
if p.isMarshaler {
m := structPointer_Interface(structp, p.stype).(Marshaler)
data, _ := m.Marshal()
n0 := len(p.tagcode)
n1 := sizeRawBytes(data)
return n0 + n1
}
n0 := len(p.tagcode)
n1 := size_struct(p.stype, p.sprop, structp)
n2 := sizeVarint(uint64(n1)) // size of encoded length
return n0 + n1 + n2
}
// Encode a group struct.
func (o *Buffer) enc_struct_group(p *Properties, base structPointer) error {
var state errorState
b := structPointer_GetStructPointer(base, p.field)
if structPointer_IsNil(b) {
return ErrNil
}
o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
err := o.enc_struct(p.stype, p.sprop, b)
if err != nil && !state.shouldContinue(err, nil) {
return err
}
o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
return state.err
}
func size_struct_group(p *Properties, base structPointer) (n int) {
b := structPointer_GetStructPointer(base, p.field)
if structPointer_IsNil(b) {
return 0
}
n += sizeVarint(uint64((p.Tag << 3) | WireStartGroup))
n += size_struct(p.stype, p.sprop, b)
n += sizeVarint(uint64((p.Tag << 3) | WireEndGroup))
return
}
// Encode a slice of bools ([]bool).
func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error {
s := *structPointer_BoolSlice(base, p.field)
l := len(s)
if l == 0 {
return ErrNil
}
for _, x := range s {
o.buf = append(o.buf, p.tagcode...)
v := uint64(0)
if x {
v = 1
}
p.valEnc(o, v)
}
return nil
}
func size_slice_bool(p *Properties, base structPointer) int {
s := *structPointer_BoolSlice(base, p.field)
l := len(s)
if l == 0 {
return 0
}
return l * (len(p.tagcode) + 1) // each bool takes exactly one byte
}
// Encode a slice of bools ([]bool) in packed format.
func (o *Buffer) enc_slice_packed_bool(p *Properties, base structPointer) error {
s := *structPointer_BoolSlice(base, p.field)
l := len(s)
if l == 0 {
return ErrNil
}
o.buf = append(o.buf, p.tagcode...)
o.EncodeVarint(uint64(l)) // each bool takes exactly one byte
for _, x := range s {
v := uint64(0)
if x {
v = 1
}
p.valEnc(o, v)
}
return nil
}
func size_slice_packed_bool(p *Properties, base structPointer) (n int) {
s := *structPointer_BoolSlice(base, p.field)
l := len(s)
if l == 0 {
return 0
}
n += len(p.tagcode)
n += sizeVarint(uint64(l))
n += l // each bool takes exactly one byte
return
}
// Encode a slice of bytes ([]byte).
func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error {
s := *structPointer_Bytes(base, p.field)
if s == nil {
return ErrNil
}
o.buf = append(o.buf, p.tagcode...)
o.EncodeRawBytes(s)
return nil
}
func size_slice_byte(p *Properties, base structPointer) (n int) {
s := *structPointer_Bytes(base, p.field)
if s == nil {
return 0
}
n += len(p.tagcode)
n += sizeRawBytes(s)
return
}
// Encode a slice of int32s ([]int32).
func (o *Buffer) enc_slice_int32(p *Properties, base structPointer) error {
s := structPointer_Word32Slice(base, p.field)
l := s.Len()
if l == 0 {
return ErrNil
}
for i := 0; i < l; i++ {
o.buf = append(o.buf, p.tagcode...)
x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
p.valEnc(o, uint64(x))
}
return nil
}
func size_slice_int32(p *Properties, base structPointer) (n int) {
s := structPointer_Word32Slice(base, p.field)
l := s.Len()
if l == 0 {
return 0
}
for i := 0; i < l; i++ {
n += len(p.tagcode)
x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
n += p.valSize(uint64(x))
}
return
}
// Encode a slice of int32s ([]int32) in packed format.
func (o *Buffer) enc_slice_packed_int32(p *Properties, base structPointer) error {
s := structPointer_Word32Slice(base, p.field)
l := s.Len()
if l == 0 {
return ErrNil
}
// TODO: Reuse a Buffer.
buf := NewBuffer(nil)
for i := 0; i < l; i++ {
x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
p.valEnc(buf, uint64(x))
}
o.buf = append(o.buf, p.tagcode...)
o.EncodeVarint(uint64(len(buf.buf)))
o.buf = append(o.buf, buf.buf...)
return nil
}
func size_slice_packed_int32(p *Properties, base structPointer) (n int) {
s := structPointer_Word32Slice(base, p.field)
l := s.Len()
if l == 0 {
return 0
}
var bufSize int
for i := 0; i < l; i++ {
x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
bufSize += p.valSize(uint64(x))
}
n += len(p.tagcode)
n += sizeVarint(uint64(bufSize))
n += bufSize
return
}
// Encode a slice of uint32s ([]uint32).
// Exactly the same as int32, except for no sign extension.
func (o *Buffer) enc_slice_uint32(p *Properties, base structPointer) error {
s := structPointer_Word32Slice(base, p.field)
l := s.Len()
if l == 0 {
return ErrNil
}
for i := 0; i < l; i++ {
o.buf = append(o.buf, p.tagcode...)
x := s.Index(i)
p.valEnc(o, uint64(x))
}
return nil
}
func size_slice_uint32(p *Properties, base structPointer) (n int) {
s := structPointer_Word32Slice(base, p.field)
l := s.Len()
if l == 0 {
return 0
}
for i := 0; i < l; i++ {
n += len(p.tagcode)
x := s.Index(i)
n += p.valSize(uint64(x))
}
return
}
// Encode a slice of uint32s ([]uint32) in packed format.
// Exactly the same as int32, except for no sign extension.
func (o *Buffer) enc_slice_packed_uint32(p *Properties, base structPointer) error {
s := structPointer_Word32Slice(base, p.field)
l := s.Len()
if l == 0 {
return ErrNil
}
// TODO: Reuse a Buffer.
buf := NewBuffer(nil)
for i := 0; i < l; i++ {
p.valEnc(buf, uint64(s.Index(i)))
}
o.buf = append(o.buf, p.tagcode...)
o.EncodeVarint(uint64(len(buf.buf)))
o.buf = append(o.buf, buf.buf...)
return nil
}
func size_slice_packed_uint32(p *Properties, base structPointer) (n int) {
s := structPointer_Word32Slice(base, p.field)
l := s.Len()
if l == 0 {
return 0
}
var bufSize int
for i := 0; i < l; i++ {
bufSize += p.valSize(uint64(s.Index(i)))
}
n += len(p.tagcode)
n += sizeVarint(uint64(bufSize))
n += bufSize
return
}
// Encode a slice of int64s ([]int64).
func (o *Buffer) enc_slice_int64(p *Properties, base structPointer) error {
s := structPointer_Word64Slice(base, p.field)
l := s.Len()
if l == 0 {
return ErrNil
}
for i := 0; i < l; i++ {
o.buf = append(o.buf, p.tagcode...)
p.valEnc(o, s.Index(i))
}
return nil
}
func size_slice_int64(p *Properties, base structPointer) (n int) {
s := structPointer_Word64Slice(base, p.field)
l := s.Len()
if l == 0 {
return 0
}
for i := 0; i < l; i++ {
n += len(p.tagcode)
n += p.valSize(s.Index(i))
}
return
}
// Encode a slice of int64s ([]int64) in packed format.
func (o *Buffer) enc_slice_packed_int64(p *Properties, base structPointer) error {
s := structPointer_Word64Slice(base, p.field)
l := s.Len()
if l == 0 {
return ErrNil
}
// TODO: Reuse a Buffer.
buf := NewBuffer(nil)
for i := 0; i < l; i++ {
p.valEnc(buf, s.Index(i))
}
o.buf = append(o.buf, p.tagcode...)
o.EncodeVarint(uint64(len(buf.buf)))
o.buf = append(o.buf, buf.buf...)
return nil
}
func size_slice_packed_int64(p *Properties, base structPointer) (n int) {
s := structPointer_Word64Slice(base, p.field)
l := s.Len()
if l == 0 {
return 0
}
var bufSize int
for i := 0; i < l; i++ {
bufSize += p.valSize(s.Index(i))
}
n += len(p.tagcode)
n += sizeVarint(uint64(bufSize))
n += bufSize
return
}
// Encode a slice of slice of bytes ([][]byte).
func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error {
ss := *structPointer_BytesSlice(base, p.field)
l := len(ss)
if l == 0 {
return ErrNil
}
for i := 0; i < l; i++ {
o.buf = append(o.buf, p.tagcode...)
o.EncodeRawBytes(ss[i])
}
return nil
}
func size_slice_slice_byte(p *Properties, base structPointer) (n int) {
ss := *structPointer_BytesSlice(base, p.field)
l := len(ss)
if l == 0 {
return 0
}
n += l * len(p.tagcode)
for i := 0; i < l; i++ {
n += sizeRawBytes(ss[i])
}
return
}
// Encode a slice of strings ([]string).
func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error {
ss := *structPointer_StringSlice(base, p.field)
l := len(ss)
for i := 0; i < l; i++ {
o.buf = append(o.buf, p.tagcode...)
o.EncodeStringBytes(ss[i])
}
return nil
}
func size_slice_string(p *Properties, base structPointer) (n int) {
ss := *structPointer_StringSlice(base, p.field)
l := len(ss)
n += l * len(p.tagcode)
for i := 0; i < l; i++ {
n += sizeStringBytes(ss[i])
}
return
}
// Encode a slice of message structs ([]*struct).
func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) error {
var state errorState
s := structPointer_StructPointerSlice(base, p.field)
l := s.Len()
for i := 0; i < l; i++ {
structp := s.Index(i)
if structPointer_IsNil(structp) {
return ErrRepeatedHasNil
}
// Can the object marshal itself?
if p.isMarshaler {
m := structPointer_Interface(structp, p.stype).(Marshaler)
data, err := m.Marshal()
if err != nil && !state.shouldContinue(err, nil) {
return err
}
o.buf = append(o.buf, p.tagcode...)
o.EncodeRawBytes(data)
continue
}
o.buf = append(o.buf, p.tagcode...)
err := o.enc_len_struct(p.stype, p.sprop, structp, &state)
if err != nil && !state.shouldContinue(err, nil) {
if err == ErrNil {
return ErrRepeatedHasNil
}
return err
}
}
return state.err
}
func size_slice_struct_message(p *Properties, base structPointer) (n int) {
s := structPointer_StructPointerSlice(base, p.field)
l := s.Len()
n += l * len(p.tagcode)
for i := 0; i < l; i++ {
structp := s.Index(i)
if structPointer_IsNil(structp) {
return // return the size up to this point
}
// Can the object marshal itself?
if p.isMarshaler {
m := structPointer_Interface(structp, p.stype).(Marshaler)
data, _ := m.Marshal()
n += len(p.tagcode)
n += sizeRawBytes(data)
continue
}
n0 := size_struct(p.stype, p.sprop, structp)
n1 := sizeVarint(uint64(n0)) // size of encoded length
n += n0 + n1
}
return
}
// Encode a slice of group structs ([]*struct).
func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error {
var state errorState
s := structPointer_StructPointerSlice(base, p.field)
l := s.Len()
for i := 0; i < l; i++ {
b := s.Index(i)
if structPointer_IsNil(b) {
return ErrRepeatedHasNil
}
o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
err := o.enc_struct(p.stype, p.sprop, b)
if err != nil && !state.shouldContinue(err, nil) {
if err == ErrNil {
return ErrRepeatedHasNil
}
return err
}
o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
}
return state.err
}
func size_slice_struct_group(p *Properties, base structPointer) (n int) {
s := structPointer_StructPointerSlice(base, p.field)
l := s.Len()
n += l * sizeVarint(uint64((p.Tag<<3)|WireStartGroup))
n += l * sizeVarint(uint64((p.Tag<<3)|WireEndGroup))
for i := 0; i < l; i++ {
b := s.Index(i)
if structPointer_IsNil(b) {
return // return size up to this point
}
n += size_struct(p.stype, p.sprop, b)
}
return
}
// Encode an extension map.
func (o *Buffer) enc_map(p *Properties, base structPointer) error {
v := *structPointer_ExtMap(base, p.field)
if err := encodeExtensionMap(v); err != nil {
return err
}
// Fast-path for common cases: zero or one extensions.
if len(v) <= 1 {
for _, e := range v {
o.buf = append(o.buf, e.enc...)
}
return nil
}
// Sort keys to provide a deterministic encoding.
keys := make([]int, 0, len(v))
for k := range v {
keys = append(keys, int(k))
}
sort.Ints(keys)
for _, k := range keys {
o.buf = append(o.buf, v[int32(k)].enc...)
}
return nil
}
func size_map(p *Properties, base structPointer) int {
v := *structPointer_ExtMap(base, p.field)
return sizeExtensionMap(v)
}
// Encode a struct.
func (o *Buffer) enc_struct(t reflect.Type, prop *StructProperties, base structPointer) error {
var state errorState
// Encode fields in tag order so that decoders may use optimizations
// that depend on the ordering.
// http://code.google.com/apis/protocolbuffers/docs/encoding.html#order
for _, i := range prop.order {
p := prop.Prop[i]
if p.enc != nil {
err := p.enc(o, p, base)
if err != nil {
if err == ErrNil {
if p.Required && state.err == nil {
state.err = &RequiredNotSetError{p.Name}
}
} else if !state.shouldContinue(err, p) {
return err
}
}
}
}
// Add unrecognized fields at the end.
if prop.unrecField.IsValid() {
v := *structPointer_Bytes(base, prop.unrecField)
if len(v) > 0 {
o.buf = append(o.buf, v...)
}
}
return state.err
}
func size_struct(t reflect.Type, prop *StructProperties, base structPointer) (n int) {
for _, i := range prop.order {
p := prop.Prop[i]
if p.size != nil {
n += p.size(p, base)
}
}
// Add unrecognized fields at the end.
if prop.unrecField.IsValid() {
v := *structPointer_Bytes(base, prop.unrecField)
n += len(v)
}
return
}
var zeroes [20]byte // longer than any conceivable sizeVarint
// Encode a struct, preceded by its encoded length (as a varint).
func (o *Buffer) enc_len_struct(t reflect.Type, prop *StructProperties, base structPointer, state *errorState) error {
iLen := len(o.buf)
o.buf = append(o.buf, 0, 0, 0, 0) // reserve four bytes for length
iMsg := len(o.buf)
err := o.enc_struct(t, prop, base)
if err != nil && !state.shouldContinue(err, nil) {
return err
}
lMsg := len(o.buf) - iMsg
lLen := sizeVarint(uint64(lMsg))
switch x := lLen - (iMsg - iLen); {
case x > 0: // actual length is x bytes larger than the space we reserved
// Move msg x bytes right.
o.buf = append(o.buf, zeroes[:x]...)
copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg])
case x < 0: // actual length is x bytes smaller than the space we reserved
// Move msg x bytes left.
copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg])
o.buf = o.buf[:len(o.buf)+x] // x is negative
}
// Encode the length in the reserved space.
o.buf = o.buf[:iLen]
o.EncodeVarint(uint64(lMsg))
o.buf = o.buf[:len(o.buf)+lMsg]
return state.err
}
// errorState maintains the first error that occurs and updates that error
// with additional context.
type errorState struct {
err error
}
// shouldContinue reports whether encoding should continue upon encountering the
// given error. If the error is RequiredNotSetError, shouldContinue returns true
// and, if this is the first appearance of that error, remembers it for future
// reporting.
//
// If prop is not nil, it may update any error with additional context about the
// field with the error.
func (s *errorState) shouldContinue(err error, prop *Properties) bool {
// Ignore unset required fields.
reqNotSet, ok := err.(*RequiredNotSetError)
if !ok {
return false
}
if s.err == nil {
if prop != nil {
err = &RequiredNotSetError{prop.Name + "." + reqNotSet.field}
}
s.err = err
}
return true
}
| 109609524-goprotobuf | proto/encode.go | Go | bsd | 26,323 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package proto
// Functions for writing the text protocol buffer format.
import (
"bufio"
"bytes"
"fmt"
"io"
"log"
"math"
"os"
"reflect"
"sort"
"strings"
)
var (
newline = []byte("\n")
spaces = []byte(" ")
gtNewline = []byte(">\n")
endBraceNewline = []byte("}\n")
backslashN = []byte{'\\', 'n'}
backslashR = []byte{'\\', 'r'}
backslashT = []byte{'\\', 't'}
backslashDQ = []byte{'\\', '"'}
backslashBS = []byte{'\\', '\\'}
posInf = []byte("inf")
negInf = []byte("-inf")
nan = []byte("nan")
)
type writer interface {
io.Writer
WriteByte(byte) error
}
// textWriter is an io.Writer that tracks its indentation level.
type textWriter struct {
ind int
complete bool // if the current position is a complete line
compact bool // whether to write out as a one-liner
w writer
}
// textMarshaler is implemented by Messages that can marshal themsleves.
// It is identical to encoding.TextMarshaler, introduced in go 1.2,
// which will eventually replace it.
type textMarshaler interface {
MarshalText() (text []byte, err error)
}
func (w *textWriter) WriteString(s string) (n int, err error) {
if !strings.Contains(s, "\n") {
if !w.compact && w.complete {
w.writeIndent()
}
w.complete = false
return io.WriteString(w.w, s)
}
// WriteString is typically called without newlines, so this
// codepath and its copy are rare. We copy to avoid
// duplicating all of Write's logic here.
return w.Write([]byte(s))
}
func (w *textWriter) Write(p []byte) (n int, err error) {
newlines := bytes.Count(p, newline)
if newlines == 0 {
if !w.compact && w.complete {
w.writeIndent()
}
n, err = w.w.Write(p)
w.complete = false
return n, err
}
frags := bytes.SplitN(p, newline, newlines+1)
if w.compact {
for i, frag := range frags {
if i > 0 {
if err := w.w.WriteByte(' '); err != nil {
return n, err
}
n++
}
nn, err := w.w.Write(frag)
n += nn
if err != nil {
return n, err
}
}
return n, nil
}
for i, frag := range frags {
if w.complete {
w.writeIndent()
}
nn, err := w.w.Write(frag)
n += nn
if err != nil {
return n, err
}
if i+1 < len(frags) {
if err := w.w.WriteByte('\n'); err != nil {
return n, err
}
n++
}
}
w.complete = len(frags[len(frags)-1]) == 0
return n, nil
}
func (w *textWriter) WriteByte(c byte) error {
if w.compact && c == '\n' {
c = ' '
}
if !w.compact && w.complete {
w.writeIndent()
}
err := w.w.WriteByte(c)
w.complete = c == '\n'
return err
}
func (w *textWriter) indent() { w.ind++ }
func (w *textWriter) unindent() {
if w.ind == 0 {
log.Printf("proto: textWriter unindented too far")
return
}
w.ind--
}
func writeName(w *textWriter, props *Properties) error {
if _, err := w.WriteString(props.OrigName); err != nil {
return err
}
if props.Wire != "group" {
return w.WriteByte(':')
}
return nil
}
var (
messageSetType = reflect.TypeOf((*MessageSet)(nil)).Elem()
)
// raw is the interface satisfied by RawMessage.
type raw interface {
Bytes() []byte
}
func writeStruct(w *textWriter, sv reflect.Value) error {
if sv.Type() == messageSetType {
return writeMessageSet(w, sv.Addr().Interface().(*MessageSet))
}
st := sv.Type()
sprops := GetProperties(st)
for i := 0; i < sv.NumField(); i++ {
fv := sv.Field(i)
props := sprops.Prop[i]
name := st.Field(i).Name
if strings.HasPrefix(name, "XXX_") {
// There are two XXX_ fields:
// XXX_unrecognized []byte
// XXX_extensions map[int32]proto.Extension
// The first is handled here;
// the second is handled at the bottom of this function.
if name == "XXX_unrecognized" && !fv.IsNil() {
if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil {
return err
}
}
continue
}
if fv.Kind() == reflect.Ptr && fv.IsNil() {
// Field not filled in. This could be an optional field or
// a required field that wasn't filled in. Either way, there
// isn't anything we can show for it.
continue
}
if fv.Kind() == reflect.Slice && fv.IsNil() {
// Repeated field that is empty, or a bytes field that is unused.
continue
}
if props.Repeated && fv.Kind() == reflect.Slice {
// Repeated field.
for j := 0; j < fv.Len(); j++ {
if err := writeName(w, props); err != nil {
return err
}
if !w.compact {
if err := w.WriteByte(' '); err != nil {
return err
}
}
v := fv.Index(j)
if v.Kind() == reflect.Ptr && v.IsNil() {
// A nil message in a repeated field is not valid,
// but we can handle that more gracefully than panicking.
if _, err := w.Write([]byte("<nil>\n")); err != nil {
return err
}
continue
}
if err := writeAny(w, v, props); err != nil {
return err
}
if err := w.WriteByte('\n'); err != nil {
return err
}
}
continue
}
if err := writeName(w, props); err != nil {
return err
}
if !w.compact {
if err := w.WriteByte(' '); err != nil {
return err
}
}
if b, ok := fv.Interface().(raw); ok {
if err := writeRaw(w, b.Bytes()); err != nil {
return err
}
continue
}
// Enums have a String method, so writeAny will work fine.
if err := writeAny(w, fv, props); err != nil {
return err
}
if err := w.WriteByte('\n'); err != nil {
return err
}
}
// Extensions (the XXX_extensions field).
pv := sv.Addr()
if pv.Type().Implements(extendableProtoType) {
if err := writeExtensions(w, pv); err != nil {
return err
}
}
return nil
}
// writeRaw writes an uninterpreted raw message.
func writeRaw(w *textWriter, b []byte) error {
if err := w.WriteByte('<'); err != nil {
return err
}
if !w.compact {
if err := w.WriteByte('\n'); err != nil {
return err
}
}
w.indent()
if err := writeUnknownStruct(w, b); err != nil {
return err
}
w.unindent()
if err := w.WriteByte('>'); err != nil {
return err
}
return nil
}
// writeAny writes an arbitrary field.
func writeAny(w *textWriter, v reflect.Value, props *Properties) error {
v = reflect.Indirect(v)
// Floats have special cases.
if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
x := v.Float()
var b []byte
switch {
case math.IsInf(x, 1):
b = posInf
case math.IsInf(x, -1):
b = negInf
case math.IsNaN(x):
b = nan
}
if b != nil {
_, err := w.Write(b)
return err
}
// Other values are handled below.
}
// We don't attempt to serialise every possible value type; only those
// that can occur in protocol buffers.
switch v.Kind() {
case reflect.Slice:
// Should only be a []byte; repeated fields are handled in writeStruct.
if err := writeString(w, string(v.Interface().([]byte))); err != nil {
return err
}
case reflect.String:
if err := writeString(w, v.String()); err != nil {
return err
}
case reflect.Struct:
// Required/optional group/message.
var bra, ket byte = '<', '>'
if props != nil && props.Wire == "group" {
bra, ket = '{', '}'
}
if err := w.WriteByte(bra); err != nil {
return err
}
if !w.compact {
if err := w.WriteByte('\n'); err != nil {
return err
}
}
w.indent()
if tm, ok := v.Interface().(textMarshaler); ok {
text, err := tm.MarshalText()
if err != nil {
return err
}
if _, err = w.Write(text); err != nil {
return err
}
} else if err := writeStruct(w, v); err != nil {
return err
}
w.unindent()
if err := w.WriteByte(ket); err != nil {
return err
}
default:
_, err := fmt.Fprint(w, v.Interface())
return err
}
return nil
}
// equivalent to C's isprint.
func isprint(c byte) bool {
return c >= 0x20 && c < 0x7f
}
// writeString writes a string in the protocol buffer text format.
// It is similar to strconv.Quote except we don't use Go escape sequences,
// we treat the string as a byte sequence, and we use octal escapes.
// These differences are to maintain interoperability with the other
// languages' implementations of the text format.
func writeString(w *textWriter, s string) error {
// use WriteByte here to get any needed indent
if err := w.WriteByte('"'); err != nil {
return err
}
// Loop over the bytes, not the runes.
for i := 0; i < len(s); i++ {
var err error
// Divergence from C++: we don't escape apostrophes.
// There's no need to escape them, and the C++ parser
// copes with a naked apostrophe.
switch c := s[i]; c {
case '\n':
_, err = w.w.Write(backslashN)
case '\r':
_, err = w.w.Write(backslashR)
case '\t':
_, err = w.w.Write(backslashT)
case '"':
_, err = w.w.Write(backslashDQ)
case '\\':
_, err = w.w.Write(backslashBS)
default:
if isprint(c) {
err = w.w.WriteByte(c)
} else {
_, err = fmt.Fprintf(w.w, "\\%03o", c)
}
}
if err != nil {
return err
}
}
return w.WriteByte('"')
}
func writeMessageSet(w *textWriter, ms *MessageSet) error {
for _, item := range ms.Item {
id := *item.TypeId
if msd, ok := messageSetMap[id]; ok {
// Known message set type.
if _, err := fmt.Fprintf(w, "[%s]: <\n", msd.name); err != nil {
return err
}
w.indent()
pb := reflect.New(msd.t.Elem())
if err := Unmarshal(item.Message, pb.Interface().(Message)); err != nil {
if _, err := fmt.Fprintf(w, "/* bad message: %v */\n", err); err != nil {
return err
}
} else {
if err := writeStruct(w, pb.Elem()); err != nil {
return err
}
}
} else {
// Unknown type.
if _, err := fmt.Fprintf(w, "[%d]: <\n", id); err != nil {
return err
}
w.indent()
if err := writeUnknownStruct(w, item.Message); err != nil {
return err
}
}
w.unindent()
if _, err := w.Write(gtNewline); err != nil {
return err
}
}
return nil
}
func writeUnknownStruct(w *textWriter, data []byte) (err error) {
if !w.compact {
if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil {
return err
}
}
b := NewBuffer(data)
for b.index < len(b.buf) {
x, err := b.DecodeVarint()
if err != nil {
_, err := fmt.Fprintf(w, "/* %v */\n", err)
return err
}
wire, tag := x&7, x>>3
if wire == WireEndGroup {
w.unindent()
if _, err := w.Write(endBraceNewline); err != nil {
return err
}
continue
}
if _, err := fmt.Fprint(w, tag); err != nil {
return err
}
if wire != WireStartGroup {
if err := w.WriteByte(':'); err != nil {
return err
}
}
if !w.compact || wire == WireStartGroup {
if err := w.WriteByte(' '); err != nil {
return err
}
}
switch wire {
case WireBytes:
buf, e := b.DecodeRawBytes(false)
if e == nil {
_, err = fmt.Fprintf(w, "%q", buf)
} else {
_, err = fmt.Fprintf(w, "/* %v */", e)
}
case WireFixed32:
x, err = b.DecodeFixed32()
err = writeUnknownInt(w, x, err)
case WireFixed64:
x, err = b.DecodeFixed64()
err = writeUnknownInt(w, x, err)
case WireStartGroup:
err = w.WriteByte('{')
w.indent()
case WireVarint:
x, err = b.DecodeVarint()
err = writeUnknownInt(w, x, err)
default:
_, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire)
}
if err != nil {
return err
}
if err = w.WriteByte('\n'); err != nil {
return err
}
}
return nil
}
func writeUnknownInt(w *textWriter, x uint64, err error) error {
if err == nil {
_, err = fmt.Fprint(w, x)
} else {
_, err = fmt.Fprintf(w, "/* %v */", err)
}
return err
}
type int32Slice []int32
func (s int32Slice) Len() int { return len(s) }
func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// writeExtensions writes all the extensions in pv.
// pv is assumed to be a pointer to a protocol message struct that is extendable.
func writeExtensions(w *textWriter, pv reflect.Value) error {
emap := extensionMaps[pv.Type().Elem()]
ep := pv.Interface().(extendableProto)
// Order the extensions by ID.
// This isn't strictly necessary, but it will give us
// canonical output, which will also make testing easier.
m := ep.ExtensionMap()
ids := make([]int32, 0, len(m))
for id := range m {
ids = append(ids, id)
}
sort.Sort(int32Slice(ids))
for _, extNum := range ids {
ext := m[extNum]
var desc *ExtensionDesc
if emap != nil {
desc = emap[extNum]
}
if desc == nil {
// Unknown extension.
if err := writeUnknownStruct(w, ext.enc); err != nil {
return err
}
continue
}
pb, err := GetExtension(ep, desc)
if err != nil {
if _, err := fmt.Fprintln(os.Stderr, "proto: failed getting extension: ", err); err != nil {
return err
}
continue
}
// Repeated extensions will appear as a slice.
if !desc.repeated() {
if err := writeExtension(w, desc.Name, pb); err != nil {
return err
}
} else {
v := reflect.ValueOf(pb)
for i := 0; i < v.Len(); i++ {
if err := writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil {
return err
}
}
}
}
return nil
}
func writeExtension(w *textWriter, name string, pb interface{}) error {
if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil {
return err
}
if !w.compact {
if err := w.WriteByte(' '); err != nil {
return err
}
}
if err := writeAny(w, reflect.ValueOf(pb), nil); err != nil {
return err
}
if err := w.WriteByte('\n'); err != nil {
return err
}
return nil
}
func (w *textWriter) writeIndent() {
if !w.complete {
return
}
remain := w.ind * 2
for remain > 0 {
n := remain
if n > len(spaces) {
n = len(spaces)
}
w.w.Write(spaces[:n])
remain -= n
}
w.complete = false
}
func marshalText(w io.Writer, pb Message, compact bool) error {
val := reflect.ValueOf(pb)
if pb == nil || val.IsNil() {
w.Write([]byte("<nil>"))
return nil
}
var bw *bufio.Writer
ww, ok := w.(writer)
if !ok {
bw = bufio.NewWriter(w)
ww = bw
}
aw := &textWriter{
w: ww,
complete: true,
compact: compact,
}
if tm, ok := pb.(textMarshaler); ok {
text, err := tm.MarshalText()
if err != nil {
return err
}
if _, err = aw.Write(text); err != nil {
return err
}
if bw != nil {
return bw.Flush()
}
return nil
}
// Dereference the received pointer so we don't have outer < and >.
v := reflect.Indirect(val)
if err := writeStruct(aw, v); err != nil {
return err
}
if bw != nil {
return bw.Flush()
}
return nil
}
// MarshalText writes a given protocol buffer in text format.
// The only errors returned are from w.
func MarshalText(w io.Writer, pb Message) error {
return marshalText(w, pb, false)
}
// MarshalTextString is the same as MarshalText, but returns the string directly.
func MarshalTextString(pb Message) string {
var buf bytes.Buffer
marshalText(&buf, pb, false)
return buf.String()
}
// CompactText writes a given protocol buffer in compact text format (one line).
func CompactText(w io.Writer, pb Message) error { return marshalText(w, pb, true) }
// CompactTextString is the same as CompactText, but returns the string directly.
func CompactTextString(pb Message) string {
var buf bytes.Buffer
marshalText(&buf, pb, true)
return buf.String()
}
| 109609524-goprotobuf | proto/text.go | Go | bsd | 16,919 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package proto
/*
* Routines for encoding data into the wire format for protocol buffers.
*/
import (
"fmt"
"os"
"reflect"
"sort"
"strconv"
"strings"
"sync"
)
const debug bool = false
// Constants that identify the encoding of a value on the wire.
const (
WireVarint = 0
WireFixed64 = 1
WireBytes = 2
WireStartGroup = 3
WireEndGroup = 4
WireFixed32 = 5
)
const startSize = 10 // initial slice/string sizes
// Encoders are defined in encode.go
// An encoder outputs the full representation of a field, including its
// tag and encoder type.
type encoder func(p *Buffer, prop *Properties, base structPointer) error
// A valueEncoder encodes a single integer in a particular encoding.
type valueEncoder func(o *Buffer, x uint64) error
// Sizers are defined in encode.go
// A sizer returns the encoded size of a field, including its tag and encoder
// type.
type sizer func(prop *Properties, base structPointer) int
// A valueSizer returns the encoded size of a single integer in a particular
// encoding.
type valueSizer func(x uint64) int
// Decoders are defined in decode.go
// A decoder creates a value from its wire representation.
// Unrecognized subelements are saved in unrec.
type decoder func(p *Buffer, prop *Properties, base structPointer) error
// A valueDecoder decodes a single integer in a particular encoding.
type valueDecoder func(o *Buffer) (x uint64, err error)
// tagMap is an optimization over map[int]int for typical protocol buffer
// use-cases. Encoded protocol buffers are often in tag order with small tag
// numbers.
type tagMap struct {
fastTags []int
slowTags map[int]int
}
// tagMapFastLimit is the upper bound on the tag number that will be stored in
// the tagMap slice rather than its map.
const tagMapFastLimit = 1024
func (p *tagMap) get(t int) (int, bool) {
if t > 0 && t < tagMapFastLimit {
if t >= len(p.fastTags) {
return 0, false
}
fi := p.fastTags[t]
return fi, fi >= 0
}
fi, ok := p.slowTags[t]
return fi, ok
}
func (p *tagMap) put(t int, fi int) {
if t > 0 && t < tagMapFastLimit {
for len(p.fastTags) < t+1 {
p.fastTags = append(p.fastTags, -1)
}
p.fastTags[t] = fi
return
}
if p.slowTags == nil {
p.slowTags = make(map[int]int)
}
p.slowTags[t] = fi
}
// StructProperties represents properties for all the fields of a struct.
// decoderTags and decoderOrigNames should only be used by the decoder.
type StructProperties struct {
Prop []*Properties // properties for each field
reqCount int // required count
decoderTags tagMap // map from proto tag to struct field number
decoderOrigNames map[string]int // map from original name to struct field number
order []int // list of struct field numbers in tag order
unrecField field // field id of the XXX_unrecognized []byte field
extendable bool // is this an extendable proto
}
// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec.
// See encode.go, (*Buffer).enc_struct.
func (sp *StructProperties) Len() int { return len(sp.order) }
func (sp *StructProperties) Less(i, j int) bool {
return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag
}
func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] }
// Properties represents the protocol-specific behavior of a single struct field.
type Properties struct {
Name string // name of the field, for error messages
OrigName string // original name before protocol compiler (always set)
Wire string
WireType int
Tag int
Required bool
Optional bool
Repeated bool
Packed bool // relevant for repeated primitives only
Enum string // set for enum types only
Default string // default value
HasDefault bool // whether an explicit default was provided
def_uint64 uint64
enc encoder
valEnc valueEncoder // set for bool and numeric types only
field field
tagcode []byte // encoding of EncodeVarint((Tag<<3)|WireType)
tagbuf [8]byte
stype reflect.Type // set for struct types only
sprop *StructProperties // set for struct types only
isMarshaler bool
isUnmarshaler bool
size sizer
valSize valueSizer // set for bool and numeric types only
dec decoder
valDec valueDecoder // set for bool and numeric types only
// If this is a packable field, this will be the decoder for the packed version of the field.
packedDec decoder
}
// String formats the properties in the protobuf struct field tag style.
func (p *Properties) String() string {
s := p.Wire
s = ","
s += strconv.Itoa(p.Tag)
if p.Required {
s += ",req"
}
if p.Optional {
s += ",opt"
}
if p.Repeated {
s += ",rep"
}
if p.Packed {
s += ",packed"
}
if p.OrigName != p.Name {
s += ",name=" + p.OrigName
}
if len(p.Enum) > 0 {
s += ",enum=" + p.Enum
}
if p.HasDefault {
s += ",def=" + p.Default
}
return s
}
// Parse populates p by parsing a string in the protobuf struct field tag style.
func (p *Properties) Parse(s string) {
// "bytes,49,opt,name=foo,def=hello!"
fields := strings.Split(s, ",") // breaks def=, but handled below.
if len(fields) < 2 {
fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s)
return
}
p.Wire = fields[0]
switch p.Wire {
case "varint":
p.WireType = WireVarint
p.valEnc = (*Buffer).EncodeVarint
p.valDec = (*Buffer).DecodeVarint
p.valSize = sizeVarint
case "fixed32":
p.WireType = WireFixed32
p.valEnc = (*Buffer).EncodeFixed32
p.valDec = (*Buffer).DecodeFixed32
p.valSize = sizeFixed32
case "fixed64":
p.WireType = WireFixed64
p.valEnc = (*Buffer).EncodeFixed64
p.valDec = (*Buffer).DecodeFixed64
p.valSize = sizeFixed64
case "zigzag32":
p.WireType = WireVarint
p.valEnc = (*Buffer).EncodeZigzag32
p.valDec = (*Buffer).DecodeZigzag32
p.valSize = sizeZigzag32
case "zigzag64":
p.WireType = WireVarint
p.valEnc = (*Buffer).EncodeZigzag64
p.valDec = (*Buffer).DecodeZigzag64
p.valSize = sizeZigzag64
case "bytes", "group":
p.WireType = WireBytes
// no numeric converter for non-numeric types
default:
fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s)
return
}
var err error
p.Tag, err = strconv.Atoi(fields[1])
if err != nil {
return
}
for i := 2; i < len(fields); i++ {
f := fields[i]
switch {
case f == "req":
p.Required = true
case f == "opt":
p.Optional = true
case f == "rep":
p.Repeated = true
case f == "packed":
p.Packed = true
case strings.HasPrefix(f, "name="):
p.OrigName = f[5:]
case strings.HasPrefix(f, "enum="):
p.Enum = f[5:]
case strings.HasPrefix(f, "def="):
p.HasDefault = true
p.Default = f[4:] // rest of string
if i+1 < len(fields) {
// Commas aren't escaped, and def is always last.
p.Default += "," + strings.Join(fields[i+1:], ",")
break
}
}
}
}
func logNoSliceEnc(t1, t2 reflect.Type) {
fmt.Fprintf(os.Stderr, "proto: no slice oenc for %T = []%T\n", t1, t2)
}
var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem()
// Initialize the fields for encoding and decoding.
func (p *Properties) setEncAndDec(typ reflect.Type, lockGetProp bool) {
p.enc = nil
p.dec = nil
p.size = nil
switch t1 := typ; t1.Kind() {
default:
fmt.Fprintf(os.Stderr, "proto: no coders for %v\n", t1)
case reflect.Ptr:
switch t2 := t1.Elem(); t2.Kind() {
default:
fmt.Fprintf(os.Stderr, "proto: no encoder function for %T -> %T\n", t1, t2)
break
case reflect.Bool:
p.enc = (*Buffer).enc_bool
p.dec = (*Buffer).dec_bool
p.size = size_bool
case reflect.Int32:
p.enc = (*Buffer).enc_int32
p.dec = (*Buffer).dec_int32
p.size = size_int32
case reflect.Uint32:
p.enc = (*Buffer).enc_uint32
p.dec = (*Buffer).dec_int32 // can reuse
p.size = size_uint32
case reflect.Int64, reflect.Uint64:
p.enc = (*Buffer).enc_int64
p.dec = (*Buffer).dec_int64
p.size = size_int64
case reflect.Float32:
p.enc = (*Buffer).enc_uint32 // can just treat them as bits
p.dec = (*Buffer).dec_int32
p.size = size_uint32
case reflect.Float64:
p.enc = (*Buffer).enc_int64 // can just treat them as bits
p.dec = (*Buffer).dec_int64
p.size = size_int64
case reflect.String:
p.enc = (*Buffer).enc_string
p.dec = (*Buffer).dec_string
p.size = size_string
case reflect.Struct:
p.stype = t1.Elem()
p.isMarshaler = isMarshaler(t1)
p.isUnmarshaler = isUnmarshaler(t1)
if p.Wire == "bytes" {
p.enc = (*Buffer).enc_struct_message
p.dec = (*Buffer).dec_struct_message
p.size = size_struct_message
} else {
p.enc = (*Buffer).enc_struct_group
p.dec = (*Buffer).dec_struct_group
p.size = size_struct_group
}
}
case reflect.Slice:
switch t2 := t1.Elem(); t2.Kind() {
default:
logNoSliceEnc(t1, t2)
break
case reflect.Bool:
if p.Packed {
p.enc = (*Buffer).enc_slice_packed_bool
p.size = size_slice_packed_bool
} else {
p.enc = (*Buffer).enc_slice_bool
p.size = size_slice_bool
}
p.dec = (*Buffer).dec_slice_bool
p.packedDec = (*Buffer).dec_slice_packed_bool
case reflect.Int32:
if p.Packed {
p.enc = (*Buffer).enc_slice_packed_int32
p.size = size_slice_packed_int32
} else {
p.enc = (*Buffer).enc_slice_int32
p.size = size_slice_int32
}
p.dec = (*Buffer).dec_slice_int32
p.packedDec = (*Buffer).dec_slice_packed_int32
case reflect.Uint32:
if p.Packed {
p.enc = (*Buffer).enc_slice_packed_uint32
p.size = size_slice_packed_uint32
} else {
p.enc = (*Buffer).enc_slice_uint32
p.size = size_slice_uint32
}
p.dec = (*Buffer).dec_slice_int32
p.packedDec = (*Buffer).dec_slice_packed_int32
case reflect.Int64, reflect.Uint64:
if p.Packed {
p.enc = (*Buffer).enc_slice_packed_int64
p.size = size_slice_packed_int64
} else {
p.enc = (*Buffer).enc_slice_int64
p.size = size_slice_int64
}
p.dec = (*Buffer).dec_slice_int64
p.packedDec = (*Buffer).dec_slice_packed_int64
case reflect.Uint8:
p.enc = (*Buffer).enc_slice_byte
p.dec = (*Buffer).dec_slice_byte
p.size = size_slice_byte
case reflect.Float32, reflect.Float64:
switch t2.Bits() {
case 32:
// can just treat them as bits
if p.Packed {
p.enc = (*Buffer).enc_slice_packed_uint32
p.size = size_slice_packed_uint32
} else {
p.enc = (*Buffer).enc_slice_uint32
p.size = size_slice_uint32
}
p.dec = (*Buffer).dec_slice_int32
p.packedDec = (*Buffer).dec_slice_packed_int32
case 64:
// can just treat them as bits
if p.Packed {
p.enc = (*Buffer).enc_slice_packed_int64
p.size = size_slice_packed_int64
} else {
p.enc = (*Buffer).enc_slice_int64
p.size = size_slice_int64
}
p.dec = (*Buffer).dec_slice_int64
p.packedDec = (*Buffer).dec_slice_packed_int64
default:
logNoSliceEnc(t1, t2)
break
}
case reflect.String:
p.enc = (*Buffer).enc_slice_string
p.dec = (*Buffer).dec_slice_string
p.size = size_slice_string
case reflect.Ptr:
switch t3 := t2.Elem(); t3.Kind() {
default:
fmt.Fprintf(os.Stderr, "proto: no ptr oenc for %T -> %T -> %T\n", t1, t2, t3)
break
case reflect.Struct:
p.stype = t2.Elem()
p.isMarshaler = isMarshaler(t2)
p.isUnmarshaler = isUnmarshaler(t2)
if p.Wire == "bytes" {
p.enc = (*Buffer).enc_slice_struct_message
p.dec = (*Buffer).dec_slice_struct_message
p.size = size_slice_struct_message
} else {
p.enc = (*Buffer).enc_slice_struct_group
p.dec = (*Buffer).dec_slice_struct_group
p.size = size_slice_struct_group
}
}
case reflect.Slice:
switch t2.Elem().Kind() {
default:
fmt.Fprintf(os.Stderr, "proto: no slice elem oenc for %T -> %T -> %T\n", t1, t2, t2.Elem())
break
case reflect.Uint8:
p.enc = (*Buffer).enc_slice_slice_byte
p.dec = (*Buffer).dec_slice_slice_byte
p.size = size_slice_slice_byte
}
}
}
// precalculate tag code
wire := p.WireType
if p.Packed {
wire = WireBytes
}
x := uint32(p.Tag)<<3 | uint32(wire)
i := 0
for i = 0; x > 127; i++ {
p.tagbuf[i] = 0x80 | uint8(x&0x7F)
x >>= 7
}
p.tagbuf[i] = uint8(x)
p.tagcode = p.tagbuf[0 : i+1]
if p.stype != nil {
if lockGetProp {
p.sprop = GetProperties(p.stype)
} else {
p.sprop = getPropertiesLocked(p.stype)
}
}
}
var (
marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem()
unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
)
// isMarshaler reports whether type t implements Marshaler.
func isMarshaler(t reflect.Type) bool {
// We're checking for (likely) pointer-receiver methods
// so if t is not a pointer, something is very wrong.
// The calls above only invoke isMarshaler on pointer types.
if t.Kind() != reflect.Ptr {
panic("proto: misuse of isMarshaler")
}
return t.Implements(marshalerType)
}
// isUnmarshaler reports whether type t implements Unmarshaler.
func isUnmarshaler(t reflect.Type) bool {
// We're checking for (likely) pointer-receiver methods
// so if t is not a pointer, something is very wrong.
// The calls above only invoke isUnmarshaler on pointer types.
if t.Kind() != reflect.Ptr {
panic("proto: misuse of isUnmarshaler")
}
return t.Implements(unmarshalerType)
}
// Init populates the properties from a protocol buffer struct tag.
func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) {
p.init(typ, name, tag, f, true)
}
func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) {
// "bytes,49,opt,def=hello!"
p.Name = name
p.OrigName = name
if f != nil {
p.field = toField(f)
}
if tag == "" {
return
}
p.Parse(tag)
p.setEncAndDec(typ, lockGetProp)
}
var (
mutex sync.Mutex
propertiesMap = make(map[reflect.Type]*StructProperties)
)
// GetProperties returns the list of properties for the type represented by t.
// t must represent a generated struct type of a protocol message.
func GetProperties(t reflect.Type) *StructProperties {
if t.Kind() != reflect.Struct {
panic("proto: type must have kind struct")
}
mutex.Lock()
sprop := getPropertiesLocked(t)
mutex.Unlock()
return sprop
}
// getPropertiesLocked requires that mutex is held.
func getPropertiesLocked(t reflect.Type) *StructProperties {
if prop, ok := propertiesMap[t]; ok {
if collectStats {
stats.Chit++
}
return prop
}
if collectStats {
stats.Cmiss++
}
prop := new(StructProperties)
// in case of recursive protos, fill this in now.
propertiesMap[t] = prop
// build properties
prop.extendable = reflect.PtrTo(t).Implements(extendableProtoType)
prop.unrecField = invalidField
prop.Prop = make([]*Properties, t.NumField())
prop.order = make([]int, t.NumField())
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
p := new(Properties)
name := f.Name
p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false)
if f.Name == "XXX_extensions" { // special case
p.enc = (*Buffer).enc_map
p.dec = nil // not needed
p.size = size_map
}
if f.Name == "XXX_unrecognized" { // special case
prop.unrecField = toField(&f)
}
prop.Prop[i] = p
prop.order[i] = i
if debug {
print(i, " ", f.Name, " ", t.String(), " ")
if p.Tag > 0 {
print(p.String())
}
print("\n")
}
if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") {
fmt.Fprintln(os.Stderr, "proto: no encoder for", f.Name, f.Type.String(), "[GetProperties]")
}
}
// Re-order prop.order.
sort.Sort(prop)
// build required counts
// build tags
reqCount := 0
prop.decoderOrigNames = make(map[string]int)
for i, p := range prop.Prop {
if strings.HasPrefix(p.Name, "XXX_") {
// Internal fields should not appear in tags/origNames maps.
// They are handled specially when encoding and decoding.
continue
}
if p.Required {
reqCount++
}
prop.decoderTags.put(p.Tag, i)
prop.decoderOrigNames[p.OrigName] = i
}
prop.reqCount = reqCount
return prop
}
// Return the Properties object for the x[0]'th field of the structure.
func propByIndex(t reflect.Type, x []int) *Properties {
if len(x) != 1 {
fmt.Fprintf(os.Stderr, "proto: field index dimension %d (not 1) for type %s\n", len(x), t)
return nil
}
prop := GetProperties(t)
return prop.Prop[x[0]]
}
// Get the address and type of a pointer to a struct from an interface.
func getbase(pb Message) (t reflect.Type, b structPointer, err error) {
if pb == nil {
err = ErrNil
return
}
// get the reflect type of the pointer to the struct.
t = reflect.TypeOf(pb)
// get the address of the struct.
value := reflect.ValueOf(pb)
b = toStructPointer(value)
return
}
// A global registry of enum types.
// The generated code will register the generated maps by calling RegisterEnum.
var enumValueMaps = make(map[string]map[string]int32)
// RegisterEnum is called from the generated code to install the enum descriptor
// maps into the global table to aid parsing text format protocol buffers.
func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) {
if _, ok := enumValueMaps[typeName]; ok {
panic("proto: duplicate enum registered: " + typeName)
}
enumValueMaps[typeName] = valueMap
}
| 109609524-goprotobuf | proto/properties.go | Go | bsd | 19,018 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2010 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/*
Package proto converts data structures to and from the wire format of
protocol buffers. It works in concert with the Go source code generated
for .proto files by the protocol compiler.
A summary of the properties of the protocol buffer interface
for a protocol buffer variable v:
- Names are turned from camel_case to CamelCase for export.
- There are no methods on v to set fields; just treat
them as structure fields.
- There are getters that return a field's value if set,
and return the field's default value if unset.
The getters work even if the receiver is a nil message.
- The zero value for a struct is its correct initialization state.
All desired fields must be set before marshaling.
- A Reset() method will restore a protobuf struct to its zero state.
- Non-repeated fields are pointers to the values; nil means unset.
That is, optional or required field int32 f becomes F *int32.
- Repeated fields are slices.
- Helper functions are available to aid the setting of fields.
Helpers for getting values are superseded by the
GetFoo methods and their use is deprecated.
msg.Foo = proto.String("hello") // set field
- Constants are defined to hold the default values of all fields that
have them. They have the form Default_StructName_FieldName.
Because the getter methods handle defaulted values,
direct use of these constants should be rare.
- Enums are given type names and maps from names to values.
Enum values are prefixed with the enum's type name. Enum types have
a String method, and a Enum method to assist in message construction.
- Nested groups and enums have type names prefixed with the name of
the surrounding message type.
- Extensions are given descriptor names that start with E_,
followed by an underscore-delimited list of the nested messages
that contain it (if any) followed by the CamelCased name of the
extension field itself. HasExtension, ClearExtension, GetExtension
and SetExtension are functions for manipulating extensions.
- Marshal and Unmarshal are functions to encode and decode the wire format.
The simplest way to describe this is to see an example.
Given file test.proto, containing
package example;
enum FOO { X = 17; };
message Test {
required string label = 1;
optional int32 type = 2 [default=77];
repeated int64 reps = 3;
optional group OptionalGroup = 4 {
required string RequiredField = 5;
}
}
The resulting file, test.pb.go, is:
package example
import "code.google.com/p/goprotobuf/proto"
type FOO int32
const (
FOO_X FOO = 17
)
var FOO_name = map[int32]string{
17: "X",
}
var FOO_value = map[string]int32{
"X": 17,
}
func (x FOO) Enum() *FOO {
p := new(FOO)
*p = x
return p
}
func (x FOO) String() string {
return proto.EnumName(FOO_name, int32(x))
}
type Test struct {
Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"`
Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"`
Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"`
Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (this *Test) Reset() { *this = Test{} }
func (this *Test) String() string { return proto.CompactTextString(this) }
const Default_Test_Type int32 = 77
func (this *Test) GetLabel() string {
if this != nil && this.Label != nil {
return *this.Label
}
return ""
}
func (this *Test) GetType() int32 {
if this != nil && this.Type != nil {
return *this.Type
}
return Default_Test_Type
}
func (this *Test) GetOptionalgroup() *Test_OptionalGroup {
if this != nil {
return this.Optionalgroup
}
return nil
}
type Test_OptionalGroup struct {
RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (this *Test_OptionalGroup) Reset() { *this = Test_OptionalGroup{} }
func (this *Test_OptionalGroup) String() string { return proto.CompactTextString(this) }
func (this *Test_OptionalGroup) GetRequiredField() string {
if this != nil && this.RequiredField != nil {
return *this.RequiredField
}
return ""
}
func init() {
proto.RegisterEnum("example.FOO", FOO_name, FOO_value)
}
To create and play with a Test object:
package main
import (
"log"
"code.google.com/p/goprotobuf/proto"
"./example.pb"
)
func main() {
test := &example.Test{
Label: proto.String("hello"),
Type: proto.Int32(17),
Optionalgroup: &example.Test_OptionalGroup{
RequiredField: proto.String("good bye"),
},
}
data, err := proto.Marshal(test)
if err != nil {
log.Fatal("marshaling error: ", err)
}
newTest := new(example.Test)
err = proto.Unmarshal(data, newTest)
if err != nil {
log.Fatal("unmarshaling error: ", err)
}
// Now test and newTest contain the same data.
if test.GetLabel() != newTest.GetLabel() {
log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
}
// etc.
}
*/
package proto
import (
"encoding/json"
"fmt"
"log"
"reflect"
"strconv"
"sync"
)
// Message is implemented by generated protocol buffer messages.
type Message interface {
Reset()
String() string
ProtoMessage()
}
// Stats records allocation details about the protocol buffer encoders
// and decoders. Useful for tuning the library itself.
type Stats struct {
Emalloc uint64 // mallocs in encode
Dmalloc uint64 // mallocs in decode
Encode uint64 // number of encodes
Decode uint64 // number of decodes
Chit uint64 // number of cache hits
Cmiss uint64 // number of cache misses
Size uint64 // number of sizes
}
// Set to true to enable stats collection.
const collectStats = false
var stats Stats
// GetStats returns a copy of the global Stats structure.
func GetStats() Stats { return stats }
// A Buffer is a buffer manager for marshaling and unmarshaling
// protocol buffers. It may be reused between invocations to
// reduce memory usage. It is not necessary to use a Buffer;
// the global functions Marshal and Unmarshal create a
// temporary Buffer and are fine for most applications.
type Buffer struct {
buf []byte // encode/decode byte stream
index int // write point
// pools of basic types to amortize allocation.
bools []bool
uint32s []uint32
uint64s []uint64
// extra pools, only used with pointer_reflect.go
int32s []int32
int64s []int64
float32s []float32
float64s []float64
}
// NewBuffer allocates a new Buffer and initializes its internal data to
// the contents of the argument slice.
func NewBuffer(e []byte) *Buffer {
return &Buffer{buf: e}
}
// Reset resets the Buffer, ready for marshaling a new protocol buffer.
func (p *Buffer) Reset() {
p.buf = p.buf[0:0] // for reading/writing
p.index = 0 // for reading
}
// SetBuf replaces the internal buffer with the slice,
// ready for unmarshaling the contents of the slice.
func (p *Buffer) SetBuf(s []byte) {
p.buf = s
p.index = 0
}
// Bytes returns the contents of the Buffer.
func (p *Buffer) Bytes() []byte { return p.buf }
/*
* Helper routines for simplifying the creation of optional fields of basic type.
*/
// Bool is a helper routine that allocates a new bool value
// to store v and returns a pointer to it.
func Bool(v bool) *bool {
return &v
}
// Int32 is a helper routine that allocates a new int32 value
// to store v and returns a pointer to it.
func Int32(v int32) *int32 {
return &v
}
// Int is a helper routine that allocates a new int32 value
// to store v and returns a pointer to it, but unlike Int32
// its argument value is an int.
func Int(v int) *int32 {
p := new(int32)
*p = int32(v)
return p
}
// Int64 is a helper routine that allocates a new int64 value
// to store v and returns a pointer to it.
func Int64(v int64) *int64 {
return &v
}
// Float32 is a helper routine that allocates a new float32 value
// to store v and returns a pointer to it.
func Float32(v float32) *float32 {
return &v
}
// Float64 is a helper routine that allocates a new float64 value
// to store v and returns a pointer to it.
func Float64(v float64) *float64 {
return &v
}
// Uint32 is a helper routine that allocates a new uint32 value
// to store v and returns a pointer to it.
func Uint32(v uint32) *uint32 {
p := new(uint32)
*p = v
return p
}
// Uint64 is a helper routine that allocates a new uint64 value
// to store v and returns a pointer to it.
func Uint64(v uint64) *uint64 {
return &v
}
// String is a helper routine that allocates a new string value
// to store v and returns a pointer to it.
func String(v string) *string {
return &v
}
// EnumName is a helper function to simplify printing protocol buffer enums
// by name. Given an enum map and a value, it returns a useful string.
func EnumName(m map[int32]string, v int32) string {
s, ok := m[v]
if ok {
return s
}
return strconv.Itoa(int(v))
}
// UnmarshalJSONEnum is a helper function to simplify recovering enum int values
// from their JSON-encoded representation. Given a map from the enum's symbolic
// names to its int values, and a byte buffer containing the JSON-encoded
// value, it returns an int32 that can be cast to the enum type by the caller.
//
// The function can deal with both JSON representations, numeric and symbolic.
func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) {
if data[0] == '"' {
// New style: enums are strings.
var repr string
if err := json.Unmarshal(data, &repr); err != nil {
return -1, err
}
val, ok := m[repr]
if !ok {
return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr)
}
return val, nil
}
// Old style: enums are ints.
var val int32
if err := json.Unmarshal(data, &val); err != nil {
return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName)
}
return val, nil
}
// DebugPrint dumps the encoded data in b in a debugging format with a header
// including the string s. Used in testing but made available for general debugging.
func (o *Buffer) DebugPrint(s string, b []byte) {
var u uint64
obuf := o.buf
index := o.index
o.buf = b
o.index = 0
depth := 0
fmt.Printf("\n--- %s ---\n", s)
out:
for {
for i := 0; i < depth; i++ {
fmt.Print(" ")
}
index := o.index
if index == len(o.buf) {
break
}
op, err := o.DecodeVarint()
if err != nil {
fmt.Printf("%3d: fetching op err %v\n", index, err)
break out
}
tag := op >> 3
wire := op & 7
switch wire {
default:
fmt.Printf("%3d: t=%3d unknown wire=%d\n",
index, tag, wire)
break out
case WireBytes:
var r []byte
r, err = o.DecodeRawBytes(false)
if err != nil {
break out
}
fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r))
if len(r) <= 6 {
for i := 0; i < len(r); i++ {
fmt.Printf(" %.2x", r[i])
}
} else {
for i := 0; i < 3; i++ {
fmt.Printf(" %.2x", r[i])
}
fmt.Printf(" ..")
for i := len(r) - 3; i < len(r); i++ {
fmt.Printf(" %.2x", r[i])
}
}
fmt.Printf("\n")
case WireFixed32:
u, err = o.DecodeFixed32()
if err != nil {
fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err)
break out
}
fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u)
case WireFixed64:
u, err = o.DecodeFixed64()
if err != nil {
fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err)
break out
}
fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u)
break
case WireVarint:
u, err = o.DecodeVarint()
if err != nil {
fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err)
break out
}
fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u)
case WireStartGroup:
if err != nil {
fmt.Printf("%3d: t=%3d start err %v\n", index, tag, err)
break out
}
fmt.Printf("%3d: t=%3d start\n", index, tag)
depth++
case WireEndGroup:
depth--
if err != nil {
fmt.Printf("%3d: t=%3d end err %v\n", index, tag, err)
break out
}
fmt.Printf("%3d: t=%3d end\n", index, tag)
}
}
if depth != 0 {
fmt.Printf("%3d: start-end not balanced %d\n", o.index, depth)
}
fmt.Printf("\n")
o.buf = obuf
o.index = index
}
// SetDefaults sets unset protocol buffer fields to their default values.
// It only modifies fields that are both unset and have defined defaults.
// It recursively sets default values in any non-nil sub-messages.
func SetDefaults(pb Message) {
setDefaults(reflect.ValueOf(pb), true, false)
}
// v is a pointer to a struct.
func setDefaults(v reflect.Value, recur, zeros bool) {
v = v.Elem()
defaultMu.RLock()
dm, ok := defaults[v.Type()]
defaultMu.RUnlock()
if !ok {
dm = buildDefaultMessage(v.Type())
defaultMu.Lock()
defaults[v.Type()] = dm
defaultMu.Unlock()
}
for _, sf := range dm.scalars {
f := v.Field(sf.index)
if !f.IsNil() {
// field already set
continue
}
dv := sf.value
if dv == nil && !zeros {
// no explicit default, and don't want to set zeros
continue
}
fptr := f.Addr().Interface() // **T
// TODO: Consider batching the allocations we do here.
switch sf.kind {
case reflect.Bool:
b := new(bool)
if dv != nil {
*b = dv.(bool)
}
*(fptr.(**bool)) = b
case reflect.Float32:
f := new(float32)
if dv != nil {
*f = dv.(float32)
}
*(fptr.(**float32)) = f
case reflect.Float64:
f := new(float64)
if dv != nil {
*f = dv.(float64)
}
*(fptr.(**float64)) = f
case reflect.Int32:
// might be an enum
if ft := f.Type(); ft != int32PtrType {
// enum
f.Set(reflect.New(ft.Elem()))
if dv != nil {
f.Elem().SetInt(int64(dv.(int32)))
}
} else {
// int32 field
i := new(int32)
if dv != nil {
*i = dv.(int32)
}
*(fptr.(**int32)) = i
}
case reflect.Int64:
i := new(int64)
if dv != nil {
*i = dv.(int64)
}
*(fptr.(**int64)) = i
case reflect.String:
s := new(string)
if dv != nil {
*s = dv.(string)
}
*(fptr.(**string)) = s
case reflect.Uint8:
// exceptional case: []byte
var b []byte
if dv != nil {
db := dv.([]byte)
b = make([]byte, len(db))
copy(b, db)
} else {
b = []byte{}
}
*(fptr.(*[]byte)) = b
case reflect.Uint32:
u := new(uint32)
if dv != nil {
*u = dv.(uint32)
}
*(fptr.(**uint32)) = u
case reflect.Uint64:
u := new(uint64)
if dv != nil {
*u = dv.(uint64)
}
*(fptr.(**uint64)) = u
default:
log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind)
}
}
for _, ni := range dm.nested {
f := v.Field(ni)
if f.IsNil() {
continue
}
// f is *T or []*T
if f.Kind() == reflect.Ptr {
setDefaults(f, recur, zeros)
} else {
for i := 0; i < f.Len(); i++ {
e := f.Index(i)
if e.IsNil() {
continue
}
setDefaults(e, recur, zeros)
}
}
}
}
var (
// defaults maps a protocol buffer struct type to a slice of the fields,
// with its scalar fields set to their proto-declared non-zero default values.
defaultMu sync.RWMutex
defaults = make(map[reflect.Type]defaultMessage)
int32PtrType = reflect.TypeOf((*int32)(nil))
)
// defaultMessage represents information about the default values of a message.
type defaultMessage struct {
scalars []scalarField
nested []int // struct field index of nested messages
}
type scalarField struct {
index int // struct field index
kind reflect.Kind // element type (the T in *T or []T)
value interface{} // the proto-declared default value, or nil
}
func ptrToStruct(t reflect.Type) bool {
return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
}
// t is a struct type.
func buildDefaultMessage(t reflect.Type) (dm defaultMessage) {
sprop := GetProperties(t)
for _, prop := range sprop.Prop {
fi, ok := sprop.decoderTags.get(prop.Tag)
if !ok {
// XXX_unrecognized
continue
}
ft := t.Field(fi).Type
// nested messages
if ptrToStruct(ft) || (ft.Kind() == reflect.Slice && ptrToStruct(ft.Elem())) {
dm.nested = append(dm.nested, fi)
continue
}
sf := scalarField{
index: fi,
kind: ft.Elem().Kind(),
}
// scalar fields without defaults
if !prop.HasDefault {
dm.scalars = append(dm.scalars, sf)
continue
}
// a scalar field: either *T or []byte
switch ft.Elem().Kind() {
case reflect.Bool:
x, err := strconv.ParseBool(prop.Default)
if err != nil {
log.Printf("proto: bad default bool %q: %v", prop.Default, err)
continue
}
sf.value = x
case reflect.Float32:
x, err := strconv.ParseFloat(prop.Default, 32)
if err != nil {
log.Printf("proto: bad default float32 %q: %v", prop.Default, err)
continue
}
sf.value = float32(x)
case reflect.Float64:
x, err := strconv.ParseFloat(prop.Default, 64)
if err != nil {
log.Printf("proto: bad default float64 %q: %v", prop.Default, err)
continue
}
sf.value = x
case reflect.Int32:
x, err := strconv.ParseInt(prop.Default, 10, 32)
if err != nil {
log.Printf("proto: bad default int32 %q: %v", prop.Default, err)
continue
}
sf.value = int32(x)
case reflect.Int64:
x, err := strconv.ParseInt(prop.Default, 10, 64)
if err != nil {
log.Printf("proto: bad default int64 %q: %v", prop.Default, err)
continue
}
sf.value = x
case reflect.String:
sf.value = prop.Default
case reflect.Uint8:
// []byte (not *uint8)
sf.value = []byte(prop.Default)
case reflect.Uint32:
x, err := strconv.ParseUint(prop.Default, 10, 32)
if err != nil {
log.Printf("proto: bad default uint32 %q: %v", prop.Default, err)
continue
}
sf.value = uint32(x)
case reflect.Uint64:
x, err := strconv.ParseUint(prop.Default, 10, 64)
if err != nil {
log.Printf("proto: bad default uint64 %q: %v", prop.Default, err)
continue
}
sf.value = x
default:
log.Printf("proto: unhandled def kind %v", ft.Elem().Kind())
continue
}
dm.scalars = append(dm.scalars, sf)
}
return dm
}
| 109609524-goprotobuf | proto/lib.go | Go | bsd | 19,973 |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2012 The Go Authors. All rights reserved.
// http://code.google.com/p/goprotobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// +build appengine,!appenginevm
// This file contains an implementation of proto field accesses using package reflect.
// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can
// be used on App Engine.
package proto
import (
"math"
"reflect"
)
// A structPointer is a pointer to a struct.
type structPointer struct {
v reflect.Value
}
// toStructPointer returns a structPointer equivalent to the given reflect value.
// The reflect value must itself be a pointer to a struct.
func toStructPointer(v reflect.Value) structPointer {
return structPointer{v}
}
// IsNil reports whether p is nil.
func structPointer_IsNil(p structPointer) bool {
return p.v.IsNil()
}
// Interface returns the struct pointer as an interface value.
func structPointer_Interface(p structPointer, _ reflect.Type) interface{} {
return p.v.Interface()
}
// A field identifies a field in a struct, accessible from a structPointer.
// In this implementation, a field is identified by the sequence of field indices
// passed to reflect's FieldByIndex.
type field []int
// toField returns a field equivalent to the given reflect field.
func toField(f *reflect.StructField) field {
return f.Index
}
// invalidField is an invalid field identifier.
var invalidField = field(nil)
// IsValid reports whether the field identifier is valid.
func (f field) IsValid() bool { return f != nil }
// field returns the given field in the struct as a reflect value.
func structPointer_field(p structPointer, f field) reflect.Value {
// Special case: an extension map entry with a value of type T
// passes a *T to the struct-handling code with a zero field,
// expecting that it will be treated as equivalent to *struct{ X T },
// which has the same memory layout. We have to handle that case
// specially, because reflect will panic if we call FieldByIndex on a
// non-struct.
if f == nil {
return p.v.Elem()
}
return p.v.Elem().FieldByIndex(f)
}
// ifield returns the given field in the struct as an interface value.
func structPointer_ifield(p structPointer, f field) interface{} {
return structPointer_field(p, f).Addr().Interface()
}
// Bytes returns the address of a []byte field in the struct.
func structPointer_Bytes(p structPointer, f field) *[]byte {
return structPointer_ifield(p, f).(*[]byte)
}
// BytesSlice returns the address of a [][]byte field in the struct.
func structPointer_BytesSlice(p structPointer, f field) *[][]byte {
return structPointer_ifield(p, f).(*[][]byte)
}
// Bool returns the address of a *bool field in the struct.
func structPointer_Bool(p structPointer, f field) **bool {
return structPointer_ifield(p, f).(**bool)
}
// BoolSlice returns the address of a []bool field in the struct.
func structPointer_BoolSlice(p structPointer, f field) *[]bool {
return structPointer_ifield(p, f).(*[]bool)
}
// String returns the address of a *string field in the struct.
func structPointer_String(p structPointer, f field) **string {
return structPointer_ifield(p, f).(**string)
}
// StringSlice returns the address of a []string field in the struct.
func structPointer_StringSlice(p structPointer, f field) *[]string {
return structPointer_ifield(p, f).(*[]string)
}
// ExtMap returns the address of an extension map field in the struct.
func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension {
return structPointer_ifield(p, f).(*map[int32]Extension)
}
// SetStructPointer writes a *struct field in the struct.
func structPointer_SetStructPointer(p structPointer, f field, q structPointer) {
structPointer_field(p, f).Set(q.v)
}
// GetStructPointer reads a *struct field in the struct.
func structPointer_GetStructPointer(p structPointer, f field) structPointer {
return structPointer{structPointer_field(p, f)}
}
// StructPointerSlice the address of a []*struct field in the struct.
func structPointer_StructPointerSlice(p structPointer, f field) structPointerSlice {
return structPointerSlice{structPointer_field(p, f)}
}
// A structPointerSlice represents the address of a slice of pointers to structs
// (themselves messages or groups). That is, v.Type() is *[]*struct{...}.
type structPointerSlice struct {
v reflect.Value
}
func (p structPointerSlice) Len() int { return p.v.Len() }
func (p structPointerSlice) Index(i int) structPointer { return structPointer{p.v.Index(i)} }
func (p structPointerSlice) Append(q structPointer) {
p.v.Set(reflect.Append(p.v, q.v))
}
var (
int32Type = reflect.TypeOf(int32(0))
uint32Type = reflect.TypeOf(uint32(0))
float32Type = reflect.TypeOf(float32(0))
int64Type = reflect.TypeOf(int64(0))
uint64Type = reflect.TypeOf(uint64(0))
float64Type = reflect.TypeOf(float64(0))
)
// A word32 represents a field of type *int32, *uint32, *float32, or *enum.
// That is, v.Type() is *int32, *uint32, *float32, or *enum and v is assignable.
type word32 struct {
v reflect.Value
}
// IsNil reports whether p is nil.
func word32_IsNil(p word32) bool {
return p.v.IsNil()
}
// Set sets p to point at a newly allocated word with bits set to x.
func word32_Set(p word32, o *Buffer, x uint32) {
t := p.v.Type().Elem()
switch t {
case int32Type:
if len(o.int32s) == 0 {
o.int32s = make([]int32, uint32PoolSize)
}
o.int32s[0] = int32(x)
p.v.Set(reflect.ValueOf(&o.int32s[0]))
o.int32s = o.int32s[1:]
return
case uint32Type:
if len(o.uint32s) == 0 {
o.uint32s = make([]uint32, uint32PoolSize)
}
o.uint32s[0] = x
p.v.Set(reflect.ValueOf(&o.uint32s[0]))
o.uint32s = o.uint32s[1:]
return
case float32Type:
if len(o.float32s) == 0 {
o.float32s = make([]float32, uint32PoolSize)
}
o.float32s[0] = math.Float32frombits(x)
p.v.Set(reflect.ValueOf(&o.float32s[0]))
o.float32s = o.float32s[1:]
return
}
// must be enum
p.v.Set(reflect.New(t))
p.v.Elem().SetInt(int64(int32(x)))
}
// Get gets the bits pointed at by p, as a uint32.
func word32_Get(p word32) uint32 {
elem := p.v.Elem()
switch elem.Kind() {
case reflect.Int32:
return uint32(elem.Int())
case reflect.Uint32:
return uint32(elem.Uint())
case reflect.Float32:
return math.Float32bits(float32(elem.Float()))
}
panic("unreachable")
}
// Word32 returns a reference to a *int32, *uint32, *float32, or *enum field in the struct.
func structPointer_Word32(p structPointer, f field) word32 {
return word32{structPointer_field(p, f)}
}
// A word32Slice is a slice of 32-bit values.
// That is, v.Type() is []int32, []uint32, []float32, or []enum.
type word32Slice struct {
v reflect.Value
}
func (p word32Slice) Append(x uint32) {
n, m := p.v.Len(), p.v.Cap()
if n < m {
p.v.SetLen(n + 1)
} else {
t := p.v.Type().Elem()
p.v.Set(reflect.Append(p.v, reflect.Zero(t)))
}
elem := p.v.Index(n)
switch elem.Kind() {
case reflect.Int32:
elem.SetInt(int64(int32(x)))
case reflect.Uint32:
elem.SetUint(uint64(x))
case reflect.Float32:
elem.SetFloat(float64(math.Float32frombits(x)))
}
}
func (p word32Slice) Len() int {
return p.v.Len()
}
func (p word32Slice) Index(i int) uint32 {
elem := p.v.Index(i)
switch elem.Kind() {
case reflect.Int32:
return uint32(elem.Int())
case reflect.Uint32:
return uint32(elem.Uint())
case reflect.Float32:
return math.Float32bits(float32(elem.Float()))
}
panic("unreachable")
}
// Word32Slice returns a reference to a []int32, []uint32, []float32, or []enum field in the struct.
func structPointer_Word32Slice(p structPointer, f field) word32Slice {
return word32Slice{structPointer_field(p, f)}
}
// word64 is like word32 but for 64-bit values.
type word64 struct {
v reflect.Value
}
func word64_Set(p word64, o *Buffer, x uint64) {
t := p.v.Type().Elem()
switch t {
case int64Type:
if len(o.int64s) == 0 {
o.int64s = make([]int64, uint64PoolSize)
}
o.int64s[0] = int64(x)
p.v.Set(reflect.ValueOf(&o.int64s[0]))
o.int64s = o.int64s[1:]
return
case uint64Type:
if len(o.uint64s) == 0 {
o.uint64s = make([]uint64, uint64PoolSize)
}
o.uint64s[0] = x
p.v.Set(reflect.ValueOf(&o.uint64s[0]))
o.uint64s = o.uint64s[1:]
return
case float64Type:
if len(o.float64s) == 0 {
o.float64s = make([]float64, uint64PoolSize)
}
o.float64s[0] = math.Float64frombits(x)
p.v.Set(reflect.ValueOf(&o.float64s[0]))
o.float64s = o.float64s[1:]
return
}
panic("unreachable")
}
func word64_IsNil(p word64) bool {
return p.v.IsNil()
}
func word64_Get(p word64) uint64 {
elem := p.v.Elem()
switch elem.Kind() {
case reflect.Int64:
return uint64(elem.Int())
case reflect.Uint64:
return elem.Uint()
case reflect.Float64:
return math.Float64bits(elem.Float())
}
panic("unreachable")
}
func structPointer_Word64(p structPointer, f field) word64 {
return word64{structPointer_field(p, f)}
}
type word64Slice struct {
v reflect.Value
}
func (p word64Slice) Append(x uint64) {
n, m := p.v.Len(), p.v.Cap()
if n < m {
p.v.SetLen(n + 1)
} else {
t := p.v.Type().Elem()
p.v.Set(reflect.Append(p.v, reflect.Zero(t)))
}
elem := p.v.Index(n)
switch elem.Kind() {
case reflect.Int64:
elem.SetInt(int64(int64(x)))
case reflect.Uint64:
elem.SetUint(uint64(x))
case reflect.Float64:
elem.SetFloat(float64(math.Float64frombits(x)))
}
}
func (p word64Slice) Len() int {
return p.v.Len()
}
func (p word64Slice) Index(i int) uint64 {
elem := p.v.Index(i)
switch elem.Kind() {
case reflect.Int64:
return uint64(elem.Int())
case reflect.Uint64:
return uint64(elem.Uint())
case reflect.Float64:
return math.Float64bits(float64(elem.Float()))
}
panic("unreachable")
}
func structPointer_Word64Slice(p structPointer, f field) word64Slice {
return word64Slice{structPointer_field(p, f)}
}
| 109609524-goprotobuf | proto/pointer_reflect.go | Go | bsd | 11,352 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.services;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.util.ObjectParser;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import java.io.IOException;
import java.util.logging.Logger;
/**
* Abstract thread-safe Google client.
*
* @since 1.12
* @author Yaniv Inbar
*/
public abstract class AbstractGoogleClient {
static final Logger LOGGER = Logger.getLogger(AbstractGoogleClient.class.getName());
/** The request factory for connections to the server. */
private final HttpRequestFactory requestFactory;
/**
* Initializer to use when creating an {@link AbstractGoogleClientRequest} or {@code null} for
* none.
*/
private final GoogleClientRequestInitializer googleClientRequestInitializer;
/**
* Root URL of the service, for example {@code "https://www.googleapis.com/"}. Must be URL-encoded
* and must end with a "/".
*/
private final String rootUrl;
/**
* Service path, for example {@code "tasks/v1/"}. Must be URL-encoded and must end with a "/".
*/
private final String servicePath;
/**
* Application name to be sent in the User-Agent header of each request or {@code null} for none.
*/
private final String applicationName;
/** Object parser or {@code null} for none. */
private final ObjectParser objectParser;
/** Whether discovery pattern checks should be suppressed on required parameters. */
private boolean suppressPatternChecks;
/**
* Constructor with required parameters.
*
* <p>
* Use {@link Builder} if you need to specify any of the optional parameters.
* </p>
*
* @param transport HTTP transport
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @param rootUrl root URL of the service
* @param servicePath service path
* @param objectParser object parser
*/
protected AbstractGoogleClient(HttpTransport transport,
HttpRequestInitializer httpRequestInitializer, String rootUrl, String servicePath,
ObjectParser objectParser) {
this(transport, httpRequestInitializer, rootUrl, servicePath, objectParser, null, null, false);
}
/**
* @param transport HTTP transport
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @param rootUrl root URL of the service
* @param servicePath service path
* @param objectParser object parser or {@code null} for none
* @param googleClientRequestInitializer Google request initializer or {@code null} for none
* @param applicationName application name to be sent in the User-Agent header of requests or
* {@code null} for none
* @param suppressPatternChecks whether discovery pattern checks should be suppressed on required
* parameters
*/
protected AbstractGoogleClient(HttpTransport transport,
HttpRequestInitializer httpRequestInitializer, String rootUrl, String servicePath,
ObjectParser objectParser, GoogleClientRequestInitializer googleClientRequestInitializer,
String applicationName, boolean suppressPatternChecks) {
this.googleClientRequestInitializer = googleClientRequestInitializer;
this.rootUrl = normalizeRootUrl(rootUrl);
this.servicePath = normalizeServicePath(servicePath);
if (Strings.isNullOrEmpty(applicationName)) {
LOGGER.warning("Application name is not set. Call Builder#setApplicationName.");
}
this.applicationName = applicationName;
this.requestFactory = httpRequestInitializer == null
? transport.createRequestFactory() : transport.createRequestFactory(httpRequestInitializer);
this.objectParser = objectParser;
this.suppressPatternChecks = suppressPatternChecks;
}
/**
* Returns the URL-encoded root URL of the service, for example
* {@code "https://www.googleapis.com/"}.
*
* <p>
* Must end with a "/".
* </p>
*/
public final String getRootUrl() {
return rootUrl;
}
/**
* Returns the URL-encoded service path of the service, for example {@code "tasks/v1/"}.
*
* <p>
* Must end with a "/" and not begin with a "/". It is allowed to be an empty string {@code ""} or
* a forward slash {@code "/"}, if it is a forward slash then it is treated as an empty string
* </p>
*/
public final String getServicePath() {
return servicePath;
}
/**
* Returns the URL-encoded base URL of the service, for example
* {@code "https://www.googleapis.com/tasks/v1/"}.
*
* <p>
* Must end with a "/". It is guaranteed to be equal to {@code getRootUrl() + getServicePath()}.
* </p>
*/
public final String getBaseUrl() {
return rootUrl + servicePath;
}
/**
* Returns the application name to be sent in the User-Agent header of each request or
* {@code null} for none.
*/
public final String getApplicationName() {
return applicationName;
}
/** Returns the HTTP request factory. */
public final HttpRequestFactory getRequestFactory() {
return requestFactory;
}
/** Returns the Google client request initializer or {@code null} for none. */
public final GoogleClientRequestInitializer getGoogleClientRequestInitializer() {
return googleClientRequestInitializer;
}
/**
* Returns the object parser or {@code null} for none.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public ObjectParser getObjectParser() {
return objectParser;
}
/**
* Initializes a {@link AbstractGoogleClientRequest} using a
* {@link GoogleClientRequestInitializer}.
*
* <p>
* Must be called before the Google client request is executed, preferably right after the request
* is instantiated. Sample usage:
* </p>
*
* <pre>
public class Get extends HttpClientRequest {
...
}
public Get get(String userId) throws IOException {
Get result = new Get(userId);
initialize(result);
return result;
}
* </pre>
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*
* @param httpClientRequest Google client request type
*/
protected void initialize(AbstractGoogleClientRequest<?> httpClientRequest) throws IOException {
if (getGoogleClientRequestInitializer() != null) {
getGoogleClientRequestInitializer().initialize(httpClientRequest);
}
}
/**
* Create an {@link BatchRequest} object from this Google API client instance.
*
* <p>
* Sample usage:
* </p>
*
* <pre>
client.batch()
.queue(...)
.queue(...)
.execute();
* </pre>
*
* @return newly created Batch request
*/
public final BatchRequest batch() {
return batch(null);
}
/**
* Create an {@link BatchRequest} object from this Google API client instance.
*
* <p>
* Sample usage:
* </p>
*
* <pre>
client.batch(httpRequestInitializer)
.queue(...)
.queue(...)
.execute();
* </pre>
*
* @param httpRequestInitializer The initializer to use when creating the top-level batch HTTP
* request or {@code null} for none
* @return newly created Batch request
*/
public final BatchRequest batch(HttpRequestInitializer httpRequestInitializer) {
BatchRequest batch =
new BatchRequest(getRequestFactory().getTransport(), httpRequestInitializer);
batch.setBatchUrl(new GenericUrl(getRootUrl() + "batch"));
return batch;
}
/** Returns whether discovery pattern checks should be suppressed on required parameters. */
public final boolean getSuppressPatternChecks() {
return suppressPatternChecks;
}
/** If the specified root URL does not end with a "/" then a "/" is added to the end. */
static String normalizeRootUrl(String rootUrl) {
Preconditions.checkNotNull(rootUrl, "root URL cannot be null.");
if (!rootUrl.endsWith("/")) {
rootUrl += "/";
}
return rootUrl;
}
/**
* If the specified service path does not end with a "/" then a "/" is added to the end. If the
* specified service path begins with a "/" then the "/" is removed.
*/
static String normalizeServicePath(String servicePath) {
Preconditions.checkNotNull(servicePath, "service path cannot be null");
if (servicePath.length() == 1) {
Preconditions.checkArgument(
"/".equals(servicePath), "service path must equal \"/\" if it is of length 1.");
servicePath = "";
} else if (servicePath.length() > 0) {
if (!servicePath.endsWith("/")) {
servicePath += "/";
}
if (servicePath.startsWith("/")) {
servicePath = servicePath.substring(1);
}
}
return servicePath;
}
/**
* Builder for {@link AbstractGoogleClient}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*/
public abstract static class Builder {
/** HTTP transport. */
private final HttpTransport transport;
/**
* Initializer to use when creating an {@link AbstractGoogleClientRequest} or {@code null} for
* none.
*/
private GoogleClientRequestInitializer googleClientRequestInitializer;
/** HTTP request initializer or {@code null} for none. */
private HttpRequestInitializer httpRequestInitializer;
/** Object parser to use for parsing responses. */
private final ObjectParser objectParser;
/** The root URL of the service, for example {@code "https://www.googleapis.com/"}. */
private String rootUrl;
/** The service path of the service, for example {@code "tasks/v1/"}. */
private String servicePath;
/**
* Application name to be sent in the User-Agent header of each request or {@code null} for
* none.
*/
private String applicationName;
/** Whether discovery pattern checks should be suppressed on required parameters. */
private boolean suppressPatternChecks;
/**
* Returns an instance of a new builder.
*
* @param transport The transport to use for requests
* @param rootUrl root URL of the service. Must end with a "/"
* @param servicePath service path
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
*/
protected Builder(HttpTransport transport, String rootUrl, String servicePath,
ObjectParser objectParser, HttpRequestInitializer httpRequestInitializer) {
this.transport = Preconditions.checkNotNull(transport);
this.objectParser = Preconditions.checkNotNull(objectParser);
setRootUrl(rootUrl);
setServicePath(servicePath);
this.httpRequestInitializer = httpRequestInitializer;
}
/** Builds a new instance of {@link AbstractGoogleClient}. */
public abstract AbstractGoogleClient build();
/** Returns the HTTP transport. */
public final HttpTransport getTransport() {
return transport;
}
/**
* Returns the object parser used or {@code null} if not specified. *
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public ObjectParser getObjectParser() {
return objectParser;
}
/**
* Returns the URL-encoded root URL of the service, for example
* {@code https://www.googleapis.com/}.
*
* <p>
* Must be URL-encoded and must end with a "/".
* </p>
*/
public final String getRootUrl() {
return rootUrl;
}
/**
* Sets the URL-encoded root URL of the service, for example {@code https://www.googleapis.com/}
* .
* <p>
* If the specified root URL does not end with a "/" then a "/" is added to the end.
* </p>
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setRootUrl(String rootUrl) {
this.rootUrl = normalizeRootUrl(rootUrl);
return this;
}
/**
* Returns the URL-encoded service path of the service, for example {@code "tasks/v1/"}.
*
* <p>
* Must be URL-encoded and must end with a "/" and not begin with a "/". It is allowed to be an
* empty string {@code ""}.
* </p>
*/
public final String getServicePath() {
return servicePath;
}
/**
* Sets the URL-encoded service path of the service, for example {@code "tasks/v1/"}.
*
* <p>
* It is allowed to be an empty string {@code ""} or a forward slash {@code "/"}, if it is a
* forward slash then it is treated as an empty string. This is determined when the library is
* generated and normally should not be changed.
* </p>
*
* <p>
* If the specified service path does not end with a "/" then a "/" is added to the end. If the
* specified service path begins with a "/" then the "/" is removed.
* </p>
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setServicePath(String servicePath) {
this.servicePath = normalizeServicePath(servicePath);
return this;
}
/** Returns the Google client request initializer or {@code null} for none. */
public final GoogleClientRequestInitializer getGoogleClientRequestInitializer() {
return googleClientRequestInitializer;
}
/**
* Sets the Google client request initializer or {@code null} for none.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setGoogleClientRequestInitializer(
GoogleClientRequestInitializer googleClientRequestInitializer) {
this.googleClientRequestInitializer = googleClientRequestInitializer;
return this;
}
/** Returns the HTTP request initializer or {@code null} for none. */
public final HttpRequestInitializer getHttpRequestInitializer() {
return httpRequestInitializer;
}
/**
* Sets the HTTP request initializer or {@code null} for none.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setHttpRequestInitializer(HttpRequestInitializer httpRequestInitializer) {
this.httpRequestInitializer = httpRequestInitializer;
return this;
}
/**
* Returns the application name to be used in the UserAgent header of each request or
* {@code null} for none.
*/
public final String getApplicationName() {
return applicationName;
}
/**
* Sets the application name to be used in the UserAgent header of each request or {@code null}
* for none.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setApplicationName(String applicationName) {
this.applicationName = applicationName;
return this;
}
/** Returns whether discovery pattern checks should be suppressed on required parameters. */
public final boolean getSuppressPatternChecks() {
return suppressPatternChecks;
}
/**
* Sets whether discovery pattern checks should be suppressed on required parameters.
*
* <p>
* Default value is {@code false}.
* </p>
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setSuppressPatternChecks(boolean suppressPatternChecks) {
this.suppressPatternChecks = suppressPatternChecks;
return this;
}
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/services/AbstractGoogleClient.java | Java | asf20 | 16,883 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.services.json;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.googleapis.batch.json.JsonBatchCallback;
import com.google.api.client.googleapis.json.GoogleJsonErrorContainer;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.googleapis.json.JsonCContent;
import com.google.api.client.googleapis.json.JsonCParser;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.subscriptions.json.JsonSubscribeRequest;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.UriTemplate;
import com.google.api.client.http.json.JsonHttpContent;
import java.io.IOException;
/**
* Google JSON request for a {@link AbstractGoogleJsonClient}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @param <T> type of the response
* @since 1.12
* @author Yaniv Inbar
*/
public abstract class AbstractGoogleJsonClientRequest<T> extends AbstractGoogleClientRequest<T> {
/** POJO that can be serialized into JSON content or {@code null} for none. */
private final Object jsonContent;
/**
* @param abstractGoogleJsonClient Google JSON client
* @param requestMethod HTTP Method
* @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/"
* the base path from the base URL will be stripped out. The URI template can also be a
* full URL. URI template expansion is done using
* {@link UriTemplate#expand(String, String, Object, boolean)}
* @param jsonContent POJO that can be serialized into JSON content or {@code null} for none
* @param responseClass response class to parse into
*/
protected AbstractGoogleJsonClientRequest(AbstractGoogleJsonClient abstractGoogleJsonClient,
String requestMethod, String uriTemplate, Object jsonContent, Class<T> responseClass) {
super(abstractGoogleJsonClient, requestMethod, uriTemplate, jsonContent == null
? null : (abstractGoogleJsonClient.getObjectParser() instanceof JsonCParser)
? new JsonCContent(abstractGoogleJsonClient.getJsonFactory(), jsonContent)
: new JsonHttpContent(abstractGoogleJsonClient.getJsonFactory(), jsonContent),
responseClass);
this.jsonContent = jsonContent;
}
@Override
public AbstractGoogleJsonClient getAbstractGoogleClient() {
return (AbstractGoogleJsonClient) super.getAbstractGoogleClient();
}
@Override
public AbstractGoogleJsonClientRequest<T> setDisableGZipContent(boolean disableGZipContent) {
return (AbstractGoogleJsonClientRequest<T>) super.setDisableGZipContent(disableGZipContent);
}
@Override
public AbstractGoogleJsonClientRequest<T> setRequestHeaders(HttpHeaders headers) {
return (AbstractGoogleJsonClientRequest<T>) super.setRequestHeaders(headers);
}
/**
* Queues the request into the specified batch request container.
*
* <p>
* Batched requests are then executed when {@link BatchRequest#execute()} is called.
* </p>
* <p>
* Example usage:
* </p>
*
* <pre>
request.queue(batchRequest, new JsonBatchCallback<SomeResponseType>() {
public void onSuccess(SomeResponseType content, HttpHeaders responseHeaders) {
log("Success");
}
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
log(e.getMessage());
}
});
* </pre>
*
*
* @param batchRequest batch request container
* @param callback batch callback
*/
public final void queue(BatchRequest batchRequest, JsonBatchCallback<T> callback)
throws IOException {
super.queue(batchRequest, GoogleJsonErrorContainer.class, callback);
}
@Override
@Deprecated
protected GoogleJsonResponseException newExceptionOnError(HttpResponse response) {
return GoogleJsonResponseException.from(getAbstractGoogleClient().getJsonFactory(), response);
}
/**
* Subscribes to parsed JSON notifications.
*
* <p>
* Overriding is only supported for the purpose of changing visibility to public, but nothing
* else.
* </p>
*
* @param notificationDeliveryMethod notification delivery method
* @throws IOException
*
* @since 1.14
*/
@Override
protected JsonSubscribeRequest subscribe(String notificationDeliveryMethod) throws IOException {
return new JsonSubscribeRequest(
buildHttpRequest(), notificationDeliveryMethod, getAbstractGoogleClient().getJsonFactory());
}
/** Returns POJO that can be serialized into JSON content or {@code null} for none. */
public Object getJsonContent() {
return jsonContent;
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/services/json/AbstractGoogleJsonClientRequest.java | Java | asf20 | 5,344 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.services.json;
import com.google.api.client.googleapis.json.JsonCParser;
import com.google.api.client.googleapis.services.AbstractGoogleClient;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
/**
* Thread-safe Google JSON client.
*
* @since 1.12
* @author Yaniv Inbar
*/
public abstract class AbstractGoogleJsonClient extends AbstractGoogleClient {
/**
* @param transport HTTP transport
* @param jsonFactory JSON factory
* @param rootUrl root URL of the service
* @param servicePath service path
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @param legacyDataWrapper whether using the legacy data wrapper in responses
*/
protected AbstractGoogleJsonClient(HttpTransport transport, JsonFactory jsonFactory,
String rootUrl, String servicePath, HttpRequestInitializer httpRequestInitializer,
boolean legacyDataWrapper) {
super(transport, httpRequestInitializer, rootUrl, servicePath, newObjectParser(
jsonFactory, legacyDataWrapper));
}
/**
* @param transport HTTP transport
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @param rootUrl root URL of the service
* @param servicePath service path
* @param jsonObjectParser JSON object parser
* @param googleClientRequestInitializer Google request initializer or {@code null} for none
* @param applicationName application name to be sent in the User-Agent header of requests or
* {@code null} for none
* @param suppressPatternChecks whether discovery pattern checks should be suppressed on required
* parameters
*/
protected AbstractGoogleJsonClient(HttpTransport transport,
HttpRequestInitializer httpRequestInitializer, String rootUrl, String servicePath,
JsonObjectParser jsonObjectParser,
GoogleClientRequestInitializer googleClientRequestInitializer, String applicationName,
boolean suppressPatternChecks) {
super(transport, httpRequestInitializer, rootUrl, servicePath, jsonObjectParser,
googleClientRequestInitializer, applicationName, suppressPatternChecks);
}
@Override
public JsonObjectParser getObjectParser() {
return (JsonObjectParser) super.getObjectParser();
}
/** Returns the JSON Factory. */
public final JsonFactory getJsonFactory() {
return getObjectParser().getJsonFactory();
}
/**
* @param jsonFactory JSON factory
* @param legacyDataWrapper whether using the legacy data wrapper in responses
*/
static JsonObjectParser newObjectParser(JsonFactory jsonFactory, boolean legacyDataWrapper) {
return legacyDataWrapper ? new JsonCParser(jsonFactory) : new JsonObjectParser(jsonFactory);
}
/**
* Builder for {@link AbstractGoogleJsonClient}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*/
public abstract static class Builder extends AbstractGoogleClient.Builder {
/**
* @param transport HTTP transport
* @param jsonFactory JSON factory
* @param rootUrl root URL of the service
* @param servicePath service path
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @param legacyDataWrapper whether using the legacy data wrapper in responses
*/
protected Builder(HttpTransport transport, JsonFactory jsonFactory, String rootUrl,
String servicePath, HttpRequestInitializer httpRequestInitializer,
boolean legacyDataWrapper) {
super(transport, rootUrl, servicePath, newObjectParser(jsonFactory, legacyDataWrapper),
httpRequestInitializer);
}
@Override
public final JsonObjectParser getObjectParser() {
return (JsonObjectParser) super.getObjectParser();
}
/** Returns the JSON Factory. */
public final JsonFactory getJsonFactory() {
return getObjectParser().getJsonFactory();
}
@Override
public abstract AbstractGoogleJsonClient build();
@Override
public Builder setRootUrl(String rootUrl) {
return (Builder) super.setRootUrl(rootUrl);
}
@Override
public Builder setServicePath(String servicePath) {
return (Builder) super.setServicePath(servicePath);
}
@Override
public Builder setGoogleClientRequestInitializer(
GoogleClientRequestInitializer googleClientRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer);
}
@Override
public Builder setHttpRequestInitializer(HttpRequestInitializer httpRequestInitializer) {
return (Builder) super.setHttpRequestInitializer(httpRequestInitializer);
}
@Override
public Builder setApplicationName(String applicationName) {
return (Builder) super.setApplicationName(applicationName);
}
@Override
public Builder setSuppressPatternChecks(boolean suppressPatternChecks) {
return (Builder) super.setSuppressPatternChecks(suppressPatternChecks);
}
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/services/json/AbstractGoogleJsonClient.java | Java | asf20 | 5,809 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Contains the basis for the generated service-specific libraries based on the JSON format.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.12
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis.services.json;
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/services/json/package-info.java | Java | asf20 | 938 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.services.json;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.CommonGoogleClientRequestInitializer;
import java.io.IOException;
/**
* Google JSON client request initializer implementation for setting properties like key and userIp.
*
* <p>
* The simplest usage is to use it to set the key parameter:
* </p>
*
* <pre>
public static final GoogleClientRequestInitializer KEY_INITIALIZER =
new CommonGoogleJsonClientRequestInitializer(KEY);
* </pre>
*
* <p>
* There is also a constructor to set both the key and userIp parameters:
* </p>
*
* <pre>
public static final GoogleClientRequestInitializer INITIALIZER =
new CommonGoogleJsonClientRequestInitializer(KEY, USER_IP);
* </pre>
*
* <p>
* If you want to implement custom logic, extend it like this:
* </p>
*
* <pre>
public static class MyRequestInitializer extends CommonGoogleJsonClientRequestInitializer {
{@literal @}Override
public void initialize(AbstractGoogleJsonClientRequest{@literal <}?{@literal >} request)
throws IOException {
// custom logic
}
}
* </pre>
*
* <p>
* Finally, to set the key and userIp parameters and insert custom logic, extend it like this:
* </p>
*
* <pre>
public static class MyRequestInitializer2 extends CommonGoogleJsonClientRequestInitializer {
public MyKeyRequestInitializer() {
super(KEY, USER_IP);
}
{@literal @}Override
public void initializeJsonRequest(AbstractGoogleJsonClientRequest{
@literal <}?{@literal >} request) throws IOException {
// custom logic
}
}
* </pre>
*
* <p>
* Subclasses should be thread-safe.
* </p>
*
* @since 1.12
* @author Yaniv Inbar
*/
public class CommonGoogleJsonClientRequestInitializer extends CommonGoogleClientRequestInitializer {
public CommonGoogleJsonClientRequestInitializer() {
super();
}
/**
* @param key API key or {@code null} to leave it unchanged
*/
public CommonGoogleJsonClientRequestInitializer(String key) {
super(key);
}
/**
* @param key API key or {@code null} to leave it unchanged
* @param userIp user IP or {@code null} to leave it unchanged
*/
public CommonGoogleJsonClientRequestInitializer(String key, String userIp) {
super(key, userIp);
}
@Override
public final void initialize(AbstractGoogleClientRequest<?> request) throws IOException {
super.initialize(request);
initializeJsonRequest((AbstractGoogleJsonClientRequest<?>) request);
}
/**
* Initializes a Google JSON client request.
*
* <p>
* Default implementation does nothing. Called from
* {@link #initialize(AbstractGoogleClientRequest)}.
* </p>
*
* @throws IOException I/O exception
*/
protected void initializeJsonRequest(AbstractGoogleJsonClientRequest<?> request)
throws IOException {
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/services/json/CommonGoogleJsonClientRequestInitializer.java | Java | asf20 | 3,503 |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Contains the basis for the generated service-specific libraries.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.6
* @author Ravi Mistry
*/
package com.google.api.client.googleapis.services;
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/services/package-info.java | Java | asf20 | 945 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.services;
import java.io.IOException;
/**
* Google client request initializer.
*
* <p>
* For example, this might be used to set a key URL query parameter on all requests:
* </p>
*
* <pre>
public class KeyRequestInitializer implements GoogleClientRequestInitializer {
public void initialize(GoogleClientRequest<?> request) {
request.put("key", KEY);
}
}
* </pre>
*
* <p>
* Implementations should be thread-safe.
* </p>
*
* @since 1.12
* @author Yaniv Inbar
*/
public interface GoogleClientRequestInitializer {
/** Initializes a Google client request. */
void initialize(AbstractGoogleClientRequest<?> request) throws IOException;
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/services/GoogleClientRequestInitializer.java | Java | asf20 | 1,266 |
/*
* Copyright (c) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.services;
import com.google.api.client.googleapis.MethodOverride;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.EmptyContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpMethod;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.json.JsonHttpClient;
import com.google.api.client.http.json.JsonHttpRequest;
import com.google.api.client.http.json.JsonHttpRequestInitializer;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import java.io.IOException;
import java.util.Arrays;
/**
* Google API client.
*
* @since 1.6
* @author Ravi Mistry
* @deprecated (scheduled to be removed in 1.14) Use {@code
* com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient} instead.
*/
@Deprecated
public class GoogleClient extends JsonHttpClient {
/** Whether discovery pattern checks should be suppressed on required parameters. */
private boolean suppressPatternChecks;
/**
* Constructor with required parameters.
*
* <p>
* Use {@link Builder} if you need to specify any of the optional parameters.
* </p>
*
* @param transport The transport to use for requests
* @param jsonFactory A factory for creating JSON parsers and serializers
* @param baseUrl The base URL of the service. Must end with a "/"
*/
public GoogleClient(HttpTransport transport, JsonFactory jsonFactory, String baseUrl) {
super(transport, jsonFactory, baseUrl);
}
/**
* Constructor with required parameters.
*
* <p>
* Use {@link Builder} if you need to specify any of the optional parameters.
* </p>
*
* @param transport The transport to use for requests
* @param jsonFactory A factory for creating JSON parsers and serializers
* @param rootUrl The root URL of the service. Must end with a "/"
* @param servicePath The service path of the service. Must end with a "/" and not begin with a
* "/". It is allowed to be an empty string {@code ""}
* @param httpRequestInitializer The HTTP request initializer or {@code null} for none
* @since 1.10
*/
public GoogleClient(HttpTransport transport, JsonFactory jsonFactory, String rootUrl,
String servicePath, HttpRequestInitializer httpRequestInitializer) {
super(transport, jsonFactory, rootUrl, servicePath, httpRequestInitializer);
}
/**
* Construct the {@link GoogleClient}.
*
* @param transport The transport to use for requests
* @param jsonHttpRequestInitializer The initializer to use when creating an
* {@link JsonHttpRequest} or {@code null} for none
* @param httpRequestInitializer The initializer to use when creating an {@link HttpRequest} or
* {@code null} for none
* @param jsonFactory A factory for creating JSON parsers and serializers
* @param jsonObjectParser JSON parser to use or {@code null} if unused
* @param baseUrl The base URL of the service. Must end with a "/"
* @param applicationName The application name to be sent in the User-Agent header of requests or
* {@code null} for none
*/
protected GoogleClient(HttpTransport transport,
JsonHttpRequestInitializer jsonHttpRequestInitializer,
HttpRequestInitializer httpRequestInitializer, JsonFactory jsonFactory,
JsonObjectParser jsonObjectParser, String baseUrl, String applicationName) {
super(transport, jsonHttpRequestInitializer, httpRequestInitializer, jsonFactory,
jsonObjectParser, baseUrl, applicationName);
}
/**
* Construct the {@link GoogleClient}.
*
* @param transport The transport to use for requests
* @param jsonHttpRequestInitializer The initializer to use when creating an
* {@link JsonHttpRequest} or {@code null} for none
* @param httpRequestInitializer The initializer to use when creating an {@link HttpRequest} or
* {@code null} for none
* @param jsonFactory A factory for creating JSON parsers and serializers
* @param jsonObjectParser JSON parser to use or {@code null} if unused
* @param rootUrl The root URL of the service. Must end with a "/"
* @param servicePath The service path of the service. Must end with a "/" and not begin with a
* "/". It is allowed to be an empty string {@code ""}
* @param applicationName The application name to be sent in the User-Agent header of requests or
* {@code null} for none
* @since 1.10
*/
protected GoogleClient(HttpTransport transport,
JsonHttpRequestInitializer jsonHttpRequestInitializer,
HttpRequestInitializer httpRequestInitializer, JsonFactory jsonFactory,
JsonObjectParser jsonObjectParser, String rootUrl, String servicePath,
String applicationName) {
super(transport, jsonHttpRequestInitializer, httpRequestInitializer, jsonFactory,
jsonObjectParser, rootUrl, servicePath, applicationName);
}
/**
* Construct the {@link GoogleClient}.
*
* @param transport The transport to use for requests
* @param jsonHttpRequestInitializer The initializer to use when creating an
* {@link JsonHttpRequest} or {@code null} for none
* @param httpRequestInitializer The initializer to use when creating an {@link HttpRequest} or
* {@code null} for none
* @param jsonFactory A factory for creating JSON parsers and serializers
* @param jsonObjectParser JSON parser to use or {@code null} if unused
* @param rootUrl The root URL of the service. Must end with a "/"
* @param servicePath The service path of the service. Must end with a "/" and not begin with a
* "/". It is allowed to be an empty string {@code ""}
* @param applicationName The application name to be sent in the User-Agent header of requests or
* {@code null} for none
* @since 1.11
*/
protected GoogleClient(HttpTransport transport,
JsonHttpRequestInitializer jsonHttpRequestInitializer,
HttpRequestInitializer httpRequestInitializer, JsonFactory jsonFactory,
JsonObjectParser jsonObjectParser, String rootUrl, String servicePath, String applicationName,
boolean suppressPatternChecks) {
super(transport, jsonHttpRequestInitializer, httpRequestInitializer, jsonFactory,
jsonObjectParser, rootUrl, servicePath, applicationName);
this.suppressPatternChecks = suppressPatternChecks;
}
/**
* Create an {@link HttpRequest} suitable for use against this service.
*
* @param method HTTP Method type
* @param url The complete URL of the service where requests should be sent. It includes the base
* path along with the URI template
* @param body A POJO that can be serialized into JSON or {@code null} for none
* @return newly created {@link HttpRequest}
*/
@Override
protected HttpRequest buildHttpRequest(HttpMethod method, GenericUrl url, Object body)
throws IOException {
HttpRequest httpRequest = super.buildHttpRequest(method, url, body);
new MethodOverride().intercept(httpRequest);
// custom methods may use POST with no content but require a Content-Length header
if (body == null && method.equals(HttpMethod.POST)) {
httpRequest.setContent(new EmptyContent());
}
return httpRequest;
}
/**
* Create an {@link BatchRequest} object from this Google API client instance.
*
* <p>
* Sample usage:
* </p>
*
* <pre>
client.batch()
.queue(...)
.queue(...)
.execute();
* </pre>
*
* @return newly created Batch request
*/
public BatchRequest batch() {
return batch(null);
}
/**
* Create an {@link BatchRequest} object from this Google API client instance.
*
* <p>
* Sample usage:
* </p>
*
* <pre>
client.batch(httpRequestInitializer)
.queue(...)
.queue(...)
.execute();
* </pre>
*
* @param httpRequestInitializer The initializer to use when creating the top-level batch HTTP
* request or {@code null} for none
* @return newly created Batch request
*/
public BatchRequest batch(HttpRequestInitializer httpRequestInitializer) {
BatchRequest batch =
new BatchRequest(getRequestFactory().getTransport(), httpRequestInitializer);
GenericUrl baseUrl;
if (isBaseUrlUsed()) {
baseUrl = new GenericUrl(getBaseUrl());
baseUrl.setPathParts(Arrays.asList("", "batch"));
} else {
baseUrl = new GenericUrl(getRootUrl() + "batch");
}
batch.setBatchUrl(baseUrl);
return batch;
}
@Override
protected HttpResponse executeUnparsed(HttpMethod method, GenericUrl url, Object body)
throws IOException {
HttpRequest request = buildHttpRequest(method, url, body);
return executeUnparsed(request);
}
@Override
protected HttpResponse executeUnparsed(HttpRequest request) throws IOException {
return GoogleJsonResponseException.execute(getJsonFactory(), request);
}
/**
* Returns whether discovery pattern checks should be suppressed on required parameters.
*
* @since 1.11
*/
public final boolean getSuppressPatternChecks() {
return suppressPatternChecks;
}
/**
* Builder for {@link GoogleClient}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.6
* @deprecated (scheduled to be removed in 1.14) Use
* {@link com.google.api.client.googleapis.services.AbstractGoogleClient.Builder}
* instead.
*/
@Deprecated
public static class Builder extends JsonHttpClient.Builder {
/** Whether discovery pattern checks should be suppressed on required parameters. */
private boolean suppressPatternChecks;
/**
* Returns whether discovery pattern checks should be suppressed on required parameters.
*
* @since 1.11
*/
public final boolean getSuppressPatternChecks() {
return suppressPatternChecks;
}
/**
* Sets whether discovery pattern checks should be suppressed on required parameters.
*
* <p>
* Default value is {@code false}.
* </p>
*
* @since 1.11
*/
public Builder setSuppressPatternChecks(boolean suppressPatternChecks) {
this.suppressPatternChecks = suppressPatternChecks;
return this;
}
/**
* Returns an instance of a new builder.
*
* @param transport The transport to use for requests
* @param jsonFactory A factory for creating JSON parsers and serializers
* @param baseUrl The base URL of the service. Must end with a "/"
*/
protected Builder(HttpTransport transport, JsonFactory jsonFactory, GenericUrl baseUrl) {
super(transport, jsonFactory, baseUrl);
}
/**
* Returns an instance of a new builder.
*
* @param transport The transport to use for requests
* @param jsonFactory A factory for creating JSON parsers and serializers
* @param rootUrl The root URL of the service. Must end with a "/"
* @param servicePath The service path of the service. Must end with a "/" and not begin with a
* "/". It is allowed to be an empty string {@code ""}
* @param httpRequestInitializer The HTTP request initializer or {@code null} for none
* @since 1.10
*/
public Builder(HttpTransport transport, JsonFactory jsonFactory, String rootUrl,
String servicePath, HttpRequestInitializer httpRequestInitializer) {
super(transport, jsonFactory, rootUrl, servicePath, httpRequestInitializer);
}
/** Builds a new instance of {@link GoogleClient}. */
@Override
public GoogleClient build() {
if (isBaseUrlUsed()) {
return new GoogleClient(getTransport(), getJsonHttpRequestInitializer(),
getHttpRequestInitializer(), getJsonFactory(), getObjectParser(), getBaseUrl().build(),
getApplicationName());
}
return new GoogleClient(getTransport(), getJsonHttpRequestInitializer(),
getHttpRequestInitializer(), getJsonFactory(), getObjectParser(), getRootUrl(),
getServicePath(), getApplicationName(), getSuppressPatternChecks());
}
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/services/GoogleClient.java | Java | asf20 | 13,050 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.services;
import com.google.api.client.googleapis.MethodOverride;
import com.google.api.client.googleapis.batch.BatchCallback;
import com.google.api.client.googleapis.batch.BatchRequest;
import com.google.api.client.googleapis.media.MediaHttpDownloader;
import com.google.api.client.googleapis.media.MediaHttpUploader;
import com.google.api.client.googleapis.subscriptions.SubscribeRequest;
import com.google.api.client.http.AbstractInputStreamContent;
import com.google.api.client.http.EmptyContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpMethods;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpResponseInterceptor;
import com.google.api.client.http.UriTemplate;
import com.google.api.client.util.GenericData;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Abstract Google client request for a {@link AbstractGoogleClient}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @param <T> type of the response
*
* @since 1.12
* @author Yaniv Inbar
*/
public abstract class AbstractGoogleClientRequest<T> extends GenericData {
/** Google client. */
private final AbstractGoogleClient abstractGoogleClient;
/** HTTP method. */
private final String requestMethod;
/** URI template for the path relative to the base URL. */
private final String uriTemplate;
/** HTTP content or {@code null} for none. */
private final HttpContent httpContent;
/** HTTP headers used for the Google client request. */
private HttpHeaders requestHeaders = new HttpHeaders();
/** HTTP headers of the last response or {@code null} before request has been executed. */
private HttpHeaders lastResponseHeaders;
/** Status code of the last response or {@code -1} before request has been executed. */
private int lastStatusCode = -1;
/** Status message of the last response or {@code null} before request has been executed. */
private String lastStatusMessage;
/** Whether to disable GZip compression of HTTP content. */
private boolean disableGZipContent;
/** Response class to parse into. */
private Class<T> responseClass;
/** Media HTTP uploader or {@code null} for none. */
private MediaHttpUploader uploader;
/** Media HTTP downloader or {@code null} for none. */
private MediaHttpDownloader downloader;
/**
* @param abstractGoogleClient Google client
* @param requestMethod HTTP Method
* @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/"
* the base path from the base URL will be stripped out. The URI template can also be a
* full URL. URI template expansion is done using
* {@link UriTemplate#expand(String, String, Object, boolean)}
* @param httpContent HTTP content or {@code null} for none
* @param responseClass response class to parse into
*/
protected AbstractGoogleClientRequest(AbstractGoogleClient abstractGoogleClient,
String requestMethod, String uriTemplate, HttpContent httpContent, Class<T> responseClass) {
this.responseClass = Preconditions.checkNotNull(responseClass);
this.abstractGoogleClient = Preconditions.checkNotNull(abstractGoogleClient);
this.requestMethod = Preconditions.checkNotNull(requestMethod);
this.uriTemplate = Preconditions.checkNotNull(uriTemplate);
this.httpContent = httpContent;
// application name
String applicationName = abstractGoogleClient.getApplicationName();
if (applicationName != null) {
requestHeaders.setUserAgent(applicationName);
}
}
/** Returns whether to disable GZip compression of HTTP content. */
public final boolean getDisableGZipContent() {
return disableGZipContent;
}
/**
* Sets whether to disable GZip compression of HTTP content.
*
* <p>
* By default it is {@code false}.
* </p>
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public AbstractGoogleClientRequest<T> setDisableGZipContent(boolean disableGZipContent) {
this.disableGZipContent = disableGZipContent;
return this;
}
/** Returns the HTTP method. */
public final String getRequestMethod() {
return requestMethod;
}
/** Returns the URI template for the path relative to the base URL. */
public final String getUriTemplate() {
return uriTemplate;
}
/** Returns the HTTP content or {@code null} for none. */
public final HttpContent getHttpContent() {
return httpContent;
}
/**
* Returns the Google client.
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public AbstractGoogleClient getAbstractGoogleClient() {
return abstractGoogleClient;
}
/** Returns the HTTP headers used for the Google client request. */
public final HttpHeaders getRequestHeaders() {
return requestHeaders;
}
/**
* Sets the HTTP headers used for the Google client request.
*
* <p>
* These headers are set on the request after {@link #buildHttpRequest} is called, this means that
* {@link HttpRequestInitializer#initialize} is called first.
* </p>
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public AbstractGoogleClientRequest<T> setRequestHeaders(HttpHeaders headers) {
this.requestHeaders = headers;
return this;
}
/**
* Returns the HTTP headers of the last response or {@code null} before request has been executed.
*/
public final HttpHeaders getLastResponseHeaders() {
return lastResponseHeaders;
}
/**
* Returns the status code of the last response or {@code -1} before request has been executed.
*/
public final int getLastStatusCode() {
return lastStatusCode;
}
/**
* Returns the status message of the last response or {@code null} before request has been
* executed.
*/
public final String getLastStatusMessage() {
return lastStatusMessage;
}
/** Returns the response class to parse into. */
public final Class<T> getResponseClass() {
return responseClass;
}
/**
* Subscribes to notifications for a resource or collection.
*
* <p>
* Overriding is only supported for the purpose of changing visibility to public, but nothing
* else.
* </p>
*
* @param notificationDeliveryMethod notification delivery method
* @throws IOException
*
* @since 1.14
*/
protected SubscribeRequest subscribe(String notificationDeliveryMethod) throws IOException {
return new SubscribeRequest(buildHttpRequest(), notificationDeliveryMethod);
}
/** Returns the media HTTP Uploader or {@code null} for none. */
public final MediaHttpUploader getMediaHttpUploader() {
return uploader;
}
/**
* Initializes the media HTTP uploader based on the media content.
*
* @param mediaContent media content
*/
protected final void initializeMediaUpload(AbstractInputStreamContent mediaContent) {
HttpRequestFactory requestFactory = abstractGoogleClient.getRequestFactory();
this.uploader = new MediaHttpUploader(
mediaContent, requestFactory.getTransport(), requestFactory.getInitializer());
this.uploader.setInitiationRequestMethod(requestMethod);
if (httpContent != null) {
this.uploader.setMetadata(httpContent);
}
}
/** Returns the media HTTP downloader or {@code null} for none. */
public final MediaHttpDownloader getMediaHttpDownloader() {
return downloader;
}
/** Initializes the media HTTP downloader. */
protected final void initializeMediaDownload() {
HttpRequestFactory requestFactory = abstractGoogleClient.getRequestFactory();
this.downloader =
new MediaHttpDownloader(requestFactory.getTransport(), requestFactory.getInitializer());
}
/**
* Creates a new instance of {@link GenericUrl} suitable for use against this service.
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*
* @return newly created {@link GenericUrl}
*/
public GenericUrl buildHttpRequestUrl() {
return new GenericUrl(
UriTemplate.expand(abstractGoogleClient.getBaseUrl(), uriTemplate, this, true));
}
/**
* Create a request suitable for use against this service.
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*/
public HttpRequest buildHttpRequest() throws IOException {
return buildHttpRequest(false);
}
/**
* Create a request suitable for use against this service, but using HEAD instead of GET.
*
* <p>
* Only supported when the original request method is GET.
* </p>
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*/
protected HttpRequest buildHttpRequestUsingHead() throws IOException {
return buildHttpRequest(true);
}
/** Create a request suitable for use against this service. */
private HttpRequest buildHttpRequest(boolean usingHead) throws IOException {
Preconditions.checkArgument(uploader == null);
Preconditions.checkArgument(!usingHead || requestMethod.equals(HttpMethods.GET));
String requestMethodToUse = usingHead ? HttpMethods.HEAD : requestMethod;
final HttpRequest httpRequest = getAbstractGoogleClient()
.getRequestFactory().buildRequest(requestMethodToUse, buildHttpRequestUrl(), httpContent);
new MethodOverride().intercept(httpRequest);
httpRequest.setParser(getAbstractGoogleClient().getObjectParser());
// custom methods may use POST with no content but require a Content-Length header
if (httpContent == null && (requestMethod.equals(HttpMethods.POST)
|| requestMethod.equals(HttpMethods.PUT) || requestMethod.equals("PATCH"))) {
httpRequest.setContent(new EmptyContent());
}
httpRequest.getHeaders().putAll(requestHeaders);
httpRequest.setEnableGZipContent(!disableGZipContent);
final HttpResponseInterceptor responseInterceptor = httpRequest.getResponseInterceptor();
httpRequest.setResponseInterceptor(new HttpResponseInterceptor() {
public void interceptResponse(HttpResponse response) throws IOException {
if (responseInterceptor != null) {
responseInterceptor.interceptResponse(response);
}
if (!response.isSuccessStatusCode() && httpRequest.getThrowExceptionOnExecuteError()) {
throw newExceptionOnError(response);
}
}
});
return httpRequest;
}
/**
* Sends the metadata request to the server and returns the raw metadata {@link HttpResponse}.
*
* <p>
* Callers are responsible for disconnecting the HTTP response by calling
* {@link HttpResponse#disconnect}. Example usage:
* </p>
*
* <pre>
HttpResponse response = request.executeUnparsed();
try {
// process response..
} finally {
response.disconnect();
}
* </pre>
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*
* @return the {@link HttpResponse}
*/
public HttpResponse executeUnparsed() throws IOException {
return executeUnparsed(false);
}
/**
* Sends the media request to the server and returns the raw media {@link HttpResponse}.
*
* <p>
* Callers are responsible for disconnecting the HTTP response by calling
* {@link HttpResponse#disconnect}. Example usage:
* </p>
*
* <pre>
HttpResponse response = request.executeMedia();
try {
// process response..
} finally {
response.disconnect();
}
* </pre>
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*
* @return the {@link HttpResponse}
*/
protected HttpResponse executeMedia() throws IOException {
set("alt", "media");
return executeUnparsed();
}
/**
* Sends the metadata request using HEAD to the server and returns the raw metadata
* {@link HttpResponse} for the response headers.
*
* <p>
* Only supported when the original request method is GET. The response content is assumed to be
* empty and ignored. Calls {@link HttpResponse#ignore()} so there is no need to disconnect the
* response. Example usage:
* </p>
*
* <pre>
HttpResponse response = request.executeUsingHead();
// look at response.getHeaders()
* </pre>
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*
* @return the {@link HttpResponse}
*/
protected HttpResponse executeUsingHead() throws IOException {
Preconditions.checkArgument(uploader == null);
HttpResponse response = executeUnparsed(true);
response.ignore();
return response;
}
/**
* Sends the metadata request using the given request method to the server and returns the raw
* metadata {@link HttpResponse}.
*/
private HttpResponse executeUnparsed(boolean usingHead) throws IOException {
HttpResponse response;
if (uploader == null) {
// normal request (not upload)
response = buildHttpRequest(usingHead).execute();
} else {
// upload request
GenericUrl httpRequestUrl = buildHttpRequestUrl();
HttpRequest httpRequest = getAbstractGoogleClient()
.getRequestFactory().buildRequest(requestMethod, httpRequestUrl, httpContent);
boolean throwExceptionOnExecuteError = httpRequest.getThrowExceptionOnExecuteError();
response = uploader.setInitiationHeaders(requestHeaders)
.setDisableGZipContent(disableGZipContent)
.upload(httpRequestUrl);
response.getRequest().setParser(getAbstractGoogleClient().getObjectParser());
// process any error
if (throwExceptionOnExecuteError && !response.isSuccessStatusCode()) {
throw newExceptionOnError(response);
}
}
// process response
lastResponseHeaders = response.getHeaders();
lastStatusCode = response.getStatusCode();
lastStatusMessage = response.getStatusMessage();
return response;
}
/**
* Returns the exception to throw on an HTTP error response as defined by
* {@link HttpResponse#isSuccessStatusCode()}.
*
* <p>
* It is guaranteed that {@link HttpResponse#isSuccessStatusCode()} is {@code false}. Default
* implementation is to call {@link HttpResponseException#HttpResponseException(HttpResponse)},
* but subclasses may override.
* </p>
*
* @param response HTTP response
* @return exception to throw
*/
protected IOException newExceptionOnError(HttpResponse response) {
return new HttpResponseException(response);
}
/**
* Sends the metadata request to the server and returns the parsed metadata response.
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*
* @return parsed HTTP response
*/
public T execute() throws IOException {
HttpResponse response = executeUnparsed();
// TODO(yanivi): remove workaround when feature is implemented
// workaround for http://code.google.com/p/google-http-java-client/issues/detail?id=110
if (Void.class.equals(responseClass)) {
response.ignore();
return null;
}
return response.parseAs(responseClass);
}
/**
* Sends the metadata request to the server and returns the metadata content input stream of
* {@link HttpResponse}.
*
* <p>
* Callers are responsible for closing the input stream after it is processed. Example sample:
* </p>
*
* <pre>
InputStream is = request.executeAsInputStream();
try {
// Process input stream..
} finally {
is.close();
}
* </pre>
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*
* @return input stream of the response content
*/
public InputStream executeAsInputStream() throws IOException {
return executeUnparsed().getContent();
}
/**
* Sends the media request to the server and returns the media content input stream of
* {@link HttpResponse}.
*
* <p>
* Callers are responsible for closing the input stream after it is processed. Example sample:
* </p>
*
* <pre>
InputStream is = request.executeMediaAsInputStream();
try {
// Process input stream..
} finally {
is.close();
}
* </pre>
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*
* @return input stream of the response content
*/
protected InputStream executeMediaAsInputStream() throws IOException {
return executeMedia().getContent();
}
/**
* Sends the metadata request to the server and writes the metadata content input stream of
* {@link HttpResponse} into the given destination output stream.
*
* <p>
* This method closes the content of the HTTP response from {@link HttpResponse#getContent()}.
* </p>
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*
* @param outputStream destination output stream
*/
public void executeAndDownloadTo(OutputStream outputStream) throws IOException {
executeUnparsed().download(outputStream);
}
/**
* Sends the media request to the server and writes the media content input stream of
* {@link HttpResponse} into the given destination output stream.
*
* <p>
* This method closes the content of the HTTP response from {@link HttpResponse#getContent()}.
* </p>
*
* <p>
* Subclasses may override by calling the super implementation.
* </p>
*
* @param outputStream destination output stream
*/
protected void executeMediaAndDownloadTo(OutputStream outputStream) throws IOException {
if (downloader == null) {
executeMedia().download(outputStream);
} else {
downloader.download(buildHttpRequestUrl(), requestHeaders, outputStream);
}
}
/**
* Queues the request into the specified batch request container using the specified error class.
*
* <p>
* Batched requests are then executed when {@link BatchRequest#execute()} is called.
* </p>
*
* @param batchRequest batch request container
* @param errorClass data class the unsuccessful response will be parsed into or
* {@code Void.class} to ignore the content
* @param callback batch callback
*/
public final <E> void queue(
BatchRequest batchRequest, Class<E> errorClass, BatchCallback<T, E> callback)
throws IOException {
Preconditions.checkArgument(uploader == null, "Batching media requests is not supported");
batchRequest.queue(buildHttpRequest(), getResponseClass(), errorClass, callback);
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/services/AbstractGoogleClientRequest.java | Java | asf20 | 19,843 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.services;
import java.io.IOException;
/**
* Google common client request initializer implementation for setting properties like key and
* userIp.
*
* <p>
* The simplest usage is to use it to set the key parameter:
* </p>
*
* <pre>
public static final GoogleClientRequestInitializer KEY_INITIALIZER =
new CommonGoogleClientRequestInitializer(KEY);
* </pre>
*
* <p>
* There is also a constructor to set both the key and userIp parameters:
* </p>
*
* <pre>
public static final GoogleClientRequestInitializer INITIALIZER =
new CommonGoogleClientRequestInitializer(KEY, USER_IP);
* </pre>
*
* <p>
* If you want to implement custom logic, extend it like this:
* </p>
*
* <pre>
public static class MyRequestInitializer extends CommonGoogleClientRequestInitializer {
{@literal @}Override
public void initialize(AbstractGoogleClientRequest{@literal <}?{@literal >} request)
throws IOException {
// custom logic
}
}
* </pre>
*
* <p>
* Finally, to set the key and userIp parameters and insert custom logic, extend it like this:
* </p>
*
* <pre>
public static class MyRequestInitializer2 extends CommonGoogleClientRequestInitializer {
public MyRequestInitializer2() {
super(KEY, USER_IP);
}
{@literal @}Override
public void initialize(AbstractGoogleClientRequest{@literal <}?{@literal >} request)
throws IOException {
super.initialize(request); // must be called to set the key and userIp parameters
// insert some additional logic
}
}
* </pre>
*
* <p>
* Subclasses should be thread-safe.
* </p>
*
* @since 1.12
* @author Yaniv Inbar
*/
public class CommonGoogleClientRequestInitializer implements GoogleClientRequestInitializer {
/** API key or {@code null} to leave it unchanged. */
private final String key;
/** User IP or {@code null} to leave it unchanged. */
private final String userIp;
public CommonGoogleClientRequestInitializer() {
this(null);
}
/**
* @param key API key or {@code null} to leave it unchanged
*/
public CommonGoogleClientRequestInitializer(String key) {
this(key, null);
}
/**
* @param key API key or {@code null} to leave it unchanged
* @param userIp user IP or {@code null} to leave it unchanged
*/
public CommonGoogleClientRequestInitializer(String key, String userIp) {
this.key = key;
this.userIp = userIp;
}
/**
* Subclasses should call super implementation in order to set the key and userIp.
*
* @throws IOException I/O exception
*/
public void initialize(AbstractGoogleClientRequest<?> request) throws IOException {
if (key != null) {
request.put("key", key);
}
if (userIp != null) {
request.put("userIp", userIp);
}
}
/** Returns the API key or {@code null} to leave it unchanged. */
public final String getKey() {
return key;
}
/** Returns the user IP or {@code null} to leave it unchanged. */
public final String getUserIp() {
return userIp;
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/services/CommonGoogleClientRequestInitializer.java | Java | asf20 | 3,635 |
/*
* Copyright (c) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.services;
import com.google.api.client.http.json.JsonHttpRequest;
import com.google.api.client.http.json.JsonHttpRequestInitializer;
/**
* Google client request initializer that specifies a Google API key for all requests.
*
* <p>
* This is needed when doing unauthenticated access to Google APIs. Otherwise, you will only be able
* to make a small number of queries. When you exceed this limit, you will receive a "403 Forbidden"
* error with the message "Daily Limit Exceeded. Please sign up". See <a
* href="http://code.google.com/p/google-api-java-client/wiki/OAuth2#Unauthenticated_access"
* >Unauthenticated access</a> for more details.
* </p>
*
* <p>
* Note that this is not needed when doing authenticated access with an OAuth 2.0 access token,
* because the OAuth 2.0 client ID is already associated with the same project as the API key.
* </p>
*
* @since 1.8
* @author Yaniv Inbar
* @deprecated (scheduled to be removed in 1.14) Instead use either
* {@link CommonGoogleClientRequestInitializer} or a subclass of it.
*/
@Deprecated
public class GoogleKeyInitializer
implements
JsonHttpRequestInitializer,
GoogleClientRequestInitializer {
/** API key. */
private final String key;
/**
* @param key API key
*/
public GoogleKeyInitializer(String key) {
this.key = key;
}
public void initialize(JsonHttpRequest request) {
request.put("key", key);
}
public void initialize(AbstractGoogleClientRequest<?> request) {
request.put("key", key);
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/services/GoogleKeyInitializer.java | Java | asf20 | 2,169 |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis;
import com.google.api.client.http.EmptyContent;
import com.google.api.client.http.HttpExecuteInterceptor;
import com.google.api.client.http.HttpMethods;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.UrlEncodedContent;
import java.io.IOException;
/**
* Thread-safe HTTP request execute interceptor for Google API's that wraps HTTP requests inside of
* a POST request and uses {@link #HEADER} header to specify the actual HTTP method.
*
* <p>
* Use this for example for an HTTP transport that doesn't support PATCH like
* {@code NetHttpTransport} or {@code UrlFetchTransport}. By default, only the methods not supported
* by the transport will be overridden. When running behind a firewall that does not support certain
* verbs like PATCH, use the {@link MethodOverride.Builder#setOverrideAllMethods(boolean)}
* constructor instead to specify to override all methods. POST is never overridden.
* </p>
*
* <p>
* This class also allows GET requests with a long URL (> 2048 chars) to be instead sent using
* method override as a POST request.
* </p>
*
* <p>
* Sample usage, taking advantage that this class implements {@link HttpRequestInitializer}:
* </p>
*
* <pre>
public static HttpRequestFactory createRequestFactory(HttpTransport transport) {
return transport.createRequestFactory(new MethodOverride());
}
* </pre>
*
* <p>
* If you have a custom request initializer, take a look at the sample usage for
* {@link HttpExecuteInterceptor}, which this class also implements.
* </p>
*
* @since 1.4
* @author Yaniv Inbar
*/
@SuppressWarnings("deprecation")
public final class MethodOverride implements HttpExecuteInterceptor, HttpRequestInitializer {
/**
* Name of the method override header.
*
* @since 1.13
*/
public static final String HEADER = "X-HTTP-Method-Override";
/** Maximum supported URL length. */
static final int MAX_URL_LENGTH = 2048;
/**
* Whether to allow all methods (except GET and POST) to be overridden regardless of whether the
* transport supports them.
*/
private final boolean overrideAllMethods;
/** Only overrides HTTP methods that the HTTP transport does not support. */
public MethodOverride() {
this(false);
}
MethodOverride(boolean overrideAllMethods) {
this.overrideAllMethods = overrideAllMethods;
}
public void initialize(HttpRequest request) {
request.setInterceptor(this);
}
public void intercept(HttpRequest request) throws IOException {
if (overrideThisMethod(request)) {
String requestMethod = request.getRequestMethod();
request.setRequestMethod(HttpMethods.POST);
request.getHeaders().set(HEADER, requestMethod);
if (requestMethod.equals(HttpMethods.GET)) {
// take the URI query part and put it into the HTTP body
request.setContent(new UrlEncodedContent(request.getUrl()));
} else if (request.getContent() == null) {
// Google servers will fail to process a POST unless the Content-Length header is specified
request.setContent(new EmptyContent());
}
}
}
private boolean overrideThisMethod(HttpRequest request) throws IOException {
String requestMethod = request.getRequestMethod();
if (requestMethod.equals(HttpMethods.POST)) {
return false;
}
if (requestMethod.equals(HttpMethods.GET)
? request.getUrl().build().length() > MAX_URL_LENGTH : overrideAllMethods) {
return true;
}
return !request.getTransport().supportsMethod(requestMethod);
}
/**
* Builder for {@link MethodOverride}.
*
* @since 1.12
* @author Yaniv Inbar
*/
public static final class Builder {
/**
* Whether to allow all methods (except GET and POST) to be overridden regardless of whether the
* transport supports them.
*/
private boolean overrideAllMethods;
/** Builds the {@link MethodOverride}. */
public MethodOverride build() {
return new MethodOverride(overrideAllMethods);
}
/**
* Returns whether to allow all methods (except GET and POST) to be overridden regardless of
* whether the transport supports them.
*/
public boolean getOverrideAllMethods() {
return overrideAllMethods;
}
/**
* Sets whether to allow all methods (except GET and POST) to be overridden regardless of
* whether the transport supports them.
*
* <p>
* Default is {@code false}.
* </p>
*/
public Builder setOverrideAllMethods(boolean overrideAllMethods) {
this.overrideAllMethods = overrideAllMethods;
return this;
}
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/MethodOverride.java | Java | asf20 | 5,328 |
/*
* Copyright (c) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.subscriptions;
import java.util.Collection;
import java.util.Collections;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* {@link SubscriptionStore} which stores all subscription information in memory.
*
* <p>
* Thread-safe implementation.
* </p>
*
* <b>Example usage:</b>
* <pre>
service.setSubscriptionStore(new MemorySubscriptionStore());
* </pre>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
public class MemorySubscriptionStore implements SubscriptionStore {
/** Lock on the token response information. */
private final Lock lock = new ReentrantLock();
/** Map of all stored subscriptions. */
private final SortedMap<String, Subscription> storedSubscriptions =
new TreeMap<String, Subscription>();
public void storeSubscription(Subscription subscription) {
lock.lock();
try {
storedSubscriptions.put(subscription.getSubscriptionId(), subscription);
} finally {
lock.unlock();
}
}
public void removeSubscription(Subscription subscription) {
lock.lock();
try {
storedSubscriptions.remove(subscription.getSubscriptionId());
} finally {
lock.unlock();
}
}
public Collection<Subscription> listSubscriptions() {
lock.lock();
try {
return Collections.unmodifiableCollection(storedSubscriptions.values());
} finally {
lock.unlock();
}
}
public Subscription getSubscription(String subscriptionId) {
lock.lock();
try {
return storedSubscriptions.get(subscriptionId);
} finally {
lock.unlock();
}
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/MemorySubscriptionStore.java | Java | asf20 | 2,303 |
/*
* Copyright (c) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.subscriptions;
/**
* Typed notification sent to this client about a subscribed resource.
*
* <p>
* Thread-safe implementation.
* </p>
*
* <b>Example usage:</b>
*
* <pre>
void handleNotification(
Subscription subscription, TypedNotification<ItemList> notification) {
for (Item item : notification.getContent().getItems()) {
System.out.println(item.getId());
}
}
* </pre>
*
* @param <T> Data content from the underlying response stored within this notification
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
public final class TypedNotification<T> extends Notification {
/** Typed content or {@code null} for none. */
private final T content;
/** Returns the typed content or {@code null} for none. */
public final T getContent() {
return content;
}
/**
* @param notification notification whose information is copied
* @param content typed content or {@code null} for none
*/
public TypedNotification(Notification notification, T content) {
super(notification);
this.content = content;
}
/**
* @param subscriptionId subscription UUID
* @param topicId opaque ID for the subscribed resource that is stable across API versions
* @param topicURI opaque ID (in the form of a canonicalized URI) for the subscribed resource that
* is sensitive to the API version
* @param clientToken client token (an opaque string) or {@code null} for none
* @param messageNumber message number (a monotonically increasing value starting with 1)
* @param eventType event type (see {@link EventTypes})
* @param changeType type of change performed on the resource or {@code null} for none
* @param content typed content or {@code null} for none
*/
public TypedNotification(String subscriptionId, String topicId, String topicURI,
String clientToken, long messageNumber, String eventType, String changeType, T content) {
super(subscriptionId, topicId, topicURI, clientToken, messageNumber, eventType, changeType);
this.content = content;
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/TypedNotification.java | Java | asf20 | 2,710 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.subscriptions;
import com.google.api.client.http.HttpResponse;
import com.google.common.base.Preconditions;
/**
* Subscribe response.
*
* @author Yaniv Inbar
* @since 1.14
*/
public class SubscribeResponse {
/** HTTP response. */
private final HttpResponse response;
/** Subscription or {@code null} for none. */
private final Subscription subscription;
/**
* @param response HTTP response
* @param subscription subscription or {@code null} for none
*/
public SubscribeResponse(HttpResponse response, Subscription subscription) {
this.response = Preconditions.checkNotNull(response);
this.subscription = subscription;
}
/** Returns the opaque ID for the subscribed resource that is stable across API versions. */
public final String getTopicId() {
return SubscriptionHeaders.getTopicId(response.getHeaders());
}
/**
* Returns the opaque ID (in the form of a canonicalized URI) for the subscribed resource that is
* sensitive to the API version.
*/
public final String getTopicUri() {
return SubscriptionHeaders.getTopicUri(response.getHeaders());
}
/** Returns the subscription UUID. */
public final String getSubscriptionId() {
return SubscriptionHeaders.getSubscriptionId(response.getHeaders());
}
/**
* Returns the HTTP Date indicating the time at which the subscription will expire returned in the
* subscribe response or {@code null} for an infinite TTL.
*/
public final String getSubscriptionExpires() {
return SubscriptionHeaders.getSubscriptionExpires(response.getHeaders());
}
/**
* Returns the client token (an opaque string) provided by the client or {@code null} for none.
*/
public final String getClientToken() {
return SubscriptionHeaders.getClientToken(response.getHeaders());
}
/** Returns the HTTP response. */
public final HttpResponse getHttpResponse() {
return response;
}
/** Returns the subscription or {@code null} for none. */
public final Subscription getSubscription() {
return subscription;
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/SubscribeResponse.java | Java | asf20 | 2,660 |
/*
* Copyright (c) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/**
* JSON-based notification handling for subscriptions.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.14
* @author Matthias Linder (mlinder)
*/
package com.google.api.client.googleapis.subscriptions.json;
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/json/package-info.java | Java | asf20 | 957 |
/*
* Copyright (c) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.googleapis.subscriptions.json;
import com.google.api.client.googleapis.subscriptions.TypedNotificationCallback;
import com.google.api.client.googleapis.subscriptions.UnparsedNotification;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.util.ObjectParser;
import java.io.IOException;
/**
* A {@link TypedNotificationCallback} which uses an JSON content encoding.
*
* <p>
* Must not be implemented in form of an anonymous class as this will break serialization.
* </p>
*
* <p>
* Implementation should be thread-safe.
* </p>
*
* <p>
* State will only be persisted once when a subscription is created. All state changes occurring
* during the {@code .handleNotification(..)} call will be lost.
* </p>
*
* <b>Example usage:</b>
* <pre>
class MyJsonNotificationCallback extends JsonNotificationCallback<ItemList> {
void handleNotification(
Subscription subscription, TypedNotification<ItemList> notification) {
for (Item item in notification.getContent().getItems()) {
System.out.println(item.getId());
}
}
}
JsonFactory createJsonFactory() {
return new JacksonFactory();
}
...
service.items.list("someID").subscribe(new MyJsonNotificationCallback()).execute()
* </pre>
*
* @param <T> Type of the data contained within a notification
* @author Matthias Linder (mlinder)
* @since 1.14
*/
@SuppressWarnings("serial")
public abstract class JsonNotificationCallback<T> extends TypedNotificationCallback<T> {
/** JSON factory used to deserialize notifications. {@code null} until first used. */
private transient JsonFactory jsonFactory;
/**
* Returns the JSON-factory used by this handler.
*/
public final JsonFactory getJsonFactory() throws IOException {
if (jsonFactory == null) {
jsonFactory = createJsonFactory();
}
return jsonFactory;
}
// TODO(mlinder): Don't have the user supply the JsonFactory, but serialize it instead.
/**
* Creates a new JSON factory which is used to deserialize notifications.
*/
protected abstract JsonFactory createJsonFactory() throws IOException;
@Override
protected final ObjectParser getParser(UnparsedNotification notification) throws IOException {
return new JsonObjectParser(getJsonFactory());
}
@Override
public JsonNotificationCallback<T> setDataType(Class<T> dataClass) {
return (JsonNotificationCallback<T>) super.setDataType(dataClass);
}
}
| 0912116-qwqwdfwedwdwq | google-api-client/src/main/java/com/google/api/client/googleapis/subscriptions/json/JsonNotificationCallback.java | Java | asf20 | 3,165 |