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
/** * Created by 相杰 on 13-10-21. */ /*脚本说明: * 对有data-selection="btn"属性的元素进行绑定,标记在a标签中,a标签的父元素需要时li标签 * */ $(function () { var $btnSelection = $('[data-selection="btn"]') $btnSelection.on("click", function () { var $this = $(this) var $parent = $this.parent() var $siblings = $parent.siblings() if(!$parent.hasClass("active")){ $siblings.removeClass("active") $parent.addClass("active") }else{ $parent.removeClass("active") } return false }) })
zzzxj-project-jackphonewebsote
trunk/js/selection.js
JavaScript
asf20
645
<!DOCTYPE html> <html> <head> <title>用户中心</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link href="css/bootstrap.min.css" rel="stylesheet" media="screen"> <link rel="stylesheet" href="css/common.css" /> <script src="js/jquery.v1.9.1.min.js"></script> <script src="js/bootstrap.min.js"></script> <style> .navbar-inverse li a { color: #FFF; } </style> </head> <body> <!--顶部栏目--> <header class="navbar navbar-inverse navbar-fixed-top bs-docs-nav" id="header"> <div class="container"> <div class="row"> <div id="backToPrevBtn" class="col-xs-2 text-while"> <a class="glyphicon glyphicon-circle-arrow-left" href="#"></a> </div> <div id="logo" class="col-xs-6 text-while"> <span>your logo</span> </div> <div id="btnUser" class="col-xs-2 text-while"> <a class="glyphicon glyphicon-user" href="User.html"></a> </div> <div id="btnShoppingCart" class="col-xs-2 text-while"> <a class="glyphicon glyphicon-shopping-cart" href="ShoppingCart.html"></a> </div> </div> </div> </header> <!--顶部栏目 END--> <!--内容--> <div class="wrapper"> <div class="container norowpadding"> <!-- banner --> <div class="row"> <div class="banner" style="height: 100px; overflow: hidden; position: relative;"> <img src="img/1.jpg" class="img-responsive" style="position: absolute; top: 0px; left: 0px; width: 100%; height: auto; z-index: 1;" /> <div style="position: absolute; z-index: 99; padding: 5px 20px;"> <h3 class="text-while" style="font-weight: bold;">您好,欢迎来到XXX</h3> <div class=""> <a href="#" class="btn btn-default">收货地址管理</a> </div> </div> </div> </div> <!-- banner end --> <!--<div class="row"> <div class="col-xs-4"></div> <div class="col-xs-4"></div> <div class="col-xs-4"></div> </div>--> <!-- 标签切换 --> <div class="row"> <ul class="nav nav-tabs navbar-inverse" id="nava"> <li class="active" style="width: 33%; text-align: center;"><a href="#payment">待付款</a></li> <li style="width: 33%; text-align: center;"><a href="#forTheGoods">待收货</a></li> <li style="width: 33%; text-align: center;"><a href="#ended">已结束</a></li> </ul> <div id="myTabContent" class="tab-content" style="padding: 5px 20px;"> <div class="tab-pane fade active in" id="payment"> <!-- 列表中的详细事项 --> <!-- 一个列表中的详细事项 --> <div class="list-group"> <div class="list-group-item hasrowpadding"> <h4 class="list-group-item-heading">这里是标题</h4> <div class="row"> <div class="col-xs-4"> <img src="img/1.jpg" class="img-responsive" /> </div> <div class="col-xs-8"> <p>微购物JackJones杰克琼斯棉质男士休闲水洗牛仔长裤I|213232029</p> </div> </div> <div class="clearfix group-footer"> <span style="float: left;">待付款</span> <span style="float: right;">共计1件商品 总价<strong class="text-danger">¥500</strong></span> </div> <div style="margin: 10px 0;"> <a class="btn btn-danger col-xs-12" href="#">立即付款</a> </div> </div> </div> <!-- 一个列表中的详细事项 end --> <div class="list-group"> <div class="list-group-item hasrowpadding"> <h4 class="list-group-item-heading">这里是标题</h4> <div class="row"> <div class="col-xs-4"> <img src="img/1.jpg" class="img-responsive" /> </div> <div class="col-xs-8"> <p>微购物JackJones杰克琼斯棉质男士休闲水洗牛仔长裤I|213232029</p> </div> </div> <div class="clearfix group-footer"> <span style="float: left;">待付款</span> <span style="float: right;">共计1件商品 总价<strong class="text-danger">¥500</strong></span> </div> </div> </div> <div class="list-group"> <div class="list-group-item hasrowpadding"> <h4 class="list-group-item-heading">这里是标题</h4> <div class="row"> <div class="col-xs-4"> <img src="img/1.jpg" class="img-responsive" /> </div> <div class="col-xs-8"> <p>微购物JackJones杰克琼斯棉质男士休闲水洗牛仔长裤I|213232029</p> </div> </div> <div class="clearfix group-footer"> <span style="float: left;">待付款</span> <span style="float: right;">共计1件商品 总价<strong class="text-danger">¥500</strong></span> </div> </div> </div> <div class="list-group"> <div class="list-group-item hasrowpadding"> <h4 class="list-group-item-heading">这里是标题</h4> <div class="row"> <div class="col-xs-4"> <img src="img/1.jpg" class="img-responsive" /> </div> <div class="col-xs-8"> <p>微购物JackJones杰克琼斯棉质男士休闲水洗牛仔长裤I|213232029</p> </div> </div> <div class="clearfix group-footer"> <span style="float: left;">待付款</span> <span style="float: right;">共计1件商品 总价<strong class="text-danger">¥500</strong></span> </div> </div> </div> <div class="list-group"> <div class="list-group-item hasrowpadding"> <h4 class="list-group-item-heading">这里是标题</h4> <div class="row"> <div class="col-xs-4"> <img src="img/1.jpg" class="img-responsive" /> </div> <div class="col-xs-8"> <p>微购物JackJones杰克琼斯棉质男士休闲水洗牛仔长裤I|213232029</p> </div> </div> <div class="clearfix group-footer"> <span style="float: left;">待付款</span> <span style="float: right;">共计1件商品 总价<strong class="text-danger">¥500</strong></span> </div> </div> </div> <!-- 列表中的详细事项 end --> </div> <div class="tab-pane fade" id="forTheGoods"> <div class="noMSG"> 暂时没有信息 </div> </div> <div class="tab-pane fade" id="ended"> <div class="noMSG"> 暂时没有信息 </div> </div> </div> </div> <!-- 标签切换 end --> </div> </div> <!--内容 END--> <!--脚部导航--> <footer id="footer"> <div class="container"> <div class="row"> <div class="col-xs-4"><a href="#" class="text-n">户首页页</a></div> <div class="col-xs-4"><a href="#">会员中心</a></div> <div class="col-xs-4"><a href="#">品牌介绍</a></div> </div> </div> </footer> <!--脚部导航 END--> </body> </html> <script> $(function () { $('#nava a').click(function (e) { e.preventDefault() $(this).tab('show') }) }) </script>
zzzxj-project-jackphonewebsote
trunk/User.html
HTML
asf20
10,462
<!DOCTYPE html> <html> <head> <title>一个类别的所有商品</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link href="css/bootstrap.min.css" rel="stylesheet" media="screen"> <link rel="stylesheet" href="css/common.css" /> <script src="js/jquery.v1.9.1.min.js"></script> <script src="js/bootstrap.min.js"></script> </head> <body> <!--顶部栏目--> <header class="navbar navbar-inverse navbar-fixed-top bs-docs-nav" id="header"> <div class="container"> <div class="row"> <div id="backToPrevBtn" class="col-xs-2 text-while"> <a class="glyphicon glyphicon-circle-arrow-left" href="#"></a> </div> <div id="logo" class="col-xs-6 text-while"> <span>your logo</span> </div> <div id="btnUser" class="col-xs-2 text-while"> <a class="glyphicon glyphicon-user" href="User.html"></a> </div> <div id="btnShoppingCart" class="col-xs-2 text-while"> <a class="glyphicon glyphicon-shopping-cart" href="ShoppingCart.html"></a> </div> </div> </div> </header> <!--顶部栏目 END--> <!--内容--> <div class="wrapper"> <div class="container norowpadding"> <div class="row"> <div class="banner"> <img src="img/5.jpg" class="img-responsive" /> </div> </div> <!-- 产品列表 --> <div class="productlist"> <h3>牛仔裤</h3> <div class="row"> <div class="col-xs-6"> <a href="ProductDetailPage.html"> <div class="list-item"> <img src="img/1.jpg" class="img-responsive" /> <div class="p10"> <p>这里是简介</p> <p class="text-danger">¥499</p> </div> </div> </a> </div> <div class="col-xs-6"> <a href="ProductDetailPage.html"> <div class="list-item"> <img src="img/2.jpg" class="img-responsive" /> <div class="p10"> <p>这里是简介</p> <p class="text-danger">¥499</p> </div> </div> </a> </div> </div> <div class="row"> <div class="col-xs-6"> <a href="ProductDetailPage.html"> <div class="list-item"> <img src="img/3.jpg" class="img-responsive" /> <div class="p10"> <p>这里是简介</p> <p class="text-danger">¥499</p> </div> </div> </a> </div> <div class="col-xs-6"> <a href="ProductDetailPage.html"> <div class="list-item"> <img src="img/4.jpg" class="img-responsive" /> <div class="p10"> <p>这里是简介</p> <p class="text-danger">¥499</p> </div> </div> </a> </div> </div> <div class="row"> <div class="col-xs-6"> <a href="ProductDetailPage.html"> <div class="list-item"> <img src="img/5.jpg" class="img-responsive" /> <div class="p10"> <p>这里是简介</p> <p class="text-danger">¥499</p> </div> </div> </a> </div> </div> </div> </div> </div> <!--内容 END--> <!--脚部导航--> <footer id="footer"> <div class="container"> <div class="row"> <div class="col-xs-4"><a href="#" class="text-n">户首页页</a></div> <div class="col-xs-4"><a href="#">会员中心</a></div> <div class="col-xs-4"><a href="#">品牌介绍</a></div> </div> </div> </footer> <!--脚部导航 END--> </body> </html>
zzzxj-project-jackphonewebsote
trunk/OneTypePage.html
HTML
asf20
5,234
<!DOCTYPE html> <html lang="zh-CN"> <head> <title>产品详细页</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link href="css/bootstrap.min.css" rel="stylesheet" media="screen"> <link rel="stylesheet" href="css/common.css" /> </head> <body> <!--顶部栏目--> <header class="navbar navbar-inverse navbar-fixed-top bs-docs-nav" id="header"> <div class="container"> <div class="row"> <div id="backToPrevBtn" class="col-xs-2 text-while"> <a class="glyphicon glyphicon-circle-arrow-left" href="#"></a> </div> <div id="logo" class="col-xs-6 text-while"> <span>your logo</span> </div> <div id="btnUser" class="col-xs-2 text-while"> <a class="glyphicon glyphicon-user" href="User.html"></a> </div> <div id="btnShoppingCart" class="col-xs-2 text-while"> <a class="glyphicon glyphicon-shopping-cart" href="ShoppingCart.html"></a> </div> </div> </div> </header> <!--顶部栏目 END--> <!--内容--> <div class="wrapper"> <div class="banner" id="banner" style=""> <div id="carousel-example-generic" class="carousel slide" data-ride="carousel" style="height:100%;"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li> <li data-target="#carousel-example-generic" data-slide-to="1"></li> <li data-target="#carousel-example-generic" data-slide-to="2"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner"> <div class="item active"> <img src="img/1.jpg" alt="" /> <div class="carousel-caption"> </div> </div> <div class="item"> <img src="img/2.jpg" alt="" /> <div class="carousel-caption"> </div> </div> <div class="item"> <img src="img/3.jpg" alt="" /> <div class="carousel-caption"> </div> </div> </div> <!-- Controls --> <a class="left carousel-control" href="#carousel-example-generic" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></span> </a> <a class="right carousel-control" href="#carousel-example-generic" data-slide="next"> <span class="glyphicon glyphicon-chevron-right"></span> </a> </div> </div> <div class="container"> <div class="info" id="productInfo"> <div style="margin-top: 10px;"> <p>微购物JackJones杰克琼斯棉质男士休闲水洗牛仔长裤I|213232029</p> <p>现价: <strong class="text-danger">¥499.00</strong></p> <p class="text-muted">运费: 快递(EMS)¥12.0</p> </div> </div> <!--the selection for select product type, example color and size--> <div id="AttributeSelection" class="selection"> <div class="select-item row" data-select="color" data-selection="group"> <dl class="items clearfix"> <dt class="item title">颜色</dt> <dd class="item desc"> <ul class="no-list-bor list-prop clearfix"> <li><a href="#" data-selection="btn">Red</a></li> <li><a href="#" data-selection="btn">Red</a></li> <li><a href="#" data-selection="btn">Red</a></li> <li><a href="#" data-selection="btn">Red</a></li> <li><a href="#" data-selection="btn">Red</a></li> </ul> </dd> </dl> </div> <div class="select-item row" data-select="size" data-selection="group"> <dl class="items clearfix"> <dt class="item title">尺寸</dt> <dd class="item desc"> <ul class="no-list-bor list-prop clearfix"> <li><a href="#" data-selection="btn">170/76A(W29/L30</a></li> <li><a href="#" data-selection="btn">170/76A(W29/L30</a></li> <li><span>170/76A(W29/L30</span></li> <li><a href="#" data-selection="btn">170/76A(W29/L30</a></li> <li><a href="#" data-selection="btn">170/76A(W29/L30</a></li> </ul> </dd> </dl> </div> <div class="select-item row" data-select="count"> <dl class="items clearfix"> <dt class="item title">数量</dt> <dd class="item desc"> <div id="count" class="row"> <div class="fl"> <a id="btnMinus" class="btnCount"><i class="glyphicon glyphicon-minus"></i></a> </div> <input type="number" id="countVla" class="fl" value="1" /> <div class="fl"> <a id="btnPlus" class="btnCount"><i class="glyphicon glyphicon-plus"></i></a> </div> </div> </dd> </dl> </div> </div> <!--selection end--> <!-- Add to shoppingCart button --> <div class="" style="padding: 10px 0;"> <a href="#" class="btn btn-primary">加入购物车</a> <a href="#" class="btn btn-danger">立即购买</a> </div> <div class=""> <p>商品详情</p> <p> 潮流水洗 潮流感的水洗设计,尽显街头的牛仔范儿,让你在夏日中展现自己与众不同的品味。 </p> </div> </div> </div> <!--内容 END--> <!--脚部导航--> <footer id="footer"> <div class="container"> <div class="row"> <div class="col-xs-4"><a href="#" class="text-n">户首页页</a></div> <div class="col-xs-4"><a href="#">会员中心</a></div> <div class="col-xs-4"><a href="#">品牌介绍</a></div> </div> </div> </footer> <!--脚部导航 END--> </body> </html> <script src="js/jquery.v1.9.1.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/selection.js"></script> <script src="js/count.js"></script>
zzzxj-project-jackphonewebsote
trunk/ProductDetailPage.html
HTML
asf20
7,728
<!DOCTYPE html> <html> <head> <title>最新上架</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="css/bootstrap.min.css" rel="stylesheet" media="screen"> <link rel="stylesheet" href="css/common.css" /> <script src="js/jquery.v1.9.1.min.js"></script> <script src="js/bootstrap.min.js"></script> </head> <body> <!--顶部栏目--> <header class="navbar navbar-inverse navbar-fixed-top bs-docs-nav" id="header"> <div class="container"> <div class="row"> <div id="backToPrevBtn" class="col-xs-2 text-while"> <a class="glyphicon glyphicon-circle-arrow-left" href="#"></a> </div> <div id="logo" class="col-xs-6 text-while"> <span>your logo</span> </div> <div id="btnUser" class="col-xs-2 text-while"> <a class="glyphicon glyphicon-user" href="User.html"></a> </div> <div id="btnShoppingCart" class="col-xs-2 text-while"> <a class="glyphicon glyphicon-shopping-cart" href="ShoppingCart.html"></a> </div> </div> </div> </header> <!--顶部栏目 END--> <!--内容--> <div class="wrapper"> <div class="container"> <div class="norowpadding"> <div class="row newrelasesitem"> <a href="OneTypePage.html"> <div class="col-xs-8"> <img src="img/1.jpg" class="img-responsive" /> </div> <div class="col-xs-4"> <span>牛仔裤</span> </div> </a> </div> <div class="row newrelasesitem"> <a href="OneTypePage.html"> <div class="col-xs-8"> <img src="img/4.jpg" class="img-responsive" /> </div> <div class="col-xs-4"> <span>西装</span> </div> </a> </div> <div class="row newrelasesitem"> <a href="OneTypePage.html"> <div class="col-xs-8"> <img src="img/3.jpg" class="img-responsive" /> </div> <div class="col-xs-4"> <span>衬衫</span> </div> </a> </div> </div> </div> </div> <!--内容 END--> <!--脚部导航--> <footer id="footer"> <div class="container"> <div class="row"> <div class="col-xs-4"><a href="#" class="text-n">户首页页</a></div> <div class="col-xs-4"><a href="#">会员中心</a></div> <div class="col-xs-4"><a href="#">品牌介绍</a></div> </div> </div> </footer> <!--脚部导航 END--> </body> </html>
zzzxj-project-jackphonewebsote
trunk/NewRelases.html
HTML
asf20
3,286
<!DOCTYPE html> <html> <head> <title>购物车</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link href="css/bootstrap.min.css" rel="stylesheet" media="screen"> <link rel="stylesheet" href="css/common.css" /> <script src="js/jquery.v1.9.1.min.js"></script> <script src="js/bootstrap.min.js"></script> <style> .navbar-inverse li a { color: #FFF; } </style> </head> <body> <!--顶部栏目--> <header class="navbar navbar-inverse navbar-fixed-top bs-docs-nav" id="header"> <div class="container"> <div class="row"> <div id="backToPrevBtn" class="col-xs-2 text-while"> <a class="glyphicon glyphicon-circle-arrow-left" href="#"></a> </div> <div id="logo" class="col-xs-6 text-while"> <span>your logo</span> </div> <div id="btnUser" class="col-xs-2 text-while"> <a class="glyphicon glyphicon-user" href="User.html"></a> </div> <div id="btnShoppingCart" class="col-xs-2 text-while"> <a class="glyphicon glyphicon-shopping-cart" href="ShoppingCart.html"></a> </div> </div> </div> </header> <!--顶部栏目 END--> <!--内容--> <div class="wrapper"> <div class="container"> <!-- 一个列表中的详细事项 --> <div class="list-group" style="margin-top: 20px;"> <div class="list-group-item hasrowpadding"> <h4 class="list-group-item-heading"> <input type="checkbox" /> </h4> <div class="row"> <div class="col-xs-4"> <img src="img/1.jpg" class="img-responsive" /> </div> <div class="col-xs-8"> <p>微购物JackJones杰克琼斯棉质男士休闲水洗牛仔长裤I|213232029</p> </div> </div> <div class="clearfix group-footer"> <div class="col-xs-2"> <a href="#"><i class="glyphicon glyphicon-trash"></i></a> </div> <div class="col-xs-5"> <span>数量:</span> <input type="text" style="height: 20px; width: 40px;" /> </div> <div class="col-xs-5"> <span>共计:<strong class="text-danger">¥100</strong></span> </div> </div> <!--<div class="row" style="margin: 10px 0;"> <a class="btn btn-danger col-xs-6" href="#">删除</a> <div class="col-xs-4"> <span>数量</span> <input type="text" style="height:20px;width:40px;" /> </div> <div class="col-xs-2"> <span>共计:<strong class="text-danger">¥100</strong></span> </div> </div>--> </div> </div> <!-- 一个列表中的详细事项 end --> <!-- 支付方式 --> <div class="list-group" style="margin-top: 20px;"> <div class="list-group-item hasrowpadding"> <h4 class="list-group-item-heading">付款方式:在线支付</h4> <div class="row"> <div class="col-xs-4"> <input type="checkbox" style="vertical-align:-2px;" /> <span>全选</span> </div> <div class="col-xs-5"> <span>总价<strong class="text-danger">¥500</strong></span> </div> <div class="col-xs-3"> <a href="#" class="btn btn-danger">去结算</a> </div> </div> </div> </div> <!-- 支付方式 end --> </div> </div> <!--内容 END--> <!--脚部导航--> <footer id="footer"> <div class="container"> <div class="row"> <div class="col-xs-4"><a href="#" class="text-n">户首页页</a></div> <div class="col-xs-4"><a href="#">会员中心</a></div> <div class="col-xs-4"><a href="#">品牌介绍</a></div> </div> </div> </footer> <!--脚部导航 END--> </body> </html> <script> $(function () { $('#nava a').click(function (e) { e.preventDefault() $(this).tab('show') }) }) </script>
zzzxj-project-jackphonewebsote
trunk/ShoppingCart.html
HTML
asf20
5,204
<!DOCTYPE html> <html> <head> <title>收货地址管理</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link href="css/bootstrap.min.css" rel="stylesheet" media="screen"> <link rel="stylesheet" href="css/common.css" /> <script src="js/jquery.v1.9.1.min.js"></script> <script src="js/bootstrap.min.js"></script> <style> .navbar-inverse li a { color: #FFF; } </style> </head> <body> <!--顶部栏目--> <header class="navbar navbar-inverse navbar-fixed-top bs-docs-nav" id="header"> <div class="container"> <div class="row"> <div id="backToPrevBtn" class="col-xs-2 text-while"> <a class="glyphicon glyphicon-circle-arrow-left" href="#"></a> </div> <div id="logo" class="col-xs-6 text-while"> <span>your logo</span> </div> <div id="btnUser" class="col-xs-2 text-while"> <a class="glyphicon glyphicon-user" href="User.html"></a> </div> <div id="btnShoppingCart" class="col-xs-2 text-while"> <a class="glyphicon glyphicon-shopping-cart" href="ShoppingCart.html"></a> </div> </div> </div> </header> <!--顶部栏目 END--> <!--内容--> <div class="wrapper"> <div class="container"> <!-- 新增收货地址 按钮 --> <div style="margin:10px 0;"> <a class="btn btn-primary col-xs-12" href="#">新增收货地址</a> </div> <!-- 新增收货地址 按钮 end --> <!-- 一个列表中的详细事项 --> <div class="list-group"> <div class="list-group-item"> <p>姓名(13888888888)</p> <p>广东省广州市xxxxxxxx</p> <div class="row"> <a href="#" class="btn btn-default col-xs-6"><i class="glyphicon glyphicon-edit" style="margin-right:5px;"></i>修改</a> <a href="#" class="btn btn-default col-xs-6"><i class="glyphicon glyphicon-trash" style="margin-right:5px;"></i>删除</a> </div> </div> </div> <!-- 一个列表中的详细事项 end --> </div> </div> <!--内容 END--> <!--脚部导航--> <footer id="footer"> <div class="container"> <div class="row"> <div class="col-xs-4"><a href="#" class="text-n">户首页页</a></div> <div class="col-xs-4"><a href="#">会员中心</a></div> <div class="col-xs-4"><a href="#">品牌介绍</a></div> </div> </div> </footer> <!--脚部导航 END--> </body> </html> <script> $(function () { $('#nava a').click(function (e) { e.preventDefault() $(this).tab('show') }) }) </script>
zzzxj-project-jackphonewebsote
trunk/ShippingAdd.html
HTML
asf20
3,186
<!DOCTYPE html> <html lang="zh-CN"> <head> <title>全部商品</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link href="css/bootstrap.min.css" rel="stylesheet" media="screen"> <link rel="stylesheet" href="css/common.css" /> <script src="js/jquery.v1.9.1.min.js"></script> <script src="js/bootstrap.min.js"></script> </head> <body> <!--顶部栏目--> <header class="navbar navbar-inverse navbar-fixed-top bs-docs-nav" id="header"> <div class="container"> <div class="row"> <div id="backToPrevBtn" class="col-xs-2 text-while"> <a class="glyphicon glyphicon-circle-arrow-left" href="#"></a> </div> <div id="logo" class="col-xs-6 text-while"> <span>your logo</span> </div> <div id="btnUser" class="col-xs-2 text-while"> <a class="glyphicon glyphicon-user" href="User.html"></a> </div> <div id="btnShoppingCart" class="col-xs-2 text-while"> <a class="glyphicon glyphicon-shopping-cart" href="ShoppingCart.html"></a> </div> </div> </div> </header> <!--顶部栏目 END--> <!--内容--> <div class="wrapper"> <div class="container norowpadding"> <div class="row"> <!--在A标签中放相应的元素--> <div class="col-xs-6 col-md-6"><a href="OneTypePage.html"> <img src="img/1.jpg" class="img-responsive" alt="" /></a></div> <div class="col-xs-6 col-md-6"> <div class="colorpiece red"></div> </div> </div> <div class="row"> <div class="col-xs-6 col-md-6"> <div class="colorpiece red"></div> </div> <div class="col-xs-6 col-md-6"><a href="OneTypePage.html"> <img src="img/2.jpg" class="img-responsive" alt="" /></a></div> </div> <div class="row"> <div class="col-xs-6 col-md-6"><a href="OneTypePage.html"> <img src="img/3.jpg" class="img-responsive" alt="" /></a></div> <div class="col-xs-6 col-md-6"> <div class="colorpiece red"></div> </div> </div> <div class="row"> <div class="col-xs-6 col-md-6"> <div class="colorpiece red"></div> </div> <div class="col-xs-6 col-md-6"><a href="OneTypePage.html"> <img src="img/4.jpg" class="img-responsive" alt="" /></a></div> <!--在A标签中放相应的元素 END--> </div> </div> </div> <!--内容 END--> <!--脚部导航--> <footer id="footer"> <div class="container"> <div class="row"> <div class="col-xs-4"><a href="#" class="text-n">户首页页</a></div> <div class="col-xs-4"><a href="#">会员中心</a></div> <div class="col-xs-4"><a href="#">品牌介绍</a></div> </div> </div> </footer> <!--脚部导航 END--> </body> </html>
zzzxj-project-jackphonewebsote
trunk/AllProduct.html
HTML
asf20
3,464
body{ a:hover{ text-decoration: none; } #header{ padding:10px 10px; } .navbar{ .glyphicon{ font-size: 1.7em; } } .wrapper{ min-height: 300px; margin-top:50px; .group-footer{ margin-top: 10px; } .noMSG{ height: 500px; line-height: 500px; text-align: center; } .list-group-item-heading{ margin-bottom: 10px; border-bottom: 1px solid #EEE; padding-bottom: 5px; } .norowpadding{ .row{ [class^="col-"]{ padding:0px 0px!important; } } } .hasrowpadding{ .row{ [class^="col-"]{ padding:0px 15px!important; } } } .banner{ overflow-y: hidden; height: 200px; background-color: #333; } .container{ .selection{ .select-item{ dl{ dt{ word-break: keep-all; } } .items{ margin-left: 15px; margin-right: 15px; .item{ float:left; } .title{ min-width: 60px; width:14.66666%; } .desc{ max-width: 270px; width:82.33333% } } } } } .colorpiece{ height:100%; } .red{ background-color: red; } .newrelasesitem{ height:120px; overflow:hidden; margin-bottom: 5px; line-height: 120px; text-align: center; } .productlist{ margin-bottom: 10px; .list-item{ border:1px solid #DDD; // box-shadow: 1px 1px #DDD; margin:0px 10px 10px 10px; } } } #footer{ padding:10px 30px; border-top:1px solid #EEE; text-align: center; a{ color:#666; } } } .text-while{ color:#FFFFFF; a,span,i,label{ color:inherit; } } .no-list-bor{ padding-left: 0px; margin-left: 0px; list-style: none; } .list-prop{ li{ float:left; margin-bottom: 5px; margin-right: 5px; a,span{ padding:6px 4px; display: block; } a{ border:1px solid #EEE; color:#666; } span{ background-color: #DDD; border:1px solid #DDD; color:#AAA; } } .active{ a{ background-color: #b94a48; border-color: #b94a48; color:#FFF; } } .disable{ span{ background-color: #DDD; border-color: #DDD; color:#AAA; } } } .fl{ float:left; } .fr{ float:right; } #count{ .btnCount{ padding:8px 12px; border: 1px solid #EEE; display: inline-block; color:#666; } #btnPlus{ } input[type="number"]{ border:1px solid #EEE; padding:8px; width:60px; } #countVla{ } #btnMinus{ } } .p10{ padding:10px; }
zzzxj-project-jackphonewebsote
trunk/css/common.less
Less
asf20
3,036
body a:hover { text-decoration: none; } body #header { padding: 10px 10px; } body .navbar .glyphicon { font-size: 1.7em; } body .wrapper { min-height: 300px; margin-top: 50px; } body .wrapper .group-footer { margin-top: 10px; } body .wrapper .noMSG { height: 500px; line-height: 500px; text-align: center; } body .wrapper .list-group-item-heading { margin-bottom: 10px; border-bottom: 1px solid #EEE; padding-bottom: 5px; } body .wrapper .norowpadding .row [class^="col-"] { padding: 0px 0px!important; } body .wrapper .hasrowpadding .row [class^="col-"] { padding: 0px 15px!important; } body .wrapper .banner { overflow-y: hidden; height: 200px; background-color: #333; } body .wrapper .container .selection .select-item dl dt { word-break: keep-all; } body .wrapper .container .selection .select-item .items { margin-left: 15px; margin-right: 15px; } body .wrapper .container .selection .select-item .items .item { float: left; } body .wrapper .container .selection .select-item .items .title { min-width: 60px; width: 14.66666%; } body .wrapper .container .selection .select-item .items .desc { max-width: 270px; width: 82.33333%; } body .wrapper .colorpiece { height: 100%; } body .wrapper .red { background-color: red; } body .wrapper .newrelasesitem { height: 120px; overflow: hidden; margin-bottom: 5px; line-height: 120px; text-align: center; } body .wrapper .productlist { margin-bottom: 10px; } body .wrapper .productlist .list-item { border: 1px solid #DDD; margin: 0px 10px 10px 10px; } body #footer { padding: 10px 30px; border-top: 1px solid #EEE; text-align: center; } body #footer a { color: #666; } .text-while { color: #FFFFFF; } .text-while a, .text-while span, .text-while i, .text-while label { color: inherit; } .no-list-bor { padding-left: 0px; margin-left: 0px; list-style: none; } .list-prop li { float: left; margin-bottom: 5px; margin-right: 5px; } .list-prop li a, .list-prop li span { padding: 6px 4px; display: block; } .list-prop li a { border: 1px solid #EEE; color: #666; } .list-prop li span { background-color: #DDD; border: 1px solid #DDD; color: #AAA; } .list-prop .active a { background-color: #b94a48; border-color: #b94a48; color: #FFF; } .list-prop .disable span { background-color: #DDD; border-color: #DDD; color: #AAA; } .fl { float: left; } .fr { float: right; } #count .btnCount { padding: 8px 12px; border: 1px solid #EEE; display: inline-block; color: #666; } #count input[type="number"] { border: 1px solid #EEE; padding: 8px; width: 60px; } .p10 { padding: 10px; }
zzzxj-project-jackphonewebsote
trunk/css/common.css
CSS
asf20
2,655
/* * Copyright 2012 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; /** * Indicates that {@link OtpSource} failed to performed the requested operation. * * @author klyubin@google.com (Alex Klyubin) */ public class OtpSourceException extends Exception { public OtpSourceException(String message) { super(message); } public OtpSourceException(String message, Throwable cause) { super(message, cause); } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/OtpSourceException.java
Java
asf20
1,021
/* * Copyright 2012 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import android.os.Handler; import java.util.concurrent.Executor; /** * {@link Executor} that invokes {@link Runnable} instances on the thread on which it was created. * The assumption is that the thread has a {@link android.os.Looper} associated with it. * * @author klyubin@google.com (Alex Klyubin) */ public class RunOnThisLooperThreadExecutor implements Executor { private final Handler mHandler = new Handler(); @Override public void execute(Runnable command) { if (Thread.currentThread() == mHandler.getLooper().getThread()) { // The calling thread is the target thread of the Handler -- invoke immediately, blocking // the calling thread. command.run(); } else { // The calling thread is not the same as the thread with which the Handler is associated -- // post to the Handler for later execution. mHandler.post(command); } } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/RunOnThisLooperThreadExecutor.java
Java
asf20
1,566
/* * Copyright 2012 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.timesync; import com.google.android.apps.authenticator.testability.DependencyInjector; import com.google.android.apps.authenticator2.R; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.Bundle; /** * Activity that adjusts the application's internal system time offset (for the purposes of * computing TOTP verification codes) by making a network request to Google and comparing Google's * time to the device's time. * * @author klyubin@google.com (Alex Klyubin) */ public class SyncNowActivity extends Activity implements SyncNowController.Presenter { // IMPLEMENTATION NOTE: This class implements a Passive View pattern. All state and business logic // are kept in the Controller which pushes the relevant state into this Activity. This helps with // testing the business logic and also with preserving state across the creation/destruction of // Activity instances due to screen orientation changes. Activity instances being destroyed // detach from the controller, and new instances being created attach to the controller. Once an // instance has attached, the controller will set up the Activity into the correct state and will // continue pushing state changes into the Activity until it detaches. private SyncNowController mController; private Dialog mProgressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getLastNonConfigurationInstance() != null) { mController = (SyncNowController) getLastNonConfigurationInstance(); } else { mController = new SyncNowController( DependencyInjector.getTotpClock(), new NetworkTimeProvider(DependencyInjector.getHttpClient())); } mController.attach(this); } @Override protected void onStop() { if (isFinishing()) { mController.detach(this); } super.onStop(); } @Override public Object onRetainNonConfigurationInstance() { return mController; } @Override public void onBackPressed() { mController.abort(this); } // --------- SyncNowController.Presenter interface implementation ------ @Override public void onStarted() { if (isFinishing()) { // Ignore this callback if this Activity is already finishing or is already finished return; } showInProgressDialog(); } @Override public void onDone(SyncNowController.Result result) { if (isFinishing()) { // Ignore this callback if this Activity is already finishing or is already finished return; } dismissInProgressDialog(); switch (result) { case TIME_ALREADY_CORRECT: new AlertDialog.Builder(this) .setCancelable(false) .setTitle(R.string.timesync_sync_now_time_already_correct_dialog_title) .setMessage(R.string.timesync_sync_now_time_already_correct_dialog_details) .setIcon(android.R.drawable.ic_dialog_info) .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }) .create() .show(); break; case TIME_CORRECTED: new AlertDialog.Builder(this) .setCancelable(false) .setTitle(R.string.timesync_sync_now_time_corrected_dialog_title) .setMessage(R.string.timesync_sync_now_time_corrected_dialog_details) .setIcon(android.R.drawable.ic_dialog_info) .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }) .create() .show(); break; case ERROR_CONNECTIVITY_ISSUE: new AlertDialog.Builder(this) .setCancelable(false) .setTitle(R.string.timesync_sync_now_connectivity_error_dialog_title) .setMessage(R.string.timesync_sync_now_connectivity_error_dialog_details) .setIcon(android.R.drawable.ic_dialog_alert) .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }) .create() .show(); break; case CANCELLED_BY_USER: finish(); break; default: throw new IllegalArgumentException(String.valueOf(result)); } } // --------- SyncNowController.Presenter interface implementation END ------ private void showInProgressDialog() { mProgressDialog = ProgressDialog.show( this, getString(R.string.timesync_sync_now_progress_dialog_title), getString(R.string.timesync_sync_now_progress_dialog_details), true, true); mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { mController.abort(SyncNowActivity.this); } }); } /** * Dismisses the progress dialog. Does nothing if the dialog has not been or no longer is * displayed. * * @see #showInProgressDialog() */ private void dismissInProgressDialog() { if (mProgressDialog != null) { mProgressDialog.dismiss(); mProgressDialog = null; } } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/timesync/SyncNowActivity.java
Java
asf20
6,292
/* * Copyright 2012 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.timesync; import com.google.android.apps.authenticator.RunOnThisLooperThreadExecutor; import com.google.android.apps.authenticator.TotpClock; import com.google.android.apps.authenticator.Utilities; import android.os.Handler; import android.util.Log; import java.io.IOException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Controller of the {@link SyncNowActivity}. As soon as started, the controller attempts to * obtain the network time using a {@link NetworkTimeProvider}, then computes the offset between * the device's system time and the network time and updates {@link TotpClock} to use that as * its time correction value. * * @author klyubin@google.com (Alex Klyubin) */ class SyncNowController { enum Result { TIME_CORRECTED, TIME_ALREADY_CORRECT, CANCELLED_BY_USER, ERROR_CONNECTIVITY_ISSUE, } /** Presentation layer. */ interface Presenter { /** Invoked when the controller starts up. */ void onStarted(); /** Invoked when the controller is finished. */ void onDone(Result result); } private enum State { NOT_STARTED, IN_PROGRESS, DONE, } private static final String LOG_TAG = "TimeSync"; private final TotpClock mTotpClock; private final NetworkTimeProvider mNetworkTimeProvider; private final Executor mBackgroundExecutor; private final Executor mCallbackFromBackgroundExecutor; private final boolean mBackgroundExecutorServiceOwnedByThisController; private Presenter mPresenter; private State mState = State.NOT_STARTED; private Result mResult; // @VisibleForTesting SyncNowController( TotpClock totpClock, NetworkTimeProvider networkTimeProvider, Executor backgroundExecutor, boolean backgroundExecutorServiceOwnedByThisController, Executor callbackFromBackgroundExecutor) { mTotpClock = totpClock; mNetworkTimeProvider = networkTimeProvider; mBackgroundExecutor = backgroundExecutor; mBackgroundExecutorServiceOwnedByThisController = backgroundExecutorServiceOwnedByThisController; mCallbackFromBackgroundExecutor = callbackFromBackgroundExecutor; } SyncNowController(TotpClock totpClock, NetworkTimeProvider networkTimeProvider) { this( totpClock, networkTimeProvider, Executors.newSingleThreadExecutor(), true, new RunOnThisLooperThreadExecutor()); } /** * Attaches the provided presentation layer to this controller. The previously attached * presentation layer (if any) stops receiving events from this controller. */ void attach(Presenter presenter) { mPresenter = presenter; switch (mState) { case NOT_STARTED: start(); break; case IN_PROGRESS: if (mPresenter != null) { mPresenter.onStarted(); } break; case DONE: if (mPresenter != null) { mPresenter.onDone(mResult); } break; default: throw new IllegalStateException(String.valueOf(mState)); } } /** * Detaches the provided presentation layer from this controller. Does nothing if the presentation * layer is not the same as the layer currently attached to the controller. */ void detach(Presenter presenter) { if (presenter != mPresenter) { return; } switch (mState) { case NOT_STARTED: case IN_PROGRESS: onCancelledByUser(); break; case DONE: break; default: throw new IllegalStateException(String.valueOf(mState)); } } /** * Requests that this controller abort its operation. Does nothing if the provided presentation * layer is not the same as the layer attached to this controller. */ void abort(Presenter presenter) { if (mPresenter != presenter) { return; } onCancelledByUser(); } /** * Starts this controller's operation (initiates a Time Sync). */ private void start() { mState = State.IN_PROGRESS; if (mPresenter != null) { mPresenter.onStarted(); } // Avoid blocking this thread on the Time Sync operation by invoking it on a different thread // (provided by the Executor) and posting the results back to this thread. mBackgroundExecutor.execute(new Runnable() { @Override public void run() { runBackgroundSyncAndPostResult(mCallbackFromBackgroundExecutor); } }); } private void onCancelledByUser() { finish(Result.CANCELLED_BY_USER); } /** * Invoked when the time correction value was successfully obtained from the network time * provider. * * @param timeCorrectionMinutes number of minutes by which this device is behind the correct time. */ private void onNewTimeCorrectionObtained(int timeCorrectionMinutes) { if (mState != State.IN_PROGRESS) { // Don't apply the new time correction if this controller is not waiting for this. // This callback may be invoked after the Time Sync operation has been cancelled or stopped // prematurely. return; } long oldTimeCorrectionMinutes = mTotpClock.getTimeCorrectionMinutes(); Log.i(LOG_TAG, "Obtained new time correction: " + timeCorrectionMinutes + " min, old time correction: " + oldTimeCorrectionMinutes + " min"); if (timeCorrectionMinutes == oldTimeCorrectionMinutes) { finish(Result.TIME_ALREADY_CORRECT); } else { mTotpClock.setTimeCorrectionMinutes(timeCorrectionMinutes); finish(Result.TIME_CORRECTED); } } /** * Terminates this controller's operation with the provided result/outcome. */ private void finish(Result result) { if (mState == State.DONE) { // Not permitted to change state when already DONE return; } if (mBackgroundExecutorServiceOwnedByThisController) { ((ExecutorService) mBackgroundExecutor).shutdownNow(); } mState = State.DONE; mResult = result; if (mPresenter != null) { mPresenter.onDone(result); } } /** * Obtains the time correction value (<b>may block for a while</b>) and posts the result/error * using the provided {@link Handler}. */ private void runBackgroundSyncAndPostResult(Executor callbackExecutor) { long networkTimeMillis; try { networkTimeMillis = mNetworkTimeProvider.getNetworkTime(); } catch (IOException e) { Log.w(LOG_TAG, "Failed to obtain network time due to connectivity issues"); callbackExecutor.execute(new Runnable() { @Override public void run() { finish(Result.ERROR_CONNECTIVITY_ISSUE); } }); return; } long timeCorrectionMillis = networkTimeMillis - System.currentTimeMillis(); final int timeCorrectionMinutes = (int) Math.round( ((double) timeCorrectionMillis) / Utilities.MINUTE_IN_MILLIS); callbackExecutor.execute(new Runnable() { @Override public void run() { onNewTimeCorrectionObtained(timeCorrectionMinutes); } }); } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/timesync/SyncNowController.java
Java
asf20
7,754
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.timesync; import com.google.android.apps.authenticator.testability.TestablePreferenceActivity; import com.google.android.apps.authenticator2.R; import android.os.Bundle; /** * Activity that displays the "Time correction" preferences. * * @author klyubin@google.com (Alex Klyubin) */ public class SettingsTimeCorrectionActivity extends TestablePreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences_time_correction); } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/timesync/SettingsTimeCorrectionActivity.java
Java
asf20
1,216
/* * Copyright 2012 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.timesync; import android.util.Log; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpHead; import org.apache.http.impl.cookie.DateParseException; import org.apache.http.impl.cookie.DateUtils; import java.io.IOException; import java.util.Date; /** * Provider of network time that obtains the time by making a network request to Google. * * @author klyubin@google.com (Alex Klyubin) */ public class NetworkTimeProvider { private static final String LOG_TAG = NetworkTimeProvider.class.getSimpleName(); private static final String URL = "https://www.google.com"; private final HttpClient mHttpClient; public NetworkTimeProvider(HttpClient httpClient) { mHttpClient = httpClient; } /** * Gets the system time by issuing a request over the network. * * @return time (milliseconds since epoch). * * @throws IOException if an I/O error occurs. */ public long getNetworkTime() throws IOException { HttpHead request = new HttpHead(URL); Log.i(LOG_TAG, "Sending request to " + request.getURI()); HttpResponse httpResponse; try { httpResponse = mHttpClient.execute(request); } catch (ClientProtocolException e) { throw new IOException(String.valueOf(e)); } catch (IOException e) { throw new IOException("Failed due to connectivity issues: " + e); } try { Header dateHeader = httpResponse.getLastHeader("Date"); Log.i(LOG_TAG, "Received response with Date header: " + dateHeader); if (dateHeader == null) { throw new IOException("No Date header in response"); } String dateHeaderValue = dateHeader.getValue(); try { Date networkDate = DateUtils.parseDate(dateHeaderValue); return networkDate.getTime(); } catch (DateParseException e) { throw new IOException( "Invalid Date header format in response: \"" + dateHeaderValue + "\""); } } finally { // Consume all of the content of the response to facilitate HTTP 1.1 persistent connection // reuse and to avoid running out of connections when this methods is scheduled on different // threads. try { HttpEntity responseEntity = httpResponse.getEntity(); if (responseEntity != null) { responseEntity.consumeContent(); } } catch (IOException e) { // Ignored because this is not an error that is relevant to clients of this transport. } } } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/timesync/NetworkTimeProvider.java
Java
asf20
3,309
/* * Copyright 2012 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.timesync; import com.google.android.apps.authenticator.wizard.WizardPageActivity; import com.google.android.apps.authenticator2.R; import android.os.Bundle; import java.io.Serializable; /** * Activity that displays more information about the Time Correction/Sync feature. * * @author klyubin@google.com (Alex Klyubin) */ public class AboutActivity extends WizardPageActivity<Serializable> { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setPageContentView(R.layout.timesync_about); setTextViewHtmlFromResource(R.id.details, R.string.timesync_about_feature_screen_details); setButtonBarModeMiddleButtonOnly(); mMiddleButton.setText(R.string.ok); } @Override protected void onMiddleButtonPressed() { onBackPressed(); } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/timesync/AboutActivity.java
Java
asf20
1,483
/* * Copyright 2009 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import java.util.HashMap; import java.util.Locale; /** * Encodes arbitrary byte arrays as case-insensitive base-32 strings. * <p> * The implementation is slightly different than in RFC 4648. During encoding, * padding is not added, and during decoding the last incomplete chunk is not * taken into account. The result is that multiple strings decode to the same * byte array, for example, string of sixteen 7s ("7...7") and seventeen 7s both * decode to the same byte array. * TODO(sarvar): Revisit this encoding and whether this ambiguity needs fixing. * * @author sweis@google.com (Steve Weis) * @author Neal Gafter */ public class Base32String { // singleton private static final Base32String INSTANCE = new Base32String("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"); // RFC 4648/3548 static Base32String getInstance() { return INSTANCE; } // 32 alpha-numeric characters. private String ALPHABET; private char[] DIGITS; private int MASK; private int SHIFT; private HashMap<Character, Integer> CHAR_MAP; static final String SEPARATOR = "-"; protected Base32String(String alphabet) { this.ALPHABET = alphabet; DIGITS = ALPHABET.toCharArray(); MASK = DIGITS.length - 1; SHIFT = Integer.numberOfTrailingZeros(DIGITS.length); CHAR_MAP = new HashMap<Character, Integer>(); for (int i = 0; i < DIGITS.length; i++) { CHAR_MAP.put(DIGITS[i], i); } } public static byte[] decode(String encoded) throws DecodingException { return getInstance().decodeInternal(encoded); } protected byte[] decodeInternal(String encoded) throws DecodingException { // Remove whitespace and separators encoded = encoded.trim().replaceAll(SEPARATOR, "").replaceAll(" ", ""); // Remove padding. Note: the padding is used as hint to determine how many // bits to decode from the last incomplete chunk (which is commented out // below, so this may have been wrong to start with). encoded = encoded.replaceFirst("[=]*$", ""); // Canonicalize to all upper case encoded = encoded.toUpperCase(Locale.US); if (encoded.length() == 0) { return new byte[0]; } int encodedLength = encoded.length(); int outLength = encodedLength * SHIFT / 8; byte[] result = new byte[outLength]; int buffer = 0; int next = 0; int bitsLeft = 0; for (char c : encoded.toCharArray()) { if (!CHAR_MAP.containsKey(c)) { throw new DecodingException("Illegal character: " + c); } buffer <<= SHIFT; buffer |= CHAR_MAP.get(c) & MASK; bitsLeft += SHIFT; if (bitsLeft >= 8) { result[next++] = (byte) (buffer >> (bitsLeft - 8)); bitsLeft -= 8; } } // We'll ignore leftover bits for now. // // if (next != outLength || bitsLeft >= SHIFT) { // throw new DecodingException("Bits left: " + bitsLeft); // } return result; } public static String encode(byte[] data) { return getInstance().encodeInternal(data); } protected String encodeInternal(byte[] data) { if (data.length == 0) { return ""; } // SHIFT is the number of bits per output character, so the length of the // output is the length of the input multiplied by 8/SHIFT, rounded up. if (data.length >= (1 << 28)) { // The computation below will fail, so don't do it. throw new IllegalArgumentException(); } int outputLength = (data.length * 8 + SHIFT - 1) / SHIFT; StringBuilder result = new StringBuilder(outputLength); int buffer = data[0]; int next = 1; int bitsLeft = 8; while (bitsLeft > 0 || next < data.length) { if (bitsLeft < SHIFT) { if (next < data.length) { buffer <<= 8; buffer |= (data[next++] & 0xff); bitsLeft += 8; } else { int pad = SHIFT - bitsLeft; buffer <<= pad; bitsLeft += pad; } } int index = MASK & (buffer >> (bitsLeft - SHIFT)); bitsLeft -= SHIFT; result.append(DIGITS[index]); } return result.toString(); } @Override // enforce that this class is a singleton public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } public static class DecodingException extends Exception { public DecodingException(String message) { super(message); } } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/Base32String.java
Java
asf20
5,058
/* * Copyright 2012 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; /** * Indicates that {@link OtpSource} failed to generate an OTP because OTP generation is not * permitted for the specified account. * * @author klyubin@google.com (Alex Klyubin) */ public class OtpGenerationNotPermittedException extends OtpSourceException { public OtpGenerationNotPermittedException(String message) { super(message); } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/OtpGenerationNotPermittedException.java
Java
asf20
1,018
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; /** * {@link OptionalFeatures} implementation used in Market builds. * * @author klyubin@google.com (Alex Klyubin) */ public class MarketBuildOptionalFeatures implements OptionalFeatures { @Override public void onAuthenticatorActivityCreated(AuthenticatorActivity activity) {} @Override public void onAuthenticatorActivityAccountSaved(Context context, String account) {} @Override public boolean interpretScanResult(Context context, Uri scanResult) { return false; } @Override public void onDataImportedFromOldApp(Context context) {} @Override public SharedPreferences getSharedPreferencesForDataImportFromOldApp(Context context) { return null; } @Override public String appendDataImportLearnMoreLink(Context context, String text) { return text; } @Override public OtpSource createOtpSource(AccountDb accountDb, TotpClock totpClock) { return new OtpProvider(accountDb, totpClock); } @Override public void onAuthenticatorActivityGetNextOtpFailed( AuthenticatorActivity activity, String accountName, OtpSourceException exception) { throw new RuntimeException("Failed to generate OTP for account", exception); } @Override public Dialog onAuthenticatorActivityCreateDialog(AuthenticatorActivity activity, int id) { return null; } @Override public void onAuthenticatorActivityAddAccount(AuthenticatorActivity activity) { activity.startActivity(new Intent(activity, AddOtherAccountActivity.class)); } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/MarketBuildOptionalFeatures.java
Java
asf20
2,321
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import android.app.Dialog; import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; /** * Interface for providing functionality not available in Market builds without having to modify * the codebase shared between the Market and non-Market builds. * * @author klyubin@google.com (Alex Klyubin) */ public interface OptionalFeatures { /** * Invoked when the {@link AuthenticatorActivity} {@code onCreate} is almost done. */ void onAuthenticatorActivityCreated(AuthenticatorActivity activity); /** * Invoked when the {@link AuthenticatorActivity} saves an account/seed. */ void onAuthenticatorActivityAccountSaved(Context context, String account); /** * Creates the {@link OtpSource} instance used for OTP generation by the app. */ OtpSource createOtpSource(AccountDb accountDb, TotpClock totpClock); /** * Invoked when a HOTP OTP could not be generated by {@link AuthenticatorActivity} * for the provided account. */ void onAuthenticatorActivityGetNextOtpFailed( AuthenticatorActivity activity, String accountName, OtpSourceException exception); /** * Invoked by {@link AuthenticatorActivity#onCreateDialog(int)} for dialog IDs not directly * handled by the {@link AuthenticatorActivity} class. * * @return dialog or {@code null} for the default behavior. */ Dialog onAuthenticatorActivityCreateDialog(AuthenticatorActivity activity, int id); /** * Invoked when {@link AuthenticatorActivity} was asked to initiate the Add Account flow. */ void onAuthenticatorActivityAddAccount(AuthenticatorActivity activity); /** * Invoked when a URI has been scanned. * * @return {@code true} if the URI has been consumed by these optional features, {@code false} * otherwise. */ boolean interpretScanResult(Context context, Uri scanResult); /** * Invoked when data have been successfully imported from the old Authenticator app. */ void onDataImportedFromOldApp(Context context); /** * Gets the {@link SharedPreferences} into which to import preferences from the old Authenticator * app. * * @return preferences or {@code null} to skip the importing of preferences. */ SharedPreferences getSharedPreferencesForDataImportFromOldApp(Context context); /** * Appends the Learn more link to data import dialog text. * * @return text with the link. */ String appendDataImportLearnMoreLink(Context context, String text); }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/OptionalFeatures.java
Java
asf20
3,174
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; /** * Simple static methods to be called at the start of your own methods to verify correct arguments * and state. Inspired by Guava. * * @author klyubin@google.com (Alex Klyubin) */ public final class Preconditions { /** Hidden to avoid instantiation. */ private Preconditions() {} /** * Ensures that an object reference passed as a parameter to the calling method is not * {@code null}. * * @return non-{@code null} reference that was validated. * * @throws NullPointerException if {@code reference} is {@code null}. */ public static <T> T checkNotNull(T reference) { if (reference == null) { throw new NullPointerException(); } return reference; } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * @throws IllegalArgumentException if {@code expression} is {@code false}. */ public static void checkArgument(boolean expression) { if (!expression) { throw new IllegalArgumentException(); } } /** * Ensures the truth of an expression involving the state of the calling * instance, but not involving any parameters to the calling method. * * @throws IllegalStateException if {@code expression} is false */ public static void checkState(boolean expression) { if (!expression) { throw new IllegalStateException(); } } /** * Ensures the truth of an expression involving the state of the calling * instance, but not involving any parameters to the calling method. * * @param errorMessage the exception message to use if the check fails; will * be converted to a string using {@link String#valueOf(Object)} * @throws IllegalStateException if {@code expression} is false */ public static void checkState( boolean expression, Object errorMessage) { if (!expression) { throw new IllegalStateException(String.valueOf(errorMessage)); } } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/Preconditions.java
Java
asf20
2,625
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import com.google.android.apps.authenticator.testability.TestablePreferenceActivity; import com.google.android.apps.authenticator2.R; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; /** * Activity that displays the "About" preferences. * * @author klyubin@google.com (Alex Klyubin) */ public class SettingsAboutActivity extends TestablePreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences_about); String packageVersion = ""; try { packageVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName; } catch (NameNotFoundException e) {} findPreference("version").setSummary(packageVersion); } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/SettingsAboutActivity.java
Java
asf20
1,476
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import java.io.IOException; /** * A class for handling file system related methods, such as setting permissions. * * @author sarvar@google.com (Sarvar Patel) */ public class FileUtilities { /** Hidden constructor to prevent instantiation. */ private FileUtilities() { } /** * Restricts the file permissions of the provided path so that only the owner (UID) * can access it. */ public static void restrictAccessToOwnerOnly(String path) throws IOException { // IMPLEMENTATION NOTE: The code below simply invokes the hidden API // android.os.FileUtils.setPermissions(path, 0700, -1, -1) via Reflection. int errorCode; try { errorCode = (Integer) Class.forName("android.os.FileUtils") .getMethod("setPermissions", String.class, int.class, int.class, int.class) .invoke(null, path, 0700, -1, -1); } catch (Exception e) { // Can't chain exception because IOException doesn't have the right constructor on Froyo // and below throw new IOException("Failed to set permissions: " + e); } if (errorCode != 0) { throw new IOException("FileUtils.setPermissions failed with error code " + errorCode); } } /* * Uses reflection to call android.os.FileUtils.getFileStatus(path) which returns FileStatus. */ public static StatStruct getStat(String path) throws IOException { boolean success; try { Object obj = Class.forName("android.os.FileUtils$FileStatus").newInstance(); success = (Boolean) Class.forName("android.os.FileUtils") .getMethod("getFileStatus", String.class, Class.forName("android.os.FileUtils$FileStatus")) .invoke(null, path, obj); if (success) { StatStruct stat = new StatStruct(); stat.dev = getFileStatusInt(obj, "dev"); stat.ino = getFileStatusInt(obj, "ino"); stat.mode = getFileStatusInt(obj, "mode"); stat.nlink = getFileStatusInt(obj, "nlink"); stat.uid = getFileStatusInt(obj, "uid"); stat.gid = getFileStatusInt(obj, "gid"); stat.rdev = getFileStatusInt(obj, "rdev"); stat.size = getFileStatusLong(obj, "size"); stat.blksize = getFileStatusInt(obj, "blksize"); stat.blocks = getFileStatusLong(obj, "blocks"); stat.atime = getFileStatusLong(obj, "atime"); stat.mtime = getFileStatusLong(obj, "mtime"); stat.ctime = getFileStatusLong(obj, "ctime"); return stat; } else { throw new IOException("FileUtils.getFileStatus returned with failure."); } } catch (Exception e) { // Can't chain exception because IOException doesn't have the right constructor on Froyo // and below throw new IOException("Failed to get FileStatus: " + e); } } private static int getFileStatusInt(Object obj, String field) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, ClassNotFoundException { return Class.forName("android.os.FileUtils$FileStatus").getField(field).getInt(obj); } private static long getFileStatusLong(Object obj, String field) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, ClassNotFoundException { return Class.forName("android.os.FileUtils$FileStatus").getField(field).getLong(obj); } public static class StatStruct { public int dev; public int ino; public int mode; public int nlink; public int uid; public int gid; public int rdev; public long size; public int blksize; public long blocks; public long atime; public long mtime; public long ctime; @Override public String toString() { return new String(String.format("StatStruct{ dev: %d, ino: %d, mode: %o (octal), nlink: %d, " + "uid: %d, gid: %d, rdev: %d, size: %d, blksize: %d, blocks: %d, atime: %d, mtime: %d, " + "ctime: %d }\n", dev, ino, mode, nlink, uid, gid, rdev, size, blksize, blocks, atime, mtime, ctime)); } } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/FileUtilities.java
Java
asf20
4,697
/* * Copyright 2012 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; /** * Hexadecimal encoding where each byte is represented by two hexadecimal digits. * * @author klyubin@google.com (Alex Klyubin) */ public class HexEncoding { /** Hidden constructor to prevent instantiation. */ private HexEncoding() {} private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray(); /** * Encodes the provided data as a hexadecimal string. */ public static String encode(byte[] data) { StringBuilder result = new StringBuilder(data.length * 2); for (byte b : data) { result.append(HEX_DIGITS[(b >>> 4) & 0x0f]); result.append(HEX_DIGITS[b & 0x0f]); } return result.toString(); } /** * Decodes the provided hexadecimal string into an array of bytes. */ public static byte[] decode(String encoded) { // IMPLEMENTATION NOTE: Special care is taken to permit odd number of hexadecimal digits. int resultLengthBytes = (encoded.length() + 1) / 2; byte[] result = new byte[resultLengthBytes]; int resultOffset = 0; int encodedCharOffset = 0; if ((encoded.length() % 2) != 0) { // Odd number of digits -- the first digit is the lower 4 bits of the first result byte. result[resultOffset++] = (byte) getHexadecimalDigitValue(encoded.charAt(encodedCharOffset)); encodedCharOffset++; } for (int len = encoded.length(); encodedCharOffset < len; encodedCharOffset += 2) { result[resultOffset++] = (byte) ((getHexadecimalDigitValue(encoded.charAt(encodedCharOffset)) << 4) | getHexadecimalDigitValue(encoded.charAt(encodedCharOffset + 1))); } return result; } private static int getHexadecimalDigitValue(char c) { if ((c >= 'a') && (c <= 'f')) { return (c - 'a') + 0x0a; } else if ((c >= 'A') && (c <= 'F')) { return (c - 'A') + 0x0a; } else if ((c >= '0') && (c <= '9')) { return c - '0'; } else { throw new IllegalArgumentException( "Invalid hexadecimal digit at position : '" + c + "' (0x" + Integer.toHexString(c) + ")"); } } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/HexEncoding.java
Java
asf20
2,721
/* * Copyright 2010 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import com.google.android.apps.authenticator2.R; import android.content.Context; import android.util.AttributeSet; import android.view.accessibility.AccessibilityEvent; import android.widget.LinearLayout; import android.widget.TextView; /** * Custom view that shows the user, pin, and "Get New Code" button (if enabled). * The layout for this is under res/layout/user_row.xml * For better accessibility, we have created this custom class to generate * accessibility events that are better suited for this widget. * * @author clchen@google.com (Charles L. Chen) */ public class UserRowView extends LinearLayout { public UserRowView(Context context) { super(context); } public UserRowView(Context context, AttributeSet attrset) { super(context, attrset); } @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent accessEvent) { Context ctx = this.getContext(); String message = ""; CharSequence pinText = ((TextView) findViewById(R.id.pin_value)).getText(); if (ctx.getString(R.string.empty_pin).equals(pinText)){ message = ctx.getString(R.string.counter_pin); } else { for (int i = 0; i < pinText.length(); i++) { message = message + pinText.charAt(i) + " "; } } CharSequence userText = ((TextView) findViewById(R.id.current_user)).getText(); message = message + " " + userText; accessEvent.setClassName(getClass().getName()); accessEvent.setPackageName(ctx.getPackageName()); accessEvent.getText().add(message); return true; } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/UserRowView.java
Java
asf20
2,237
/* * Copyright 2009 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import com.google.android.apps.authenticator.AccountDb.OtpType; import com.google.android.apps.authenticator.Base32String.DecodingException; import com.google.android.apps.authenticator.wizard.WizardPageActivity; import com.google.android.apps.authenticator2.R; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import java.io.Serializable; /** * The activity that lets the user manually add an account by entering its name, key, and type * (TOTP/HOTP). * * @author sweis@google.com (Steve Weis) */ public class EnterKeyActivity extends WizardPageActivity<Serializable> implements TextWatcher { private static final int MIN_KEY_BYTES = 10; private EditText mKeyEntryField; private EditText mAccountName; private Spinner mType; /** * Called when the activity is first created */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setPageContentView(R.layout.enter_key); // Find all the views on the page mKeyEntryField = (EditText) findViewById(R.id.key_value); mAccountName = (EditText) findViewById(R.id.account_name); mType = (Spinner) findViewById(R.id.type_choice); ArrayAdapter<CharSequence> types = ArrayAdapter.createFromResource(this, R.array.type, android.R.layout.simple_spinner_item); types.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mType.setAdapter(types); // Set listeners mKeyEntryField.addTextChangedListener(this); mRightButton.setText(R.string.enter_key_page_add_button); } /* * Return key entered by user, replacing visually similar characters 1 and 0. */ private String getEnteredKey() { String enteredKey = mKeyEntryField.getText().toString(); return enteredKey.replace('1', 'I').replace('0', 'O'); } /* * Verify that the input field contains a valid base32 string, * and meets minimum key requirements. */ private boolean validateKeyAndUpdateStatus(boolean submitting) { String userEnteredKey = getEnteredKey(); try { byte[] decoded = Base32String.decode(userEnteredKey); if (decoded.length < MIN_KEY_BYTES) { // If the user is trying to submit a key that's too short, then // display a message saying it's too short. mKeyEntryField.setError(submitting ? getString(R.string.enter_key_too_short) : null); return false; } else { mKeyEntryField.setError(null); return true; } } catch (DecodingException e) { mKeyEntryField.setError(getString(R.string.enter_key_illegal_char)); return false; } } @Override protected void onRightButtonPressed() { // TODO(cemp): This depends on the OtpType enumeration to correspond // to array indices for the dropdown with different OTP modes. OtpType mode = mType.getSelectedItemPosition() == OtpType.TOTP.value ? OtpType.TOTP : OtpType.HOTP; if (validateKeyAndUpdateStatus(true)) { AuthenticatorActivity.saveSecret(this, mAccountName.getText().toString(), getEnteredKey(), null, mode, AccountDb.DEFAULT_HOTP_COUNTER); exitWizard(); } } /** * {@inheritDoc} */ @Override public void afterTextChanged(Editable userEnteredValue) { validateKeyAndUpdateStatus(false); } /** * {@inheritDoc} */ @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // Do nothing } /** * {@inheritDoc} */ @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // Do nothing } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/EnterKeyActivity.java
Java
asf20
4,465
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; /** * Counter whose value is a deterministic function of time as described in RFC 6238 * "TOTP: Time-Based One-Time Password Algorithm". * * <p>The 64-bit counter assumes the value {@code 0} at a predefined point in time and periodically * increments its value by one periodically. * * <p>The value {@code V} of the counter at time instant {@code T} is: * <pre> * V = (T - T0) / TimeStep * </pre> * where {@code T0} is the earliest time instant at which the counter assumes the value {@code 0}, * and {@code TimeStep} is the duration of time for which the values of the counter remain constant. * * <p><em>Note: All time instants are in seconds since UNIX epoch, and all time durations are * in seconds.</em> * * <p><em>Note: All time instants must be non-negative.</em> * * <p>Thread-safety: Instances of this class are immutable and are thus thread-safe. * * @author klyubin@google.com (Alex Klyubin) */ public class TotpCounter { /** Interval of time (seconds) between successive changes of this counter's value. */ private final long mTimeStep; /** * Earliest time instant (seconds since UNIX epoch) at which this counter assumes the value of * {@code 0}. */ private final long mStartTime; /** * Constructs a new {@code TotpCounter} that starts with the value {@code 0} at time instant * {@code 0} (seconds since UNIX epoch) and increments its value with the specified frequency. * * @param timeStep interval of time (seconds) between successive changes of this counter's value. */ public TotpCounter(long timeStep) { this(timeStep, 0); } /** * Constructs a new {@code TotpCounter} that starts with the value {@code 0} at the specified * time and increments its value with the specified frequency. * * @param timeStep interval of time (seconds) between successive changes of this counter's value. * @param startTime the earliest time instant (seconds since UNIX epoch) at which this counter * assumes the value {@code 0}. */ public TotpCounter(long timeStep, long startTime) { if (timeStep < 1) { throw new IllegalArgumentException("Time step must be positive: " + timeStep); } assertValidTime(startTime); mTimeStep = timeStep; mStartTime = startTime; } /** * Gets the frequency with which the value of this counter changes. * * @return interval of time (seconds) between successive changes of this counter's value. */ public long getTimeStep() { return mTimeStep; } /** * Gets the earliest time instant at which this counter assumes the value {@code 0}. * * @return time (seconds since UNIX epoch). */ public long getStartTime() { return mStartTime; } /** * Gets the value of this counter at the specified time. * * @param time time instant (seconds since UNIX epoch) for which to obtain the value. * * @return value of the counter at the {@code time}. */ public long getValueAtTime(long time) { assertValidTime(time); // According to the RFC: // T = (Current Unix time - T0) / X, where the default floor function is used. // T - counter value, // T0 - start time. // X - time step. // It's important to use a floor function instead of simple integer division. For example, // assuming a time step of 3: // Time since start time: -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 // Correct value: -2 -2 -2 -1 -1 -1 0 0 0 1 1 1 2 // Simple division / 3: -2 -1 -1 -1 0 0 0 0 0 1 1 1 2 // // To avoid using Math.floor which requires imprecise floating-point arithmetic, we // we compute the value using integer division, but using a different equation for // negative and non-negative time since start time. long timeSinceStartTime = time - mStartTime; if (timeSinceStartTime >= 0) { return timeSinceStartTime / mTimeStep; } else { return (timeSinceStartTime - (mTimeStep - 1)) / mTimeStep; } } /** * Gets the time when the counter assumes the specified value. * * @param value value. * * @return earliest time instant (seconds since UNIX epoch) when the counter assumes the value. */ public long getValueStartTime(long value) { return mStartTime + (value * mTimeStep); } private static void assertValidTime(long time) { if (time < 0) { throw new IllegalArgumentException("Negative time: " + time); } } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/TotpCounter.java
Java
asf20
5,134
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.testability; import android.app.Activity; import android.content.Intent; /** * Base class for {@link Activity} instances to make them more testable. * * @author klyubin@google.com (Alex Klyubin) */ public class TestableActivity extends Activity { @Override public void startActivity(Intent intent) { StartActivityListener listener = DependencyInjector.getStartActivityListener(); if ((listener != null) && (listener.onStartActivityInvoked(this, intent))) { return; } super.startActivity(intent); } @Override public void startActivityForResult(Intent intent, int requestCode) { StartActivityListener listener = DependencyInjector.getStartActivityListener(); if ((listener != null) && (listener.onStartActivityInvoked(this, intent))) { return; } super.startActivityForResult(intent, requestCode); } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/testability/TestableActivity.java
Java
asf20
1,528
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.testability; import com.google.android.apps.authenticator.AccountDb; import com.google.android.apps.authenticator.AuthenticatorActivity; import com.google.android.apps.authenticator.MarketBuildOptionalFeatures; import com.google.android.apps.authenticator.OptionalFeatures; import com.google.android.apps.authenticator.OtpSource; import com.google.android.apps.authenticator.TotpClock; import com.google.android.apps.authenticator.dataimport.ExportServiceBasedImportController; import com.google.android.apps.authenticator.dataimport.ImportController; import android.content.Context; import android.content.pm.PackageManager; import android.preference.PreferenceManager; import android.test.RenamingDelegatingContext; import org.apache.http.client.HttpClient; import org.apache.http.conn.ClientConnectionManager; /** * Dependency injector that decouples the clients of various objects from their * creators/constructors and enables the injection of these objects for testing purposes. * * <p>The injector is singleton. It needs to be configured for production or test use using * {@link #configureForProductionIfNotConfigured(Context)} or * {@link #resetForIntegrationTesting(Context)}. * After that its clients can access the various objects such as {@link AccountDb} using the * respective getters (e.g., {@link #getAccountDb()}. * * <p>When testing, this class provides the means to inject different implementations of the * injectable objects (e.g., {@link #setAccountDb(AccountDb) setAccountDb}). To avoid inter-test * state-leakage, each test should invoke {@link #resetForIntegrationTesting(Context)}. * * @author klyubin@google.com (Alex Klyubin) */ public final class DependencyInjector { private static Context sContext; private static AccountDb sAccountDb; private static OtpSource sOtpProvider; private static TotpClock sTotpClock; private static PackageManager sPackageManager; private static StartActivityListener sStartActivityListener; private static HttpClient sHttpClient; private static ImportController sImportController; private static OptionalFeatures sOptionalFeatures; private enum Mode { PRODUCTION, INTEGRATION_TEST, } private static Mode sMode; private DependencyInjector() {} /** * Gets the {@link Context} passed the instances created by this injector. */ public static synchronized Context getContext() { if (sContext == null) { throw new IllegalStateException("Context not set"); } return sContext; } /** * Sets the {@link AccountDb} instance returned by this injector. This will prevent the injector * from creating its own instance. */ public static synchronized void setAccountDb(AccountDb accountDb) { if (sAccountDb != null) { sAccountDb.close(); } sAccountDb = accountDb; } public static synchronized AccountDb getAccountDb() { if (sAccountDb == null) { sAccountDb = new AccountDb(getContext()); if (sMode != Mode.PRODUCTION) { sAccountDb.deleteAllData(); } } return sAccountDb; } /** * Sets the {@link OtpSource} instance returned by this injector. This will prevent the injector * from creating its own instance. */ public static synchronized void setOtpProvider(OtpSource otpProvider) { sOtpProvider = otpProvider; } public static synchronized OtpSource getOtpProvider() { if (sOtpProvider == null) { sOtpProvider = getOptionalFeatures().createOtpSource(getAccountDb(), getTotpClock()); } return sOtpProvider; } /** * Sets the {@link TotpClock} instance returned by this injector. This will prevent the injector * from creating its own instance. */ public static synchronized void setTotpClock(TotpClock totpClock) { sTotpClock = totpClock; } public static synchronized TotpClock getTotpClock() { if (sTotpClock == null) { sTotpClock = new TotpClock(getContext()); } return sTotpClock; } /** * Sets the {@link PackageManager} instance returned by this injector. This will prevent the * injector from creating its own instance. */ public static synchronized void setPackageManager(PackageManager packageManager) { sPackageManager = packageManager; } public static synchronized PackageManager getPackageManager() { if (sPackageManager == null) { sPackageManager = getContext().getPackageManager(); } return sPackageManager; } /** * Sets the {@link StartActivityListener} instance returned by this injector. */ public static synchronized void setStartActivityListener(StartActivityListener listener) { sStartActivityListener = listener; } public static synchronized StartActivityListener getStartActivityListener() { // Don't create an instance on demand -- the default behavior when the listener is null is to // proceed with launching activities. return sStartActivityListener; } /** * Sets the {@link ImportController} instance returned by this injector. This will prevent the * injector from creating its own instance. */ public static synchronized void setDataImportController(ImportController importController) { sImportController = importController; } public static synchronized ImportController getDataImportController() { if (sImportController == null) { if (sMode == Mode.PRODUCTION) { sImportController = new ExportServiceBasedImportController(); } else { // By default, use a no-op controller during tests to avoid them being dependent on the // presence of the "old" app on the device under test. sImportController = new ImportController() { @Override public void start(Context context, Listener listener) {} }; } } return sImportController; } /** * Sets the {@link HttpClient} instance returned by this injector. This will prevent the * injector from creating its own instance. */ public static synchronized void setHttpClient(HttpClient httpClient) { sHttpClient = httpClient; } public static synchronized HttpClient getHttpClient() { if (sHttpClient == null) { sHttpClient = HttpClientFactory.createHttpClient(getContext()); } return sHttpClient; } public static synchronized void setOptionalFeatures(OptionalFeatures optionalFeatures) { sOptionalFeatures = optionalFeatures; } public static synchronized OptionalFeatures getOptionalFeatures() { if (sOptionalFeatures == null) { try { Class<?> resultClass = Class.forName( AuthenticatorActivity.class.getPackage().getName() + ".NonMarketBuildOptionalFeatures"); try { sOptionalFeatures = (OptionalFeatures) resultClass.newInstance(); } catch (Exception e) { throw new RuntimeException("Failed to instantiate optional features module", e); } } catch (ClassNotFoundException e) { sOptionalFeatures = new MarketBuildOptionalFeatures(); } } return sOptionalFeatures; } /** * Clears any state and configures this injector for production use. Does nothing if the injector * is already configured. */ public static synchronized void configureForProductionIfNotConfigured(Context context) { if (sMode != null) { return; } close(); sMode = Mode.PRODUCTION; sContext = context; } /** * Clears any state and configures this injector to provide objects that are suitable for * integration testing. */ // @VisibleForTesting public static synchronized void resetForIntegrationTesting(Context context) { if (context == null) { throw new NullPointerException("context == null"); } close(); sMode = Mode.INTEGRATION_TEST; RenamingDelegatingContext renamingContext = new RenamingDelegatingContext(context, "test_"); renamingContext.makeExistingFilesAndDbsAccessible(); sContext = new SharedPreferencesRenamingDelegatingContext(renamingContext, "test_"); PreferenceManager.getDefaultSharedPreferences(sContext).edit().clear().commit(); } /** * Closes any resources and objects held by this injector. To use the injector again, invoke * {@link #resetForIntegrationTesting(Context)}. */ public static synchronized void close() { if (sAccountDb != null) { sAccountDb.close(); } if (sHttpClient != null) { ClientConnectionManager httpClientConnectionManager = sHttpClient.getConnectionManager(); if (httpClientConnectionManager != null) { httpClientConnectionManager.shutdown(); } } sMode = null; sContext = null; sAccountDb = null; sOtpProvider = null; sTotpClock = null; sPackageManager = null; sStartActivityListener = null; sHttpClient = null; sImportController = null; sOptionalFeatures = null; } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/testability/DependencyInjector.java
Java
asf20
9,557
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.testability; import android.content.Intent; import android.preference.PreferenceActivity; /** * Base class for {@link PreferenceActivity} instances to make them more testable. * * @author klyubin@google.com (Alex Klyubin) */ public class TestablePreferenceActivity extends PreferenceActivity { @Override public void startActivity(Intent intent) { StartActivityListener listener = DependencyInjector.getStartActivityListener(); if ((listener != null) && (listener.onStartActivityInvoked(this, intent))) { return; } super.startActivity(intent); } @Override public void startActivityForResult(Intent intent, int requestCode) { StartActivityListener listener = DependencyInjector.getStartActivityListener(); if ((listener != null) && (listener.onStartActivityInvoked(this, intent))) { return; } super.startActivityForResult(intent, requestCode); } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/testability/TestablePreferenceActivity.java
Java
asf20
1,575
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.testability; import android.content.Context; import android.os.Build; import org.apache.http.client.HttpClient; import org.apache.http.client.params.HttpClientParams; import org.apache.http.conn.params.ConnManagerParams; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Factory that creates an {@link HttpClient}. * * @author klyubin@google.com (Alex Klyubin) */ final class HttpClientFactory { /** Timeout (ms) for establishing a connection.*/ // @VisibleForTesting static final int DEFAULT_CONNECT_TIMEOUT_MILLIS = 20 * 1000; /** Timeout (ms) for read operations on connections. */ // @VisibleForTesting static final int DEFAULT_READ_TIMEOUT_MILLIS = 20 * 1000; /** Timeout (ms) for obtaining a connection from the connection pool.*/ // @VisibleForTesting static final int DEFAULT_GET_CONNECTION_FROM_POOL_TIMEOUT_MILLIS = 20 * 1000; /** Hidden constructor to prevent instantiation. */ private HttpClientFactory() {} /** * Creates a new {@link HttpClient}. * * @param context context for reusing SSL sessions. */ static HttpClient createHttpClient(Context context) { HttpClient client; // TODO(klyubin): Remove this complicated code once the minimum target is Froyo. if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ECLAIR_MR1) { try { client = createHttpClientForFroyoAndHigher(context); } catch (Exception e) { throw new RuntimeException("Failed to create HttpClient", e); } } else { client = createHttpClientForEclair(); } configureHttpClient(client); return client; } private static void configureHttpClient(HttpClient httpClient) { HttpParams params = httpClient.getParams(); HttpConnectionParams.setStaleCheckingEnabled(params, false); HttpConnectionParams.setConnectionTimeout(params, DEFAULT_CONNECT_TIMEOUT_MILLIS); HttpConnectionParams.setSoTimeout(params, DEFAULT_READ_TIMEOUT_MILLIS); HttpConnectionParams.setSocketBufferSize(params, 8192); ConnManagerParams.setTimeout(params, DEFAULT_GET_CONNECTION_FROM_POOL_TIMEOUT_MILLIS); // Don't handle redirects automatically HttpClientParams.setRedirecting(params, false); // Don't handle authentication automatically HttpClientParams.setAuthenticating(params, false); } private static HttpClient createHttpClientForFroyoAndHigher(Context context) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { // IMPLEMENTATION NOTE: We create the instance via Reflection API to avoid raising the // target SDK version to 8 because that will cause Eclipse to complain for no good reason. // The code below invokes: // AndroidHttpClient.newInstance(null, getContext()) Class<?> androidHttpClientClass = context.getClassLoader().loadClass("android.net.http.AndroidHttpClient"); Method newInstanceMethod = androidHttpClientClass.getMethod("newInstance", String.class, Context.class); return (HttpClient) newInstanceMethod.invoke(null, null, context); } /** * Creates a new instance of {@code HttpClient} for Eclair where we can't use * {@code android.net.http.AndroidHttpClient}. */ private static HttpClient createHttpClientForEclair() { // IMPLEMENTATION NOTE: Since AndroidHttpClient is not available on Eclair, we create a // DefaultHttpClient with a configuration similar to that of AndroidHttpClient. return new DefaultHttpClient(new BasicHttpParams()); } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/testability/HttpClientFactory.java
Java
asf20
4,425
/* * Copyright 2012 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.testability; import android.content.Context; import android.content.ContextWrapper; import android.content.SharedPreferences; /** * {@link ContextWrapper} that prefixes shared preference file names with the provided prefix and * passes all other invocations through unmodified to the delegate {@link Context}. * * @author klyubin@google.com (Alex Klyubin) */ public class SharedPreferencesRenamingDelegatingContext extends ContextWrapper { private final String mPrefix; public SharedPreferencesRenamingDelegatingContext(Context delegate, String prefix) { super(delegate); mPrefix = prefix; } @Override public SharedPreferences getSharedPreferences(String name, int mode) { return super.getSharedPreferences(mPrefix + name, mode); } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/testability/SharedPreferencesRenamingDelegatingContext.java
Java
asf20
1,431
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.testability; import android.content.Context; import android.content.Intent; /** * Listener which is invoked when an attempt is made to launch an {@link android.app.Activity} via * {@link Context#startActivity(Intent)} or * {@link android.app.Activity#startActivityForResult(Intent, int)}. * The listener can decide whether to proceed with the launch. * * @author klyubin@google.com (Alex Klyubin) */ public interface StartActivityListener { /** * Invoked when a launch of an {@link android.app.Activity} is requested. * * @return {@code true} to consume/ignore the request, {@code false} to proceed with the launching * of the {@code Activity}. */ boolean onStartActivityInvoked(Context sourceContext, Intent intent); }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/testability/StartActivityListener.java
Java
asf20
1,420
/* * Copyright 2012 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; /** * Clock input for the time-based OTPs (TOTP). The input is based on the current system time * and is adjusted by a persistently stored correction value (offset in minutes). * * @author klyubin@google.com (Alex Klyubin) */ public class TotpClock { // @VisibleForTesting static final String PREFERENCE_KEY_OFFSET_MINUTES = "timeCorrectionMinutes"; private final SharedPreferences mPreferences; private final Object mLock = new Object(); /** * Cached value of time correction (in minutes) or {@code null} if not cached. The value is cached * because it's read very frequently (once every 100ms) and is modified very infrequently. * * @GuardedBy {@link #mLock} */ private Integer mCachedCorrectionMinutes; public TotpClock(Context context) { mPreferences = PreferenceManager.getDefaultSharedPreferences(context); } /** * Gets the number of milliseconds since epoch. */ public long currentTimeMillis() { return System.currentTimeMillis() + getTimeCorrectionMinutes() * Utilities.MINUTE_IN_MILLIS; } /** * Gets the currently used time correction value. * * @return number of minutes by which this device is behind the correct time. */ public int getTimeCorrectionMinutes() { synchronized (mLock) { if (mCachedCorrectionMinutes == null) { mCachedCorrectionMinutes = mPreferences.getInt(PREFERENCE_KEY_OFFSET_MINUTES, 0); } return mCachedCorrectionMinutes; } } /** * Sets the currently used time correction value. * * @param minutes number of minutes by which this device is behind the correct time. */ public void setTimeCorrectionMinutes(int minutes) { synchronized (mLock) { mPreferences.edit().putInt(PREFERENCE_KEY_OFFSET_MINUTES, minutes).commit(); // Invalidate the cache to force reading actual settings from time to time mCachedCorrectionMinutes = null; } } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/TotpClock.java
Java
asf20
2,710
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import com.google.android.apps.authenticator.testability.TestablePreferenceActivity; import com.google.android.apps.authenticator2.R; import android.os.Bundle; /** * Top-level preferences Activity. * * @author klyubin@google.com (Alex Klyubin) */ public class SettingsActivity extends TestablePreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/SettingsActivity.java
Java
asf20
1,151
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.dataexport; import android.os.Bundle; interface IExportServiceV2 { Bundle getData(); void onImportSucceeded(); }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/dataexport/IExportServiceV2.aidl
AIDL
asf20
782
/* * Copyright 2010 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import android.webkit.WebView; /** * A class for handling a variety of utility things. This was mostly made * because I needed to centralize dialog related constants. I foresee this class * being used for other code sharing across Activities in the future, however. * * @author alexei@czeskis.com (Alexei Czeskis) * */ public class Utilities { // Links public static final String ZXING_MARKET = "market://search?q=pname:com.google.zxing.client.android"; public static final String ZXING_DIRECT = "https://zxing.googlecode.com/files/BarcodeScanner3.1.apk"; // Dialog IDs public static final int DOWNLOAD_DIALOG = 0; public static final int MULTIPLE_ACCOUNTS_DIALOG = 1; static final int INVALID_QR_CODE = 3; static final int INVALID_SECRET_IN_QR_CODE = 7; public static final long SECOND_IN_MILLIS = 1000; public static final long MINUTE_IN_MILLIS = 60 * SECOND_IN_MILLIS; // Constructor -- Does nothing yet private Utilities() { } public static final long millisToSeconds(long timeMillis) { return timeMillis / 1000; } public static final long secondsToMillis(long timeSeconds) { return timeSeconds * 1000; } /** * Sets the provided HTML as the contents of the provided {@link WebView}. */ public static void setWebViewHtml(WebView view, String html) { view.loadDataWithBaseURL(null, html, "text/html", "utf-8", null); } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/Utilities.java
Java
asf20
2,067
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.wizard; import com.google.android.apps.authenticator.AuthenticatorActivity; import com.google.android.apps.authenticator.testability.TestableActivity; import com.google.android.apps.authenticator2.R; import android.content.Intent; import android.os.Bundle; import android.text.Html; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import java.io.Serializable; /** * Base class for a page of a wizard. * * <p> * The main features are: * <ul> * <li>Layout consists of a settable contents page (see {@link #setPageContentView(int)}) * and a button bar at the bottom of the page,</li> * <li>Supports three modes: Back + Next buttons, middle button only, and progress bar (with * indeterminate progress) with a Cancel button. Back + Next buttons is the default.</li> * <li>Automatically passes the status of the wizard through the pages if they are launched with * {@link #startPageActivity(Class)}.</li> * </ul> * * @author klyubin@google.com (Alex Klyubin) */ public class WizardPageActivity<WizardState extends Serializable> extends TestableActivity { // @VisibleForTesting public static final String KEY_WIZARD_STATE = "wizardState"; /** Type of the button bar displayed at the bottom of the page. */ private enum ButtonBarType { LEFT_RIGHT_BUTTONS, MIDDLE_BUTTON_ONLY, CANCEL_BUTTON_ONLY, } private WizardState mWizardState; private View mLeftRightButtonBar; private View mMiddleButtonOnlyBar; private View mCancelButtonOnlyBar; private View mInlineProgressView; private ViewGroup mPageContentView; protected Button mLeftButton; protected Button mRightButton; protected Button mMiddleButton; protected View mCancelButton; private ButtonBarType mButtonBarType; private ButtonBarType mButtonBarTypeBeforeInlineProgressDisplayed; @SuppressWarnings("unchecked") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WizardState wizardState; if (savedInstanceState == null) { wizardState = getWizardStateFromIntent(getIntent()); } else { wizardState = (WizardState) savedInstanceState.getSerializable(KEY_WIZARD_STATE); } checkWizardStateValidity(wizardState); mWizardState = wizardState; setContentView(R.layout.wizard_page); mLeftRightButtonBar = findViewById(R.id.button_bar_left_right_buttons); mMiddleButtonOnlyBar = findViewById(R.id.button_bar_middle_button_only); mPageContentView = (ViewGroup) findViewById(R.id.page_content); mLeftButton = (Button) mLeftRightButtonBar.findViewById(R.id.button_left); mLeftButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onLeftButtonPressed(); } }); mRightButton = (Button) findViewById(R.id.button_right); mRightButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onRightButtonPressed(); } }); mMiddleButton = (Button) findViewById(R.id.button_middle); mMiddleButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onMiddleButtonPressed(); } }); mCancelButtonOnlyBar = findViewById(R.id.button_bar_cancel_only); mInlineProgressView = findViewById(R.id.inline_progress); mCancelButton = findViewById(R.id.button_cancel); setButtonBarType(ButtonBarType.LEFT_RIGHT_BUTTONS); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(KEY_WIZARD_STATE, mWizardState); } protected WizardState getWizardState() { return mWizardState; } protected void setWizardState(WizardState wizardState) { mWizardState = wizardState; } protected View setPageContentView(int resId) { View view = getLayoutInflater().inflate(resId, null); mPageContentView.removeAllViews(); mPageContentView.addView(view); return view; } protected void setButtonBarModeMiddleButtonOnly() { setButtonBarType(ButtonBarType.MIDDLE_BUTTON_ONLY); } /** * Invoked when the left button is pressed. The default implementation invokes * {@link #onBackPressed()}. */ protected void onLeftButtonPressed() { onBackPressed(); } /** * Invoked when the right button is pressed. The default implementation does nothing. */ protected void onRightButtonPressed() {} /** * Invoked when the middle button is pressed. The default implementation does nothing. */ protected void onMiddleButtonPressed() {} /** * Launches/displays the specified page of the wizard. The page will get a copy of the current * state of the wizard. */ protected void startPageActivity(Class<? extends WizardPageActivity<WizardState>> activityClass) { Intent intent = new Intent(this, activityClass); intent.putExtra(KEY_WIZARD_STATE, getWizardState()); startActivity(intent); } /** * Launches/displays the specified page of the wizard. The page will get a copy of the current * state of the wizard. */ protected void startPageActivityForResult( Class<? extends WizardPageActivity<WizardState>> activityClass, int requestCode) { Intent intent = new Intent(this, activityClass); intent.putExtra(KEY_WIZARD_STATE, getWizardState()); startActivityForResult(intent, requestCode); } /** * Extracts the state of the wizard from the provided Intent. * * @return state or {@code null} if not found. */ @SuppressWarnings("unchecked") protected WizardState getWizardStateFromIntent(Intent intent) { return (intent != null) ? (WizardState) intent.getSerializableExtra(KEY_WIZARD_STATE) : null; } /** * Sets the contents of the {@code TextView} to the HTML contained in the string resource. */ protected void setTextViewHtmlFromResource(int viewId, int resId) { setTextViewHtmlFromResource((TextView) findViewById(viewId), resId); } /** * Sets the contents of the {@code TextView} to the HTML contained in the string resource. */ protected void setTextViewHtmlFromResource(TextView view, int resId) { view.setText(Html.fromHtml(getString(resId))); } /** * Sets the contents of the {@code TextView} to the provided HTML. */ protected void setTextViewHtml(int viewId, String html) { setTextViewHtml((TextView) findViewById(viewId), html); } /** * Sets the contents of the {@code TextView} to the provided HTML. */ protected void setTextViewHtml(TextView view, String html) { view.setText(Html.fromHtml(html)); } /** * Sets the type of the button bar displayed at the bottom of the page. */ private void setButtonBarType(ButtonBarType type) { mButtonBarType = type; switch (type) { case LEFT_RIGHT_BUTTONS: mLeftRightButtonBar.setVisibility(View.VISIBLE); mMiddleButtonOnlyBar.setVisibility(View.GONE); mCancelButtonOnlyBar.setVisibility(View.GONE); break; case MIDDLE_BUTTON_ONLY: mMiddleButtonOnlyBar.setVisibility(View.VISIBLE); mLeftRightButtonBar.setVisibility(View.GONE); mCancelButtonOnlyBar.setVisibility(View.GONE); break; case CANCEL_BUTTON_ONLY: mCancelButtonOnlyBar.setVisibility(View.VISIBLE); mLeftRightButtonBar.setVisibility(View.GONE); mMiddleButtonOnlyBar.setVisibility(View.GONE); break; default: throw new IllegalArgumentException(String.valueOf(type)); } } /** * Changes this page to show an indefinite progress bar with a Cancel button. * * @param cancelListener listener invoked when the Cancel button is pressed. * * @see #dismissInlineProgress() */ protected void showInlineProgress(View.OnClickListener cancelListener) { mCancelButton.setOnClickListener(cancelListener); mCancelButton.setEnabled(true); mInlineProgressView.setVisibility(View.VISIBLE); if (mButtonBarType != ButtonBarType.CANCEL_BUTTON_ONLY) { mButtonBarTypeBeforeInlineProgressDisplayed = mButtonBarType; } setButtonBarType(ButtonBarType.CANCEL_BUTTON_ONLY); } /** * Changes this page to hide the indefinite progress bar with a Cancel button. The page reverts * to the usual layout with the left and right buttons. * * @see #showInlineProgress(android.view.View.OnClickListener) */ protected void dismissInlineProgress() { mCancelButton.setOnClickListener(null); setButtonBarType(mButtonBarTypeBeforeInlineProgressDisplayed); } protected void exitWizard() { Intent intent = new Intent(this, AuthenticatorActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); } /** * Checks the validity of the current state of the wizard. * * @throws IllegalStateException if the state is invalid. */ protected void checkWizardStateValidity(@SuppressWarnings("unused") WizardState wizardState) {} }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/wizard/WizardPageActivity.java
Java
asf20
9,768
/* * Copyright 2010 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import java.util.Collection; /** * Abstraction for collection of OTP tokens. * * @author cemp@google.com (Cem Paya) */ public interface OtpSource { /** * Enumerate list of accounts that this OTP token supports. * * @param result Collection to append usernames. This object is NOT cleared on * entry; if there are existing items, they will not be removed. * @return Number of accounts added to the collection. */ int enumerateAccounts(Collection<String> result); /** * Return the next OTP code for specified username. * Invoking this function may change internal state of the OTP generator, * for example advancing the counter. * * @param accountName Username, email address or other unique identifier for the account. * @return OTP as string code. */ String getNextCode(String accountName) throws OtpSourceException; /** * Generate response to a given challenge based on next OTP code. * Subclasses are not required to implement this method. * * @param accountName Username, email address or other unique identifier for the account. * @param challenge Server specified challenge as UTF8 string. * @return Response to the challenge. * @throws UnsupportedOperationException if the token does not support * challenge-response extension for this account. */ String respondToChallenge(String accountName, String challenge) throws OtpSourceException; /** * Gets the counter for generating or verifying TOTP codes. */ TotpCounter getTotpCounter(); /** * Gets the clock for generating or verifying TOTP codes. */ TotpClock getTotpClock(); }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/OtpSource.java
Java
asf20
2,328
/* * Copyright 2009 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import com.google.android.apps.authenticator.AccountDb.OtpType; import com.google.android.apps.authenticator.dataimport.ImportController; import com.google.android.apps.authenticator.howitworks.IntroEnterPasswordActivity; import com.google.android.apps.authenticator.testability.DependencyInjector; import com.google.android.apps.authenticator.testability.TestableActivity; import com.google.android.apps.authenticator2.R; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Vibrator; import android.text.ClipboardManager; import android.text.Html; import android.util.Log; import android.util.TypedValue; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.webkit.WebView; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.Serializable; import java.util.ArrayList; /** * The main activity that displays usernames and codes * * @author sweis@google.com (Steve Weis) * @author adhintz@google.com (Drew Hintz) * @author cemp@google.com (Cem Paya) * @author klyubin@google.com (Alex Klyubin) */ public class AuthenticatorActivity extends TestableActivity { /** The tag for log messages */ private static final String LOCAL_TAG = "AuthenticatorActivity"; private static final long VIBRATE_DURATION = 200L; /** Frequency (milliseconds) with which TOTP countdown indicators are updated. */ private static final long TOTP_COUNTDOWN_REFRESH_PERIOD = 100; /** * Minimum amount of time (milliseconds) that has to elapse from the moment a HOTP code is * generated for an account until the moment the next code can be generated for the account. * This is to prevent the user from generating too many HOTP codes in a short period of time. */ private static final long HOTP_MIN_TIME_INTERVAL_BETWEEN_CODES = 5000; /** * The maximum amount of time (milliseconds) for which a HOTP code is displayed after it's been * generated. */ private static final long HOTP_DISPLAY_TIMEOUT = 2 * 60 * 1000; // @VisibleForTesting static final int DIALOG_ID_UNINSTALL_OLD_APP = 12; // @VisibleForTesting static final int DIALOG_ID_SAVE_KEY = 13; /** * Intent action to that tells this Activity to initiate the scanning of barcode to add an * account. */ // @VisibleForTesting static final String ACTION_SCAN_BARCODE = AuthenticatorActivity.class.getName() + ".ScanBarcode"; private View mContentNoAccounts; private View mContentAccountsPresent; private TextView mEnterPinPrompt; private ListView mUserList; private PinListAdapter mUserAdapter; private PinInfo[] mUsers = {}; /** Counter used for generating TOTP verification codes. */ private TotpCounter mTotpCounter; /** Clock used for generating TOTP verification codes. */ private TotpClock mTotpClock; /** * Task that periodically notifies this activity about the amount of time remaining until * the TOTP codes refresh. The task also notifies this activity when TOTP codes refresh. */ private TotpCountdownTask mTotpCountdownTask; /** * Phase of TOTP countdown indicators. The phase is in {@code [0, 1]} with {@code 1} meaning * full time step remaining until the code refreshes, and {@code 0} meaning the code is refreshing * right now. */ private double mTotpCountdownPhase; private AccountDb mAccountDb; private OtpSource mOtpProvider; /** * Key under which the {@link #mOldAppUninstallIntent} is stored in the instance state * {@link Bundle}. */ private static final String KEY_OLD_APP_UNINSTALL_INTENT = "oldAppUninstallIntent"; /** * {@link Intent} for uninstalling the "old" app or {@code null} if not known/available. * * <p> * Note: this field is persisted in the instance state {@link Bundle}. We need to resolve to this * error-prone mechanism because showDialog on Eclair doesn't take parameters. Once Froyo is * the minimum targetted SDK, this contrived code can be removed. */ private Intent mOldAppUninstallIntent; /** Whether the importing of data from the "old" app has been started and has not yet finished. */ private boolean mDataImportInProgress; /** * Key under which the {@link #mSaveKeyDialogParams} is stored in the instance state * {@link Bundle}. */ private static final String KEY_SAVE_KEY_DIALOG_PARAMS = "saveKeyDialogParams"; /** * Parameters to the save key dialog (DIALOG_ID_SAVE_KEY). * * <p> * Note: this field is persisted in the instance state {@link Bundle}. We need to resolve to this * error-prone mechanism because showDialog on Eclair doesn't take parameters. Once Froyo is * the minimum targetted SDK, this contrived code can be removed. */ private SaveKeyDialogParams mSaveKeyDialogParams; /** * Whether this activity is currently displaying a confirmation prompt in response to the * "save key" Intent. */ private boolean mSaveKeyIntentConfirmationInProgress; private static final String OTP_SCHEME = "otpauth"; private static final String TOTP = "totp"; // time-based private static final String HOTP = "hotp"; // counter-based private static final String SECRET_PARAM = "secret"; private static final String COUNTER_PARAM = "counter"; // @VisibleForTesting public static final int CHECK_KEY_VALUE_ID = 0; // @VisibleForTesting public static final int RENAME_ID = 1; // @VisibleForTesting public static final int REMOVE_ID = 2; // @VisibleForTesting static final int COPY_TO_CLIPBOARD_ID = 3; // @VisibleForTesting static final int SCAN_REQUEST = 31337; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAccountDb = DependencyInjector.getAccountDb(); mOtpProvider = DependencyInjector.getOtpProvider(); // Use a different (longer) title from the one that's declared in the manifest (and the one that // the Android launcher displays). setTitle(R.string.app_name); mTotpCounter = mOtpProvider.getTotpCounter(); mTotpClock = mOtpProvider.getTotpClock(); setContentView(R.layout.main); // restore state on screen rotation Object savedState = getLastNonConfigurationInstance(); if (savedState != null) { mUsers = (PinInfo[]) savedState; // Re-enable the Get Code buttons on all HOTP accounts, otherwise they'll stay disabled. for (PinInfo account : mUsers) { if (account.isHotp) { account.hotpCodeGenerationAllowed = true; } } } if (savedInstanceState != null) { mOldAppUninstallIntent = savedInstanceState.getParcelable(KEY_OLD_APP_UNINSTALL_INTENT); mSaveKeyDialogParams = (SaveKeyDialogParams) savedInstanceState.getSerializable(KEY_SAVE_KEY_DIALOG_PARAMS); } mUserList = (ListView) findViewById(R.id.user_list); mContentNoAccounts = findViewById(R.id.content_no_accounts); mContentAccountsPresent = findViewById(R.id.content_accounts_present); mContentNoAccounts.setVisibility((mUsers.length > 0) ? View.GONE : View.VISIBLE); mContentAccountsPresent.setVisibility((mUsers.length > 0) ? View.VISIBLE : View.GONE); TextView noAccountsPromptDetails = (TextView) findViewById(R.id.details); noAccountsPromptDetails.setText( Html.fromHtml(getString(R.string.welcome_page_details))); findViewById(R.id.how_it_works_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { displayHowItWorksInstructions(); } }); findViewById(R.id.add_account_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addAccount(); } }); mEnterPinPrompt = (TextView) findViewById(R.id.enter_pin_prompt); mUserAdapter = new PinListAdapter(this, R.layout.user_row, mUsers); mUserList.setVisibility(View.GONE); mUserList.setAdapter(mUserAdapter); mUserList.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> unusedParent, View row, int unusedPosition, long unusedId) { NextOtpButtonListener clickListener = (NextOtpButtonListener) row.getTag(); View nextOtp = row.findViewById(R.id.next_otp); if ((clickListener != null) && nextOtp.isEnabled()){ clickListener.onClick(row); } mUserList.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); } }); if (savedInstanceState == null) { // This is the first time this Activity is starting (i.e., not restoring previous state which // was saved, for example, due to orientation change) DependencyInjector.getOptionalFeatures().onAuthenticatorActivityCreated(this); importDataFromOldAppIfNecessary(); handleIntent(getIntent()); } } /** * Reacts to the {@link Intent} that started this activity or arrived to this activity without * restarting it (i.e., arrived via {@link #onNewIntent(Intent)}). Does nothing if the provided * intent is {@code null}. */ private void handleIntent(Intent intent) { if (intent == null) { return; } String action = intent.getAction(); if (action == null) { return; } if (ACTION_SCAN_BARCODE.equals(action)) { scanBarcode(); } else if (intent.getData() != null) { interpretScanResult(intent.getData(), true); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(KEY_OLD_APP_UNINSTALL_INTENT, mOldAppUninstallIntent); outState.putSerializable(KEY_SAVE_KEY_DIALOG_PARAMS, mSaveKeyDialogParams); } @Override public Object onRetainNonConfigurationInstance() { return mUsers; // save state of users and currently displayed PINs } // Because this activity is marked as singleTop, new launch intents will be // delivered via this API instead of onResume(). // Override here to catch otpauth:// URL being opened from QR code reader. @Override protected void onNewIntent(Intent intent) { Log.i(getString(R.string.app_name), LOCAL_TAG + ": onNewIntent"); handleIntent(intent); } @Override protected void onStart() { super.onStart(); updateCodesAndStartTotpCountdownTask(); } @Override protected void onResume() { super.onResume(); Log.i(getString(R.string.app_name), LOCAL_TAG + ": onResume"); importDataFromOldAppIfNecessary(); } @Override protected void onStop() { stopTotpCountdownTask(); super.onStop(); } private void updateCodesAndStartTotpCountdownTask() { stopTotpCountdownTask(); mTotpCountdownTask = new TotpCountdownTask(mTotpCounter, mTotpClock, TOTP_COUNTDOWN_REFRESH_PERIOD); mTotpCountdownTask.setListener(new TotpCountdownTask.Listener() { @Override public void onTotpCountdown(long millisRemaining) { if (isFinishing()) { // No need to reach to this even because the Activity is finishing anyway return; } setTotpCountdownPhaseFromTimeTillNextValue(millisRemaining); } @Override public void onTotpCounterValueChanged() { if (isFinishing()) { // No need to reach to this even because the Activity is finishing anyway return; } refreshVerificationCodes(); } }); mTotpCountdownTask.startAndNotifyListener(); } private void stopTotpCountdownTask() { if (mTotpCountdownTask != null) { mTotpCountdownTask.stop(); mTotpCountdownTask = null; } } /** Display list of user emails and updated pin codes. */ protected void refreshUserList() { refreshUserList(false); } private void setTotpCountdownPhase(double phase) { mTotpCountdownPhase = phase; updateCountdownIndicators(); } private void setTotpCountdownPhaseFromTimeTillNextValue(long millisRemaining) { setTotpCountdownPhase( ((double) millisRemaining) / Utilities.secondsToMillis(mTotpCounter.getTimeStep())); } private void refreshVerificationCodes() { refreshUserList(); setTotpCountdownPhase(1.0); } private void updateCountdownIndicators() { for (int i = 0, len = mUserList.getChildCount(); i < len; i++) { View listEntry = mUserList.getChildAt(i); CountdownIndicator indicator = (CountdownIndicator) listEntry.findViewById(R.id.countdown_icon); if (indicator != null) { indicator.setPhase(mTotpCountdownPhase); } } } /** * Display list of user emails and updated pin codes. * * @param isAccountModified if true, force full refresh */ // @VisibleForTesting public void refreshUserList(boolean isAccountModified) { ArrayList<String> usernames = new ArrayList<String>(); mAccountDb.getNames(usernames); int userCount = usernames.size(); if (userCount > 0) { boolean newListRequired = isAccountModified || mUsers.length != userCount; if (newListRequired) { mUsers = new PinInfo[userCount]; } for (int i = 0; i < userCount; ++i) { String user = usernames.get(i); try { computeAndDisplayPin(user, i, false); } catch (OtpSourceException ignored) {} } if (newListRequired) { // Make the list display the data from the newly created array of accounts // This forces the list to scroll to top. mUserAdapter = new PinListAdapter(this, R.layout.user_row, mUsers); mUserList.setAdapter(mUserAdapter); } mUserAdapter.notifyDataSetChanged(); if (mUserList.getVisibility() != View.VISIBLE) { mUserList.setVisibility(View.VISIBLE); registerForContextMenu(mUserList); } } else { mUsers = new PinInfo[0]; // clear any existing user PIN state mUserList.setVisibility(View.GONE); } // Display the list of accounts if there are accounts, otherwise display a // different layout explaining the user how this app works and providing the user with an easy // way to add an account. mContentNoAccounts.setVisibility((mUsers.length > 0) ? View.GONE : View.VISIBLE); mContentAccountsPresent.setVisibility((mUsers.length > 0) ? View.VISIBLE : View.GONE); } /** * Computes the PIN and saves it in mUsers. This currently runs in the UI * thread so it should not take more than a second or so. If necessary, we can * move the computation to a background thread. * * @param user the user email to display with the PIN * @param position the index for the screen of this user and PIN * @param computeHotp true if we should increment counter and display new hotp */ public void computeAndDisplayPin(String user, int position, boolean computeHotp) throws OtpSourceException { PinInfo currentPin; if (mUsers[position] != null) { currentPin = mUsers[position]; // existing PinInfo, so we'll update it } else { currentPin = new PinInfo(); currentPin.pin = getString(R.string.empty_pin); currentPin.hotpCodeGenerationAllowed = true; } OtpType type = mAccountDb.getType(user); currentPin.isHotp = (type == OtpType.HOTP); currentPin.user = user; if (!currentPin.isHotp || computeHotp) { // Always safe to recompute, because this code path is only // reached if the account is: // - Time-based, in which case getNextCode() does not change state. // - Counter-based (HOTP) and computeHotp is true. currentPin.pin = mOtpProvider.getNextCode(user); currentPin.hotpCodeGenerationAllowed = true; } mUsers[position] = currentPin; } /** * Parses a secret value from a URI. The format will be: * * otpauth://totp/user@example.com?secret=FFF... * otpauth://hotp/user@example.com?secret=FFF...&counter=123 * * @param uri The URI containing the secret key * @param confirmBeforeSave a boolean to indicate if the user should be * prompted for confirmation before updating the otp * account information. */ private void parseSecret(Uri uri, boolean confirmBeforeSave) { final String scheme = uri.getScheme().toLowerCase(); final String path = uri.getPath(); final String authority = uri.getAuthority(); final String user; final String secret; final OtpType type; final Integer counter; if (!OTP_SCHEME.equals(scheme)) { Log.e(getString(R.string.app_name), LOCAL_TAG + ": Invalid or missing scheme in uri"); showDialog(Utilities.INVALID_QR_CODE); return; } if (TOTP.equals(authority)) { type = OtpType.TOTP; counter = AccountDb.DEFAULT_HOTP_COUNTER; // only interesting for HOTP } else if (HOTP.equals(authority)) { type = OtpType.HOTP; String counterParameter = uri.getQueryParameter(COUNTER_PARAM); if (counterParameter != null) { try { counter = Integer.parseInt(counterParameter); } catch (NumberFormatException e) { Log.e(getString(R.string.app_name), LOCAL_TAG + ": Invalid counter in uri"); showDialog(Utilities.INVALID_QR_CODE); return; } } else { counter = AccountDb.DEFAULT_HOTP_COUNTER; } } else { Log.e(getString(R.string.app_name), LOCAL_TAG + ": Invalid or missing authority in uri"); showDialog(Utilities.INVALID_QR_CODE); return; } user = validateAndGetUserInPath(path); if (user == null) { Log.e(getString(R.string.app_name), LOCAL_TAG + ": Missing user id in uri"); showDialog(Utilities.INVALID_QR_CODE); return; } secret = uri.getQueryParameter(SECRET_PARAM); if (secret == null || secret.length() == 0) { Log.e(getString(R.string.app_name), LOCAL_TAG + ": Secret key not found in URI"); showDialog(Utilities.INVALID_SECRET_IN_QR_CODE); return; } if (AccountDb.getSigningOracle(secret) == null) { Log.e(getString(R.string.app_name), LOCAL_TAG + ": Invalid secret key"); showDialog(Utilities.INVALID_SECRET_IN_QR_CODE); return; } if (secret.equals(mAccountDb.getSecret(user)) && counter == mAccountDb.getCounter(user) && type == mAccountDb.getType(user)) { return; // nothing to update. } if (confirmBeforeSave) { mSaveKeyDialogParams = new SaveKeyDialogParams(user, secret, type, counter); showDialog(DIALOG_ID_SAVE_KEY); } else { saveSecretAndRefreshUserList(user, secret, null, type, counter); } } private static String validateAndGetUserInPath(String path) { if (path == null || !path.startsWith("/")) { return null; } // path is "/user", so remove leading "/", and trailing white spaces String user = path.substring(1).trim(); if (user.length() == 0) { return null; // only white spaces. } return user; } /** * Saves the secret key to local storage on the phone and updates the displayed account list. * * @param user the user email address. When editing, the new user email. * @param secret the secret key * @param originalUser If editing, the original user email, otherwise null. * @param type hotp vs totp * @param counter only important for the hotp type */ private void saveSecretAndRefreshUserList(String user, String secret, String originalUser, OtpType type, Integer counter) { if (saveSecret(this, user, secret, originalUser, type, counter)) { refreshUserList(true); } } /** * Saves the secret key to local storage on the phone. * * @param user the user email address. When editing, the new user email. * @param secret the secret key * @param originalUser If editing, the original user email, otherwise null. * @param type hotp vs totp * @param counter only important for the hotp type * * @return {@code true} if the secret was saved, {@code false} otherwise. */ static boolean saveSecret(Context context, String user, String secret, String originalUser, OtpType type, Integer counter) { if (originalUser == null) { // new user account originalUser = user; } if (secret != null) { AccountDb accountDb = DependencyInjector.getAccountDb(); accountDb.update(user, secret, originalUser, type, counter); DependencyInjector.getOptionalFeatures().onAuthenticatorActivityAccountSaved(context, user); // TODO: Consider having a display message that activities can call and it // will present a toast with a uniform duration, and perhaps update // status messages (presuming we have a way to remove them after they // are stale). Toast.makeText(context, R.string.secret_saved, Toast.LENGTH_LONG).show(); ((Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE)) .vibrate(VIBRATE_DURATION); return true; } else { Log.e(LOCAL_TAG, "Trying to save an empty secret key"); Toast.makeText(context, R.string.error_empty_secret, Toast.LENGTH_LONG).show(); return false; } } /** Converts user list ordinal id to user email */ private String idToEmail(long id) { return mUsers[(int) id].user; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; String user = idToEmail(info.id); OtpType type = mAccountDb.getType(user); menu.setHeaderTitle(user); menu.add(0, COPY_TO_CLIPBOARD_ID, 0, R.string.copy_to_clipboard); // Option to display the check-code is only available for HOTP accounts. if (type == OtpType.HOTP) { menu.add(0, CHECK_KEY_VALUE_ID, 0, R.string.check_code_menu_item); } menu.add(0, RENAME_ID, 0, R.string.rename); menu.add(0, REMOVE_ID, 0, R.string.context_menu_remove_account); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); Intent intent; final String user = idToEmail(info.id); // final so listener can see value switch (item.getItemId()) { case COPY_TO_CLIPBOARD_ID: ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); clipboard.setText(mUsers[(int) info.id].pin); return true; case CHECK_KEY_VALUE_ID: intent = new Intent(Intent.ACTION_VIEW); intent.setClass(this, CheckCodeActivity.class); intent.putExtra("user", user); startActivity(intent); return true; case RENAME_ID: final Context context = this; // final so listener can see value final View frame = getLayoutInflater().inflate(R.layout.rename, (ViewGroup) findViewById(R.id.rename_root)); final EditText nameEdit = (EditText) frame.findViewById(R.id.rename_edittext); nameEdit.setText(user); new AlertDialog.Builder(this) .setTitle(String.format(getString(R.string.rename_message), user)) .setView(frame) .setPositiveButton(R.string.submit, this.getRenameClickListener(context, user, nameEdit)) .setNegativeButton(R.string.cancel, null) .show(); return true; case REMOVE_ID: // Use a WebView to display the prompt because it contains non-trivial markup, such as list View promptContentView = getLayoutInflater().inflate(R.layout.remove_account_prompt, null, false); WebView webView = (WebView) promptContentView.findViewById(R.id.web_view); webView.setBackgroundColor(Color.TRANSPARENT); // Make the WebView use the same font size as for the mEnterPinPrompt field double pixelsPerDip = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics()) / 10d; webView.getSettings().setDefaultFontSize( (int) (mEnterPinPrompt.getTextSize() / pixelsPerDip)); Utilities.setWebViewHtml( webView, "<html><body style=\"background-color: transparent;\" text=\"white\">" + getString( mAccountDb.isGoogleAccount(user) ? R.string.remove_google_account_dialog_message : R.string.remove_account_dialog_message) + "</body></html>"); new AlertDialog.Builder(this) .setTitle(getString(R.string.remove_account_dialog_title, user)) .setView(promptContentView) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.remove_account_dialog_button_remove, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { mAccountDb.delete(user); refreshUserList(true); } } ) .setNegativeButton(R.string.cancel, null) .show(); return true; default: return super.onContextItemSelected(item); } } private DialogInterface.OnClickListener getRenameClickListener(final Context context, final String user, final EditText nameEdit) { return new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { String newName = nameEdit.getText().toString(); if (newName != user) { if (mAccountDb.nameExists(newName)) { Toast.makeText(context, R.string.error_exists, Toast.LENGTH_LONG).show(); } else { saveSecretAndRefreshUserList(newName, mAccountDb.getSecret(user), user, mAccountDb.getType(user), mAccountDb.getCounter(user)); } } } }; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case R.id.add_account: addAccount(); return true; case R.id.how_it_works: displayHowItWorksInstructions(); return true; case R.id.settings: showSettings(); return true; } return super.onMenuItemSelected(featureId, item); } @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { Log.i(getString(R.string.app_name), LOCAL_TAG + ": onActivityResult"); if (requestCode == SCAN_REQUEST && resultCode == Activity.RESULT_OK) { // Grab the scan results and convert it into a URI String scanResult = (intent != null) ? intent.getStringExtra("SCAN_RESULT") : null; Uri uri = (scanResult != null) ? Uri.parse(scanResult) : null; interpretScanResult(uri, false); } } private void displayHowItWorksInstructions() { startActivity(new Intent(this, IntroEnterPasswordActivity.class)); } private void addAccount() { DependencyInjector.getOptionalFeatures().onAuthenticatorActivityAddAccount(this); } private void scanBarcode() { Intent intentScan = new Intent("com.google.zxing.client.android.SCAN"); intentScan.putExtra("SCAN_MODE", "QR_CODE_MODE"); intentScan.putExtra("SAVE_HISTORY", false); try { startActivityForResult(intentScan, SCAN_REQUEST); } catch (ActivityNotFoundException error) { showDialog(Utilities.DOWNLOAD_DIALOG); } } public static Intent getLaunchIntentActionScanBarcode(Context context) { return new Intent(AuthenticatorActivity.ACTION_SCAN_BARCODE) .setComponent(new ComponentName(context, AuthenticatorActivity.class)); } private void showSettings() { Intent intent = new Intent(); intent.setClass(this, SettingsActivity.class); startActivity(intent); } /** * Interprets the QR code that was scanned by the user. Decides whether to * launch the key provisioning sequence or the OTP seed setting sequence. * * @param scanResult a URI holding the contents of the QR scan result * @param confirmBeforeSave a boolean to indicate if the user should be * prompted for confirmation before updating the otp * account information. */ private void interpretScanResult(Uri scanResult, boolean confirmBeforeSave) { if (DependencyInjector.getOptionalFeatures().interpretScanResult(this, scanResult)) { // Scan result consumed by an optional component return; } // The scan result is expected to be a URL that adds an account. // If confirmBeforeSave is true, the user has to confirm/reject the action. // We need to ensure that new results are accepted only if the previous ones have been // confirmed/rejected by the user. This is to prevent the attacker from sending multiple results // in sequence to confuse/DoS the user. if (confirmBeforeSave) { if (mSaveKeyIntentConfirmationInProgress) { Log.w(LOCAL_TAG, "Ignoring save key Intent: previous Intent not yet confirmed by user"); return; } // No matter what happens below, we'll show a prompt which, once dismissed, will reset the // flag below. mSaveKeyIntentConfirmationInProgress = true; } // Sanity check if (scanResult == null) { showDialog(Utilities.INVALID_QR_CODE); return; } // See if the URL is an account setup URL containing a shared secret if (OTP_SCHEME.equals(scanResult.getScheme()) && scanResult.getAuthority() != null) { parseSecret(scanResult, confirmBeforeSave); } else { showDialog(Utilities.INVALID_QR_CODE); } } /** * This method is deprecated in SDK level 8, but we have to use it because the * new method, which replaces this one, does not exist before SDK level 8 */ @Override protected Dialog onCreateDialog(final int id) { Dialog dialog = null; switch(id) { /** * Prompt to download ZXing from Market. If Market app is not installed, * such as on a development phone, open the HTTPS URI for the ZXing apk. */ case Utilities.DOWNLOAD_DIALOG: AlertDialog.Builder dlBuilder = new AlertDialog.Builder(this); dlBuilder.setTitle(R.string.install_dialog_title); dlBuilder.setMessage(R.string.install_dialog_message); dlBuilder.setIcon(android.R.drawable.ic_dialog_alert); dlBuilder.setPositiveButton(R.string.install_button, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(Utilities.ZXING_MARKET)); try { startActivity(intent); } catch (ActivityNotFoundException e) { // if no Market app intent = new Intent(Intent.ACTION_VIEW, Uri.parse(Utilities.ZXING_DIRECT)); startActivity(intent); } } } ); dlBuilder.setNegativeButton(R.string.cancel, null); dialog = dlBuilder.create(); break; case DIALOG_ID_SAVE_KEY: final SaveKeyDialogParams saveKeyDialogParams = mSaveKeyDialogParams; dialog = new AlertDialog.Builder(this) .setTitle(R.string.save_key_message) .setMessage(saveKeyDialogParams.user) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { saveSecretAndRefreshUserList( saveKeyDialogParams.user, saveKeyDialogParams.secret, null, saveKeyDialogParams.type, saveKeyDialogParams.counter); } }) .setNegativeButton(R.string.cancel, null) .create(); // Ensure that whenever this dialog is to be displayed via showDialog, it displays the // correct (latest) user/account name. If this dialog is not explicitly removed after it's // been dismissed, then next time showDialog is invoked, onCreateDialog will not be invoked // and the dialog will display the previous user/account name instead of the current one. dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { removeDialog(id); onSaveKeyIntentConfirmationPromptDismissed(); } }); break; case Utilities.INVALID_QR_CODE: dialog = createOkAlertDialog(R.string.error_title, R.string.error_qr, android.R.drawable.ic_dialog_alert); markDialogAsResultOfSaveKeyIntent(dialog); break; case Utilities.INVALID_SECRET_IN_QR_CODE: dialog = createOkAlertDialog( R.string.error_title, R.string.error_uri, android.R.drawable.ic_dialog_alert); markDialogAsResultOfSaveKeyIntent(dialog); break; case DIALOG_ID_UNINSTALL_OLD_APP: dialog = new AlertDialog.Builder(this) .setTitle(R.string.dataimport_import_succeeded_uninstall_dialog_title) .setMessage( DependencyInjector.getOptionalFeatures().appendDataImportLearnMoreLink( this, getString(R.string.dataimport_import_succeeded_uninstall_dialog_prompt))) .setCancelable(true) .setPositiveButton( R.string.button_uninstall_old_app, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { startActivity(mOldAppUninstallIntent); } }) .setNegativeButton(R.string.cancel, null) .create(); break; default: dialog = DependencyInjector.getOptionalFeatures().onAuthenticatorActivityCreateDialog(this, id); if (dialog == null) { dialog = super.onCreateDialog(id); } break; } return dialog; } private void markDialogAsResultOfSaveKeyIntent(Dialog dialog) { dialog.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { onSaveKeyIntentConfirmationPromptDismissed(); } }); } /** * Invoked when a user-visible confirmation prompt for the Intent to add a new account has been * dimissed. */ private void onSaveKeyIntentConfirmationPromptDismissed() { mSaveKeyIntentConfirmationInProgress = false; } /** * Create dialog with supplied ids; icon is not set if iconId is 0. */ private Dialog createOkAlertDialog(int titleId, int messageId, int iconId) { return new AlertDialog.Builder(this) .setTitle(titleId) .setMessage(messageId) .setIcon(iconId) .setPositiveButton(R.string.ok, null) .create(); } /** * A tuple of user, OTP value, and type, that represents a particular user. * * @author adhintz@google.com (Drew Hintz) */ private static class PinInfo { private String pin; // calculated OTP, or a placeholder if not calculated private String user; private boolean isHotp = false; // used to see if button needs to be displayed /** HOTP only: Whether code generation is allowed for this account. */ private boolean hotpCodeGenerationAllowed; } /** Scale to use for the text displaying the PIN numbers. */ private static final float PIN_TEXT_SCALEX_NORMAL = 1.0f; /** Underscores are shown slightly smaller. */ private static final float PIN_TEXT_SCALEX_UNDERSCORE = 0.87f; /** * Listener for the Button that generates the next OTP value. * * @author adhintz@google.com (Drew Hintz) */ private class NextOtpButtonListener implements OnClickListener { private final Handler mHandler = new Handler(); private final PinInfo mAccount; private NextOtpButtonListener(PinInfo account) { mAccount = account; } @Override public void onClick(View v) { int position = findAccountPositionInList(); if (position == -1) { throw new RuntimeException("Account not in list: " + mAccount); } try { computeAndDisplayPin(mAccount.user, position, true); } catch (OtpSourceException e) { DependencyInjector.getOptionalFeatures().onAuthenticatorActivityGetNextOtpFailed( AuthenticatorActivity.this, mAccount.user, e); return; } final String pin = mAccount.pin; // Temporarily disable code generation for this account mAccount.hotpCodeGenerationAllowed = false; mUserAdapter.notifyDataSetChanged(); // The delayed operation below will be invoked once code generation is yet again allowed for // this account. The delay is in wall clock time (monotonically increasing) and is thus not // susceptible to system time jumps. mHandler.postDelayed( new Runnable() { @Override public void run() { mAccount.hotpCodeGenerationAllowed = true; mUserAdapter.notifyDataSetChanged(); } }, HOTP_MIN_TIME_INTERVAL_BETWEEN_CODES); // The delayed operation below will hide this OTP to prevent the user from seeing this OTP // long after it's been generated (and thus hopefully used). mHandler.postDelayed( new Runnable() { @Override public void run() { if (!pin.equals(mAccount.pin)) { return; } mAccount.pin = getString(R.string.empty_pin); mUserAdapter.notifyDataSetChanged(); } }, HOTP_DISPLAY_TIMEOUT); } /** * Gets the position in the account list of the account this listener is associated with. * * @return {@code 0}-based position or {@code -1} if the account is not in the list. */ private int findAccountPositionInList() { for (int i = 0, len = mUsers.length; i < len; i++) { if (mUsers[i] == mAccount) { return i; } } return -1; } } /** * Displays the list of users and the current OTP values. * * @author adhintz@google.com (Drew Hintz) */ private class PinListAdapter extends ArrayAdapter<PinInfo> { public PinListAdapter(Context context, int userRowId, PinInfo[] items) { super(context, userRowId, items); } /** * Displays the user and OTP for the specified position. For HOTP, displays * the button for generating the next OTP value; for TOTP, displays the countdown indicator. */ @Override public View getView(int position, View convertView, ViewGroup parent){ LayoutInflater inflater = getLayoutInflater(); PinInfo currentPin = getItem(position); View row; if (convertView != null) { // Reuse an existing view row = convertView; } else { // Create a new view row = inflater.inflate(R.layout.user_row, null); } TextView pinView = (TextView) row.findViewById(R.id.pin_value); TextView userView = (TextView) row.findViewById(R.id.current_user); View buttonView = row.findViewById(R.id.next_otp); CountdownIndicator countdownIndicator = (CountdownIndicator) row.findViewById(R.id.countdown_icon); if (currentPin.isHotp) { buttonView.setVisibility(View.VISIBLE); buttonView.setEnabled(currentPin.hotpCodeGenerationAllowed); ((ViewGroup) row).setDescendantFocusability( ViewGroup.FOCUS_BLOCK_DESCENDANTS); // makes long press work NextOtpButtonListener clickListener = new NextOtpButtonListener(currentPin); buttonView.setOnClickListener(clickListener); row.setTag(clickListener); countdownIndicator.setVisibility(View.GONE); } else { // TOTP, so no button needed buttonView.setVisibility(View.GONE); buttonView.setOnClickListener(null); row.setTag(null); countdownIndicator.setVisibility(View.VISIBLE); countdownIndicator.setPhase(mTotpCountdownPhase); } if (getString(R.string.empty_pin).equals(currentPin.pin)) { pinView.setTextScaleX(PIN_TEXT_SCALEX_UNDERSCORE); // smaller gap between underscores } else { pinView.setTextScaleX(PIN_TEXT_SCALEX_NORMAL); } pinView.setText(currentPin.pin); userView.setText(currentPin.user); return row; } } private void importDataFromOldAppIfNecessary() { if (mDataImportInProgress) { return; } mDataImportInProgress = true; DependencyInjector.getDataImportController().start(this, new ImportController.Listener() { @Override public void onOldAppUninstallSuggested(Intent uninstallIntent) { if (isFinishing()) { return; } mOldAppUninstallIntent = uninstallIntent; showDialog(DIALOG_ID_UNINSTALL_OLD_APP); } @Override public void onDataImported() { if (isFinishing()) { return; } refreshUserList(true); DependencyInjector.getOptionalFeatures().onDataImportedFromOldApp( AuthenticatorActivity.this); } @Override public void onFinished() { if (isFinishing()) { return; } mDataImportInProgress = false; } }); } /** * Parameters to the {@link AuthenticatorActivity#DIALOG_ID_SAVE_KEY} dialog. */ private static class SaveKeyDialogParams implements Serializable { private final String user; private final String secret; private final OtpType type; private final Integer counter; private SaveKeyDialogParams(String user, String secret, OtpType type, Integer counter) { this.user = user; this.secret = secret; this.type = type; this.counter = counter; } } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/AuthenticatorActivity.java
Java
asf20
44,301
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.dataimport; import com.google.android.apps.authenticator.AccountDb; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Imports the contents of {@link AccountDb} and the key material and settings from a * {@link Bundle}. * * @author klyubin@google.com (Alex Klyubin) */ public class Importer { private static final String LOG_TAG = Importer.class.getSimpleName(); // @VisibleForTesting static final String KEY_ACCOUNTS = "accountDb"; // @VisibleForTesting static final String KEY_PREFERENCES = "preferences"; // @VisibleForTesting static final String KEY_NAME = "name"; // @VisibleForTesting static final String KEY_ENCODED_SECRET = "encodedSecret"; // @VisibleForTesting static final String KEY_TYPE = "type"; // @VisibleForTesting static final String KEY_COUNTER = "counter"; /** * Imports the contents of the provided {@link Bundle} into the provided {@link AccountDb} and * {@link SharedPreferences}. Does not overwrite existing records in the database. * * @param bundle source bundle. * @param accountDb destination {@link AccountDb}. * @param preferences destination preferences or {@code null} for none. */ public void importFromBundle(Bundle bundle, AccountDb accountDb, SharedPreferences preferences) { Bundle accountDbBundle = bundle.getBundle(KEY_ACCOUNTS); if (accountDbBundle != null) { importAccountDbFromBundle(accountDbBundle, accountDb); } if (preferences != null) { Bundle preferencesBundle = bundle.getBundle(KEY_PREFERENCES); if (preferencesBundle != null) { importPreferencesFromBundle(preferencesBundle, preferences); } } } private void importAccountDbFromBundle(Bundle bundle, AccountDb accountDb) { // Each account is stored in a Bundle whose key is a string representing the ordinal (integer) // position of the account in the database. List<String> sortedAccountBundleKeys = new ArrayList<String>(bundle.keySet()); Collections.sort(sortedAccountBundleKeys, new IntegerStringComparator()); int importedAccountCount = 0; for (String accountBundleKey : sortedAccountBundleKeys) { Bundle accountBundle = bundle.getBundle(accountBundleKey); String name = accountBundle.getString(KEY_NAME); if (name == null) { Log.w(LOG_TAG, "Skipping account #" + accountBundleKey + ": name missing"); continue; } if (accountDb.nameExists(name)) { // Don't log account name here and below because it's considered PII Log.w(LOG_TAG, "Skipping account #" + accountBundleKey + ": already configured"); continue; } String encodedSecret = accountBundle.getString(KEY_ENCODED_SECRET); if (encodedSecret == null) { Log.w(LOG_TAG, "Skipping account #" + accountBundleKey + ": secret missing"); continue; } String typeString = accountBundle.getString(KEY_TYPE); AccountDb.OtpType type; if ("totp".equals(typeString)) { type = AccountDb.OtpType.TOTP; } else if ("hotp".equals(typeString)) { type = AccountDb.OtpType.HOTP; } else { Log.w(LOG_TAG, "Skipping account #" + accountBundleKey + ": unsupported type: \"" + typeString + "\""); continue; } Integer counter = accountBundle.containsKey(KEY_COUNTER) ? accountBundle.getInt(KEY_COUNTER) : null; if (counter == null) { if (type == AccountDb.OtpType.HOTP) { Log.w(LOG_TAG, "Skipping account #" + accountBundleKey + ": counter missing"); continue; } else { // TOTP counter = AccountDb.DEFAULT_HOTP_COUNTER; } } accountDb.update(name, encodedSecret, name, type, counter); importedAccountCount++; } Log.i(LOG_TAG, "Imported " + importedAccountCount + " accounts"); } private static class IntegerStringComparator implements Comparator<String> { @Override public int compare(String lhs, String rhs) { int lhsValue = Integer.parseInt(lhs); int rhsValue = Integer.parseInt(rhs); return lhsValue - rhsValue; } } private boolean tryImportPreferencesFromBundle(Bundle bundle, SharedPreferences preferences) { SharedPreferences.Editor preferencesEditor = preferences.edit(); for (String key : bundle.keySet()) { Object value = bundle.get(key); if (value instanceof Boolean) { preferencesEditor.putBoolean(key, (Boolean) value); } else if (value instanceof Float) { preferencesEditor.putFloat(key, (Float) value); } else if (value instanceof Integer) { preferencesEditor.putInt(key, (Integer) value); } else if (value instanceof Long) { preferencesEditor.putLong(key, (Long) value); } else if (value instanceof String) { preferencesEditor.putString(key, (String) value); } else { // Ignore: can only be Set<String> at the moment (API Level 11+), which we don't use anyway. } } return preferencesEditor.commit(); } private void importPreferencesFromBundle(Bundle bundle, SharedPreferences preferences) { // Retry until the operation succeeds while (!tryImportPreferencesFromBundle(bundle, preferences)) {} } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/dataimport/Importer.java
Java
asf20
6,086
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.dataimport; import android.content.Context; import android.content.Intent; /** * Controller for importing data from the "old" app. * * @author klyubin@google.com (Alex Klyubin) */ public interface ImportController { public interface Listener { void onDataImported(); void onOldAppUninstallSuggested(Intent uninstallIntent); void onFinished(); } void start(Context context, Listener listener); }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/dataimport/ImportController.java
Java
asf20
1,083
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.dataimport; import com.google.android.apps.authenticator.dataexport.IExportServiceV2; import com.google.android.apps.authenticator.testability.DependencyInjector; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; /** * @author klyubin@google.com (Alex Klyubin) */ public class ExportServiceBasedImportController implements ImportController { private static final String OLD_APP_PACKAGE_NAME = "com.google.android.apps.authenticator"; private static final String OLD_APP_EXPORT_SERVICE_CLASS_NAME = OLD_APP_PACKAGE_NAME + ".dataexport.ExportServiceV2"; private static final String LOG_TAG = "ImportController"; public ExportServiceBasedImportController() {} @Override public void start(Context context, Listener listener) { int oldAppVersionCode = getOldAppVersionCode(); if (oldAppVersionCode == -1) { Log.d(LOG_TAG, "Skipping importing because the old app is not installed"); notifyListenerFinished(listener); return; } Intent intent = new Intent(); intent.setComponent(new ComponentName(OLD_APP_PACKAGE_NAME, OLD_APP_EXPORT_SERVICE_CLASS_NAME)); ServiceConnection serviceConnection = new ExportServiceConnection(context, listener); boolean bound = context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE); if (!bound) { Log.i(LOG_TAG, "Not importing because the old app is too old (" + oldAppVersionCode + ") and can't export"); context.unbindService(serviceConnection); notifyListenerFinished(listener); return; } // The flow continues in ExportServiceConnection.onServiceConnected which is invoked // later on by the OS once the connection with the ExportService has been established. } private class ExportServiceConnection implements ServiceConnection { private final Context mContext; private final Listener mListener; private ExportServiceConnection(Context context, Listener listener) { mContext = context; mListener = listener; } @Override public void onServiceConnected(ComponentName name, IBinder service) { try { IExportServiceV2 exportService; try { exportService = IExportServiceV2.Stub.asInterface(service); } catch (SecurityException e) { Log.w(LOG_TAG, "Failed to obtain export interface: " + e); return; } Bundle importedData; try { importedData = exportService.getData(); } catch (SecurityException e) { Log.w(LOG_TAG, "Failed to obtain data: " + e); return; } catch (RemoteException e) { Log.w(LOG_TAG, "Failed to obtain data: " + e); return; } if (importedData != null) { new Importer().importFromBundle( importedData, DependencyInjector.getAccountDb(), DependencyInjector.getOptionalFeatures() .getSharedPreferencesForDataImportFromOldApp(mContext)); Log.i(LOG_TAG, "Successfully imported data from the old app"); notifyListenerDataImported(mListener); try { exportService.onImportSucceeded(); } catch (SecurityException e) { Log.w(LOG_TAG, "Failed to notify old app that import succeeded: " + e); return; } catch (RemoteException e) { Log.w(LOG_TAG, "Failed to notify old app that import succeeded: " + e); return; } notifyListenerUninstallOldAppSuggested(mListener); } else { Log.w(LOG_TAG, "Old app returned null data"); } } finally { // The try-catch below is to avoid crashing when the unbind operation fails. Occasionally // the operation throws an IllegalArgumentException because the connection has been closed // by the OS/framework. try { mContext.unbindService(this); } catch (Exception e) { Log.w(LOG_TAG, "Failed to unbind service", e); } finally { notifyListenerFinished(mListener); } } } @Override public void onServiceDisconnected(ComponentName name) {} } /** * Gets the version code of the old app. * * @return version code or {@code -1} if the old app is not installed. */ private static int getOldAppVersionCode() { try { PackageInfo oldAppPackageInfo = DependencyInjector.getPackageManager().getPackageInfo( OLD_APP_PACKAGE_NAME, 0); return oldAppPackageInfo.versionCode; } catch (PackageManager.NameNotFoundException e) { return -1; } } private static void notifyListenerDataImported(Listener listener) { if (listener != null) { listener.onDataImported(); } } private static void notifyListenerUninstallOldAppSuggested(Listener listener) { if (listener != null) { listener.onOldAppUninstallSuggested( new Intent(Intent.ACTION_DELETE, Uri.parse("package:" + OLD_APP_PACKAGE_NAME))); } } private static void notifyListenerFinished(Listener listener) { if (listener != null) { listener.onFinished(); } } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/dataimport/ExportServiceBasedImportController.java
Java
asf20
6,138
/* * Copyright 2010 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import com.google.android.apps.authenticator.AccountDb.OtpType; import com.google.android.apps.authenticator.PasscodeGenerator.Signer; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.util.Collection; /** * Class containing implementation of HOTP/TOTP. * Generates OTP codes for one or more accounts. * @author Steve Weis (sweis@google.com) * @author Cem Paya (cemp@google.com) */ public class OtpProvider implements OtpSource { private static final int PIN_LENGTH = 6; // HOTP or TOTP private static final int REFLECTIVE_PIN_LENGTH = 9; // ROTP @Override public int enumerateAccounts(Collection<String> result) { return mAccountDb.getNames(result); } @Override public String getNextCode(String accountName) throws OtpSourceException { return getCurrentCode(accountName, null); } // This variant is used when an additional challenge, such as URL or // transaction details, are included in the OTP request. // The additional string is appended to standard HOTP/TOTP state before // applying the MAC function. @Override public String respondToChallenge(String accountName, String challenge) throws OtpSourceException { if (challenge == null) { return getCurrentCode(accountName, null); } try { byte[] challengeBytes = challenge.getBytes("UTF-8"); return getCurrentCode(accountName, challengeBytes); } catch (UnsupportedEncodingException e) { return ""; } } @Override public TotpCounter getTotpCounter() { return mTotpCounter; } @Override public TotpClock getTotpClock() { return mTotpClock; } private String getCurrentCode(String username, byte[] challenge) throws OtpSourceException { // Account name is required. if (username == null) { throw new OtpSourceException("No account name"); } OtpType type = mAccountDb.getType(username); String secret = getSecret(username); long otp_state = 0; if (type == OtpType.TOTP) { // For time-based OTP, the state is derived from clock. otp_state = mTotpCounter.getValueAtTime(Utilities.millisToSeconds(mTotpClock.currentTimeMillis())); } else if (type == OtpType.HOTP){ // For counter-based OTP, the state is obtained by incrementing stored counter. mAccountDb.incrementCounter(username); Integer counter = mAccountDb.getCounter(username); otp_state = counter.longValue(); } return computePin(secret, otp_state, challenge); } public OtpProvider(AccountDb accountDb, TotpClock totpClock) { this(DEFAULT_INTERVAL, accountDb, totpClock); } public OtpProvider(int interval, AccountDb accountDb, TotpClock totpClock) { mAccountDb = accountDb; mTotpCounter = new TotpCounter(interval); mTotpClock = totpClock; } /** * Computes the one-time PIN given the secret key. * * @param secret the secret key * @param otp_state current token state (counter or time-interval) * @param challenge optional challenge bytes to include when computing passcode. * @return the PIN */ private String computePin(String secret, long otp_state, byte[] challenge) throws OtpSourceException { if (secret == null || secret.length() == 0) { throw new OtpSourceException("Null or empty secret"); } try { Signer signer = AccountDb.getSigningOracle(secret); PasscodeGenerator pcg = new PasscodeGenerator(signer, (challenge == null) ? PIN_LENGTH : REFLECTIVE_PIN_LENGTH); return (challenge == null) ? pcg.generateResponseCode(otp_state) : pcg.generateResponseCode(otp_state, challenge); } catch (GeneralSecurityException e) { throw new OtpSourceException("Crypto failure", e); } } /** * Reads the secret key that was saved on the phone. * @param user Account name identifying the user. * @return the secret key as base32 encoded string. */ String getSecret(String user) { return mAccountDb.getSecret(user); } /** Default passcode timeout period (in seconds) */ public static final int DEFAULT_INTERVAL = 30; private final AccountDb mAccountDb; /** Counter for time-based OTPs (TOTP). */ private final TotpCounter mTotpCounter; /** Clock input for time-based OTPs (TOTP). */ private final TotpClock mTotpClock; }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/OtpProvider.java
Java
asf20
5,037
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import com.google.android.apps.authenticator2.R; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.RectF; import android.util.AttributeSet; import android.view.View; /** * Circular countdown indicator. The indicator is a filled arc which starts as a full circle ({@code * 360} degrees) and shrinks to {@code 0} degrees the less time is remaining. * @author klyubin@google.com (Alex Klyubin) */ public class CountdownIndicator extends View { private final Paint mRemainingSectorPaint; private final Paint mBorderPaint; private static final int DEFAULT_COLOR = 0xff3060c0; /** * Countdown phase starting with {@code 1} when a full cycle is remaining and shrinking to * {@code 0} the closer the countdown is to zero. */ private double mPhase; public CountdownIndicator(Context context) { this(context, null); } public CountdownIndicator(Context context, AttributeSet attrs) { super(context, attrs); int color = DEFAULT_COLOR; Resources.Theme theme = context.getTheme(); TypedArray appearance = theme.obtainStyledAttributes( attrs, R.styleable.CountdownIndicator, 0, 0); if (appearance != null) { int n = appearance.getIndexCount(); for (int i = 0; i < n; i++) { int attr = appearance.getIndex(i); switch (attr) { case R.styleable.CountdownIndicator_color: color = appearance.getColor(attr, DEFAULT_COLOR); break; } } } mBorderPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mBorderPaint.setStrokeWidth(0); // hairline mBorderPaint.setStyle(Style.STROKE); mBorderPaint.setColor(color); mRemainingSectorPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mRemainingSectorPaint.setColor(mBorderPaint.getColor()); } @Override protected void onDraw(Canvas canvas) { float remainingSectorSweepAngle = (float) (mPhase * 360); float remainingSectorStartAngle = 270 - remainingSectorSweepAngle; // Draw the sector/filled arc // We need to leave the leftmost column and the topmost row out of the drawingRect because // in anti-aliased mode drawArc and drawOval use these areas for some reason. RectF drawingRect = new RectF(1, 1, getWidth() - 1, getHeight() - 1); if (remainingSectorStartAngle < 360) { canvas.drawArc( drawingRect, remainingSectorStartAngle, remainingSectorSweepAngle, true, mRemainingSectorPaint); } else { // 360 degrees is equivalent to 0 degrees for drawArc, hence the drawOval below. canvas.drawOval(drawingRect, mRemainingSectorPaint); } // Draw the outer border canvas.drawOval(drawingRect, mBorderPaint); } /** * Sets the phase of this indicator. * * @param phase phase {@code [0, 1]}: {@code 1} when the maximum amount of time is remaining, * {@code 0} when no time is remaining. */ public void setPhase(double phase) { if ((phase < 0) || (phase > 1)) { throw new IllegalArgumentException("phase: " + phase); } mPhase = phase; invalidate(); } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/CountdownIndicator.java
Java
asf20
3,933
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import com.google.android.apps.authenticator.testability.DependencyInjector; import android.app.Application; /** * Authenticator application which is one of the first things instantiated when our process starts. * At the moment the only reason for the existence of this class is to initialize * {@link DependencyInjector} with the application context so that the class can (later) instantiate * the various objects it owns. * * Also restrict UNIX file permissions on application's persistent data directory to owner * (this app's UID) only. * * @author klyubin@google.com (Alex Klyubin) */ public class AuthenticatorApplication extends Application { @Override public void onCreate() { super.onCreate(); // Try to restrict data dir file permissions to owner (this app's UID) only. This mitigates the // security vulnerability where SQLite database transaction journals are world-readable. // NOTE: This also prevents all files in the data dir from being world-accessible, which is fine // because this application does not need world-accessible files. try { FileUtilities.restrictAccessToOwnerOnly( getApplicationContext().getApplicationInfo().dataDir); } catch (Throwable e) { // Ignore this exception and don't log anything to avoid attracting attention to this fix } // During test runs the injector may have been configured already. Thus we take care to avoid // overwriting any existing configuration here. DependencyInjector.configureForProductionIfNotConfigured(getApplicationContext()); } @Override public void onTerminate() { DependencyInjector.close(); super.onTerminate(); } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/AuthenticatorApplication.java
Java
asf20
2,355
/* * Copyright 2010 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import com.google.android.apps.authenticator.Base32String.DecodingException; import com.google.android.apps.authenticator.PasscodeGenerator.Signer; import android.content.ContentValues; import android.content.Context; import android.content.pm.PackageManager; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.os.Process; import android.util.Log; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collection; import java.util.Locale; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; /** * A database of email addresses and secret values * * @author sweis@google.com (Steve Weis) */ public class AccountDb { public static final Integer DEFAULT_HOTP_COUNTER = 0; public static final String GOOGLE_CORP_ACCOUNT_NAME = "Google Internal 2Factor"; private static final String ID_COLUMN = "_id"; private static final String EMAIL_COLUMN = "email"; private static final String SECRET_COLUMN = "secret"; private static final String COUNTER_COLUMN = "counter"; private static final String TYPE_COLUMN = "type"; // @VisibleForTesting static final String PROVIDER_COLUMN = "provider"; // @VisibleForTesting static final String TABLE_NAME = "accounts"; // @VisibleForTesting static final String PATH = "databases"; private static final String TABLE_INFO_COLUMN_NAME_COLUMN = "name"; private static final int PROVIDER_UNKNOWN = 0; private static final int PROVIDER_GOOGLE = 1; // @VisibleForTesting SQLiteDatabase mDatabase; private static final String LOCAL_TAG = "GoogleAuthenticator.AccountDb"; /** * Types of secret keys. */ public enum OtpType { // must be the same as in res/values/strings.xml:type TOTP (0), // time based HOTP (1); // counter based public final Integer value; // value as stored in SQLite database OtpType(Integer value) { this.value = value; } public static OtpType getEnum(Integer i) { for (OtpType type : OtpType.values()) { if (type.value.equals(i)) { return type; } } return null; } } public AccountDb(Context context) { mDatabase = openDatabase(context); // Create the table if it doesn't exist mDatabase.execSQL(String.format( "CREATE TABLE IF NOT EXISTS %s" + " (%s INTEGER PRIMARY KEY, %s TEXT NOT NULL, %s TEXT NOT NULL, " + " %s INTEGER DEFAULT %s, %s INTEGER, %s INTEGER DEFAULT %s)", TABLE_NAME, ID_COLUMN, EMAIL_COLUMN, SECRET_COLUMN, COUNTER_COLUMN, DEFAULT_HOTP_COUNTER, TYPE_COLUMN, PROVIDER_COLUMN, PROVIDER_UNKNOWN)); Collection<String> tableColumnNames = listTableColumnNamesLowerCase(); if (!tableColumnNames.contains(PROVIDER_COLUMN.toLowerCase(Locale.US))) { // Migrate from old schema where the PROVIDER_COLUMN wasn't there mDatabase.execSQL(String.format( "ALTER TABLE %s ADD COLUMN %s INTEGER DEFAULT %s", TABLE_NAME, PROVIDER_COLUMN, PROVIDER_UNKNOWN)); } } /* * Tries three times to open database before throwing AccountDbOpenException. */ private SQLiteDatabase openDatabase(Context context) { for (int count = 0; true; count++) { try { return context.openOrCreateDatabase(PATH, Context.MODE_PRIVATE, null); } catch (SQLiteException e) { if (count < 2) { continue; } else { throw new AccountDbOpenException("Failed to open AccountDb database in three tries.\n" + getAccountDbOpenFailedErrorString(context), e); } } } } private String getAccountDbOpenFailedErrorString(Context context) { String dataPackageDir = context.getApplicationInfo().dataDir; String databaseDirPathname = context.getDatabasePath(PATH).getParent(); String databasePathname = context.getDatabasePath(PATH).getAbsolutePath(); String[] dirsToStat = new String[] {dataPackageDir, databaseDirPathname, databasePathname}; StringBuilder error = new StringBuilder(); int myUid = Process.myUid(); for (String directory : dirsToStat) { try { FileUtilities.StatStruct stat = FileUtilities.getStat(directory); String ownerUidName = null; try { if (stat.uid == 0) { ownerUidName = "root"; } else { PackageManager packageManager = context.getPackageManager(); ownerUidName = (packageManager != null) ? packageManager.getNameForUid(stat.uid) : null; } } catch (Exception e) { ownerUidName = e.toString(); } error.append(directory + " directory stat (my UID: " + myUid); if (ownerUidName == null) { error.append("): "); } else { error.append(", dir owner UID name: " + ownerUidName + "): "); } error.append(stat.toString() + "\n"); } catch (IOException e) { error.append(directory + " directory stat threw an exception: " + e + "\n"); } } return error.toString(); } /** * Closes this database and releases any system resources held. */ public void close() { mDatabase.close(); } /** * Lists the names of all the columns in the specified table. */ // @VisibleForTesting static Collection<String> listTableColumnNamesLowerCase( SQLiteDatabase database, String tableName) { Cursor cursor = database.rawQuery(String.format("PRAGMA table_info(%s)", tableName), new String[0]); Collection<String> result = new ArrayList<String>(); try { if (cursor != null) { int nameColumnIndex = cursor.getColumnIndexOrThrow(TABLE_INFO_COLUMN_NAME_COLUMN); while (cursor.moveToNext()) { result.add(cursor.getString(nameColumnIndex).toLowerCase(Locale.US)); } } return result; } finally { tryCloseCursor(cursor); } } /** * Lists the names of all the columns in the accounts table. */ private Collection<String> listTableColumnNamesLowerCase() { return listTableColumnNamesLowerCase(mDatabase, TABLE_NAME); } /* * deleteAllData() will remove all rows. Useful for testing. */ public boolean deleteAllData() { mDatabase.delete(AccountDb.TABLE_NAME, null, null); return true; } public boolean nameExists(String email) { Cursor cursor = getAccount(email); try { return !cursorIsEmpty(cursor); } finally { tryCloseCursor(cursor); } } public String getSecret(String email) { Cursor cursor = getAccount(email); try { if (!cursorIsEmpty(cursor)) { cursor.moveToFirst(); return cursor.getString(cursor.getColumnIndex(SECRET_COLUMN)); } } finally { tryCloseCursor(cursor); } return null; } static Signer getSigningOracle(String secret) { try { byte[] keyBytes = decodeKey(secret); final Mac mac = Mac.getInstance("HMACSHA1"); mac.init(new SecretKeySpec(keyBytes, "")); // Create a signer object out of the standard Java MAC implementation. return new Signer() { @Override public byte[] sign(byte[] data) { return mac.doFinal(data); } }; } catch (DecodingException error) { Log.e(LOCAL_TAG, error.getMessage()); } catch (NoSuchAlgorithmException error) { Log.e(LOCAL_TAG, error.getMessage()); } catch (InvalidKeyException error) { Log.e(LOCAL_TAG, error.getMessage()); } return null; } private static byte[] decodeKey(String secret) throws DecodingException { return Base32String.decode(secret); } public Integer getCounter(String email) { Cursor cursor = getAccount(email); try { if (!cursorIsEmpty(cursor)) { cursor.moveToFirst(); return cursor.getInt(cursor.getColumnIndex(COUNTER_COLUMN)); } } finally { tryCloseCursor(cursor); } return null; } void incrementCounter(String email) { ContentValues values = new ContentValues(); values.put(EMAIL_COLUMN, email); Integer counter = getCounter(email); values.put(COUNTER_COLUMN, counter + 1); mDatabase.update(TABLE_NAME, values, whereClause(email), null); } public OtpType getType(String email) { Cursor cursor = getAccount(email); try { if (!cursorIsEmpty(cursor)) { cursor.moveToFirst(); Integer value = cursor.getInt(cursor.getColumnIndex(TYPE_COLUMN)); return OtpType.getEnum(value); } } finally { tryCloseCursor(cursor); } return null; } void setType(String email, OtpType type) { ContentValues values = new ContentValues(); values.put(EMAIL_COLUMN, email); values.put(TYPE_COLUMN, type.value); mDatabase.update(TABLE_NAME, values, whereClause(email), null); } public boolean isGoogleAccount(String email) { Cursor cursor = getAccount(email); try { if (!cursorIsEmpty(cursor)) { cursor.moveToFirst(); if (cursor.getInt(cursor.getColumnIndex(PROVIDER_COLUMN)) == PROVIDER_GOOGLE) { // The account is marked as source: Google return true; } // The account is from an unknown source. Could be a Google account added by scanning // a QR code or by manually entering a key String emailLowerCase = email.toLowerCase(Locale.US); return(emailLowerCase.endsWith("@gmail.com")) || (emailLowerCase.endsWith("@google.com")) || (email.equals(GOOGLE_CORP_ACCOUNT_NAME)); } } finally { tryCloseCursor(cursor); } return false; } /** * Finds the Google corp account in this database. * * @return the name of the account if it is present or {@code null} if the account does not exist. */ public String findGoogleCorpAccount() { return nameExists(GOOGLE_CORP_ACCOUNT_NAME) ? GOOGLE_CORP_ACCOUNT_NAME : null; } private static String whereClause(String email) { return EMAIL_COLUMN + " = " + DatabaseUtils.sqlEscapeString(email); } public void delete(String email) { mDatabase.delete(TABLE_NAME, whereClause(email), null); } /** * Save key to database, creating a new user entry if necessary. * @param email the user email address. When editing, the new user email. * @param secret the secret key. * @param oldEmail If editing, the original user email, otherwise null. * @param type hotp vs totp * @param counter only important for the hotp type */ public void update(String email, String secret, String oldEmail, OtpType type, Integer counter) { update(email, secret, oldEmail, type, counter, null); } /** * Save key to database, creating a new user entry if necessary. * @param email the user email address. When editing, the new user email. * @param secret the secret key. * @param oldEmail If editing, the original user email, otherwise null. * @param type hotp vs totp * @param counter only important for the hotp type * @param googleAccount whether the key is for a Google account or {@code null} to preserve * the previous value (or use a default if adding a key). */ public void update(String email, String secret, String oldEmail, OtpType type, Integer counter, Boolean googleAccount) { ContentValues values = new ContentValues(); values.put(EMAIL_COLUMN, email); values.put(SECRET_COLUMN, secret); values.put(TYPE_COLUMN, type.ordinal()); values.put(COUNTER_COLUMN, counter); if (googleAccount != null) { values.put( PROVIDER_COLUMN, (googleAccount.booleanValue()) ? PROVIDER_GOOGLE : PROVIDER_UNKNOWN); } int updated = mDatabase.update(TABLE_NAME, values, whereClause(oldEmail), null); if (updated == 0) { mDatabase.insert(TABLE_NAME, null, values); } } private Cursor getNames() { return mDatabase.query(TABLE_NAME, null, null, null, null, null, null, null); } private Cursor getAccount(String email) { return mDatabase.query(TABLE_NAME, null, EMAIL_COLUMN + "= ?", new String[] {email}, null, null, null); } /** * Returns true if the cursor is null, or contains no rows. */ private static boolean cursorIsEmpty(Cursor c) { return c == null || c.getCount() == 0; } /** * Closes the cursor if it is not null and not closed. */ private static void tryCloseCursor(Cursor c) { if (c != null && !c.isClosed()) { c.close(); } } /** * Get list of all account names. * @param result Collection of strings-- account names are appended, without * clearing this collection on entry. * @return Number of accounts added to the output parameter. */ public int getNames(Collection<String> result) { Cursor cursor = getNames(); try { if (cursorIsEmpty(cursor)) return 0; int nameCount = cursor.getCount(); int index = cursor.getColumnIndex(AccountDb.EMAIL_COLUMN); for (int i = 0; i < nameCount; ++i) { cursor.moveToPosition(i); String username = cursor.getString(index); result.add(username); } return nameCount; } finally { tryCloseCursor(cursor); } } private static class AccountDbOpenException extends RuntimeException { public AccountDbOpenException(String message, Exception e) { super(message, e); } } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/AccountDb.java
Java
asf20
14,285
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.howitworks; import com.google.android.apps.authenticator.wizard.WizardPageActivity; import com.google.android.apps.authenticator2.R; import android.os.Bundle; import java.io.Serializable; /** * The page of the "How it works" that explains that occasionally the user might need to enter a * verification code generated by this application. The user simply needs to click the Next button * to go to the next page. * * @author klyubin@google.com (Alex Klyubin) */ public class IntroEnterCodeActivity extends WizardPageActivity<Serializable> { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setPageContentView(R.layout.howitworks_enter_code); setTextViewHtmlFromResource(R.id.details, R.string.howitworks_page_enter_code_details); } @Override protected void onRightButtonPressed() { startPageActivity(IntroVerifyDeviceActivity.class); } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/howitworks/IntroEnterCodeActivity.java
Java
asf20
1,591
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.howitworks; import com.google.android.apps.authenticator.wizard.WizardPageActivity; import com.google.android.apps.authenticator2.R; import android.os.Bundle; import java.io.Serializable; /** * The start page of the "How it works" flow that explains that in addition to entering the password * during sign in a verification code may be required. The user simply needs to click the Next * button to go to the next page. * * @author klyubin@google.com (Alex Klyubin) */ public class IntroEnterPasswordActivity extends WizardPageActivity<Serializable> { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setPageContentView(R.layout.howitworks_enter_password); setTextViewHtmlFromResource(R.id.details, R.string.howitworks_page_enter_password_details); } @Override protected void onRightButtonPressed() { startPageActivity(IntroEnterCodeActivity.class); } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/howitworks/IntroEnterPasswordActivity.java
Java
asf20
1,607
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.howitworks; import com.google.android.apps.authenticator.wizard.WizardPageActivity; import com.google.android.apps.authenticator2.R; import android.os.Bundle; import java.io.Serializable; /** * The page of the "How it works" flow that explains that the user can ask Google not to * ask for verification codes every time the user signs in from a verified computer or device. * The user needs to click the Exit button to exit the flow. * * @author klyubin@google.com (Alex Klyubin) */ public class IntroVerifyDeviceActivity extends WizardPageActivity<Serializable> { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setPageContentView(R.layout.howitworks_verify_device); setTextViewHtmlFromResource(R.id.details, R.string.howitworks_page_verify_device_details); mRightButton.setText(R.string.button_exit_howitworks_flow); } @Override protected void onRightButtonPressed() { exitWizard(); } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/howitworks/IntroVerifyDeviceActivity.java
Java
asf20
1,649
/* * Copyright 2009 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import java.io.ByteArrayInputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import javax.crypto.Mac; /** * An implementation of the HOTP generator specified by RFC 4226. Generates * short passcodes that may be used in challenge-response protocols or as * timeout passcodes that are only valid for a short period. * * The default passcode is a 6-digit decimal code. The maximum passcode length is 9 digits. * * @author sweis@google.com (Steve Weis) * */ public class PasscodeGenerator { private static final int MAX_PASSCODE_LENGTH = 9; /** Default time interval */ public static final int INTERVAL = OtpProvider.DEFAULT_INTERVAL; /** Default decimal passcode length */ private static final int PASS_CODE_LENGTH = 6; /** The number of previous and future intervals to check */ private static final int ADJACENT_INTERVALS = 1; private final Signer signer; private final int codeLength; /** * Using an interface to allow us to inject different signature * implementations. */ interface Signer { /** * @param data Preimage to sign, represented as sequence of arbitrary bytes * @return Signature as sequence of bytes. * @throws GeneralSecurityException */ byte[] sign(byte[] data) throws GeneralSecurityException; } /** * @param mac A {@link Mac} used to generate passcodes */ public PasscodeGenerator(Mac mac) { this(mac, PASS_CODE_LENGTH); } public PasscodeGenerator(Signer signer) { this(signer, PASS_CODE_LENGTH); } /** * @param mac A {@link Mac} used to generate passcodes * @param passCodeLength The length of the decimal passcode */ public PasscodeGenerator(final Mac mac, int passCodeLength) { this(new Signer() { @Override public byte[] sign(byte[] data){ return mac.doFinal(data); } }, passCodeLength); } public PasscodeGenerator(Signer signer, int passCodeLength) { if ((passCodeLength < 0) || (passCodeLength > MAX_PASSCODE_LENGTH)) { throw new IllegalArgumentException( "PassCodeLength must be between 1 and " + MAX_PASSCODE_LENGTH + " digits."); } this.signer = signer; this.codeLength = passCodeLength; } private String padOutput(int value) { String result = Integer.toString(value); for (int i = result.length(); i < codeLength; i++) { result = "0" + result; } return result; } /** * @param state 8-byte integer value representing internal OTP state. * @return A decimal response code * @throws GeneralSecurityException If a JCE exception occur */ public String generateResponseCode(long state) throws GeneralSecurityException { byte[] value = ByteBuffer.allocate(8).putLong(state).array(); return generateResponseCode(value); } /** * @param state 8-byte integer value representing internal OTP state. * @param challenge Optional challenge as array of bytes. * @return A decimal response code * @throws GeneralSecurityException If a JCE exception occur */ public String generateResponseCode(long state, byte[] challenge) throws GeneralSecurityException { if (challenge == null) { return generateResponseCode(state); } else { // Allocate space for combination and store. byte value[] = ByteBuffer.allocate(8 + challenge.length) .putLong(state) // Write out OTP state .put(challenge, 0, challenge.length) // Concatenate with challenge. .array(); return generateResponseCode(value); } } /** * @param challenge An arbitrary byte array used as a challenge * @return A decimal response code * @throws GeneralSecurityException If a JCE exception occur */ public String generateResponseCode(byte[] challenge) throws GeneralSecurityException { byte[] hash = signer.sign(challenge); // Dynamically truncate the hash // OffsetBits are the low order bits of the last byte of the hash int offset = hash[hash.length - 1] & 0xF; // Grab a positive integer value starting at the given offset. int truncatedHash = hashToInt(hash, offset) & 0x7FFFFFFF; int pinValue = truncatedHash % (int) Math.pow(10, codeLength); return padOutput(pinValue); } /** * Grabs a positive integer value from the input array starting at * the given offset. * @param bytes the array of bytes * @param start the index into the array to start grabbing bytes * @return the integer constructed from the four bytes in the array */ private int hashToInt(byte[] bytes, int start) { DataInput input = new DataInputStream( new ByteArrayInputStream(bytes, start, bytes.length - start)); int val; try { val = input.readInt(); } catch (IOException e) { throw new IllegalStateException(e); } return val; } /** * @param challenge A challenge to check a response against * @param response A response to verify * @return True if the response is valid */ public boolean verifyResponseCode(long challenge, String response) throws GeneralSecurityException { String expectedResponse = generateResponseCode(challenge, null); return expectedResponse.equals(response); } /** * Verify a timeout code. The timeout code will be valid for a time * determined by the interval period and the number of adjacent intervals * checked. * * @param timeoutCode The timeout code * @return True if the timeout code is valid */ public boolean verifyTimeoutCode(long currentInterval, String timeoutCode) throws GeneralSecurityException { return verifyTimeoutCode(timeoutCode, currentInterval, ADJACENT_INTERVALS, ADJACENT_INTERVALS); } /** * Verify a timeout code. The timeout code will be valid for a time * determined by the interval period and the number of adjacent intervals * checked. * * @param timeoutCode The timeout code * @param pastIntervals The number of past intervals to check * @param futureIntervals The number of future intervals to check * @return True if the timeout code is valid */ public boolean verifyTimeoutCode(String timeoutCode, long currentInterval, int pastIntervals, int futureIntervals) throws GeneralSecurityException { // Ensure that look-ahead and look-back counts are not negative. pastIntervals = Math.max(pastIntervals, 0); futureIntervals = Math.max(futureIntervals, 0); // Try upto "pastIntervals" before current time, and upto "futureIntervals" after. for (int i = -pastIntervals; i <= futureIntervals; ++i) { String candidate = generateResponseCode(currentInterval - i, null); if (candidate.equals(timeoutCode)) { return true; } } return false; } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/PasscodeGenerator.java
Java
asf20
7,747
/* * Copyright 2009 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.Html; import android.text.TextUtils; import android.view.View; import android.widget.TextView; import com.google.android.apps.authenticator.Base32String.DecodingException; import com.google.android.apps.authenticator.testability.DependencyInjector; import com.google.android.apps.authenticator2.R; import java.security.GeneralSecurityException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; /** * The activity that displays the integrity check value for a key. * The user is passed in via the extra bundle in "user". * * @author sweis@google.com (Steve Weis) */ public class CheckCodeActivity extends Activity { private TextView mCheckCodeTextView; private TextView mCodeTextView; private TextView mCounterValue; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.check_code); mCodeTextView = (TextView) findViewById(R.id.code_value); mCheckCodeTextView = (TextView) findViewById(R.id.check_code); mCounterValue = (TextView) findViewById(R.id.counter_value); Intent intent = getIntent(); Bundle extras = intent.getExtras(); String user = extras.getString("user"); AccountDb accountDb = DependencyInjector.getAccountDb(); AccountDb.OtpType type = accountDb.getType(user); if (type == AccountDb.OtpType.HOTP) { mCounterValue.setText(accountDb.getCounter(user).toString()); findViewById(R.id.counter_area).setVisibility(View.VISIBLE); } else { findViewById(R.id.counter_area).setVisibility(View.GONE); } String secret = accountDb.getSecret(user); String checkCode = null; String errorMessage = null; try { checkCode = getCheckCode(secret); } catch (GeneralSecurityException e) { errorMessage = getString(R.string.general_security_exception); } catch (DecodingException e) { errorMessage = getString(R.string.decoding_exception); } if (errorMessage != null) { mCheckCodeTextView.setText(errorMessage); return; } mCodeTextView.setText(checkCode); String checkCodeMessage = String.format(getString(R.string.check_code), TextUtils.htmlEncode(user)); CharSequence styledCheckCode = Html.fromHtml(checkCodeMessage); mCheckCodeTextView.setText(styledCheckCode); mCheckCodeTextView.setVisibility(View.VISIBLE); findViewById(R.id.code_area).setVisibility(View.VISIBLE); } static String getCheckCode(String secret) throws GeneralSecurityException, DecodingException { final byte[] keyBytes = Base32String.decode(secret); Mac mac = Mac.getInstance("HMACSHA1"); mac.init(new SecretKeySpec(keyBytes, "")); PasscodeGenerator pcg = new PasscodeGenerator(mac); return pcg.generateResponseCode(0L); } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/CheckCodeActivity.java
Java
asf20
3,619
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import com.google.android.apps.authenticator.wizard.WizardPageActivity; import com.google.android.apps.authenticator2.R; import android.content.Intent; import android.os.Bundle; import android.view.View; import java.io.Serializable; /** * The page of the "Add account" flow that offers the user to add an account. * The page offers the user to scan a barcode or manually enter the account details. * * @author klyubin@google.com (Alex Klyubin) */ public class AddOtherAccountActivity extends WizardPageActivity<Serializable> { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setPageContentView(R.layout.add_other_account); findViewById(R.id.scan_barcode).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { scanBarcode(); } }); findViewById(R.id.manually_add_account).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { manuallyEnterAccountDetails(); } }); mRightButton.setVisibility(View.INVISIBLE); } private void manuallyEnterAccountDetails() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setClass(this, EnterKeyActivity.class); startActivity(intent); } private void scanBarcode() { startActivity(AuthenticatorActivity.getLaunchIntentActionScanBarcode(this)); finish(); } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/AddOtherAccountActivity.java
Java
asf20
2,104
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import android.os.Handler; /** * Task that periodically notifies its listener about the time remaining until the value of a TOTP * counter changes. * * @author klyubin@google.com (Alex Klyubin) */ class TotpCountdownTask implements Runnable { private final TotpCounter mCounter; private final TotpClock mClock; private final long mRemainingTimeNotificationPeriod; private final Handler mHandler = new Handler(); private long mLastSeenCounterValue = Long.MIN_VALUE; private boolean mShouldStop; private Listener mListener; /** * Listener notified of changes to the time remaining until the counter value changes. */ interface Listener { /** * Invoked when the time remaining till the TOTP counter changes its value. * * @param millisRemaining time (milliseconds) remaining. */ void onTotpCountdown(long millisRemaining); /** Invoked when the TOTP counter changes its value. */ void onTotpCounterValueChanged(); } /** * Constructs a new {@code TotpRefreshTask}. * * @param counter TOTP counter this task monitors. * @param clock TOTP clock that drives this task. * @param remainingTimeNotificationPeriod approximate interval (milliseconds) at which this task * notifies its listener about the time remaining until the @{code counter} changes its * value. */ TotpCountdownTask(TotpCounter counter, TotpClock clock, long remainingTimeNotificationPeriod) { mCounter = counter; mClock = clock; mRemainingTimeNotificationPeriod = remainingTimeNotificationPeriod; } /** * Sets the listener that this task will periodically notify about the state of the TOTP counter. * * @param listener listener or {@code null} for no listener. */ void setListener(Listener listener) { mListener = listener; } /** * Starts this task and immediately notifies the listener that the counter value has changed. * * <p>The immediate notification during startup ensures that the listener does not miss any * updates. * * @throws IllegalStateException if the task has already been stopped. */ void startAndNotifyListener() { if (mShouldStop) { throw new IllegalStateException("Task already stopped and cannot be restarted."); } run(); } /** * Stops this task. This task will never notify the listener after the task has been stopped. */ void stop() { mShouldStop = true; } @Override public void run() { if (mShouldStop) { return; } long now = mClock.currentTimeMillis(); long counterValue = getCounterValue(now); if (mLastSeenCounterValue != counterValue) { mLastSeenCounterValue = counterValue; fireTotpCounterValueChanged(); } fireTotpCountdown(getTimeTillNextCounterValue(now)); scheduleNextInvocation(); } private void scheduleNextInvocation() { long now = mClock.currentTimeMillis(); long counterValueAge = getCounterValueAge(now); long timeTillNextInvocation = mRemainingTimeNotificationPeriod - (counterValueAge % mRemainingTimeNotificationPeriod); mHandler.postDelayed(this, timeTillNextInvocation); } private void fireTotpCountdown(long timeRemaining) { if ((mListener != null) && (!mShouldStop)) { mListener.onTotpCountdown(timeRemaining); } } private void fireTotpCounterValueChanged() { if ((mListener != null) && (!mShouldStop)) { mListener.onTotpCounterValueChanged(); } } /** * Gets the value of the counter at the specified time instant. * * @param time time instant (milliseconds since epoch). */ private long getCounterValue(long time) { return mCounter.getValueAtTime(Utilities.millisToSeconds(time)); } /** * Gets the time remaining till the counter assumes its next value. * * @param time time instant (milliseconds since epoch) for which to perform the query. * * @return time (milliseconds) till next value. */ private long getTimeTillNextCounterValue(long time) { long currentValue = getCounterValue(time); long nextValue = currentValue + 1; long nextValueStartTime = Utilities.secondsToMillis(mCounter.getValueStartTime(nextValue)); return nextValueStartTime - time; } /** * Gets the age of the counter value at the specified time instant. * * @param time time instant (milliseconds since epoch). * * @return age (milliseconds). */ private long getCounterValueAge(long time) { return time - Utilities.secondsToMillis(mCounter.getValueStartTime(getCounterValue(time))); } }
zzhyjun-zzhyjun
src/com/google/android/apps/authenticator/TotpCountdownTask.java
Java
asf20
5,267
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import com.google.android.apps.authenticator.PasscodeGenerator.Signer; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import junit.framework.TestCase; /** * Unit test for {@link PasscodeGenerator} * @author sarvar@google.com (Sarvar ) */ public class PasscodeGeneratorTest extends TestCase { private byte[] KEYBYTES1; private byte[] KEYBYTES2; private Mac mac1; private Mac mac2; private PasscodeGenerator passcodeGenerator1; private PasscodeGenerator passcodeGenerator2; private Signer signer; @Override public void setUp() throws Exception { KEYBYTES1 = Base32String.decode("7777777777777777"); KEYBYTES2 = Base32String.decode("22222222222222222"); mac1 = Mac.getInstance("HMACSHA1"); mac1.init(new SecretKeySpec(KEYBYTES1, "")); mac2 = Mac.getInstance("HMACSHA1"); mac2.init(new SecretKeySpec(KEYBYTES2, "")); passcodeGenerator1 = new PasscodeGenerator(mac1); passcodeGenerator2 = new PasscodeGenerator(mac2); signer = AccountDb.getSigningOracle("7777777777777777"); } public void testGenerateResponseCodeLong() throws Exception { // test with long String response1Long = passcodeGenerator1.generateResponseCode(123456789123456789L); assertTrue(passcodeGenerator1.verifyResponseCode(123456789123456789L, response1Long)); assertFalse(passcodeGenerator1.verifyResponseCode(123456789123456789L, "boguscode")); // test with (long, null), response code should be same as with just long String response1LongNull = passcodeGenerator1.generateResponseCode(123456789123456789L, null); assertEquals(response1Long, response1LongNull); // test with byte[] using base32 encoded representation of byte array created from 0L String response1ByteArray = passcodeGenerator1.generateResponseCode(Base32String.decode("AG3JWS5M2BPRK")); assertEquals(response1Long, response1ByteArray); // test Long with another key bytes. String response2Long = passcodeGenerator2.generateResponseCode(123456789123456789L); assertTrue(passcodeGenerator2.verifyResponseCode(123456789123456789L, response2Long)); } public void testRegressionGenerateResponseCode() throws Exception { // test with long assertEquals("724477", passcodeGenerator1.generateResponseCode(0L)); assertEquals("815107", passcodeGenerator1.generateResponseCode(123456789123456789L)); // test with byte[] for 0L and then for 123456789123456789L assertEquals("724477", passcodeGenerator1.generateResponseCode(Base32String.decode("AAAAAAAAAAAAA"))); assertEquals("815107", passcodeGenerator1.generateResponseCode(Base32String.decode("AG3JWS5M2BPRK"))); // test with long and byte[] assertEquals("498157", passcodeGenerator1.generateResponseCode( 123456789123456789L, "challenge".getBytes("UTF-8"))); } public void testVerifyTimeoutCode() throws Exception { /* currentInterval is 1234 in this test. * timeInterval, timeoutCode values around 1234. * 1231, 422609 * 1232, 628381 * 1233, 083501 * 1234, 607007 * 1235, 972746 * 1236, 706552 * 1237, 342936 */ // verify code and plus one interval and minus one interval timeout codes. assertTrue(passcodeGenerator1.verifyTimeoutCode(1234, "607007")); assertTrue(passcodeGenerator1.verifyTimeoutCode(1234, "972746")); // plus one assertTrue(passcodeGenerator1.verifyTimeoutCode(1234, "083501")); // minus one assertFalse(passcodeGenerator1.verifyTimeoutCode(1234, "628381")); // fail for minus two // verify timeout with custom window of +/- 2 intervals assertTrue(passcodeGenerator1.verifyTimeoutCode("607007", 1234, 2, 2)); assertTrue(passcodeGenerator1.verifyTimeoutCode("972746", 1234, 2, 2)); // plus one assertTrue(passcodeGenerator1.verifyTimeoutCode("706552", 1234, 2, 2)); // plus two assertTrue(passcodeGenerator1.verifyTimeoutCode("083501", 1234, 2, 2)); // minus one assertTrue(passcodeGenerator1.verifyTimeoutCode("628381", 1234, 2, 2)); // minus two assertFalse(passcodeGenerator1.verifyTimeoutCode("000000", 1234, 2, 2)); // fail for wrong code assertFalse(passcodeGenerator1.verifyTimeoutCode("342936", 1234, 2, 2)); // fail for plus three // verify timeout with custom window of +1 and -2 intervals assertTrue(passcodeGenerator1.verifyTimeoutCode("607007", 1234, 1, 2)); assertTrue(passcodeGenerator1.verifyTimeoutCode("972746", 1234, 1, 2)); // plus one assertTrue(passcodeGenerator1.verifyTimeoutCode("083501", 1234, 1, 2)); // minus one assertTrue(passcodeGenerator1.verifyTimeoutCode("628381", 1234, 1, 2)); // minus two assertFalse(passcodeGenerator1.verifyTimeoutCode("706552", 1234, 1, 2)); // fail for plus two assertFalse(passcodeGenerator1.verifyTimeoutCode("342936", 1234, 1, 2)); // fail for plus three assertFalse(passcodeGenerator1.verifyTimeoutCode("000000", 1234, 1, 2)); // fail for wrong code // verify timeout with custom window of 0 and -0 intervals assertTrue(passcodeGenerator1.verifyTimeoutCode("607007", 1234, 0, 0)); // pass for current assertFalse(passcodeGenerator1.verifyTimeoutCode("972746", 1234, 0, 0)); // fail for plus one assertFalse(passcodeGenerator1.verifyTimeoutCode("083501", 1234, 0, 0)); // fail for minus one } public void testMacAndSignEquivalence() throws Exception { String codeFromMac = passcodeGenerator1.generateResponseCode(0L); String codeFromSigning = new PasscodeGenerator(signer, 6).generateResponseCode(0L); assertEquals(codeFromMac, codeFromSigning); String codeFromSigning2 = new PasscodeGenerator(signer, 6).generateResponseCode(1L); assertFalse(codeFromSigning.equals(codeFromSigning2)); } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/PasscodeGeneratorTest.java
Java
asf20
6,501
/* * Copyright 2012 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.timesync; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.MockitoAnnotations.initMocks; import android.test.MoreAsserts; import junit.framework.TestCase; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.message.BasicHeader; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.Mockito; import java.io.IOException; import java.util.Arrays; /** * Unit tests for {@link NetworkTimeProvider}. * * @author klyubin@google.com (Alex Klyubin) */ public class NetworkTimeProviderTest extends TestCase { @Mock private HttpClient mMockHttpClient; private NetworkTimeProvider mProvider; @Override protected void setUp() throws Exception { super.setUp(); initMocks(this); mProvider = new NetworkTimeProvider(mMockHttpClient); } @Override protected void tearDown() throws Exception { super.tearDown(); } public void testRequest() throws Exception { withHttpRequestThrowing(new IOException("arbitrary")); try { mProvider.getNetworkTime(); } catch (Exception expected) {} ArgumentCaptor<HttpUriRequest> requestCaptor = ArgumentCaptor.forClass(HttpUriRequest.class); verify(mMockHttpClient).execute(requestCaptor.capture()); HttpUriRequest request = requestCaptor.getValue(); assertEquals("HEAD", request.getMethod()); assertEquals("https://www.google.com", request.getURI().toString()); MoreAsserts.assertEmpty(Arrays.asList(request.getAllHeaders())); } public void testResponseWithValidDate() throws Exception { withHttpRequestReturningDate("Tue, 05 Jun 2012 22:54:01 GMT"); assertEquals(1338936841000L, mProvider.getNetworkTime()); } public void testResponseWithMissingDate() throws Exception { withHttpRequestReturningDate(null); try { mProvider.getNetworkTime(); fail(); } catch (IOException expected) {} } public void testResponseWithMalformedDate() throws Exception { withHttpRequestReturningDate("Tue, 05 Jun 2012 22:54:01 Unknown"); try { mProvider.getNetworkTime(); fail(); } catch (IOException expected) {} } public void testRequestThrowsExceptions() throws Exception { withHttpRequestThrowing(new IOException("")); try { mProvider.getNetworkTime(); fail(); } catch (IOException expected) {} withHttpRequestThrowing(new ClientProtocolException()); try { mProvider.getNetworkTime(); fail(); } catch (IOException expected) {} } private void withHttpRequestThrowing(Exception exception) throws IOException { doThrow(exception).when(mMockHttpClient).execute(Mockito.<HttpUriRequest>anyObject()); } private void withHttpRequestReturningDate(String dateHeaderValue) throws IOException { HttpResponse mockResponse = mock(HttpResponse.class); if (dateHeaderValue != null) { doReturn(new BasicHeader("Date", dateHeaderValue)).when(mockResponse).getLastHeader("Date"); } doReturn(mockResponse).when(mMockHttpClient).execute(Mockito.<HttpUriRequest>anyObject()); } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/timesync/NetworkTimeProviderTest.java
Java
asf20
4,004
/* * Copyright 2012 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.timesync; import static org.mockito.Mockito.anyInt; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.MockitoAnnotations.initMocks; import com.google.android.apps.authenticator.RunImmediatelyOnCallingThreadExecutor; import com.google.android.apps.authenticator.TotpClock; import com.google.android.apps.authenticator.Utilities; import junit.framework.TestCase; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import java.io.IOException; import java.util.concurrent.Executor; /** * Unit tests for {@link SyncNowController}. * * @author klyubin@google.com (Alex Klyubin) */ public class SyncNowControllerTest extends TestCase { @Mock private NetworkTimeProvider mMockNetworkTimeProvider; @Mock private TotpClock mMockTotpClock; @Mock private SyncNowController.Presenter mMockPresenter; private Executor mBackgroundExecutor; private Executor mCallbackExecutor; private SyncNowController mController; @Override protected void setUp() throws Exception { super.setUp(); initMocks(this); // By default, configure the controller to invoke its background operations on the calling // thread so that tests do not depend on other threads (especially Looper threads) and are // easier to read due to lack of concurrency complications. withImmediateExecutors(); } @Override protected void tearDown() throws Exception { super.tearDown(); } public void testAdjustmentMade() throws Exception { withTotpClockTimeCorrectionMinutes(7); withNetworkTimeProviderReturningMillis( System.currentTimeMillis() + 3 * Utilities.MINUTE_IN_MILLIS); createController(); mController.attach(mMockPresenter); assertEquals(SyncNowController.Result.TIME_CORRECTED, verifyPresenterOnDoneInvoked()); assertEquals(3, verifyTotpClockSetTimeCorrectionInvoked()); reset(mMockPresenter); mController.detach(mMockPresenter); verifyZeroInteractions(mMockPresenter); } public void testAdjustmentNotNeeded() throws Exception { withTotpClockTimeCorrectionMinutes(-3); withNetworkTimeProviderReturningMillis( System.currentTimeMillis() - 3 * Utilities.MINUTE_IN_MILLIS); createController(); mController.attach(mMockPresenter); assertEquals(SyncNowController.Result.TIME_ALREADY_CORRECT, verifyPresenterOnDoneInvoked()); verifyTotpClockSetTimeCorrectionNotInvoked(); } public void testConnectivityError() throws Exception { withNetworkTimeProviderThrowing(new IOException()); createController(); mController.attach(mMockPresenter); assertEquals(SyncNowController.Result.ERROR_CONNECTIVITY_ISSUE, verifyPresenterOnDoneInvoked()); verifyTotpClockSetTimeCorrectionNotInvoked(); } public void testCancelledByUserBeforeBackgroundOperation() throws Exception { withTotpClockTimeCorrectionMinutes(-7); withNetworkTimeProviderReturningMillis( System.currentTimeMillis() - 7 * Utilities.MINUTE_IN_MILLIS); withBackgroundExecutorThatAbortsControllerBeforeExecuting(); createController(); mController.attach(mMockPresenter); assertEquals(SyncNowController.Result.CANCELLED_BY_USER, verifyPresenterOnDoneInvoked()); verifyTotpClockSetTimeCorrectionNotInvoked(); } public void testCancelledByUserBeforeCallback() throws Exception { withTotpClockTimeCorrectionMinutes(-7); withNetworkTimeProviderReturningMillis( System.currentTimeMillis() - 7 * Utilities.MINUTE_IN_MILLIS); withCallbackExecutorThatAbortsControllerBeforeExecuting(); createController(); mController.attach(mMockPresenter); assertEquals(SyncNowController.Result.CANCELLED_BY_USER, verifyPresenterOnDoneInvoked()); verifyTotpClockSetTimeCorrectionNotInvoked(); } public void testAttachToNewPresenter() throws Exception { withTotpClockTimeCorrectionMinutes(7); withNetworkTimeProviderReturningMillis( System.currentTimeMillis() + 3 * Utilities.MINUTE_IN_MILLIS); createController(); mController.attach(mMockPresenter); assertEquals(SyncNowController.Result.TIME_CORRECTED, verifyPresenterOnDoneInvoked()); assertEquals(3, verifyTotpClockSetTimeCorrectionInvoked()); reset(mMockTotpClock, mMockNetworkTimeProvider); mMockPresenter = mock(SyncNowController.Presenter.class); mController.attach(mMockPresenter); assertEquals(SyncNowController.Result.TIME_CORRECTED, verifyPresenterOnDoneInvoked()); verifyZeroInteractions(mMockTotpClock, mMockNetworkTimeProvider); } public void testDetachPresenterBeforeFinished() throws Exception { withTotpClockTimeCorrectionMinutes(7); withNetworkTimeProviderReturningMillis( System.currentTimeMillis() + 3 * Utilities.MINUTE_IN_MILLIS); withBackgroundExecutorThatDetachesPresenterBeforeExecuting(); createController(); mController.attach(mMockPresenter); assertEquals(SyncNowController.Result.CANCELLED_BY_USER, verifyPresenterOnDoneInvoked()); verifyZeroInteractions(mMockTotpClock); } private void createController() { mController = new SyncNowController( mMockTotpClock, mMockNetworkTimeProvider, mBackgroundExecutor, false, mCallbackExecutor); } private void withNetworkTimeProviderReturningMillis(long timeMillis) throws IOException { doReturn(timeMillis).when(mMockNetworkTimeProvider).getNetworkTime(); } private void withNetworkTimeProviderThrowing(IOException exception) throws IOException { doThrow(exception).when(mMockNetworkTimeProvider).getNetworkTime(); } private void withTotpClockTimeCorrectionMinutes(int timeCorrectionMinutes) { doReturn(timeCorrectionMinutes).when(mMockTotpClock).getTimeCorrectionMinutes(); } private SyncNowController.Result verifyPresenterOnDoneInvoked() { ArgumentCaptor<SyncNowController.Result> resultCaptor = ArgumentCaptor.forClass(SyncNowController.Result.class); verify(mMockPresenter).onDone(resultCaptor.capture()); return resultCaptor.getValue(); } private void verifyTotpClockSetTimeCorrectionNotInvoked() { verify(mMockTotpClock, never()).setTimeCorrectionMinutes(anyInt()); } private int verifyTotpClockSetTimeCorrectionInvoked() { ArgumentCaptor<Integer> resultCaptor = ArgumentCaptor.forClass(Integer.class); verify(mMockTotpClock).setTimeCorrectionMinutes(resultCaptor.capture()); return resultCaptor.getValue(); } private void withImmediateExecutors() { mBackgroundExecutor = new RunImmediatelyOnCallingThreadExecutor(); mCallbackExecutor = new RunImmediatelyOnCallingThreadExecutor(); } private void withBackgroundExecutorThatAbortsControllerBeforeExecuting() { mBackgroundExecutor = new Executor() { @Override public void execute(Runnable command) { mController.abort(mMockPresenter); command.run(); } }; } private void withCallbackExecutorThatAbortsControllerBeforeExecuting() { mCallbackExecutor = new Executor() { @Override public void execute(Runnable command) { mController.abort(mMockPresenter); command.run(); } }; } private void withBackgroundExecutorThatDetachesPresenterBeforeExecuting() { mBackgroundExecutor = new Executor() { @Override public void execute(Runnable command) { mController.detach(mMockPresenter); command.run(); } }; } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/timesync/SyncNowControllerTest.java
Java
asf20
8,351
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import com.google.android.apps.authenticator.AccountDb.OtpType; import com.google.android.apps.authenticator.testability.DependencyInjector; import com.google.android.apps.authenticator2.R; import android.content.Intent; import android.test.ActivityInstrumentationTestCase2; import android.test.MoreAsserts; import android.test.ViewAsserts; import android.view.View; import android.widget.TextView; /** * Unit tests for {@link CheckCodeActivity}. * * @author sarvar@google.com (Sarvar Patel) */ public class CheckCodeActivityTest extends ActivityInstrumentationTestCase2<CheckCodeActivity> { public CheckCodeActivityTest() { super(TestUtilities.APP_PACKAGE_NAME, CheckCodeActivity.class); } @Override public void setUp() throws Exception { super.setUp(); DependencyInjector.resetForIntegrationTesting(getInstrumentation().getTargetContext()); AccountDb accountDb = DependencyInjector.getAccountDb(); accountDb.update( "johndoe@gmail.com", "7777777777777777", "johndoe@gmail.com", OtpType.TOTP, null); accountDb.update( "shadowmorton@aol.com", "2222222222222222", "shadowmorton@aol.com", OtpType.HOTP, null); accountDb.update( "maryweiss@yahoo.com", "7777777777777777", "maryweiss@yahoo.com", OtpType.HOTP, 0); setActivityInitialTouchMode(false); } @Override protected void tearDown() throws Exception { DependencyInjector.close(); super.tearDown(); } public void testWithTimeBasedAccount() { // For TOTP accounts, AuthenticatorActivity never calls CheckCodeActivity, however, the // code exists and we check its behavior here. setActivityIntent(new Intent(Intent.ACTION_MAIN).putExtra("user", "johndoe@gmail.com")); CheckCodeActivity mActivity = getActivity(); TextView mCodeTextView = (TextView) mActivity.findViewById(R.id.code_value); TextView mCheckCodeTextView = (TextView) mActivity.findViewById(R.id.check_code); TextView mCounterValue = (TextView) mActivity.findViewById(R.id.counter_value); // check existence of fields assertNotNull(mActivity); assertNotNull(mCheckCodeTextView); assertNotNull(mCodeTextView); assertNotNull(mCounterValue); // check visibility View origin = mActivity.getWindow().getDecorView(); ViewAsserts.assertOnScreen(origin, mCheckCodeTextView); ViewAsserts.assertOnScreen(origin, mCodeTextView); assertTrue(mActivity.findViewById(R.id.code_area).isShown()); // layout area assertFalse(mCounterValue.isShown()); // TOTP has no counter value to show. assertFalse(mActivity.findViewById(R.id.counter_area).isShown()); // layout area // check values MoreAsserts.assertContainsRegex("johndoe@gmail.com", mCheckCodeTextView.getText().toString()); assertEquals("724477", mCodeTextView.getText().toString()); } public void testWithCounterBasedAccount() { setActivityIntent(new Intent(Intent.ACTION_MAIN).putExtra("user", "maryweiss@yahoo.com")); CheckCodeActivity mActivity = getActivity(); TextView mCodeTextView = (TextView) mActivity.findViewById(R.id.code_value); TextView mCheckCodeTextView = (TextView) mActivity.findViewById(R.id.check_code); TextView mCounterValue = (TextView) mActivity.findViewById(R.id.counter_value); // check existence of fields assertNotNull(mCheckCodeTextView); assertNotNull(mCodeTextView); assertNotNull(mCounterValue); // check visibility View origin = mActivity.getWindow().getDecorView(); ViewAsserts.assertOnScreen(origin, mCheckCodeTextView); ViewAsserts.assertOnScreen(origin, mCodeTextView); ViewAsserts.assertOnScreen(origin, mCounterValue); assertTrue(mActivity.findViewById(R.id.code_area).isShown()); // layout area assertTrue(mActivity.findViewById(R.id.counter_area).isShown()); // layout area // check values MoreAsserts.assertContainsRegex("maryweiss@yahoo.com", mCheckCodeTextView.getText().toString()); assertEquals("724477", mCodeTextView.getText().toString()); assertEquals("0", mCounterValue.getText().toString()); } public void testWithAnotherCounterBasedAccount() { setActivityIntent(new Intent(Intent.ACTION_MAIN).putExtra("user", "shadowmorton@aol.com")); CheckCodeActivity mActivity = getActivity(); TextView mCodeTextView = (TextView) mActivity.findViewById(R.id.code_value); TextView mCheckCodeTextView = (TextView) mActivity.findViewById(R.id.check_code); MoreAsserts.assertContainsRegex( "shadowmorton@aol.com", mCheckCodeTextView.getText().toString()); assertEquals("086620", mCodeTextView.getText().toString()); } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/CheckCodeActivityTest.java
Java
asf20
5,287
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import com.google.android.apps.authenticator.testability.DependencyInjector; import com.google.android.apps.authenticator.testability.StartActivityListener; import android.app.Activity; import android.app.Instrumentation; import android.content.Context; import android.content.Intent; import android.graphics.Point; import android.os.Build; import android.os.Looper; import android.os.SystemClock; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceScreen; import android.test.InstrumentationTestCase; import android.test.TouchUtils; import android.test.ViewAsserts; import android.view.Gravity; import android.view.View; import android.view.ViewParent; import android.widget.EditText; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.Spinner; import junit.framework.Assert; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * A class that offers various utility methods for writing tests. * * @author sarvar@google.com (Sarvar Patel) */ public class TestUtilities { public static final String APP_PACKAGE_NAME = "com.google.android.apps.authenticator2"; /** * Timeout (milliseconds) when waiting for the results of a UI action performed by the code * under test. */ public static final int UI_ACTION_EFFECT_TIMEOUT_MILLIS = 5000; private TestUtilities() { } public static void clickView(Instrumentation instr, final View view) { instr.runOnMainSync(new Runnable() { @Override public void run() { view.performClick(); } }); // this shouldn't be needed but without it or sleep, there isn't time for view refresh, etc. instr.waitForIdleSync(); } public static void longClickView(Instrumentation instr, final View view) { instr.runOnMainSync(new Runnable() { @Override public void run() { view.performLongClick(); } }); instr.waitForIdleSync(); } /** * Selects the item at the requested position in the Spinner. * * @return the selected item as string. */ public static String selectSpinnerItem( Instrumentation instr, final Spinner spinner, final int position) { instr.runOnMainSync(new Runnable() { @Override public void run() { spinner.setSelection(position); } }); instr.waitForIdleSync(); return spinner.getSelectedItem().toString(); } /** * Sets the text of the provided {@link EditText} widget on the UI thread. * * @return the resulting text of the widget. */ public static String setText(Instrumentation instr, final EditText editText, final String text) { instr.runOnMainSync(new Runnable() { @Override public void run() { editText.setText(text); } }); instr.waitForIdleSync(); return editText.getText().toString(); } /* * Sends a string to a EditText box. * * @return the resulting string read from the editText - this should equal text. */ public static String enterText( Instrumentation instr, final EditText editText, final String text) { instr.runOnMainSync(new Runnable() { @Override public void run() { editText.requestFocus(); } }); // TODO(sarvar): decide on using touch mode and how to do it consistently. e.g., // the above could be replaced by "TouchUtils.tapView(this, editText);" instr.sendStringSync(text); return editText.getText().toString(); } /** * Taps the specified preference displayed by the provided Activity. */ public static void tapPreference(InstrumentationTestCase instrumentationTestCase, PreferenceActivity activity, Preference preference) { // IMPLEMENTATION NOTE: There's no obvious way to find out which View corresponds to the // preference because the Preference list in the adapter is flattened, whereas the View // hierarchy in the ListView is not. // Thus, we go for the Reflection-based invocation of Preference.performClick() which is as // close to the invocation stack of a normal tap as it gets. // Only perform the click if the preference is in the adapter to catch cases where the // preference is not part of the PreferenceActivity for some reason. ListView listView = activity.getListView(); ListAdapter listAdapter = listView.getAdapter(); for (int i = 0, len = listAdapter.getCount(); i < len; i++) { if (listAdapter.getItem(i) == preference) { invokePreferencePerformClickOnMainThread( instrumentationTestCase.getInstrumentation(), preference, activity.getPreferenceScreen()); return; } } throw new IllegalArgumentException("Preference " + preference + " not in list"); } private static void invokePreferencePerformClickOnMainThread( Instrumentation instrumentation, final Preference preference, final PreferenceScreen preferenceScreen) { if (Thread.currentThread() == Looper.getMainLooper().getThread()) { invokePreferencePerformClick(preference, preferenceScreen); } else { FutureTask<Void> task = new FutureTask<Void>(new Runnable() { @Override public void run() { invokePreferencePerformClick(preference, preferenceScreen); } }, null); instrumentation.runOnMainSync(task); try { task.get(); } catch (Exception e) { throw new RuntimeException("Failed to click on preference on main thread", e); } } } private static void invokePreferencePerformClick( Preference preference, PreferenceScreen preferenceScreen) { try { Method performClickMethod = Preference.class.getDeclaredMethod("performClick", PreferenceScreen.class); performClickMethod.setAccessible(true); performClickMethod.invoke(preference, preferenceScreen); } catch (NoSuchMethodException e) { throw new RuntimeException("Preference.performClickMethod method not found", e); } catch (InvocationTargetException e) { throw new RuntimeException("Preference.performClickMethod failed", e); } catch (IllegalAccessException e) { throw new RuntimeException("Failed to access Preference.performClickMethod", e); } } /** * Waits until the window which contains the provided view has focus. */ public static void waitForWindowFocus(View view) throws InterruptedException, TimeoutException { long deadline = SystemClock.uptimeMillis() + UI_ACTION_EFFECT_TIMEOUT_MILLIS; while (!view.hasWindowFocus()) { long millisTillDeadline = deadline - SystemClock.uptimeMillis(); if (millisTillDeadline < 0) { throw new TimeoutException("Timed out while waiting for window focus"); } Thread.sleep(50); } } /** * Waits until the {@link Activity} is finishing. */ public static void waitForActivityFinishing(Activity activity) throws InterruptedException, TimeoutException { long deadline = SystemClock.uptimeMillis() + UI_ACTION_EFFECT_TIMEOUT_MILLIS; while (!activity.isFinishing()) { long millisTillDeadline = deadline - SystemClock.uptimeMillis(); if (millisTillDeadline < 0) { throw new TimeoutException("Timed out while waiting for activity to start finishing"); } Thread.sleep(50); } } /** * Invokes the {@link Activity}'s {@code onBackPressed()} on the UI thread and blocks (with * a timeout) the calling thread until the invocation completes. If the calling thread is the UI * thread, the {@code finish} is invoked directly and without a timeout. */ public static void invokeActivityOnBackPressedOnUiThread(final Activity activity) throws InterruptedException, TimeoutException { FutureTask<Void> finishTask = new FutureTask<Void>(new Runnable() { @Override public void run() { activity.onBackPressed(); } }, null); activity.runOnUiThread(finishTask); try { finishTask.get(UI_ACTION_EFFECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } catch (ExecutionException e) { throw new RuntimeException("Activity.onBackPressed() failed", e); } } /** * Invokes the {@link Activity}'s {@code finish()} on the UI thread and blocks (with * a timeout) the calling thread until the invocation completes. If the calling thread is the UI * thread, the {@code finish} is invoked directly and without a timeout. */ public static void invokeFinishActivityOnUiThread(final Activity activity) throws InterruptedException, TimeoutException { FutureTask<Void> finishTask = new FutureTask<Void>(new Runnable() { @Override public void run() { activity.finish(); } }, null); activity.runOnUiThread(finishTask); try { finishTask.get(UI_ACTION_EFFECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } catch (ExecutionException e) { throw new RuntimeException("Activity.finish() failed", e); } } private static boolean isViewAndAllItsParentsVisible(View view) { if (view.getVisibility() != View.VISIBLE) { return false; } ViewParent parent = view.getParent(); if (!(parent instanceof View)) { // This View is the root of the View hierarche, and it's visible (checked above) return true; } // This View itself is actually visible only all of its parents are visible. return isViewAndAllItsParentsVisible((View) parent); } private static boolean isViewOrAnyParentVisibilityGone(View view) { if (view.getVisibility() == View.GONE) { return true; } ViewParent parent = view.getParent(); if (!(parent instanceof View)) { // This View is the root of the View hierarchy, and its visibility is not GONE (checked above) return false; } // This View itself is actually visible only all of its parents are visible. return isViewOrAnyParentVisibilityGone((View) parent); } /** * Asserts that the provided {@link View} and all its parents are visible. */ public static void assertViewAndAllItsParentsVisible(View view) { Assert.assertTrue(isViewAndAllItsParentsVisible(view)); } /** * Asserts that the provided {@link View} and all its parents are visible. */ public static void assertViewOrAnyParentVisibilityGone(View view) { Assert.assertTrue(isViewOrAnyParentVisibilityGone(view)); } /** * Asserts that the provided {@link View} is on the screen and is visible (which means its parent * and the parent of its parent and so forth are visible too). */ public static void assertViewVisibleOnScreen(View view) { ViewAsserts.assertOnScreen(view.getRootView(), view); assertViewAndAllItsParentsVisible(view); } /** * Opens the options menu of the provided {@link Activity} and invokes the menu item with the * provided ID. * * Note: This method cannot be invoked on the main thread. */ public static void openOptionsMenuAndInvokeItem( Instrumentation instrumentation, final Activity activity, final int itemId) { if (!instrumentation.invokeMenuActionSync(activity, itemId, 0)) { throw new RuntimeException("Failed to invoke options menu item ID " + itemId); } instrumentation.waitForIdleSync(); } /** * Opens the context menu for the provided {@link View} and invokes the menu item with the * provided ID. * * Note: This method cannot be invoked on the main thread. */ public static void openContextMenuAndInvokeItem( Instrumentation instrumentation, final Activity activity, final View view, final int itemId) { // IMPLEMENTATION NOTE: Instrumentation.invokeContextMenuAction would've been much simpler, but // it doesn't work on ICS because its KEY_UP event times out. FutureTask<Boolean> task = new FutureTask<Boolean>(new Callable<Boolean>() { @Override public Boolean call() { // Use performLongClick instead of showContextMenu to exercise more of the code path that // is invoked when the user normally opens a context menu. view.performLongClick(); return activity.getWindow().performContextMenuIdentifierAction(itemId, 0); } }); instrumentation.runOnMainSync(task); try { if (!task.get()) { throw new RuntimeException("Failed to invoke context menu item with ID " + itemId); } } catch (Exception e) { throw new RuntimeException("Failed to open context menu and select a menu item", e); } instrumentation.waitForIdleSync(); } /** * Asserts that the provided {@link Activity} displayed a dialog with the provided ID at some * point in the past. Note that this does not necessarily mean that the dialog is still being * displayed. * * <p> * <b>Note:</b> this method resets the "was displayed" state of the dialog. This means that a * consecutive invocation of this method for the same dialog ID will fail unless the dialog * was displayed again prior to the invocation of this method. */ public static void assertDialogWasDisplayed(Activity activity, int dialogId) { // IMPLEMENTATION NOTE: This code below relies on the fact that, if a dialog with the ID was // every displayed, then dismissDialog will succeed, whereas if the dialog with the ID has // never been shown, then dismissDialog throws an IllegalArgumentException. try { activity.dismissDialog(dialogId); // Reset the "was displayed" state activity.removeDialog(dialogId); } catch (IllegalArgumentException e) { Assert.fail("No dialog with ID " + dialogId + " was ever displayed"); } } /** * Taps the positive button of a currently displayed dialog. This method assumes that a button * of the dialog is currently selected. * * @see #tapDialogNegativeButton(InstrumentationTestCase) */ public static void tapDialogNegativeButton(InstrumentationTestCase testCase) { // The order of the buttons is reversed from ICS onwards if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { testCase.sendKeys("DPAD_RIGHT DPAD_CENTER"); } else { testCase.sendKeys("DPAD_LEFT DPAD_CENTER"); } } /** * Taps the negative button of a currently displayed dialog. This method assumes that a button * of the dialog is currently selected. * * @see #tapDialogNegativeButton(InstrumentationTestCase) */ public static void tapDialogPositiveButton(InstrumentationTestCase testCase) { // The order of the buttons is reversed from ICS onwards if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { testCase.sendKeys("DPAD_LEFT DPAD_CENTER"); } else { testCase.sendKeys("DPAD_RIGHT DPAD_CENTER"); } } /** * Taps the negative button of a currently displayed 3 button dialog. This method assumes * that a button of the dialog is currently selected. */ public static void tapNegativeButtonIn3ButtonDialog(InstrumentationTestCase testCase) { // The order of the buttons is reversed from ICS onwards if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { testCase.sendKeys("DPAD_RIGHT DPAD_RIGHT DPAD_CENTER"); } else { testCase.sendKeys("DPAD_LEFT DPAD_LEFT DPAD_CENTER"); } } /** * Taps the neutral button of a currently displayed 3 button dialog. This method assumes * that a button of the dialog is currently selected. */ public static void tapNeutralButtonIn3ButtonDialog(InstrumentationTestCase testCase) { // The order of the buttons is reversed from ICS onwards if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { testCase.sendKeys("DPAD_RIGHT DPAD_CENTER"); } else { testCase.sendKeys("DPAD_RIGHT DPAD_CENTER"); } } /** * Taps the positive button of a currently displayed 3 button dialog. This method assumes * that a button of the dialog is currently selected. */ public static void tapPositiveButtonIn3ButtonDialog(InstrumentationTestCase testCase) { // The order of the buttons is reversed from ICS onwards if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { testCase.sendKeys("DPAD_LEFT DPAD_LEFT DPAD_CENTER"); } else { testCase.sendKeys("DPAD_RIGHT DPAD_RIGHT DPAD_CENTER"); } } /** * Configures the {@link DependencyInjector} with a {@link StartActivityListener} that prevents * activity launches. */ public static void withLaunchPreventingStartActivityListenerInDependencyResolver() { StartActivityListener mockListener = Mockito.mock(StartActivityListener.class); doReturn(true).when(mockListener).onStartActivityInvoked( Mockito.<Context>anyObject(), Mockito.<Intent>anyObject()); DependencyInjector.setStartActivityListener(mockListener); } /** * Verifies (with a timeout of {@link #UI_ACTION_EFFECT_TIMEOUT_MILLIS}) that an activity launch * has been attempted and returns the {@link Intent} with which the attempt occurred. * * <p><b>NOTE: This method assumes that the {@link DependencyInjector} was configured * using {@link #withLaunchPreventingStartActivityListenerInDependencyResolver()}.</b> */ public static Intent verifyWithTimeoutThatStartActivityAttemptedExactlyOnce() { StartActivityListener mockListener = DependencyInjector.getStartActivityListener(); ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); verify(mockListener, timeout(UI_ACTION_EFFECT_TIMEOUT_MILLIS)) .onStartActivityInvoked(Mockito.<Context>anyObject(), intentCaptor.capture()); return intentCaptor.getValue(); } public static void assertLessThanOrEquals(long expected, long actual) { if (actual > expected) { Assert.fail(actual + " > " + expected); } } /* * Returns the x and y coordinates of center of view in pixels. */ public static Point getCenterOfViewOnScreen( InstrumentationTestCase instr, View view) { int[] location = new int[2]; view.getLocationOnScreen(location); int width = view.getWidth(); int height = view.getHeight(); final int center_x = location[0] + width / 2; final int center_y = location[1] + height / 2; return new Point(center_x, center_y); } /* * returns the pixel value at the right side end of the view. */ public static int getRightXofViewOnScreen(View view) { int[] location = new int[2]; view.getLocationOnScreen(location); int width = view.getWidth(); return location[0] + width; } /* * returns the pixel value at the left side end of the view. */ public static int getLeftXofViewOnScreen(View view) { int[] location = new int[2]; view.getLocationOnScreen(location); return location[0]; } /* * Drags from the center of the view to the toX value. * This methods exists in TouchUtil, however, it has a bug which causes it to work * while dragging on the left side, but not on the right side, hence, we * had to recreate it here. */ public static int dragViewToX(InstrumentationTestCase test, View v, int gravity, int toX) { if (gravity != Gravity.CENTER) { throw new IllegalArgumentException("Can only handle Gravity.CENTER."); } Point point = getCenterOfViewOnScreen(test, v); final int fromX = point.x; final int fromY = point.y; int deltaX = Math.abs(fromX - toX); TouchUtils.drag(test, fromX, toX, fromY, fromY, deltaX); return deltaX; } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/TestUtilities.java
Java
asf20
20,683
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import android.test.AndroidTestCase; import java.io.File; import java.io.IOException; /** * Unit tests for {@link Utilities}. * * @author sarvar@google.com (Sarvar Patel) */ public class FileUtilitiesTest extends AndroidTestCase { public void testRestrictAccess_withActualDirectory() throws Exception { File dir = createTempDirInCacheDir(); try { String path = dir.getPath(); setFilePermissions(path, 0755); FileUtilities.restrictAccessToOwnerOnly(path); assertEquals(0700, getFilePermissions(path) & 0777); } finally { dir.delete(); } } public void testRestrictAccess_withActualNonExistentDirectory() throws Exception { File dir = createTempDirInCacheDir(); assertTrue(dir.delete()); try { FileUtilities.restrictAccessToOwnerOnly(dir.getPath()); fail(); } catch (IOException expected) {} } public void testGetStat_withActualDirectory() throws Exception { File dir = createTempDirInCacheDir(); try { String path = dir.getPath(); setFilePermissions(path, 0755); FileUtilities.StatStruct s1 = FileUtilities.getStat(path); assertEquals(0755, s1.mode & 0777); long ctime1 = s1.ctime; assertTrue(s1.toString().contains(Long.toString(ctime1))); setFilePermissions(path, 0700); FileUtilities.StatStruct s2 = FileUtilities.getStat(path); assertEquals(0700, s2.mode & 0777); long ctime2 = s2.ctime; assertTrue(ctime2 >= ctime1); } finally { dir.delete(); } } public void testGetStat_withActualNonExistentDirectory() throws Exception { File dir = createTempDirInCacheDir(); assertTrue(dir.delete()); try { FileUtilities.getStat(dir.getPath()); fail(); } catch (IOException expected) {} } private static void setFilePermissions(String path, int mode) throws Exception { // IMPLEMENTATION NOTE: The code below simply invokes // android.os.FileUtils.setPermissions(path, mode, -1, -1) via Reflection. int errorCode = (Integer) Class.forName("android.os.FileUtils") .getMethod("setPermissions", String.class, int.class, int.class, int.class) .invoke(null, path, mode, -1, -1); assertEquals(0, errorCode); assertEquals(mode, getFilePermissions(path) & 0777); } private static int getFilePermissions(String path) throws Exception { // IMPLEMENTATION NOTE: The code below simply invokes // android.os.FileUtils.getPermissions(path, int[]) via Reflection. int[] modeUidAndGid = new int[3]; int errorCode = (Integer) Class.forName("android.os.FileUtils") .getMethod("getPermissions", String.class, int[].class) .invoke(null, path, modeUidAndGid); assertEquals(0, errorCode); return modeUidAndGid[0]; } private File createTempDirInCacheDir() throws IOException { // IMPLEMENTATION NOTE: There's no API to create temp dir on one go. Thus, we create // a temp file, delete it, and recreate it as a directory. File file = File.createTempFile(getClass().getSimpleName(), "", getContext().getCacheDir()); assertTrue(file.delete()); assertTrue(file.mkdir()); return file; } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/FileUtilitiesTest.java
Java
asf20
3,863
/* * Copyright 2012 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import android.test.MoreAsserts; import junit.framework.TestCase; /** * Unit tests for {@link HexEncoding}. * * @author klyubin@google.com (Alex Klyubin) */ public class HexEncodingTest extends TestCase { public void testEncodeNull() { try { HexEncoding.encode(null); fail(); } catch (NullPointerException expected) {} } public void testEncodeEmpty() { assertEquals("", HexEncoding.encode(new byte[0])); } public void testEncodeAllDigits() { assertEquals("0123456789abcdef", HexEncoding.encode( new byte[] {0x01, 0x23, 0x45, 0x67, (byte) 0x89, (byte) 0xab, (byte) 0xcd, (byte) 0xef})); } public void testDecodeNull() { try { HexEncoding.decode(null); fail(); } catch (NullPointerException expected) {} } public void testDecodeEmpty() { MoreAsserts.assertEquals(new byte[0], HexEncoding.decode("")); } public void testDecodeAllDigits() { MoreAsserts.assertEquals( new byte[] {0x01, 0x23, 0x45, 0x67, (byte) 0x89, (byte) 0xab, (byte) 0xcd, (byte) 0xef}, HexEncoding.decode("0123456789abcdef")); } public void testDecodeOddNumberOfDigits() { MoreAsserts.assertEquals( new byte[] {0x0f, 0x23, 0x45}, HexEncoding.decode("f2345")); } public void testDecodeOneDigit() { MoreAsserts.assertEquals( new byte[] {0x03}, HexEncoding.decode("3")); } public void testDecode_withSpaces() { try { HexEncoding.decode("01 23"); fail(); } catch (IllegalArgumentException expected) {} } public void testDecode_withUpperCaseDigits() { MoreAsserts.assertEquals( new byte[] {(byte) 0xab, (byte) 0xcd, (byte) 0xef}, HexEncoding.decode("ABCDEF")); } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/HexEncodingTest.java
Java
asf20
2,407
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.testability; import android.os.Build; import android.test.AndroidTestCase; import org.apache.http.client.HttpClient; import org.apache.http.client.params.HttpClientParams; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.params.ConnManagerParams; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; /** * Unit tests for {@link HttpClientFactory}. * * @author klyubin@google.com (Alex Klyubin) */ public class HttpClientFactoryTest extends AndroidTestCase { private HttpClient mClient; @Override protected void setUp() throws Exception { super.setUp(); mClient = HttpClientFactory.createHttpClient(getContext()); } @Override protected void tearDown() throws Exception { if (mClient != null) { ClientConnectionManager connectionManager = mClient.getConnectionManager(); if (connectionManager != null) { connectionManager.shutdown(); } } super.tearDown(); } public void testClientClass() throws Exception { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.ECLAIR_MR1) { assertEquals( getContext().getClassLoader().loadClass(DefaultHttpClient.class.getName()), mClient.getClass()); } else { assertEquals( getContext().getClassLoader().loadClass("android.net.http.AndroidHttpClient"), mClient.getClass()); } } public void testClientConfiguration() throws Exception { HttpParams params = mClient.getParams(); assertFalse(HttpClientParams.isRedirecting(params)); assertFalse(HttpClientParams.isAuthenticating(params)); assertEquals( HttpClientFactory.DEFAULT_CONNECT_TIMEOUT_MILLIS, HttpConnectionParams.getConnectionTimeout(params)); assertEquals( HttpClientFactory.DEFAULT_READ_TIMEOUT_MILLIS, HttpConnectionParams.getSoTimeout(params)); assertEquals( HttpClientFactory.DEFAULT_GET_CONNECTION_FROM_POOL_TIMEOUT_MILLIS, ConnManagerParams.getTimeout(params)); } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/testability/HttpClientFactoryTest.java
Java
asf20
2,765
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import static org.mockito.MockitoAnnotations.initMocks; import com.google.android.apps.authenticator.AccountDb.OtpType; import com.google.android.apps.authenticator.dataimport.ImportController; import com.google.android.apps.authenticator.testability.DependencyInjector; import com.google.android.apps.authenticator2.R; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.test.ActivityInstrumentationTestCase2; import android.test.MoreAsserts; import android.view.View; import org.mockito.Mock; import java.util.ArrayList; import java.util.List; /** * Unit test for authenticator activity (part/shard 2). * * @author sarvar@google.com (Sarvar Patel) */ public class AuthenticatorActivityPart2Test extends ActivityInstrumentationTestCase2<AuthenticatorActivity> { private AccountDb mAccountDb; @Mock private ImportController mMockDataImportController; public AuthenticatorActivityPart2Test() { super(TestUtilities.APP_PACKAGE_NAME, AuthenticatorActivity.class); } @Override protected void setUp() throws Exception { super.setUp(); DependencyInjector.resetForIntegrationTesting(getInstrumentation().getTargetContext()); mAccountDb = DependencyInjector.getAccountDb(); initMocks(this); DependencyInjector.setDataImportController(mMockDataImportController); } @Override protected void tearDown() throws Exception { // Stop the activity to avoid it using the DependencyInjector after it's been closed. TestUtilities.invokeFinishActivityOnUiThread(getActivity()); DependencyInjector.close(); super.tearDown(); } public void testAccountSetup_validTotpUriAccepted() throws Throwable { getActivity(); String secret = "CQAHUXJ2VWDI7WFF"; String accountName = "9.99.99.999"; callOnActivityResultOnUiThreadWithScannedUri( "otpauth://totp/" + accountName + "?secret=" + secret); List<String> accountNames = new ArrayList<String>(); assertEquals(1, mAccountDb.getNames(accountNames)); assertEquals(accountName, accountNames.get(0)); assertEquals(secret, mAccountDb.getSecret(accountName)); assertEquals(OtpType.TOTP, mAccountDb.getType(accountName)); assertFalse(getActivity().isFinishing()); // AuthenticatorActivity should continue } public void testAccountSetup_validHotpUriWithoutCounterAccepted() throws Throwable { getActivity(); String secret = "CQAHUXJ2VWDI7WFF"; String accountName = "9.99.99.999"; callOnActivityResultOnUiThreadWithScannedUri( "otpauth://hotp/" + accountName + "?secret=" + secret); List<String> accountNames = new ArrayList<String>(); assertEquals(1, mAccountDb.getNames(accountNames)); assertEquals(accountName, accountNames.get(0)); assertEquals(secret, mAccountDb.getSecret(accountName)); assertEquals(OtpType.HOTP, mAccountDb.getType(accountName)); assertEquals(new Integer(0), mAccountDb.getCounter(accountName)); assertFalse(getActivity().isFinishing()); // AuthenticatorActivity should continue } public void testAccountSetup_validHotpUriWithCounterAccepted() throws Throwable { getActivity(); String secret = "CQAHUXJ2VWDI7WFF"; String accountName = "9.99.99.999"; callOnActivityResultOnUiThreadWithScannedUri( "otpauth://hotp/" + accountName + "?secret=" + secret + "&counter=264"); List<String> accountNames = new ArrayList<String>(); assertEquals(1, mAccountDb.getNames(accountNames)); assertEquals(accountName, accountNames.get(0)); assertEquals(secret, mAccountDb.getSecret(accountName)); assertEquals(OtpType.HOTP, mAccountDb.getType(accountName)); assertEquals(new Integer(264), mAccountDb.getCounter(accountName)); assertFalse(getActivity().isFinishing()); // AuthenticatorActivity should continue } ///////////////////// Tests with Scanned URIs returned in ActivityResult //////////////// private void checkBadAccountSetup(String uri, int dialogId) throws Throwable { getActivity(); callOnActivityResultOnUiThreadWithScannedUri(uri); List<String> accountNames = new ArrayList<String>(); mAccountDb.getNames(accountNames); MoreAsserts.assertEmpty(accountNames); TestUtilities.assertDialogWasDisplayed(getActivity(), dialogId); assertFalse(getActivity().isFinishing()); // AuthenticatorActivity should continue } public void testAccountSetup_uriWithMissingSecretRejected() throws Throwable { checkBadAccountSetup("otpauth://totp/9.99.99.999?secret2=unused", Utilities.INVALID_SECRET_IN_QR_CODE); } public void testAccountSetup_uriWithEmptySecretRejected() throws Throwable { checkBadAccountSetup("otpauth://totp/9.99.99.999?secret=", Utilities.INVALID_SECRET_IN_QR_CODE); } public void testAccountSetup_uriWithInvalidSecretRejected() throws Throwable { // The URI contains an invalid base32 characters: 1 and 8 checkBadAccountSetup("otpauth://totp/9.99.99.999?secret=CQ1HUXJ2VWDI8WFF", Utilities.INVALID_SECRET_IN_QR_CODE); } public void testAccountSetup_withNullUri() throws Throwable { checkBadAccountSetup(null, Utilities.INVALID_QR_CODE); } public void testAccountSetup_withNullScheme() throws Throwable { checkBadAccountSetup("totp/9.99.99.999?secret=CQAHUXJ2VWDI7WFF", Utilities.INVALID_QR_CODE); } public void testAccountSetup_withBadScheme() throws Throwable { checkBadAccountSetup("otpauth?//totp/9.99.99.999?secret=CQAHUXJ2VWDI7WFF", Utilities.INVALID_QR_CODE); } public void testAccountSetup_withEmptyAuthority() throws Throwable { checkBadAccountSetup("otpauth:///9.99.99.999?secret=CQAHUXJ2VWDI7WFF", Utilities.INVALID_QR_CODE); } public void testAccountSetup_withBadAuthority() throws Throwable { checkBadAccountSetup("otpauth://bad/9.99.99.999?secret=CQAHUXJ2VWDI7WFF", Utilities.INVALID_QR_CODE); } public void testAccountSetup_withEmptyUserAccount() throws Throwable { checkBadAccountSetup("otpauth://totp/?secret=CQAHUXJ2VWDI7WFF", Utilities.INVALID_QR_CODE); } public void testAccountSetup_withWhiteSpaceForUserAccount() throws Throwable { checkBadAccountSetup("otpauth://totp/ ?secret=CQAHUXJ2VWDI7WFF", Utilities.INVALID_QR_CODE); } public void testAccountSetup_withCounterTooBig() throws Throwable { checkBadAccountSetup("otpauth://hotp/?secret=CQAHUXJ2VWDI7WFF&counter=34359738368", Utilities.INVALID_QR_CODE); } public void testAccountSetup_withNonNumericCounter() throws Throwable { checkBadAccountSetup("otpauth://hotp/?secret=CQAHUXJ2VWDI7WFF&counter=abc", Utilities.INVALID_QR_CODE); } public void testAccountSetup_withNullIntent() throws Throwable { getActivity(); callOnActivityResultOnUiThread(AuthenticatorActivity.SCAN_REQUEST, Activity.RESULT_OK, null); List<String> accountNames = new ArrayList<String>(); mAccountDb.getNames(accountNames); MoreAsserts.assertEmpty(accountNames); TestUtilities.assertDialogWasDisplayed(getActivity(), Utilities.INVALID_QR_CODE); assertFalse(getActivity().isFinishing()); // AuthenticatorActivity should continue } /** * Invokes the activity's {@code onActivityResult} as though it received the specified scanned * URI. */ private void callOnActivityResultOnUiThreadWithScannedUri(String uri) throws Throwable { Intent intent = new Intent(Intent.ACTION_VIEW, null); intent.putExtra("SCAN_RESULT", uri); callOnActivityResultOnUiThread(AuthenticatorActivity.SCAN_REQUEST, Activity.RESULT_OK, intent); } private void callOnActivityResultOnUiThread( final int requestCode, final int resultCode, final Intent intent) throws Throwable { runTestOnUiThread(new Runnable() { @Override public void run () { getActivity().onActivityResult(requestCode, resultCode, intent); } }); } public void testDirectAccountSetupWithConfirmationAccepted() throws Throwable { // start AuthenticatorActivity with a valid Uri for account setup. String secret = "CQAHUXJ2VWDI7WFF"; String accountName = "9.99.99.999"; Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("otpauth://totp/" + accountName + "?secret=" + secret)); setActivityIntent(intent); getActivity(); // check main screen does not have focus because of save confirmation dialog. View contentView = getActivity().findViewById(R.id.content_no_accounts); assertFalse(contentView.hasWindowFocus()); // click Ok on the dialog box which has focus. TestUtilities.tapDialogPositiveButton(this); // check main screen gets focus back after dialog window disappears. TestUtilities.waitForWindowFocus(contentView); // check update to database. List<String> accountNames = new ArrayList<String>(); assertEquals(1, mAccountDb.getNames(accountNames)); assertEquals(accountName, accountNames.get(0)); assertEquals(secret, mAccountDb.getSecret(accountName)); assertEquals(OtpType.TOTP, mAccountDb.getType(accountName)); } public void testDirectAccountSetupWithConfirmationRejected() throws Throwable { // start AuthenticatorActivity with a valid Uri for account setup. String secret = "CQAHUXJ2VWDI7WFF"; String accountName = "9.99.99.999"; Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("otpauth://totp/" + accountName + "?secret=" + secret)); setActivityIntent(intent); getActivity(); // check main screen does not have focus because of save confirmation dialog. View contentView = getActivity().findViewById(R.id.content_no_accounts); assertFalse(contentView.hasWindowFocus()); // click Cancel on the save confirmation dialog box. TestUtilities.tapDialogNegativeButton(this); // check main screen gets focus back after dialog window disappears. TestUtilities.waitForWindowFocus(contentView); // check database has not been updated. List<String> accountNames = new ArrayList<String>(); assertEquals(0, mAccountDb.getNames(accountNames)); assertEquals(null, mAccountDb.getSecret(accountName)); } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/AuthenticatorActivityPart2Test.java
Java
asf20
10,954
/* * Copyright 2012 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import java.util.concurrent.Executor; /** * {@link Executor} that invokes the provided {@link Runnable} instances immediately on the thread * invoking its {@code execute} method. * * @author klyubin@google.com (Alex Klyubin) */ public class RunImmediatelyOnCallingThreadExecutor implements Executor { @Override public void execute(Runnable command) { command.run(); } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/RunImmediatelyOnCallingThreadExecutor.java
Java
asf20
1,052
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import com.google.android.apps.authenticator.Base32String.DecodingException; import android.test.MoreAsserts; import java.io.UnsupportedEncodingException; import junit.framework.TestCase; /** * Unit test for {@link Base32String} * @author sarvar@google.com (Sarvar Patel) */ public class Base32StringTest extends TestCase { // regression input and output values taken from RFC 4648 // but stripped of the "=" padding from encoded output as required by the // implemented encoding in Base32String.java private static final byte[] INPUT1 = string2Bytes("foo"); private static final byte[] INPUT2 = string2Bytes("foob"); private static final byte[] INPUT3 = string2Bytes("fooba"); private static final byte[] INPUT4 = string2Bytes("foobar"); // RFC 4648 expected encodings for above inputs are: // "MZXW6===", "MZXW6YQ=", "MZXW6YTB", MZXW6YTBOI======". // Base32String encoding, however, drops the "=" padding. private static final String OUTPUT1 = "MZXW6"; private static final String OUTPUT2 = "MZXW6YQ"; private static final String OUTPUT3 = "MZXW6YTB"; private static final String OUTPUT4 = "MZXW6YTBOI"; private static byte[] string2Bytes(String s) { try { return s.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 encoding is unsupported"); } } public void testRegressionValuesFromRfc4648() throws DecodingException { // check encoding assertEquals(OUTPUT1, Base32String.encode(INPUT1)); assertEquals(OUTPUT2, Base32String.encode(INPUT2)); assertEquals(OUTPUT3, Base32String.encode(INPUT3)); assertEquals(OUTPUT4, Base32String.encode(INPUT4)); // check decoding MoreAsserts.assertEquals(INPUT1, Base32String.decode(OUTPUT1)); MoreAsserts.assertEquals(INPUT2, Base32String.decode(OUTPUT2)); MoreAsserts.assertEquals(INPUT3, Base32String.decode(OUTPUT3)); MoreAsserts.assertEquals(INPUT4, Base32String.decode(OUTPUT4)); } /** * Base32String implementation is not the same as that of RFC 4648, it drops * the last incomplete chunk and thus accepts encoded strings that should have * been rejected; also this results in multiple encoded strings being decoded * to the same byte array. * This test will catch any changes made regarding this behavior. */ public void testAmbiguousDecoding() throws DecodingException { byte[] b16 = Base32String.decode("7777777777777777"); // 16 7s. byte[] b17 = Base32String.decode("77777777777777777"); // 17 7s. MoreAsserts.assertEquals(b16, b17); } // returns true if decoded, else false. private byte[] checkDecoding(String s) { try { return Base32String.decode(s); } catch (DecodingException e) { return null; // decoding failed. } } public void testSmallDecodingsAndFailures() { // decoded, but not enough to return any bytes. assertEquals(0, checkDecoding("A").length); assertEquals(0, checkDecoding("").length); assertEquals(0, checkDecoding(" ").length); // decoded successfully and returned 1 byte. assertEquals(1, checkDecoding("AA").length); assertEquals(1, checkDecoding("AAA").length); // decoded successfully and returned 2 bytes. assertEquals(2, checkDecoding("AAAA").length); // acceptable separators " " and "-" which should be ignored assertEquals(2, checkDecoding("AA-AA").length); assertEquals(2, checkDecoding("AA-AA").length); MoreAsserts.assertEquals(checkDecoding("AA-AA"), checkDecoding("AA AA")); MoreAsserts.assertEquals(checkDecoding("AAAA"), checkDecoding("AA AA")); // 1, 8, 9, 0 are not a valid character, decoding should fail assertNull(checkDecoding("11")); assertNull(checkDecoding("A1")); assertNull(checkDecoding("AAA8")); assertNull(checkDecoding("AAA9")); assertNull(checkDecoding("AAA0")); // non-alphanumerics (except =) are not valid characters and decoding should fail assertNull(checkDecoding("AAA,")); assertNull(checkDecoding("AAA;")); assertNull(checkDecoding("AAA.")); assertNull(checkDecoding("AAA!")); // this just documents that a null string causes a nullpointerexception. try { checkDecoding(null); fail(); } catch (NullPointerException e) { // expected. } } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/Base32StringTest.java
Java
asf20
4,981
/* * Copyright 2012 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import android.os.Build; import android.os.Bundle; import android.test.InstrumentationTestRunner; import org.mockito.Mockito; /** * {@link InstrumentationTestRunner} that makes it possible to use Mockito on Eclair * without changing any other code. The runner by the framework is created before any tests are run * and thus has the opportunity to fix Mockito on Eclair. * * @author klyubin@google.com (Alex Klyubin) */ public class MockitoWorkaroundForEclairInstrumentationTestRunner extends InstrumentationTestRunner { @Override public void onCreate(Bundle arguments) { // This is a workaround for Eclair for http://code.google.com/p/mockito/issues/detail?id=354. // Mockito loads the Android-specific MockMaker (provided by DexMaker) using the current // thread's context ClassLoader. On Eclair this ClassLoader is set to the system ClassLoader // which doesn't know anything about this app (which includes DexMaker). The workaround is to // use the app's ClassLoader. // TODO(klyubin): Remove this workaround (and most likely this whole class) once Eclair is no // longer supported. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) { // Make Mockito look up a MockMaker using the app's ClassLoader, by asking Mockito to create // a mock. ClassLoader originalContextClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(Mockito.class.getClassLoader()); Mockito.mock(Runnable.class); Thread.currentThread().setContextClassLoader(originalContextClassLoader); } super.onCreate(arguments); } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/MockitoWorkaroundForEclairInstrumentationTestRunner.java
Java
asf20
2,313
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.wizard; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import com.google.android.apps.authenticator.AuthenticatorActivity; import com.google.android.apps.authenticator.TestUtilities; import com.google.android.apps.authenticator.testability.DependencyInjector; import com.google.android.apps.authenticator2.R; import android.content.ComponentName; import android.content.Intent; import android.os.Bundle; import android.test.ActivityUnitTestCase; import android.view.View; import android.widget.TextView; import java.io.Serializable; /** * Unit tests for {@link WizardPageActivity}. * * @author klyubin@google.com (Alex Klyubin) */ public class WizardPageActivityTest extends ActivityUnitTestCase<WizardPageActivityTest.TestableWizardPageActivity> { public WizardPageActivityTest() { super(TestableWizardPageActivity.class); } @Override protected void setUp() throws Exception { super.setUp(); DependencyInjector.resetForIntegrationTesting(getInstrumentation().getTargetContext()); } @Override protected void tearDown() throws Exception { DependencyInjector.close(); super.tearDown(); } public void testCleanStartSucceeds_withNullWizardState() { WizardPageActivity<WizardState> activity = startActivityWithWizardState(null); assertNull(activity.getWizardState()); } public void testCleanStartSucceeds_withWizardState() { WizardState wizardState = new WizardState(); wizardState.mText = "123"; WizardPageActivity<WizardState> activity = startActivityWithWizardState(wizardState); // Check that the wizard state has been loaded by the Activity from the Intent assertEquals(wizardState, activity.getWizardState()); } public void testStartWithInstanceStateLoadsWizardStateFromBundle() { WizardState wizardStateInIntent = new WizardState(); WizardState wizardStateInBundle = new WizardState(); wizardStateInBundle.mText = "1234"; Bundle savedInstanceState = new Bundle(); savedInstanceState.putSerializable(WizardPageActivity.KEY_WIZARD_STATE, wizardStateInBundle); WizardPageActivity<WizardState> activity = startActivity(getStartIntent(wizardStateInIntent), savedInstanceState, null); // Check that the wizard state has been loaded by the Activity from the Bundle assertEquals(wizardStateInBundle, activity.getWizardState()); } public void testOnSaveSaveInstanceStateSavesWizardStateInBundle() { WizardState wizardState = new WizardState(); wizardState.mText = "test"; WizardPageActivity<WizardState> activity = startActivityWithWizardState(wizardState); Bundle savedInstanceState = new Bundle(); activity.onSaveInstanceState(savedInstanceState); assertEquals( wizardState, savedInstanceState.getSerializable(WizardPageActivity.KEY_WIZARD_STATE)); } public void testSetWizardState() { WizardPageActivity<WizardState> activity = startActivity(); WizardState wizardState = new WizardState(); wizardState.mText = "test"; assertFalse(wizardState.equals(activity.getWizardState())); activity.setWizardState(wizardState); assertEquals(wizardState, activity.getWizardState()); } public void testUiStateAfterCreate() { WizardPageActivity<WizardState> activity = startActivity(); TestUtilities.assertViewVisibleOnScreen(activity.mLeftButton); TestUtilities.assertViewVisibleOnScreen(activity.mRightButton); TestUtilities.assertViewOrAnyParentVisibilityGone(activity.mMiddleButton); TestUtilities.assertViewOrAnyParentVisibilityGone(activity.mCancelButton); assertEquals( activity.getString(R.string.button_back), ((TextView) activity.mLeftButton).getText()); assertEquals(activity.getString( R.string.button_next), ((TextView) activity.mRightButton).getText()); } public void testUiStateInButtonBarMiddleButtonOnlyMode() { WizardPageActivity<WizardState> activity = startActivity(); activity.setButtonBarModeMiddleButtonOnly(); TestUtilities.assertViewVisibleOnScreen(activity.mMiddleButton); TestUtilities.assertViewOrAnyParentVisibilityGone(activity.mLeftButton); TestUtilities.assertViewOrAnyParentVisibilityGone(activity.mRightButton); TestUtilities.assertViewOrAnyParentVisibilityGone(activity.mCancelButton); } public void testUiStateInInlineProgressMode() { WizardPageActivity<WizardState> activity = startActivity(); activity.showInlineProgress(null); TestUtilities.assertViewVisibleOnScreen(activity.mCancelButton); TestUtilities.assertViewOrAnyParentVisibilityGone(activity.mLeftButton); TestUtilities.assertViewOrAnyParentVisibilityGone(activity.mRightButton); TestUtilities.assertViewOrAnyParentVisibilityGone(activity.mMiddleButton); assertEquals( activity.getString(R.string.cancel), ((TextView) activity.mCancelButton).getText()); } public void testInlineProgressCallbackInvokedWhenCancelButtonPressed() { WizardPageActivity<WizardState> activity = startActivity(); View.OnClickListener listener = mock(View.OnClickListener.class); activity.showInlineProgress(listener); activity.mCancelButton.performClick(); verify(listener).onClick(activity.mCancelButton); } public void testButtonBarModeRestoredAfterDismissingInlineProgress() { WizardPageActivity<WizardState> activity = startActivity(); activity.setButtonBarModeMiddleButtonOnly(); activity.showInlineProgress(null); activity.dismissInlineProgress(); TestUtilities.assertViewVisibleOnScreen(activity.mMiddleButton); TestUtilities.assertViewOrAnyParentVisibilityGone(activity.mLeftButton); TestUtilities.assertViewOrAnyParentVisibilityGone(activity.mRightButton); TestUtilities.assertViewOrAnyParentVisibilityGone(activity.mCancelButton); } public void testStartPageActivity() { WizardPageActivity<WizardState> activity = startActivity(); activity.getWizardState().mText = "token"; activity.startPageActivity(TestableWizardPageActivity.class); Intent intent = getStartedActivityIntent(); assertNotNull(intent); assertEquals( new ComponentName(activity, TestableWizardPageActivity.class), intent.getComponent()); assertEquals( activity.getWizardState(), intent.getSerializableExtra(WizardPageActivity.KEY_WIZARD_STATE)); } public void testStartPageActivityForResult() { WizardPageActivity<WizardState> activity = startActivity(); activity.getWizardState().mText = "token"; activity.startPageActivityForResult(TestableWizardPageActivity.class, 13); assertEquals(13, getStartedActivityRequest()); Intent intent = getStartedActivityIntent(); assertNotNull(intent); assertEquals( new ComponentName(activity, TestableWizardPageActivity.class), intent.getComponent()); assertEquals( activity.getWizardState(), intent.getSerializableExtra(WizardPageActivity.KEY_WIZARD_STATE)); } public void testExitWizardLaunchesAuthenticatorActivity() { WizardPageActivity<WizardState> activity = startActivity(); activity.exitWizard(); Intent intent = getStartedActivityIntent(); assertNotNull(intent); assertEquals(new ComponentName(activity, AuthenticatorActivity.class), intent.getComponent()); assertTrue( (intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_TOP) == Intent.FLAG_ACTIVITY_CLEAR_TOP); } public void testLeftButtonInvokesOnLeftButtonPressed() { TestableWizardPageActivity activity = startActivity(); activity.mLeftButton.performClick(); assertTrue(activity.mOnLeftButtonPressedInvoked); } public void testRightButtonInvokesOnRightButtonPressed() { TestableWizardPageActivity activity = startActivity(); activity.mRightButton.performClick(); assertTrue(activity.mOnRightButtonPressedInvoked); } public void testMiddleButtonInvokesOnMiddleButtonPressed() { TestableWizardPageActivity activity = startActivity(); activity.setButtonBarModeMiddleButtonOnly(); activity.mMiddleButton.performClick(); assertTrue(activity.mOnMiddleButtonPressedInvoked); } public void testOnLeftButtonPressedInvokesOnBackPressed() { TestableWizardPageActivity activity = startActivity(); activity.onLeftButtonPressed(); assertTrue(activity.mOnBackPressedInvoked); } private static Intent getStartIntent(WizardState wizardState) { Intent intent = new Intent(); if (wizardState != null) { intent.putExtra(WizardPageActivity.KEY_WIZARD_STATE, wizardState); } return intent; } private TestableWizardPageActivity startActivity() { return startActivityWithWizardState(new WizardState()); } private TestableWizardPageActivity startActivityWithWizardState(WizardState wizardState) { return startActivity(getStartIntent(wizardState), null, null); } /** * Subclass of {@link WizardPageActivity} to test whether certain methods of the class are * invoked. */ public static class TestableWizardPageActivity extends WizardPageActivity<WizardState> { private boolean mOnLeftButtonPressedInvoked; private boolean mOnRightButtonPressedInvoked; private boolean mOnMiddleButtonPressedInvoked; private boolean mOnBackPressedInvoked; @Override protected void onLeftButtonPressed() { mOnLeftButtonPressedInvoked = true; super.onLeftButtonPressed(); } @Override protected void onRightButtonPressed() { mOnRightButtonPressedInvoked = true; super.onRightButtonPressed(); } @Override protected void onMiddleButtonPressed() { mOnMiddleButtonPressedInvoked = true; super.onMiddleButtonPressed(); } @Override public void onBackPressed() { mOnBackPressedInvoked = true; super.onBackPressed(); } } private static class WizardState implements Serializable { private String mText; @Override public int hashCode() { return (mText != null) ? mText.hashCode() : 0; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } WizardState other = (WizardState) obj; if (mText == null) { if (other.mText != null) { return false; } } else if (!mText.equals(other.mText)) { return false; } return true; } } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/wizard/WizardPageActivityTest.java
Java
asf20
11,172
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.wizard; import com.google.android.apps.authenticator.TestUtilities; import com.google.android.apps.authenticator.testability.DependencyInjector; import com.google.android.apps.authenticator2.R; import android.content.ComponentName; import android.content.Intent; import android.test.ActivityInstrumentationTestCase2; import android.view.View; import java.io.Serializable; import java.util.concurrent.TimeoutException; /** * Base class for unit tests of Activity classes representing pages of a wizard. * * @author klyubin@google.com (Alex Klyubin) */ @SuppressWarnings("rawtypes") public class WizardPageActivityTestBase< A extends WizardPageActivity, WizardState extends Serializable> extends ActivityInstrumentationTestCase2<A> { public WizardPageActivityTestBase(Class<A> activityClass) { super(TestUtilities.APP_PACKAGE_NAME, activityClass); } @Override protected void setUp() throws Exception { super.setUp(); DependencyInjector.resetForIntegrationTesting(getInstrumentation().getTargetContext()); TestUtilities.withLaunchPreventingStartActivityListenerInDependencyResolver(); } @Override protected void tearDown() throws Exception { DependencyInjector.close(); super.tearDown(); } protected void setWizardStateInActivityIntent(WizardState state) { setActivityIntent(new Intent().putExtra(WizardPageActivity.KEY_WIZARD_STATE, state)); } @SuppressWarnings("unchecked") protected WizardState getWizardStateFromIntent(Intent intent) { return (WizardState) intent.getSerializableExtra(WizardPageActivity.KEY_WIZARD_STATE); } /** * Asserts that pressing the {@code Back} key finishes the Activity under test. */ protected void assertBackKeyFinishesActivity() throws InterruptedException, TimeoutException { TestUtilities.invokeActivityOnBackPressedOnUiThread(getActivity()); assertTrue(getActivity().isFinishing()); } /** * Asserts that pressing the {@code Back} key does not finish the Activity under test. */ protected void assertBackKeyDoesNotFinishActivity() throws InterruptedException, TimeoutException { TestUtilities.invokeActivityOnBackPressedOnUiThread(getActivity()); assertFalse(getActivity().isFinishing()); } protected void assertLeftButtonPressFinishesActivity() { pressButton(R.id.button_left); assertTrue(getActivity().isFinishing()); } private void pressButton(int buttonViewId) { View button = getActivity().findViewById(buttonViewId); // The button can only be pressed if it's on screen and visible assertNotNull(button); TestUtilities.assertViewVisibleOnScreen(button); assertTrue(button.isEnabled()); TestUtilities.assertViewVisibleOnScreen(button); TestUtilities.clickView(getInstrumentation(), button); } protected void pressLeftButton() { pressButton(R.id.button_left); } protected void pressRightButton() { pressButton(R.id.button_right); } protected void pressMiddleButton() { pressButton(R.id.button_middle); } private Intent pressButtonAndCaptureActivityStartIntent(int buttonViewId) { pressButton(buttonViewId); return TestUtilities.verifyWithTimeoutThatStartActivityAttemptedExactlyOnce(); } protected Intent pressMiddleButtonAndCaptureActivityStartIntent() { return pressButtonAndCaptureActivityStartIntent(R.id.button_middle); } protected Intent pressRightButtonAndCaptureActivityStartIntent() { return pressButtonAndCaptureActivityStartIntent(R.id.button_right); } protected void assertIntentForClassInTargetPackage(Class<?> expectedClass, Intent intent) { assertEquals( new ComponentName( getInstrumentation().getTargetContext(), expectedClass), intent.getComponent()); } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/wizard/WizardPageActivityTestBase.java
Java
asf20
4,456
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.MockitoAnnotations.initMocks; import com.google.android.apps.authenticator.AccountDb.OtpType; import com.google.android.apps.authenticator.dataimport.ImportController; import com.google.android.apps.authenticator.howitworks.IntroEnterPasswordActivity; import com.google.android.apps.authenticator.testability.DependencyInjector; import com.google.android.apps.authenticator.testability.StartActivityListener; import com.google.android.apps.authenticator2.R; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.test.ActivityInstrumentationTestCase2; import android.test.ViewAsserts; import android.text.ClipboardManager; import android.view.KeyEvent; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.Mockito; import java.util.ArrayList; import java.util.List; /** * Unit test for authenticator activity (part/shard 1). * * @author sarvar@google.com (Sarvar Patel) */ public class AuthenticatorActivityTest extends ActivityInstrumentationTestCase2<AuthenticatorActivity> { private AccountDb mAccountDb; @Mock private ImportController mMockDataImportController; public AuthenticatorActivityTest() { super(TestUtilities.APP_PACKAGE_NAME, AuthenticatorActivity.class); } @Override protected void setUp() throws Exception { super.setUp(); DependencyInjector.resetForIntegrationTesting(getInstrumentation().getTargetContext()); mAccountDb = DependencyInjector.getAccountDb(); initMocks(this); DependencyInjector.setDataImportController(mMockDataImportController); TestUtilities.withLaunchPreventingStartActivityListenerInDependencyResolver(); } @Override protected void tearDown() throws Exception { // Stop the activity to avoid it using the DependencyInjector after it's been closed. TestUtilities.invokeFinishActivityOnUiThread(getActivity()); DependencyInjector.close(); super.tearDown(); } public void testGetTitle() { assertEquals(getActivity().getString(R.string.app_name), getActivity().getTitle()); } //////////////////////// Main screen UI Tests /////////////////////////////// public void testNoAccountUi() throws Throwable { getActivity(); ListView userList = (ListView) getActivity().findViewById(R.id.user_list); TextView enterPinPrompt = (TextView) getActivity().findViewById(R.id.enter_pin_prompt); Button howItWorksButton = (Button) getActivity().findViewById(R.id.how_it_works_button); Button addAccountButton = (Button) getActivity().findViewById(R.id.add_account_button); View contentWhenNoAccounts = getActivity().findViewById(R.id.content_no_accounts); // check existence of fields assertNotNull(userList); assertNotNull(enterPinPrompt); assertNotNull(howItWorksButton); assertNotNull(addAccountButton); assertNotNull(contentWhenNoAccounts); // check visibility View origin = getActivity().getWindow().getDecorView(); ViewAsserts.assertOnScreen(origin, enterPinPrompt); ViewAsserts.assertOnScreen(origin, howItWorksButton); ViewAsserts.assertOnScreen(origin, addAccountButton); ViewAsserts.assertOnScreen(origin, contentWhenNoAccounts); assertFalse(userList.isShown()); } public void testGetOtpWithOneTotpAccount() throws Throwable { mAccountDb.update( "johndoeTotp@gmail.com", "7777777777777777", "johndoeTotp@gmail.com", OtpType.TOTP, null); ListView userList = (ListView) getActivity().findViewById(R.id.user_list); assertEquals(1, userList.getChildCount()); View listEntry = userList.getChildAt(0); String user = ((TextView) listEntry.findViewById(R.id.current_user)).getText().toString(); String pin = ((TextView) listEntry.findViewById(R.id.pin_value)).getText().toString(); assertEquals("johndoeTotp@gmail.com", user); assertTrue(Integer.parseInt(pin) >= 0 && Integer.parseInt(pin) <= 999999); assertEquals(6, pin.length()); assertFalse(listEntry.findViewById(R.id.next_otp).isShown()); assertTrue(listEntry.findViewById(R.id.countdown_icon).isShown()); } public void testGetOtpWithOneHotpAccount() throws Throwable { mAccountDb.update( "johndoeHotp@gmail.com", "7777777777777777", "johndoeHotp@gmail.com", OtpType.HOTP, null); ListView userList = (ListView) getActivity().findViewById(R.id.user_list); assertEquals(1, userList.getChildCount()); View listEntry = userList.getChildAt(0); String user = ((TextView) listEntry.findViewById(R.id.current_user)).getText().toString(); String pin = ((TextView) listEntry.findViewById(R.id.pin_value)).getText().toString(); assertEquals("johndoeHotp@gmail.com", user); assertEquals(getActivity().getString(R.string.empty_pin), pin); // starts empty assertFalse(listEntry.findViewById(R.id.countdown_icon).isShown()); View buttonView = listEntry.findViewById(R.id.next_otp); assertTrue(buttonView.isShown()); // get next Otp value by clicking icon TestUtilities.clickView(getInstrumentation(), buttonView); pin = ((TextView) listEntry.findViewById(R.id.pin_value)).getText().toString(); assertEquals("683298", pin); } public void testGetOtpWithMultipleAccounts() throws Throwable { mAccountDb.update( "johndoeHotp@gmail.com", "7777777777777777", "johndoeHotp@gmail.com", OtpType.HOTP, null); mAccountDb.update( "johndoeTotp1@gmail.com", "2222222222222222", "johndoeTotp1@gmail.com", OtpType.TOTP, null); mAccountDb.update( "johndoeTotp2@gmail.com", "3333333333333333", "johndoeTotp2@gmail.com", OtpType.TOTP, null); ListView userList = (ListView) getActivity().findViewById(R.id.user_list); assertEquals(3, userList.getChildCount()); // check hotp account View listEntry0 = userList.getChildAt(0); String user = ((TextView) listEntry0.findViewById(R.id.current_user)).getText().toString(); String pin = ((TextView) listEntry0.findViewById(R.id.pin_value)).getText().toString(); assertEquals("johndoeHotp@gmail.com", user); assertEquals(getActivity().getString(R.string.empty_pin), pin); // starts empty assertFalse(listEntry0.findViewById(R.id.countdown_icon).isShown()); View buttonView = listEntry0.findViewById(R.id.next_otp); assertTrue(buttonView.isShown()); // get next Otp value by clicking icon TestUtilities.clickView(getInstrumentation(), buttonView); listEntry0 = userList.getChildAt(0); // get refreshed value after clicking nextOtp button. pin = ((TextView) listEntry0.findViewById(R.id.pin_value)).getText().toString(); assertEquals("683298", pin); // check first totp account View listEntry1 = userList.getChildAt(1); user = ((TextView) listEntry1.findViewById(R.id.current_user)).getText().toString(); pin = ((TextView) listEntry1.findViewById(R.id.pin_value)).getText().toString(); assertEquals("johndoeTotp1@gmail.com", user); assertTrue(Integer.parseInt(pin) > 0 && Integer.parseInt(pin) <= 999999); assertFalse(listEntry1.findViewById(R.id.next_otp).isShown()); assertTrue(listEntry1.findViewById(R.id.countdown_icon).isShown()); View listEntry2 = userList.getChildAt(2); // check second totp account user = ((TextView) listEntry2.findViewById(R.id.current_user)).getText().toString(); pin = ((TextView) listEntry2.findViewById(R.id.pin_value)).getText().toString(); assertEquals("johndoeTotp2@gmail.com", user); assertTrue(Integer.parseInt(pin) > 0 && Integer.parseInt(pin) <= 999999); assertFalse(listEntry1.findViewById(R.id.next_otp).isShown()); assertTrue(listEntry1.findViewById(R.id.countdown_icon).isShown()); } ////////////////////////// Context Menu Tests //////////////////////////// public void testContextMenuCheckCode() throws Exception { mAccountDb.update( "johndoeHotp@gmail.com", "7777777777777777", "johndoeHotp@gmail.com", OtpType.HOTP, null); ListView userList = (ListView) getActivity().findViewById(R.id.user_list); View listEntry0 = userList.getChildAt(0); TestUtilities.openContextMenuAndInvokeItem( getInstrumentation(), getActivity(), listEntry0, AuthenticatorActivity.CHECK_KEY_VALUE_ID); Intent launchIntent = TestUtilities.verifyWithTimeoutThatStartActivityAttemptedExactlyOnce(); assertEquals( new ComponentName(getInstrumentation().getTargetContext(), CheckCodeActivity.class), launchIntent.getComponent()); assertEquals("johndoeHotp@gmail.com", launchIntent.getStringExtra("user")); } public void testContextMenuRemove() throws Exception { mAccountDb.update( "johndoeHotp@gmail.com", "7777777777777777", "johndoeHotp@gmail.com", OtpType.HOTP, null); ListView userList = (ListView) getActivity().findViewById(R.id.user_list); View listEntry0 = userList.getChildAt(0); TestUtilities.openContextMenuAndInvokeItem( getInstrumentation(), getActivity(), listEntry0, AuthenticatorActivity.REMOVE_ID); // Select Remove on confirmation dialog to remove account. sendKeys(KeyEvent.KEYCODE_DPAD_DOWN); sendKeys(KeyEvent.KEYCODE_DPAD_CENTER); // check main screen gets focus back; TestUtilities.waitForWindowFocus(listEntry0); // check that account is deleted in database. assertEquals(0, mAccountDb.getNames(new ArrayList<String>())); } public void testContextMenuRename() throws Exception { mAccountDb.update( "johndoeHotp@gmail.com", "7777777777777777", "johndoeHotp@gmail.com", OtpType.HOTP, null); ListView userList = (ListView) getActivity().findViewById(R.id.user_list); View listEntry0 = userList.getChildAt(0); TestUtilities.openContextMenuAndInvokeItem( getInstrumentation(), getActivity(), listEntry0, AuthenticatorActivity.RENAME_ID); // Type new name and select save on dialog. sendKeys("21*DPAD_RIGHT"); // move right to end; sendKeys("21*DEL"); // delete the entire name sendKeys("N E W N A M E AT G M A I L PERIOD C O M"); sendKeys("DPAD_DOWN"); TestUtilities.tapDialogPositiveButton(this); // select save on the dialog // check main screen gets focus back; listEntry0 = userList.getChildAt(0); TestUtilities.waitForWindowFocus(listEntry0); // check update to database. List<String> accountNames = new ArrayList<String>(); assertEquals(1, mAccountDb.getNames(accountNames)); assertEquals("newname@gmail.com", accountNames.get(0)); } public void testContextMenuCopyToClipboard() throws Exception { // use HOTP to avoid any timing issues when "current" pin is compared with clip board text. mAccountDb.update( "johndoeHotp@gmail.com", "7777777777777777", "johndoeHotp@gmail.com", OtpType.HOTP, null); ListView userList = (ListView) getActivity().findViewById(R.id.user_list); // find and click next otp button. View buttonView = getActivity().findViewById(R.id.next_otp); TestUtilities.clickView(getInstrumentation(), buttonView); // get the pin being displayed View listEntry0 = userList.getChildAt(0); String pin = ((TextView) listEntry0.findViewById(R.id.pin_value)).getText().toString(); TestUtilities.openContextMenuAndInvokeItem( getInstrumentation(), getActivity(), listEntry0, AuthenticatorActivity.COPY_TO_CLIPBOARD_ID); // check clip board value. Context context = getInstrumentation().getTargetContext(); ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); assertEquals(pin, clipboard.getText()); } /////////////////////////// Options Menu Tests ///////////////////////////// private void checkOptionsMenuItemWithComponent(int itemId, Class<?> cls) throws Exception { TestUtilities.openOptionsMenuAndInvokeItem(getInstrumentation(), getActivity(), itemId); Intent launchIntent = TestUtilities.verifyWithTimeoutThatStartActivityAttemptedExactlyOnce(); assertEquals(new ComponentName(getInstrumentation().getTargetContext(), cls), launchIntent.getComponent()); } public void testOptionsMenuHowItWorks() throws Exception { checkOptionsMenuItemWithComponent(R.id.how_it_works, IntroEnterPasswordActivity.class); } public void testOptionsMenuAddAccount() throws Exception { checkOptionsMenuItemWithComponent(R.id.add_account, AddOtherAccountActivity.class); } public void testOptionsMenuSettings() throws Exception { checkOptionsMenuItemWithComponent(R.id.settings, SettingsActivity.class); } public void testIntentActionScanBarcode_withScannerInstalled() throws Exception { setActivityIntent(new Intent(AuthenticatorActivity.ACTION_SCAN_BARCODE)); getActivity(); Intent launchIntent = TestUtilities.verifyWithTimeoutThatStartActivityAttemptedExactlyOnce(); assertEquals("com.google.zxing.client.android.SCAN", launchIntent.getAction()); assertEquals("QR_CODE_MODE", launchIntent.getStringExtra("SCAN_MODE")); assertEquals(false, launchIntent.getExtras().get("SAVE_HISTORY")); } public void testIntentActionScanBarcode_withScannerNotInstalled() throws Exception { // When no barcode scanner is installed no matching activities are found as emulated below. StartActivityListener mockStartActivityListener = mock(StartActivityListener.class); doThrow(new ActivityNotFoundException()) .when(mockStartActivityListener).onStartActivityInvoked( Mockito.<Context>anyObject(), Mockito.<Intent>anyObject()); DependencyInjector.setStartActivityListener(mockStartActivityListener); setActivityIntent(new Intent(AuthenticatorActivity.ACTION_SCAN_BARCODE)); getActivity(); TestUtilities.assertDialogWasDisplayed( getActivity(), Utilities.DOWNLOAD_DIALOG); } /////////////////////////// Data Import tests ///////////////////////////// public void testLaunchingActivityStartsImportController() { AuthenticatorActivity activity = getActivity(); ArgumentCaptor<Context> contextArgCaptor = ArgumentCaptor.forClass(Context.class); verify(mMockDataImportController) .start(contextArgCaptor.capture(), Mockito.<ImportController.Listener>anyObject()); assertEquals(activity, contextArgCaptor.getValue()); } public void testImportControllerOldAppUninstallCallbackDisplaysDialog() { final ImportController.Listener listener = startActivityAndGetDataImportListener(); assertNotNull(listener); invokeDataImportListenerOnOldAppUninstallSuggestedOnMainThread(listener, new Intent()); invokeDataImportListenerFinishedOnMainThread(listener); TestUtilities.assertDialogWasDisplayed( getActivity(), AuthenticatorActivity.DIALOG_ID_UNINSTALL_OLD_APP); } public void testImportControllerDataImportedDoesNotBlowUp() { final ImportController.Listener listener = startActivityAndGetDataImportListener(); assertNotNull(listener); invokeDataImportListenerOnDataImportedOnMainThread(listener); invokeDataImportListenerFinishedOnMainThread(listener); getInstrumentation().waitForIdleSync(); } public void testImportControllerUnknownFailureDoesNotBlowUp() { final ImportController.Listener listener = startActivityAndGetDataImportListener(); assertNotNull(listener); invokeDataImportListenerFinishedOnMainThread(listener); getInstrumentation().waitForIdleSync(); } private ImportController.Listener startActivityAndGetDataImportListener() { ArgumentCaptor<ImportController.Listener> listenerArgCaptor = ArgumentCaptor.forClass(ImportController.Listener.class); doNothing().when(mMockDataImportController).start( Mockito.<Context>anyObject(), listenerArgCaptor.capture()); getActivity(); return listenerArgCaptor.getValue(); } private void invokeDataImportListenerOnOldAppUninstallSuggestedOnMainThread( final ImportController.Listener listener, final Intent uninstallIntent) { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { listener.onOldAppUninstallSuggested(uninstallIntent); } }); } private void invokeDataImportListenerOnDataImportedOnMainThread( final ImportController.Listener listener) { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { listener.onDataImported(); } }); } private void invokeDataImportListenerFinishedOnMainThread( final ImportController.Listener listener) { getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { listener.onFinished(); } }); } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/AuthenticatorActivityTest.java
Java
asf20
17,750
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import com.google.android.apps.authenticator.testability.DependencyInjector; import com.google.android.apps.authenticator2.R; import android.content.Intent; import android.preference.Preference; import android.test.ActivityInstrumentationTestCase2; /** * Unit tests for {@link SettingsAboutActivity}. * * @author klyubin@google.com (Alex Klyubin) */ public class SettingsAboutActivityTest extends ActivityInstrumentationTestCase2<SettingsAboutActivity> { public SettingsAboutActivityTest() { super(TestUtilities.APP_PACKAGE_NAME, SettingsAboutActivity.class); } @Override protected void setUp() throws Exception { super.setUp(); DependencyInjector.resetForIntegrationTesting(getInstrumentation().getTargetContext()); TestUtilities.withLaunchPreventingStartActivityListenerInDependencyResolver(); } @Override protected void tearDown() throws Exception { DependencyInjector.close(); super.tearDown(); } public void testVersionTakenFromPackageVersion() throws Exception { Preference preference = getActivity().findPreference("version"); String expectedVersion = getInstrumentation().getTargetContext().getPackageManager().getPackageInfo( getActivity().getPackageName(), 0).versionName; assertEquals(expectedVersion, preference.getSummary()); } public void testOpenSourcePreferenceOpensUrl() throws Exception { Intent intent = tapOnPreferenceAndCatchFiredIntent("opensource"); assertDefaultViewActionIntent( getInstrumentation().getTargetContext().getString(R.string.opensource_page_url), intent); } public void testTermsOfServicePreferenceOpensUrl() throws Exception { Intent intent = tapOnPreferenceAndCatchFiredIntent("terms"); assertDefaultViewActionIntent( getInstrumentation().getTargetContext().getString(R.string.terms_page_url), intent); } public void testPrivacyPolicyPreferenceOpensUrl() throws Exception { Intent intent = tapOnPreferenceAndCatchFiredIntent("privacy"); assertDefaultViewActionIntent( getInstrumentation().getTargetContext().getString(R.string.privacy_page_url), intent); } private static void assertDefaultViewActionIntent(String expectedData, Intent intent) { assertEquals("android.intent.action.VIEW", intent.getAction()); assertEquals(expectedData, intent.getDataString()); } private Intent tapOnPreferenceAndCatchFiredIntent(String preferenceKey) { TestUtilities.tapPreference(this, getActivity(), getActivity().findPreference(preferenceKey)); return TestUtilities.verifyWithTimeoutThatStartActivityAttemptedExactlyOnce(); } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/SettingsAboutActivityTest.java
Java
asf20
3,325
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import static org.mockito.Mockito.doReturn; import static org.mockito.MockitoAnnotations.initMocks; import com.google.android.apps.authenticator.AccountDb.OtpType; import com.google.android.apps.authenticator.testability.DependencyInjector; import android.test.AndroidTestCase; import android.test.MoreAsserts; import org.mockito.Mock; import java.util.ArrayList; import java.util.Collection; /** * Unit tests for {@link OtpProvider}. * @author sarvar@google.com (Sarvar Patel) * */ public class OtpProviderTest extends AndroidTestCase { private static final String SECRET = "7777777777777777"; // 16 sevens private static final String SECRET2 = "2222222222222222"; // 16 twos private Collection<String> result = new ArrayList<String>(); private OtpProvider otpProvider; private AccountDb accountDb; @Mock private TotpClock mockTotpClock; @Override public void setUp() throws Exception { super.setUp(); DependencyInjector.resetForIntegrationTesting(getContext()); initMocks(this); DependencyInjector.setTotpClock(mockTotpClock); accountDb = DependencyInjector.getAccountDb(); otpProvider = new OtpProvider(accountDb, mockTotpClock); } @Override protected void tearDown() throws Exception { DependencyInjector.close(); super.tearDown(); } private void addSomeRecords() { accountDb.update("johndoe@gmail.com", SECRET, "johndoe@gmail.com", OtpType.TOTP, null); accountDb.update("amywinehouse@aol.com", SECRET2, "amywinehouse@aol.com", OtpType.TOTP, null); accountDb.update("maryweiss@yahoo.com", SECRET, "maryweiss@yahoo.com", OtpType.HOTP, 0); } public void testEnumerateAccountsNoRecords() throws Exception { assertEquals(0, otpProvider.enumerateAccounts(result)); MoreAsserts.assertEmpty(result); } public void testEnumerateAccounts() throws Exception { addSomeRecords(); otpProvider.enumerateAccounts(result); MoreAsserts.assertContentsInAnyOrder(result, "johndoe@gmail.com", "amywinehouse@aol.com", "maryweiss@yahoo.com"); } public void testGetNextCode() throws Exception { addSomeRecords(); // HOTP, counter at 0, check getNextcode response. assertEquals("683298", otpProvider.getNextCode("maryweiss@yahoo.com")); // counter updated to 1, check response has changed. assertEquals("891123", otpProvider.getNextCode("maryweiss@yahoo.com")); // TOTP: HOTP with current time (seconds / 30) as the counter withTotpClockCurrentTimeSeconds(OtpProvider.DEFAULT_INTERVAL * 1); assertEquals("683298", otpProvider.getNextCode("johndoe@gmail.com")); withTotpClockCurrentTimeSeconds(OtpProvider.DEFAULT_INTERVAL * 2); assertEquals("891123", otpProvider.getNextCode("johndoe@gmail.com")); // Different TOTP account/secret withTotpClockCurrentTimeSeconds(OtpProvider.DEFAULT_INTERVAL * 1234567890L); assertEquals("817746", otpProvider.getNextCode("amywinehouse@aol.com")); } public void testGetNextCodeWithEmptyAccountName() throws Exception { accountDb.update("", SECRET, "", OtpType.HOTP, null); // HOTP, counter at 0, check getNextcode response. assertEquals("683298", otpProvider.getNextCode("")); } public void testRespondToChallengeWithNullChallenge() throws Exception { addSomeRecords(); assertEquals("683298", otpProvider.respondToChallenge("maryweiss@yahoo.com", null)); } public void testRespondToChallenge() throws Exception { addSomeRecords(); assertEquals("308683298", otpProvider.respondToChallenge("maryweiss@yahoo.com", "")); assertEquals("561472261", otpProvider.respondToChallenge("maryweiss@yahoo.com", "this is my challenge")); // TOTP: HOTP with current time (seconds / 30) as the counter withTotpClockCurrentTimeSeconds(OtpProvider.DEFAULT_INTERVAL * 1); assertEquals("308683298", otpProvider.respondToChallenge("johndoe@gmail.com", "")); withTotpClockCurrentTimeSeconds(OtpProvider.DEFAULT_INTERVAL * 2); assertEquals("561472261", otpProvider.respondToChallenge("johndoe@gmail.com", "this is my challenge")); // Different TOTP account/secret withTotpClockCurrentTimeSeconds(OtpProvider.DEFAULT_INTERVAL * 9876543210L); assertEquals("834647199", otpProvider.respondToChallenge("amywinehouse@aol.com", "this is my challenge")); } private void withTotpClockCurrentTimeSeconds(long timeSeconds) { doReturn(Utilities.secondsToMillis(timeSeconds)).when(mockTotpClock).currentTimeMillis(); } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/OtpProviderTest.java
Java
asf20
5,163
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import junit.framework.TestCase; /** * Unit tests for {@link Preconditions}. * * @author klyubin@google.com (Alex Klyubin) */ public class PreconditionsTest extends TestCase { public void testCheckNotNullSingleArg() { Object reference = "test"; assertSame(reference, Preconditions.checkNotNull(reference)); try { Preconditions.checkNotNull(null); fail("NullPointerException should have been thrown"); } catch (NullPointerException e) { // Expected } } public void testCheckArgumentSingleArg() { Preconditions.checkArgument(true); try { Preconditions.checkArgument(false); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { // Expected } } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/PreconditionsTest.java
Java
asf20
1,441
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import junit.framework.TestCase; /** * Unit tests for {@link TotpCounter}. * * @author klyubin@google.com (Alex Klyubin) */ public class TotpCounterTest extends TestCase { public void testConstruct_withInvalidDuration() { try { new TotpCounter(0); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { // Expected } try { new TotpCounter(-3); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { // Expected } } public void testConstruct_withNegativeStartTime() { try { new TotpCounter(1, -3); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { // Expected } } public void testConstruct_withDurationAndStartTime() { TotpCounter counter = new TotpCounter(3, 7); assertEquals(3, counter.getTimeStep()); assertEquals(7, counter.getStartTime()); } public void testConstruct_withDefaultStartTime() { TotpCounter counter = new TotpCounter(11); assertEquals(11, counter.getTimeStep()); assertEquals(0, counter.getStartTime()); } public void testGetValueAtTime_withNegativeTime() { TotpCounter counter = new TotpCounter(3); try { counter.getValueAtTime(-7); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { // Expected } } public void testGetValueAtTime_withTimeBeforeStartTime() { TotpCounter counter = new TotpCounter(3, 11); assertEquals(-1, counter.getValueAtTime(10)); } public void testGetValueAtTime() { TotpCounter counter = new TotpCounter(7, 123); assertEquals(-18, counter.getValueAtTime(0)); assertEquals(-2, counter.getValueAtTime(115)); assertEquals(-1, counter.getValueAtTime(116)); assertEquals(-1, counter.getValueAtTime(117)); assertEquals(-1, counter.getValueAtTime(122)); assertEquals(0, counter.getValueAtTime(123)); assertEquals(0, counter.getValueAtTime(124)); assertEquals(0, counter.getValueAtTime(129)); assertEquals(1, counter.getValueAtTime(130)); assertEquals(1, counter.getValueAtTime(131)); assertEquals(100, counter.getValueAtTime(823)); assertEquals(10000000000L, counter.getValueAtTime(70000000123L)); } public void testGetValueStartTime() { TotpCounter counter = new TotpCounter(7, 123); assertEquals(-577, counter.getValueStartTime(-100)); assertEquals(116, counter.getValueStartTime(-1)); assertEquals(123, counter.getValueStartTime(0)); assertEquals(130, counter.getValueStartTime(1)); assertEquals(137, counter.getValueStartTime(2)); assertEquals(823, counter.getValueStartTime(100)); assertEquals(70000000123L, counter.getValueStartTime(10000000000L)); } public void testValueIncreasesByOneEveryTimeStep() { TotpCounter counter = new TotpCounter(7, 123); assertValueIncreasesByOneEveryTimeStep(counter, 11, 500); assertValueIncreasesByOneEveryTimeStep(counter, Long.MAX_VALUE - 1234567, 500); } public void testValueStartTimeInRangeOverTime() { TotpCounter counter = new TotpCounter(11, 123); assertValueStartTimeInRangeOverTime(counter, 0, 500); assertValueStartTimeInRangeOverTime(counter, Long.MAX_VALUE - 1234567, 500); } private static void assertValueIncreasesByOneEveryTimeStep( TotpCounter counter, long startTime, long duration) { long previousValue = counter.getValueAtTime(startTime); long previousValueStartTime = counter.getValueStartTime(previousValue); // Adjust the start time so that it starts when the counter first assumes the current value long startTimeAdjustment = startTime - previousValueStartTime; startTime -= startTimeAdjustment; duration += startTimeAdjustment; for (long time = startTime, endTime = startTime + duration; time <= endTime; time++) { long value = counter.getValueAtTime(time); if (value != previousValue) { if (value == previousValue + 1) { long timeSincePreviousValueStart = time - previousValueStartTime; if (timeSincePreviousValueStart != counter.getTimeStep()) { fail("Value incremented by 1 at the wrong time: " + time); } previousValue = value; previousValueStartTime = time; } else { fail("Value changed by an unexpected amount " + (value - previousValue) + " at time " + time); } } else if ((time - previousValueStartTime) == counter.getTimeStep()) { fail("Counter value did not change at time " + time); } } } /** * Asserts that during the specified time interval the start time of each value from that * interval is not in the future and also is no older than {@code timeStep - 1}. */ private static void assertValueStartTimeInRangeOverTime( TotpCounter counter, long startTime, long duration) { for (long time = startTime, endTime = startTime + duration; time <= endTime; time++) { long value = counter.getValueAtTime(time); long valueStartTime = counter.getValueStartTime(value); if ((valueStartTime > time) || (valueStartTime <= time - counter.getTimeStep())) { fail("Start time of value " + value + " out of range: time: " + time + ", valueStartTime: " + startTime + ", timeStep: " + counter.getTimeStep()); } } } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/TotpCounterTest.java
Java
asf20
6,145
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.dataimport; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.MockitoAnnotations.initMocks; import com.google.android.apps.authenticator.AccountDb; import com.google.android.apps.authenticator.AccountDb.OtpType; import com.google.android.apps.authenticator.testability.DependencyInjector; import android.content.SharedPreferences; import android.os.Bundle; import android.test.AndroidTestCase; import android.test.MoreAsserts; import org.mockito.Mock; import java.util.ArrayList; import java.util.List; /** * Unit tests for {@link Importer}. * * @author klyubin@google.com (Alex Klyubin) */ public class ImporterTest extends AndroidTestCase { private Importer mImporter; private AccountDb mAccountDb; @Mock private SharedPreferences mMockPreferences; @Mock private SharedPreferences.Editor mMockPreferencesEditor; @Override protected void setUp() throws Exception { super.setUp(); DependencyInjector.resetForIntegrationTesting(getContext()); initMocks(this); doReturn(mMockPreferencesEditor).when(mMockPreferences).edit(); doReturn(true).when(mMockPreferencesEditor).commit(); mAccountDb = DependencyInjector.getAccountDb(); mImporter = new Importer(); } @Override protected void tearDown() throws Exception { DependencyInjector.close(); super.tearDown(); } public void testImport_withNullBundle() { try { mImporter.importFromBundle(null, mAccountDb, mMockPreferences); fail("NullPointerExcepton should have been thrown"); } catch (NullPointerException e) { // Expected } } public void testImport_withNullAccountDb() { mImporter.importFromBundle(new Bundle(), null, mMockPreferences); } public void testImport_withNullPreferences() { mImporter.importFromBundle(new Bundle(), mAccountDb, null); } public void testImportAccountDb_withAccounts() { String account2 = "a@gmail.com"; String account1 = "b@gmail.com"; Bundle bundle = bundle( accountsBundle( accountBundle(account1, "ABCDEFGHI", "hotp", 12345), accountBundle(account2, "ABCDEF", "totp", null)), null); mImporter.importFromBundle(bundle, mAccountDb, null); assertAccountsInDbInOrder(account1, account2); assertAccountInDb(account1, "ABCDEFGHI", OtpType.HOTP, 12345); assertAccountInDb(account2, "ABCDEF", OtpType.TOTP, 0); } public void testImportAccountDbDoesNotOverwriteExistingAccounts() { String account2 = "a@gmail.com"; String account1 = "b@gmail.com"; mAccountDb.update(account1, "AAAAAAAA", account1, OtpType.TOTP, 13); Bundle bundle = bundle( accountsBundle( accountBundle(account1, "ABCDEFGHI", "hotp", 12345), accountBundle(account2, "ABCDEF", "totp", null)), null); mImporter.importFromBundle(bundle, mAccountDb, null); assertAccountsInDbInOrder(account1, account2); assertAccountInDb(account1, "AAAAAAAA", OtpType.TOTP, 13); assertAccountInDb(account2, "ABCDEF", OtpType.TOTP, 0); } public void testImportAccountDb_withAccountsWithMissingName() { // First account's name is missing String account2 = "a@gmail.com"; Bundle bundle = bundle( accountsBundle( accountBundle(null, "ABCDEFGHI", "hotp", 12345), accountBundle(account2, "ABCDEF", "totp", null)), null); mImporter.importFromBundle(bundle, mAccountDb, null); assertAccountsInDbInOrder(account2); assertAccountInDb(account2, "ABCDEF", OtpType.TOTP, 0); } public void testImportAccountDb_withAccountsWithMissingSecret() { // First account's secret is missing String account2 = "a@gmail.com"; Bundle bundle = bundle( accountsBundle( accountBundle("test", null, "hotp", 12345), accountBundle(account2, "ABCDEF", "totp", null)), null); mImporter.importFromBundle(bundle, mAccountDb, null); assertAccountsInDbInOrder(account2); assertAccountInDb(account2, "ABCDEF", OtpType.TOTP, 0); } public void testImportAccountDb_withAccountsWithMissingType() { // First account's type is missing String account2 = "a@gmail.com"; Bundle bundle = bundle( accountsBundle( accountBundle("test", "ABCDEFGHI", null, 12345), accountBundle(account2, "ABCDEF", "totp", null)), null); mImporter.importFromBundle(bundle, mAccountDb, null); assertAccountsInDbInOrder(account2); assertAccountInDb(account2, "ABCDEF", OtpType.TOTP, 0); } public void testImportAccountDb_withAccountsWithMissingHotpCounter() { // First account's HOTP counter is missing String account2 = "a@gmail.com"; Bundle bundle = bundle( accountsBundle( accountBundle("test", "ABCDEFGHI", "hotp", null), accountBundle(account2, "ABCDEF", "totp", null)), null); mImporter.importFromBundle(bundle, mAccountDb, null); assertAccountsInDbInOrder(account2); assertAccountInDb(account2, "ABCDEF", OtpType.TOTP, 0); } public void testImportAccountDb_withAccountsWithMissingTotpCounter() { // Second account's TOTP counter is missing, but it doesn't matter as it's not needed String account1 = "b@gmail.com"; String account2 = "a@gmail.com"; Bundle bundle = bundle( accountsBundle( accountBundle(account1, "ABCDEFGHI", "hotp", 12345), accountBundle(account2, "ABCDEF", "totp", null)), null); mImporter.importFromBundle(bundle, mAccountDb, null); assertAccountsInDbInOrder(account1, account2); assertAccountInDb(account1, "ABCDEFGHI", OtpType.HOTP, 12345); assertAccountInDb(account2, "ABCDEF", OtpType.TOTP, 0); } public void testImportAccountDb_withNoAccounts() { Bundle bundle = bundle(accountsBundle(), null); mImporter.importFromBundle(bundle, mAccountDb, null); assertAccountsInDbInOrder(); } public void testGetDataExportPreferences_withPreferences() { Bundle prefBundle = new Bundle(); prefBundle.putBoolean("bool", true); prefBundle.putInt("int", 9); prefBundle.putFloat("float", 3.14f); prefBundle.putString("string", "testing"); prefBundle.putLong("long", 0x123456DEADBEEFL); prefBundle.putStringArray("stringarray", new String[] {"1", "2", "3"}); Bundle bundle = new Bundle(); bundle.putBundle("preferences", prefBundle); mImporter.importFromBundle(bundle, null, mMockPreferences); verify(mMockPreferencesEditor).putBoolean("bool", true); verify(mMockPreferencesEditor).putInt("int", 9); verify(mMockPreferencesEditor).putFloat("float", 3.14f); verify(mMockPreferencesEditor).putString("string", "testing"); verify(mMockPreferencesEditor).putLong("long", 0x123456DEADBEEFL); verify(mMockPreferencesEditor).commit(); verifyNoMoreInteractions(mMockPreferencesEditor); } public void testGetDataExportPreferences_withEmptyPreferences() { Bundle prefBundle = new Bundle(); Bundle bundle = new Bundle(); bundle.putBundle("preferences", prefBundle); mImporter.importFromBundle(bundle, null, mMockPreferences); verify(mMockPreferencesEditor).commit(); verifyNoMoreInteractions(mMockPreferencesEditor); } public void testImportPreferences_withNullPreferences() { mImporter.importFromBundle(new Bundle(), null, mMockPreferences); verifyZeroInteractions(mMockPreferences); } private static Bundle accountBundle( String name, String encodedSecret, String type, Integer counter) { Bundle result = new Bundle(); if (name != null) { result.putString(Importer.KEY_NAME, name); } if (encodedSecret != null) { result.putString(Importer.KEY_ENCODED_SECRET, encodedSecret); } if (type != null) { result.putString(Importer.KEY_TYPE, type); } if (counter != null) { result.putInt(Importer.KEY_COUNTER, counter); } return result; } private static Bundle accountsBundle(Bundle... accountBundles) { Bundle result = new Bundle(); if (accountBundles != null) { for (int i = 0, len = accountBundles.length; i < len; i++) { result.putBundle(String.valueOf(i), accountBundles[i]); } } return result; } private static Bundle bundle(Bundle accountsBundle, Bundle preferencesBundle) { Bundle result = new Bundle(); if (accountsBundle != null) { result.putBundle(Importer.KEY_ACCOUNTS, accountsBundle); } if (preferencesBundle != null) { result.putBundle(Importer.KEY_PREFERENCES, preferencesBundle); } return result; } private void assertAccountInDb(String name, String encodedSecret, OtpType type, int counter) { assertEquals(encodedSecret, mAccountDb.getSecret(name)); assertEquals(type, mAccountDb.getType(name)); assertEquals(new Integer(counter), mAccountDb.getCounter(name)); } private void assertAccountsInDbInOrder(String... expectedNames) { List<String> actualNames = new ArrayList<String>(); mAccountDb.getNames(actualNames); MoreAsserts.assertContentsInOrder(actualNames, (Object[]) expectedNames); } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/dataimport/ImporterTest.java
Java
asf20
9,964
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import junit.framework.TestCase; /** * Unit tests for {@link Utilities}. * * @author klyubin@google.com (Alex Klyubin) */ public class UtilitiesTest extends TestCase { public void testMillisToSeconds() { // Test rounding assertEquals(1234, Utilities.millisToSeconds(1234567)); assertEquals(1234, Utilities.millisToSeconds(1234000)); assertEquals(1234, Utilities.millisToSeconds(1234999)); // Test that it works fine for longs assertEquals(12345678901L, Utilities.millisToSeconds(12345678901234L)); } public void testSecondsToMillis() { assertEquals(1234000, Utilities.secondsToMillis(1234)); // Test that it works fine for longs assertEquals(12345678901000L, Utilities.secondsToMillis(12345678901L)); } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/UtilitiesTest.java
Java
asf20
1,423
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.howitworks; import com.google.android.apps.authenticator.wizard.WizardPageActivityTestBase; import android.content.Intent; import java.io.Serializable; /** * Unit tests for {@link IntroEnterCodeActivity}. * * @author klyubin@google.com (Alex Klyubin) */ public class IntroEnterCodeActivityTest extends WizardPageActivityTestBase<IntroEnterCodeActivity, Serializable> { public IntroEnterCodeActivityTest() { super(IntroEnterCodeActivity.class); } public void testBackKeyFinishesActivity() throws Exception { assertBackKeyFinishesActivity(); } public void testLeftButtonFinishesActivity() throws Exception { assertLeftButtonPressFinishesActivity(); } public void testRightButtonStartsNextPage() throws Exception { Intent intent = pressRightButtonAndCaptureActivityStartIntent(); assertIntentForClassInTargetPackage(IntroVerifyDeviceActivity.class, intent); assertFalse(getActivity().isFinishing()); } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/howitworks/IntroEnterCodeActivityTest.java
Java
asf20
1,620
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.howitworks; import com.google.android.apps.authenticator.wizard.WizardPageActivityTestBase; import android.content.Intent; import java.io.Serializable; /** * Unit tests for {@link IntroEnterPasswordActivity}. * * @author klyubin@google.com (Alex Klyubin) */ public class IntroEnterPasswordActivityTest extends WizardPageActivityTestBase<IntroEnterPasswordActivity, Serializable> { public IntroEnterPasswordActivityTest() { super(IntroEnterPasswordActivity.class); } public void testBackKeyFinishesActivity() throws Exception { assertBackKeyFinishesActivity(); } public void testLeftButtonFinishesActivity() throws Exception { assertLeftButtonPressFinishesActivity(); } public void testRightButtonStartsNextPage() throws Exception { Intent intent = pressRightButtonAndCaptureActivityStartIntent(); assertIntentForClassInTargetPackage(IntroEnterCodeActivity.class, intent); assertFalse(getActivity().isFinishing()); } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/howitworks/IntroEnterPasswordActivityTest.java
Java
asf20
1,637
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator.howitworks; import com.google.android.apps.authenticator.AuthenticatorActivity; import com.google.android.apps.authenticator.wizard.WizardPageActivityTestBase; import android.content.Intent; import java.io.Serializable; /** * Unit tests for {@link IntroVerifyDeviceActivity}. * * @author klyubin@google.com (Alex Klyubin) */ public class IntroVerifyDeviceActivityTest extends WizardPageActivityTestBase<IntroVerifyDeviceActivity, Serializable> { public IntroVerifyDeviceActivityTest() { super(IntroVerifyDeviceActivity.class); } public void testBackKeyFinishesActivity() throws Exception { assertBackKeyFinishesActivity(); } public void testLeftButtonFinishesActivity() throws Exception { assertLeftButtonPressFinishesActivity(); } public void testRightButtonExitsWizard() throws Exception { Intent intent = pressRightButtonAndCaptureActivityStartIntent(); assertIntentForClassInTargetPackage(AuthenticatorActivity.class, intent); assertTrue(getActivity().isFinishing()); } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/howitworks/IntroVerifyDeviceActivityTest.java
Java
asf20
1,695
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import com.google.android.apps.authenticator.testability.DependencyInjector; import com.google.android.apps.authenticator2.R; import android.app.Instrumentation; import android.test.ActivityInstrumentationTestCase2; import android.test.MoreAsserts; import android.test.ViewAsserts; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import java.util.ArrayList; import java.util.Collection; /** * Unit tests for {@link EnterKeyActivity}. * * @author sarvar@google.com (Sarvar Patel) */ public class EnterKeyActivityTest extends ActivityInstrumentationTestCase2<EnterKeyActivity> { private EnterKeyActivity mActivity; private Instrumentation mInstr; private EditText mKeyEntryField; private EditText mAccountName; private Spinner mType; private Button mSubmitButton; private Collection<String> result = new ArrayList<String>(); private AccountDb mAccountDb; public EnterKeyActivityTest() { super(TestUtilities.APP_PACKAGE_NAME, EnterKeyActivity.class); } @Override public void setUp() throws Exception { // TODO(sarvar): sending keys require that emulators have their keyguards // unlocked. We could do this with code here, this would require giving // permission in the apps AndroidManifest.xml. Consider if this is needed. super.setUp(); DependencyInjector.resetForIntegrationTesting(getInstrumentation().getTargetContext()); TestUtilities.withLaunchPreventingStartActivityListenerInDependencyResolver(); mAccountDb = DependencyInjector.getAccountDb(); setActivityInitialTouchMode(false); mInstr = getInstrumentation(); mActivity = getActivity(); mAccountName = (EditText) mActivity.findViewById(R.id.account_name); mKeyEntryField = (EditText) mActivity.findViewById(R.id.key_value); mType = (Spinner) mActivity.findViewById(R.id.type_choice); mSubmitButton = (Button) mActivity.findViewById(R.id.button_right); } @Override protected void tearDown() throws Exception { DependencyInjector.close(); super.tearDown(); } public void testPreconditions() { // check that the test has input fields assertNotNull(mAccountName); assertNotNull(mKeyEntryField); assertNotNull(mType); assertNotNull(mType.getAdapter()); assertEquals(2, mType.getAdapter().getCount()); } public void testStartingFieldValues() { assertEquals("", mAccountName.getText().toString()); assertEquals("", mKeyEntryField.getText().toString()); } public void testFieldsAreOnScreen() { Window window = mActivity.getWindow(); View origin = window.getDecorView(); ViewAsserts.assertOnScreen(origin, mAccountName); ViewAsserts.assertOnScreen(origin, mKeyEntryField); ViewAsserts.assertOnScreen(origin, mType); ViewAsserts.assertOnScreen(origin, mSubmitButton); } private void checkCorrectEntry(AccountDb.OtpType type) { // enter account name assertEquals("johndoe@gmail.com", TestUtilities.setText(mInstr, mAccountName, "johndoe@gmail.com")); // enter key assertEquals("7777777777777777", TestUtilities.setText(mInstr, mKeyEntryField, "7777777777777777")); // select TOTP/HOTP type assertEquals(mActivity.getResources().getStringArray(R.array.type)[type.value], TestUtilities.selectSpinnerItem(mInstr, mType, type.value)); assertFalse(mActivity.isFinishing()); // save TestUtilities.clickView(mInstr, mSubmitButton); // check activity's resulting update of database. assertEquals(1, mAccountDb.getNames(result)); MoreAsserts.assertContentsInOrder(result, "johndoe@gmail.com"); assertEquals(type, mAccountDb.getType("johndoe@gmail.com")); assertEquals(0, mAccountDb.getCounter("johndoe@gmail.com").intValue()); assertTrue(mActivity.isFinishing()); } public void testCorrectEntryTOTP() { checkCorrectEntry(AccountDb.OtpType.TOTP); } public void testCorrectEntryHOTP() { checkCorrectEntry(AccountDb.OtpType.HOTP); } public void testSubmitFailsWithShortKey() { assertEquals("johndoe@gmail.com", TestUtilities.setText(mInstr, mAccountName, "johndoe@gmail.com")); TestUtilities.selectSpinnerItem(mInstr, mType, AccountDb.OtpType.TOTP.value); assertEquals( mActivity.getResources().getStringArray(R.array.type)[AccountDb.OtpType.TOTP.value], TestUtilities.selectSpinnerItem(mInstr, mType, AccountDb.OtpType.TOTP.value)); // enter bad key without submitting, check status message assertEquals("@@", TestUtilities.setText(mInstr, mKeyEntryField, "@@")); assertEquals(mActivity.getString(R.string.enter_key_illegal_char), mKeyEntryField.getError()); // clear bad keys, see status message is cleared. assertEquals("", TestUtilities.setText(mInstr, mKeyEntryField, "")); assertEquals(null, mKeyEntryField.getError()); // enter short key, check status message is empty assertEquals("77777", TestUtilities.setText(mInstr, mKeyEntryField, "77777")); assertEquals(null, mKeyEntryField.getError()); // submit short key, and verify no updates to database and check status msg. TestUtilities.clickView(getInstrumentation(), mSubmitButton); assertFalse(mActivity.isFinishing()); assertEquals(0, mAccountDb.getNames(result)); assertEquals(mActivity.getString(R.string.enter_key_too_short), mKeyEntryField.getError()); // check key field is unchanged. assertEquals("77777", mKeyEntryField.getText().toString()); // submit empty key. assertEquals("", TestUtilities.setText(mInstr, mKeyEntryField, "")); TestUtilities.clickView(getInstrumentation(), mSubmitButton); assertFalse(mActivity.isFinishing()); assertEquals(0, mAccountDb.getNames(result)); assertEquals(mActivity.getString(R.string.enter_key_too_short), mKeyEntryField.getError()); } // TODO(sarvar): Consider not allowing acceptance of such bad account names. public void testSubmitWithEmptyAccountName() { assertEquals("7777777777777777", TestUtilities.setText(mInstr, mKeyEntryField, "7777777777777777")); assertEquals( mActivity.getResources().getStringArray(R.array.type)[AccountDb.OtpType.TOTP.value], TestUtilities.selectSpinnerItem(mInstr, mType, AccountDb.OtpType.TOTP.value)); // enter empty name assertEquals("", TestUtilities.setText(mInstr, mAccountName, "")); TestUtilities.clickView(mInstr, mSubmitButton); assertEquals(1, mAccountDb.getNames(result)); assertEquals("7777777777777777", mAccountDb.getSecret("")); } // TODO(sarvar): Consider not allowing acceptance of such bad account names. public void testSubmitWithWierdAccountName() { assertEquals("7777777777777777", TestUtilities.setText(mInstr, mKeyEntryField, "7777777777777777")); assertEquals( mActivity.getResources().getStringArray(R.array.type)[AccountDb.OtpType.TOTP.value], TestUtilities.selectSpinnerItem(mInstr, mType, AccountDb.OtpType.TOTP.value)); // enter empty name assertEquals(",,", TestUtilities.setText(mInstr, mAccountName, ",,")); TestUtilities.clickView(getInstrumentation(), mSubmitButton); assertEquals(1, mAccountDb.getNames(result)); assertEquals("7777777777777777", mAccountDb.getSecret(",,")); } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/EnterKeyActivityTest.java
Java
asf20
8,044
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import com.google.android.apps.authenticator.AccountDb.OtpType; import com.google.android.apps.authenticator.PasscodeGenerator.Signer; import com.google.android.apps.authenticator.testability.DependencyInjector; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.test.AndroidTestCase; import android.test.MoreAsserts; import java.util.ArrayList; import java.util.Collection; /** * Unit tests for {@link AccountDb}. * @author sarvar@google.com (Sarvar Patel) * * TestCases belonging to the same test suite that are run simultaneously may interfere * with each other because AccountDb instances in this class point to the same underlying database. * For the time being this is not an issue since tests for android are run sequentially. */ public class AccountDbTest extends AndroidTestCase { private static final String MESSAGE = "hello"; private static final String SIGNATURE = "2GOH22N7HTHRAC3C4IY24TWH6FEFEOZ7"; private static final String SECRET = "7777777777777777"; // 16 sevens private static final String SECRET2 = "2222222222222222"; // 16 twos private Collection<String> result = new ArrayList<String>(); private AccountDb accountDb; @Override public void setUp() throws Exception { super.setUp(); DependencyInjector.resetForIntegrationTesting(getContext()); accountDb = DependencyInjector.getAccountDb(); } @Override protected void tearDown() throws Exception { DependencyInjector.close(); super.tearDown(); } private void addSomeRecords() { accountDb.update("johndoe@gmail.com", SECRET, "johndoe@gmail.com", OtpType.TOTP, null); accountDb.update("amywinehouse@aol.com", SECRET2, "amywinehouse@aol.com", OtpType.TOTP, null); accountDb.update("maryweiss@yahoo.com", SECRET, "maryweiss@yahoo.com", OtpType.HOTP, 0); } public void testNoRecords() throws Exception { assertEquals(0, accountDb.getNames(result)); assertEquals(0, result.size()); assertEquals(false, accountDb.nameExists("johndoe@gmail.com")); assertEquals(null, accountDb.getSecret("johndoe@gmail.com")); } public void testGetNames() throws Exception { addSomeRecords(); accountDb.getNames(result); MoreAsserts.assertContentsInAnyOrder(result, "johndoe@gmail.com", "amywinehouse@aol.com", "maryweiss@yahoo.com"); // check nameExists() assertTrue(accountDb.nameExists("johndoe@gmail.com")); assertTrue(accountDb.nameExists("amywinehouse@aol.com")); assertTrue(accountDb.nameExists("maryweiss@yahoo.com")); assertFalse(accountDb.nameExists("marywinehouse@aol.com")); // non-existent email. } public void testGetSecret() throws Exception { addSomeRecords(); assertEquals(SECRET, accountDb.getSecret("johndoe@gmail.com")); assertEquals(SECRET2, accountDb.getSecret("amywinehouse@aol.com")); assertEquals(null, accountDb.getSecret("marywinehouse@aol.com")); // non-existent email. } public void testGetAndIncrementCounter() throws Exception { addSomeRecords(); assertEquals(0, (int) accountDb.getCounter("maryweiss@yahoo.com")); accountDb.incrementCounter("maryweiss@yahoo.com"); assertEquals(1, (int) accountDb.getCounter("maryweiss@yahoo.com")); assertEquals(null, accountDb.getCounter("marywinehouse@yahoo.com")); // non-existent record. assertEquals(0, (int) accountDb.getCounter("amywinehouse@aol.com")); // TOTP record } public void testGetAndSetType() throws Exception { addSomeRecords(); assertTrue(accountDb.getType("johndoe@gmail.com").equals(OtpType.TOTP)); assertTrue(accountDb.getType("maryweiss@yahoo.com").equals(OtpType.HOTP)); assertFalse(accountDb.getType("amywinehouse@aol.com").equals(OtpType.HOTP)); accountDb.setType("johndoe@gmail.com", OtpType.HOTP); assertTrue(accountDb.getType("johndoe@gmail.com").equals(OtpType.HOTP)); // check that the counter retains its values. assertEquals(0, (int) accountDb.getCounter("johndoe@gmail.com")); // check that it can be reset to original value accountDb.setType("johndoe@gmail.com", OtpType.TOTP); assertTrue(accountDb.getType("johndoe@gmail.com").equals(OtpType.TOTP)); } public void testGetAndSetAccountType() throws Exception { addSomeRecords(); assertTrue(accountDb.getType("johndoe@gmail.com").equals(OtpType.TOTP)); assertTrue(accountDb.getType("maryweiss@yahoo.com").equals(OtpType.HOTP)); assertFalse(accountDb.getType("amywinehouse@aol.com").equals(OtpType.HOTP)); accountDb.setType("johndoe@gmail.com", OtpType.HOTP); assertTrue(accountDb.getType("johndoe@gmail.com").equals(OtpType.HOTP)); // check that the counter retains its values. assertEquals(0, (int) accountDb.getCounter("johndoe@gmail.com")); // check that it can be reset to original value accountDb.setType("johndoe@gmail.com", OtpType.TOTP); assertTrue(accountDb.getType("johndoe@gmail.com").equals(OtpType.TOTP)); } public void testDelete() throws Exception { addSomeRecords(); accountDb.delete("johndoe@gmail.com"); assertEquals(2, accountDb.getNames(result)); assertFalse(accountDb.nameExists("johndoe@gmail.com")); // re-add johndoe. accountDb.update("johndoe@gmail.com", SECRET, "johndoe@gmail.com", OtpType.TOTP, null); assertTrue(accountDb.nameExists("johndoe@gmail.com")); } public void testUpdate() throws Exception { addSomeRecords(); // check updates with existing records - that it doesn't increase the records. accountDb.update("johndoe@gmail.com", SECRET, "johndoe@gmail.com", OtpType.TOTP, null); accountDb.getNames(result); MoreAsserts.assertContentsInAnyOrder(result, "johndoe@gmail.com", "amywinehouse@aol.com", "maryweiss@yahoo.com"); // add new record. accountDb.update("johndoenew@gmail.com", SECRET, "johndoe@gmail.com", OtpType.TOTP, null); result.clear(); accountDb.getNames(result); MoreAsserts.assertContentsInAnyOrder(result, "johndoenew@gmail.com", "amywinehouse@aol.com", "maryweiss@yahoo.com"); // re-update with the original name accountDb.update("johndoe@gmail.com", SECRET, "johndoenew@gmail.com", OtpType.TOTP, null); result.clear(); accountDb.getNames(result); MoreAsserts.assertContentsInAnyOrder(result, "johndoe@gmail.com", "amywinehouse@aol.com", "maryweiss@yahoo.com"); } public void testIsGoogleAccount() { accountDb.update("1@b.c", SECRET, "1@b.c", OtpType.TOTP, null, true); accountDb.update("2@gmail.com", SECRET, "2@gmail.com", OtpType.TOTP, null); accountDb.update("3@google.com", SECRET, "3@google.com", OtpType.TOTP, null); accountDb.update("4", SECRET, "4", OtpType.HOTP, 3, true); accountDb.update("5@yahoo.co.uk", SECRET, "5@yahoo.co.uk", OtpType.TOTP, null); accountDb.update("gmail.com", SECRET, "gmail.com", OtpType.TOTP, null); accountDb.update( "Google Internal 2Factor", SECRET, "Google Internal 2Factor", OtpType.HOTP, null); assertTrue(accountDb.isGoogleAccount("1@b.c")); assertTrue(accountDb.isGoogleAccount("2@gmail.com")); assertTrue(accountDb.isGoogleAccount("3@google.com")); assertTrue(accountDb.isGoogleAccount("4")); assertFalse(accountDb.isGoogleAccount("5@yahoo.co.uk")); assertFalse(accountDb.isGoogleAccount("gmail.com")); assertTrue(accountDb.isGoogleAccount("Google Internal 2Factor")); assertFalse(accountDb.isGoogleAccount("non-existent account")); } public void testUpdateWithoutSourceValuePreservesSourceValue() { accountDb.update("a@b.c", SECRET, "a@b.c", OtpType.TOTP, null, true); accountDb.update("test@gmail.com", SECRET, "test@gmail.com", OtpType.TOTP, null); assertTrue(accountDb.isGoogleAccount("a@b.c")); assertTrue(accountDb.isGoogleAccount("test@gmail.com")); accountDb.update("b@a.c", SECRET, "a@b.c", OtpType.TOTP, null); accountDb.update("test@yahoo.com", SECRET, "test@gmail.com", OtpType.TOTP, null); assertTrue(accountDb.isGoogleAccount("b@a.c")); assertFalse(accountDb.isGoogleAccount("test@yahoo.com")); } public void testConstruct_whenNoDatabase() { deleteAccountDb(); accountDb = DependencyInjector.getAccountDb(); } public void testConstruct_whenDatabaseWithoutProviderColumn() { deleteAccountDb(); SQLiteDatabase database = DependencyInjector.getContext().openOrCreateDatabase( AccountDb.PATH, Context.MODE_PRIVATE, null); database.execSQL("CREATE TABLE " + AccountDb.TABLE_NAME + " (first INTEGER)"); MoreAsserts.assertContentsInAnyOrder( AccountDb.listTableColumnNamesLowerCase(database, AccountDb.TABLE_NAME), "first"); database.close(); database = null; accountDb = DependencyInjector.getAccountDb(); MoreAsserts.assertContentsInAnyOrder( AccountDb.listTableColumnNamesLowerCase(accountDb.mDatabase, AccountDb.TABLE_NAME), "first", AccountDb.PROVIDER_COLUMN); } private void deleteAccountDb() { if (accountDb != null) { accountDb.close(); accountDb = null; } DependencyInjector.setAccountDb(null); assertTrue(DependencyInjector.getContext().deleteDatabase(AccountDb.PATH)); } public void testSigningOracle() throws Exception { Signer signer = AccountDb.getSigningOracle(SECRET); assertEquals(SIGNATURE, Base32String.encode(signer.sign(MESSAGE.getBytes()))); } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/AccountDbTest.java
Java
asf20
10,052
/* * Copyright 2012 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import com.google.android.apps.authenticator.testability.DependencyInjector; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.test.AndroidTestCase; /** * Unit tests for {@link TotpClock}. * * @author klyubin@google.com (Alex Klyubin) */ public class TotpClockTest extends AndroidTestCase { private TotpClock mClock; @Override protected void setUp() throws Exception { super.setUp(); DependencyInjector.resetForIntegrationTesting(getContext()); mClock = new TotpClock(DependencyInjector.getContext()); } @Override protected void tearDown() throws Exception { DependencyInjector.close(); super.tearDown(); } public void testCurrentTimeMillisUsesCurrentTimeAndTimeCorrection() { assertEquals(0, mClock.getTimeCorrectionMinutes()); long millisBefore = System.currentTimeMillis(); long actualMillis = mClock.currentTimeMillis(); long millisAfter = System.currentTimeMillis(); assertInRangeInclusive(actualMillis, millisBefore, millisAfter); mClock.setTimeCorrectionMinutes(137); millisBefore = System.currentTimeMillis(); actualMillis = mClock.currentTimeMillis(); millisAfter = System.currentTimeMillis(); assertInRangeInclusive( actualMillis, millisBefore + 137 * Utilities.MINUTE_IN_MILLIS, millisAfter + 137 * Utilities.MINUTE_IN_MILLIS); } public void testTimeCorrectionBackedByPreferences() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(DependencyInjector.getContext()); assertTrue(preferences.edit().putInt(TotpClock.PREFERENCE_KEY_OFFSET_MINUTES, 7).commit()); assertEquals(7, mClock.getTimeCorrectionMinutes()); mClock.setTimeCorrectionMinutes(42); assertEquals(42, preferences.getInt(TotpClock.PREFERENCE_KEY_OFFSET_MINUTES, 0)); assertEquals(42, mClock.getTimeCorrectionMinutes()); } public void testTimeCorrectionCaching() { // Check that the preference is only read first time the the time correction value is requested SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(DependencyInjector.getContext()); assertTrue(preferences.edit().putInt(TotpClock.PREFERENCE_KEY_OFFSET_MINUTES, 7).commit()); assertEquals(7, mClock.getTimeCorrectionMinutes()); assertTrue(preferences.edit().putInt(TotpClock.PREFERENCE_KEY_OFFSET_MINUTES, 42).commit()); assertEquals(7, mClock.getTimeCorrectionMinutes()); } private static void assertInRangeInclusive( long actual, long expectedMinValue, long expectedMaxValue) { if ((actual < expectedMinValue) || (actual > expectedMaxValue)) { fail(actual + " not in [" + expectedMinValue + ", " + expectedMaxValue + "]"); } } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/TotpClockTest.java
Java
asf20
3,452
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import com.google.android.apps.authenticator.testability.DependencyInjector; import com.google.android.apps.authenticator2.R; import android.content.ComponentName; import android.content.Intent; import android.test.ActivityInstrumentationTestCase2; /** * Unit tests for {@link AddOtherAccountActivity}. * * @author klyubin@google.com (Alex Klyubin) */ public class AddOtherAccountActivityTest extends ActivityInstrumentationTestCase2<AddOtherAccountActivity> { public AddOtherAccountActivityTest() { super(TestUtilities.APP_PACKAGE_NAME, AddOtherAccountActivity.class); } @Override protected void setUp() throws Exception { super.setUp(); DependencyInjector.resetForIntegrationTesting(getInstrumentation().getTargetContext()); TestUtilities.withLaunchPreventingStartActivityListenerInDependencyResolver(); } @Override protected void tearDown() throws Exception { DependencyInjector.close(); super.tearDown(); } public void testScanBarcode() throws Exception { TestUtilities.clickView(getInstrumentation(), getActivity().findViewById(R.id.scan_barcode)); Intent actualIntent = TestUtilities.verifyWithTimeoutThatStartActivityAttemptedExactlyOnce(); Intent expectedIntent = AuthenticatorActivity.getLaunchIntentActionScanBarcode(getActivity()); assertEquals(expectedIntent.getAction(), actualIntent.getAction()); assertEquals(expectedIntent.getComponent(), actualIntent.getComponent()); } public void testManuallyAddAccount() throws Exception { TestUtilities.clickView( getInstrumentation(), getActivity().findViewById(R.id.manually_add_account)); Intent actualIntent = TestUtilities.verifyWithTimeoutThatStartActivityAttemptedExactlyOnce(); assertEquals( new ComponentName(getActivity(), EnterKeyActivity.class), actualIntent.getComponent()); } }
zzhyjun-zzhyjun
tests/src/com/google/android/apps/authenticator/AddOtherAccountActivityTest.java
Java
asf20
2,534
package columbia.edu; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; //import java.sql.DriverManager; //import java.sql.PreparedStatement; import java.sql.SQLException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class Logout */ public class Logout extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Logout() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { HttpSession session = req.getSession(true); session.invalidate(); System.out.println("Session invalidated"); //String connectionURL = "jdbc:oracle:thin:@//w4111b.cs.columbia.edu:1521/ADB"; Connection connection=null; res.setContentType("text/html"); PrintWriter out = res.getWriter(); try { Class.forName("oracle.jdbc.pool.OracleDataSource"); /* connection = (Connection) req.getSession().getAttribute("Connection"); if (connection == null) { connection = DriverManager.getConnection(connectionURL, "ab3416", "kFxJssQk"); req.getSession().setAttribute("Connection", connection); }*/ //String sql = "delete from login"; //PreparedStatement pst = connection.prepareStatement(sql); //int del=pst.executeUpdate(); //System.out.println("Number of deleted records: " + del); //pst.close(); } catch(ClassNotFoundException e){ out.println("Couldn't load database driver: " + e.getMessage()); } /*catch(SQLException e){ out.println("SQLException caught: " + e.getMessage()); }*/ catch (Exception e){ out.println(e); } finally { //req.setAttribute("name", fname.toUpperCase() ); String nextJSP = "/AuthenticLogin.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP); dispatcher.forward(req,res); try { if (connection != null) connection.close(); } catch (SQLException ignored){ out.println(ignored); } } } }
zznshop
trunk/src/columbia/edu/Logout.java
Java
epl
2,763
package columbia.edu; import java.io.IOException; import java.io.PrintWriter; import java.sql.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import oracle.jdbc.pool.OracleDataSource; /** * Servlet implementation class OracleServlet */ public class DisplayDetailsServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String connect_string = //"jdbc:oracle:thin:scott/tiger@//w4111b.cs.columbia.edu:1521/ADB"; "jdbc:oracle:thin:ab3416/kFxJssQk@//w4111b.cs.columbia.edu:1521/ADB"; //"jdbc:oracle:thin:zzn2101/ycmrmMbM@//w4111b.cs.columbia.edu:1521/ADB"; private Connection conn; /** * @see HttpServlet#HttpServlet() */ public DisplayDetailsServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = new PrintWriter(response.getOutputStream()); try { if (conn == null) { // Create a OracleDataSource instance and set URL OracleDataSource ods = new OracleDataSource(); ods.setURL(connect_string); //conn = ods.getConnection(); conn = (Connection) request.getSession().getAttribute("Connection"); if (conn == null) { conn = ods.getConnection(); request.getSession().setAttribute("Connection",conn); } } Statement stmt = conn.createStatement(); //ResultSet rset = stmt.executeQuery("select ENAME from EMP"); String custID = (String)(request.getSession().getAttribute("theName")); custID=custID.trim(); int qty; try { qty = Integer.parseInt(request.getParameter("qty")); } catch( Exception e) { qty=0; } request.getSession().setAttribute("qty", qty); pw.println("<html>"); pw.println("<head><title>Please confirm your Details</title></head>"); pw.println("<link rel='stylesheet' href='style.css' type='text/css' charset='utf-8' />"); pw.println("<BR><BR>"); pw.println("<H1>Please confirm your Details </H1><BR>"); pw.println("<BR><BR>"); pw.println("<H2>Payment Info </H2><BR>"); pw.println("<BR>"); pw.println("<body>"); String pid = request.getSession().getAttribute("ID").toString(); ResultSet rset = stmt.executeQuery("select price from products where pid = '" + pid + "'"); Double price = 0.0; if (rset.next()) { price = rset.getDouble("price"); } price = price * qty; pw.println("<H3>"); pw.println("Payment Amount $" + price + "<BR>"); rset = stmt.executeQuery("select cardtype, cardno, expdate from payment_info p, customers c where c.cust_id = p.cust_id and c.cust_id = '" + custID + "'"); response.setContentType("text/html"); //pw.println("ID " + ID); //pw.println("<body><BR>"); while (rset.next()) { //pw.println (rset.getString("ename") + "<BR>"); pw.print("Card Type : "); pw.println (rset.getString("cardtype") + "<BR>"); //pw.print(" "); pw.print("Card No : "); pw.println (rset.getString("cardno") + "<BR>"); //pw.print(" "); pw.print("Exp Date : "); pw.println (rset.getString("expdate") + "<BR>"); //pw.print(" "); } pw.println("</H3>"); pw.println("<BR><BR>"); pw.println("<H2>Shipping Address <BR></H2>"); pw.println("<BR>"); rset = stmt.executeQuery("select street, city, state, country, zip from address a, customers c where c.cust_id = a.cust_id and a.type_of_addr = 'S' and c.cust_id = '" + custID + "'"); response.setContentType("text/html"); pw.println("<H3>"); while (rset.next()) { //pw.println (rset.getString("ename") + "<BR>"); // pw.print("Card Type : "); pw.println (rset.getString("street")); //pw.print(" "); //pw.print("Card No : "); pw.println (" " + rset.getString("city")); //pw.print(" "); //pw.print("Exp Date : "); pw.println (" " + rset.getString("state")); pw.println (" " + rset.getString("country")); //pw.print(" "); pw.println (" " + rset.getString("zip")); } pw.println("</H3>"); pw.println("<form action='RecordOrderDetails'>"); pw.println("<br><input type='submit' value='Place Your Order'</br>"); pw.println("</form>"); pw.println("<div id='nav-top'>"); pw.println("<ul>"); pw.println("<li><a href='Logout.jsp'>Logout</a> |</li>"); //pw.println("<li><a href='Account.jsp'>My Account</a> |</li>"); pw.println("<li><a href='Contact.jsp'>Contact us</a></li>"); pw.println("</ul>"); pw.println("</div>"); pw.println("</body></html>"); } catch (SQLException e) { pw.println(e.getMessage()); } pw.close(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
zznshop
trunk/src/columbia/edu/DisplayDetailsServlet.java
Java
epl
4,914
package columbia.edu; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Details */ public class Details extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Details() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String str = request.getParameter("prodID"); System.out.println("PID="+str); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
zznshop
trunk/src/columbia/edu/Details.java
Java
epl
1,117
package columbia.edu; import java.io.IOException; import java.io.PrintWriter; import java.sql.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import oracle.jdbc.pool.OracleDataSource; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * Servlet implementation class OracleServlet */ public class RecordOrderDetails extends HttpServlet { private static final long serialVersionUID = 1L; private static final String connect_string = //"jdbc:oracle:thin:scott/tiger@//w4111b.cs.columbia.edu:1521/ADB"; "jdbc:oracle:thin:ab3416/kFxJssQk@//w4111b.cs.columbia.edu:1521/ADB"; private Connection conn; /** * @see HttpServlet#HttpServlet() */ public RecordOrderDetails() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = new PrintWriter(response.getOutputStream()); try { if (conn == null) { // Create a OracleDataSource instance and set URL OracleDataSource ods = new OracleDataSource(); ods.setURL(connect_string); conn = (Connection) request.getSession().getAttribute("Connection"); if (conn == null) { conn = ods.getConnection(); request.getSession().setAttribute("Connection", conn); } } Statement stmt = conn.createStatement(); //ResultSet rset = stmt.executeQuery("select ENAME from EMP"); String custID = (String)(request.getSession().getAttribute("theName")); custID=custID.trim(); //TODO: Calculate Total Price from Quantity entered double total_price = 0; String pid = (request.getSession().getAttribute("ID")).toString(); ResultSet rset = stmt.executeQuery("select price from products where pid = '" + pid + "'"); rset.next(); double price = rset.getDouble("price"); int qty = (Integer) request.getSession().getAttribute("qty"); total_price = price * qty; Calendar calendar = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy"); String currentDate = ""; try { currentDate= dateFormat.format(calendar.getTime()); } catch (Exception e) { e.printStackTrace(); } //String insertStatement2 = "insert into orders(cust_id, orderdate, total_price) values('" + custID + "','" + currentDate + "'," + total_price + ")"; stmt.executeUpdate("insert into orders(cust_id, orderdate, total_price) values('" + custID.trim() + "','" + currentDate + "'," + total_price + ")"); //stmt.executeUpdate("insert into orders(cust_id, orderdate, total_price) values('39daisy','04-APR-2011',0)"); response.setContentType("text/html"); rset = stmt.executeQuery("select max(orderno) as orderid from orders where cust_id = '" + custID.trim() + "'"); response.setContentType("text/html"); rset.next(); int orderid = rset.getInt("orderid".trim()); //TODO: Set qty to quantity entered by user //int qty=1; String insertStatement = "insert into sales values(" + orderid + ",'" + pid + "'," + qty; //stmt.executeUpdate("insert into sales values(" + orderid + ",'" + pid + "'," + qty); stmt.executeUpdate("insert into sales values(" + orderid + ",'" + pid.trim() + "'," + qty + ")"); response.setContentType("text/html"); pw.println("<html>"); pw.println("<head><title>Confirmation of order</title></head>"); pw.println("<link rel='stylesheet' href='style.css' type='text/css' charset='utf-8' />"); pw.println("<BR><BR>"); pw.println("<H1>Your order has been placed! <BR></H1>"); pw.println("<BR><BR>"); pw.println("<H2>Your order no is " + orderid + "<BR></H2>"); //pw.println("<H1>" + insertStatement + "<BR></H1>"); //pw.println("<H1>" + insertStatement2 + "<BR></H1>"); //pw.println("ID " + ID); //pw.println("<body><BR>"); //rset = stmt.executeQuery("select ) pw.println("<div id='nav-top'>"); pw.println("<ul>"); pw.println("<li><a href='Logout.jsp'>Logout</a> |</li>"); //pw.println("<li><a href='Account.jsp'>My Account</a> |</li>"); pw.println("<li><a href='Contact.jsp'>Contact us</a></li>"); pw.println("</ul>"); pw.println("</div>"); pw.println("</html>"); } catch (SQLException e) { pw.println(e.getMessage()); } pw.close(); /* try { if (conn != null) { conn.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } */ } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
zznshop
trunk/src/columbia/edu/RecordOrderDetails.java
Java
epl
4,828
package columbia.edu; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.sql.*; import javax.servlet.*; public class Registration extends HttpServlet{ /** * */ private static final long serialVersionUID = 1L; public void init(ServletConfig config) throws ServletException{ super.init(config); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ String connectionURL = "jdbc:oracle:thin:@//w4111b.cs.columbia.edu:1521/ADB"; Connection connection=null; res.setContentType("text/html"); PrintWriter out = res.getWriter(); String uname = req.getParameter("username"); String pass = req.getParameter("password"); String fname = req.getParameter("firstname"); String lname = req.getParameter("lastname"); String street = req.getParameter("street"); String city = req.getParameter("city"); String state = req.getParameter("state"); String country = req.getParameter("country"); String zipcode = req.getParameter("zipcode"); String shipstreet = req.getParameter("shipstreet"); String shipcity = req.getParameter("shipcity"); String shipstate = req.getParameter("shipstate"); String shipcountry = req.getParameter("shipcountry"); String shipzipcode = req.getParameter("shipzipcode"); String cardname = req.getParameter("card"); String cardno = req.getParameter("cardno"); String expdate = req.getParameter("expdate"); System.out.println("ship street "+ shipstreet); String addid = "1"; String addidship = "10"; String payid = "1"; String typeaddr = "B"; String shiptypeaddr = "S"; String typemember= "R"; try { Class.forName("oracle.jdbc.pool.OracleDataSource"); connection = (Connection) req.getSession().getAttribute("Connection"); if (connection == null) { connection = DriverManager.getConnection(connectionURL, "ab3416", "kFxJssQk"); req.getSession().setAttribute("Connection", connection); } System.out.println("conn est"); String sqlcust = "insert into customers (cust_id,pwd,fname,lname,type_of_member) values(?,?,?,?,?)"; String sqladd = "insert into address values (?,?,?,?,?,?,?,?)"; String sqladdship = "insert into address values (?,?,?,?,?,?,?,?)"; String sqlpay = "insert into payment_info values (?,?,?,?,?)"; PreparedStatement pstcust = connection.prepareStatement(sqlcust); PreparedStatement pstadd = connection.prepareStatement(sqladd); PreparedStatement pstaddship = connection.prepareStatement(sqladdship); PreparedStatement pstpay = connection.prepareStatement(sqlpay); pstcust.setString(1,uname ); pstcust.setString(2,pass ); pstcust.setString(3,fname ); pstcust.setString(4,lname ); pstcust.setString(5,typemember ); pstcust.executeUpdate(); pstcust.close(); System.out.println("insert in cust complete"); pstadd.setString(1, addid); pstadd.setString(2, typeaddr); pstadd.setString(3, street); pstadd.setString(4, city); pstadd.setString(5, state); pstadd.setString(6, country); pstadd.setString(7, zipcode); pstadd.setString(8, uname); pstadd.executeUpdate(); pstadd.close(); System.out.println("insert in address bill complete"); pstaddship.setString(1, addidship); pstaddship.setString(2, shiptypeaddr); pstaddship.setString(3, shipstreet); pstaddship.setString(4, shipcity); pstaddship.setString(5, shipstate); pstaddship.setString(6, shipcountry); pstaddship.setString(7, shipzipcode); pstaddship.setString(8, uname); pstaddship.executeUpdate(); pstaddship.close(); System.out.println("insert in address ship complete"); pstpay.setString(1, payid); pstpay.setString(2, cardname); pstpay.setString(3, cardno); pstpay.setString(4, expdate); pstpay.setString(5, uname); pstpay.executeUpdate(); pstpay.close(); System.out.println("insert in pay complete"); System.out.println("insert complete"); } catch(ClassNotFoundException e){ out.println("Couldn't load database driver: " + e.getMessage()); } catch(SQLException e){ out.println("SQLException caught: " + e.getMessage()); } catch (Exception e){ out.println(e); } finally { req.setAttribute("fname", fname.toUpperCase() ); String nextJSP = "/index2.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP); dispatcher.forward(req,res); /* try { if (connection != null) connection.close(); } catch (SQLException ignored){ out.println(ignored); } */ } } }
zznshop
trunk/src/columbia/edu/Registration.java
Java
epl
4,910
package columbia.edu; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Display */ public class Display extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Display() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //int[] price; //int i=0; //price = new int[100]; ArrayList<String> prodArray = new ArrayList<String>(); String connectionURL = "jdbc:oracle:thin:@//w4111b.cs.columbia.edu:1521/ADB"; Connection connection=null; response.setContentType("text/html"); PrintWriter out = response.getWriter(); String str = request.getParameter("name"); System.out.println("Str="+str); System.out.println("Logged in="+request.getSession().getAttribute("theName")); String item=null; ResultSet rs; try { String sql=null; Class.forName("oracle.jdbc.pool.OracleDataSource"); //connection = DriverManager.getConnection(connectionURL, "ab3416", "kFxJssQk"); connection = (Connection) request.getSession().getAttribute("Connection"); if (connection == null) { connection = DriverManager.getConnection(connectionURL, "ab3416", "kFxJssQk"); request.getSession().setAttribute("Connection",connection); } if (str.equals("tops")){ sql = "select p.description,c.brand,p.price,p.pid from products p, clothes c where c.category='T' and p.pid=c.pid "; }else if (str.equals("pants")){ sql = "select p.description,c.brand,p.price,p.pid from products p, clothes c where c.category='P' and p.pid=c.pid "; }else if (str.equals("other")){ sql = "select p.description,c.brand,p.price,p.pid from products p, clothes c where c.category='O' and p.pid=c.pid "; }else if (str.equals("books")){ sql = "select p.description,b.author,p.price,p.pid from products p, books b where p.pid=b.pid "; } Statement s = connection.createStatement(); s.executeQuery (sql); rs = s.getResultSet(); if(str.equals("tops")||str.equals("pants")||str.equals("other")){ while(rs.next()){ String str1 = rs.getString("description"); prodArray.add(str1); String str2 = rs.getString("brand"); prodArray.add(str2); String str3 = rs.getString("price"); prodArray.add(str3); String str4 = rs.getString("pid"); prodArray.add(str4); item="clothes"; //price[i]=rs.getInt("price"); System.out.println(str1); System.out.println(str2); System.out.println(str3); System.out.println(str4); //i++; } }else if(str.equals("books")){ while(rs.next()){ String str1 = rs.getString("description"); prodArray.add(str1); String str2 = rs.getString("author"); prodArray.add(str2); String str3 = rs.getString("price"); prodArray.add(str3); String str4 = rs.getString("pid"); prodArray.add(str4); item="books"; } } } catch(ClassNotFoundException e){ out.println("Couldn't load database driver: " + e.getMessage()); } catch(SQLException e){ out.println("SQLException caught: " + e.getMessage()); } catch (Exception e){ out.println(e); } finally { //request.setAttribute("array",price ); //request.setAttribute("length",i ); request.setAttribute("pricearray",prodArray); request.setAttribute("item",item); String nextJSP = "/Display.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP); dispatcher.forward(request,response); /* try { if (connection != null) connection.close(); } catch (SQLException ignored){ out.println(ignored); } */ } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
zznshop
trunk/src/columbia/edu/Display.java
Java
epl
4,914
package columbia.edu; import java.io.IOException; import java.io.PrintWriter; import java.sql.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import oracle.jdbc.pool.OracleDataSource; /** * Servlet implementation class OracleServlet */ public class OracleServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String connect_string = "jdbc:oracle:thin:ab3416/kFxJssQk@//w4111b.cs.columbia.edu:1521/ADB"; private Connection conn; /** * @see HttpServlet#HttpServlet() */ public OracleServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = new PrintWriter(response.getOutputStream()); try { if (conn == null) { // Create a OracleDataSource instance and set URL OracleDataSource ods = new OracleDataSource(); ods.setURL(connect_string); conn = ods.getConnection(); } Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery("select FNAME from CUSTOMERS"); response.setContentType("text/html"); pw.println("<html>"); pw.println("<head><title>Customer Table Servlet Sample</title></head>"); pw.println("<H1>Show CUSTOMER Table Data <BR></H1>"); pw.println("<body><BR>"); while (rset.next()) { pw.println (rset.getString("fname") + "<BR>"); } pw.println("</body></html>"); } catch (SQLException e) { pw.println(e.getMessage()); } pw.close(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
zznshop
trunk/src/columbia/edu/OracleServlet.java
Java
epl
1,974
package columbia.edu; import java.io.IOException; import java.io.PrintWriter; import java.sql.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import oracle.jdbc.pool.OracleDataSource; /** * Servlet implementation class OracleServlet */ public class SearchResultServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String connect_string = //"jdbc:oracle:thin:scott/tiger@//w4111b.cs.columbia.edu:1521/ADB"; //"jdbc:oracle:thin:ab3416/kFxJssQk@//w4111b.cs.columbia.edu:1521/ADB"; "jdbc:oracle:thin:zzn2101/ycmrmMbM@//w4111b.cs.columbia.edu:1521/ADB"; private Connection conn; /** * @see HttpServlet#HttpServlet() */ public SearchResultServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = new PrintWriter(response.getOutputStream()); try { conn = (Connection) request.getSession().getAttribute("Connection"); if (conn == null) { // Create a OracleDataSource instance and set URL OracleDataSource ods = new OracleDataSource(); ods.setURL(connect_string); conn = ods.getConnection(); request.getSession().setAttribute("Connection", conn); } Statement stmt = conn.createStatement(); //String custID = (String)(request.getSession().getAttribute("custID")); //custID=custID.trim(); String searchText = request.getParameter("searchText"); searchText.trim(); if (searchText != "" || searchText != null) { /*ResultSet rset = stmt.executeQuery("select p.pid, description, price, type, " + "decode(category, 'T','Tops','P','Pants','O','Others') as categoryClothes, brand, author, " + "isbn from " + "products p, clothes c, books b where p.pid=b.pid and p.pid=c.pid " + "and description like '%" + searchText + "%' or brand like '%" + searchText + "%' or decode(category, 'T','Tops','P','Pants','O','Others') like '%" + searchText + "%' " + "or author like '%" + searchText + "%' or isbn like '%" + searchText + "%'");*/ pw.println("<html>"); pw.println("<head><title>Search Results</title></head>"); pw.println("<link rel='stylesheet' href='style.css' type='text/css' charset='utf-8' />"); pw.println("<BR><BR>"); pw.println("<H1>The following results matched your search criteria<BR></H1>"); pw.println("<body>"); ResultSet rset = stmt.executeQuery("select distinct p.pid, p.type, description, price, " + "decode(category, 'T','Tops','P','Pants','O','Others') as clothesCategory, " + "brand" + " from products p, clothes c " + "where p.pid=c.pid " + "and (lower(description) like lower('%" + searchText + "%') or lower(brand) like " + "lower('%" + searchText + "%') or lower(decode(category, 'T','Tops','P','Pants','O','Others')) like lower('%" + searchText + "%'))"); response.setContentType("text/html"); pw.println("<BR>"); pw.println("<BR>"); pw.println("<H2>"); while (rset.next()) { char type = rset.getString("type").trim().charAt(0); String prod_id = rset.getString("pid").trim(); String desc = rset.getString("description"); String price = rset.getString("price"); request.getSession().setAttribute("ID", prod_id); pw.print("Type Of Product : "); pw.println ("Clothes<BR>"); pw.print("Category : "); pw.println (rset.getString("clothesCategory") + "<BR>"); pw.print("Brand : "); pw.println (rset.getString("brand") + "<BR>"); pw.print("Description : "); pw.println (rset.getString("description") + "<BR>"); pw.print("Price : "); pw.println (rset.getString("price") + "<BR>"); String attr = "pid"; //request.setAttribute("pid", prod_id); //pw.println("<a href = Details.jsp?prodID=" + prod_id + ">Click here to purchase this product</a><BR>"); pw.println("<a href = Details.jsp?prodID=" + prod_id + ">Click here to purchase this product</a><BR>"); pw.println("<BR>"); pw.println("<BR>"); } rset.close(); pw.println("</H2>"); ResultSet rset1 = stmt.executeQuery("select distinct p.pid, p.type, description, price, " + "isbn, " + "author" + " from products p, books b " + "where p.pid=b.pid " + "and (lower(description) like lower('%" + searchText + "%') or " + "lower(isbn) like lower('%" + searchText + "%') or lower(author) like lower('%" + searchText + "%'))"); response.setContentType("text/html"); pw.println("<H2>"); while (rset1.next()) { String prod_id = rset1.getString("pid").trim(); request.getSession().setAttribute("ID", prod_id); pw.print("Type of Product : "); pw.println ("Books<BR>"); pw.print("Author : "); pw.println (rset1.getString("author") + "<BR>"); pw.print("ISBN : "); pw.println (rset1.getString("isbn") + "<BR>"); pw.print("Description : "); pw.println (rset1.getString("description") + "<BR>"); pw.print("Price : "); pw.println (rset1.getString("price") + "<BR>"); pw.println("<a href = Details.jsp?prodID=" + prod_id + ">Click here to purchase this product</a><BR>"); //pw.println("<a href = Details.jsp onclick = Details.jsp?prodID='" + prod_id + "'>Click here to purchase this product</a><BR>"); pw.println("<BR>"); pw.println("<BR>"); } pw.println("</H2>"); pw.println("<div id='nav-top'>"); pw.println("<ul>"); pw.println("<li><a href='Logout.jsp'>Logout</a> |</li>"); //pw.println("<li><a href='Account.jsp'>My Account</a> |</li>"); pw.println("<li><a href='Contact.jsp'>Contact us</a></li>"); pw.println("</ul>"); pw.println("</div>"); pw.println("</body></html>"); } } catch (SQLException e) { pw.println(e.getMessage()); } pw.close(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
zznshop
trunk/src/columbia/edu/SearchResultServlet.java
Java
epl
6,227
package columbia.edu; import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class LoginAuthentication extends HttpServlet{ private static final long serialVersionUID = 1L; //public void init(ServletConfig config) throws ServletException{} public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{ PrintWriter out = response.getWriter(); HttpSession session = request.getSession(true); if (session.isNew()){ session.setAttribute("accessCount", 1); System.out.println("This is a new session"); }else{ System.out.println("Welcome back!"); } System.out.println("session id: " + session.getId()); Integer accessCount = (Integer)session.getAttribute("accessCount"); if (accessCount != null) { accessCount = new Integer(accessCount.intValue() + 1); } session.setAttribute("accessCount", accessCount); System.out.println("accessCount" + accessCount); String connectionURL = "jdbc:oracle:thin:@//w4111b.cs.columbia.edu:1521/ADB"; Connection connection=null; ResultSet rs; String username=null; String passwrd=null; String fname="Anonymous"; String lname="Anonymous"; response.setContentType("text/html"); try { // Load the database driver boolean foundUser=false; Class.forName("oracle.jdbc.pool.OracleDataSource"); // Get a Connection to the database connection = (Connection) request.getSession().getAttribute("Connection"); if (connection == null) { connection = DriverManager.getConnection(connectionURL, "ab3416", "kFxJssQk"); request.getSession().setAttribute("Connection",connection); } String sql = "select cust_id,pwd from customers "; Statement s = connection.createStatement(); s.executeQuery (sql); rs = s.getResultSet(); System.out.println("size="+rs.getFetchSize()); String userform = request.getParameter("user"); String passform = request.getParameter("pass"); session.setAttribute("theName", userform); session.setAttribute("thePass", passform); System.out.println("userName from jsp="+userform ); System.out.println("pass from jsp="+ passform); while (rs.next ()){ username=rs.getString("cust_id").trim(); passwrd=rs.getString("pwd").trim(); System.out.println("username from data="+ username); System.out.println("password from data="+ passwrd); System.out.println("for user="+username.equals(request.getParameter("user"))); System.out.println("for pass="+passwrd.equals(request.getParameter("pass"))); if(username.equals(request.getParameter("user").trim()) && passwrd.equals(request.getParameter("pass"))){ String query = "select fname, lname from customers where cust_id LIKE ?"; PreparedStatement s1 = connection.prepareStatement(query); s1.setString(1,"%" + userform + "%"); // set input parameter ResultSet rs1 = s1.executeQuery(); System.out.println("size="+rs1.getFetchSize()); try { while (rs1.next()) { System.out.println("In while loop"); fname=rs1.getString("fname"); lname=rs1.getString("lname"); System.out.println("fname from data="+ fname); System.out.println("lname from data="+ lname); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } rs1.close(); s1.close(); request.setAttribute("fname", fname.toUpperCase() ); request.setAttribute("lname", lname.toUpperCase() ); String nextJSP = "/index2.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP); dispatcher.forward(request,response); foundUser=true; break; } } rs.close (); s.close (); if(!foundUser){ out.println("Please enter correct username and password"); out.println("<a href='AuthenticLogin.jsp'><br>Login again</a>"); } }catch(Exception e){ System.out.println("Exception is ;"+e); } finally { /* try { if (connection != null) connection.close(); } catch (SQLException ignored){ out.println(ignored); } */ } } }
zznshop
trunk/src/columbia/edu/LoginAuthentication.java
Java
epl
4,732
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@page import="java.sql.*"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <link rel="stylesheet" href="style.css" type="text/css" charset="utf-8" /> <title>Logout</title> </head> <body> <br><br> <form name="frmLogout" action="Logout" method=post > <h2 style="text-align:center">Are you sure you want to Logout?</h2> <br><br> <center><input type="submit" value="Yes"></center> </form> <br><br> <h4 style="text-align:center"><a href= "index2.jsp">Return to home page</a></h4> </body> </html>
zznshop
trunk/WebContent/Logout.jsp
Java Server Pages
epl
769
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ page import="java.sql.*"%> <%@ page import="oracle.jdbc.pool.OracleDataSource"%> <!-- Database lookup --> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <link rel="stylesheet" href="style.css" type="text/css" charset="utf-8" /> <title>Displaying product details</title> </head> <body> <BR> <BR> <H1>Here are the details of the product you selected</H1> <BR> <BR> <% Connection conn = null; ResultSet rset = null; String error_msg = ""; String ID = request.getParameter("prodID").toString(); ID=ID.trim(); try { OracleDataSource ods = new OracleDataSource(); ods.setURL("jdbc:oracle:thin:ab3416/kFxJssQk@//w4111b.cs.columbia.edu:1521/ADB"); conn=(Connection) request.getSession().getAttribute("Connection"); if (conn == null) { conn = ods.getConnection(); request.getSession().setAttribute("Connection", conn); } //request.getSession().setAttribute("custID", "39daisy"); //String ID = (String)(request.getSession().getAttribute("ID")); //String ID = request.getParameter("pid").toString(); //String ID = "CP005"; Statement stmt = conn.createStatement(); request.getSession().setAttribute("ID", ID); rset = stmt.executeQuery("select decode(category, 'T','Tops','P','Pants','O','Others') as type, description, brand, price from clothes c, products p where p.pid = c.pid and p.pid = '" + ID + "'"); response.setContentType("text/html"); } catch (SQLException e) { error_msg = e.getMessage(); //if( conn != null ) { //conn.close(); //} } %> <H3> <TABLE> <% if(rset != null) { while(rset.next()) { out.print("<tr>"); out.print("Type : " + rset.getString("type") + "<BR>"); out.print("</tr>"); out.print("<tr>"); out.print("Description : " + rset.getString("description") + "<BR>"); out.print("</tr>"); out.print("<tr>"); out.print("Brand : " + rset.getString("brand") + "<BR>"); out.print("</tr>"); out.print("<tr>"); out.print("Price : $" + rset.getString("price") + "<BR>"); out.print("</tr>"); } } else { out.print(error_msg); } //if( conn != null ) { //conn.close(); //} %> </TABLE> </H3> <% try { OracleDataSource ods = new OracleDataSource(); ods.setURL("jdbc:oracle:thin:ab3416/kFxJssQk@//w4111b.cs.columbia.edu:1521/ADB"); conn=(Connection) request.getSession().getAttribute("Connection"); if (conn == null) { conn = ods.getConnection(); request.getSession().setAttribute("Connection", conn); } Statement stmt = conn.createStatement(); rset = stmt.executeQuery("select description, isbn, author, publisher, published_date, edition, price " + "from books b, products p where p.pid = b.pid and p.pid = '" + ID + "'"); response.setContentType("text/html"); } catch(SQLException e) { error_msg = e.getMessage(); } %> <H3> <TABLE> <% if(rset != null) { while(rset.next()) { out.print("<tr>"); out.print("Description : " + rset.getString("description") + "<BR>"); out.print("</tr>"); out.print("<tr>"); out.print("ISBN : " + rset.getString("isbn") + "<BR>"); out.print("</tr>"); out.print("<tr>"); out.print("Author : " + rset.getString("author") + "<BR>"); out.print("</tr>"); out.print("<tr>"); out.print("Publisher : " + rset.getString("publisher") + "<BR>"); out.print("</tr>"); out.print("<tr>"); out.print("Published Date : " + rset.getString("published_date") + "<BR>"); out.print("</tr>"); out.print("<tr>"); out.print("Edition : $" + rset.getString("edition") + "<BR>"); out.print("</tr>"); out.print("<tr>"); out.print("Price : $" + rset.getString("price") + "<BR>"); out.print("</tr>"); } } else { out.print(error_msg); } //if( conn != null ) { //conn.close(); //} %> </TABLE> </H3> <form name='ProdDetailsForm' action='DisplayDetailsServlet'> <br> <h3> Enter Quantity Required : <input type='text' id = 'Enter Quantity Required : ' name='qty'> </h3> <br><br><input type='submit' value='Purchase'></br> </form> <div id="nav-top" align="right"> <ul> <li><a href="Logout.jsp">Logout</a> |</li> <!-- <li><a href="Account.jsp">My Account</a> |</li> --> <li><a href="Contact.jsp">Contact us</a></li> </ul> </div> </body> </html>
zznshop
trunk/WebContent/Details.jsp
Java Server Pages
epl
4,426
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- This import is necessary for JDBC --> <%@ page import="java.sql.*"%> <%@ page import="oracle.jdbc.pool.OracleDataSource"%> <!-- Database lookup --> <% Connection conn = null; ResultSet rset = null; String error_msg = ""; try { OracleDataSource ods = new OracleDataSource(); ods.setURL("jdbc:oracle:ab3416/kFxJssQk/tiger@//w4111b.cs.columbia.edu:1521/ADB"); conn=(Connection) request.getSession().getAttribute("Connection"); if (conn == null) { conn = ods.getConnection(); request.getSession().setAttribute("Connection", conn); } Statement stmt = conn.createStatement(); rset = stmt.executeQuery("select empno, ename, sal from emp"); } catch (SQLException e) { error_msg = e.getMessage(); if( conn != null ) { conn.close(); } } %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Employee Table JSP Sample</title> </head> <body> <H2>Employee Table</H2> <TABLE> <tr> <td>EMPNO</td><td>ENAME</td><td>SAL</td> </tr> <tr> <td><b>----------</b></td><td><b>----------</b></td><td><b>----------</b></td> </tr> <% if(rset != null) { while(rset.next()) { out.print("<tr>"); out.print("<td>" + rset.getInt("empno") + "</td><td>" + rset.getString("ename") + "</td>" + "<td>" + rset.getInt("sal") + "</td>"); out.print("</tr>"); } } else { out.print(error_msg); } if( conn != null ) { conn.close(); } %> </TABLE> <form method="post"> <table border="0" cellpadding="0" cellspacing="0"> <tr> <td>Enter your name: </td> <td><input type="text" name="txtName" size="20"/></td> </tr> <tr> <td>&nbsp;</td> <td><input type="submit" name="B1"/> <input type="reset" name="B2"/></td> </tr> </table> </form> </body> </html>
zznshop
trunk/WebContent/oracle_sample.jsp
Java Server Pages
epl
1,978
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <link rel="stylesheet" href="style.css" type="text/css" charset="utf-8" /> <title>Fashion Clothes</title> </head> <body> <div id="header"> <h1><em>Zen-Arch</em><strong>COLLECTION</strong></h1> </div> <div id="left-person"></div> <div id="uppers"> <form action="http://www.free-css.com/"> <select name="gender"> <option value="w">woman</option> <option value="w">man</option> </select> <input type="text" name="q" value="Enter product code" id="q" /> <input type="image" name="s" src="images/btn_header.gif" id="s" /> </form> <div id="nav-top"> <ul> <li><a href="AuthenticLogin.jsp">Login</a> |</li> <li><a href="Registration.jsp">New User</a> |</li> <li><a href="http://www.free-css.com/">Contact us</a></li> </ul> </div> </div> <div id="nav"> <div> <ul> <li><a href="index.jsp">HOME</a> &nbsp;|&nbsp;</li> <li><a href="http://www.free-css.com/">NEWS</a> &nbsp;|&nbsp;</li> <li><a href="http://www.free-css.com/">ACCESSORIES</a> &nbsp;|&nbsp;</li> <li><a href="http://www.free-css.com/">MEN COLLECTION</a> &nbsp;|&nbsp;</li> <li><a href="http://www.free-css.com/">WOMEN COLLECTION</a> &nbsp;|&nbsp;</li> <li><a href="http://www.free-css.com/">KIDS COLLECTION</a></li> </ul> </div> </div> <div id="body"> <h2><em>Welcome to our site</em> </h2> <p>This is an online shopping store </p> </div> <div id="black-tl"> <div id="black-tr"> <div id="black-br"> <div id="black-bl"> <div class="black-box"> <h2><em>Tops</em></h2> <p><a href="Clothes.jsp" onClick="Clothes.jsp?param=tops"><img src="pics/doublelayer.jpg" width="80" height="105" alt="Pic 1" /></a></p> <p>Our fashionable collection of tops</p> </div> <div class="black-box"> <h2><em>Pants</em> </h2> <p><a href="Display?name=pants"><img src="pics/chino.jpg" width="80" height="105" alt="Pic 2" /></a></p> <p>If you're looking for comfort and style </p> </div> <div class="black-box"> <h2><em>Others</em> </h2> <p><a href="Clothes.jsp" ><img src="pics/stripedenimblazer.jpg" width="80" height="105" alt="Pic 3" /></a></p> <p>Blazers,etc </p> </div> <div class="clear"></div> </div> </div> </div> </div> <div id="footer"> <div id="tips"> <h2><em>Fashion</em> tips</h2> <p>Comfort is fashion</p> <p class="more"><a href="http://www.free-css.com/">more</a></p> </div> <div id="choose"> <h2><em>Choose</em> a brand</h2> <p>Choose a Designer</p> <form action="http://www.free-css.com/"> <select name="q"> <option value="">Brand</option> </select> <input type="image" name="submit" src="images/btn_footer.gif" id="submit" /> </form> </div> </div> <div class="clear"></div> <div id="copyright"> Copyright information goes here. All rights reserved.</div> </body> </html>
zznshop
trunk/WebContent/index.jsp
Java Server Pages
epl
3,354
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <link rel="stylesheet" href="style.css" type="text/css" charset="utf-8" /> <title>Fashion Clothes</title> </head> <body> <div id="header"> <h1><em>Zen-Arch</em><strong>COLLECTION</strong></h1> </div> <div id="left-person"></div> <div id="uppers"> <form action="SearchResultServlet"> <input type="text" id="Enter a product you want to search for" value="Enter Desc" name="searchText"> <input type="image" name="s" src="images/btn_header.gif" id="s" /> </form> <div id="nav-top"> <ul> <li><a href="Logout.jsp">Logout</a> |</li> <!-- <li><a href="Account.jsp">My Account</a> |</li> --> <li><a href="Contact.jsp">Contact us</a></li> </ul> </div> </div> <div id="nav"> <div> <ul> <li><a href="index2.jsp">HOME</a> &nbsp;|&nbsp;</li> <li><a href="http://news.yahoo.com/entertainment/fashion">FASHION NEWS</a> &nbsp;|&nbsp;</li> <li><a href="http://ladyspeak.com/fashion">FASHION TIPS</a> &nbsp;&nbsp;</li> </ul> </div> </div> <div id="body"> <h2><em>Welcome to our site ${fname} </em> </h2> <p>This is an online shopping store </p> </div> <div id="black-tl"> <div id="black-tr"> <div id="black-br"> <div id="black-bl"> <div class="black-box"> <h2><em>Tops</em></h2> <p><a href="Display?name=tops"><img src="pics/doublelayer.jpg" width="80" height="105" alt="Pic 1" /></a></p> <p>Our fashionable collection of tops</p> </div> <div class="black-box"> <h2><em>Pants</em> </h2> <p><a href="Display?name=pants"><img src="pics/chino.jpg" width="80" height="105" alt="Pic 2" /></a></p> <p>If you're looking for comfort and style </p> </div> <div class="black-box"> <h2><em>Others</em> </h2> <p><a href="Display?name=other" ><img src="pics/stripedenimblazer.jpg" width="80" height="105" alt="Pic 3" /></a></p> <p>Blazers,etc </p> </div> <div class="black-box"> <h2><em>Books</em> </h2> <p><a href="Display?name=books" ><img src="pics/books.jpg" width="80" height="105" alt="Pic 3" /></a></p> <p>Variety of books </p> </div> <div class="clear"></div> </div> </div> </div> </div> <div id="footer"> <div id="tips"> <h2><em>Fashion</em> tips</h2> <p>Comfort is fashion</p> <p class="more"><a href="http://news.yahoo.com/entertainment/fashion">more</a></p> </div> </div> <div class="clear"></div> <div id="copyright"> Copyright information goes here. All rights reserved. </div> </body> </html>
zznshop
trunk/WebContent/index2.jsp
Java Server Pages
epl
2,962
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> </body> </html>
zznshop
trunk/WebContent/Books.jsp
Java Server Pages
epl
366
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@page import="java.util.*"%> <%@page import="java.io.*"%> <%@page import="java.sql.*"%> <%@page import="java.util.*"%> <%@page import="java.io.*"%> <%@page import="java.net.*"%> <%@page import="javax.servlet.*"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <link rel="stylesheet" href="style.css" type="text/css" charset="utf-8" /> <title>Display</title> </head> <body> <div id="header"> <h1><em>Zen-Arch</em><strong>COLLECTION</strong></h1> </div> <div id="nav-top"> <center> <ul> <li><a href="Logout.jsp">Logout</a> |</li> <!-- <li><a href="Account.jsp">My Account</a> |</li> --> <li><a href="Contact.jsp">Contact us</a></li> </ul> </center> </div> <div id="nav"> <div> <ul> <li><a href="index2.jsp">HOME</a> &nbsp;|&nbsp;</li> <li><a href="http://news.yahoo.com/entertainment/fashion">FASHION NEWS</a> &nbsp;|&nbsp;</li> <li><a href="www.ladyspeak.com/fashion">FASHION TIPS</a> &nbsp;&nbsp;</li> </ul> </div> </div> <br><br><br><br> <div id="body"> <center><table border="10" cellpadding="10"> <% String str= request.getAttribute("item").toString(); if (str.equals("clothes")){ %> <tr> <td><B>Description</B></td><td><B>Brand</B></td><td><B>Price (in $)</B></td><td><B>Click here to buy</B></td> </tr> <%}else if(str.equals("books")){%> <tr> <td><B>Description</B></td><td><B>Author</B></td><td><B>Price (in $)</B></td><td><B>Click here to buy</B></td> </tr> <%}%> <% ArrayList priceArray = (ArrayList) request.getAttribute("pricearray"); String myString=""; if(priceArray.isEmpty()==false){ for (int i=0;i<priceArray.size();i++){ //myString = (String) priceArray.get(i); %> <tr> <th><%=priceArray.get(i++) %></th><th><%=priceArray.get(i++) %></th><th><%=priceArray.get(i++) %></th><th><a href="Details.jsp?prodID=<%=priceArray.get(i) %>">Buy</a></th> </tr> <% } } %> </table> </center> </div> </body> </html>
zznshop
trunk/WebContent/Display.jsp
Java Server Pages
epl
2,285
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <link rel="stylesheet" href="style.css" type="text/css" charset="utf-8" /> <title>Registration Page</title> <script type="text/javascript" language = "Javascript"> function FillFields(box) { if(box.checked == false) { return; } document.me.shipstreet.value = document.me.street.value; document.me.shipcity.value = document.me.city.value; document.me.shipstate.value = document.me.state.value; document.me.shipcountry.value = document.me.country.value; document.me.shipzipcode.value = document.me.zipcode.value; } function Validate(){ var uname=document.me.username; var pass=document.me.password; var fname=document.me.firstname; var lname=document.me.lastname; var street=document.me.street; var city=document.me.city; var state=document.me.state; var country=document.me.country; var zipcode=document.me.zipcode; var card=document.me.card; var cardno=document.me.cardno; var expdate=document.me.expdate; if ((uname.value==null)||(uname.value=="")){ alert("Please Enter user name"); uname.focus(); return false; } if ((pass.value==null)||(pass.value=="")){ alert("Please Enter password"); pass.focus(); return false; } if ((fname.value==null)||(fname.value=="")){ alert("Please Enter first name"); fname.focus(); return false; } if ((lname.value==null)||(lname.value=="")){ alert("Please Enter last name"); lname.focus(); return false; } if ((street.value==null)||(street.value=="")){ alert("Please Enter Street"); uname.focus(); return false; } if ((city.value==null)||(city.value=="")){ alert("Please Enter City"); pass.focus(); return false; } if ((state.value==null)||(state.value=="")){ alert("Please Enter State"); state.focus(); return false; } if ((country.value==null)||(country.value=="")){ alert("Please Enter Country"); fname.focus(); return false; } if ((zipcode.value==null)||(zipcode.value=="")){ alert("Please Enter Zip COde"); lname.focus(); return false; } if ((card.value==null)||(card.value=="")){ alert("Please Enter Card Type V or M"); pass.focus(); return false; } if ((cardno.value==null)||(cardno.value=="")){ alert("Please Enter Cardno"); fname.focus(); return false; } if ((expdate.value==null)||(expdate.value=="")){ alert("Please Enter Exp date mm/yy"); lname.focus(); return false; } return true; } </script> </head> <body> <form name="me" action="Registration " method=post onSubmit="return Validate()" > <table cellpadding=4 cellspacing=10 border=0> <tr><th><font size=5>REGISTRATION</font></th></tr> <tr> <td valign=top><b>User Name<sup>*</sup></b> <br><input type="text" name="username" value="" size=10 maxlength=10></td> <td valign=top><b>Password<sup>*</sup></b> <br><input type="password" name="password" value="" size=10 maxlength=10></td> </tr> <tr> <td valign=top><b>First Name<sup>*</sup></b> <br><input type="text" name="firstname" value="" size=10 maxlength=20></td> <td valign=top><b>Last Name<sup>*</sup></b> <br><input type="text" name="lastname" value="" size=10 maxlength=20></td> </tr> <tr> <td>BILLING ADDRESS</td> </tr> <tr > <td valign=top><b>Street<sup>*</sup></b> <br><input type="text" name="street" size=20 maxlength=20><br></td> <td valign=top><b>City<sup>*</sup></b> <br><input type="text" name="city" size=10 maxlength=10></td> </tr> <tr> <td valign=top><b>State<sup>*</sup></b> <br><input type="text" name="state" size=10 maxlength=20></td> <td valign=top><b>Country<sup>*</sup></b> <br><input type="text" name="country" size=10 maxlength=20></td> </tr> <tr> <td valign=top><b>ZipCode<sup>*</sup></b> <br><input type="text" name="zipcode" size=10 maxlength=10></td> </tr> <tr> <td> <input type="checkbox" onclick="FillFields(this)"> Check box to copy billing info into shipping. <br> </td> </tr> <tr> <td>SHIPPING ADDRESS</td> </tr> <tr > <td valign=top><b>Street<sup>*</sup></b> <br><input type="text" name="shipstreet" size=20 maxlength=20><br></td> <td valign=top><b>City<sup>*</sup></b> <br><input type="text" name="shipcity" size=10 maxlength=10></td> </tr> <tr> <td valign=top><b>State<sup>*</sup></b> <br><input type="text" name="shipstate" size=10 maxlength=20></td> <td valign=top><b>Country<sup>*</sup></b> <br><input type="text" name="shipcountry" size=10 maxlength=20></td> </tr> <tr> <td valign=top><b>ZipCode<sup>*</sup></b> <br><input type="text" name="shipzipcode" size=10 maxlength=10></td> </tr> <tr> <td valign=top><b>Card <sup>*</sup></b><br> <select name="card"> <option value="V">Visa</option> <option value="M">Mastercard</option> </select></td> <td valign=top><b>Card No<sup>*</sup></b> <br><input type="password" name="cardno" size=16 value="" maxlength=16></td> </tr> <tr> <td valign=top><b>Expiration Date MM/YY<sup>*</sup></b> <br><input type="text" name="expdate" size=5 value="" maxlength=5></td> </tr> <tr> <td align=center colspan=2><hr> <input type="submit" value="Submit"></td> </tr> </table> </form> </body> </html>
zznshop
trunk/WebContent/Registration.jsp
Java Server Pages
epl
5,421