`
y806839048
  • 浏览: 1121561 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

rest 应用demo

    博客分类:
  • rest
阅读更多
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
分享到:
评论

相关推荐

    REST api demo

    这个"REST api demo"项目提供了学习和实践REST API设计和实现的一个基础平台,对于理解如何将这些技术结合使用以构建现代Web服务非常有帮助。通过深入研究和扩展这个项目,开发者可以更好地掌握RESTful API设计原则...

    云通讯CCP_REST_DEMO_Python_v2.7r.zip

    "云通讯CCP_REST_DEMO_Python_v2.7r.zip"是容联云通讯为Python开发者量身定制的一个版本为2.7的SDK,它通过RESTful API接口封装了多项功能,使得Python开发者能够更便捷地调用这些接口,实现高效的应用开发。...

    rest webservice demo spring

    本示例"rest webservice demo spring"是一个使用Spring框架实现的RESTful Web服务的演示项目。Spring是Java领域的一个开源框架,特别适合于构建企业级应用,它提供了全面的编程和配置模型,包括对REST的支持。 1. *...

    CCP_REST_DEMO_PHP_v2.7r.zip_Ccp rest 请求_DEMO_breathl77_php短信验证码通

    1、使用Rest SDK及Demo需要先获得帐号及应用信息,并使用这些信息完成SDK初始化操作, 主帐号可以从开发者控制台获取,应用ID和子帐号可以使用测试Demo应用及其配套的子帐号, 也可以自建应用及子帐号。 2、测试...

    spring mvc rest基础学习demo

    在"spring mvc rest基础学习demo"中,我们将深入探讨如何使用Spring MVC构建RESTful API。 REST(Representational State Transfer,表现层状态转移)是一种网络应用程序的设计风格和开发方式,基于HTTP协议,以...

    Spring MVC REST Demo

    Spring MVC 是一个强大的Java框架,用于构建Web应用程序,而REST(Representational State Transfer)是一种软件架构风格,常用于创建Web服务。"Spring MVC REST Demo"是一个示例项目,旨在展示如何在Spring MVC框架...

    基于dubbo的rest注册demo

    REST(Representational State Transfer)是一种网络应用程序的设计风格和开发方式,它基于HTTP协议,使得API更加简洁、易用。将REST与Dubbo结合,可以实现更灵活、更易于集成的服务调用方式。本示例是关于如何在...

    rest_demo.zip

    【标题】"rest_demo.zip" 是一个包含RESTful API开发示例的压缩文件,它基于Spring Boot框架构建,旨在提供一个快速理解REST API开发的简易平台。REST(Representational State Transfer)是一种网络应用程序的设计...

    Jquery+JSON+REST WCF DEMO

    **jQuery + JSON + REST WCF DEMO 知识点详解** 在IT行业中,开发Web应用程序时,经常会使用到jQuery、JSON、RESTful API以及WCF(Windows Communication Foundation)等技术。"Jquery+JSON+REST WCF DEMO"是一个...

    SPRING-MVC-MQ-CXF-REST_Demo

    "SPRING-MVC-MQ-CXF-REST_Demo"这个项目很可能是用来演示如何在同一个应用中整合Spring MVC、MQ、CXF和REST技术。项目可能包含了以下部分: 1. Spring MVC配置:展示了如何设置DispatcherServlet、视图解析器以及...

    spring cxf rest demo

    【Spring CXF REST Demo】项目是一个使用Maven构建的Java应用程序,它展示了如何将Spring框架与Apache CXF集成,以创建RESTful风格的服务。在这个项目中,开发者可以学习到如何利用CXF作为服务端的REST服务提供者,...

    rest webservice demo

    在这个“rest webservice demo”中,我们将会探讨如何使用Java来快速实现一个RESTful Web服务。 Java中实现REST服务最常用的框架是JAX-RS,它提供了一套标准API,使得开发者可以方便地创建RESTful接口。JAX-RS的...

    Spring-Rest-Demo

    Spring休息演示在此示例代码演示中,如何使用[Jackson Databind]( )使用Spring将信息从Rest-Client传递到Rest-Web...testapi / helloapp-显示Hello应用/ spring-rest-demo / api / rules-显示json数据当Tomcat服

    spring+mybatis+rest全注解demo

    【标题】"Spring+Mybatis+REST全注解Demo"是一个综合性的开发示例,它展示了如何使用Spring框架、Mybatis持久层框架以及RESTful API设计原则,通过注解方式来构建一个完整的Java应用程序。这个Demo旨在帮助开发者...

    Springboot data jpa + springboot data rest demo

    本文将深入探讨这两个技术,并结合一个实际的Demo来解释它们的工作原理和如何在项目中应用。 首先,SpringBoot Data JPA是Spring Data项目的一部分,它简化了Java Persistence API (JPA) 的使用。JPA是Java平台上的...

    activiti+springMVC+mybatis rest风格整合demo

    在本项目"activiti+springMVC+mybatis rest风格整合demo"中,开发者通过集成Activiti、Spring MVC和MyBatis三个核心组件,构建了一个基于RESTful API的工作流管理系统。这个项目对于初学者来说是一个很好的学习资源...

    CXF-REST搭建WebService服务端demo

    本示例将详细讲解如何使用Spring、Apache CXF和Maven来创建一个基于REST的WebService服务端Demo。 首先,让我们理解这些关键组件的作用: 1. **Spring**:这是一个全面的开发框架,用于构建Java应用程序,特别是...

    springboot-rest-demo

    通过运行,服务器主要是用于插入和列出框架的REST api。 所有逻辑都在客户端中运行。 该逻辑通过spock测试在groovy中完成,并通过转换为javascript。 使用require.js加载所有JavaScript内容。 创建创意项目: ./...

    重写Django REST framework源码demo

    在"basic_data_api"这个项目中,你可能已经在实践中应用了上述的一些技术。通过重写源码,你可以使Django REST framework完全适应你的业务需求,提供更加个性化的API服务。这不仅能提高代码的可维护性,也能提升用户...

    KEPServerEX IoT Gateway REST and MQTT Client Agent Demo with Node-RED.docx

    KEPServerEX IoT Gateway REST and MQTT Client Agent Demo with Node-RED KEPServerEX IoT Gateway 是一个强大的工业物联网网关,能够将工业设备连接到云端和企业系统。这个网关支持多种工业协议和数据格式,能够...

Global site tag (gtag.js) - Google Analytics