提交 d4e48089 authored 作者: chenxinchang's avatar chenxinchang

--no commit message

上级 f25933c2
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>com.zrqx.server</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.genuitec.eclipse.springframework.springbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.genuitec.eclipse.springframework.springnature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
</natures>
</projectDescription>
eclipse.preferences.version=1
encoding//src/main/java=UTF-8
encoding//src/main/resources=UTF-8
encoding//src/test/java=UTF-8
encoding//src/test/resources=UTF-8
encoding/<project>=UTF-8
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.8
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1
<root>
<facet id="me.spring">
<node name="libprov">
<attribute name="provider-id" value="spring-no-op-library-provider"/>
</node>
</facet>
</root>
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<installed facet="java" version="1.8"/>
<installed facet="me.spring" version="4.1"/>
</faceted-project>
<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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zrqx.server</groupId>
<artifactId>com.zrqx.server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- 继承默认值为Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
</parent>
<!-- 添加Web应用程序的典型依赖项 -->
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
</dependency>
<dependency>
<groupId>org.jyaml</groupId>
<artifactId>jyaml</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.graphql-java/graphql-java -->
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java</artifactId>
<version>2018-12-21T21-00-05-9a6abf2</version>
</dependency>
</dependencies>
<!-- 作为可执行jar的包 -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<!-- 添加Spring存储库 -->
<!-- (如果您使用的是.RELEASE版本,则不需要这样) -->
<!-- <repositories> <repository> <id>spring-snapshots</id> <url>https://repo.spring.io/snapshot</url>
<snapshots><enabled>true</enabled></snapshots> </repository> <repository>
<id>spring-milestones</id> <url>https://repo.spring.io/milestone</url> </repository>
</repositories> <pluginRepositories> <pluginRepository> <id>spring-snapshots</id>
<url>https://repo.spring.io/snapshot</url> </pluginRepository> <pluginRepository>
<id>spring-milestones</id> <url>https://repo.spring.io/milestone</url> </pluginRepository>
</pluginRepositories> -->
</project>
\ No newline at end of file
package com.zrqx.server;
import org.slf4j.*;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
@SpringBootApplication
public class ServerStart {
private final static Logger logger = LoggerFactory.getLogger(ServerStart.class);
public static void main(String[] args) {
SpringApplication.run(ServerStart.class, args);
logger.info("server服务启动完成。");
}
}
package com.zrqx.server.controller;
import java.io.IOException;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zrqx.server.utils.WebSocketServer;
@RestController
@RequestMapping("/checkcenter")
public class CheckCenterController {
//推送数据接口
@RequestMapping("/socket/push/{cid}")
public String pushToWeb(@PathVariable String cid,String message) {
try {
WebSocketServer.sendInfo(message,cid);
} catch (IOException e) {
e.printStackTrace();
return cid+"#"+e.getMessage();
}
return cid;
}
}
package com.zrqx.server.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.zrqx.server.data.DataBase;
import com.zrqx.server.data.Jar;
import com.zrqx.server.utils.FileUtil;
import com.zrqx.server.utils.JsonUtil;
import com.zrqx.server.utils.Shell;
@RestController
@RequestMapping("/jar")
public class JarController {
private final static Logger logger = LoggerFactory.getLogger(JarController.class);
@PostMapping("/add")
public String add(@RequestParam("jar") MultipartFile file,
@RequestParam String serverName,
@RequestParam String conf,
@RequestParam String path,
@RequestParam Integer port) throws Exception{
Jar jar = new Jar(serverName,file.getOriginalFilename(),conf,path, port);
FileUtil.read(file.getInputStream(), FileUtil.createFilePath(path+"/"+jar.getJarName()));
Shell.sh(jar);
DataBase.getInstanceSystem(DataBase.JAR).put(jar.getServerName(), JsonUtil.bean2Json(jar));
logger.info("新增服务"+jar);
return "success";
}
@GetMapping("/download")
public void download(HttpServletRequest request, HttpServletResponse response) throws IOException, BackingStoreException{
DataBase.getInstanceSystem(DataBase.JAR).exportNode(response.getOutputStream());
}
@GetMapping("/delete")
public void delete(String key){
DataBase.getInstanceSystem(DataBase.JAR).remove(key);
}
@GetMapping("/getList")
public List<Jar> getList() throws JsonParseException, JsonMappingException, IOException{
Preferences prefs = DataBase.getInstanceSystem(DataBase.JAR);
String[] keys = null;
try {
keys = prefs.keys();
} catch (BackingStoreException e) {
logger.debug(e.getMessage());
e.printStackTrace();
}
//List<Jar> jarList = new ArrayList<Jar>();
List<Jar> jarList = new ArrayList<Jar>();
for (String key : keys) {
logger.debug(key);
jarList.add(JsonUtil.json2Bean(prefs.get(key, "未找到"), Jar.class));
}
logger.debug("return jarList");
return jarList;
}
@GetMapping("/start/{key}")
public String start(@PathVariable("key")String key) throws Exception{
String jarInfo = DataBase.getInstanceSystem(DataBase.JAR).get(key,null);
if(null == jarInfo){
return "未找到";
}
Jar jar = JsonUtil.json2Bean(jarInfo, Jar.class);
return Shell.into("sh start.sh", jar.getPath(), "<br/>");
}
@GetMapping("/stop/{key}")
public String stop(@PathVariable("key")String key) throws Exception{
String jarInfo = DataBase.getInstanceSystem(DataBase.JAR).get(key,null);
if(null == jarInfo){
return "未找到";
}
Jar jar = JsonUtil.json2Bean(jarInfo, Jar.class);
return Shell.into("sh stop.sh", jar.getPath(), "<br/>");
}
}
package com.zrqx.server.controller;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zrqx.server.data.DataBase;
import com.zrqx.server.data.Sh;
import com.zrqx.server.utils.JsonUtil;
import com.zrqx.server.utils.Shell;
@RestController
@RequestMapping("/sh")
public class ShController {
private final static Logger logger = LoggerFactory.getLogger(ShController.class);
@PostMapping("/addItem")
public String add(@RequestBody Sh sh) throws Exception{
File shFile = new File(sh.getPath()+"/"+sh.getName());
shFile.mkdirs();
//SVN拉去项目
Shell.svn(sh);
//创建shell脚本
Shell.sh(sh);
DataBase.getInstanceSystem(DataBase.SH).put(sh.getName(), JsonUtil.bean2Json(sh));
logger.info("新增服务"+sh);
return "SUCCESS";
}
@GetMapping("/download")
public void download(HttpServletRequest request, HttpServletResponse response) throws IOException, BackingStoreException{
DataBase.getInstanceSystem(DataBase.SH).exportNode(response.getOutputStream());
}
@GetMapping("/delete")
public void delete(String key){
DataBase.getInstanceSystem(DataBase.SH).remove(key);
}
@GetMapping("/getList")
public List<Sh> getList() throws Exception{
Preferences prefs = DataBase.getInstanceSystem(DataBase.SH);
String [] keys = prefs.keys();
List<Sh> shList = new ArrayList<Sh>();
for (String key : keys) {
logger.debug(key);
shList.add(JsonUtil.json2Bean(prefs.get(key, "未找到"), Sh.class));
}
logger.debug("return shList");
return shList;
}
@GetMapping("/shell/{name}/{shell}")
public String start(@PathVariable("name")String name,@PathVariable("shell")String shell) throws Exception{
Preferences prefs = DataBase.getInstanceSystem(DataBase.SH);
String [] keys = prefs.keys();
for (String key : keys) {
if(key.equals(name)) {
Sh sh = JsonUtil.json2Bean(prefs.get(key, "未找到"), Sh.class);
return Shell.into("sh "+ sh.getPath()+"/"+sh.getName()+"/" +shell, null, "<br/>");
}
}
return "未执行任何脚本";
}
}
package com.zrqx.server.data;
import java.util.prefs.Preferences;
public class DataBase {
public static final String JAR = "jar";
public static final String SH = "sh";
private DataBase() {}
public static Preferences getInstanceUser(String node) {
return Preferences.userRoot().node(node);
}
public static Preferences getInstanceSystem(String node) {
return Preferences.systemRoot().node(node);
}
}
package com.zrqx.server.data;
import lombok.*;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Jar {
//服务名称
private String serverName;
//jar名称
private String jarName;
//启动配置
private String conf;
//存储路径
private String path;
//服务端口
private Integer port;
}
package com.zrqx.server.data;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Sh {
//服务名称
private String serverName;
//jar名称
private String jarName;
//启动配置
private String conf;
//存储路径
private String path;
//svn仓库地址
private String address;
//项目名称
private String name;
//项目依赖
private String coreName;
//服务端口
private Integer port;
private List<Sh> shList;
}
package com.zrqx.server.form;
import graphql.ExecutionResult;
import graphql.GraphQL;
import graphql.schema.GraphQLSchema;
import graphql.schema.StaticDataFetcher;
import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
public class HelloWorld {
public static void main(String[] args) {
String schema = "type Query{hello: String} schema{query: Query}";
SchemaParser schemaParser = new SchemaParser();
TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);
RuntimeWiring runtimeWiring = RuntimeWiring.newRuntimeWiring()
.type("Query", builder -> builder.dataFetcher("hello", new StaticDataFetcher("world")))
.build();
SchemaGenerator schemaGenerator = new SchemaGenerator();
GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);
GraphQL build = GraphQL.newGraphQL(graphQLSchema).build();
ExecutionResult executionResult = build.execute("{hello}");
System.out.println(executionResult.getData().toString());
// Prints: {hello=world}
}
}
\ No newline at end of file
package com.zrqx.server.utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileUtil {
private final static Logger logger = LoggerFactory.getLogger(FileUtil.class);
/**
* 默认每次读取长度
*/
private static final int length = 2 * 1024;
public static File createFilePath(String filePath){
File file = new File(filePath);
File path = file.getParentFile();
if (!path.exists()) {
path.mkdirs();
}
/*try {
file.createNewFile();
} catch (IOException e) {
logger.info("文件创建失败!");
e.printStackTrace();
}*/
return file;
}
public static File createPath(String path){
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
return file;
}
public static void main(String[] args) {
createFilePath("e:/1233/1223.txt");
}
/**
* 读文件
* @param out 文件输出流
* @param file 要读取的文件
* length 默认 2 * 1024
* @throws Exception
*/
public static void write(OutputStream out, File file) throws Exception {
write(out, file, length);
}
/**
* 读文件
* @param out 文件输出流
* @param file 要读取的文件
* @param length 每次读取长度
* @throws Exception
*/
public static void write(OutputStream out, File file, int length) throws Exception {
byte[] buffer = new byte[length];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
// 文件输入流
bis = new BufferedInputStream(fis);
// 输出流
while (-1 != bis.read(buffer)) {
out.write(buffer);
}
} catch (Exception e) {
logger.error("读取异常:" + e);
e.printStackTrace();
throw new Exception("文件读取失败!");
} finally {
try {
if (null != fis)
fis.close();
if (null != bis)
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 写文件
* @param in 文件输入流
* @param file 要写入的文件
* @param length 每次读取长度
* @throws Exception
*/
public static void read(InputStream in, File file, int length) throws Exception {
byte[] buffer = new byte[length];
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
while (-1 != in.read(buffer)) {
bos.write(buffer);
}
} catch (Exception e) {
logger.error("写入异常:" + e);
e.printStackTrace();
throw new Exception("文件写入失败!");
} finally {
try {
if (null != fos)
fos.flush();
if (null != bos)
bos.close();
} catch (IOException e) {
}
}
}
/**
* 写文件
* @param in 文件输入流
* @param file 要写入的文件
* length 默认 2 * 1024
* @throws Exception
*/
public static void read(InputStream in, File file) throws Exception {
read(in, file,length);
}
}
package com.zrqx.server.utils;
import java.io.IOException;
import java.io.StringWriter;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtil {
private static ObjectMapper mapper = new ObjectMapper();
@SuppressWarnings("deprecation")
public static String bean2Json(Object obj) throws IOException {
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
mapper.writeValue(gen, obj);
gen.close();
return sw.toString();
}
public static <T> T json2Bean(String jsonStr, Class<T> objClass)
throws JsonParseException, JsonMappingException, IOException {
return mapper.readValue(jsonStr, objClass);
}
}
package com.zrqx.server.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.dom4j.Element;
import org.ho.yaml.Yaml;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zrqx.server.data.Jar;
import com.zrqx.server.data.Sh;
public class Shell {
private final static Logger logger = LoggerFactory.getLogger(Shell.class);
private static String CHMOD777 = "chmod 777 ";
/*
* private static String PATH = "/root/test"; public static String SYSUSER =
* PATH + "/sys.sh";
*/
public static String into(String shell, String dir, String huanhang) {
logger.debug("执行 目录: " + dir + " shell:" + shell);
StringBuffer sb = new StringBuffer();
File file = null;
if (null != dir) {
file = FileUtil.createPath(dir);
}
try {
Process ps = Runtime.getRuntime().exec(shell, null, file);
int status = ps.waitFor();
if (status == 1) {
sb.append("权限不够 自动赋权重新执行" + CHMOD777);
String newShell = CHMOD777 + shell;
Runtime.getRuntime().exec(newShell, null, file);
logger.debug("执行 目录: " + dir + " 赋权shell:" + newShell);
ps = Runtime.getRuntime().exec(shell, null, file);
logger.debug("执行 目录: " + dir + " shell:" + shell);
}
if (status == 2) {
sb.append("文件或目录不存在");
return sb.toString();
}
if (ps.waitFor() != 0) {
sb.append("执行结果:" + ps.waitFor() + " " + read(ps.getInputStream(), "\n"));
} else {
sb.append(read(ps.getInputStream(), huanhang));
}
logger.debug(sb.toString());
} catch (Exception e) {
sb.append(shell).append("执行异常:" + e.getMessage()).append("\n");
logger.info(sb.toString());
e.printStackTrace();
}
return sb.toString();
}
public static String into(String shell) {
return into(shell, null, null);
}
private static StringBuffer read(InputStream in, String huanhang) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
if (null != huanhang) {
sb.append(huanhang);
}
}
return sb;
}
public static String getPid(int port) throws Exception {
String shell = "netstat -nlp | grep :" + port + " | awk '{print $7}' | awk -F'/' '{print $1}';";
String pid = into(shell).toString();
return pid;
}
public static String kill(String pid) throws Exception {
String shell = "kill -9 " + pid;
String code = into(shell).toString();
return code;
}
public static String restart(Jar jar) throws Exception {
String pid = Shell.getPid(jar.getPort());
if (null != pid && !pid.equals("")) {
Shell.kill(pid);
}
String shpath = "nohup java -jar " + jar.getConf() + " " + jar.getPath() + jar.getJarName() + " > "
+ jar.getServerName() + ".log &";
return Shell.into(shpath);
}
public static void svn(Sh sh) throws IOException {
String svncosh = sh.getPath() + "/"+sh.getName()+"-svnco.sh";
PrintWriter svnco = new PrintWriter(new FileWriter(svncosh));
svnco.println("svn co " + sh.getAddress() +" "+ sh.getPath()+"/"+sh.getName());
svnco.close();
String info = Shell.into("sh "+svncosh);
logger.info(info);
}
public static void sh(Sh sh) throws Exception {
File shFile = new File(sh.getPath()+"/"+sh.getName());
File[] fileList = shFile.listFiles();
List<Sh> shList = new ArrayList<Sh>();
for (int i = 0; i < fileList.length; i++) {
if (fileList[i].isDirectory()) {//判断是否为文件夹
String fileName = fileList[i].getName();
Sh shServer = new Sh();
if(sh.getConf() != null) {
shServer.setConf(sh.getConf());
}else {
shServer.setConf("");
}
shServer.setName(fileName);
if(fileName.equals("com.zrqx.core") || fileName.equals("com.zrqx.pom") || fileName.equals(".svn")) {
continue;
}
if(!fileName.equals("com.zrqx.eureka") && !fileName.equals("config-server") && !fileName.equals("com.zrqx.zuul")) {
shServer.setCoreName("com.zrqx.core");
}
shServer.setPath(sh.getPath()+"/"+sh.getName());
shServer.setServerName(fileName.substring(fileName.lastIndexOf(".")+1));
File dumpFile=new File(sh.getPath()+"/"+sh.getName()+"/"+fileName+"/src/main/resources/bootstrap.yml");
logger.info(fileName);
logger.info(dumpFile.getPath());
Map map =(Map) Yaml.load(dumpFile);
shServer.setPort((Integer)((Map)map.get("server")).get("port"));
logger.info(shServer.toString());
createSH(shServer);
shList.add(shServer);
}
}
sh.setShList(shList);
}
public static void createSH(Sh sh) throws Exception {
PrintWriter start = new PrintWriter(new FileWriter(sh.getPath() + "/"+sh.getServerName()+"-start.sh"));
PrintWriter reset = new PrintWriter(new FileWriter(sh.getPath() + "/"+sh.getServerName()+"-reset.sh"));
PrintWriter stop = new PrintWriter(new FileWriter(sh.getPath() + "/"+sh.getServerName()+"-stop.sh"));
String netstat = "pid=$(netstat -nlp | grep :" + sh.getPort() + " | awk '{print $7}' | awk -F'/' '{print $1}');";
String ifStr = "if [ -n '$pid' ]; then";
String kill = " kill -9 $pid;";
String fiStr = "fi";
String svnUpCore = null;
String mvnInstall = null;
if(null!=sh.getCoreName()&&!"".equals(sh.getCoreName())){
svnUpCore = "svn up " + sh.getPath() + "/" + sh.getCoreName();
mvnInstall = "mvn clean install -f " + sh.getPath() + "/" + sh.getCoreName() + "/pom.xml";
}
String svnUp = "svn up " + sh.getPath() + "/" + sh.getName();
String pom = sh.getPath() + "/" + sh.getName() + "/pom.xml";
String mvnPackage = "mvn clean package -f " + pom;
String jarName = jarName(pom)+".jar";
sh.setJarName(jarName);
String shpath = "nohup java -jar " + sh.getConf() + " " + sh.getPath() + "/" + sh.getName() + "/target/"+ jarName +" >/dev/null 2>&1 &";
stop.println(netstat);
stop.println(ifStr);
stop.println(kill);
stop.println(fiStr);
stop.close();
start.println(netstat);
start.println(ifStr);
start.println(kill);
start.println(fiStr);
start.append(shpath);
start.close();
reset.println(netstat);
reset.println(ifStr);
reset.println(kill);
reset.println(fiStr);
if(null != svnUpCore)
reset.println(svnUpCore);
reset.println(svnUp);
if(null != mvnInstall)
reset.println(mvnInstall);
reset.println(mvnPackage);
reset.append(shpath);
reset.close();
}
/**
*
* @param path
* 服务器存放路径
* @param port
* 服务占用端口
* @param conf
* 服务启动内存配置
* @param jarName
* @throws IOException
*/
public static void sh(Jar jar) throws IOException {
PrintWriter start = new PrintWriter(new FileWriter(jar.getPath() + "/start.sh"));
PrintWriter stop = new PrintWriter(new FileWriter(jar.getPath() + "/stop.sh"));
String netstat = "pid=$(netstat -nlp | grep :" + jar.getPort() + " | awk '{print $7}' | awk -F'/' '{print $1}');";
String ifStr = "if [ -n '$pid' ]; then";
String kill = " kill -9 $pid;";
String fiStr = "fi";
String shpath = "nohup java -jar " + jar.getConf() + " " + jar.getJarName() + " > "+jar.getServerName()+".log 2>&1 &";
stop.println(netstat);
stop.println(ifStr);
stop.println(kill);
stop.println(fiStr);
stop.close();
start.println(netstat);
start.println(ifStr);
start.println(kill);
start.println(fiStr);
start.append(shpath);
start.close();
}
public static String jarName(String pom) throws Exception{
Element node = XmlNodeUtil.getNode(pom);
String artifactId = node.element("artifactId").getText();
String version = null;
Element nodeVersion = node.element("version");
if(null != nodeVersion)
version = nodeVersion.getText();
else
version = node.element("parent").element("version").getText();
String jarName = artifactId+"-"+version;
return jarName+".SNAPSHOT";
}
public static void main(String[] args) throws Exception {
Sh sh = new Sh();
sh.setConf("peizhi");
sh.setName("cs");
sh.setAddress("svn");
sh.setPath("D:/Workspaces");
sh(sh);
}
public static String reset() {
return null;
}
public static String stop() {
return null;
}
}
\ No newline at end of file
package com.zrqx.server.utils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* 开启WebSocket支持
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
package com.zrqx.server.utils;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@ServerEndpoint("/websocket/{sid}")
@Component
public class WebSocketServer {
private final static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//接收sid
private String sid="";
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session,@PathParam("sid") String sid) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
this.sid=sid;
try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("websocket IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("收到来自窗口"+sid+"的信息:"+message);
//群发消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 群发自定义消息
* */
public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException {
log.info("推送消息到窗口"+sid+",推送内容:"+message);
for (WebSocketServer item : webSocketSet) {
try {
//这里可以设定只推送给这个sid的,为null则全部推送
if(sid==null) {
item.sendMessage(message);
}else if(item.sid.equals(sid)){
item.sendMessage(message);
}
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
package com.zrqx.server.utils;
import java.io.File;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class XmlNodeUtil {
public static Element getNode(String path) throws Exception{
// 创建saxReader对象
SAXReader reader = new SAXReader();
// 通过read方法读取一个文件 转换成Document对象
Document document = reader.read(new File(path));
//获取根节点元素对象
Element node = document.getRootElement();
//遍历所有的元素节点
// listNodes(node);
return node;
}
}
server:
port: 6789
spring:
application:
name: server #服务名称
http:
multipart:
max-file-size: 2000M
max-request-size: 2000M
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径 -->
<property name="LOG_HOME" value="/opt/logs" />
<property name="NAME" value="server" />
<!-- 控制台输出 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 -->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<!-- 按照每天生成日志文件 -->
<appender name="FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志文件输出的文件名 -->
<FileNamePattern>${LOG_HOME}/${NAME}/%d{yyyy-MM-dd}.%i.log
</FileNamePattern>
<!--日志文件保留天数 -->
<MaxHistory>30</MaxHistory>
<!--日志文件最大的大小 -->
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 -->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<!-- SQL相关日志输出-->
<logger name="org.mybatis.spring" level="DEBUG" additivity="true" />
<logger name="com.zrqx.server" level="DEBUG" additivity="true" />
<!-- 日志输出级别 -->
<root level="INFO">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
</root>
</configuration>
\ No newline at end of file
<html>
<head>
<title>server list</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="jquery-ui-1.12.1/jquery-ui.min.css" />
<script src="jquery-ui-1.12.1/external/jquery/jquery.js"></script>
<script src="jquery-ui-1.12.1/jquery-ui.min.js"></script>
<script src="js/public.js"></script>
</head>
<body>
<div id="jarInfoList">
<table id="list">
<tr>
<td>服务名</td>
<td>服务jar包</td>
<td>启动内存配置</td>
<td>服务器存储路径</td>
<td>端口</td>
<td>操作</td>
</tr>
</table>
</div>
<div id="item">
</div>
</body>
<script src="js/index.js"></script>
</html>
\ No newline at end of file
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="jquery-ui-1.12.1/jquery-ui.min.css" />
<script src="jquery-ui-1.12.1/external/jquery/jquery.js"></script>
<script src="jquery-ui-1.12.1/jquery-ui.min.js"></script>
<script src="js/public.js"></script>
<title></title>
</head>
<body>
<div id="jarInfo">
<form id="form">
<table>
<tr>
<td>服务名</td>
<td><input id="serverName" name="serverName" /></td>
</tr>
<tr>
<td>服务jar包</td>
<td><input id="jar" name="jar" type="file" /></td>
</tr>
<tr>
<td>启动内存配置</td>
<td><input id="conf" name="conf" /></td>
</tr>
<tr>
<td>服务器存储路径</td>
<td><input id="path" name="path" /></td>
</tr>
<tr>
<td>端口</td>
<td><input id="port" name="port" /></td>
</tr>
<tr>
<td><input type="button" id="commit" value="提交" /></td>
<td><input type="button" id="esc" value="取消" /></td>
</tr>
</table>
</form>
</div>
</body>
<script src="js/jar.js"></script>
</html>
\ No newline at end of file
Copyright jQuery Foundation and other contributors, https://jquery.org/
This software consists of voluntary contributions made by many
individuals. For exact contribution history, see the revision history
available at https://github.com/jquery/jquery-ui
The following license applies to all parts of this software except as
documented below:
====
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
====
Copyright and related rights for sample code are waived via CC0. Sample
code is defined as all source code contained within the demos directory.
CC0: http://creativecommons.org/publicdomain/zero/1.0/
====
All files located in the node_modules and external directories are
externally maintained libraries used by this software which have their
own licenses; we recommend you read them, as their terms may differ from
the terms above.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"name": "jquery-ui",
"title": "jQuery UI",
"description": "A curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library.",
"version": "1.12.1",
"homepage": "http://jqueryui.com",
"author": {
"name": "jQuery Foundation and other contributors",
"url": "https://github.com/jquery/jquery-ui/blob/1.12.1/AUTHORS.txt"
},
"main": "ui/widget.js",
"maintainers": [
{
"name": "Scott González",
"email": "scott.gonzalez@gmail.com",
"url": "http://scottgonzalez.com"
},
{
"name": "Jörn Zaefferer",
"email": "joern.zaefferer@gmail.com",
"url": "http://bassistance.de"
},
{
"name": "Mike Sherov",
"email": "mike.sherov@gmail.com",
"url": "http://mike.sherov.com"
},
{
"name": "TJ VanToll",
"email": "tj.vantoll@gmail.com",
"url": "http://tjvantoll.com"
},
{
"name": "Felix Nagel",
"email": "info@felixnagel.com",
"url": "http://www.felixnagel.com"
},
{
"name": "Alex Schmitz",
"email": "arschmitz@gmail.com",
"url": "https://github.com/arschmitz"
}
],
"repository": {
"type": "git",
"url": "git://github.com/jquery/jquery-ui.git"
},
"bugs": "https://bugs.jqueryui.com/",
"license": "MIT",
"scripts": {
"test": "grunt"
},
"dependencies": {},
"devDependencies": {
"commitplease": "2.3.0",
"grunt": "0.4.5",
"grunt-bowercopy": "1.2.4",
"grunt-cli": "0.1.13",
"grunt-compare-size": "0.4.0",
"grunt-contrib-concat": "0.5.1",
"grunt-contrib-csslint": "0.5.0",
"grunt-contrib-jshint": "0.12.0",
"grunt-contrib-qunit": "1.0.1",
"grunt-contrib-requirejs": "0.4.4",
"grunt-contrib-uglify": "0.11.1",
"grunt-git-authors": "3.1.0",
"grunt-html": "6.0.0",
"grunt-jscs": "2.1.0",
"load-grunt-tasks": "3.4.0",
"rimraf": "2.5.1",
"testswarm": "1.1.0"
},
"keywords": []
}
function getList() {
$.ajax({
url : http+'/jar/getList',
type : 'GET',
dataType:'JSON',
success : function(data) {
for (i = 0; i < data.length; i++) {
var tr = $("<tr></tr>");
var td = "<td></td>"
tr.append($(td).html(data[i].serverName));
tr.append($(td).html(data[i].jarName));
tr.append($(td).html(data[i].conf));
tr.append($(td).html(data[i].path));
tr.append($(td).html(data[i].port));
tr.append($(td).html("<a href='"+http+"/jar/start/" + data[i].serverName + "' target='view_window'>启动</a>"));
tr.append($(td).html("<a href='"+http+"/jar/stop/" + data[i].serverName + "' target='view_window'>关闭</a>"));
$("#list").append(tr);
}
},
error : function(data) {
$.MsgBox.Alert("消息", "查询失败!");
}
});
$.ajax({
url : http+'/sh/getList',
type : 'GET',
dataType:'JSON',
success : function(data) {
for (i = 0; i < data.length; i++) {
var tab = $("<table></table>");
var tr = $("<tr></tr>");
var td = "<td></td>"
tr.append($(td).html(data[i].name));
tr.append($(td).html(data[i].path));
tr.append($(td).html(data[i].address));
tr.append($(td).html("<button onclick='resetSh(\""+data[i].name+"\",\""+data[i].path+"\",\""+data[i].address+"\",\""+(data[i].conf==null?'':data[i].conf)+"\")'>重新生成sh</button>"));
tab.append(tr);
for(g = 0; g < data[i].shList.length; g++) {
var trs = $("<tr></tr>");
trs.append($(td).html(data[i].shList[g].serverName));
trs.append($(td).html(data[i].shList[g].jarName));
trs.append($(td).html(data[i].shList[g].conf));
trs.append($(td).html(data[i].shList[g].path));
trs.append($(td).html(data[i].shList[g].port));
trs.append($(td).html(data[i].shList[g].name));
trs.append($(td).html("<a href='"+http+"/sh/shell/"+data[i].name +"/"+ data[i].shList[g].serverName+"-start.sh' target='view_window'>启动</a>"));
trs.append($(td).html("<a href='"+http+"/sh/shell/"+data[i].name +"/"+ data[i].shList[g].serverName+"-reset.sh' target='view_window'>打包启动</a>"));
trs.append($(td).html("<a href='"+http+"/sh/shell/"+data[i].name +"/"+ data[i].shList[g].serverName+"-stop.sh' target='view_window'>关闭</a>"));
tab.append(trs);
}
$("#item").append(tab);
}
},
error : function(data) {
$.MsgBox.Alert("消息", "查询失败!");
}
});
}
getList();
function resetSh(name,path,address,conf) {
$.ajax({
url : http+'/sh/addItem',
type : 'POST',
contentType:'application/json',
dataType:'JSON',
data : JSON.stringify({"name":name,"path":path,"address":address,"conf":conf}),
success : function(data) {
window.location.reload();
},
error : function(data) {
$.MsgBox.Alert("消息", "添加失败!");
}
});
};
\ No newline at end of file
$("#commit").click(function() {
var formData = new FormData($("#form")[0]);
$.ajax({
url : http+'/jar/add',
type : 'POST',
data : formData,
async : false,
cache : false,
contentType : false,
processData : false,
success : function(data) {
window.location.href=href;
},
error : function(data) {
$.MsgBox.Alert("消息", "添加失败!");
}
});
});
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$("#commit").click(function() {
$.ajax({
url : 'http://192.168.2.231:8704/bg/permissions/login',
type : 'get',
contentType:'application/json',
dataType:'JSON',
crossDomain: true,
xhrFields: {
withCredentials: true
},
data : $('#form').serialize(),
success : function(data) {
$.MsgBox.Alert("消息", data);
},
error : function(data) {
$.MsgBox.Alert("消息", "添加失败!");
}
});
});
$("#commit1").click(function() {
$.ajax({
url : 'http://192.168.2.231:8096/sysuser/bg/permissions/login',
type : 'get',
contentType:'application/json',
dataType:'JSON',
crossDomain: true,
xhrFields: {
withCredentials: true
},
data : $('#form').serialize(),
success : function(data) {
$.MsgBox.Alert("消息", data);
},
error : function(data) {
$.MsgBox.Alert("消息", "添加失败!");
}
});
});
$("#commit2").click(function() {
$.ajax({
url : 'http://192.168.2.231:8096/sysuser/bg/permissions/user',
type : 'get',
contentType:'application/json',
dataType:'JSON',
crossDomain: true,
xhrFields: {
withCredentials: true
},
success : function(data) {
$.MsgBox.Alert("消息", data);
}
});
});
$("#commit3").click(function() {
$.ajax({
url : 'http://192.168.2.231:8096/sysuser/bg/permissions/id',
type : 'get',
contentType:'application/json',
dataType:'JSON',
crossDomain: true,
xhrFields: {
withCredentials: true
},
success : function(data) {
$.MsgBox.Alert("消息", data);
}
});
});
$("#commit4").click(function() {
$.ajax({
url : 'http://192.168.2.231:8096/sysuser/bg/permissions/permissions',
type : 'get',
contentType:'application/json',
dataType:'JSON',
crossDomain: true,
xhrFields: {
withCredentials: true
},
success : function(data) {
$.MsgBox.Alert("消息", data);
}
});
});
\ No newline at end of file
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$("#commit").click(function() {
$.ajax({
url : 'http://192.168.2.29:8704/bg/permissions/login',
type : 'get',
contentType:'application/json',
dataType:'JSON',
crossDomain: true,
xhrFields: {
withCredentials: true
},
data : $('#form').serialize(),
success : function(data) {
$.MsgBox.Alert("消息", data);
},
error : function(data) {
$.MsgBox.Alert("消息", "添加失败!");
}
});
});
$("#commit1").click(function() {
$.ajax({
url : 'http://192.168.2.29:8096/sysuser/bg/permissions/login',
type : 'get',
contentType:'application/json',
dataType:'JSON',
crossDomain: true,
xhrFields: {
withCredentials: true
},
data : $('#form').serialize(),
success : function(data) {
$.MsgBox.Alert("消息", data);
},
error : function(data) {
$.MsgBox.Alert("消息", "添加失败!");
}
});
});
$("#commit2").click(function() {
$.ajax({
url : 'http://192.168.2.29:8096/sysuser/bg/permissions/user',
type : 'get',
contentType:'application/json',
dataType:'JSON',
crossDomain: true,
xhrFields: {
withCredentials: true
},
success : function(data) {
$.MsgBox.Alert("消息", data);
}
});
});
$("#commit3").click(function() {
$.ajax({
url : 'http://192.168.2.29:8096/sysuser/bg/permissions/id',
type : 'get',
contentType:'application/json',
dataType:'JSON',
crossDomain: true,
xhrFields: {
withCredentials: true
},
success : function(data) {
$.MsgBox.Alert("消息", data);
}
});
});
$("#commit4").click(function() {
$.ajax({
url : 'http://192.168.2.231:8096/sysuser/bg/permissions/permissions',
type : 'get',
contentType:'application/json',
dataType:'JSON',
crossDomain: true,
xhrFields: {
withCredentials: true
},
success : function(data) {
$.MsgBox.Alert("消息", data);
}
});
});
\ No newline at end of file
function getIpPort(){
//获取当前网址,如: http://localhost:8080/Tmall/index.jsp
var curWwwPath = window.document.location.href;
//获取主机地址之后的目录如:/Tmall/index.jsp
var pathName = window.document.location.pathname;
var pos = curWwwPath.indexOf(pathName);
//获取主机地址,如: http://localhost:8080
var localhostPaht=curWwwPath.substring(0,pos);
return localhostPaht;
//var index = localhostPaht.lastIndexOf(":");
//var ip = localhostPaht.substring(0,index);
//return ip;
}
var http=getIpPort();
(function() {
$.MsgBox = {
Alert: function(title, msg) {
GenerateHtml("alert", title, msg);
btnOk(); //alert只是弹出消息,因此没必要用到回调函数callback
btnNo();
},
Confirm: function(title, msg, callback) {
GenerateHtml("confirm", title, msg);
btnOk(callback);
btnNo();
}
}
//生成Html
var GenerateHtml = function(type, title, msg) {
var _html = "";
_html += '<div id="mb_box"></div><div id="mb_con"><span id="mb_tit">' + title + '</span>';
_html += '<a id="mb_ico">x</a><div id="mb_msg">' + msg + '</div><div id="mb_btnbox">';
if (type == "alert") {
_html += '<input id="mb_btn_ok" type="button" value="确定" />';
}
if (type == "confirm") {
_html += '<input id="mb_btn_ok" type="button" value="确定" />';
_html += '<input id="mb_btn_no" type="button" value="取消" />';
}
_html += '</div></div>';
//必须先将_html添加到body,再设置Css样式
$("body").append(_html);
//生成Css
GenerateCss();
}
//生成Css
var GenerateCss = function() {
$("#mb_box").css({
width: '100%',
height: '100%',
zIndex: '99999',
position: 'fixed',
filter: 'Alpha(opacity=60)',
backgroundColor: 'black',
top: '0',
left: '0',
opacity: '0.6'
});
$("#mb_con").css({
zIndex: '999999',
width: '400px',
position: 'fixed',
backgroundColor: 'White',
borderRadius: '15px'
});
$("#mb_tit").css({
display: 'block',
fontSize: '14px',
color: '#444',
padding: '10px 15px',
backgroundColor: '#DDD',
borderRadius: '15px 15px 0 0',
borderBottom: '3px solid #009BFE',
fontWeight: 'bold'
});
$("#mb_msg").css({
padding: '20px',
lineHeight: '20px',
borderBottom: '1px dashed #DDD',
fontSize: '13px'
});
$("#mb_ico").css({
display: 'block',
position: 'absolute',
right: '10px',
top: '9px',
border: '1px solid Gray',
width: '18px',
height: '18px',
textAlign: 'center',
lineHeight: '16px',
cursor: 'pointer',
borderRadius: '12px',
fontFamily: '微软雅黑'
});
$("#mb_btnbox").css({
margin: '15px 0 10px 0',
textAlign: 'center'
});
$("#mb_btn_ok,#mb_btn_no").css({
width: '85px',
height: '30px',
color: 'white',
border: 'none'
});
$("#mb_btn_ok").css({
backgroundColor: '#168bbb'
});
$("#mb_btn_no").css({
backgroundColor: 'gray',
marginLeft: '20px'
});
//右上角关闭按钮hover样式
$("#mb_ico").hover(function() {
$(this).css({
backgroundColor: 'Red',
color: 'White'
});
}, function() {
$(this).css({
backgroundColor: '#DDD',
color: 'black'
});
});
var _widht = document.documentElement.clientWidth; //屏幕宽
var _height = document.documentElement.clientHeight; //屏幕高
var boxWidth = $("#mb_con").width();
var boxHeight = $("#mb_con").height();
//让提示框居中
$("#mb_con").css({
top: (_height - boxHeight) / 2 + "px",
left: (_widht - boxWidth) / 2 + "px"
});
}
//确定按钮事件
var btnOk = function(callback) {
$("#mb_btn_ok").click(function() {
$("#mb_box,#mb_con").remove();
if (typeof(callback) == 'function') {
callback();
}
});
}
//取消按钮事件
var btnNo = function() {
$("#mb_btn_no,#mb_ico").click(function() {
$("#mb_box,#mb_con").remove();
});
}
})();
\ No newline at end of file
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$("#commit").click(function() {
$.ajax({
url : http+'/sh/addItem',
type : 'POST',
contentType:'application/json',
dataType:'JSON',
data : JSON.stringify($('#form').serializeObject()),
success : function(data) {
window.location.href=href+"/sh/index.html";
},
error : function(data) {
$.MsgBox.Alert("消息", "添加失败!");
}
});
});
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="jquery-ui-1.12.1/jquery-ui.min.css" />
<script src="jquery-ui-1.12.1/external/jquery/jquery.js"></script>
<script src="jquery-ui-1.12.1/jquery-ui.min.js"></script>
<script src="js/public.js"></script>
<title></title>
</head>
<body>
<div id="jarInfo">
<form id="form">
<table>
<tr>
<td>账号</td>
<td><input name="name" /></td>
</tr>
<tr>
<td>密码</td>
<td><input name="password" /></td>
</tr>
<tr>
<td><input type="button" id="commit" value="登录" /></td>
<td><input type="button" id="commit1" value="登录1" /></td>
<td><input type="button" id="commit2" value="getUser" /></td>
<td><input type="button" id="commit3" value="getSessionId" /></td>
<td><input type="button" id="commit4" value="get" /></td>
<td><input type="button" id="esc" value="取消" /></td>
</tr>
</table>
</form>
</div>
</body>
<script src="js/login.js"></script>
</html>
\ No newline at end of file
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="jquery-ui-1.12.1/jquery-ui.min.css" />
<script src="jquery-ui-1.12.1/external/jquery/jquery.js"></script>
<script src="jquery-ui-1.12.1/jquery-ui.min.js"></script>
<script src="js/public.js"></script>
<title></title>
</head>
<body>
<div id="jarInfo">
<form id="form">
<table>
<tr>
<td>账号</td>
<td><input name="name" /></td>
</tr>
<tr>
<td>密码</td>
<td><input name="password" /></td>
</tr>
<tr>
<td><input type="button" id="commit" value="登录" /></td>
<td><input type="button" id="commit1" value="登录1" /></td>
<td><input type="button" id="commit2" value="getUser" /></td>
<td><input type="button" id="commit3" value="getSessionId" /></td>
<td><input type="button" id="commit4" value="get" /></td>
<td><input type="button" id="esc" value="取消" /></td>
</tr>
</table>
</form>
</div>
</body>
<script src="js/login2.js"></script>
</html>
\ No newline at end of file
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="jquery-ui-1.12.1/jquery-ui.min.css" />
<script src="jquery-ui-1.12.1/external/jquery/jquery.js"></script>
<script src="jquery-ui-1.12.1/jquery-ui.min.js"></script>
<script src="js/public.js"></script>
<title></title>
</head>
<body>
<div id="jarInfo">
<form id="form">
<table>
<tr>
<td>项目名</td>
<td><input name="name" /></td>
</tr>
<tr>
<td>SVN仓库地址</td>
<td><input name="address" /></td>
</tr>
<tr>
<td>服务器存储路径</td>
<td><input name="path" /></td>
</tr>
<tr>
<td><input type="button" id="commit" value="提交" /></td>
<td><input type="button" id="esc" value="取消" /></td>
</tr>
</table>
</form>
</div>
</body>
<script src="js/sh.js"></script>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="jquery-ui-1.12.1/external/jquery/jquery.js"></script>
<script>
if (typeof (WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
console.log("您的浏览器支持WebSocket");
}
var socket;
function login() {
loginId = $('#sendId').val();
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
//等同于socket = new WebSocket("ws://localhost:8083/checkcentersys/websocket/20");
socket = new WebSocket("ws://192.168.2.23:6789/websocket/" + loginId);
//打开事件
socket.onopen = function() {
console.log("Socket 已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function(msg) {
$('#info').val($('#info').val()+"\r"+msg.data);
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
socket.onclose = function() {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function() {
alert("Socket发生了错误");
//此时可以尝试刷新页面
}
//离开页面时,关闭socket
//jquery1.8中已经被废弃,3.0中已经移除
// $(window).unload(function(){
// socket.close();
//});
}
function sendMessage() {
sendId = $('#sendId').val();
message = $('#message').val();
socket.send("sendId:"+sendId+",这是来自客户端的消息" + message );
};
</script>
</head>
<body>
登录id<input id="sendId" />
<input type="button" id="login" value="登录" onclick="login()"/>
发送内容<input type="text" id="message" />
<input type="button" id="send" value="发送" onclick="sendMessage()"/><br>
<textarea id="info" rows="30" cols="100"></textarea>
</body>
</html>
\ No newline at end of file
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论