Commit c764f986 authored by jthu's avatar jthu

重新添加路径计算module群

parent 3c6c46d5
...@@ -3,8 +3,8 @@ ...@@ -3,8 +3,8 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <parent>
<artifactId>cnf</artifactId>
<groupId>top.ninwoo</groupId> <groupId>top.ninwoo</groupId>
<artifactId>cnf</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<relativePath>../../../pom.xml</relativePath> <relativePath>../../../pom.xml</relativePath>
</parent> </parent>
......
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>cnf-pathComp-app</artifactId>
<groupId>top.ninwoo</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>app-docker-api</artifactId>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package top.ninwoo.api;
import lombok.Data;
import java.io.Serializable;
import java.util.concurrent.ConcurrentHashMap;
/**
* 路径计算数据包
*/
@Data
public class CnfData implements Serializable {
//加入任务表:ConcurrentHashMap<卫星名字,功能函数名>
private ConcurrentHashMap<String,String> taskTable = new ConcurrentHashMap<>();
//加入路径表:String[]
private String[] pathTable = new String[]{};
//全局路由表:String[][]
private String[][] route = new String[][]{};
//IP池
//sataName:sataIP
private ConcurrentHashMap<String,String> IpPool = new ConcurrentHashMap<>();
//加权路径路由表
double[][] lt;
//本机卫星名
private String currentSataHop;
//下一跳卫星名
private String nextSataHop;
//下一跳ip地址
private String nextIPHop;
//该条路径的目的卫星名
private String destinSataHop;
//图像
private Picture picture;
//终节点
private String endSateHop;
//源节点
private String oriSateHop;
}
package top.ninwoo.api;
import lombok.Data;
import java.io.Serializable;
/**
* 传输图片数据
*/
@Data
public class Picture implements Serializable {
// 图片名
private String PicId;
//切片的id,唯一且有顺序要求
private String sliceId = "0";
//切片数目
private int sliceNum = 1;
//图片数据
private byte[] data;
}
package top.ninwoo.api;
import lombok.Data;
import java.util.concurrent.ConcurrentHashMap;
@Data
public class TacticsCtl {
//发出信令的卫星节点
String sate;
//当前卫星节点
String currentHop;
//加权路径路由表
double[][] lt;
//返回的路径
ConcurrentHashMap<String, Double> sateMap;
//ipool
ConcurrentHashMap<String,String> IpPool = new ConcurrentHashMap<>();
//路由表
private String[][] route = new String[][]{};
//扩散等级
int level = 1;
}
package top.ninwoo.api;
import lombok.Data;
@Data
public class sendConf {
/**
* 时延等其他参数,未在考虑范围之内
*/
private int delay;
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>cnf-pathComp-app</artifactId>
<groupId>top.ninwoo</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>app-docker-cloud</artifactId>
<dependencies>
<dependency>
<groupId>top.ninwoo</groupId>
<artifactId>app-docker-api</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.3.7.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package top.ninwoo.cloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
public class CnfEarthApp {
public static void main(String[] args) {
SpringApplication.run(CnfEarthApp.class, args);
}
}
package top.ninwoo.cloud.config;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestConfig {
private ApplicationContext applicationContext = null;
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(20000);
factory.setConnectTimeout(20000);
return factory;
}
}
package top.ninwoo.cloud.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import top.ninwoo.api.CnfData;
import top.ninwoo.api.Picture;
import top.ninwoo.cloud.service.cpcTrans.CpcTrans;
import top.ninwoo.cloud.service.dbctrans.DbcTrans;
import top.ninwoo.cloud.service.findService.FindServiceImpl;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.io.*;
import java.text.ParseException;
import java.util.LinkedList;
import java.util.concurrent.ConcurrentHashMap;
@Controller
public class DataCtrl {
@Autowired
CpcTrans cpcTrans;
@Autowired
DbcTrans dbcTrans;
@Resource
private RestTemplate restTemplate;
@RequestMapping(value = "/cpcTrans",method = RequestMethod.GET)
public String upload() {
return "cpcTrans";
}
@RequestMapping(value = "/cpcTrans")
@ResponseBody
public String CpcTrans(@RequestParam("file") MultipartFile file, @RequestParam("fileId") String fileId) {
if(!file.isEmpty()){
try {
//包装图片
Picture picture = cpcTrans.packagePic(ImageIO.read(file.getInputStream()), fileId);
//包装数据包
LinkedList<CnfData> cnfData = cpcTrans.packageData(picture);
//发送
for (CnfData data : cnfData) {
cpcTrans.sendData(data, data.getNextIPHop());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
return "上传失败," + e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "上传失败," + e.getMessage();
} catch (ParseException e) {
e.printStackTrace();
}
return "上传成功!";
} else {
return "上传失败,因为文件是空的.";
}
}
@PostMapping(value = "/dbcTrans")
@ResponseBody
public String DbcTrans(@RequestParam("file") MultipartFile file, @RequestParam("fileId") String fileId) {
if(!file.isEmpty()){
try {
//包装图片
Picture picture = dbcTrans.packagePic(ImageIO.read(file.getInputStream()), fileId);
//包装数据包
LinkedList<CnfData> cnfData = dbcTrans.packageData(picture);
//发送
for (CnfData data : cnfData) {
dbcTrans.sendData(data, data.getNextIPHop());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
return "上传失败," + e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "上传失败," + e.getMessage();
} catch (ParseException e) {
e.printStackTrace();
}
return "上传成功!";
} else {
return "上传失败,因为文件是空的.";
}
}
@GetMapping(value = "/getImg")
@ResponseBody
public String GetAllImg(){
FindServiceImpl findService = new FindServiceImpl();
ConcurrentHashMap<String, String> ipool = findService.findIPool();
for (int i = 1; i < ipool.size()+1; i++) {
String str = "sate"+i;
System.out.println(str);
String ip = ipool.get(str);
System.out.println(ip);
GetImg(str,ip);
}
return "sucess";
}
public void GetImg(String sataname, String ip){
String IP =ip + ":8083";
byte[][] res = restTemplate.getForObject("http://" + IP +"/getImg",byte[][].class);
if(res == null){
System.out.println(sataname+"no picture");
return;
}
//创建一个字节输出流
OutputStream outputStream = null;
try {
int i = 0;
for (byte[] re : res) {
//得到新路径
String path = "/home/dell/show/public/assets/cpc_images/"+sataname+"-"+i+".jpg";
outputStream = new FileOutputStream(path);
//将图片输处到流中
outputStream.write(re);
//刷新
outputStream.flush();
i++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//关闭
if (outputStream != null){
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//获取计算能力
@GetMapping("/getComputing")
@ResponseBody
public LinkedList<Double> getComputing() {
FindServiceImpl findService = new FindServiceImpl();
ConcurrentHashMap<String, String> ipool = findService.findIPool();
LinkedList<Double> cpuCom = new LinkedList<>();
for (int i = 1; i < ipool.size(); i++) {
String str = "sate"+i;
String ip = ipool.get(str);
double res = cpcTrans.sendCpuCtr(ip);
cpuCom.add(res);
}
return cpuCom;
}
//获取计算能力
@GetMapping("/download")
@ResponseBody
public String download() {
return null;
}
@GetMapping("/testCpc")
@ResponseBody
public String CpcTest() throws ParseException, IOException {
File file = new File("C:\\Users\\Elf\\Desktop\\test\\2.jpg");
Picture picture = cpcTrans.packagePic(ImageIO.read(file), "123");
//包装数据包
LinkedList<CnfData> cnfData = cpcTrans.packageData(picture);
return cpcTrans.sendData(cnfData.get(0),cnfData.get(0).getNextIPHop());
}
@GetMapping("/testDbc")
@ResponseBody
public CnfData DbcTest() throws IOException, ParseException {
File file = new File("C:\\Users\\Elf\\Desktop\\test\\2.jpg");
Picture picture = dbcTrans.packagePic(ImageIO.read(file), "123");
LinkedList<CnfData> cnfData = dbcTrans.packageData(picture, "sate3");
return cnfData.get(0);
}
@GetMapping("/test")
@ResponseBody
public CnfData Test1() throws ParseException, IOException {
File file = new File("C:\\Users\\Elf\\Desktop\\test\\1.jpg");
Picture picture = cpcTrans.packagePic(ImageIO.read(file), "123");
//包装数据包
LinkedList<CnfData> cnfData = cpcTrans.packageData(picture);
//String res = cpcTrans.sendData(cnfData.get(0),"127.0.0.1");
return cnfData.get(0);
}
@GetMapping("/testlt")
@ResponseBody
public String[][] LtTest() throws IOException, ParseException {
File file = new File("C:\\Users\\Elf\\Desktop\\test\\2.jpg");
Picture picture = dbcTrans.packagePic(ImageIO.read(file), "123");
return dbcTrans.getIt();
}
}
package top.ninwoo.cloud.service;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
public interface FindService {
/**
* 根据路径表,找到本机需要处理路径条数
* c->a ==> sata1->sata3
*/
ArrayList<String> findDestinSataHops(String[] pathTable, String currenthop);
/**
* 根据本机卫星名,全局路由表,路由表得到本机路由表
*/
String[] findRoute(String currentSataHop, String[][] routeTable);
/**
* 得到ip池
*/
ConcurrentHashMap<String,String> findIPool();
/**
* 根据目的卫星名,本机路由表找到下一跳卫星名
*/
String findNextHop(String destinSataHop, String[] route);
/**
* 找到下一跳的ip地址
* @return
*/
String findIp(String sataName, ConcurrentHashMap<String,String> ipool);
}
package top.ninwoo.cloud.service;
import top.ninwoo.api.CnfData;
import top.ninwoo.api.Picture;
import java.awt.image.BufferedImage;
import java.text.ParseException;
import java.util.LinkedList;
public interface TransService {
/**
* 打包picture
* @return picture列表
*/
Picture packagePic(BufferedImage bufferedImage, String fileId);
/**
*打包成数据包
*/
LinkedList<CnfData> packageData(Picture picture) throws ParseException;
LinkedList<CnfData> packageData(Picture picture, String satename) throws ParseException;
/**
* 发送数据包
*/
String sendData(CnfData cnfData, String url);
/**
* 发送得到cpu计算能力的指令
*/
Double sendCpuCtr(String url);
/**
* 得到稳态图
*/
String[][] getIt() throws ParseException;
}
package top.ninwoo.cloud.service.bpso;
public class InterSlotDijstraV2 {
public static void main(String[] args) {
double [][] edgeWeight = new double[][] {
{0, 96, 157, 100, MAXWEIGHT, MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT},
{371, 0, 163, MAXWEIGHT, 100,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT},
{84, 395, 0, MAXWEIGHT, MAXWEIGHT, 100,MAXWEIGHT,MAXWEIGHT,MAXWEIGHT},
{MAXWEIGHT,MAXWEIGHT,MAXWEIGHT, 0, 8, 1,100,MAXWEIGHT,MAXWEIGHT},
{MAXWEIGHT,MAXWEIGHT,MAXWEIGHT, 5, 0, 1,MAXWEIGHT,100,MAXWEIGHT},
{MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, 5, 5, 0,MAXWEIGHT,MAXWEIGHT,100},
{MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, 0, 46, 83 },
{MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, 25, 0, 55},
{MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, 35, 18, 0}};
int num = 3;
double slot = 100;
double testLatency = 0;
InterSlotDijstraV2 di = new InterSlotDijstraV2(num, slot);
di.dijstra(edgeWeight, testLatency);
}
/* //最短路矩阵
double [][] pathWeight;
//*/
//设备数目
int num;
//时隙值
double slot;
//最大权值
static final int MAXWEIGHT = 10000*1000;
public InterSlotDijstraV2( int num, double slot) {
// TODO Auto-generated constructor stub
this.num = num;
this.slot = slot;
}
//最短路径算法
public pathRecord dijstra(double [][] edgeWeight, double testLatency) {
pathRecord pathRecord = new pathRecord();
//存放上一条路径
pathRecord.lastHop = new int[edgeWeight.length][edgeWeight.length];
//存放最短路径
pathRecord.pathWeight = new double[edgeWeight.length][edgeWeight.length];
for(int i = 0; i < edgeWeight.length; i++) {
singlePointDijstra(edgeWeight, i, testLatency, pathRecord.lastHop[i], pathRecord.pathWeight[i]);
}
return pathRecord;
}
//单点最短路算法
private double[] singlePointDijstra(double[][] edgeWeight, int point, double testLatency, int [] lastHopi, double [] pathWeighti) {
//存放已求得最短路径节点
boolean [] isVisited = new boolean[edgeWeight.length];
//初始化
for(int j = 0; j < edgeWeight.length; j++) {
if(edgeWeight[point][j]!=MAXWEIGHT && edgeWeight[point][j]!=slot) {
if((edgeWeight[point][j]+testLatency) <= slot) {
pathWeighti[j] = edgeWeight[point][j] + testLatency;
}else {
pathWeighti[j] = MAXWEIGHT;
}
}else {
pathWeighti[j] = edgeWeight[point][j];
}
}
isVisited[point] = true;
//遍历所有节点
for(int j = 0; j < edgeWeight[point].length; j++) {
//遍历下一节点
int index = MAXWEIGHT;
index = nextPoint(pathWeighti, index, isVisited, edgeWeight);
if(index == MAXWEIGHT) {break;}
isVisited[index] = true;
//更新以下一节点中转的全局最短路
pathWeighti = updateSRW(edgeWeight, pathWeighti, point, index, isVisited, lastHopi);
}
return pathWeighti;
}
//遍历下一节点
private int nextPoint(double [] singleRowWeight, int index, boolean [] isVisited, double[][] edgeWeight) {
double min = 0;
for(int j = 0; j < edgeWeight.length; j++) {
if(isVisited[j] == false) {
if (singleRowWeight[j] != 0 && min == 0 && singleRowWeight[j] != MAXWEIGHT) {
min = singleRowWeight[j];
index = j;
}
if(singleRowWeight[j] < min) {
min = singleRowWeight[j];
index = j;
}
}
}
return index;
}
//更新以下一节点中转的全局最短路
private double [] updateSRW(double[][] edgeWeight, double [] singleRowWeight,
int point, int index, boolean [] isVisited, int [] lastHopi) {
double temp = singleRowWeight[index];
for(int k = 0; k < edgeWeight.length; k++) {
if(!isVisited[k]) {
if ((index + num) == k) {
if( (k/num-point/num)*slot < singleRowWeight[k]) {
singleRowWeight[k] = (k/num-point/num)*slot;
lastHopi[k] = index;
}
}else{
if((temp + edgeWeight[index][k])<= (k/num-point/num+1)*slot && (temp + edgeWeight[index][k]) < singleRowWeight[k]) {
singleRowWeight[k] = temp + edgeWeight[index][k];
lastHopi[k] = index;
}
}
}
/*else if(isVisited[k]){
lastHopi[k] = -1;
}*/
}
return singleRowWeight;
}
public static class pathRecord{
//最短路矩阵
double [][] pathWeight;
//上一跳矩阵
int [][] lastHop;
public double[][] getPathWeight(){
return pathWeight;
}
public int[][] getLastHop(){return lastHop;}
}
}
package top.ninwoo.cloud.service.bpso;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface path {
String savePath() default "/home/ninwoo/jthudocker/picResult";
String rmCmd() default "rm /home/ninwoo/jthudocker/picResult/*.jpg";
String saveCmd1() default "docker cp sate1_0:/pic/in.jpg /home/ninwoo/jthudocker/picResult/source.jpg";
String saveCmd2() default "docker cp sate1_0:/pic/out1.jpg /home/ninwoo/jthudocker/picResult/task_1.1.jpg";
String saveCmd3() default "docker cp sate1_0:/pic/out2.jpg /home/ninwoo/jthudocker/picResult/task_1.2.jpg";
String saveCmd4() default "_0:/pic/out.jpg /home/ninwoo/jthudocker/picResult/task_";
String saveCmd5() default "save pictrues to jthudocker/picResult directory finish";
// /home/ninwoo/jthudocker/picResult /home/ninwoo/dynamic_sate/picResult
}
package top.ninwoo.cloud.service.cpcTrans;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import top.ninwoo.api.CnfData;
import top.ninwoo.api.Picture;
import top.ninwoo.cloud.service.TransService;
import top.ninwoo.cloud.service.bpso.Bpso;
import top.ninwoo.cloud.service.findService.FindServiceImpl;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.concurrent.ConcurrentHashMap;
import static top.ninwoo.cloud.service.bpso.Bpso.lastHop;
@Service
public class CpcTrans implements TransService {
@Resource
private RestTemplate restTemplate;
/**
* 打包picture
*
* @return picture列表
*/
@Override
public Picture packagePic(BufferedImage bufferedImage, String fileId){
Picture picture = new Picture();
//转化为byte[]数组
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
//todo 需要增加输入图片格式
ImageIO.write(bufferedImage, "jpg", out);
} catch (IOException e) {
e.printStackTrace();
}
//设置图片数据
picture.setData(out.toByteArray());
//设置文件名
picture.setPicId(fileId);
return picture;
}
/**
* 打包成数据包
*/
@Override
public LinkedList<CnfData> packageData(Picture picture) throws ParseException {
LinkedList<CnfData> cnfDatas = new LinkedList<>();
FindServiceImpl findService = new FindServiceImpl();
//判断npe
if(picture == null){
System.out.println("出错");
return null;
}
// 输入:
//子任务依赖关系 边
int[][] link = {{0, 1, 1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6, 6, 7}};
//task编号
int[] func = {0, 2, 3, 3, 1, 1, 4, 0};
//任务表
String[] tasks = {"start/end","binaryProcess", "cutProcess", "greyProcess", "mergeProcess", "tailorProcess"};
Bpso doMap = new Bpso();
doMap.doMapApp(link,func);
//映射结果
int[] result = doMap.result;
System.out.println("optimal mapping scheme"+ Arrays.toString(result));
//路径表
String[] path = new String[link[0].length];
for (int tm = 0;tm<link[0].length;tm++){
String startHop = "sate"+result[link[0][tm]];
String endHop = "sate"+result[link[1][tm]];
if(startHop.equals("sate0")){
path[tm] = "D1" +"->"+ endHop;
continue;
}
//要修改
//todo
if(endHop.equals("sate31")){
path[tm] = startHop +"->"+ "D2";
continue;
}
//左为边起点,右为边终点
path[tm] = startHop+"->"+endHop;
}
//任务表
ConcurrentHashMap<String,String> taskTable = new ConcurrentHashMap();
for (int tm = 0;tm<result.length;tm++){
String hop = "sate"+result[tm];
if(hop.equals("sate0")){
taskTable.put("D1",tasks[func[tm]]);
continue;
}
//要修改
//todo
if(hop.equals("sate31")){
taskTable.put("D2",tasks[func[tm]]);
continue;
}
taskTable.put(hop,tasks[func[tm]]);
}
//T3路由表
String[][] route = new String[lastHop.length][lastHop[0].length];
for(int i =0;i<lastHop.length;i++){
for (int j=0;j<lastHop[0].length;j++){
route[i][j] = "sate"+(lastHop[i][j]);
if (route[i][j].equals("sate0")){
route[i][j]="sate"+(j);
}
if (route[i][j].equals("sate0")){
route[i][j]="D1";
}
//要修改
//todo
if (route[i][j].equals("sate31")){
route[i][j]="D2";
}
}
}
boolean flad = false;
for(int i =0;i<lastHop.length;i++){
for (int j=0;j<lastHop[0].length;j++){
if (route[i][j].equals("sate"+(i)) && i!=j){
flad = true;
}
}
}
if (flad==false){
System.out.println("correct");
}
CnfData dataPackage = new CnfData();
ConcurrentHashMap<String,String> ipool = findService.findIPool();
dataPackage.setIpPool(ipool);
//路径表
dataPackage.setPathTable(path);
//任务表
dataPackage.setTaskTable(taskTable);
//路由表
dataPackage.setRoute(route);
//图片
dataPackage.setPicture(picture);
//ip池
dataPackage.setIpPool(findService.findIPool());
String[] routeself = findService.findRoute(dataPackage.getCurrentSataHop(), dataPackage.getRoute());
ArrayList<String> destinSataHops = findService.findDestinSataHops(path,"D1");
for(String des : destinSataHops) {
CnfData transferPackage = dataPackage;
//目的
transferPackage.setDestinSataHop(des);
//当前
transferPackage.setNextSataHop(findService.findNextHop(des, routeself));
//下一跳
transferPackage.setCurrentSataHop(transferPackage.getNextSataHop());
//ip
transferPackage.setNextIPHop(findService.findIp(transferPackage.getNextSataHop(),transferPackage.getIpPool()));
//终止节点
transferPackage.setEndSateHop("sate11");
//返回一个数据包
cnfDatas.add(transferPackage);
}
return cnfDatas;
}
@Override
public LinkedList<CnfData> packageData(Picture picture, String satename) throws ParseException {
return null;
}
/**
* 发送数据包
*
* @param cnfData
* @param url
*/
@Override
public String sendData(CnfData cnfData, String url) {
/*Map<String, Object> param = new HashMap<>();
param.put("cnfData ", cnfData);*/
String IP = url + ":8083";
ResponseEntity<String> res = restTemplate.postForEntity("http://" + IP + "/transfer", cnfData, String.class);
if (!res.getStatusCode().is2xxSuccessful()) {
throw new RuntimeException("send Error!");
}
return "sucess";
}
/**
* 发送得到cpu计算能力的指令
*
* @param url
*/
@Override
public Double sendCpuCtr(String url) {
String IP = url + ":8083";
return restTemplate.getForObject("http://" + IP + "/getCpuComputing", Double.class);
}
/**
* 得到稳态图
*/
@Override
public String[][] getIt() throws ParseException {
return new String[0][];
}
private boolean repetition(int[] result) {
HashSet<Integer> set = new HashSet<>();
for (int a : result){
set.add(a);
}
if (set.size()==result.length) return false;
else return true;
}
}
package top.ninwoo.cloud.service.csv;
import top.ninwoo.cloud.service.bpso.Bpso;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
public class GetTopo {
public static void main(String[] args){
String str;
String str1;
String str2;
//传输时间参数
str = ReadFile.date+" 5-00-00";
//System.out.println(Arrays.deepToString(TopoRequire(str)));
//传输当前时间
Date current = new Date();
Date current1 = new Date(current.getTime()+ (long) Bpso.slot);
Date current2 = new Date(current1.getTime()+ (long)Bpso.slot);
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH-mm-ss");
str = sdf.format(current);
str1 = sdf.format(current1);
str2 = sdf.format(current2);
}
//得到拓扑图
public static int[][] TopoRequire(String str, NodeL[][] parse) {
/* //网络信息表
NodeL[][] parse = ReadFile.parse();*/
LocalDate dateC = LocalDate.now();
ReadFile.date = dateC.getYear()+"-"+dateC.getMonthValue()+"-"+dateC.getDayOfMonth();
Long timeMillis= getTim(str);
int[][] topo = getTp(parse,timeMillis);
topo = reshape(topo);
// System.out.println(Arrays.deepToString(topo));
//需要删掉
topo[0][1] = 1;
return topo;
}
//现在改成十个卫星
//todo
private static int[][] reshape(int[][] topo) {
int[][] topos = new int[12][12];
for (int i =56;i<66;i++){
for (int j =56;j<66;j++){
topos[i-55][j-55] = topo[i][j];
}
}
for (int i = 56; i < 66; i++) {
topos[0][i-55] = topo[66][i];
}
for (int i = 56; i < 66; i++) {
if (topo[67][i] == 1){
topos[i-55][11] = 1;
topos[11][i-55] = 1;
}
}
return topos;
}
public static Long getTim(String dateL){
long time = 0L;
SimpleDateFormat sDF = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
try {
time = sDF.parse(dateL).getTime();
} catch (ParseException e) {
e.printStackTrace();
}finally {
return time;
}
}
public static int[][] getTp(NodeL[][] parse,Long timeMillis) {
int high = parse.length;
int width = parse[0].length;
int[][] result = new int[high][width];
for (int i =0;i<high;i++){
for (int j = 0;j<width;j++){
NodeL tmp = parse[i][j];
while (tmp!=null){
if (tmp.start<=timeMillis && tmp.end>=timeMillis) {
result[i][j] = 1;
break;
}
tmp = tmp.next;
}
if (tmp==null) result[i][j]=0;
}
}
return result;
}
}
package top.ninwoo.cloud.service.csv;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Iterator;
public class ReadFile {
public static void main(String[] args){
LocalDate dateC = LocalDate.now();
date = dateC.getYear()+"-"+dateC.getMonthValue()+"-"+dateC.getDayOfMonth();
NodeL[][] parse = ReadFile.parse();
long timeMillis = System.currentTimeMillis();
System.out.print(timeMillis);
}
public static NodeL[][] parse(){
File csv = new File("C:\\Users\\Elf\\Desktop\\test\\leo60.csv");
// D:\LabratoryJavaPro\
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(csv));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line = "";
String everyLine = "";
ArrayList<String> allString = new ArrayList<>();
//处理每行数据
try {
line=br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
while (line!=null){
everyLine = line;
String[] strings = everyLine.split(",");
for (String s: strings){
if (s.charAt(0)=='L'){
int count = 0;
StringBuffer str = new StringBuffer();
str.append('L');
for (int qq=1;qq<s.length();qq++){
if (s.charAt(qq)-'0'<10 && s.charAt(qq)-'0'>=0){
str.append(s.charAt(qq));
count++;
}
if (count==3) str.append(' ');
}
s = str.toString();
}
if (s.charAt(0)=='T')
{
int count = 0;
StringBuffer str = new StringBuffer();
str.append('T');
for (int qq=1;qq<s.length();qq++){
if (s.charAt(qq)-'0'<10 && s.charAt(qq)-'0'>=0){
str.append(s.charAt(qq));
count++;
}
//str.append("72");
if (count==1) str.append(' ');
}
s = str.toString();
}
// System.out.println(s);
allString.add(s);
}
try {
line=br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
//删除重复项
for (int i = 0; i < allString.size()-1; i++) {
if(allString.get(i).equals(allString.get(i+1))){
allString.remove(i);
}
}
// System.out.println("csv表格中所有行数:"+allString.size());
//处理字符链表至矩阵链表
NodeL[][] nodeLS = new NodeL[6*11+2][6*11+2];
//定位矩阵索引位
Iterator<String> allSItr = allString.iterator();
String next = allSItr.next();
while (allSItr.hasNext()){
//解析轨道行
if (next.charAt(0)=='L'){
//转化字符串为数字
String[] s = new String[2];
split(next,s);
//获取节点索引位置
int row = Integer.valueOf(s[0].substring(1));
int column = Integer.valueOf(s[1]);
//轨道面与节点编号转换公式
row = (row/100-1)*11+row%100-1;
column = (column/100-1)*11+column%100-1;
// 解析时间行
// 将读取数据转化为long型
NodeL tmp = null;
while (allSItr.hasNext()){
next = allSItr.next();
if (next.charAt(0)!='L' & next.charAt(0)!='T'){
Long start = shift(next);
// System.out.println(start);
next = allSItr.next();
Long end = shift(next);
NodeL nodeL = new NodeL(start,end);
if (tmp ==null) {
nodeLS[row][column] = nodeL;
nodeLS[column][row] = nodeL;
}
if (tmp!=null) tmp.next=nodeL;
tmp = nodeL;
}else break;
}
//显示赋值节点元素
/*System.out.print("拓扑第"+row+"行,第"+column+"列元素"+'\t');
NodeL show = nodeLS[row][column];
while (show!=null){
System.out.print("start="+show.start+" end="+show.end+'\t');
show = show.next;
}
System.out.println();*/
}
//解析地面站
else if (next.charAt(0)=='T'){
String[] s = new String[2];
split(next,s);
//获取节点索引位置
int row = Integer.valueOf(s[0].substring(1));
int column = Integer.valueOf(s[1]);
//轨道面与节点编号转换公式
row = 65+row;
column = (column/100-1)*11+column%100-1;
// 解析时间行
// 将读取数据转化为long型
NodeL tmp = null;
while (allSItr.hasNext()){
next = allSItr.next();
if (next.charAt(0)!='L' & next.charAt(0)!='T'){
Long start = shift(next);
// System.out.println(start);
next = allSItr.next();
Long end = shift(next);
NodeL nodeL = new NodeL(start,end);
if (tmp ==null) {
nodeLS[row][column] = nodeL;
nodeLS[column][row] = nodeL;
}
if (tmp!=null) tmp.next=nodeL;
tmp = nodeL;
}else break;
}
}
}
//填充链表
// System.out.println(nodeLS.);
return nodeLS;
}
private static void split(String next, String[] s) {
StringBuffer sbr = new StringBuffer(next);
int posi = 0;
int index = 0;
int start = 0;
for (;index<sbr.length();index++){
if (sbr.charAt(index)==' ')
{
s[posi++] = sbr.substring(start,index);
while (index<sbr.length() && sbr.charAt(index)==' ') index++;
start=index;
}
s[posi] = sbr.substring(start,index+1);
}
}
public static String date = "1970-1-2";
private static Long shift(String next) {
long time = 0L;
StringBuffer sbr = new StringBuffer(next);
for (int d= 0;d<sbr.length();d++){
if (sbr.charAt(d)==':') sbr.setCharAt(d,'-');
}
String dateL = date+" "+sbr;
SimpleDateFormat sDF = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
try {
time = sDF.parse(dateL).getTime();
} catch (ParseException e) {
e.printStackTrace();
}finally {
return time;
}
}
}
class NodeL{
public Long start;
public Long end;
public NodeL next = null;
public NodeL(Long start, Long end) {
this.start = start;
this.end = end;
}
}
package top.ninwoo.cloud.service.csv;
import top.ninwoo.cloud.service.bpso.Bpso;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import static top.ninwoo.cloud.service.csv.GetTopo.TopoRequire;
public class Wteg {
//获取当前3时隙拓扑
/**
* 先用SimpleDateFormat.parse() 方法将日期字符串转化为Date格式
* 通过Date.getTime()方法,将其转化为毫秒数
*/
public static double[][] getWteg(int dev) throws ParseException {
//传输时间参数
String str;
String str1;
String str2;
//可在这里修改时间
//todo 应该放在yaml文件中
String dateInput = "5-00-00";
long time;
//测试时间
str = ReadFile.date+" "+ dateInput;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
Date current1 = new Date(sdf.parse(str).getTime()+ (long) Bpso.slot);
Date current2 = new Date(current1.getTime()+ (long)Bpso.slot);
//网络信息表
NodeL[][] parse = ReadFile.parse();
//
str1 = sdf.format(current1);
str2 = sdf.format(current2);
//产生三个时隙
int[][] topo = TopoRequire(str,parse);
int[][] topo1 = TopoRequire(str1,parse);
int[][] topo2 = TopoRequire(str2,parse);
//获得单时隙连接矩阵 0或MAXWEIGHT
//等待下一时隙开始执行业务
int num = Bpso.num;
int MAXWEIGHT = Bpso.MAXWEIGHT;
double slot = Bpso.slot;
double[][] slot1 = new double[num][num];
for(int i = 0;i<slot1.length;i++){
for(int j = 0;j<slot1.length;j++){
if (topo[i][j]==0){
if (i==j){
slot1[i][j]=0.0;
}else
slot1[i][j] = MAXWEIGHT;
}else{
slot1[i][j] = 500;
}
}
}
double[][] slot2 = new double[num][num];
for(int i = 0;i<slot2.length;i++){
for(int j = 0;j<slot2.length;j++){
if (topo1[i][j]==0){
if (i==j){
slot2[i][j]=0.0;
}else
slot2[i][j] = MAXWEIGHT;
}else {
slot2[i][j] = 500;
}
}
}
double[][] slot3 = new double[num][num];
for(int i = 0;i<slot3.length;i++){
for(int j = 0;j<slot3.length;j++){
if (topo2[i][j]==0){
if (i==j){
slot3[i][j]=0.0;
}else
slot3[i][j] = MAXWEIGHT;
}else {
slot3[i][j] = 500;
}
}
}
//生成相邻时隙矩阵
double[][] neighbor = new double[num][num];
for(int i = 0;i<neighbor.length;i++){
for(int j = 0;j<neighbor.length;j++){
if(i == j){
neighbor[i][j] = slot;
}else{
neighbor[i][j] = MAXWEIGHT;
}
}
}
//生成其余时隙矩阵
double[][] nonNeighbor = new double[num][num];
for(int i = 0;i<nonNeighbor.length;i++){
for(int j = 0;j<nonNeighbor.length;j++){
nonNeighbor[i][j] = MAXWEIGHT;
}
}
//组装连接矩阵
double[][] edgeWeight = new double[dev][dev];
for(int i = 0;i<edgeWeight.length;i++){
for(int j = 0;j<edgeWeight.length;j++){
if (i>=0 & i<num & j>=0 & j<num) {
edgeWeight[i][j] = slot1[i][j];
}else if (i>=num & i<2*num & j>=num & j<2*num) {
edgeWeight[i][j] = slot2[i%num][j%num];
}else if (i>=2*num & i<3*num & j>=2*num & j<3*num) {
edgeWeight[i][j] = slot3[i%num][j%num];
}else if ((i>=0 & i<num & j>=num & j<2*num) || (i>=num & i<2*num & j>=2*num & j<3*num)){
edgeWeight[i][j] = neighbor[i%num][j%num];
}else {
edgeWeight[i][j] = nonNeighbor[i%num][j%num];
}
}
}
return edgeWeight;
}
}
package top.ninwoo.cloud.service.dbctrans;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import top.ninwoo.api.CnfData;
import top.ninwoo.api.Picture;
import top.ninwoo.cloud.service.TransService;
import top.ninwoo.cloud.service.bpso.Bpso;
import top.ninwoo.cloud.service.bpso.InterSlotDijstraV2;
import top.ninwoo.cloud.service.csv.Wteg;
import top.ninwoo.cloud.service.findService.FindServiceImpl;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.concurrent.ConcurrentHashMap;
@Service
public class DbcTrans implements TransService {
@Resource
private RestTemplate restTemplate;
/**
* 打包picture
*
* @return picture列表
*/
@Override
public Picture packagePic(BufferedImage bufferedImage, String fileId) {
Picture picture = new Picture();
//转化为byte[]数组
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
ImageIO.write(bufferedImage, "jpg", out);
} catch (IOException e) {
e.printStackTrace();
}
//设置图片数据
picture.setData(out.toByteArray());
//设置文件名
picture.setPicId(fileId);
return picture;
}
/**
* 打包成数据包
*
* @param picture
*/
@Override
public LinkedList<CnfData> packageData(Picture picture) throws ParseException {
return null;
}
/**
* 打包成数据包
*/
//satename 为需要完成分散计算的卫星节点
@Override
public LinkedList<CnfData> packageData(Picture picture,String satename) throws ParseException {
LinkedList<CnfData> cnfDatas = new LinkedList<>();
CnfData cnfData = new CnfData();
FindServiceImpl findService = new FindServiceImpl();
//判断npe
if(picture == null){
System.out.println("出错");
return null;
}
//设备数
int num = Bpso.num;
//时隙大小
double slot = Bpso.slot;
//时空拓展图大小
int dev = 3 * num;
//1组装最短路矩阵
double[][] edgeWeight = Wteg.getWteg(dev);
InterSlotDijstraV2 dijs = new InterSlotDijstraV2(num, slot);
InterSlotDijstraV2.pathRecord pathRecord = dijs.dijstra(edgeWeight, 0);
//2加权最短路由矩阵
double[][] lt = pathRecord.getPathWeight();
//最短路由矩阵
int[][] lastHop = pathRecord.getLastHop();
//路径表
String[] path = new String[1];
path[0] = "D1->"+satename;
cnfData.setPathTable(path);
//任务表
ConcurrentHashMap<String,String> taskTable = new ConcurrentHashMap();
taskTable.put(satename,"distributeProcess");
cnfData.setTaskTable(taskTable);
//T3路由表 todo
String[][] route = new String[lastHop.length][lastHop[0].length];
for(int i =0;i<lastHop.length;i++){
for (int j=0;j<lastHop[0].length;j++){
route[i][j] = "sate"+(lastHop[i][j]);
if (route[i][j].equals("sate0")){
route[i][j]="sate"+(j);
}
if (route[i][j].equals("sate0")){
route[i][j]="D1";
}
//要修改
//todo
if (route[i][j].equals("sate31")){
route[i][j]="D2";
}
}
}
//不太正确
cnfData.setRoute(route);
//图片
cnfData.setPicture(picture);
//ip池
cnfData.setIpPool(findService.findIPool());
String[] routeself = findService.findRoute(cnfData.getCurrentSataHop(), cnfData.getRoute());
ArrayList<String> destinSataHops = findService.findDestinSataHops(path,"D1");
for(String des : destinSataHops) {
CnfData transferPackage = cnfData;
//目的
transferPackage.setDestinSataHop(des);
//当前
transferPackage.setNextSataHop(findService.findNextHop(des, routeself));
//下一跳
transferPackage.setCurrentSataHop(transferPackage.getNextSataHop());
//ip
transferPackage.setNextIPHop(findService.findIp(transferPackage.getNextSataHop(),transferPackage.getIpPool()));
//终止节点
transferPackage.setEndSateHop("sate11");
//加权路径路由
transferPackage.setLt(lt);
//返回一个数据包
cnfDatas.add(transferPackage);
}
return cnfDatas;
}
/**
* 发送数据包
*
* @param cnfData
* @param url
*/
@Override
public String sendData(CnfData cnfData, String url) {
String IP = url + ":8083";
ResponseEntity<String> res = restTemplate.postForEntity("http://" + IP + "/transfer", cnfData, String.class);
if (!res.getStatusCode().is2xxSuccessful()) {
throw new RuntimeException("send Error!");
}
return "sucess";
}
/**
* 发送得到cpu计算能力的指令
*
* @param url
*/
@Override
public Double sendCpuCtr(String url) {
System.out.println("kaishi fasong ");
String IP = url + ":8083";
Double res = restTemplate.getForObject("http://" + IP + "/getCpuComputing", Double.class);
System.out.println(res);
return res;
}
@Override
public String[][] getIt() throws ParseException {
//设备数
int num = Bpso.num;
//时隙大小
double slot = Bpso.slot;
//时空拓展图大小
int dev = 3 * num;
//1组装最短路矩阵
double[][] edgeWeight = Wteg.getWteg(dev);
InterSlotDijstraV2 dijs = new InterSlotDijstraV2(num, slot);
InterSlotDijstraV2.pathRecord pathRecord = dijs.dijstra(edgeWeight, 0);
//2最短路由矩阵
double[][] lt = pathRecord.getPathWeight();
int[][] lastHop = pathRecord.getLastHop();
for (int j = 0;j<lastHop.length;j++){
for(int i = 0;i<lastHop.length;i++){
int tmp0 = lastHop[j][i];
while (tmp0 != 0){
lastHop[j][i] = tmp0;
tmp0 = lastHop[j][tmp0];
}
}
}
//T3路由表
String[][] routetest = new String[lastHop.length][lastHop[0].length];
for (int l = 0; l < lastHop.length/num; l++) {
for (int i = l * num; i < l*num+num; i++) {
for (int j = l * num; j < lastHop.length; j++) {
routetest[i][j] = "sate" + (lastHop[i][j]);
//到自己
if((i != 0 || i != num*l)&(routetest[i][j].equals("sate0"))){
routetest[i][j] = "sate"+i;
}
//表示不可达
if(j==num*l){
routetest[i][j] = null;
}
}
}
}
return routetest;
}
}
package top.ninwoo.cloud.service.findService;
import org.springframework.stereotype.Service;
import top.ninwoo.cloud.service.FindService;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
@Service
public class FindServiceImpl implements FindService {
/**
* 根据路径表,找到本机需要处理路径条数
* c->a ==> sata1->sata3
*
* @param pathTable
* @param currenthop
*/
@Override
public ArrayList<String> findDestinSataHops(String[] pathTable, String currenthop) {
ArrayList<String> destinSataHops = new ArrayList<String>();
if(pathTable.length == 0){
System.out.println("路径表为空");
destinSataHops.add("nopara");
return destinSataHops;
}
for (int i = 0; i < pathTable.length; i++) {
//判断本机是否为路径起点
if(currenthop.equals(pathTable[i].split("->")[0])){
destinSataHops.add(pathTable[i].split("->")[1]);
}
}
return destinSataHops;
}
/**
* 根据本机卫星名,全局路由表,路由表得到本机路由表
*
* @param currentSataHop
* @param routeTable
*/
@Override
public String[] findRoute(String currentSataHop, String[][] routeTable) {
//判断路由表是否存在
if (routeTable.length == 0) {
System.out.println("路由表为空");
return null;
}
//找到本机路由表
return routeTable[0];
}
/**
* 得到ip池
*/
@Override
public ConcurrentHashMap<String, String> findIPool() {
ConcurrentHashMap<String, String> ipool = new ConcurrentHashMap<>();
String str;
// 文件地址
File file = new File("C:\\Users\\Elf\\Desktop\\test\\sateIP.txt");
try{
BufferedReader br = new BufferedReader(new FileReader(file));
while((str = br.readLine()) != null){
ipool.put(str.split(":")[0],str.split(":")[1]);
}
}catch(Exception e){
e.printStackTrace();
}
return ipool;
}
/**
* 根据目的卫星名,本机路由表找到下一跳卫星名
*
* @param destinSataHop
* @param route
*/
@Override
public String findNextHop(String destinSataHop, String[] route) {
int index = Integer.parseInt(destinSataHop.split("sate")[1]);
return route[index-1];
}
@Override
public String findIp(String sataName, ConcurrentHashMap<String,String> ipool) {
String sataIP = ipool.get(sataName);
if(sataIP.equals(null)){
return "no ip";
}
return sataIP;
}
}
server.port=8082
spring.application.name=cnf-earth
#thymeleaf
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.cache=false
#
spring.servlet.multipart.max-file-size=1024000000000MB
spring.servlet.multipart.max-request-size=1024000000000MB
\ No newline at end of file
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>步骤可分割</title>
</head>
<body>
<hr/>
<form method="POST" enctype="multipart/form-data" action="/cpcTrans" id="uploadForm">
<p>
文件:<input type="file" name="file" />
</p>
<p>
文件ID:<input type="text" name="fileId" palcegolder="请输入" />
</p>
<p>
<input type="submit" value="上传" />
</p>
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>数据可分割</title>
</head>
<body>
<hr/>
<form method="POST" enctype="multipart/form-data" action="/dbcTrans" id="uploadForm">
<p>
文件:<input type="file" name="file" />
</p>
<p>
文件ID:<input type="text" name="fileId" palcegolder="请输入" />
</p>
<p>
<input type="submit" value="上传" />
</p>
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>文件显示</title>
</head>
<body>
<hr/>
<!--<a href="jpg/1.jpg">预览图片</a>-->
<!--<a href="@{/getFile/(fileName=${fileName},fileId=${fileId})}">预览图片</a>-->
<img th:src="file+'/'+${fileName}">
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>cnf-pathComp-app</artifactId>
<groupId>top.ninwoo</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>app-docker-edge</artifactId>
<dependencies>
<dependency>
<groupId>top.ninwoo</groupId>
<artifactId>app-docker-api</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${springboot.version}</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package top.ninwoo.edge;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
public class CnfSateApp {
public static void main(String[] args) {
SpringApplication.run(CnfSateApp.class, args);
}
}
package top.ninwoo.edge.config;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestConfig {
private ApplicationContext applicationContext = null;
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(1000000);
factory.setConnectTimeout(1000000);
return factory;
}
}
package top.ninwoo.edge.service;
import top.ninwoo.api.CnfData;
import top.ninwoo.api.Picture;
import top.ninwoo.api.TacticsCtl;
import java.io.IOException;
import java.util.LinkedList;
public interface DistributeService {
/**
* 打包信令
*/
TacticsCtl packageTactics(CnfData cnfData);
/**
* 发出请求,能否做任务
* @return
*/
String askIsProcss(TacticsCtl tacticsCtl, String url);
/**
* 返回请求
* 若可以:y
* 若不行:n
*/
String backAsk(TacticsCtl tacticsCtl);
/**
* 开始传输
*/
String startTranser(LinkedList<String> sateArr) throws IOException;
/**
* 判断是否小于size大小
*/
boolean isHandle(CnfData cnfData);
/**
* 包装要做的数据包
*/
String packageHasCut(CnfData cnfData, Picture picture);
}
package top.ninwoo.edge.service;
import java.util.ArrayList;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* 发现路由
*/
public interface FindService{
/**
* 根据路径表,找到本机需要处理路径条数
* c->a ==> sata1->sata3
*/
ArrayList<String> findDestinSataHops(String[] pathTable, String currenthop);
/**
* 根据本机卫星名,全局路由表,路由表得到本机路由表
*/
String[] findRoute(String currentSataHop, String[][] routeTable);
/**
* 根据目的卫星名,本机路由表找到下一跳卫星名
*/
String findNextHop(String destinSataHop, String[] route);
/**
* 找到本机的任务
*/
String findTask(String currenSataHop, ConcurrentHashMap<String, String> taskMap);
/**
* 找到下一跳的ip地址
* @return
*/
String findIp(String sataName, ConcurrentHashMap<String, String> ipool);
/**
* 找到直联的节点
*/
Set<String> findDrictHop(String currenthop, String[][] ipool);
//判断是否能在第个时隙内返回
int findBackTime(String currenthop, String dishop, String[][] route);
}
package top.ninwoo.edge.service;
public interface LinuxUtils {
String runCmd(String cmd);
}
package top.ninwoo.edge.service;
import top.ninwoo.api.Picture;
import java.util.LinkedList;
/**
* 图片处理功能模块
*/
public interface PicService {
/**
* @param num 图片切割个数,或者图片合并的个数,若是二值等操作则默认为1
* @param pictures
* @return
*/
LinkedList<Picture> picProcess(int num, LinkedList<Picture> pictures);
String in_file = "/pic/in.jpg";
String out_file = "/pic/out.jpg";
String in_file1 = "/pic/in1.jpg";
String in_file2 = "/pic/in2.jpg";
String out_file1 = "/pic/out1.jpg";
String out_file2 = "/pic/out2.jpg";
}
package top.ninwoo.edge.service;
import top.ninwoo.api.CnfData;
import top.ninwoo.api.TacticsCtl;
import java.io.IOException;
//分散计算的策略
public interface Tactics {
/**
* 打包成信令
*/
TacticsCtl packageTactics(CnfData cnfData);
/**
* 请求信令
*/
TacticsCtl askTactics(TacticsCtl tacticsCtl);
/**
* repackage
*/
TacticsCtl repackage(TacticsCtl tacticsCtl);
/**
* 处理信令
*/
String handle() throws IOException;
String setTactics(TacticsCtl tacticsCtl);
}
\ No newline at end of file
package top.ninwoo.edge.service;
import top.ninwoo.api.CnfData;
import top.ninwoo.api.Picture;
import top.ninwoo.api.TacticsCtl;
import java.util.LinkedList;
public interface TransferService {
/**
* 发送数据
*/
String sendData(CnfData cnfData, String url);
/**
* 发送指令
*/
String sendCtl(TacticsCtl tacticsCtl, String url);
String backCtl(TacticsCtl tacticsCtl, String url);
/**
* 拆包
* @return 要完成的功能名称,如果仅作为转发节点,则返回 pass
*/
String parseData(CnfData cnfData);
/**
* 装包
*/
LinkedList<CnfData> packageData(CnfData cnfData);
/**
* 装包
*/
LinkedList<CnfData> packageData(CnfData cnfData, LinkedList<Picture> pictures);
void backEarth(String message);
}
package top.ninwoo.edge.service;
import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Component;
import java.lang.annotation.*;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Utils {
/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
*
* @return the suggested component name, if any (or empty String otherwise)
*/
@AliasFor(annotation = Component.class)
String value() default "";
}
package top.ninwoo.edge.service;
public interface appService {
//得到负载
Float getOverload();
//得到Cpu核心数
Float getCpuNum();
//得到核心线程数
Float getCpuThread();
//得到Cpu核心数
Float getCpuMhz();
//得到Cpu信息
String getCpu();
}
package top.ninwoo.edge.service.impl;
import top.ninwoo.edge.service.LinuxUtils;
import top.ninwoo.edge.service.Utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
@Utils
public class LinuxUtilsImpl implements LinuxUtils {
@Override
public String runCmd(String cmd) {
String result = "";
try {
Process exec = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", cmd});
exec.waitFor();
InputStream in = exec.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String msg;
while((msg = br.readLine())!= null && msg.length() > 0) {
result += msg + "\n";
}
if("".equals(result)) {
// 构建Error
InputStream errorStream = exec.getErrorStream();
BufferedReader ebr = new BufferedReader(new InputStreamReader(errorStream));
String eMsg;
while((eMsg = ebr.readLine())!= null && eMsg.length() > 0) {
result += eMsg + "\n";
}
if(result.equals("")) {
return result;
}
result = "Error: " + result;
}
if(result.length() > 0) {
result = result.substring(0, result.length()-1);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return result;
}
}
package top.ninwoo.edge.service.impl;
import org.springframework.stereotype.Service;
import top.ninwoo.api.Picture;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.LinkedList;
@Service
public class PicServiceImpl {
//传入的图片
public LinkedList<Picture> picOrigin = new LinkedList<>();
//处理后的图片
public LinkedList<Picture> picRes = new LinkedList<>();
//要完成的任务
public static String taskName;
//需要生成 picTable(暂时不需要) 和 picPara
//图片处理功能
public void PicTask(){
//清空图像
delPicPara();
// 创建图像处理功能对象
picRes = getPicService(taskName,1,picOrigin);
picOrigin.clear();
}
private LinkedList<Picture> getPicService(String taskName, int SliceNum, LinkedList<Picture> picOrigin) {
String in = (taskName.substring(0, 1).toUpperCase() + taskName.substring(1)+"Impl")
.replace("Process","Service");
String packagePath = "org.elf.cnf.sate.service.impl.picService.";
LinkedList<Picture> result = null;
try {
Class<?> name = Class.forName(packagePath+in);
Constructor<?> constructor = name.getConstructor(null);
Object instance = constructor.newInstance();
Method picProcess = name.getMethod("picProcess", int.class, LinkedList.class);
result = (LinkedList<Picture>) picProcess.invoke(instance,SliceNum, picOrigin);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return result;
}
//返回图片结果
public LinkedList<Picture> getPicPara(){
return picRes;
}
//清空图片
public String delPicPara(){
if(picRes.size() == 0){
return "no para";
}
picRes.clear();
return "sucess";
}
// 装载待处理图片
public String setPicOrigin(String task, Picture picture){
if(picture.equals(null)){
System.out.println("图片呢");
}
picOrigin.add(picture);
taskName = task;
//单图片情况及多图片并且全都收到
if(picture.getSliceNum() == picOrigin.size() || !taskName.equals("mergeProcess")){
return "sucess";
}
//多图片未完全收到
else{
//判断是否为同一个任务
//初始为空
return "wait";
}
}
}
// switch (taskName){
// case "binaryProcess":
//// 创建图像处理功能对象
// picRes = getPicService(taskName,1,picOrigin);
//// picRes = new BinaryServiceImpl().picProcess(1, picOrigin);
// break;
// case "cutProcess":
// picRes = getPicService(taskName,picOrigin.get(0).getSliceNum(),picOrigin);
//// picRes = new SplitServiceImpl().picProcess(picOrigin.get(0).getSliceNum(), picOrigin);
// break;
// case "greyProcess":
// picRes = getPicService(taskName,1,picOrigin);
//// picRes = new GrayServiceImpl().picProcess(1, picOrigin);
// break;
// case "mergeProcess":
// picRes = getPicService(taskName,picOrigin.get(0).getSliceNum(),picOrigin);
//// picRes = new MerageServiceImpl().picProcess(picOrigin.get(0).getSliceNum(), picOrigin);
// break;
// case "tailorProcess":
// picRes = getPicService(taskName,1,picOrigin);
//// picRes = new TailorServiceImpl().picProcess(1, picOrigin);
// break;
// }
\ No newline at end of file
package top.ninwoo.edge.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import top.ninwoo.api.CnfData;
import top.ninwoo.api.Picture;
import top.ninwoo.api.TacticsCtl;
import top.ninwoo.edge.service.FindService;
import top.ninwoo.edge.service.Tactics;
import top.ninwoo.edge.service.impl.transferService.TransServiceImpl;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
@Service
public class TacticsImpl implements Tactics {
private int level;
private static int slicenum = 7;
private CnfData oriData = new CnfData();
private String currentSate;
//阻止更多的信令回来
private int tag;
//返回的卫星和计算能力
private ConcurrentHashMap<String, Double> computeTable = new ConcurrentHashMap<>();
@Resource
private RestTemplate restTemplate;
@Autowired
private FindService findService;
@Autowired
TransServiceImpl transService;
/**
* 打包成信令
*/
@Override
public TacticsCtl packageTactics(CnfData cnfData) {
//初始化一些参数
init(cnfData);
//打包
TacticsCtl tacticsCtl = new TacticsCtl();
tacticsCtl.setSate(cnfData.getCurrentSataHop());
tacticsCtl.setLt(cnfData.getLt());
tacticsCtl.setIpPool(cnfData.getIpPool());
tacticsCtl.setRoute(cnfData.getRoute());
setLevel(tacticsCtl);
return tacticsCtl;
}
/**
* 请求信令
*/
@Override
public TacticsCtl askTactics(TacticsCtl tacticsCtl) {
if(setLevel(tacticsCtl)){
return repackage(tacticsCtl);
}
return null;
}
/**
* repackage
*/
@Override
public TacticsCtl repackage(TacticsCtl tacticsCtl) {
ConcurrentHashMap<String, Double> sateMap = new ConcurrentHashMap<>();
Double res = sendCpuCtr("127.0.0.1");
sateMap.put(tacticsCtl.getCurrentHop(), res);
tacticsCtl.setSateMap(sateMap);
return tacticsCtl;
}
/**
* 处理信令
*/
@Override
public String handle() throws IOException {
ConcurrentHashMap<String, Picture> result = imageSplit(oriData.getPicture(),computeTable);
for (String key : result.keySet()) {
CnfData cnfData = oriData;
System.out.println(key+" : "+result.get(key).getSliceId());
System.out.println("currenthop: "+ currentSate);
String[] path = new String[2];
path[0] = currentSate +"->"+key;
System.out.println(path[0]);
path[1] = key + "->" + currentSate;
System.out.println(path[1]);
//路径表
cnfData.setPathTable(path);
ConcurrentHashMap<String, String> tasktable = new ConcurrentHashMap<>();
tasktable.put(key,"greyProcess");
tasktable.put(currentSate,"start/end");
//任务表
cnfData.setTaskTable(tasktable);
//设置图片
cnfData.setPicture(result.get(key));
//设置目的节点
cnfData.setDestinSataHop(key);
System.out.println("destinsatahop "+key);
String[] route = findService.findRoute(currentSate, cnfData.getRoute());
//设置下一跳地址
cnfData.setNextSataHop(findService.findNextHop(cnfData.getDestinSataHop(), route));
//设置本机地址
cnfData.setCurrentSataHop(cnfData.getNextSataHop());
//设置下一跳ip地址
String nextIP = findService.findIp(cnfData.getNextSataHop(), cnfData.getIpPool());
cnfData.setNextIPHop(nextIP);
System.out.println("send picRes to "+nextIP);
//发包
transService.sendData(cnfData, cnfData.getNextIPHop());
}
return "sucess";
}
@Override
public String setTactics(TacticsCtl tacticsCtl) {
if(tag==1) {
for (String key : tacticsCtl.getSateMap().keySet()) {
System.out.println(key+":"+tacticsCtl.getSateMap().get(key));
computeTable.put(key, tacticsCtl.getSateMap().get(key));
}
if (computeTable.size() == slicenum) {
tag = 0;
System.out.println("complete receive");
return "complete";
}
}
return "wait";
}
//得到本机的计算能力
public Double sendCpuCtr(String url) {
//System.out.println("kaishi fasong ");
String IP = url + ":8083";
Double res = restTemplate.getForObject("http://" + IP + "/getCpuComputing", Double.class);
//System.out.println(IP+":"+res);
return res;
}
private boolean setLevel(TacticsCtl tacticsCtl){
//level == 0 等于没有被扩散
if(level == 0){
System.out.println("no distributed");
level = tacticsCtl.getLevel();
System.out.println("kuosandengji:"+level);
return true;
}
System.out.println("start distributed");
return false;
}
private void init(CnfData cnfData){
level = 0;
tag = 1;
oriData = cnfData;
currentSate = cnfData.getCurrentSataHop();
}
private ConcurrentHashMap<String, Picture> imageSplit(Picture picture, ConcurrentHashMap<String, Double> computeTable) throws IOException {
ConcurrentHashMap<String, Picture> imgstable = new ConcurrentHashMap<>();
//归一化处理
ConcurrentHashMap<String, Double> compute = normalize(computeTable);
//BufferedImage images = readImage(name);
ByteArrayInputStream bis = new ByteArrayInputStream(picture.getData());
BufferedImage images = ImageIO.read(bis);
int rows = 1;
// 计算每个小图的宽度和高度
int chunkHeight = images.getHeight() / rows;
int count = 0;
int tmp = 0;
//BufferedImage imgs[] = new BufferedImage[chunks];
BufferedImage imgs[] = new BufferedImage[slicenum];
for (String key : compute.keySet()) {
int chunkWidth = (int) (images.getWidth()*compute.get(key));
//设置小图的大小和类型
imgs[count] = new BufferedImage(chunkWidth, chunkHeight, images.getType());
//写入图像内容
Graphics2D gr = imgs[count++].createGraphics();
gr.drawImage(images, 0, 0,
chunkWidth, chunkHeight,
tmp, 0,
tmp + chunkWidth, chunkHeight,
null);
gr.dispose();
tmp = tmp + chunkWidth;
}
//将imgs[]转为相应的byte数组
int i = 0 ;
for (String key : compute.keySet()) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(imgs[i],"jpg",bos);
} catch (IOException e) {
e.printStackTrace();
}
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
Picture picture1 = new Picture();
picture1.setData(bos.toByteArray());
picture1.setSliceNum(slicenum);
picture1.setPicId(picture.getPicId());
picture1.setSliceId(i+"");
imgstable.put(key,picture1);
i++;
}
return imgstable;
}
//归一化的结果
private ConcurrentHashMap<String, Double> normalize(ConcurrentHashMap<String, Double> computeTable){
ConcurrentHashMap<String, Double> normalizeTable = new ConcurrentHashMap<>();
double sum = 0.0;
for (String key : computeTable.keySet()) {
sum = sum +computeTable.get(key);
}
for (String key : computeTable.keySet()) {
double after = computeTable.get(key)/sum;
normalizeTable.put(key,after);
//System.out.println(key+":"+normalizeTable.get(key));
}
return normalizeTable;
}
}
package top.ninwoo.edge.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.ninwoo.edge.service.appService;
@SuppressWarnings("unchecked")
@Service
public class appServiceImpl implements appService {
@Autowired
private LinuxUtilsImpl linuxUtils;
@Override
public Float getOverload() {
String cmd = "uptime";
String str = "error";
String result = linuxUtils.runCmd(cmd);
if(result.contains("Error")) {
throw new RuntimeException(" failed!:[" + cmd + "]:" + result);
}
String res[] = result.split(",");
for (String re : res) {
if(re.startsWith(" load average")){
str = re.split(":")[1];
}
}
//以字符串形式输出
//System.out.println(Float.parseFloat(str));
return Float.parseFloat(str);
}
@Override
public Float getCpuNum() {
String cmd = "lscpu";
String str = "error";
String result = linuxUtils.runCmd(cmd);
if(result.contains("Error")) {
throw new RuntimeException("failed!:[" + cmd + "]:" + result);
}
//以字符串形式输出
String res[] = result.split("\n");
for (String re : res) {
if (re.startsWith("CPU(s):")){
str = re.split(": ")[1];
}
}
//System.out.println(Float.parseFloat(str));
return Float.parseFloat(str);
}
@Override
public Float getCpuThread() {
String cmd = "lscpu";
String str = "error";
String result = linuxUtils.runCmd(cmd);
if(result.contains("Error")) {
throw new RuntimeException("failed!:[" + cmd + "]:" + result);
}
//以字符串形式输出
String res[] = result.split("\n");
for (String re : res) {
if (re.startsWith("Thread(s) per core:")){
str = re.split(": ")[1];
}
}
//System.out.println(Float.parseFloat(str));
return Float.parseFloat(str);
}
@Override
public Float getCpuMhz() {
String cmd = "lscpu";
String str = "error";
String result = linuxUtils.runCmd(cmd);
if(result.contains("Error")) {
throw new RuntimeException("failed!:[" + cmd + "]:" + result);
}
//以字符串形式输出
String res[] = result.split("\n");
for (String re : res) {
if (re.startsWith("CPU MHz:")){
str = re.split(": ")[1];
}
}
//System.out.println(Float.parseFloat(str));
return Float.parseFloat(str);
}
@Override
public String getCpu() {
String cmd = "lscpu";
String str = "error";
String result = linuxUtils.runCmd(cmd);
if(result.contains("Error")) {
throw new RuntimeException("failed!:[" + cmd + "]:" + result);
}
//以字符串形式输出
/*String res[] = result.split("\n");
for (String re : res) {
if (re.startsWith("CPU MHz:")){
str = re.split(":")[1];
}
}*/
//System.out.println(Float.parseFloat(str));
return result;
}
}
\ No newline at end of file
package top.ninwoo.edge.service.impl.fileService;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.LinkedList;
public class GetFile {
//得到所有的图片名
public static LinkedList<String> getFileName() {
String path = "/pic/"; // 路径
File f = new File(path);
//判断文件是否存在
if (!f.exists()) {
System.out.println(path + " not exists");
return null;
}
File[] fa = f.listFiles();
LinkedList<String> fname = new LinkedList<>();
for (File fs : fa) {
if (fs.getName().startsWith("out")) {
fname.add(fs.getName());
}
}
return fname;
}
//得到图片的byte[]格式
//路径需要修改
public static LinkedList<byte[]> getByte(LinkedList<String> names) throws IOException {
LinkedList<byte[]> bytes = new LinkedList<>();
for(String name : names){
//输出的数组
ByteArrayOutputStream out = new ByteArrayOutputStream();
//路径
String path = "/pic/"+ name;
System.out.println(path);
//输入
InputStream inputStream = new FileInputStream(path);
BufferedImage bufferedImage = ImageIO.read(inputStream);
ImageIO.write(bufferedImage, "jpg", out);
//放到数组中
bytes.add(out.toByteArray());
}
return bytes;
}
/**
* 删除所有图片
* @return
*/
public static String delImg(LinkedList<String> fnames){
for (String fname : fnames) {
File file = new File("/pic/"+fname);
if(file.exists()) {
file.delete();
}
}
return null;
}
}
package top.ninwoo.edge.service.impl.fileService;
import top.ninwoo.api.Picture;
import java.io.*;
/**
* save(储存)传入图片
* load(加载)传出图片
*/
public class SaveFile {
public static void saveToFile(Picture picture, String file_path) {
byte[] pic_data = picture.getData();
File targetFile = new File(file_path);
if (targetFile.exists()) {
targetFile.delete();
}
//为什么创建父类
createParents(targetFile);
try {
targetFile.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(targetFile);
fileOutputStream.write(pic_data);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void createParents(File f) {
String parentName = f.getParent();
File parent = new File(parentName);
if (!parent.exists()) {
createParents(parent);
parent.mkdir();
}
}
public static Picture loadPicture(String pic_url) {
try {
File f = new File(pic_url);
InputStream is = new FileInputStream(f);
byte[] b = new byte[(int) f.length()];
is.read(b);
is.close();
Picture picture = new Picture();
picture.setData(b);
return picture;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
package top.ninwoo.edge.service.impl.picService;
import top.ninwoo.api.Picture;
import top.ninwoo.edge.service.PicService;
import java.io.IOException;
import java.util.LinkedList;
import static top.ninwoo.edge.service.impl.fileService.SaveFile.loadPicture;
import static top.ninwoo.edge.service.impl.fileService.SaveFile.saveToFile;
public class BinaryServiceImpl implements PicService {
public LinkedList<Picture> picPara = new LinkedList<>();
@Override
public LinkedList<Picture> picProcess(int num, LinkedList<Picture> pictures) {
for (Picture picture:pictures) {
saveToFile(picture, in_file);
try {
String command = "python binary-pro.py " + in_file + " " + out_file;
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
Picture newPicture = loadPicture(out_file);
newPicture.setPicId(picture.getPicId());
newPicture.setSliceId(picture.getSliceId());
newPicture.setSliceNum(picture.getSliceNum());
picPara.add(newPicture);
}
return picPara;
}
}
package top.ninwoo.edge.service.impl.picService;
import top.ninwoo.api.Picture;
import top.ninwoo.edge.service.PicService;
import java.io.IOException;
import java.util.LinkedList;
import static top.ninwoo.edge.service.impl.fileService.SaveFile.loadPicture;
import static top.ninwoo.edge.service.impl.fileService.SaveFile.saveToFile;
public class GrayServiceImpl implements PicService {
public static LinkedList<Picture> picPara = new LinkedList<>();
@Override
public LinkedList<Picture> picProcess(int num, LinkedList<Picture> pictures) {
for (Picture picture : pictures) {
saveToFile(picture, in_file);
try {
String command = "python grey-pro.py " + in_file + " " + out_file;
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
Picture newPicture = loadPicture(out_file);
newPicture.setPicId(picture.getPicId());
newPicture.setSliceId(picture.getSliceId());
newPicture.setSliceNum(picture.getSliceNum());
picPara.add(newPicture);
}
return picPara;
}
}
package top.ninwoo.edge.service.impl.picService;
import top.ninwoo.api.Picture;
import top.ninwoo.edge.service.PicService;
import java.io.IOException;
import java.util.LinkedList;
import static top.ninwoo.edge.service.impl.fileService.SaveFile.loadPicture;
import static top.ninwoo.edge.service.impl.fileService.SaveFile.saveToFile;
public class MerageServiceImpl implements PicService {
public static LinkedList<Picture> picPara = new LinkedList<>();
@Override
public LinkedList<Picture> picProcess(int num, LinkedList<Picture> pictures) {
System.out.println("run Before saveToFile");
saveToFile(pictures.get(0),in_file1);
saveToFile(pictures.get(1),in_file2);
System.out.println("run after saveToFile");
try {
String command = "python merge-pro.py " + in_file1 + " " + in_file2 + " " + out_file;
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
Picture newPicture = loadPicture(out_file);
newPicture.setPicId(pictures.get(0).getPicId());
newPicture.setSliceId(1+"");
newPicture.setSliceNum(1);
picPara.add(newPicture);
return picPara;
}
}
package top.ninwoo.edge.service.impl.picService;
import top.ninwoo.api.Picture;
import top.ninwoo.edge.service.PicService;
import java.io.IOException;
import java.util.LinkedList;
import static top.ninwoo.edge.service.impl.fileService.SaveFile.loadPicture;
import static top.ninwoo.edge.service.impl.fileService.SaveFile.saveToFile;
public class SplitServiceImpl implements PicService {
public static LinkedList<Picture> picPara = new LinkedList<>();
@Override
public LinkedList<Picture> picProcess(int num, LinkedList<Picture> pictures) {
for (Picture picture:pictures) {
saveToFile(picture, in_file);
try {
String command = "python cut-pro.py " + in_file + " " + out_file1 + " " + out_file2 + " " + 0.5;
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
Picture picture1 = loadPicture(out_file1);
Picture picture2 = loadPicture(out_file2);
picture1.setSliceNum(2);
picture1.setPicId(picture.getPicId());
picture1.setSliceId(1+"");
picture2.setSliceNum(2);
picture2.setPicId(picture.getPicId());
picture2.setSliceId(2+"");
picPara.add(picture1);
picPara.add(picture2);
}
return picPara;
}
}
package top.ninwoo.edge.service.impl.picService;
import top.ninwoo.api.Picture;
import top.ninwoo.edge.service.PicService;
import java.io.IOException;
import java.util.LinkedList;
import static top.ninwoo.edge.service.impl.fileService.SaveFile.loadPicture;
import static top.ninwoo.edge.service.impl.fileService.SaveFile.saveToFile;
public class TailorServiceImpl implements PicService {
/**
* @param num 图片切割个数,或者图片合并的个数,若是二值等操作则默认为1
* @param pictures
* @return
*/
public static LinkedList<Picture> picPara = new LinkedList<>();
@Override
public LinkedList<Picture> picProcess(int num, LinkedList<Picture> pictures) {
for (Picture picture:pictures) {
saveToFile(picture, in_file);
try {
String command = "python tailor-pro.py " + in_file + " " + out_file + " " + 0.8;
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
Picture newPicture = loadPicture(out_file);
newPicture.setPicId(picture.getPicId());
newPicture.setSliceId(picture.getSliceId());
newPicture.setSliceNum(picture.getSliceNum());
picPara.add(newPicture);
}
return picPara;
}
}
package top.ninwoo.edge.service.impl.transferService;
import org.springframework.stereotype.Service;
import top.ninwoo.edge.service.FindService;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@Service
public class FindServiceImpl implements FindService {
/**
* 根据路径表,找到本机需要处理路径条数
* c->a ==> sata1->sata3
*
* @param pathTable
* @param currenthop
*/
@Override
public ArrayList<String> findDestinSataHops(String[] pathTable, String currenthop) {
ArrayList<String> destinSataHops = new ArrayList<String>();
int j = 0;
if(pathTable.length == 0){
System.out.println("路径表为空");
destinSataHops.add("nopara");
return destinSataHops;
}
for (int i = 0; i < pathTable.length; i++) {
//判断本机是否为路径起点
if(currenthop.equals(pathTable[i].split("->")[0])){
destinSataHops.add(pathTable[i].split("->")[1]);
}
}
return destinSataHops;
}
/**
* 根据本机卫星名,全局路由表,路由表得到本机路由表
*
* @param currentSataHop
* @param routeTable
*/
@Override
public String[] findRoute(String currentSataHop, String[][] routeTable) {
//判断路由表是否存在
if(routeTable.length == 0){
System.out.println("路由表为空");
return null;
}
//找到本机路由表
String[] route = this.findCurrentRoute(currentSataHop,routeTable);
return route;
}
/**
* 根据目的卫星名,本机路由表找到下一跳卫星名
*
* @param destinSataHop
* @param route
*/
@Override
public String findNextHop(String destinSataHop, String[] route) {
int index = Integer.parseInt(destinSataHop.split("sate")[1]);
if(route[index].equals("direct")){
return destinSataHop;
}
if(route[index].equals("self")){
return destinSataHop;
}
return route[index];
}
/**
* 找到本机的任务
*
* @param currenSataHop
* @param taskMap
*/
@Override
public String findTask(String currenSataHop, ConcurrentHashMap<String, String> taskMap) {
if(taskMap.isEmpty()){
System.out.println("无任务表");
return null;
}
return taskMap.get(currenSataHop);
}
/**
* 找到下一跳的ip地址
*
* @param sataName
* @return
*/
// todo 需要设置文件地址
@Override
public String findIp(String sataName, ConcurrentHashMap<String, String> ipool) {
String sataIP = ipool.get(sataName);
if(sataIP.equals(null)){
return "no ip";
}
return sataIP;
}
/**
* 找到直联的节点
*/
@Override
public Set<String> findDrictHop(String currenthop, String[][] routeTable) {
//System.out.println(currenthop);
int num = routeTable.length / 3;
String[] route = findRoute(currenthop, routeTable);
Set<String> drictHop = new HashSet<>();
for (int i = 0; i < route.length; i++) {
if (route[i] != null && route[i].equals("direct") && !currenthop.equals("sate" + (i % num))) {
//System.out.println(i);
drictHop.add("sate" + (i % num));
}
}
return drictHop;
}
@Override
public int findBackTime(String currenthop, String dishop, String[][] route) {
//卫星数目
int num = route.length / 3;
//时隙数目
int time = 0;
int index = Integer.parseInt(dishop.split("sate")[1]);
String[] rouTable = findCurrentRoute(currenthop, route);
//每一个时隙都去判断
for (int i = 0; i<3; i++) {
if ( ((num*i) +index) < rouTable.length || rouTable[(num*i) +index] != null){
time = i;
}
else break;
}
return time;
}
//找到本卫星的路由
private String[] findCurrentRoute(String sataname, String[][] routeTable){
int index = Integer.parseInt(sataname.split("sate")[1]);
// System.out.println(index);
return routeTable[index];
}
}
package top.ninwoo.edge.service.impl.transferService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import top.ninwoo.api.CnfData;
import top.ninwoo.api.Picture;
import top.ninwoo.api.TacticsCtl;
import top.ninwoo.edge.service.FindService;
import top.ninwoo.edge.service.TransferService;
import top.ninwoo.edge.service.impl.PicServiceImpl;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedList;
@Service
public class TransServiceImpl implements TransferService {
@Resource
private RestTemplate restTemplate;
@Autowired
private FindService findService;
@Autowired
private PicServiceImpl picService;
@Override
public String sendData(CnfData cnfData, String url){
String IP = url + ":8083";
ResponseEntity<String> res = restTemplate.postForEntity("http://" + IP + "/transfer", cnfData, String.class);
if (!res.getStatusCode().is2xxSuccessful()) {
throw new RuntimeException("send Error!");
}
System.out.println("send picRes sucess");
return "sucess";
}
/**
* 发送指令
*/
@Override
public String sendCtl(TacticsCtl tacticsCtl, String url) {
String IP = url + ":8083";
ResponseEntity<String> res = restTemplate.postForEntity("http://" + IP + "/tactics", tacticsCtl, String.class);
if (!res.getStatusCode().is2xxSuccessful()) {
throw new RuntimeException("send Error!");
}
System.out.println("send ctl sucess");
return "sucess";
}
@Override
public String backCtl(TacticsCtl tacticsCtl, String url) {
String IP = url + ":8083";
ResponseEntity<String> res = restTemplate.postForEntity("http://" + IP + "/backtactics", tacticsCtl, String.class);
if (!res.getStatusCode().is2xxSuccessful()) {
throw new RuntimeException("send Error!");
}
System.out.println("back ctl sucess");
return "sucess";
}
@Override
public String parseData(CnfData cnfData) {
//npe检查
if(cnfData.equals(null)){
return "error";
}
//是否为终节点
if(cnfData.getCurrentSataHop().equals(cnfData.getEndSateHop())) {
return "end";
}
//是否为该边节点
if (cnfData.getCurrentSataHop().equals(cnfData.getDestinSataHop())){
// 通过任务分配表和当前卫星名寻找当前任务
String task = findService.findTask(cnfData.getCurrentSataHop(),cnfData.getTaskTable());
// 任务不在列表中
if (task.equals("null")){
System.out.println("find error");
return "error";
}
if (task.equals("start/end")){
return "end";
}
// 啥意思
if(task.equals("distributeProcess")){
return "distributeProcess";
}
// 传输当前任务名及待处理图片,返回节点执行状态
String status = picService.setPicOrigin(task, cnfData.getPicture());
switch (status) {
case "sucess":
//正义执行
return "pathComputing";
case "wait":
//等待执行
return "wait";
case "error":
//报错
return "error";
}
}
//转发节点
else {
return "pass";
}
return "i dont know what error";
}
/**
* 装包
*/
@Override
public LinkedList<CnfData> packageData(CnfData cnfData) {
LinkedList<CnfData> newData = new LinkedList<>();
//找到路由
String[] route = findService.findRoute(cnfData.getCurrentSataHop(), cnfData.getRoute());
CnfData newDataPackage = cnfData;
//设置下一跳地址
newDataPackage.setNextSataHop(findService.findNextHop(newDataPackage.getDestinSataHop(), route));
//设置本机地址
newDataPackage.setCurrentSataHop(newDataPackage.getNextSataHop());
//设置下一跳ip地址
String nextIP = findService.findIp(newDataPackage.getNextSataHop(),newDataPackage.getIpPool());
newDataPackage.setNextIPHop(nextIP);
newData.add(newDataPackage);
return newData;
}
@Override
public LinkedList<CnfData> packageData(CnfData cnfData, LinkedList<Picture> pictures) {
LinkedList<CnfData> newData = new LinkedList<>();
//找到路由
String[] route = findService.findRoute(cnfData.getCurrentSataHop(), cnfData.getRoute());
//找到每段的终节点
ArrayList<String> destinSataHops = findService.findDestinSataHops(cnfData.getPathTable(), cnfData.getCurrentSataHop());
for (String destinSataHop : destinSataHops) {
CnfData newDataPackage = new CnfData();
//重新设置
newDataPackage.setEndSateHop(cnfData.getEndSateHop());
newDataPackage.setTaskTable(cnfData.getTaskTable());
newDataPackage.setRoute(cnfData.getRoute());
newDataPackage.setPathTable(cnfData.getPathTable());
newDataPackage.setIpPool(cnfData.getIpPool() );
//设置目的地址
newDataPackage.setDestinSataHop(destinSataHop);
//设置下一跳地址
newDataPackage.setNextSataHop(findService.findNextHop(destinSataHop, route));
//设置本机地址
newDataPackage.setCurrentSataHop(newDataPackage.getNextSataHop());
//设置下一跳ip地址
String nextIP = findService.findIp(newDataPackage.getNextSataHop(),newDataPackage.getIpPool());
newDataPackage.setNextIPHop(nextIP);
//放入图片
newDataPackage.setPicture(pictures.removeFirst());
newData.add(newDataPackage);
}
return newData;
}
@Override
public void backEarth(String message){
String IP = "192.168.31.213" + ":8082";
String res = restTemplate.postForObject("http://" + IP + "/getDate?message=", message, String.class);
System.out.println(res);
}
}
server.port=8083
spring.application.name=app-docker-edge
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>cnf</artifactId>
<groupId>top.ninwoo</groupId>
<version>1.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cnf-pathComp-app</artifactId>
<packaging>pom</packaging>
<modules>
<module>app-docker-api</module>
<module>app-docker-cloud</module>
<module>app-docker-edge</module>
</modules>
</project>
\ No newline at end of file
bishe.app.app-name=joliu bishe.app.app-name=joliu
bishe.app.cloud-url=192.168.31.156:9090 bishe.app.cloud-url=cloud.cnf.org:9091
spring.influx.url=http://192.168.0.108:8086 spring.influx.url=http://192.168.253.130:8086
spring.influx.user=admin spring.influx.user=admin
spring.influx.password=admin spring.influx.password=admin
\ No newline at end of file
...@@ -24,6 +24,7 @@ ...@@ -24,6 +24,7 @@
<module>apps/cnf-path-computing/businessInCloud</module> <module>apps/cnf-path-computing/businessInCloud</module>
<module>apps/cnf-path-computing/sateDeploy</module> <module>apps/cnf-path-computing/sateDeploy</module>
<module>apps/cnf-path-computing/business-api</module> <module>apps/cnf-path-computing/business-api</module>
<module>apps/cnf-pathComp-app</module>
</modules> </modules>
...@@ -167,7 +168,7 @@ ...@@ -167,7 +168,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version> <version>3.6.2</version>
<configuration> <configuration>
<target>8</target> <target>8</target>
<source>8</source> <source>8</source>
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment