- 浏览: 1080469 次
- 性别:
- 来自: 上海
文章分类
- 全部博客 (1055)
- quartz定时任务 (1)
- json (9)
- 接口 (1)
- http (1)
- sccket (2)
- xmlbean (1)
- webservice (1)
- flex (1)
- sitemesh (2)
- json组装 (2)
- 存储过程 (6)
- ajax后台返回前台上下问 (3)
- flect反射机制 (1)
- 页面列表 (1)
- oracal结果集合并 (1)
- lucene (1)
- 读取配置文件工具 (1)
- 框架整合 (1)
- jms (3)
- 断点续传 (1)
- 页面之间的传值 (1)
- jpa (6)
- sql (8)
- jsp跳转 (1)
- jsp (6)
- jquery (2)
- ui (1)
- js与jsp之间的值的交互应用 (1)
- js空值判断 (1)
- Ajax (9)
- web-inf 编译目录 (1)
- 多线程 (9)
- 资料 (0)
- oracal (4)
- 多线程webservice (1)
- ztree (1)
- 加载与内容的变化 (1)
- 页面的公用变量 (1)
- web-inf目录结构 (1)
- 登陆系列 (1)
- jass应用于webservice认证 (2)
- 路径问题 (1)
- list合并 (1)
- list map中的value获取 (2)
- 标签tag (4)
- 方法 (1)
- 树形数据及其渲染 (1)
- require js 回调 (1)
- tab 页面切换 (2)
- 计时获取验证码 (1)
- 模式 (6)
- easyui (3)
- dialog (2)
- 乱码问题 (1)
- spring (29)
- sqlserver (1)
- iis,netframework (0)
- iis (1)
- netframework (1)
- 处理乱码问题 (1)
- struts-ajax (0)
- ,理论,了;,; (0)
- 排错方法 (1)
- hibernate (1)
- 二级缓存 (1)
- portal (1)
- date类型 (0)
- jvm out of memery StackOverflowError (1)
- echart数据填充 (0)
- echart (1)
- jmv (1)
- 学习 (0)
- java基础 (1)
- oracle性能优化 (1)
- 数据库三范式 (1)
- easy UI (1)
- oracle11g (1)
- form (3)
- servlet (2)
- spring mvc (1)
- htm5 (0)
- ibatise (1)
- 序列化 (1)
- tomcat双认证 (1)
- maven Lib (1)
- tomcat eclipse (2)
- ehcache (1)
- http 代替 ajax (2)
- rest (6)
- script脚本占位模板 (1)
- strust 标签 el表达式 (1)
- js bo (1)
- 公司资料 (0)
- js return (1)
- spring 第三方插件的工具类 (1)
- linux (10)
- linux 克隆 (1)
- linux xshell连接 (1)
- yum expect (1)
- linux 应用命令 (1)
- yum 缓存rmp包 (1)
- yum 本地库离线安装 (2)
- yum错误 (1)
- jsp页面用定时调用 (1)
- ajax setup (2)
- Exception,RuntimeException (1)
- 对话框 dialog (1)
- maven (17)
- PropertyPlaceholderConfigurer properties文件 (1)
- 错误集 (1)
- mybatise (0)
- 拦截器filter (1)
- http get post 区别 (1)
- rest 客户端两种返回的数据处理方式 (1)
- listener (2)
- maven工程 (1)
- ContainerResponseFilter (1)
- ajax action 打印任意实体类jsp (1)
- yum svn mvn (1)
- 分页 (1)
- angularjs (1)
- memcached (1)
- git (12)
- yyyyyyyy (0)
- oracal安装 (4)
- jaxwswebservice (1)
- spring bean (1)
- 排方法 (0)
- java 生成pdf (2)
- 创建目录 (1)
- 下载与生产pdf文件 (1)
- base64 (2)
- 配置文件 (2)
- blob (1)
- pdf (1)
- yum linux 安装Oracle (1)
- excl 插入数据库 (1)
- 搭建框架 (1)
- .classpath和jdk jre (1)
- mybatise 配置文件通配 (1)
- 用Maven插件生成Mybatis代码 (2)
- springmvc值的传递 (1)
- js jsp html (1)
- ajax跨域 (1)
- javamail (0)
- 提交复杂格式json数据 (1)
- get中文乱码/post (1)
- 弹出框,承载弹出链接----页面,显示大图 (1)
- @RequestBody list bean (1)
- 隐藏域 (1)
- 多页保存 (1)
- form 校验 (1)
- 注册,上传图片 (1)
- 登录验证 (1)
- 全局的异常处理 (0)
- 异常捕获,显示在页面 (0)
- mybatise事物配置 (1)
- maven compile (1)
- 时间格式 (1)
- js 跳转页面 (1)
- pringsecurity 角色授资源要重启服务 (0)
- Retrofi restfull (1)
- session过期推出,直接点击退出,退出 (0)
- 参数放于requestbody (1)
- maven本地仓库jar包 (1)
- 编译环境出错jdk1.6 1,7 (1)
- jsonarray ---json数组格式 (1)
- java后台文件上传,接受的2种方式 (0)
- 生成保存图片 (1)
- 权限mysql数据库Md5加密sql (1)
- mysql一对多关联查询 (1)
- mysql批量更新 (0)
- oracle in exists 区别 (1)
- https (1)
- linux发布脚本 (1)
- dubbo zookeepr (1)
- request.getParameter() (1)
- request.setAttribute() (1)
- @RequestMapping @ResponseBody (1)
- @RequestMapping @responsebody src控件 后台如何写入src值 (1)
- dwz (8)
- lib jar maven (1)
- web服务访问名称 (1)
- mvc返回内容设置,拦截 (1)
- @ResponseBody 返回json处理 (1)
- 视图,函数,存储过程 (1)
- <context:annotation-config/> (1)
- <context:component-scan/> (1)
- xml路劲通配 (2)
- 杂项 (1)
- dubbo (34)
- redis (25)
- mybatis (34)
- springmvc (15)
- js (7)
- sprinvmvc (1)
- 设计理念 (1)
- 工程 (1)
- 其他 (149)
- 导出,下载 (1)
- session (4)
- token (1)
- Exception处理 (2)
- 注解 (2)
- 框架 (3)
- shrio (1)
- login (1)
- 项目结构设计 (1)
- mybatis两种关联查询 (1)
- mybaits (2)
- 迭代模式 (1)
- oralce树形数据结构构建 (2)
- 树形结构的jsp展现 (1)
- filter intecept(Struts) (1)
- 树形结构数据的提交 (1)
- @RequestBody @RequestParam (1)
- div (1)
- equals重写 (1)
- 程序设计 (1)
- f多层for循环跳出 (1)
- 看源码 (0)
- 权限系统普遍通性 (1)
- 设计程序 (1)
- 动态拼接元素样式问题 (1)
- sql迭代 (1)
- debug断点 (1)
- spring mvc 扫描注解(ioc (1)
- di) (1)
- jdk (2)
- cglib (1)
- mybatis 多层括号(超过三层)解析不了 (1)
- tiles (2)
- cacheManager缓存的切换 (1)
- jsp,xml中el表达式等占位符中的数据操作 (1)
- jpa 及spring data jpa开发 (1)
- compareTo equals toString (1)
- 子页面用父页面js (1)
- jsp相对路径自加问题 (1)
- bean之间的相互拷贝 (1)
- DECODE (2)
- 泛型 (2)
- NVL (1)
- jsp jstl函数 用标签声明页面变量,供jstl使用,时间格式问题 (1)
- form表单切换action值 (1)
- response.getWriter().write()功能优于springMvc的返回 (1)
- 快速复制构建项目 (1)
- activeMq (15)
- cache (2)
- sql获取序列号 (1)
- 上传 (2)
- tfs (1)
- jsp标签 (2)
- qita (1)
- 触发器 (1)
- Exception (1)
- mybais (1)
- 标签 (1)
- connect by (1)
- for ... in (1)
- map转化为list (1)
- 树形结构list构建(树形实体) (1)
- 左侧菜单的设计 (1)
- response.getWriter().write() (1)
- eclipse打断点之后断无效 (1)
- 直接访问/web-inf/下的页面 (1)
- clob (1)
- freemark (1)
- 框架的设计 (1)
- get方式处理乱码 (1)
- Request的getParameter和getAttribute方法的区别 (1)
- cas (9)
- 时间格式问题 (1)
- ResponseUtil.writeToResponse (1)
- 树形数据的反选 (1)
- spring data jpa (1)
- jsp异常提示 (1)
- jquery js (1)
- eclipse (1)
- 乱码 (1)
- Json OBJETC (1)
- PROCEDURE (1)
- pl/sql oracle (1)
- 设计 (1)
- el表达式 (3)
- iframe (1)
- map (1)
- jsp中调用Java (1)
- response.getWriter().write() ajax (1)
- mybatis xml 传入参数 (0)
- response与request在返回时作用区别 (1)
- spring cache (1)
- 模型驱动 (1)
- 关于mybatis传空值的处理 (1)
- 日志配置 (1)
- mapper (1)
- mapper mybatis (1)
- mapper mybatis-spring spring-data-jpa (1)
- js插件 (1)
- spring-data-jpa (2)
- 字节流转化过程 (1)
- 数据库 (11)
- jsp页面 (1)
- 局域网络访问问题 (1)
- plsql (2)
- response (1)
- plsq (1)
- Proxool (1)
- cas security (1)
- 系统配置化 (1)
- 集群 (4)
- springboot (24)
- 设计模式 (5)
- 通知 (1)
- 架构 (48)
- zookeeper (5)
- mvc框架 (1)
- 事物隔离策略 (1)
- jvm (8)
- 调研 (1)
- Java工具类 (1)
- 并发容器 (3)
- 多线程管理器 (4)
- 简历 (0)
- 查询 (1)
- 集群工具 (1)
- springMcv (1)
- ConcurrentHashMap (1)
- hashtable (1)
- cac (1)
- 树形结构 (1)
- 定时任务 (1)
- tortoiseGit (2)
- struts (11)
- shiro (31)
- log4j (3)
- struts2 (2)
- 编码 (1)
- request (3)
- Nginx (14)
- tomcat (1)
- idea (12)
- mvc (2)
- BeanUtils (2)
- image (1)
- mino (1)
- httpClient (1)
- volecity (1)
- swagger (3)
- 调错 (0)
- data (1)
- log (1)
- shell (1)
- 事物 (3)
- junit (1)
- RestTemplate (2)
- 线程 (0)
- Exception异常处理 (1)
- Exception异常注解 (1)
- lock (1)
- HashMap (1)
- 面试 (0)
- rabbitMq (1)
- rainCat (1)
- 其它 (1)
- activemq消息传送机制以及ACK机制详解 (0)
- mysql (7)
- fildder (1)
- UML (1)
- 校验 (1)
- 反射 (1)
- 切面 (1)
- springioc (1)
- urule2 (0)
- skywalking (1)
- urule (2)
- docker (2)
- 前端 (1)
- bootstrap (1)
- eureka (2)
- springcloud (16)
- jenkins (2)
- springsecurity (1)
- 数据结构 (4)
- gradle (1)
- mycat (3)
- nacos (1)
- canary (1)
- 线程池 (1)
- solr (1)
- resteasy (2)
- BI (1)
- dfs (2)
- elasticsearch (1)
- ruby (1)
- logstash (1)
- clickhouse (2)
- davinci (15)
- java (1)
- davinvi (1)
- fastdfs (1)
- vue (1)
- 《将博客搬至CSDN》 (1)
最新评论
-
nizhipeng123:
private SessionFactory sessio ...
用map接收参数的几个注意的问题
web.xml
<servlet>
<servlet-name>RESTEntrance</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.certusnet.nfv.mano.vnfm.RestApplication</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>RESTEntrance</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
////新增的接口
package com.certusnet.nfv.mano.vim.vm.rest;
import java.awt.List;
import java.util.Iterator;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import com.certusnet.nfv.mano.exception.ManoException;
import com.certusnet.nfv.mano.rest.ContentType;
import com.certusnet.nfv.mano.vim.ExceptionCode;
import com.certusnet.nfv.mano.vim.HttpsUtil;
import com.certusnet.nfv.mano.vim.network.rest.NetworkRest;
import com.certusnet.nfv.mano.vim.network.service.INetworkService;
import com.certusnet.nfv.mano.vim.vm.rsclient.IVmRsClient;
import com.certusnet.nfv.mano.vim.vm.rsclient.impl.VmRsClient;
import javax.ws.rs.FormParam;
@Component
@Path("/")
public class VmRest {
private static Logger logger = Logger.getLogger(VmRest.class);
@Autowired
// private IVmRsClient vmRsClient = new VmRsClient();
private IVmRsClient vmRsClient;
//访问的时候用url建立客户端,之后,直接通过get标注获取标注中写接收response的类即可
@GET
@Path("vdus")
@Produces(ContentType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.TEXT_PLAIN)
public JSONArray findVmList(@HeaderParam("X-Auth-Token") String token) {
logger.info("findVmList-X-Auth-Token=" + token);
try {
String returnStr = vmRsClient.findVmList(token);
logger.debug("find-vm-list-returnstr=" + returnStr);
returnStr = returnStr.replace("null", "\"\"");
JSONObject jsonObj = JSONObject.fromObject(returnStr);
if (!"200".equalsIgnoreCase(jsonObj.getString("retCode")))
throw new ManoException(ExceptionCode.FIND_VDU_LIST_FAILED);
JSONArray vmJsonObj = jsonObj.getJSONArray("vms");
logger.info("find-vm-list-returnobj=" + vmJsonObj);
return vmJsonObj;
} catch (ManoException ex) {
throw ex;
} catch (Exception ex) {
throw new ManoException(ExceptionCode.FIND_VDU_LIST_FAILED, ex);
}
}
@GET
@Path("vdus/{vdu_uuid}/detail")
@Produces(ContentType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.TEXT_PLAIN)
public JSONObject findVmById(@PathParam("vdu_uuid") String vm_id,@HeaderParam("X-Auth-Token") String token) {
logger.info("findVmById-X-Auth-Token=" + token);
if ((null == vm_id) || (vm_id.trim().equalsIgnoreCase(""))) {
throw new ManoException(ExceptionCode.PARAM_NEEDED_IS_NULL);
}
try {
String returnStr = vmRsClient.findVmById(vm_id,token);
logger.debug("findVmById-returnstr=" + returnStr);
returnStr = returnStr.replace("null", "\"\"");
JSONObject jsonObj = JSONObject.fromObject(returnStr);
if (!"200".equalsIgnoreCase(jsonObj.getString("retCode")) && !"404".equalsIgnoreCase(jsonObj.getString("retCode")))
throw new ManoException(ExceptionCode.FIND_VDU_FAILED);
if ("404".equalsIgnoreCase(jsonObj.getString("retCode")))
throw new ManoException(ExceptionCode.ITEM_NOT_FOUND);
logger.debug("findVmById-jsonObj = " + jsonObj);
JSONObject vmJsonObj = jsonObj.getJSONObject("vm").getJSONObject(
"server");
String flavor_id = vmJsonObj.getJSONObject("flavor")
.getString("id");
JSONObject addresses = vmJsonObj.getJSONObject("addresses");
logger.debug("findVmById-addresses = " + addresses);
String ip_addr = "";
for (Iterator iter = addresses.keys(); iter.hasNext();) {
String key = (String)iter.next();
String ip_addr_temp = addresses.getJSONArray(key).getJSONObject(0).getString("addr").trim();
if (!ip_addr_temp.equals("")) {
if (ip_addr.equals("")) {
ip_addr += ip_addr_temp;
} else {
ip_addr += "," + ip_addr_temp;
}
}
}
String returnFlavorStr = vmRsClient.findFlavorById(flavor_id);
logger.debug("findVmById-returnFlavorStr=" + returnFlavorStr);
JSONObject returnFlvorJsonObj = JSONObject
.fromObject(returnFlavorStr);
logger.debug("findVmById-flavor-returnJsonObj=" + returnFlvorJsonObj);
JSONObject flavorJsonObj = returnFlvorJsonObj
.getJSONObject("flavor");
int cpu_number = flavorJsonObj.getInt("vcpus");
Double memory_size = ((Double) (flavorJsonObj.getInt("ram") * 1.0)) / 1024;
int disk_size = flavorJsonObj.getInt("disk");
JSONObject returnJsonObj = new JSONObject();
returnJsonObj.put("status", vmJsonObj.getString("status"));
returnJsonObj.put("vm_image", vmJsonObj.getJSONObject("image").getString("id"));
returnJsonObj.put("cpu_number", cpu_number);
returnJsonObj.put("memory_size", memory_size);
returnJsonObj.put("disk_size", disk_size);
returnJsonObj.put("path", "");
returnJsonObj.put("uuid",vm_id);
returnJsonObj.put("ip_addr",ip_addr);
returnJsonObj.put("name",vmJsonObj.getString("name"));
logger.info("findVmById-returnJsonObj=" + returnJsonObj);
return returnJsonObj;
} catch (ManoException ex) {
throw ex;
} catch (Exception ex) {
throw new ManoException(ExceptionCode.FIND_VDU_FAILED, ex);
}
}
@POST
@Path("vdus")
@Produces(ContentType.APPLICATION_JSON_UTF_8)
// @Consumes(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
// "application/json"
// @Consumes("application/json")
// public String createVm(@QueryParam("vdu_params") String vdu_params)
public Object createVm(@FormParam("vdu_params") String vdu_params,
@HeaderParam("X-Auth-Token") String token) throws ManoException {
logger.info("createVm-X-Auth-Token=" + token);
if ((null == token) || (token.trim().equalsIgnoreCase(""))) {
throw new ManoException(ExceptionCode.AUTH_TOKEN_IS_EMPTY);
}
logger.info("createVm-vdu_params:" + vdu_params);
if ((null == vdu_params) || (vdu_params.trim().equalsIgnoreCase(""))) {
throw new ManoException(ExceptionCode.PARAM_NEEDED_IS_NULL);
}
try {
logger.info("createVm-vdu_params:" + vdu_params);
JSONObject jsonObj = JSONObject.fromObject(vdu_params);
logger.info("tangjing-createVm-vdu_params-json:" + jsonObj.toString());
String image_id = "";
String cpu_number = "";
String mem_size = "";
String disk = "";
String network_list = "";
String user_param = "";
String seq_id = "";
String id = "";
String parent_id = "";
JSONArray networklist = new JSONArray();
JSONObject network_json = new JSONObject();
String vm_image = jsonObj.getString("vm_image");
image_id = vm_image;
int cpu_number_int = jsonObj.getInt("cpu_number");
cpu_number = "" + cpu_number_int;
double memory_size_int = jsonObj.getDouble("memory_size");
mem_size = "" + memory_size_int * 1024;
int disk_size_int = jsonObj.getInt("disk_size");
disk = "" + disk_size_int;
String user_param_from_json = jsonObj.getString("user_param");
user_param = user_param_from_json;
int seq_id_from_json = jsonObj.getInt("seq_id");
seq_id = "" + seq_id_from_json;
String id_from_json = jsonObj.getString("id");
id = id_from_json;
String parent_id_from_json = jsonObj.getString("parent_id");
parent_id = parent_id_from_json;
// String path = jsonObj.getString("vm_image");
//
// String file_content = jsonObj.getString("file_content");
JSONArray vlink_uuid_list = jsonObj.getJSONArray("vlink_uuid_list");
if ((null == vlink_uuid_list) || (vlink_uuid_list.isEmpty())) {
throw new ManoException(ExceptionCode.CREATE_VDU_FAILED);
} else {
int vlink_length = vlink_uuid_list.size();
logger.info("create-vm-vlink_length=" + vlink_length);
// System.Text.StringBuilder stringBuilder = new
// System.Text.StringBuilder();
for (int i = 0; i < vlink_length; i++) {
JSONObject tempJsonObj = vlink_uuid_list.getJSONObject(i);
JSONObject oneNetwork = new JSONObject();
String tmpStr = "";
tmpStr = tmpStr + tempJsonObj.getString("vlink_uuid");
oneNetwork.put("network_uuid", tempJsonObj.getString("vlink_uuid"));
String tempStrNetworkType = tempJsonObj
.getString("network_type");
tmpStr = tmpStr + "," + tempStrNetworkType;
oneNetwork.put("network_type", tempStrNetworkType);
tmpStr = tmpStr + ","
+ tempJsonObj.getString("service_type");
;
oneNetwork.put("service_type", tempJsonObj.getString("service_type"));
if ("E-LAN-L3".equalsIgnoreCase(tempStrNetworkType)) {
tmpStr = tmpStr + ","
+ tempJsonObj.getString("gateway_ip");
;
oneNetwork.put("gateway_ip", tempJsonObj.getString("gateway_ip"));
}
network_list = network_list + tmpStr;
if (i < vlink_length - 1) {
network_list = network_list + "/";
}
oneNetwork.put("seq_id", "" + tempJsonObj.getInt("seq_id"));
oneNetwork.put("vif_model", tempJsonObj.getString("vif_model"));
networklist.add(oneNetwork);
logger.info("create-vm-oneNetwork:" + oneNetwork);
}
}
network_json.put("network_list", networklist);
logger.info("create-vm-network_json:" + network_json);
logger.info("create-vm-network_list:" + network_list);
String scapeRestReturnStr = vmRsClient.createVm(image_id,
cpu_number, mem_size, disk,id,parent_id,seq_id,user_param, network_json.toString(),token);
JSONObject scapeJsonObj = JSONObject.fromObject(scapeRestReturnStr);
logger.info("createVm-scapeJsonObj=" + scapeJsonObj.toString());
logger.info("createVm-retCode=" + scapeJsonObj.getString("retCode"));
if (!"200".equalsIgnoreCase(scapeJsonObj.getString("retCode")))
throw new ManoException(ExceptionCode.CREATE_VDU_FAILED);
JSONObject returnJsonObj = new JSONObject();
returnJsonObj.put("uuid", scapeJsonObj.getString("id"));
return returnJsonObj;
} catch (ManoException ex) {
throw ex;
} catch (Exception ex) {
logger.error("createVm-ex:" + ex);
throw new ManoException(ExceptionCode.CREATE_VDU_FAILED, ex);
}
}
@DELETE
@Path("vdus/{vdu_uuid}")
@Produces(ContentType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.TEXT_PLAIN)
public String deleteVm(@PathParam("vdu_uuid") String vm_id,
@HeaderParam("X-Auth-Token") String token) throws ManoException {
logger.info("deleteVm-X-Auth-Token=" + token);
if ((null == token) || (token.trim().equalsIgnoreCase(""))) {
throw new ManoException(ExceptionCode.AUTH_TOKEN_IS_EMPTY);
}
logger.info("deleteVm-vdu_uuid:" + vm_id);
if ((null == vm_id) || (vm_id.trim().equalsIgnoreCase(""))) {
throw new ManoException(ExceptionCode.PARAM_NEEDED_IS_NULL);
}
try {
String returnStr = vmRsClient.deleteVm(vm_id,token);
JSONObject jsonObj = JSONObject.fromObject(returnStr);
logger.info("deleteVm-find-host-list-returnStrJsonObj=" + jsonObj);
if (!"200".equalsIgnoreCase(jsonObj.getString("retCode")) && !"404".equalsIgnoreCase(jsonObj.getString("retCode")))
throw new ManoException(ExceptionCode.DELETE_VDU_FAILED);
if ("404".equalsIgnoreCase(jsonObj.getString("retCode")))
throw new ManoException(ExceptionCode.ITEM_NOT_FOUND);
return "";
} catch (ManoException ex) {
throw ex;
} catch (Exception ex) {
throw new ManoException(ExceptionCode.DELETE_VDU_FAILED, ex);
}
}
//不能放在main方法中,否则没有实例可以创建,这个可以用单元测试@junite
public static void main(String[] args) {
VmRest vm = new VmRest();
// String image_id = "307e56ea-f500-4c1f-a5b8-8a43cb8d1e83";
// String cpu_number = "1";
// String mem_size = "512";
// String disk = "1";
// String network_list= "71d9ca38-bb8e-4384-873b-82985bcfb7f0,L2,data";
//vm.findVmList();
vm.findVmById("b5a74a90-011c-43f9-87a1-c33c1901f386", "123");
// vm.findVmById("15afdb66-e607-43c4-b7c4-589fe0218c6a");
// vm.createVm(image_id, cpu_number, mem_size, disk, network_list);
// vm.deleteVm("cd171a62-ce10-47be-9dad-ddebbc27908c");
}
}
////注册新增的接口
package com.certusnet.nfv.mano.vim;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.web.filter.RequestContextFilter;
import com.certusnet.nfv.mano.rest.ManoExceptionMapper;
import com.certusnet.nfv.mano.rest.RestResponseFilter;
import com.certusnet.nfv.mano.vim.host.rest.HostRest;
import com.certusnet.nfv.mano.vim.alarm.rest.AlarmRest;
import com.certusnet.nfv.mano.vim.cpu_utilization_history.rest.Cpu_utilization_historyRest;
import com.certusnet.nfv.mano.vim.network.rest.NetworkRest;
import com.certusnet.nfv.mano.vim.port.rest.PortRest;
import com.certusnet.nfv.mano.vim.providernet.rest.ProvidernetRest;
import com.certusnet.nfv.mano.vim.usage_history.rest.Usage_historyRest;
import com.certusnet.nfv.mano.vim.vm.rest.VmRest;
import com.certusnet.nfv.mano.vim.vnf.rest.HelloNfvRest;
public class RestApplication extends ResourceConfig {
/**
* Register JAX-RS application components.
*/
public RestApplication () {
register(RequestContextFilter.class);
register(HelloNfvRest.class);
register(VmRest.class);
register(Usage_historyRest.class);
register(Cpu_utilization_historyRest.class);
register(ProvidernetRest.class);
register(ManoExceptionMapper.class);
register(RestResponseFilter.class);
register(NetworkRest.class);
register(HostRest.class);
register(AlarmRest.class);
register(PortRest.class);
}
}
//客户端
package com.certusnet.nfv.mano.nfvo.vnfr.rsclient.impl;
import org.apache.log4j.Logger;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import org.springframework.util.StringUtils;
import com.certusnet.nfv.mano.common.pojo.VDUDetailResp;
import com.certusnet.nfv.mano.common.pojo.VDUDetailResult;
import com.certusnet.nfv.mano.common.pojo.VduVm;
import com.certusnet.nfv.mano.exception.ManoException;
import com.certusnet.nfv.mano.nfvo.vnfr.pojo.VduQueryResp;
import com.certusnet.nfv.mano.nfvo.vnfr.rsclient.IVduRsClient;
import com.certusnet.nfv.mano.rest.ContentType;
import com.certusnet.nfv.mano.rest.RestResultCode;
import com.certusnet.nfv.mano.rsclient.RsClient;
//用注入的方式获取vimRestRootUrl
//<bean id="vimRsClient"
//class="com.certusnet.nfv.mano.vnfm.vnfr.vimrestclient.VimRestClient">
// <property name="vimRestRootUrl" value="${VIM_REST_ROOT_URL}" />
//</bean>
public class VduRsClient extends RsClient implements IVduRsClient {
private static final String VDU_URL = "vdus";
private static Logger logger = Logger.getLogger(VduRsClient.class);
@Override
public VDUDetailResult queryVDUDetail(String uuid) {
if(StringUtils.isEmpty(uuid))
{
return null;
}
Client client = getClient();
WebTarget webTarget = client.target(vimRestRootUrl).path(VDU_URL)
.path(uuid).path("detail");
Invocation.Builder invocationBuilder = webTarget
.request(ContentType.APPLICATION_JSON_UTF_8);
VDUDetailResp resp = invocationBuilder.get(VDUDetailResp.class);
if (!"ok".equals(resp.getRetCode().trim())) {
if(RestResultCode.ITEM_NOT_FOUND.equals(resp.getRetCode()))
{
logger.error(resp.getRetCode() + ":" + resp.getMsg());
return null;
}
else
{
throw new ManoException(resp.getRetCode(), resp.getMsg());
}
}
return resp.getResult();
}
@Override
public VduVm findVduVm(String vduUUID) {
if(StringUtils.isEmpty(vduUUID))
{
return null;
}
Client client = getClient();
WebTarget webTarget = client.target(vimRestRootUrl).path(VDU_URL)
.path(vduUUID).path("detail");
Invocation.Builder invocationBuilder = webTarget
.request(ContentType.APPLICATION_JSON_UTF_8);
VduQueryResp resp = invocationBuilder.get(VduQueryResp.class);
if (!resp.getRetCode().equals("ok")) {
if(RestResultCode.ITEM_NOT_FOUND.equals(resp.getRetCode()))
{
logger.error(resp.getRetCode() + ":" + resp.getMsg());
return null;
}
else
{
throw new ManoException(resp.getRetCode(), resp.getMsg());
}
}
return resp.getResult();
}
}
//客户端2(框架本身)
package com.certusnet.nfv.mano.nfvo.vnfr.rsclient.impl;
import javax.annotation.Resource;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.certusnet.nfv.mano.common.pojo.RestResultResp;
import com.certusnet.nfv.mano.exception.ManoException;
import com.certusnet.nfv.mano.rest.ContentType;
import com.certusnet.nfv.mano.rest.RestResultCode;
import com.certusnet.nfv.mano.rsclient.RsClient;
import com.certusnet.nfv.mano.vnfm.token.RestToken;
//访问的时候用url建立客户端,之后,直接通过get标注获取标注中写接收response的类即可
@Component
public class VnfmRsClient extends RsClient {
private Logger logger = Logger.getLogger(VnfmRsClient.class);
private static final String VNFM_URL = "vnfrs";
@Resource
private RestToken restToken;
public void deleteVNFR(Long vnfrId) {
Client client = getClient();
WebTarget webTarget = client.target(vnfmRestRootUrl).path(VNFM_URL)
.path(String.valueOf(vnfrId));
Invocation.Builder invocationBuilder = webTarget.request(
ContentType.APPLICATION_JSON_UTF_8).header(RestToken.key,
restToken.getToken());
RestResultResp resp = invocationBuilder.delete(RestResultResp.class);
if (!RestResultCode.OK.equals(resp.getRetCode().trim())
&& !RestResultCode.ITEM_NOT_FOUND.equals(resp.getRetCode()
.trim())) {
logger.error("Request VNFM RESTful for deleteVNFR, the response msg is : "
+ resp.getMsg());
throw new ManoException(resp.getRetCode(), resp.getMsg());
}
}
public void deleteVLByVNFRId(Long vnfrId) {
Client client = getClient();
WebTarget webTarget = client.target(vnfmRestRootUrl).path(VNFM_URL)
.path(String.valueOf(vnfrId)).path("vlrs");
Invocation.Builder invocationBuilder = webTarget.request(
ContentType.APPLICATION_JSON_UTF_8).header(RestToken.key,
restToken.getToken());
RestResultResp resp = invocationBuilder.delete(RestResultResp.class);////与结果集对应字段的类
if (!RestResultCode.OK.equals(resp.getRetCode().trim())
&& !RestResultCode.ITEM_NOT_FOUND.equals(resp.getRetCode()
.trim())) {
logger.error("Request VNFM RESTful for deleteVLByVNFRId, the response msg is : "
+ resp.getMsg());
throw new ManoException(resp.getRetCode(), resp.getMsg());
}
}
}
//客户端 3 (要用到工具类)
public SummeryOfResourcesVO getSummeryOfResource() {
logger.info("查询一组资源使用情况(云主机、虚拟内核、虚拟内存、安全组)信息");
final SummeryOfResourcesVO vo = new SummeryOfResourcesVO();
final JSONObject[] provider = new JSONObject[1];
final String[] reslt= new String[1];
/**取资源使用情况*/
HttpClientRequest request = new HttpClientGetRequest(ConfigFileLoad.getConfContent("API_IP") + "/rest/resource_used");
try {
request.process(new HttpClientResponseHandler() {
@Override
public void handle(String response, String retCode, String msg) throws HttpClientException,ManoException {
logger.debug("查询一组资源使用情况信息,返回状态:" + retCode + ",返回信息:" + msg);
JSONObject obj = JSONObject.parseObject(response);
if(obj.get("result")!=null){
System.out.println(obj.get("result").toString());
JSONObject jsonObj = JSONObject.parseObject(obj.get("result").toString());
if (jsonObj == null){
//&&!reslt[0].equals("0")
return;
}
// 一 、请求并计算 云主机信息
Integer vms = jsonObj.getInteger(Constants.OverView.VMS);
Integer used_vms = jsonObj.getInteger(Constants.OverView.USED_VMS);
Integer unused_vms = 0;
if (vms == null || vms.equals("")) {
vms = 0;
} else if (used_vms == null || used_vms.equals("")) {
used_vms = 0;
} else {
unused_vms = vms - used_vms;
}
vo.setCloudPlatformAll(String.valueOf(vms));
vo.setCloudPlatformUsed(String.valueOf(used_vms));
vo.setCloudPlatformUnUsed(String.valueOf(unused_vms));
// 二 、请求 虚拟内核
Integer cpus = jsonObj.getInteger(Constants.OverView.CPUS);
Integer used_cpus = jsonObj.getInteger(Constants.OverView.USED_CPUS);
Integer unused_cpus = 0;
if (cpus == null || cpus.equals("")) {
cpus = 0;
} else if (used_cpus == null || used_cpus.equals("")) {
used_cpus = 0;
} else {
unused_cpus = cpus - used_cpus;
}
vo.setVirtualKernelAll(String.valueOf(cpus));
vo.setVirtualKernelUsed(String.valueOf(used_cpus));
vo.setVirtualKernelUnUsed(String.valueOf(unused_cpus));
// 三、请求 虚拟内存
Integer mems = jsonObj.getInteger(Constants.OverView.MEMS);
Integer used_mem = jsonObj.getInteger(Constants.OverView.USED_MEM);
Integer unused_mem = 0;
if (mems == null || mems.equals("")) {
mems = 0;
} else if (used_mem == null || used_mem.equals("")) {
used_mem = 0;
} else {
unused_mem = mems - used_mem;
}
vo.setVirtualMemoryAll(String.valueOf(mems));
vo.setVirtualMemoryUsed(String.valueOf(used_mem));
vo.setVirtualMemoryUnUsed(String.valueOf(unused_mem));
// 四、请求 安全组
Integer security_group = jsonObj.getInteger(Constants.OverView.SECURITY_GROUP);
Integer used_security_group = jsonObj.getInteger(Constants.OverView.USED_SECURITY_GROUP);
Integer unused_security_group = 0;
if (security_group == null || security_group.equals("")) {
security_group = 0;
} else if (used_security_group == null || used_security_group.equals("")) {
used_security_group = 0;
} else {
unused_security_group = security_group - used_security_group;
}
vo.setSecurityGroupAll(String.valueOf(security_group));
vo.setSecurityGroupUsed(String.valueOf(used_security_group));
vo.setSecurityGroupUnUsed(String.valueOf(unused_security_group));
}else{
/**provider连接数*/
HttpClientRequest requestProvider = new HttpClientGetRequest(ConfigFileLoad.getConfContent("API_IP") + "/rest/provider_network_cn");
try {
requestProvider.process(new HttpClientResponseHandler() {
@Override
public void handle(String response, String retCode, String msg) throws HttpClientException {
logger.debug("查询一组资源使用情况信息,返回状态:" + retCode + ",返回信息:" + msg);
provider[0] = JSONObject.parseObject(response);
System.out.println(provider[0].get("result").toString()+"rrrrrrrrrrrrr");
String jsonObj = provider[0].get("result").toString();
reslt[0] =jsonObj;
if (jsonObj == null)
return;
}
});
} catch (HttpClientException e) {
e.printStackTrace();
}
if(reslt[0].equals("0")){
throw new ManoException("0","没建立与openstack的连接,请检查openstack资源中openstack提供者是否已添加");
}else{
throw new ManoException("1","没有数据");
}
//throw new HttpClientException("没建立连接");
}
}});
} catch (HttpClientException e) {
throw new ManoException("1","没建立连接");
}
logger.info("SummeryOfResourcesVO is " + vo.toString());
return vo;
}
客户端 4:
@Override
public String saveEventNameId(String id, String name) {
String ret = "";
try {
logger.info("开始记录日志");
String url = ConfigFileLoad.getConfContent("NFVO_IP") + "/rest/logs/EventId";
// url = "http://172.16.25.138:9090/nfvo/rest/logs/generation";
HttpRestClientRequest hr = new HttpRestClientRequest(url);
hr.addParam("Event-Id", id);
hr.addParam("Event-Name", formatStr(name));
ret = hr.postRequest();
} catch (Exception e) {
logger.info("记录日志失败" + ret);
e.printStackTrace();
}
return ret;
}
客户端4对应的工具类:
package com.certus.util.httpClient;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.certus.util.CommonUtil;
/**
* @ClassName 类 名 称: HttpRestClientRequest.java
* @Description 功能描述: 调用rest接口的客户端
* @author 创 建 者: <A HREF="wanglz@certusnet.com.cn">wanglz</A>
* @date 创建日期: 2015年4月2日下午4:28:04
*/
public class HttpRestClientRequest {
private String url;
private Map<String, Object> paramMap = new HashMap<String, Object>();
public static final String APPLICATION_JSON_UTF_8 = MediaType.APPLICATION_JSON + "; " + MediaType.CHARSET_PARAMETER + "=UTF-8";
public HttpRestClientRequest(String url) {
this.url = url;
}
public void addParam(String key, Object value) {
this.paramMap.put(key, value);
}
public String postRequest() {
String token = CommonUtil.getAuthToken();
String message = "";
try {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
if (!paramMap.isEmpty()) {
paramMap.keySet().iterator();
for (Iterator<String> iter = paramMap.keySet().iterator(); iter.hasNext();) {
String key = iter.next();
target = target.queryParam(key, paramMap.get(key));
}
}
Entity<String> entity = Entity.entity("Test", MediaType.APPLICATION_JSON_TYPE);
Response response = target.request().header("X-Auth-Token", token).buildPost(entity).invoke();
int code = response.getStatus();
message = response.readEntity(String.class);
response.close();
/* System.out.println(code);
System.out.println(message);*/
} catch (Exception e) {
e.printStackTrace();
}
return message;
}
}
////////////////用的jar包
javax.ws.rs-api-2.0.1.jar
<servlet>
<servlet-name>RESTEntrance</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.certusnet.nfv.mano.vnfm.RestApplication</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>RESTEntrance</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
////新增的接口
package com.certusnet.nfv.mano.vim.vm.rest;
import java.awt.List;
import java.util.Iterator;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import com.certusnet.nfv.mano.exception.ManoException;
import com.certusnet.nfv.mano.rest.ContentType;
import com.certusnet.nfv.mano.vim.ExceptionCode;
import com.certusnet.nfv.mano.vim.HttpsUtil;
import com.certusnet.nfv.mano.vim.network.rest.NetworkRest;
import com.certusnet.nfv.mano.vim.network.service.INetworkService;
import com.certusnet.nfv.mano.vim.vm.rsclient.IVmRsClient;
import com.certusnet.nfv.mano.vim.vm.rsclient.impl.VmRsClient;
import javax.ws.rs.FormParam;
@Component
@Path("/")
public class VmRest {
private static Logger logger = Logger.getLogger(VmRest.class);
@Autowired
// private IVmRsClient vmRsClient = new VmRsClient();
private IVmRsClient vmRsClient;
//访问的时候用url建立客户端,之后,直接通过get标注获取标注中写接收response的类即可
@GET
@Path("vdus")
@Produces(ContentType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.TEXT_PLAIN)
public JSONArray findVmList(@HeaderParam("X-Auth-Token") String token) {
logger.info("findVmList-X-Auth-Token=" + token);
try {
String returnStr = vmRsClient.findVmList(token);
logger.debug("find-vm-list-returnstr=" + returnStr);
returnStr = returnStr.replace("null", "\"\"");
JSONObject jsonObj = JSONObject.fromObject(returnStr);
if (!"200".equalsIgnoreCase(jsonObj.getString("retCode")))
throw new ManoException(ExceptionCode.FIND_VDU_LIST_FAILED);
JSONArray vmJsonObj = jsonObj.getJSONArray("vms");
logger.info("find-vm-list-returnobj=" + vmJsonObj);
return vmJsonObj;
} catch (ManoException ex) {
throw ex;
} catch (Exception ex) {
throw new ManoException(ExceptionCode.FIND_VDU_LIST_FAILED, ex);
}
}
@GET
@Path("vdus/{vdu_uuid}/detail")
@Produces(ContentType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.TEXT_PLAIN)
public JSONObject findVmById(@PathParam("vdu_uuid") String vm_id,@HeaderParam("X-Auth-Token") String token) {
logger.info("findVmById-X-Auth-Token=" + token);
if ((null == vm_id) || (vm_id.trim().equalsIgnoreCase(""))) {
throw new ManoException(ExceptionCode.PARAM_NEEDED_IS_NULL);
}
try {
String returnStr = vmRsClient.findVmById(vm_id,token);
logger.debug("findVmById-returnstr=" + returnStr);
returnStr = returnStr.replace("null", "\"\"");
JSONObject jsonObj = JSONObject.fromObject(returnStr);
if (!"200".equalsIgnoreCase(jsonObj.getString("retCode")) && !"404".equalsIgnoreCase(jsonObj.getString("retCode")))
throw new ManoException(ExceptionCode.FIND_VDU_FAILED);
if ("404".equalsIgnoreCase(jsonObj.getString("retCode")))
throw new ManoException(ExceptionCode.ITEM_NOT_FOUND);
logger.debug("findVmById-jsonObj = " + jsonObj);
JSONObject vmJsonObj = jsonObj.getJSONObject("vm").getJSONObject(
"server");
String flavor_id = vmJsonObj.getJSONObject("flavor")
.getString("id");
JSONObject addresses = vmJsonObj.getJSONObject("addresses");
logger.debug("findVmById-addresses = " + addresses);
String ip_addr = "";
for (Iterator iter = addresses.keys(); iter.hasNext();) {
String key = (String)iter.next();
String ip_addr_temp = addresses.getJSONArray(key).getJSONObject(0).getString("addr").trim();
if (!ip_addr_temp.equals("")) {
if (ip_addr.equals("")) {
ip_addr += ip_addr_temp;
} else {
ip_addr += "," + ip_addr_temp;
}
}
}
String returnFlavorStr = vmRsClient.findFlavorById(flavor_id);
logger.debug("findVmById-returnFlavorStr=" + returnFlavorStr);
JSONObject returnFlvorJsonObj = JSONObject
.fromObject(returnFlavorStr);
logger.debug("findVmById-flavor-returnJsonObj=" + returnFlvorJsonObj);
JSONObject flavorJsonObj = returnFlvorJsonObj
.getJSONObject("flavor");
int cpu_number = flavorJsonObj.getInt("vcpus");
Double memory_size = ((Double) (flavorJsonObj.getInt("ram") * 1.0)) / 1024;
int disk_size = flavorJsonObj.getInt("disk");
JSONObject returnJsonObj = new JSONObject();
returnJsonObj.put("status", vmJsonObj.getString("status"));
returnJsonObj.put("vm_image", vmJsonObj.getJSONObject("image").getString("id"));
returnJsonObj.put("cpu_number", cpu_number);
returnJsonObj.put("memory_size", memory_size);
returnJsonObj.put("disk_size", disk_size);
returnJsonObj.put("path", "");
returnJsonObj.put("uuid",vm_id);
returnJsonObj.put("ip_addr",ip_addr);
returnJsonObj.put("name",vmJsonObj.getString("name"));
logger.info("findVmById-returnJsonObj=" + returnJsonObj);
return returnJsonObj;
} catch (ManoException ex) {
throw ex;
} catch (Exception ex) {
throw new ManoException(ExceptionCode.FIND_VDU_FAILED, ex);
}
}
@POST
@Path("vdus")
@Produces(ContentType.APPLICATION_JSON_UTF_8)
// @Consumes(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
// "application/json"
// @Consumes("application/json")
// public String createVm(@QueryParam("vdu_params") String vdu_params)
public Object createVm(@FormParam("vdu_params") String vdu_params,
@HeaderParam("X-Auth-Token") String token) throws ManoException {
logger.info("createVm-X-Auth-Token=" + token);
if ((null == token) || (token.trim().equalsIgnoreCase(""))) {
throw new ManoException(ExceptionCode.AUTH_TOKEN_IS_EMPTY);
}
logger.info("createVm-vdu_params:" + vdu_params);
if ((null == vdu_params) || (vdu_params.trim().equalsIgnoreCase(""))) {
throw new ManoException(ExceptionCode.PARAM_NEEDED_IS_NULL);
}
try {
logger.info("createVm-vdu_params:" + vdu_params);
JSONObject jsonObj = JSONObject.fromObject(vdu_params);
logger.info("tangjing-createVm-vdu_params-json:" + jsonObj.toString());
String image_id = "";
String cpu_number = "";
String mem_size = "";
String disk = "";
String network_list = "";
String user_param = "";
String seq_id = "";
String id = "";
String parent_id = "";
JSONArray networklist = new JSONArray();
JSONObject network_json = new JSONObject();
String vm_image = jsonObj.getString("vm_image");
image_id = vm_image;
int cpu_number_int = jsonObj.getInt("cpu_number");
cpu_number = "" + cpu_number_int;
double memory_size_int = jsonObj.getDouble("memory_size");
mem_size = "" + memory_size_int * 1024;
int disk_size_int = jsonObj.getInt("disk_size");
disk = "" + disk_size_int;
String user_param_from_json = jsonObj.getString("user_param");
user_param = user_param_from_json;
int seq_id_from_json = jsonObj.getInt("seq_id");
seq_id = "" + seq_id_from_json;
String id_from_json = jsonObj.getString("id");
id = id_from_json;
String parent_id_from_json = jsonObj.getString("parent_id");
parent_id = parent_id_from_json;
// String path = jsonObj.getString("vm_image");
//
// String file_content = jsonObj.getString("file_content");
JSONArray vlink_uuid_list = jsonObj.getJSONArray("vlink_uuid_list");
if ((null == vlink_uuid_list) || (vlink_uuid_list.isEmpty())) {
throw new ManoException(ExceptionCode.CREATE_VDU_FAILED);
} else {
int vlink_length = vlink_uuid_list.size();
logger.info("create-vm-vlink_length=" + vlink_length);
// System.Text.StringBuilder stringBuilder = new
// System.Text.StringBuilder();
for (int i = 0; i < vlink_length; i++) {
JSONObject tempJsonObj = vlink_uuid_list.getJSONObject(i);
JSONObject oneNetwork = new JSONObject();
String tmpStr = "";
tmpStr = tmpStr + tempJsonObj.getString("vlink_uuid");
oneNetwork.put("network_uuid", tempJsonObj.getString("vlink_uuid"));
String tempStrNetworkType = tempJsonObj
.getString("network_type");
tmpStr = tmpStr + "," + tempStrNetworkType;
oneNetwork.put("network_type", tempStrNetworkType);
tmpStr = tmpStr + ","
+ tempJsonObj.getString("service_type");
;
oneNetwork.put("service_type", tempJsonObj.getString("service_type"));
if ("E-LAN-L3".equalsIgnoreCase(tempStrNetworkType)) {
tmpStr = tmpStr + ","
+ tempJsonObj.getString("gateway_ip");
;
oneNetwork.put("gateway_ip", tempJsonObj.getString("gateway_ip"));
}
network_list = network_list + tmpStr;
if (i < vlink_length - 1) {
network_list = network_list + "/";
}
oneNetwork.put("seq_id", "" + tempJsonObj.getInt("seq_id"));
oneNetwork.put("vif_model", tempJsonObj.getString("vif_model"));
networklist.add(oneNetwork);
logger.info("create-vm-oneNetwork:" + oneNetwork);
}
}
network_json.put("network_list", networklist);
logger.info("create-vm-network_json:" + network_json);
logger.info("create-vm-network_list:" + network_list);
String scapeRestReturnStr = vmRsClient.createVm(image_id,
cpu_number, mem_size, disk,id,parent_id,seq_id,user_param, network_json.toString(),token);
JSONObject scapeJsonObj = JSONObject.fromObject(scapeRestReturnStr);
logger.info("createVm-scapeJsonObj=" + scapeJsonObj.toString());
logger.info("createVm-retCode=" + scapeJsonObj.getString("retCode"));
if (!"200".equalsIgnoreCase(scapeJsonObj.getString("retCode")))
throw new ManoException(ExceptionCode.CREATE_VDU_FAILED);
JSONObject returnJsonObj = new JSONObject();
returnJsonObj.put("uuid", scapeJsonObj.getString("id"));
return returnJsonObj;
} catch (ManoException ex) {
throw ex;
} catch (Exception ex) {
logger.error("createVm-ex:" + ex);
throw new ManoException(ExceptionCode.CREATE_VDU_FAILED, ex);
}
}
@DELETE
@Path("vdus/{vdu_uuid}")
@Produces(ContentType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.TEXT_PLAIN)
public String deleteVm(@PathParam("vdu_uuid") String vm_id,
@HeaderParam("X-Auth-Token") String token) throws ManoException {
logger.info("deleteVm-X-Auth-Token=" + token);
if ((null == token) || (token.trim().equalsIgnoreCase(""))) {
throw new ManoException(ExceptionCode.AUTH_TOKEN_IS_EMPTY);
}
logger.info("deleteVm-vdu_uuid:" + vm_id);
if ((null == vm_id) || (vm_id.trim().equalsIgnoreCase(""))) {
throw new ManoException(ExceptionCode.PARAM_NEEDED_IS_NULL);
}
try {
String returnStr = vmRsClient.deleteVm(vm_id,token);
JSONObject jsonObj = JSONObject.fromObject(returnStr);
logger.info("deleteVm-find-host-list-returnStrJsonObj=" + jsonObj);
if (!"200".equalsIgnoreCase(jsonObj.getString("retCode")) && !"404".equalsIgnoreCase(jsonObj.getString("retCode")))
throw new ManoException(ExceptionCode.DELETE_VDU_FAILED);
if ("404".equalsIgnoreCase(jsonObj.getString("retCode")))
throw new ManoException(ExceptionCode.ITEM_NOT_FOUND);
return "";
} catch (ManoException ex) {
throw ex;
} catch (Exception ex) {
throw new ManoException(ExceptionCode.DELETE_VDU_FAILED, ex);
}
}
//不能放在main方法中,否则没有实例可以创建,这个可以用单元测试@junite
public static void main(String[] args) {
VmRest vm = new VmRest();
// String image_id = "307e56ea-f500-4c1f-a5b8-8a43cb8d1e83";
// String cpu_number = "1";
// String mem_size = "512";
// String disk = "1";
// String network_list= "71d9ca38-bb8e-4384-873b-82985bcfb7f0,L2,data";
//vm.findVmList();
vm.findVmById("b5a74a90-011c-43f9-87a1-c33c1901f386", "123");
// vm.findVmById("15afdb66-e607-43c4-b7c4-589fe0218c6a");
// vm.createVm(image_id, cpu_number, mem_size, disk, network_list);
// vm.deleteVm("cd171a62-ce10-47be-9dad-ddebbc27908c");
}
}
////注册新增的接口
package com.certusnet.nfv.mano.vim;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.web.filter.RequestContextFilter;
import com.certusnet.nfv.mano.rest.ManoExceptionMapper;
import com.certusnet.nfv.mano.rest.RestResponseFilter;
import com.certusnet.nfv.mano.vim.host.rest.HostRest;
import com.certusnet.nfv.mano.vim.alarm.rest.AlarmRest;
import com.certusnet.nfv.mano.vim.cpu_utilization_history.rest.Cpu_utilization_historyRest;
import com.certusnet.nfv.mano.vim.network.rest.NetworkRest;
import com.certusnet.nfv.mano.vim.port.rest.PortRest;
import com.certusnet.nfv.mano.vim.providernet.rest.ProvidernetRest;
import com.certusnet.nfv.mano.vim.usage_history.rest.Usage_historyRest;
import com.certusnet.nfv.mano.vim.vm.rest.VmRest;
import com.certusnet.nfv.mano.vim.vnf.rest.HelloNfvRest;
public class RestApplication extends ResourceConfig {
/**
* Register JAX-RS application components.
*/
public RestApplication () {
register(RequestContextFilter.class);
register(HelloNfvRest.class);
register(VmRest.class);
register(Usage_historyRest.class);
register(Cpu_utilization_historyRest.class);
register(ProvidernetRest.class);
register(ManoExceptionMapper.class);
register(RestResponseFilter.class);
register(NetworkRest.class);
register(HostRest.class);
register(AlarmRest.class);
register(PortRest.class);
}
}
//客户端
package com.certusnet.nfv.mano.nfvo.vnfr.rsclient.impl;
import org.apache.log4j.Logger;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import org.springframework.util.StringUtils;
import com.certusnet.nfv.mano.common.pojo.VDUDetailResp;
import com.certusnet.nfv.mano.common.pojo.VDUDetailResult;
import com.certusnet.nfv.mano.common.pojo.VduVm;
import com.certusnet.nfv.mano.exception.ManoException;
import com.certusnet.nfv.mano.nfvo.vnfr.pojo.VduQueryResp;
import com.certusnet.nfv.mano.nfvo.vnfr.rsclient.IVduRsClient;
import com.certusnet.nfv.mano.rest.ContentType;
import com.certusnet.nfv.mano.rest.RestResultCode;
import com.certusnet.nfv.mano.rsclient.RsClient;
//用注入的方式获取vimRestRootUrl
//<bean id="vimRsClient"
//class="com.certusnet.nfv.mano.vnfm.vnfr.vimrestclient.VimRestClient">
// <property name="vimRestRootUrl" value="${VIM_REST_ROOT_URL}" />
//</bean>
public class VduRsClient extends RsClient implements IVduRsClient {
private static final String VDU_URL = "vdus";
private static Logger logger = Logger.getLogger(VduRsClient.class);
@Override
public VDUDetailResult queryVDUDetail(String uuid) {
if(StringUtils.isEmpty(uuid))
{
return null;
}
Client client = getClient();
WebTarget webTarget = client.target(vimRestRootUrl).path(VDU_URL)
.path(uuid).path("detail");
Invocation.Builder invocationBuilder = webTarget
.request(ContentType.APPLICATION_JSON_UTF_8);
VDUDetailResp resp = invocationBuilder.get(VDUDetailResp.class);
if (!"ok".equals(resp.getRetCode().trim())) {
if(RestResultCode.ITEM_NOT_FOUND.equals(resp.getRetCode()))
{
logger.error(resp.getRetCode() + ":" + resp.getMsg());
return null;
}
else
{
throw new ManoException(resp.getRetCode(), resp.getMsg());
}
}
return resp.getResult();
}
@Override
public VduVm findVduVm(String vduUUID) {
if(StringUtils.isEmpty(vduUUID))
{
return null;
}
Client client = getClient();
WebTarget webTarget = client.target(vimRestRootUrl).path(VDU_URL)
.path(vduUUID).path("detail");
Invocation.Builder invocationBuilder = webTarget
.request(ContentType.APPLICATION_JSON_UTF_8);
VduQueryResp resp = invocationBuilder.get(VduQueryResp.class);
if (!resp.getRetCode().equals("ok")) {
if(RestResultCode.ITEM_NOT_FOUND.equals(resp.getRetCode()))
{
logger.error(resp.getRetCode() + ":" + resp.getMsg());
return null;
}
else
{
throw new ManoException(resp.getRetCode(), resp.getMsg());
}
}
return resp.getResult();
}
}
//客户端2(框架本身)
package com.certusnet.nfv.mano.nfvo.vnfr.rsclient.impl;
import javax.annotation.Resource;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.certusnet.nfv.mano.common.pojo.RestResultResp;
import com.certusnet.nfv.mano.exception.ManoException;
import com.certusnet.nfv.mano.rest.ContentType;
import com.certusnet.nfv.mano.rest.RestResultCode;
import com.certusnet.nfv.mano.rsclient.RsClient;
import com.certusnet.nfv.mano.vnfm.token.RestToken;
//访问的时候用url建立客户端,之后,直接通过get标注获取标注中写接收response的类即可
@Component
public class VnfmRsClient extends RsClient {
private Logger logger = Logger.getLogger(VnfmRsClient.class);
private static final String VNFM_URL = "vnfrs";
@Resource
private RestToken restToken;
public void deleteVNFR(Long vnfrId) {
Client client = getClient();
WebTarget webTarget = client.target(vnfmRestRootUrl).path(VNFM_URL)
.path(String.valueOf(vnfrId));
Invocation.Builder invocationBuilder = webTarget.request(
ContentType.APPLICATION_JSON_UTF_8).header(RestToken.key,
restToken.getToken());
RestResultResp resp = invocationBuilder.delete(RestResultResp.class);
if (!RestResultCode.OK.equals(resp.getRetCode().trim())
&& !RestResultCode.ITEM_NOT_FOUND.equals(resp.getRetCode()
.trim())) {
logger.error("Request VNFM RESTful for deleteVNFR, the response msg is : "
+ resp.getMsg());
throw new ManoException(resp.getRetCode(), resp.getMsg());
}
}
public void deleteVLByVNFRId(Long vnfrId) {
Client client = getClient();
WebTarget webTarget = client.target(vnfmRestRootUrl).path(VNFM_URL)
.path(String.valueOf(vnfrId)).path("vlrs");
Invocation.Builder invocationBuilder = webTarget.request(
ContentType.APPLICATION_JSON_UTF_8).header(RestToken.key,
restToken.getToken());
RestResultResp resp = invocationBuilder.delete(RestResultResp.class);////与结果集对应字段的类
if (!RestResultCode.OK.equals(resp.getRetCode().trim())
&& !RestResultCode.ITEM_NOT_FOUND.equals(resp.getRetCode()
.trim())) {
logger.error("Request VNFM RESTful for deleteVLByVNFRId, the response msg is : "
+ resp.getMsg());
throw new ManoException(resp.getRetCode(), resp.getMsg());
}
}
}
//客户端 3 (要用到工具类)
public SummeryOfResourcesVO getSummeryOfResource() {
logger.info("查询一组资源使用情况(云主机、虚拟内核、虚拟内存、安全组)信息");
final SummeryOfResourcesVO vo = new SummeryOfResourcesVO();
final JSONObject[] provider = new JSONObject[1];
final String[] reslt= new String[1];
/**取资源使用情况*/
HttpClientRequest request = new HttpClientGetRequest(ConfigFileLoad.getConfContent("API_IP") + "/rest/resource_used");
try {
request.process(new HttpClientResponseHandler() {
@Override
public void handle(String response, String retCode, String msg) throws HttpClientException,ManoException {
logger.debug("查询一组资源使用情况信息,返回状态:" + retCode + ",返回信息:" + msg);
JSONObject obj = JSONObject.parseObject(response);
if(obj.get("result")!=null){
System.out.println(obj.get("result").toString());
JSONObject jsonObj = JSONObject.parseObject(obj.get("result").toString());
if (jsonObj == null){
//&&!reslt[0].equals("0")
return;
}
// 一 、请求并计算 云主机信息
Integer vms = jsonObj.getInteger(Constants.OverView.VMS);
Integer used_vms = jsonObj.getInteger(Constants.OverView.USED_VMS);
Integer unused_vms = 0;
if (vms == null || vms.equals("")) {
vms = 0;
} else if (used_vms == null || used_vms.equals("")) {
used_vms = 0;
} else {
unused_vms = vms - used_vms;
}
vo.setCloudPlatformAll(String.valueOf(vms));
vo.setCloudPlatformUsed(String.valueOf(used_vms));
vo.setCloudPlatformUnUsed(String.valueOf(unused_vms));
// 二 、请求 虚拟内核
Integer cpus = jsonObj.getInteger(Constants.OverView.CPUS);
Integer used_cpus = jsonObj.getInteger(Constants.OverView.USED_CPUS);
Integer unused_cpus = 0;
if (cpus == null || cpus.equals("")) {
cpus = 0;
} else if (used_cpus == null || used_cpus.equals("")) {
used_cpus = 0;
} else {
unused_cpus = cpus - used_cpus;
}
vo.setVirtualKernelAll(String.valueOf(cpus));
vo.setVirtualKernelUsed(String.valueOf(used_cpus));
vo.setVirtualKernelUnUsed(String.valueOf(unused_cpus));
// 三、请求 虚拟内存
Integer mems = jsonObj.getInteger(Constants.OverView.MEMS);
Integer used_mem = jsonObj.getInteger(Constants.OverView.USED_MEM);
Integer unused_mem = 0;
if (mems == null || mems.equals("")) {
mems = 0;
} else if (used_mem == null || used_mem.equals("")) {
used_mem = 0;
} else {
unused_mem = mems - used_mem;
}
vo.setVirtualMemoryAll(String.valueOf(mems));
vo.setVirtualMemoryUsed(String.valueOf(used_mem));
vo.setVirtualMemoryUnUsed(String.valueOf(unused_mem));
// 四、请求 安全组
Integer security_group = jsonObj.getInteger(Constants.OverView.SECURITY_GROUP);
Integer used_security_group = jsonObj.getInteger(Constants.OverView.USED_SECURITY_GROUP);
Integer unused_security_group = 0;
if (security_group == null || security_group.equals("")) {
security_group = 0;
} else if (used_security_group == null || used_security_group.equals("")) {
used_security_group = 0;
} else {
unused_security_group = security_group - used_security_group;
}
vo.setSecurityGroupAll(String.valueOf(security_group));
vo.setSecurityGroupUsed(String.valueOf(used_security_group));
vo.setSecurityGroupUnUsed(String.valueOf(unused_security_group));
}else{
/**provider连接数*/
HttpClientRequest requestProvider = new HttpClientGetRequest(ConfigFileLoad.getConfContent("API_IP") + "/rest/provider_network_cn");
try {
requestProvider.process(new HttpClientResponseHandler() {
@Override
public void handle(String response, String retCode, String msg) throws HttpClientException {
logger.debug("查询一组资源使用情况信息,返回状态:" + retCode + ",返回信息:" + msg);
provider[0] = JSONObject.parseObject(response);
System.out.println(provider[0].get("result").toString()+"rrrrrrrrrrrrr");
String jsonObj = provider[0].get("result").toString();
reslt[0] =jsonObj;
if (jsonObj == null)
return;
}
});
} catch (HttpClientException e) {
e.printStackTrace();
}
if(reslt[0].equals("0")){
throw new ManoException("0","没建立与openstack的连接,请检查openstack资源中openstack提供者是否已添加");
}else{
throw new ManoException("1","没有数据");
}
//throw new HttpClientException("没建立连接");
}
}});
} catch (HttpClientException e) {
throw new ManoException("1","没建立连接");
}
logger.info("SummeryOfResourcesVO is " + vo.toString());
return vo;
}
客户端 4:
@Override
public String saveEventNameId(String id, String name) {
String ret = "";
try {
logger.info("开始记录日志");
String url = ConfigFileLoad.getConfContent("NFVO_IP") + "/rest/logs/EventId";
// url = "http://172.16.25.138:9090/nfvo/rest/logs/generation";
HttpRestClientRequest hr = new HttpRestClientRequest(url);
hr.addParam("Event-Id", id);
hr.addParam("Event-Name", formatStr(name));
ret = hr.postRequest();
} catch (Exception e) {
logger.info("记录日志失败" + ret);
e.printStackTrace();
}
return ret;
}
客户端4对应的工具类:
package com.certus.util.httpClient;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.certus.util.CommonUtil;
/**
* @ClassName 类 名 称: HttpRestClientRequest.java
* @Description 功能描述: 调用rest接口的客户端
* @author 创 建 者: <A HREF="wanglz@certusnet.com.cn">wanglz</A>
* @date 创建日期: 2015年4月2日下午4:28:04
*/
public class HttpRestClientRequest {
private String url;
private Map<String, Object> paramMap = new HashMap<String, Object>();
public static final String APPLICATION_JSON_UTF_8 = MediaType.APPLICATION_JSON + "; " + MediaType.CHARSET_PARAMETER + "=UTF-8";
public HttpRestClientRequest(String url) {
this.url = url;
}
public void addParam(String key, Object value) {
this.paramMap.put(key, value);
}
public String postRequest() {
String token = CommonUtil.getAuthToken();
String message = "";
try {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
if (!paramMap.isEmpty()) {
paramMap.keySet().iterator();
for (Iterator<String> iter = paramMap.keySet().iterator(); iter.hasNext();) {
String key = iter.next();
target = target.queryParam(key, paramMap.get(key));
}
}
Entity<String> entity = Entity.entity("Test", MediaType.APPLICATION_JSON_TYPE);
Response response = target.request().header("X-Auth-Token", token).buildPost(entity).invoke();
int code = response.getStatus();
message = response.readEntity(String.class);
response.close();
/* System.out.println(code);
System.out.println(message);*/
} catch (Exception e) {
e.printStackTrace();
}
return message;
}
}
////////////////用的jar包
javax.ws.rs-api-2.0.1.jar
发表评论
-
rest路径形式相同的话,通过@GET @DELETE 区别
2015-05-18 14:17 1516通过位置对应接收参数,如果rest路径形式相同的话,通过@GE ... -
rest 调用有参数接口
2015-05-06 17:22 3002//有参数rest,调用客户端 OperateLogSer ... -
rest 应用demo 3 客户端的另一中方式
2015-04-30 14:53 906//rest接口访问地址特征 API_IP = http:// ... -
rest 应用demo 2
2015-04-30 14:48 1194web.xml <servlet> < ... -
rest
2015-04-14 14:18 824http://blog.sina.com.cn/s/blog_ ...
相关推荐
1、使用Rest SDK及Demo需要先获得帐号及应用信息,并使用这些信息完成SDK初始化操作, 主帐号可以从开发者控制台获取,应用ID和子帐号可以使用测试Demo应用及其配套的子帐号, 也可以自建应用及子帐号。 2、测试...
Spring休息演示在此示例代码演示中,如何使用[Jackson Databind]( )使用Spring将信息从Rest-Client传递到Rest-Web...testapi / helloapp-显示Hello应用/ spring-rest-demo / api / rules-显示json数据当Tomcat服
通过运行,服务器主要是用于插入和列出框架的REST api。 所有逻辑都在客户端中运行。 该逻辑通过spock测试在groovy中完成,并通过转换为javascript。 使用require.js加载所有JavaScript内容。 创建创意项目: ./...
Spring-Data-JPA-Rest-DemoApp 如何减少REST API中的样板代码:Spring Data REST'。 在Spring Data REST概念中,我们甚至不必编写RestController及其方法。 Spring Data REST依赖项将使用HATEOAS(超文本作为应用...
BBDN-REST-Demo-CSharp 该项目包含用于与C#中的Blackboard Learn REST Web服务进行交互的示例代码。 此示例是针对.NET Framework 4.7.2在Microsoft Visual Studio Community 2019中构建的。 它使用HttpClient和...
在此存储库中尝试代码的最简单方法是通过自述文件中针对主要rest-demo项目的docker-compose方法: 要专门请求此前端,请确保docker-compose命令的前缀为FRONTEND=react ,如下所示: > FRONTEND=react d
rest client全套封装好的java调用elasticsearch功能的工程demo,亲测可用。我安装的es是elasticsearch-7.10.0版本,测试好用。直接用idea打开工程就可以使用,并且有写好的junit测试类,可供测试。可以直接拿来做应用...
aREST-演示 使用 WiFi、蓝牙和 XBee 模块的 aREST 库演示。...接口:使用 aREST 库控制 WiFi 模块、蓝牙模块和 XBee 模块的简单 Web 应用程序的代码。 您可以在 Open Home Automation 网站上找到该文章:
NULL 博文链接:https://flyqantas.iteye.com/blog/2191032
这是一个 symfony 标准版应用程序,使用和来显示创建简单的 REST api 很容易。 有关更多信息,请参阅捆绑包的文档。 如果您想查看它的实际效果,此应用程序已部署到 。 数据库每分钟重置一次。 或者自己试试... ...
春天休息演示这是基本的Spring REST应用程序,它将返回学生列表。 已经为Spring使用了基于注释的配置。
要求PHP 5.2 或更高版本CodeIgniter 2.1.0 到 3.0-dev 注意:对于 1.7.x 支持,从下载选项卡下载 v2.2安装将application/libraries/Format.php和application/libraries/REST_Controller.php文件拖放到应用程序的目录...
这是一个演示 REST API,用于在类似 CRM 的 Web 应用程序中管理客户的联系信息。 它实现了“CRUD”方法,以及一种检测可能重复客户的方法,因此可以合并他们的联系人。 蜜蜂 所有 API 都在客户的 JSON 模型上运行,...
Spring Boot REST应用程序+带有JWT的Spring Security 一个用于测试RESTful应用程序的Spring Security和JWT的演示 用法 要登录,请在'/ login'处将以下代码添加到GET请求的正文中: {"username":"user","password":...
link-rest-cms-demo 一个简单的JAX RS项目,展示了框架的使用 需要Java 1.8或更高版本 需要Servlet 3.1容器(尽管可能在3.0上可用) 如果要基于此示例构建真实的应用程序,请先在GitHub上克隆项目,然后进行以下...
这是 OpenIOU 移动应用程序的演示应用程序。 ![Codeship 状态] ( )
microservices-jooby-demo1:Jooby的Java microframework对REST的Web应用程序
使用Spring WebFlux和Reactive MongoDB构建Reactive Rest API ... 该应用程序定义以下REST API 1. GET /tweets - Get All Tweets 2. POST /tweets - Create a new Tweet 3. GET /tweets/{id} - Retrieve a Tweet
服务器应用程序的 REST 服务器部分具有三个资源用户广告图片我将使用 CURL 演示典型的流程,然后由 MVC 客户端开发人员使用它来输入来自浏览器的 XHR 请求。 请注意,Windows 用户应安装因为本机 Windows 中的 curl ...
该应用程序应该用作演示和展示,以了解如何使用 TYPO3 Flow 来提供 REST API - 以及如何从 Angular.js 使用/使用该 API。 只需查看源代码即可了解它是如何连接在一起的。怎么走? 未经测试,让我知道它是否有效克隆...