diff --git a/HelloAnnotation/db.sqlite3 b/HelloAnnotation/db.sqlite3 deleted file mode 100644 index 518cec9..0000000 Binary files a/HelloAnnotation/db.sqlite3 and /dev/null differ diff --git a/HelloAnnotation/hello_annotation.postman_collection.json b/HelloAnnotation/postman/hello_annotation.postman_collection.json similarity index 100% rename from HelloAnnotation/hello_annotation.postman_collection.json rename to HelloAnnotation/postman/hello_annotation.postman_collection.json diff --git a/HelloAudio/pom.xml b/HelloAudio/pom.xml index 4e804a1..d0e3504 100644 --- a/HelloAudio/pom.xml +++ b/HelloAudio/pom.xml @@ -21,33 +21,11 @@ - - org.apache.commons - commons-collections4 - 4.4 - org.apache.commons commons-lang3 3.7 - - com.alibaba - fastjson - 1.2.60 - - - - - org.apache.httpcomponents - httpclient - 4.5.2 - - - org.apache.httpcomponents - httpmime - 4.5 - junit @@ -55,16 +33,6 @@ 4.11 test - - org.slf4j - slf4j-api - 1.7.7 - - - org.slf4j - slf4j-log4j12 - 1.7.7 - diff --git a/HelloAudio/rec.wav b/HelloAudio/rec.wav deleted file mode 100644 index 57b2871..0000000 Binary files a/HelloAudio/rec.wav and /dev/null differ diff --git a/HelloAudio/src/main/java/com/hello/App.java b/HelloAudio/src/main/java/com/hello/App.java index 4ecff3e..aa3818d 100644 --- a/HelloAudio/src/main/java/com/hello/App.java +++ b/HelloAudio/src/main/java/com/hello/App.java @@ -1,6 +1,5 @@ package com.hello; -import com.hello.audio.ChatUtil; import com.hello.audio.RecordHelper; import com.hello.audio.TimeListener; @@ -11,7 +10,7 @@ public class App { public static void main(String[] args) { // create frame - final JFrame frame = new JFrame("Walle"); + final JFrame frame = new JFrame("Audio"); frame.setSize(300, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); @@ -24,7 +23,7 @@ public static void main(String[] args) { // Create buttons final long msDuration = 5000; - final String title = "AI语音聊天"; + final String title = "Record"; final JButton recordBtn = new JButton(title); recordBtn.addActionListener(new ActionListener() { @Override @@ -41,7 +40,7 @@ public void timeUpdated(long seconds) { @Override public void stopped(long seconds) { recordBtn.setText(title); - ChatUtil.chat(); + recordHelper.play(); } }, msDuration); } diff --git a/HelloAudio/src/main/java/com/hello/audio/ChatUtil.java b/HelloAudio/src/main/java/com/hello/audio/ChatUtil.java deleted file mode 100644 index 7c2e4e7..0000000 --- a/HelloAudio/src/main/java/com/hello/audio/ChatUtil.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.hello.audio; - -import com.hello.http.HttpUtil; -import com.hello.http.RespData; -import com.hello.util.B64Util; - -import java.io.ByteArrayOutputStream; -import java.util.HashMap; - -public class ChatUtil { - public static void chat() { - RecordHelper recordHelper = RecordHelper.getInst(); - final ByteArrayOutputStream data = recordHelper.save(new ByteArrayOutputStream()); - - RespData resp = new RespData(); - byte[] ret = HttpUtil.sendHttpPost( - "http://localhost:8011/speech/walle", - null, new HashMap() {{ - put("size", data.size()); - put("format", "wav"); - put("audio", B64Util.encode(data.toByteArray())); - }}, resp - ); - System.out.printf("%s, %s, %s, %d, %d\n", - resp.getContentType(), resp.getFileName(), resp.getFileExt(), - resp.getContentLength(), ret == null ? 0 : ret.length - ); - - if (ret != null && ret.length > 0) { - Player.asyncPlay(ret); - } else { - // 播放自己的声音吧 - recordHelper.play(); - } - } -} diff --git a/HelloAudio/src/main/java/com/hello/http/HttpUtil.java b/HelloAudio/src/main/java/com/hello/http/HttpUtil.java deleted file mode 100644 index c336d08..0000000 --- a/HelloAudio/src/main/java/com/hello/http/HttpUtil.java +++ /dev/null @@ -1,247 +0,0 @@ -package com.hello.http; - -import com.hello.util.JsonUtil; -import com.hello.util.LogUtil; -import com.hello.util.StrUtil; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.collections4.MapUtils; -import org.apache.http.HttpEntity; -import org.apache.http.NameValuePair; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.ResponseHandler; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.socket.PlainConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLContextBuilder; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.entity.mime.MultipartEntityBuilder; -import org.apache.http.entity.mime.content.StringBody; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.message.BasicNameValuePair; - -import java.io.File; -import java.io.IOException; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Map; - -public class HttpUtil { - private static final String CHARSET_UTF_8 = "utf-8"; - private static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded;charset=utf-8"; - private static final String CONTENT_TYPE_JSON = "application/json;charset=utf-8"; - - private static final int MAX_TOTAL = 100; - private static final int MAX_PER_ROUTE = 20; - - private static final int SOCKET_TIMEOUT = 10000; - private static final int CONNECT_TIMEOUT = 10000; - private static final int REQUEST_TIMEOUT = 10000; - - private static PoolingHttpClientConnectionManager connectionPool; - private static RequestConfig requestConfig; - - static { - try { - SSLContextBuilder builder = new SSLContextBuilder(); - builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); - SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); - Registry socketFactoryRegistry = RegistryBuilder.create() - .register("http", PlainConnectionSocketFactory.getSocketFactory()) - .register("https", sslsf) - .build(); - - connectionPool = new PoolingHttpClientConnectionManager(socketFactoryRegistry); - connectionPool.setMaxTotal(MAX_TOTAL); - connectionPool.setDefaultMaxPerRoute(MAX_PER_ROUTE); - } catch (KeyStoreException e) { - e.printStackTrace(); - } catch (KeyManagementException e) { - e.printStackTrace(); - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } - - requestConfig = RequestConfig.custom() - .setSocketTimeout(SOCKET_TIMEOUT) - .setConnectTimeout(CONNECT_TIMEOUT) - .setConnectionRequestTimeout(REQUEST_TIMEOUT) - .build(); - } - - private static CloseableHttpClient getHttpClient() { - return HttpClients.custom() - .setConnectionManager(connectionPool) - .setDefaultRequestConfig(requestConfig) - .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)) - .build(); - } - - private static T sendHttpRequest(HttpRequestBase httpRequest, ResponseHandler handler) { - try { - return getHttpClient().execute(httpRequest, handler); - } catch (ClientProtocolException e) { - LogUtil.error("Error when sendHttpRequest", e.getMessage()); - } catch (IOException e) { - LogUtil.error("Error when sendHttpRequest", e.getMessage()); - } - return null; - } - - public static T sendHttpGet(String httpUrl, ResponseHandler handler) { - HttpGet httpGet = new HttpGet(httpUrl); - return sendHttpRequest(httpGet, handler); - } - - public static String sendHttpGet(String httpUrl) { - return sendHttpGet(httpUrl, new RespStr()); - } - - public static T sendHttpGet(String httpUrl, Map headers, ResponseHandler handler) { - HttpGet httpGet = new HttpGet(httpUrl); - fillHeaders(httpGet, headers); - return sendHttpRequest(httpGet, handler); - } - - public static String sendHttpGet(String httpUrl, Map headers) { - HttpGet httpGet = new HttpGet(httpUrl); - fillHeaders(httpGet, headers); - return sendHttpRequest(httpGet, new RespStr()); - } - - public static T sendHttpGet(String httpUrl, Map headers, Map params, ResponseHandler handler) { - if (!MapUtils.isEmpty(params)) { - List paramList = new ArrayList(); - for (Map.Entry param : params.entrySet()) { - Object value = param.getValue(); - if (value != null) { - paramList.add(String.format("%s=%s", param.getKey(), UrlUtil.encode(String.valueOf(value)))); - } - } - - String paramStr = StrUtil.join(paramList, "&"); - httpUrl = String.format("%s%s%s", httpUrl, httpUrl.indexOf("?") > 0 ? "&" : "?", paramStr); - } - return sendHttpGet(httpUrl, headers, handler); - } - - public static String sendHttpGet(String httpUrl, Map headers, Map params) { - return sendHttpGet(httpUrl, headers, params, new RespStr()); - } - - public static T sendHttpPost(String httpUrl, Map headers, Map params, ResponseHandler handler) { - HttpPost httpPost = new HttpPost(httpUrl); - fillHeaders(httpPost, headers); - - if (!MapUtils.isEmpty(params)) { - String jsonStr = JsonUtil.toStr(params); - StringEntity stringEntity = new StringEntity(jsonStr, "UTF-8"); - stringEntity.setContentType(CONTENT_TYPE_JSON); - httpPost.setEntity(stringEntity); - } - return sendHttpRequest(httpPost, handler); - } - - public static String sendHttpPost(String httpUrl, Map headers, Map params) { - return sendHttpPost(httpUrl, headers, params, new RespStr()); - } - - public static T sendHttpPost(String httpUrl, Map headers, Map params, File file, ResponseHandler handler) { - File[] files = new File[]{file}; - return sendHttpPost(httpUrl, headers, params, Arrays.asList(files), handler); - } - - public static T sendHttpPost(String httpUrl, Map headers, Map params, Collection files, ResponseHandler handler) { - HttpPost httpPost = new HttpPost(httpUrl); - fillHeaders(httpPost, headers); - - MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create(); - if (!MapUtils.isEmpty(params)) { - for (String key : params.keySet()) { - Object value = params.get(key); - if (value != null) { - meBuilder.addPart(key, new StringBody(String.valueOf(value), ContentType.TEXT_PLAIN)); - } - } - } - - if (!CollectionUtils.isEmpty(files)) { - for (File file : files) { - meBuilder.addBinaryBody("file", file); - } - } - - HttpEntity reqEntity = meBuilder.build(); - httpPost.setEntity(reqEntity); - return sendHttpRequest(httpPost, handler); - } - - public static T sendHttpForm(String httpUrl, Map headers, Map params, ResponseHandler handler) { - HttpPost httpPost = new HttpPost(httpUrl); - fillHeaders(httpPost, headers); - - if (!MapUtils.isEmpty(params)) { - List pairs = new ArrayList(params.size()); - for (Map.Entry param : params.entrySet()) { - Object value = param.getValue(); - if (value != null) { - pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(value))); - } - } - - try { - httpPost.setEntity(new UrlEncodedFormEntity(pairs)); - } catch (Exception e) { - LogUtil.error("Error when sendHttpSubmit", e.getMessage()); - } - } - return sendHttpRequest(httpPost, handler); - } - - public static T sendHttpPut(String httpUrl, Map headers, Map params, ResponseHandler handler) { - HttpPut httpPut = new HttpPut(httpUrl); - fillHeaders(httpPut, headers); - - if (!MapUtils.isEmpty(params)) { - String jsonStr = JsonUtil.toStr(params); - StringEntity stringEntity = new StringEntity(jsonStr, "UTF-8"); - stringEntity.setContentType(CONTENT_TYPE_JSON); - httpPut.setEntity(stringEntity); - } - return sendHttpRequest(httpPut, handler); - } - - public static T sendHttpDelete(String httpUrl, Map headers, ResponseHandler handler) { - HttpDelete httpDelete = new HttpDelete(httpUrl); - fillHeaders(httpDelete, headers); - return sendHttpRequest(httpDelete, handler); - } - - private static void fillHeaders(HttpRequestBase request, Map headers) { - if (request == null || MapUtils.isEmpty(headers)) { - return; - } - - for (Map.Entry header : headers.entrySet()) { - request.addHeader(header.getKey(), header.getValue()); - } - } -} diff --git a/HelloAudio/src/main/java/com/hello/http/RespData.java b/HelloAudio/src/main/java/com/hello/http/RespData.java deleted file mode 100644 index 69d4eb3..0000000 --- a/HelloAudio/src/main/java/com/hello/http/RespData.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.hello.http; - -import com.hello.util.LogUtil; -import com.hello.util.StrUtil; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.ResponseHandler; -import org.apache.http.util.EntityUtils; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - -public class RespData implements ResponseHandler { - private byte[] bytes; - private String fileName; - private String fileExt; - private String contentType; - private String contentLength; - - public byte[] getBytes() { - return bytes; - } - - public String getFileName() { - return fileName; - } - - public String getFileExt() { - return fileExt; - } - - public String getContentType() { - return contentType; - } - - public int getContentLength() { - return StrUtil.isEmpty(contentLength) ? 0 : Integer.valueOf(contentLength); - } - - public String saveFile(String filePath) { - if (StrUtil.isEmpty(filePath)) { - filePath = fileName; - } - if (StrUtil.isEmpty(filePath) || bytes == null || bytes.length <= 0) { - return null; - } - - // Check path - File file = new File(filePath); - String fileName = file.getName(); - filePath = file.getParent(); - - file = new File(filePath == null ? "tmp" : filePath); - if (!file.exists() && !file.mkdirs()) { - return null; - } - - // Write to disc - Path path = Paths.get(file.getPath(), fileName); - try { - Files.write(path, bytes); - } catch (IOException e) { - LogUtil.error("Fail to save file: %s, %s\n", path.toString(), e.getMessage()); - return null; - } - return path.toString(); - } - - private String getHeader(HttpResponse response, String header) { - return response.containsHeader(header) ? response.getFirstHeader(header).getValue() : null; - } - - @Override - public byte[] handleResponse(HttpResponse response) throws IOException { - // 判断响应状态 - if (response.getStatusLine().getStatusCode() >= 300) { - throw new IOException("HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode()); - } - - // 读取文件名称,Header: Content-Disposition: attachment;fileName=abc.txt - String disposition = getHeader(response, "Content-Disposition"); - if (!StrUtil.isEmpty(disposition) && disposition.contains("=")) { - fileName = disposition.split("=")[1]; - } - - // 读取ContentType: audio/mp3 - contentType = getHeader(response, "Content-Type"); - if (!StrUtil.isEmpty(contentType) && contentType.contains("/")) { - fileExt = contentType.split("/")[1]; - } - - contentLength = getHeader(response, "Content-Length"); - - // 读取返回内容 - HttpEntity entity = response.getEntity(); - if (entity == null) { - throw new ClientProtocolException("Response contains no content"); - } - - bytes = EntityUtils.toByteArray(entity); - return bytes; - } -} diff --git a/HelloAudio/src/main/java/com/hello/http/RespJsonObj.java b/HelloAudio/src/main/java/com/hello/http/RespJsonObj.java deleted file mode 100644 index 44fc5ff..0000000 --- a/HelloAudio/src/main/java/com/hello/http/RespJsonObj.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.hello.http; - -import com.alibaba.fastjson.JSONObject; -import com.hello.util.JsonUtil; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.ResponseHandler; -import org.apache.http.entity.ContentType; -import org.apache.http.util.EntityUtils; - -import java.io.IOException; -import java.nio.charset.Charset; - -public class RespJsonObj implements ResponseHandler { - @Override - public JSONObject handleResponse(HttpResponse resp) throws IOException { - HttpEntity entity = resp.getEntity(); - if (entity == null) { - throw new ClientProtocolException("Response contains no content"); - } - - // read content - ContentType contentType = ContentType.getOrDefault(entity); - Charset charset = contentType.getCharset(); - String jsonStr = EntityUtils.toString(entity, charset == null ? Charset.forName("utf-8") : charset); - - // parse JSON object - return JsonUtil.parseObj(jsonStr); - } -} diff --git a/HelloAudio/src/main/java/com/hello/http/RespStr.java b/HelloAudio/src/main/java/com/hello/http/RespStr.java deleted file mode 100644 index ccaf5ee..0000000 --- a/HelloAudio/src/main/java/com/hello/http/RespStr.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.hello.http; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.ResponseHandler; -import org.apache.http.entity.ContentType; -import org.apache.http.util.EntityUtils; - -import java.io.IOException; -import java.nio.charset.Charset; - -public class RespStr implements ResponseHandler { - @Override - public String handleResponse(HttpResponse httpResponse) throws IOException { - HttpEntity entity = httpResponse.getEntity(); - if (entity == null) { - throw new ClientProtocolException("Response contains no content"); - } - - // 读取返回内容 - ContentType contentType = ContentType.getOrDefault(entity); - Charset charset = contentType.getCharset(); - return EntityUtils.toString(entity, charset == null ? Charset.forName("utf-8") : charset); - } -} diff --git a/HelloAudio/src/main/java/com/hello/http/UrlUtil.java b/HelloAudio/src/main/java/com/hello/http/UrlUtil.java deleted file mode 100644 index 7899028..0000000 --- a/HelloAudio/src/main/java/com/hello/http/UrlUtil.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.hello.http; - -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.net.URLEncoder; - -public class UrlUtil { - public static String encode(String str) { - if (str == null) { - return null; - } - - try { - return URLEncoder.encode(str, "UTF-8"); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - return null; - } - - public static String decode(String str) { - if (str == null) { - return null; - } - - try { - return URLDecoder.decode(str, "UTF-8"); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - return null; - } -} diff --git a/HelloAudio/src/main/java/com/hello/util/B64Util.java b/HelloAudio/src/main/java/com/hello/util/B64Util.java deleted file mode 100644 index 4d9e7b9..0000000 --- a/HelloAudio/src/main/java/com/hello/util/B64Util.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.hello.util; - -import org.apache.commons.codec.binary.Base64; - -import java.io.UnsupportedEncodingException; - -public class B64Util { - public static String encode(String str) { - if (str == null) { - return null; - } - - try { - return encode(str.getBytes("UTF-8")); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - return null; - } - - public static String encode(byte[] bytes) { - return bytes == null ? null : Base64.encodeBase64String(bytes); - } - - public static String decode(String str) { - if (str == null) { - return null; - } - - byte[] bytes = decodeForBytes(str); - try { - return new String(bytes, "UTF-8"); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - return null; - } - - public static byte[] decodeForBytes(String str) { - return str == null ? null : Base64.decodeBase64(str); - } -} diff --git a/HelloAudio/src/main/java/com/hello/util/JsonUtil.java b/HelloAudio/src/main/java/com/hello/util/JsonUtil.java deleted file mode 100644 index fcd90ca..0000000 --- a/HelloAudio/src/main/java/com/hello/util/JsonUtil.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.hello.util; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; - -import java.util.List; - -public class JsonUtil { - public static String toStr(Object javaObj) { - return javaObj == null ? null : JSONObject.toJSONString(javaObj); - } - - public static JSONObject parseObj(String jsonStr) { - if (StrUtil.isEmpty(jsonStr)) { - return null; - } - - try { - return JSONObject.parseObject(jsonStr); - } catch (Exception e) { - String msg = e.getMessage(); - if (msg != null && msg.length() > 100) { - msg = msg.substring(0, 100); - } - LogUtil.warn("Exception when parseJson", msg); - } - return null; - } - - public static T parseObj(String jsonStr, Class clazz) { - if (StrUtil.isEmpty(jsonStr)) { - return null; - } - - try { - return JSONObject.parseObject(jsonStr, clazz); - } catch (Exception e) { - String msg = e.getMessage(); - if (msg != null && msg.length() > 100) { - msg = msg.substring(0, 100); - } - LogUtil.warn("Exception when parseObj", msg); - } - return null; - } - - public static JSONArray parseArr(String jsonStr) { - if (StrUtil.isEmpty(jsonStr)) { - return null; - } - - try { - return JSONObject.parseArray(jsonStr); - } catch (Exception e) { - String msg = e.getMessage(); - if (msg != null && msg.length() > 100) { - msg = msg.substring(0, 100); - } - LogUtil.warn("Exception when parseJson", msg); - } - return null; - } - - public static List parseArr(String jsonStr, Class clazz) { - if (StrUtil.isEmpty(jsonStr)) { - return null; - } - - try { - return JSONObject.parseArray(jsonStr, clazz); - } catch (Exception e) { - String msg = e.getMessage(); - if (msg != null && msg.length() > 100) { - msg = msg.substring(0, 100); - } - LogUtil.warn("Exception when parseObj", msg); - } - return null; - } -} diff --git a/HelloAudio/src/main/java/com/hello/util/LogUtil.java b/HelloAudio/src/main/java/com/hello/util/LogUtil.java deleted file mode 100644 index 1875c33..0000000 --- a/HelloAudio/src/main/java/com/hello/util/LogUtil.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.hello.util; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class LogUtil { - private static final Logger log = LoggerFactory.getLogger(LogUtil.class); - - public static void debug(Object... msg) { - debug(log, msg); - } - - public static void debug(Logger log, Object... msg) { - log.debug(StrUtil.joinObj(msg, ", ")); - } - - public static void info(Object... msg) { - info(log, msg); - } - - public static void info(Logger log, Object... msg) { - log.info(StrUtil.joinObj(msg, ", ")); - } - - public static void warn(Object... msg) { - warn(log, msg); - } - - public static void warn(Logger log, Object... msg) { - log.warn(StrUtil.joinObj(msg, ", ")); - } - - public static void error(Object... msg) { - error(log, msg); - } - - public static void error(Logger log, Object... msg) { - log.error(StrUtil.joinObj(msg, ", ")); - } -} diff --git a/HelloAudio/src/main/java/com/hello/util/StrUtil.java b/HelloAudio/src/main/java/com/hello/util/StrUtil.java deleted file mode 100644 index 995bb48..0000000 --- a/HelloAudio/src/main/java/com/hello/util/StrUtil.java +++ /dev/null @@ -1,192 +0,0 @@ -package com.hello.util; - -import org.apache.commons.collections4.CollectionUtils; - -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class StrUtil { - /** - * String is null or empty - */ - public static boolean isEmpty(String str) { - return isEmpty(str, true); - } - - public static boolean isEmpty(String str, boolean trim) { - return str == null || str.isEmpty() || (trim && str.trim().isEmpty()); - } - - public static boolean chkLen(String str, int minLen, int maxLen) { - return str != null - && str.length() >= Math.max(minLen, 0) - && str.length() <= Math.min(Math.max(maxLen, 0), 1024); - } - - public static String mask(String str) { - return mask(str, 1, 12); - } - - public static String mask(String str, int minLen, int maxLen) { - if (isEmpty(str)) { - return ""; - } - - str = str.trim().replace(" ", "") - .replace("-", "") - .replace("_", ""); - if (str.length() <= minLen && minLen > 0) { - return str; - } - - // Remove the middle part if it's too long - if (maxLen > 0) { - if (maxLen % 2 != 0) { - maxLen++; - } - - if (str.length() > maxLen) { - str = String.format("%s%s", - str.substring(0, maxLen / 2), - str.substring(str.length() - maxLen / 2, str.length()) - ); - } - } - - // Divide 3 parts: str+mask+str - final int len = str.length(); - final int maskLen = len > 3 ? len / 3 : 1; - StringBuilder sb = new StringBuilder(maskLen); - for (int i = 0; i < maskLen; i++) { - sb.append("*"); - } - - int startLen = (len - maskLen) / 2; - return String.format("%s%s%s", - str.substring(0, startLen), sb.toString(), str.substring(startLen + maskLen, len) - ); - } - - public static boolean matches(String str, String pattern) { - if (isEmpty(str) || isEmpty(pattern)) { - return false; - } - Pattern p = Pattern.compile(pattern); - Matcher m = p.matcher(str); - return m.matches(); - } - - public static String[] parse(String str, String pattern) { - if (isEmpty(str) || isEmpty(pattern)) { - return null; - } - - List list = new ArrayList(); - Pattern p = Pattern.compile(pattern); - Matcher m = p.matcher(str); - while (m.find()) { - list.add(m.group()); - } - if (list.size() <= 0) { - return null; - } - - String[] arr = new String[list.size()]; - list.toArray(arr); - return arr; - } - - public static boolean contains(String str, String subStr) { - return contains(str, subStr, ","); - } - - public static boolean contains(String str, String subStr, String separator) { - if (isEmpty(str) || isEmpty(subStr)) { - return false; - } - - if (subStr.equalsIgnoreCase(str)) { - return true; - } - - String[] strArray = split(str, separator); - if (strArray == null) { - return false; - } - - for (String tmpStr : strArray) { - if (tmpStr.trim().length() == 0 && subStr.trim().length() == 0) { - return true; - } - - if (tmpStr.trim().equalsIgnoreCase(subStr.trim())) { - return true; - } - } - return false; - } - - public static String[] split(String str, String separator) { - if (isEmpty(str) || isEmpty(separator)) { - return null; - } - return str.split(separator); - } - - public static String joinObj(Object[] objArr, String separator) { - return objArr == null ? null : joinObj(Arrays.asList(objArr), separator); - } - - public static String joinObj(Collection objList, String separator) { - if (CollectionUtils.isEmpty(objList)) { - return null; - } - - List strList = new ArrayList(); - for (Object obj : objList) { - strList.add(obj == null ? "" : obj.toString()); - } - return join(strList, separator); - } - - public static String join(String[] strArr, String separator) { - return strArr == null ? null : join(Arrays.asList(strArr), separator); - } - - public static String join(Collection strList, String separator) { - if (CollectionUtils.isEmpty(strList) || separator == null) { - return null; - } - - StringBuilder sb = new StringBuilder(); - for (String str : strList) { - sb.append(separator); - sb.append(str); - } - return sb.substring(separator.length()); - } - - /** - * Get the bytes with UTF-8 - */ - public static byte[] getBytes(String str) { - if (str == null) { - return null; - } - try { - return str.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - return null; - } - - public static String trimChinese(String str) { - return isEmpty(str) ? "" : str.replaceAll("[\u4e00-\u9fa5]+", ""); - } -} diff --git a/HelloDialog/src/main/java/com/hello/dialog/App.java b/HelloDialog/src/main/java/com/hello/dialog/App.java index 9965c12..78fa87f 100644 --- a/HelloDialog/src/main/java/com/hello/dialog/App.java +++ b/HelloDialog/src/main/java/com/hello/dialog/App.java @@ -1,9 +1,7 @@ package com.hello.dialog; + import javax.swing.*; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; /** * Hello dialog! @@ -11,69 +9,12 @@ public class App { public static void main(String[] args) { // create frame - final JFrame frame = new JFrame("Hello Dialog"); + final JFrame frame = new Frame(); + frame.setTitle("Hello App"); frame.setSize(300, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(false); - - // create panel - JPanel panel = new JPanel(); - Box verticalBox = Box.createVerticalBox(); - panel.add(verticalBox); - - // Create buttons - verticalBox.add(new JButton("Record") {{ - addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - // Record audio - } - }); - }}); - - verticalBox.add(new JButton("About") {{ - addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - showDialog(frame, frame); - } - }); - }}); - - // Show panel - frame.setContentPane(panel); frame.setVisible(true); } - - private static void showDialog(Frame owner, Component parentComponnent) { - // create dialog - final JDialog dialog = new JDialog(owner, "Info", true); - dialog.setSize(250, 150); - dialog.setResizable(false); - dialog.setLocationRelativeTo(parentComponnent); - - // Add list - Box verticalBox = Box.createVerticalBox(); - - // create content - verticalBox.add(new JLabel("Message")); - verticalBox.add(new JButton("OK") {{ - addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - // close dialog - dialog.dispose(); - } - }); - }}); - - // Add to panel - JPanel panel = new JPanel(); - panel.add(verticalBox); - - // Show panel in dialog - dialog.setContentPane(panel); - dialog.setVisible(true); - } } diff --git a/HelloDialog/src/main/java/com/hello/dialog/Dialog.java b/HelloDialog/src/main/java/com/hello/dialog/Dialog.java new file mode 100644 index 0000000..70c7586 --- /dev/null +++ b/HelloDialog/src/main/java/com/hello/dialog/Dialog.java @@ -0,0 +1,39 @@ +package com.hello.dialog; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +public class Dialog { + public static void showDialog(JFrame owner, Component parentComponnent) { + // create dialog + final JDialog dialog = new JDialog(owner, "Hello Dialog", true); + dialog.setSize(250, 150); + dialog.setResizable(false); + dialog.setLocationRelativeTo(parentComponnent); + + // Add list + Box verticalBox = Box.createVerticalBox(); + + // create content + verticalBox.add(new JLabel("Message")); + verticalBox.add(new JButton("OK") {{ + addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + // close dialog + dialog.dispose(); + } + }); + }}); + + // Add to panel + JPanel panel = new JPanel(); + panel.add(verticalBox); + + // Show panel in dialog + dialog.setContentPane(panel); + dialog.setVisible(true); + } +} diff --git a/HelloDialog/src/main/java/com/hello/dialog/Frame.java b/HelloDialog/src/main/java/com/hello/dialog/Frame.java new file mode 100644 index 0000000..3c548e0 --- /dev/null +++ b/HelloDialog/src/main/java/com/hello/dialog/Frame.java @@ -0,0 +1,73 @@ +package com.hello.dialog; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Date; + +public class Frame extends JFrame { + public Frame(){ + this.setTitle("Hello Frame"); + this.setSize(300, 300); + this.setLocation(300, 300); + this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + this.setLayout(new BorderLayout()); + this.setResizable(false); + this.setVisible(true); + + // create panel + JPanel topPanel = new JPanel(); + topPanel.setLayout(new FlowLayout()); + this.add(topPanel, BorderLayout.NORTH); + + // Create buttons + topPanel.add(new JButton("Btn1")); + topPanel.add(new JButton("Btn2")); + topPanel.add(new JButton("Btn3")); + + // create panel + JPanel bottomPanel = new JPanel(); + bottomPanel.setLayout(new BorderLayout()); + this.add(bottomPanel, BorderLayout.SOUTH); + + // Create buttons + bottomPanel.add(new JButton("Btn4"), BorderLayout.NORTH); + bottomPanel.add(new JButton("Btn5"), BorderLayout.CENTER); + bottomPanel.add(new JButton("Btn6"), BorderLayout.WEST); + bottomPanel.add(new JButton("Btn7"), BorderLayout.EAST); + + // create panel + JPanel centerPanel = new JPanel(); + centerPanel.setLayout(new BorderLayout()); + this.add(centerPanel, BorderLayout.CENTER); + + Box verticalBox = Box.createVerticalBox(); + centerPanel.add(verticalBox, BorderLayout.CENTER); + + final JTextArea textArea = new JTextArea(); + textArea.setEditable(false); + + // Create buttons + final JFrame frame = this; + verticalBox.add(new JButton("Edit") {{ + addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + textArea.insert(String.format("Edit %d: %s\n", textArea.getLineCount(), new Date().toString()), 0); + } + }); + }}, BorderLayout.NORTH); + + verticalBox.add(new JButton("About") {{ + addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Dialog.showDialog(frame, frame); + } + }); + }}, BorderLayout.NORTH); + + verticalBox.add(textArea, BorderLayout.SOUTH); + } +} diff --git a/HelloFlyway/src/main/resources/application.yml b/HelloFlyway/src/main/resources/application.yml index ede9447..234e165 100644 --- a/HelloFlyway/src/main/resources/application.yml +++ b/HelloFlyway/src/main/resources/application.yml @@ -1,6 +1,6 @@ spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://127.0.0.1:3306/flyway?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=UTC - username: dba - password: dba + url: jdbc:mysql://127.0.0.1:3306/starter?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=UTC + username: root + password: root diff --git a/HelloFtp/pom.xml b/HelloFtp/pom.xml new file mode 100644 index 0000000..5d2a794 --- /dev/null +++ b/HelloFtp/pom.xml @@ -0,0 +1,67 @@ + + + + 4.0.0 + + com.hello + ftp + 1.0-SNAPSHOT + + ftp + https://github.com/jextop/ + + + UTF-8 + 1.7 + 1.7 + + + + + junit + junit + 4.11 + test + + + commons-net + commons-net + 3.6 + + + + + + + org.apache.maven.plugins + maven-shade-plugin + 2.4.1 + + + package + + shade + + + + + com.hello.ftp.App + + + META-INF/spring.handlers + + + META-INF/spring.schemas + + + + + + + + + diff --git a/HelloFtp/readme.md b/HelloFtp/readme.md new file mode 100644 index 0000000..7d986f9 --- /dev/null +++ b/HelloFtp/readme.md @@ -0,0 +1,7 @@ +# ftp +https://github.com/rickding/HelloDocker/tree/master/ftp + +docker run -d -v /home/vsftpd:/home/vsftpd -p 20:20 -p 21:21 -p 21100-21110:21100-21110 -e FTP_USER=test -e FTP_PASS=test --name vsftpd fauria/vsftpd + +# client +https://github.com/rickding/HelloJava/tree/master/HelloFtp diff --git a/HelloFtp/src/main/java/com/hello/ftp/App.java b/HelloFtp/src/main/java/com/hello/ftp/App.java new file mode 100644 index 0000000..919fc2a --- /dev/null +++ b/HelloFtp/src/main/java/com/hello/ftp/App.java @@ -0,0 +1,17 @@ +package com.hello.ftp; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Date; + +public class App { + public static void main(String[] args) throws IOException { + String filePath = "readme.md"; + InputStream fileStream = new FileInputStream(new File(filePath)); + + FtpUtil.upload("app-main", String.format("%d_%s", new Date().getHours(), filePath), fileStream); + fileStream.close(); + } +} diff --git a/HelloFtp/src/main/java/com/hello/ftp/FtpUtil.java b/HelloFtp/src/main/java/com/hello/ftp/FtpUtil.java new file mode 100644 index 0000000..02fdd60 --- /dev/null +++ b/HelloFtp/src/main/java/com/hello/ftp/FtpUtil.java @@ -0,0 +1,92 @@ +package com.hello.ftp; + +import org.apache.commons.net.ftp.FTPClient; +import org.apache.commons.net.ftp.FTPReply; + +import java.io.IOException; +import java.io.InputStream; + +public class FtpUtil { + private static FTPClient ftpClient = null; + + private static FTPClient getInst() { + if (ftpClient == null) { + synchronized (FtpUtil.class) { + if (ftpClient == null) { + ftpClient = connect("127.0.0.1", 21, "test", "test"); + } + } + } + + return ftpClient; + } + + private static FTPClient connect(String host, int port, String username, String pwd) { + FTPClient ftpClient = new FTPClient(); + ftpClient.setControlEncoding("utf-8"); + ftpClient.setDataTimeout(1000 * 120); + + // 取消服务器获取自身Ip地址和提交的host进行匹配,否则当不一致时会报异常。 + ftpClient.setRemoteVerificationEnabled(false); + + String status = null; + try { + ftpClient.connect(host, port); + ftpClient.login(username, pwd); + status = ftpClient.getStatus(); + } catch (IOException e) { + System.err.printf("Fail to connect: %s, %d, %s, %s, %s\n", host, port, username, pwd, e.getMessage()); + return null; + } + + int replyCode = ftpClient.getReplyCode(); + System.out.printf("Connect: %s, %d, %s, %s, %d, %s\n", host, port, username, pwd, replyCode, status); + if (!FTPReply.isPositiveCompletion(replyCode)) { + return null; + } + + System.out.printf("本地主机: %s, %d\n", ftpClient.getLocalAddress(), ftpClient.getLocalPort()); + System.out.printf("被动模式主机: %s, %d\n", ftpClient.getPassiveHost(), ftpClient.getPassivePort()); + System.out.printf("主动模式主机: %s, %d\n", ftpClient.getRemoteAddress(), ftpClient.getRemotePort()); + return ftpClient; + } + + public static void close() { + if (ftpClient != null) { + synchronized (FtpUtil.class) { + if (ftpClient != null) { + try { + ftpClient.logout(); + ftpClient.disconnect(); + } catch (IOException e) { + System.err.printf("Fail to close: %s\n", e.getMessage()); + } + } + ftpClient = null; + } + } + } + + public static boolean upload(String pathname, String fileName, InputStream inputStream) { + System.out.printf("Start upload: %s\n", fileName); + FTPClient ftpClient = getInst(); + + // 设置被动模式(FTP客户端在docker容器内,需用被动模式) + ftpClient.enterLocalPassiveMode(); + + try { + // 设置传输的模式为二进制文件类型传输和工作路径 + ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); + ftpClient.makeDirectory(pathname); + ftpClient.changeWorkingDirectory(pathname); + + ftpClient.storeFile(fileName, inputStream); + } catch (IOException e) { + System.err.printf("Fail to upload: %s, %s\n", fileName, e.getMessage()); + return false; + } + + System.out.printf("Success upload: %s\n", fileName); + return true; + } +} \ No newline at end of file diff --git a/HelloFtp/src/test/java/com/hello/ftp/AppTest.java b/HelloFtp/src/test/java/com/hello/ftp/AppTest.java new file mode 100644 index 0000000..9f64866 --- /dev/null +++ b/HelloFtp/src/test/java/com/hello/ftp/AppTest.java @@ -0,0 +1,15 @@ +package com.hello.ftp; + +import org.junit.Test; + +import static org.junit.Assert.assertTrue; + +/** + * Unit test for simple App. + */ +public class AppTest { + @Test + public void shouldAnswerWithTrue() { + assertTrue(true); + } +} diff --git a/HelloFtp/src/test/java/com/hello/ftp/FtpUtilTest.java b/HelloFtp/src/test/java/com/hello/ftp/FtpUtilTest.java new file mode 100644 index 0000000..a76f1ec --- /dev/null +++ b/HelloFtp/src/test/java/com/hello/ftp/FtpUtilTest.java @@ -0,0 +1,24 @@ +package com.hello.ftp; + +import org.junit.Assert; +import org.junit.Test; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Date; + +public class FtpUtilTest { + @Test + public void testUpload() throws IOException { + String filePath = "readme.md"; + InputStream fileStream = new FileInputStream(new File(filePath)); + + boolean ret = FtpUtil.upload("unit-testing", String.format("%d_%s", new Date().getHours(), filePath), fileStream); + fileStream.close(); + FtpUtil.close(); + + Assert.assertTrue(ret); + } +} diff --git a/HelloHackerRank/src/test/java/com/hello/ListRemoveTest.java b/HelloHackerRank/src/test/java/com/hello/ListRemoveTest.java new file mode 100644 index 0000000..48e60f2 --- /dev/null +++ b/HelloHackerRank/src/test/java/com/hello/ListRemoveTest.java @@ -0,0 +1,75 @@ +package com.hello; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +/** + * @author dingxl + * @date 3/16/2021 7:05 PM + */ +public class ListRemoveTest { + @Test + public void testListRemoveException() { + List list = new ArrayList() {{ + add("0"); + add("1"); + add("2"); + add("3"); + add("4"); + }}; + + for (int i = 0; i < list.size(); i++) { + if (i % 2 == 0) { + System.out.printf("remove: %s\n", list.get(i)); + list.remove(i); + } else { + System.out.printf("keep: %s\n", list.get(i)); + } + } + } + + @Test + public void testListRemove() { + List list = new ArrayList() {{ + add("0"); + add("1"); + add("2"); + add("3"); + add("4"); + }}; + + for (int i = list.size() - 1; i >= 0; i--) { + if (i % 2 == 0) { + System.out.printf("remove: %s\n", list.get(i)); + list.remove(i); + } else { + System.out.printf("keep: %s\n", list.get(i)); + } + } + } + + @Test + public void testIteratorRemove() { + List list = new ArrayList() {{ + add("0"); + add("1"); + add("2"); + add("3"); + add("4"); + }}; + + Iterator it = list.iterator(); + while (it.hasNext()) { + String str = it.next(); + if (Integer.parseInt(str) % 2 == 0) { + System.out.printf("remove: %s\n", str); + it.remove(); + } else { + System.out.printf("keep: %s\n", str); + } + } + } +} diff --git a/HelloHtml/.gitignore b/HelloHtml/.gitignore new file mode 100644 index 0000000..a2a3040 --- /dev/null +++ b/HelloHtml/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/HelloHtml/.mvn/wrapper/MavenWrapperDownloader.java b/HelloHtml/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..e76d1f3 --- /dev/null +++ b/HelloHtml/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,117 @@ +/* + * Copyright 2007-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/HelloHtml/.mvn/wrapper/maven-wrapper.jar b/HelloHtml/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..2cc7d4a Binary files /dev/null and b/HelloHtml/.mvn/wrapper/maven-wrapper.jar differ diff --git a/HelloHtml/.mvn/wrapper/maven-wrapper.properties b/HelloHtml/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..642d572 --- /dev/null +++ b/HelloHtml/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/HelloHtml/mvnw b/HelloHtml/mvnw new file mode 100644 index 0000000..a16b543 --- /dev/null +++ b/HelloHtml/mvnw @@ -0,0 +1,310 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/HelloHtml/mvnw.cmd b/HelloHtml/mvnw.cmd new file mode 100644 index 0000000..c8d4337 --- /dev/null +++ b/HelloHtml/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/HelloHtml/pom.xml b/HelloHtml/pom.xml new file mode 100644 index 0000000..014ba75 --- /dev/null +++ b/HelloHtml/pom.xml @@ -0,0 +1,53 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.6.RELEASE + + + com.hello + html + 0.0.1-SNAPSHOT + html + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-freemarker + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/HelloHtml/src/main/java/com/hello/html/HtmlApplication.java b/HelloHtml/src/main/java/com/hello/html/HtmlApplication.java new file mode 100644 index 0000000..5c64429 --- /dev/null +++ b/HelloHtml/src/main/java/com/hello/html/HtmlApplication.java @@ -0,0 +1,12 @@ +package com.hello.html; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class HtmlApplication { + public static void main(String[] args) { + SpringApplication.run(HtmlApplication.class, args); + } +} diff --git a/HelloHtml/src/main/java/com/hello/html/HtmlController.java b/HelloHtml/src/main/java/com/hello/html/HtmlController.java new file mode 100644 index 0000000..22ca60b --- /dev/null +++ b/HelloHtml/src/main/java/com/hello/html/HtmlController.java @@ -0,0 +1,14 @@ +package com.hello.html; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +public class HtmlController { + @RequestMapping + public String index(Model model){ + model.addAttribute("msg","Hello Html!"); + return "index"; + } +} diff --git a/HelloHtml/src/main/resources/application.properties b/HelloHtml/src/main/resources/application.properties new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/HelloHtml/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/HelloHtml/src/main/resources/templates/index.ftl b/HelloHtml/src/main/resources/templates/index.ftl new file mode 100644 index 0000000..c11c24d --- /dev/null +++ b/HelloHtml/src/main/resources/templates/index.ftl @@ -0,0 +1,10 @@ + + + + + Title + + +Hello World! ${msg} + + diff --git a/HelloPDF/pom.xml b/HelloPDF/pom.xml new file mode 100644 index 0000000..6566f27 --- /dev/null +++ b/HelloPDF/pom.xml @@ -0,0 +1,95 @@ + + + + 4.0.0 + + com.hello + HelloPDF + 0.0.1-SNAPSHOT + + HelloPDF + + http://www.example.com + + + UTF-8 + 1.7 + 1.7 + + + + + com.e-iceblue + e-iceblue + http://repo.e-iceblue.com/nexus/content/groups/public/ + + + + + + org.apache.pdfbox + pdfbox + 2.0.4 + + + + e-iceblue + spire.pdf.free + 2.2.2 + + + + junit + junit + 4.11 + test + + + + + + + + + maven-clean-plugin + 3.1.0 + + + + maven-resources-plugin + 3.0.2 + + + maven-compiler-plugin + 3.8.0 + + + maven-surefire-plugin + 2.22.1 + + + maven-jar-plugin + 3.0.2 + + + maven-install-plugin + 2.5.2 + + + maven-deploy-plugin + 2.8.2 + + + + maven-site-plugin + 3.7.1 + + + maven-project-info-reports-plugin + 3.0.0 + + + + + diff --git a/HelloPDF/src/main/java/com/hello/App.java b/HelloPDF/src/main/java/com/hello/App.java new file mode 100644 index 0000000..f6eaca9 --- /dev/null +++ b/HelloPDF/src/main/java/com/hello/App.java @@ -0,0 +1,14 @@ +package com.hello; + +/** + * Hello world! + */ +public class App { + public static void main(String[] args) { + System.out.println("Hello World!"); + + + String fileName = "测试.pdf"; + PDFUtil.readPDF(fileName); + } +} diff --git a/HelloPDF/src/main/java/com/hello/PDFUtil.java b/HelloPDF/src/main/java/com/hello/PDFUtil.java new file mode 100644 index 0000000..6952792 --- /dev/null +++ b/HelloPDF/src/main/java/com/hello/PDFUtil.java @@ -0,0 +1,49 @@ +package com.hello; + +import java.io.*; +import org.apache.pdfbox.*; + +public class PDFUtil { + /** + * 读PDF文件,使用了pdfbox开源项目 + */ + public static void readPDF(String fileName) { + File file = new File(fileName); + FileInputStream in = null; + try { + in = new FileInputStream(fileName); + + // 新建一个PDF解析器对象 + PDFParser parser = new PDFParser(new RandomAccessFile(file, "rw")); + + // 对PDF文件进行解析 + parser.parse(); + + // 获取解析后得到的PDF文档对象 + PDDocument pdfdocument = parser.getPDDocument(); + + // 新建一个PDF文本剥离器 + PDFTextStripper stripper = new PDFTextStripper(); + stripper.setSortByPosition(sort); //sort设置为true 则按照行进行读取,默认是false + + // 从PDF文档对象中剥离文本 + String result = stripper.getText(pdfdocument); + FileWriter fileWriter = new FileWriter(new File("pdf.txt")); + fileWriter.write(result); + fileWriter.flush(); + fileWriter.close(); + System.out.println("PDF文件的文本内容如下:"); + System.out.println(result); + } catch (Exception e) { + System.out.println("读取PDF文件" + file.getAbsolutePath() + "生失败!" + e); + e.printStackTrace(); + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e1) { + } + } + } + } +} diff --git a/HelloQuartz/pom.xml b/HelloQuartz/pom.xml index 0010d37..85468c6 100644 --- a/HelloQuartz/pom.xml +++ b/HelloQuartz/pom.xml @@ -27,11 +27,6 @@ org.springframework.boot spring-boot-starter-quartz - - org.apache.httpcomponents - httpclient - 4.5.2 - org.springframework.boot diff --git a/HelloQuartz/src/main/java/com/hello/quartz/QuartzConfig.java b/HelloQuartz/src/main/java/com/hello/quartz/QuartzConfig.java index d1bac11..1558c65 100644 --- a/HelloQuartz/src/main/java/com/hello/quartz/QuartzConfig.java +++ b/HelloQuartz/src/main/java/com/hello/quartz/QuartzConfig.java @@ -29,14 +29,14 @@ public JobDetail quartzJob() { @Bean public Trigger quartzTrigger() { - CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron); + CronScheduleBuilder schedule = CronScheduleBuilder.cronSchedule(cron); JobDataMap dataMap = new JobDataMap() {{ put("trigger_int", 333); }}; return TriggerBuilder.newTrigger() .forJob(quartzJob()) - .withSchedule(scheduleBuilder) + .withSchedule(schedule) .usingJobData(dataMap) .build(); } diff --git a/HelloQuartz/src/main/java/com/hello/quartz/QuartzJob.java b/HelloQuartz/src/main/java/com/hello/quartz/QuartzJob.java index 4dab995..42659c7 100644 --- a/HelloQuartz/src/main/java/com/hello/quartz/QuartzJob.java +++ b/HelloQuartz/src/main/java/com/hello/quartz/QuartzJob.java @@ -11,14 +11,12 @@ public class QuartzJob extends QuartzJobBean { @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { - // System.out.printf("quartz cron: %s\n", new Date()); + System.out.printf("quartz cron: %s\n", new Date()); // get data from context JobDataMap dataMap = context.getMergedJobDataMap(); for (Map.Entry data : dataMap.entrySet()) { - // System.out.printf("%s = %s\n", data.getKey(), data.getValue()); + System.out.printf("%s = %s\n", data.getKey(), data.getValue()); } - - // do work } } diff --git a/HelloShiro/.gitignore b/HelloShiro/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/HelloShiro/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/HelloShiro/.mvn/wrapper/MavenWrapperDownloader.java b/HelloShiro/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..e76d1f3 --- /dev/null +++ b/HelloShiro/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,117 @@ +/* + * Copyright 2007-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/HelloShiro/.mvn/wrapper/maven-wrapper.jar b/HelloShiro/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..2cc7d4a Binary files /dev/null and b/HelloShiro/.mvn/wrapper/maven-wrapper.jar differ diff --git a/HelloShiro/.mvn/wrapper/maven-wrapper.properties b/HelloShiro/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..642d572 --- /dev/null +++ b/HelloShiro/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/HelloShiro/mvnw b/HelloShiro/mvnw new file mode 100644 index 0000000..a16b543 --- /dev/null +++ b/HelloShiro/mvnw @@ -0,0 +1,310 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/HelloShiro/mvnw.cmd b/HelloShiro/mvnw.cmd new file mode 100644 index 0000000..c8d4337 --- /dev/null +++ b/HelloShiro/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/HelloShiro/pom.xml b/HelloShiro/pom.xml new file mode 100644 index 0000000..13ff89e --- /dev/null +++ b/HelloShiro/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.3.4.RELEASE + + + + com.hello + spring-shiro-demo + 0.0.1-SNAPSHOT + spring-shiro-demo + Demo project for Spring Boot + + + 1.8 + 1.6.0 + + + + + org.springframework.boot + spring-boot-starter-web + + + + + org.apache.shiro + shiro-spring + ${spring.shiro.version} + + + + org.projectlombok + lombok + true + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/HelloShiro/postman/hello_shiro.postman_collection.json b/HelloShiro/postman/hello_shiro.postman_collection.json new file mode 100644 index 0000000..3f36f95 --- /dev/null +++ b/HelloShiro/postman/hello_shiro.postman_collection.json @@ -0,0 +1,95 @@ +{ + "info": { + "_postman_id": "9ede35c7-f565-440d-a504-65bc372351df", + "name": "hello_shiro", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "http://localhost:8080/login?userName=admin&password=123456", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "http://localhost:8080/login?userName=user&password=123456", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "login" + ], + "query": [ + { + "key": "userName", + "value": "user" + }, + { + "key": "password", + "value": "123456" + } + ] + } + }, + "response": [] + }, + { + "name": "http://localhost:8080/admin", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "http://localhost:8080/admin", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "admin" + ] + } + }, + "response": [] + }, + { + "name": "http://localhost:8080/query", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "http://localhost:8080/query", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "query" + ] + } + }, + "response": [] + }, + { + "name": "http://localhost:8080/add", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "http://localhost:8080/add", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "add" + ] + } + }, + "response": [] + } + ] +} \ No newline at end of file diff --git a/HelloShiro/src/main/java/com/hello/shiro/ApiController.java b/HelloShiro/src/main/java/com/hello/shiro/ApiController.java new file mode 100644 index 0000000..e33c374 --- /dev/null +++ b/HelloShiro/src/main/java/com/hello/shiro/ApiController.java @@ -0,0 +1,69 @@ +package com.hello.shiro; + +import com.hello.shiro.model.Permission; +import com.hello.shiro.model.Role; +import com.hello.shiro.model.User; +import lombok.extern.slf4j.Slf4j; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.AuthenticationException; +import org.apache.shiro.authc.UnknownAccountException; +import org.apache.shiro.authc.UsernamePasswordToken; +import org.apache.shiro.authz.AuthorizationException; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.apache.shiro.authz.annotation.RequiresRoles; +import org.apache.shiro.subject.Subject; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * @author dingxl + */ +@RestController +@Slf4j +public class ApiController { + @GetMapping("/login") + public String login(User user) { + if (StringUtils.isEmpty(user.getUserName()) || StringUtils.isEmpty(user.getPassword())) { + return "请输入用户名和密码!"; + } + + Subject subject = SecurityUtils.getSubject(); + try { + // 用户认证 + subject.login(new UsernamePasswordToken( + user.getUserName(), + user.getPassword() + )); + } catch (UnknownAccountException e) { + log.error("用户名不存在!", e); + return "用户名不存在!"; + } catch (AuthenticationException e) { + log.error("账号或密码错误!", e); + return "账号或密码错误!"; + } catch (AuthorizationException e) { + log.error("没有权限!", e); + return "没有权限"; + } + return "login success"; + } + + @RequiresRoles(Role.ADMIN) + @GetMapping("/admin") + public String admin() { + return "admin success!"; + } + + @RequiresRoles(Role.USER) + @RequiresPermissions(Permission.QUERY) + @GetMapping("/query") + public String query() { + return "query success!"; + } + + @RequiresPermissions(Permission.ADD) + @GetMapping("/add") + public String add() { + return "add success!"; + } +} diff --git a/HelloShiro/src/main/java/com/hello/shiro/HelloShiroApplication.java b/HelloShiro/src/main/java/com/hello/shiro/HelloShiroApplication.java new file mode 100644 index 0000000..85b5377 --- /dev/null +++ b/HelloShiro/src/main/java/com/hello/shiro/HelloShiroApplication.java @@ -0,0 +1,14 @@ +package com.hello.shiro; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * @author dingxl + */ +@SpringBootApplication +public class HelloShiroApplication { + public static void main(String[] args) { + SpringApplication.run(HelloShiroApplication.class, args); + } +} diff --git a/HelloShiro/src/main/java/com/hello/shiro/config/ExceptionAdvice.java b/HelloShiro/src/main/java/com/hello/shiro/config/ExceptionAdvice.java new file mode 100644 index 0000000..17b675f --- /dev/null +++ b/HelloShiro/src/main/java/com/hello/shiro/config/ExceptionAdvice.java @@ -0,0 +1,29 @@ +package com.hello.shiro.config; + +import lombok.extern.slf4j.Slf4j; +import org.apache.shiro.authc.AuthenticationException; +import org.apache.shiro.authz.AuthorizationException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; + +/** + * @author dingxl + */ +@ControllerAdvice +@Slf4j +public class ExceptionAdvice { + @ExceptionHandler + @ResponseBody + public String authorizationException(AuthorizationException e) { + log.error("没有通过权限验证!", e); + return e.getMessage(); + } + + @ExceptionHandler + @ResponseBody + public String authenticationException(AuthenticationException e) { + log.error("没有通过用户认证!", e); + return e.getMessage(); + } +} diff --git a/HelloShiro/src/main/java/com/hello/shiro/config/ShiroConfig.java b/HelloShiro/src/main/java/com/hello/shiro/config/ShiroConfig.java new file mode 100644 index 0000000..4086087 --- /dev/null +++ b/HelloShiro/src/main/java/com/hello/shiro/config/ShiroConfig.java @@ -0,0 +1,77 @@ +package com.hello.shiro.config; + +import org.apache.shiro.mgt.SecurityManager; +import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; +import org.apache.shiro.spring.web.ShiroFilterFactoryBean; +import org.apache.shiro.web.mgt.DefaultWebSecurityManager; +import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.HashMap; + +@Configuration +public class ShiroConfig { + @Bean + @ConditionalOnMissingBean + public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() { + return new DefaultAdvisorAutoProxyCreator() {{ + setProxyTargetClass(true); + }}; + } + + /** + * 将验证方式加入容器 + */ + @Bean + public ShiroRealm shiroRealm() { + return new ShiroRealm(); + } + + /** + * 配置Realm管理认证 + */ + @Bean + public SecurityManager securityManager() { + return new DefaultWebSecurityManager() {{ + setRealm(shiroRealm()); + }}; + } + + /** + * 设置对应的过滤条件和跳转条件 + */ + @Bean + public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) { + ShiroFilterFactoryBean filterFactory = new ShiroFilterFactoryBean() {{ + // 登录 + setLoginUrl("/login"); + // 首页 + setSuccessUrl("/index"); + // 错误页面,认证不通过跳转 + setUnauthorizedUrl("/error"); + }}; + + filterFactory.setFilterChainDefinitionMap(new HashMap() {{ + // 登出 + put("/logout", "logout"); + + // 对所有用户认证 + put("/**", "authc"); + }}); + + filterFactory.setSecurityManager(securityManager); + return filterFactory; + } + + /** + * 注入权限管理 + */ + @Bean + public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) { + AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor(); + advisor.setSecurityManager(securityManager); + return advisor; + } +} diff --git a/HelloShiro/src/main/java/com/hello/shiro/config/ShiroRealm.java b/HelloShiro/src/main/java/com/hello/shiro/config/ShiroRealm.java new file mode 100644 index 0000000..66d52d2 --- /dev/null +++ b/HelloShiro/src/main/java/com/hello/shiro/config/ShiroRealm.java @@ -0,0 +1,65 @@ +package com.hello.shiro.config; + +import com.hello.shiro.model.Permission; +import com.hello.shiro.model.Role; +import com.hello.shiro.model.User; +import com.hello.shiro.service.UserService; +import org.apache.shiro.authc.AuthenticationException; +import org.apache.shiro.authc.AuthenticationInfo; +import org.apache.shiro.authc.AuthenticationToken; +import org.apache.shiro.authc.SimpleAuthenticationInfo; +import org.apache.shiro.authz.AuthorizationInfo; +import org.apache.shiro.authz.SimpleAuthorizationInfo; +import org.apache.shiro.realm.AuthorizingRealm; +import org.apache.shiro.subject.PrincipalCollection; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.StringUtils; + +/** + * @author dingxl + */ +public class ShiroRealm extends AuthorizingRealm { + @Autowired + UserService userService; + + /** + * 权限配置类 + */ + @Override + protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { + // 查询用户 + String name = principalCollection.getPrimaryPrincipal().toString(); + User user = userService.getUserByName(name); + if (user == null) { + return null; + } + + // 添加角色和权限 + SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(); + for (Role role : user.getRoles()) { + simpleAuthorizationInfo.addRole(role.getRoleName()); + + for (Permission permissions : role.getPermissions()) { + simpleAuthorizationInfo.addStringPermission(permissions.getPermissionName()); + } + } + return simpleAuthorizationInfo; + } + + /** + * 认证配置类 + */ + @Override + protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { + if (StringUtils.isEmpty(authenticationToken.getPrincipal())) { + return null; + } + + // 获取用户信息 + String name = authenticationToken.getPrincipal().toString(); + User user = userService.getUserByName(name); + + // 验证authenticationToken和simpleAuthenticationInfo + return user == null ? null : new SimpleAuthenticationInfo(name, user.getPassword(), getName()); + } +} diff --git a/HelloShiro/src/main/java/com/hello/shiro/model/Permission.java b/HelloShiro/src/main/java/com/hello/shiro/model/Permission.java new file mode 100644 index 0000000..e18efd4 --- /dev/null +++ b/HelloShiro/src/main/java/com/hello/shiro/model/Permission.java @@ -0,0 +1,17 @@ +package com.hello.shiro.model; + +import lombok.AllArgsConstructor; +import lombok.Data; + +/** + * @author dingxl + */ +@Data +@AllArgsConstructor +public class Permission { + public static final String QUERY = "query"; + public static final String ADD = "add"; + + private String id; + private String permissionName; +} diff --git a/HelloShiro/src/main/java/com/hello/shiro/model/Role.java b/HelloShiro/src/main/java/com/hello/shiro/model/Role.java new file mode 100644 index 0000000..0088856 --- /dev/null +++ b/HelloShiro/src/main/java/com/hello/shiro/model/Role.java @@ -0,0 +1,20 @@ +package com.hello.shiro.model; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import java.util.Set; + +/** + * @author dingxl + */ +@Data +@AllArgsConstructor +public class Role { + public static final String ADMIN = "admin"; + public static final String USER = "user"; + + private String id; + private String roleName; + private Set permissions; +} diff --git a/HelloShiro/src/main/java/com/hello/shiro/model/User.java b/HelloShiro/src/main/java/com/hello/shiro/model/User.java new file mode 100644 index 0000000..476e845 --- /dev/null +++ b/HelloShiro/src/main/java/com/hello/shiro/model/User.java @@ -0,0 +1,18 @@ +package com.hello.shiro.model; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import java.util.Set; + +/** + * @author dingxl + */ +@Data +@AllArgsConstructor +public class User { + private String id; + private String userName; + private String password; + private Set roles; +} diff --git a/HelloShiro/src/main/java/com/hello/shiro/service/UserService.java b/HelloShiro/src/main/java/com/hello/shiro/service/UserService.java new file mode 100644 index 0000000..fd81d41 --- /dev/null +++ b/HelloShiro/src/main/java/com/hello/shiro/service/UserService.java @@ -0,0 +1,45 @@ +package com.hello.shiro.service; + +import com.hello.shiro.model.Permission; +import com.hello.shiro.model.Role; +import com.hello.shiro.model.User; +import org.springframework.stereotype.Service; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; + +/** + * @author dingxl + */ +@Service +public class UserService { + static final Map USER_MAP; + + static { + Permission permissionsQuery = new Permission("1", Permission.QUERY); + Permission permissionsAdd = new Permission("2", Permission.ADD); + + User admin = new User("1", "admin", "123456", new HashSet() {{ + add(new Role("1", Role.ADMIN, new HashSet() {{ + add(permissionsQuery); + add(permissionsAdd); + }})); + }}); + + User user = new User("2", "user", "123456", new HashSet() {{ + add(new Role("2", Role.USER, new HashSet() {{ + add(permissionsQuery); + }})); + }}); + + USER_MAP = new HashMap() {{ + put(admin.getUserName(), admin); + put(user.getUserName(), user); + }}; + } + + public User getUserByName(String userName) { + return USER_MAP.get(userName); + } +} diff --git a/HelloShiro/src/main/resources/application.yml b/HelloShiro/src/main/resources/application.yml new file mode 100644 index 0000000..a7afc92 --- /dev/null +++ b/HelloShiro/src/main/resources/application.yml @@ -0,0 +1,2 @@ +server: + port: 8080 diff --git a/HelloShiro/src/test/java/com/hello/shiro/HelloShiroApplicationTest.java b/HelloShiro/src/test/java/com/hello/shiro/HelloShiroApplicationTest.java new file mode 100644 index 0000000..f053929 --- /dev/null +++ b/HelloShiro/src/test/java/com/hello/shiro/HelloShiroApplicationTest.java @@ -0,0 +1,14 @@ +package com.hello.shiro; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class HelloShiroApplicationTest { + @Test + public void contextLoads() { + } +} diff --git a/HelloSocket/.gitignore b/HelloSocket/.gitignore new file mode 100644 index 0000000..a2a3040 --- /dev/null +++ b/HelloSocket/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/HelloSocket/.mvn/wrapper/MavenWrapperDownloader.java b/HelloSocket/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..e76d1f3 --- /dev/null +++ b/HelloSocket/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,117 @@ +/* + * Copyright 2007-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/HelloSocket/.mvn/wrapper/maven-wrapper.jar b/HelloSocket/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..2cc7d4a Binary files /dev/null and b/HelloSocket/.mvn/wrapper/maven-wrapper.jar differ diff --git a/HelloSocket/.mvn/wrapper/maven-wrapper.properties b/HelloSocket/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..642d572 --- /dev/null +++ b/HelloSocket/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/HelloSocket/mvnw b/HelloSocket/mvnw new file mode 100644 index 0000000..a16b543 --- /dev/null +++ b/HelloSocket/mvnw @@ -0,0 +1,310 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/HelloSocket/mvnw.cmd b/HelloSocket/mvnw.cmd new file mode 100644 index 0000000..c8d4337 --- /dev/null +++ b/HelloSocket/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/HelloSocket/pom.xml b/HelloSocket/pom.xml new file mode 100644 index 0000000..4843f09 --- /dev/null +++ b/HelloSocket/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.6.RELEASE + + + com.hello + socket + 0.0.1-SNAPSHOT + socket + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + + org.springframework.boot + spring-boot-starter-websocket + + + + + org.t-io + tio-websocket-spring-boot-starter + 3.6.0.v20200315-RELEASE + + + + org.apache.commons + commons-lang3 + 3.7 + + + org.springframework.boot + spring-boot-starter-freemarker + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/HelloSocket/src/main/java/com/hello/SocketApplication.java b/HelloSocket/src/main/java/com/hello/SocketApplication.java new file mode 100644 index 0000000..31c4884 --- /dev/null +++ b/HelloSocket/src/main/java/com/hello/SocketApplication.java @@ -0,0 +1,15 @@ +package com.hello; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.tio.websocket.starter.EnableTioWebSocketServer; + +@EnableTioWebSocketServer +@EnableAutoConfiguration +@SpringBootApplication +public class SocketApplication { + public static void main(String[] args) { + SpringApplication.run(SocketApplication.class, args); + } +} diff --git a/HelloSocket/src/main/java/com/hello/controller/SocketController.java b/HelloSocket/src/main/java/com/hello/controller/SocketController.java new file mode 100644 index 0000000..011b3b3 --- /dev/null +++ b/HelloSocket/src/main/java/com/hello/controller/SocketController.java @@ -0,0 +1,26 @@ +package com.hello.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +public class SocketController { + @RequestMapping + public String index(Model model){ + model.addAttribute("msg","Hello Socket!"); + return "index"; + } + + @RequestMapping("/ws") + public String ws(Model model){ + model.addAttribute("msg","Web Socket!"); + return "socket"; + } + + @RequestMapping("/tio") + public String tio(Model model){ + model.addAttribute("msg","Tio Socket!"); + return "tio"; + } +} diff --git a/HelloSocket/src/main/java/com/hello/socket/SocketConfig.java b/HelloSocket/src/main/java/com/hello/socket/SocketConfig.java new file mode 100644 index 0000000..46b6bd9 --- /dev/null +++ b/HelloSocket/src/main/java/com/hello/socket/SocketConfig.java @@ -0,0 +1,13 @@ +package com.hello.socket; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.socket.server.standard.ServerEndpointExporter; + +@Configuration +public class SocketConfig { + @Bean + public ServerEndpointExporter serverEndpointExporter() { + return new ServerEndpointExporter(); + } +} diff --git a/HelloSocket/src/main/java/com/hello/socket/SocketServer.java b/HelloSocket/src/main/java/com/hello/socket/SocketServer.java new file mode 100644 index 0000000..5e7609d --- /dev/null +++ b/HelloSocket/src/main/java/com/hello/socket/SocketServer.java @@ -0,0 +1,70 @@ +package com.hello.socket; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Component; + +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 java.io.IOException; +import java.util.concurrent.ConcurrentHashMap; + +@ServerEndpoint("/ws/{uid}") +@Component +public class SocketServer { + private static ConcurrentHashMap webSocketMap = new ConcurrentHashMap<>(); + + private Session session; + private String uid; + + public static void sendMessage(String uid, String msg) { + System.out.printf("Send message: %s, %s\n", uid, msg); + if (StringUtils.isNotBlank(uid) && webSocketMap.containsKey(uid)) { + webSocketMap.get(uid).sendMessage(msg); + } else { + System.err.printf("Offline: %s\n", uid); + } + } + + public void sendMessage(String msg) { + try { + session.getBasicRemote().sendText(msg); + } catch (IOException e) { + System.err.println(e.getMessage()); + } + } + + @OnMessage + public void onMessage(String msg, Session session) { + System.out.printf("Receive message: %s, %s, %s\n", uid, session.getId(), msg); + + for (String uid : webSocketMap.keySet()) { + sendMessage(uid, String.format("%s消息: %s", uid.equals(this.uid) ? "自己" : "转发", msg)); + } + } + + @OnOpen + public void onOpen(Session session, @PathParam("uid") String uid) { + this.session = session; + this.uid = uid; + + webSocketMap.put(uid, this); + System.out.printf("Online: %d, %s\n", webSocketMap.size(), uid); + sendMessage("连接成功"); + } + + @OnClose + public void onClose() { + webSocketMap.remove(uid); + System.out.printf("Offline 1, %s, online: %d\n", uid, webSocketMap.size()); + } + + @OnError + public void onError(Session session, Throwable e) { + System.err.printf("Error: %s, %s, %s\n", uid, session.getId(), e.getMessage()); + } +} diff --git a/HelloSocket/src/main/java/com/hello/socket/TioMsgHandler.java b/HelloSocket/src/main/java/com/hello/socket/TioMsgHandler.java new file mode 100644 index 0000000..f2972c1 --- /dev/null +++ b/HelloSocket/src/main/java/com/hello/socket/TioMsgHandler.java @@ -0,0 +1,52 @@ +package com.hello.socket; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.tio.core.ChannelContext; +import org.tio.core.Tio; +import org.tio.http.common.HttpRequest; +import org.tio.http.common.HttpResponse; +import org.tio.websocket.common.WsRequest; +import org.tio.websocket.common.WsResponse; +import org.tio.websocket.server.handler.IWsMsgHandler; +import org.tio.websocket.starter.TioWebSocketServerBootstrap; + +@Component +public class TioMsgHandler implements IWsMsgHandler { + @Autowired + private TioWebSocketServerBootstrap tioServer; + + public void sendMessage(String msg) { + Tio.sendToAll(tioServer.getServerTioConfig(), WsResponse.fromText(msg, "utf-8")); + } + + @Override + public Object onText(WsRequest wsRequest, String msg, ChannelContext channelContext) throws Exception { + System.out.printf("收到文本消息:%s\n", msg); + + sendMessage(String.format("转发消息: %s", msg)); + return String.format("收到消息: %s", msg); + } + + @Override + public Object onBytes(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception { + System.out.printf("收到二进制数据:%d\n", bytes.length); + return null; + } + + @Override + public HttpResponse handshake(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception { + return httpResponse; + } + + @Override + public void onAfterHandshaked(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception { + System.out.println("连接成功"); + } + + @Override + public Object onClose(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception { + System.out.println("关闭连接"); + return null; + } +} diff --git a/HelloSocket/src/main/resources/application.yml b/HelloSocket/src/main/resources/application.yml new file mode 100644 index 0000000..c66101b --- /dev/null +++ b/HelloSocket/src/main/resources/application.yml @@ -0,0 +1,5 @@ +tio: + websocket: + server: + port: 8200 + heartbeat-timeout: 3600000 diff --git a/HelloSocket/src/main/resources/templates/index.ftl b/HelloSocket/src/main/resources/templates/index.ftl new file mode 100644 index 0000000..c11c24d --- /dev/null +++ b/HelloSocket/src/main/resources/templates/index.ftl @@ -0,0 +1,10 @@ + + + + + Title + + +Hello World! ${msg} + + diff --git a/HelloSocket/src/main/resources/templates/socket.ftl b/HelloSocket/src/main/resources/templates/socket.ftl new file mode 100644 index 0000000..0ce742c --- /dev/null +++ b/HelloSocket/src/main/resources/templates/socket.ftl @@ -0,0 +1,72 @@ + + + + + HelloSocket + + + + + + +${msg} + +
uid: +
+
msg: +
+ +
+
+ +
+
+
+ +
+ +
+
+ + + \ No newline at end of file diff --git a/HelloSocket/src/main/resources/templates/tio.ftl b/HelloSocket/src/main/resources/templates/tio.ftl new file mode 100644 index 0000000..4a06d1a --- /dev/null +++ b/HelloSocket/src/main/resources/templates/tio.ftl @@ -0,0 +1,72 @@ + + + + + HelloSocket + + + + + + +${msg} + +
uid: +
+
msg: +
+ +
+
+ +
+
+
+ +
+ +
+
+ + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index e91b708..c3c3ab7 100644 --- a/pom.xml +++ b/pom.xml @@ -21,18 +21,23 @@ HelloCodeM HelloDialog HelloFlyway + HelloFtp HelloHack HelloHackerRank HelloHessian + HelloHtml HelloHttp HelloJpa HelloJUnit HelloMyBatis HelloOrder + HelloPDF HelloQuartz HelloRedis HelloRunner + HelloShiro HelloSingleton + HelloSocket HelloThread HelloWar HelloWeb diff --git a/push_master.sh b/push_master.sh new file mode 100644 index 0000000..102d2bf --- /dev/null +++ b/push_master.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +git checkout master + +git push origin master +git push gitee master +git push github master