diff --git a/src/main/java/io/jboot/codegen/service/JbootServiceImplGenerator.java b/src/main/java/io/jboot/codegen/service/JbootServiceImplGenerator.java index df746e5a4786ba2e24eaf5ac4e2640ec27d504d7..3984c961e98fb1270471271ae93d066d877f914a 100644 --- a/src/main/java/io/jboot/codegen/service/JbootServiceImplGenerator.java +++ b/src/main/java/io/jboot/codegen/service/JbootServiceImplGenerator.java @@ -1,101 +1,108 @@ -/** - * Copyright (c) 2015-2018, Michael Yang 杨福海 (fuhai999@gmail.com). - *

- * 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 - *

- * http://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. - */ -package io.jboot.codegen.service; - -import com.jfinal.kit.Kv; -import com.jfinal.kit.PathKit; -import com.jfinal.kit.StrKit; -import com.jfinal.plugin.activerecord.generator.BaseModelGenerator; -import com.jfinal.plugin.activerecord.generator.TableMeta; -import com.jfinal.template.Engine; -import com.jfinal.template.source.ClassPathSourceFactory; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.List; - -public class JbootServiceImplGenerator extends BaseModelGenerator { - - String basePackage; - String modelPackage; - - public JbootServiceImplGenerator(String basePackage, String modelPackage) { - super(basePackage + ".impl", PathKit.getWebRootPath() + "/src/main/java/" + (basePackage + ".impl").replace(".", "/")); - - this.basePackage = basePackage; - this.modelPackage = modelPackage; - this.template = "io/jboot/codegen/service/service_impl_template.jf"; - - - } - - @Override - public void generate(List tableMetas) { - System.out.println("Generate base model ..."); - System.out.println("Base Model Output Dir: " + baseModelOutputDir); - - Engine engine = Engine.create("forServiceImpl"); - engine.setSourceFactory(new ClassPathSourceFactory()); - engine.addSharedMethod(new StrKit()); - engine.addSharedObject("getterTypeMap", getterTypeMap); - engine.addSharedObject("javaKeyword", javaKeyword); - - for (TableMeta tableMeta : tableMetas) { - genBaseModelContent(tableMeta); - } - writeToFile(tableMetas); - } - - - @Override - protected void genBaseModelContent(TableMeta tableMeta) { - Kv data = Kv.by("serviceImplPackageName", baseModelPackageName); - data.set("generateChainSetter", generateChainSetter); - data.set("tableMeta", tableMeta); - data.set("basePackage", basePackage); - data.set("modelPackage", modelPackage); - - Engine engine = Engine.use("forServiceImpl"); - tableMeta.baseModelContent = engine.getTemplate(template).renderToString(data); - } - - /** - * base model 覆盖写入 - */ - @Override - protected void writeToFile(TableMeta tableMeta) throws IOException { - File dir = new File(baseModelOutputDir); - if (!dir.exists()) { - dir.mkdirs(); - } - - String target = baseModelOutputDir + File.separator + tableMeta.modelName + "ServiceImpl" + ".java"; - - File targetFile = new File(target); - if (targetFile.exists()) { - return; - } - - - FileWriter fw = new FileWriter(target); - try { - fw.write(tableMeta.baseModelContent); - } finally { - fw.close(); - } - } -} +/** + * Copyright (c) 2015-2018, Michael Yang 杨福海 (fuhai999@gmail.com). + *

+ * 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 + *

+ * http://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. + */ +package io.jboot.codegen.service; + +import com.jfinal.kit.Kv; +import com.jfinal.kit.PathKit; +import com.jfinal.kit.StrKit; +import com.jfinal.plugin.activerecord.generator.BaseModelGenerator; +import com.jfinal.plugin.activerecord.generator.TableMeta; +import com.jfinal.template.Engine; +import com.jfinal.template.source.ClassPathSourceFactory; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.List; + +public class JbootServiceImplGenerator extends BaseModelGenerator { + + String basePackage; + String modelPackage; + + public JbootServiceImplGenerator(String basePackage, String modelPackage) { + super(basePackage + ".impl", PathKit.getWebRootPath() + "/src/main/java/" + (basePackage + ".impl").replace(".", "/")); + + this.basePackage = basePackage; + this.modelPackage = modelPackage; + this.template = "io/jboot/codegen/service/service_impl_template.jf"; + + + } + + @Override + public void generate(List tableMetas) { + System.out.println("Generate base model ..."); + System.out.println("Base Model Output Dir: " + baseModelOutputDir); + + Engine engine = Engine.create("forServiceImpl"); + engine.setSourceFactory(new ClassPathSourceFactory()); + engine.addSharedMethod(new StrKit()); + engine.addSharedObject("getterTypeMap", getterTypeMap); + engine.addSharedObject("javaKeyword", javaKeyword); + + for (TableMeta tableMeta : tableMetas) { + genBaseModelContent(tableMeta); + } + writeToFile(tableMetas); + } + + + @Override + protected void genBaseModelContent(TableMeta tableMeta) { + Kv data = Kv.by("serviceImplPackageName", baseModelPackageName); + data.set("generateChainSetter", generateChainSetter); + data.set("tableMeta", tableMeta); + data.set("basePackage", basePackage); + data.set("modelPackage", modelPackage); + + Engine engine = Engine.use("forServiceImpl"); + tableMeta.baseModelContent = engine.getTemplate(template).renderToString(data); + } + + /** + * base model 覆盖写入 + */ + @Override + protected void writeToFile(TableMeta tableMeta) throws IOException { + File dir = new File(baseModelOutputDir); + if (!dir.exists()) { + dir.mkdirs(); + } + + String target = baseModelOutputDir + File.separator + tableMeta.modelName + "ServiceImpl" + ".java"; + + File targetFile = new File(target); + if (targetFile.exists()) { + return; + } + + + FileWriter fw = new FileWriter(target); + try { + fw.write(tableMeta.baseModelContent); + } finally { + if(fw != null) { + try { + fw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + } + } +} diff --git a/src/main/java/io/jboot/codegen/service/JbootServiceInterfaceGenerator.java b/src/main/java/io/jboot/codegen/service/JbootServiceInterfaceGenerator.java index d481b7ffbd165e1ab138883d29d6ea41c8f60751..474bae85b491ddfd581ec094be90840a208edb06 100644 --- a/src/main/java/io/jboot/codegen/service/JbootServiceInterfaceGenerator.java +++ b/src/main/java/io/jboot/codegen/service/JbootServiceInterfaceGenerator.java @@ -1,102 +1,108 @@ -/** - * Copyright (c) 2015-2018, Michael Yang 杨福海 (fuhai999@gmail.com). - *

- * 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 - *

- * http://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. - */ -package io.jboot.codegen.service; - -import com.jfinal.kit.Kv; -import com.jfinal.kit.PathKit; -import com.jfinal.kit.StrKit; -import com.jfinal.plugin.activerecord.generator.BaseModelGenerator; -import com.jfinal.plugin.activerecord.generator.TableMeta; -import com.jfinal.template.Engine; -import com.jfinal.template.source.ClassPathSourceFactory; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.List; - -public class JbootServiceInterfaceGenerator extends BaseModelGenerator { - - private String modelPacket; - private String basePackage; - - public JbootServiceInterfaceGenerator(String basePackage, String modelPacket) { - super(basePackage, PathKit.getWebRootPath() + "/src/main/java/" + basePackage.replace(".", "/")); - - - this.modelPacket = modelPacket; - this.basePackage = basePackage; - this.template = "io/jboot/codegen/service/service_template.jf"; - - } - - @Override - public void generate(List tableMetas) { - System.out.println("Generate base model ..."); - System.out.println("Base Model Output Dir: " + baseModelOutputDir); - - Engine engine = Engine.create("forService"); - engine.setSourceFactory(new ClassPathSourceFactory()); - engine.addSharedMethod(new StrKit()); - engine.addSharedObject("getterTypeMap", getterTypeMap); - engine.addSharedObject("javaKeyword", javaKeyword); - - for (TableMeta tableMeta : tableMetas) { - genBaseModelContent(tableMeta); - } - writeToFile(tableMetas); - } - - @Override - protected void genBaseModelContent(TableMeta tableMeta) { - Kv data = Kv.by("baseModelPackageName", baseModelPackageName); - data.set("generateChainSetter", generateChainSetter); - data.set("tableMeta", tableMeta); - data.set("modelPacket", modelPacket); - data.set("basePackage", basePackage); - - Engine engine = Engine.use("forService"); - tableMeta.baseModelContent = engine.getTemplate(template).renderToString(data); - } - - - /** - * base model 覆盖写入 - */ - @Override - protected void writeToFile(TableMeta tableMeta) throws IOException { - File dir = new File(baseModelOutputDir); - if (!dir.exists()) { - dir.mkdirs(); - } - - String target = baseModelOutputDir + File.separator + tableMeta.modelName + "Service" + ".java"; - - File targetFile = new File(target); - if (targetFile.exists()) { - return; - } - - FileWriter fw = new FileWriter(target); - try { - fw.write(tableMeta.baseModelContent); - } finally { - fw.close(); - } - } - - -} +/** + * Copyright (c) 2015-2018, Michael Yang 杨福海 (fuhai999@gmail.com). + *

+ * 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 + *

+ * http://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. + */ +package io.jboot.codegen.service; + +import com.jfinal.kit.Kv; +import com.jfinal.kit.PathKit; +import com.jfinal.kit.StrKit; +import com.jfinal.plugin.activerecord.generator.BaseModelGenerator; +import com.jfinal.plugin.activerecord.generator.TableMeta; +import com.jfinal.template.Engine; +import com.jfinal.template.source.ClassPathSourceFactory; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.List; + +public class JbootServiceInterfaceGenerator extends BaseModelGenerator { + + private String modelPacket; + private String basePackage; + + public JbootServiceInterfaceGenerator(String basePackage, String modelPacket) { + super(basePackage, PathKit.getWebRootPath() + "/src/main/java/" + basePackage.replace(".", "/")); + + + this.modelPacket = modelPacket; + this.basePackage = basePackage; + this.template = "io/jboot/codegen/service/service_template.jf"; + + } + + @Override + public void generate(List tableMetas) { + System.out.println("Generate base model ..."); + System.out.println("Base Model Output Dir: " + baseModelOutputDir); + + Engine engine = Engine.create("forService"); + engine.setSourceFactory(new ClassPathSourceFactory()); + engine.addSharedMethod(new StrKit()); + engine.addSharedObject("getterTypeMap", getterTypeMap); + engine.addSharedObject("javaKeyword", javaKeyword); + + for (TableMeta tableMeta : tableMetas) { + genBaseModelContent(tableMeta); + } + writeToFile(tableMetas); + } + + @Override + protected void genBaseModelContent(TableMeta tableMeta) { + Kv data = Kv.by("baseModelPackageName", baseModelPackageName); + data.set("generateChainSetter", generateChainSetter); + data.set("tableMeta", tableMeta); + data.set("modelPacket", modelPacket); + data.set("basePackage", basePackage); + + Engine engine = Engine.use("forService"); + tableMeta.baseModelContent = engine.getTemplate(template).renderToString(data); + } + + + /** + * base model 覆盖写入 + */ + @Override + protected void writeToFile(TableMeta tableMeta) throws IOException { + File dir = new File(baseModelOutputDir); + if (!dir.exists()) { + dir.mkdirs(); + } + + String target = baseModelOutputDir + File.separator + tableMeta.modelName + "Service" + ".java"; + + File targetFile = new File(target); + if (targetFile.exists()) { + return; + } + + FileWriter fw = new FileWriter(target); + try { + fw.write(tableMeta.baseModelContent); + } finally { + if(fw != null) { + try { + fw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + +} diff --git a/src/main/java/io/jboot/core/http/jboot/JbootHttpImpl.java b/src/main/java/io/jboot/core/http/jboot/JbootHttpImpl.java index 4d43a5b29e0027efbe1326bcfe9fbf349dab7c6d..9d3159158a955cd4f7be3e78c2350aebf1571e1b 100644 --- a/src/main/java/io/jboot/core/http/jboot/JbootHttpImpl.java +++ b/src/main/java/io/jboot/core/http/jboot/JbootHttpImpl.java @@ -1,268 +1,279 @@ -/** - * Copyright (c) 2015-2018, Michael Yang 杨福海 (fuhai999@gmail.com). - *

- * 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 - *

- * http://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. - */ -package io.jboot.core.http.jboot; - -import com.jfinal.log.Log; -import io.jboot.core.http.JbootHttpBase; -import io.jboot.core.http.JbootHttpRequest; -import io.jboot.core.http.JbootHttpResponse; -import io.jboot.exception.JbootException; -import io.jboot.utils.ArrayUtils; -import io.jboot.utils.StringUtils; - -import javax.net.ssl.*; -import java.io.*; -import java.net.HttpURLConnection; -import java.net.ProtocolException; -import java.net.URL; -import java.security.KeyStore; -import java.security.SecureRandom; -import java.security.cert.X509Certificate; -import java.util.Map; - - -public class JbootHttpImpl extends JbootHttpBase { - - private static final Log LOG = Log.getLog(JbootHttpImpl.class); - - - @Override - public JbootHttpResponse handle(JbootHttpRequest request) { - - JbootHttpResponse response = request.getDownloadFile() == null - ? new JbootHttpResponse() - : new JbootHttpResponse(request.getDownloadFile()); - doProcess(request, response); - return response; - } - - - private void doProcess(JbootHttpRequest request, JbootHttpResponse response) { - HttpURLConnection connection = null; - InputStream stream = null; - try { - - connection = getConnection(request); - configConnection(connection, request); - - - if (request.isGetRquest()) { - - connection.setInstanceFollowRedirects(true); - connection.connect(); - } - /** - * 处理 post请求 - */ - else if (request.isPostRquest()) { - - connection.setRequestMethod("POST"); - connection.setDoOutput(true); - - /** - * 处理 非文件上传的 post 请求 - */ - if (!request.isMultipartFormData()) { - - String postContent = buildParams(request); - if (StringUtils.isNotEmpty(postContent)) { - DataOutputStream dos = new DataOutputStream(connection.getOutputStream()); - dos.write(postContent.getBytes(request.getCharset())); - dos.flush(); - dos.close(); - } - - } - - /** - * 处理文件上传的post请求 - */ - else { - - if (ArrayUtils.isNotEmpty(request.getParams())) { - uploadData(request, connection); - } - - } - } - - stream = getInutStream(connection); - - response.setContentType(connection.getContentType()); - response.setResponseCode(connection.getResponseCode()); - response.setHeaders(connection.getHeaderFields()); - - response.pipe(stream); - response.finish(); - - } catch (Throwable ex) { - LOG.warn(ex.toString(), ex); - response.setError(ex); - } finally { - if (connection != null) { - connection.disconnect(); - } - if (stream != null) { - try { - stream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } - - private InputStream getInutStream(HttpURLConnection connection) throws IOException { - return connection.getResponseCode() >= 400 ? connection.getErrorStream() : connection.getInputStream(); - } - - private void uploadData(JbootHttpRequest request, HttpURLConnection connection) throws IOException { - String endFlag = "\r\n"; - String boundary = "---------" + StringUtils.uuid(); - connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); - DataOutputStream dos = new DataOutputStream(connection.getOutputStream()); - for (Map.Entry entry : request.getParams().entrySet()) { - if (entry.getValue() instanceof File) { - File file = (File) entry.getValue(); - checkFileNormal(file); - dos.writeBytes(boundary + endFlag); - dos.writeBytes(String.format("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"", entry.getKey(), file.getName()) + endFlag); - dos.writeBytes(endFlag); - FileInputStream fStream = new FileInputStream(file); - byte[] buffer = new byte[2028]; - for (int len = 0; (len = fStream.read(buffer)) > 0; ) { - dos.write(buffer, 0, len); - } - - dos.writeBytes(endFlag); - } else { - dos.writeBytes("Content-Disposition: form-data; name=\"" + entry.getKey() + "\""); - dos.writeBytes(endFlag); - dos.writeBytes(endFlag); - dos.writeBytes(String.valueOf(entry.getValue())); - dos.writeBytes(endFlag); - } - } - - dos.writeBytes("--" + boundary + "--" + endFlag); - } - - private static void checkFileNormal(File file) { - if (!file.exists()) { - throw new JbootException("file not exists!!!!" + file); - } - if (file.isDirectory()) { - throw new JbootException("cannot upload directory!!!!" + file); - } - if (!file.canRead()) { - throw new JbootException("cannnot read file!!!" + file); - } - } - - - private static void configConnection(HttpURLConnection connection, JbootHttpRequest request) throws ProtocolException { - if (connection == null) - return; - connection.setReadTimeout(request.getReadTimeOut()); - connection.setConnectTimeout(request.getConnectTimeOut()); - connection.setRequestMethod(request.getMethod()); - - - connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); - connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36"); - if (request.getHeaders() != null && request.getHeaders().size() > 0) { - for (Map.Entry entry : request.getHeaders().entrySet()) { - connection.setRequestProperty(entry.getKey(), entry.getValue()); - } - } - } - - private static HttpURLConnection getConnection(JbootHttpRequest request) { - try { - if (request.isGetRquest()) { - buildGetUrlWithParams(request); - } - if (request.getRequestUrl().toLowerCase().startsWith("https")) { - return getHttpsConnection(request); - } else { - return getHttpConnection(request.getRequestUrl()); - } - } catch (Throwable ex) { - throw new JbootException(ex); - } - } - - private static HttpURLConnection getHttpConnection(String urlStr) throws Exception { - URL url = new URL(urlStr); - HttpURLConnection conn = (HttpURLConnection) url.openConnection(); - return conn; - } - - private static HttpsURLConnection getHttpsConnection(JbootHttpRequest request) throws Exception { - URL url = new URL(request.getRequestUrl()); - HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); - - if (request.getCertPath() != null && request.getCertPass() != null) { - - KeyStore clientStore = KeyStore.getInstance("PKCS12"); - clientStore.load(new FileInputStream(request.getCertPath()), request.getCertPass().toCharArray()); - - KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); - keyManagerFactory.init(clientStore, request.getCertPass().toCharArray()); - KeyManager[] keyManagers = keyManagerFactory.getKeyManagers(); - - - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - trustManagerFactory.init(clientStore); - - SSLContext sslContext = SSLContext.getInstance("TLSv1"); - sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), new SecureRandom()); - - conn.setSSLSocketFactory(sslContext.getSocketFactory()); - - } else { - conn.setHostnameVerifier(hnv); - SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); - if (sslContext != null) { - TrustManager[] tm = {trustAnyTrustManager}; - sslContext.init(null, tm, null); - SSLSocketFactory ssf = sslContext.getSocketFactory(); - conn.setSSLSocketFactory(ssf); - } - } - return conn; - } - - private static X509TrustManager trustAnyTrustManager = new X509TrustManager() { - public void checkClientTrusted(X509Certificate[] chain, String authType) { - } - - public void checkServerTrusted(X509Certificate[] chain, String authType) { - } - - public X509Certificate[] getAcceptedIssuers() { - return null; - } - }; - - private static HostnameVerifier hnv = new HostnameVerifier() { - public boolean verify(String hostname, SSLSession session) { - return true; - } - }; - - -} +/** + * Copyright (c) 2015-2018, Michael Yang 杨福海 (fuhai999@gmail.com). + *

+ * 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 + *

+ * http://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. + */ +package io.jboot.core.http.jboot; + +import com.jfinal.log.Log; +import io.jboot.core.http.JbootHttpBase; +import io.jboot.core.http.JbootHttpRequest; +import io.jboot.core.http.JbootHttpResponse; +import io.jboot.exception.JbootException; +import io.jboot.utils.ArrayUtils; +import io.jboot.utils.StringUtils; + +import javax.net.ssl.*; +import java.io.*; +import java.net.HttpURLConnection; +import java.net.ProtocolException; +import java.net.URL; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.security.cert.X509Certificate; +import java.util.Map; + + +public class JbootHttpImpl extends JbootHttpBase { + + private static final Log LOG = Log.getLog(JbootHttpImpl.class); + + + @Override + public JbootHttpResponse handle(JbootHttpRequest request) { + + JbootHttpResponse response = request.getDownloadFile() == null + ? new JbootHttpResponse() + : new JbootHttpResponse(request.getDownloadFile()); + doProcess(request, response); + return response; + } + + + private void doProcess(JbootHttpRequest request, JbootHttpResponse response) { + HttpURLConnection connection = null; + InputStream stream = null; + try { + + connection = getConnection(request); + configConnection(connection, request); + + + if (request.isGetRquest()) { + + connection.setInstanceFollowRedirects(true); + connection.connect(); + } + /** + * 处理 post请求 + */ + else if (request.isPostRquest()) { + + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + + /** + * 处理 非文件上传的 post 请求 + */ + if (!request.isMultipartFormData()) { + + String postContent = buildParams(request); + if (StringUtils.isNotEmpty(postContent)) { + DataOutputStream dos = null; + try { + dos = new DataOutputStream(connection.getOutputStream()); + dos.write(postContent.getBytes(request.getCharset())); + dos.flush(); + } finally { + if (dos!=null) { + try { + dos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + } + + } + + /** + * 处理文件上传的post请求 + */ + else { + + if (ArrayUtils.isNotEmpty(request.getParams())) { + uploadData(request, connection); + } + + } + } + + stream = getInutStream(connection); + + response.setContentType(connection.getContentType()); + response.setResponseCode(connection.getResponseCode()); + response.setHeaders(connection.getHeaderFields()); + + response.pipe(stream); + response.finish(); + + } catch (Throwable ex) { + LOG.warn(ex.toString(), ex); + response.setError(ex); + } finally { + if (connection != null) { + connection.disconnect(); + } + if (stream != null) { + try { + stream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + private InputStream getInutStream(HttpURLConnection connection) throws IOException { + return connection.getResponseCode() >= 400 ? connection.getErrorStream() : connection.getInputStream(); + } + + private void uploadData(JbootHttpRequest request, HttpURLConnection connection) throws IOException { + String endFlag = "\r\n"; + String boundary = "---------" + StringUtils.uuid(); + connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); + DataOutputStream dos = new DataOutputStream(connection.getOutputStream()); + for (Map.Entry entry : request.getParams().entrySet()) { + if (entry.getValue() instanceof File) { + File file = (File) entry.getValue(); + checkFileNormal(file); + dos.writeBytes(boundary + endFlag); + dos.writeBytes(String.format("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"", entry.getKey(), file.getName()) + endFlag); + dos.writeBytes(endFlag); + try(FileInputStream fStream = new FileInputStream(file)){ + byte[] buffer = new byte[2028]; + for (int len = 0; (len = fStream.read(buffer)) > 0; ) { + dos.write(buffer, 0, len); + } + } + dos.writeBytes(endFlag); + } else { + dos.writeBytes("Content-Disposition: form-data; name=\"" + entry.getKey() + "\""); + dos.writeBytes(endFlag); + dos.writeBytes(endFlag); + dos.writeBytes(String.valueOf(entry.getValue())); + dos.writeBytes(endFlag); + } + } + + dos.writeBytes("--" + boundary + "--" + endFlag); + } + + private static void checkFileNormal(File file) { + if (!file.exists()) { + throw new JbootException("file not exists!!!!" + file); + } + if (file.isDirectory()) { + throw new JbootException("cannot upload directory!!!!" + file); + } + if (!file.canRead()) { + throw new JbootException("cannnot read file!!!" + file); + } + } + + + private static void configConnection(HttpURLConnection connection, JbootHttpRequest request) throws ProtocolException { + if (connection == null) + return; + connection.setReadTimeout(request.getReadTimeOut()); + connection.setConnectTimeout(request.getConnectTimeOut()); + connection.setRequestMethod(request.getMethod()); + + + connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36"); + if (request.getHeaders() != null && request.getHeaders().size() > 0) { + for (Map.Entry entry : request.getHeaders().entrySet()) { + connection.setRequestProperty(entry.getKey(), entry.getValue()); + } + } + } + + private static HttpURLConnection getConnection(JbootHttpRequest request) { + try { + if (request.isGetRquest()) { + buildGetUrlWithParams(request); + } + if (request.getRequestUrl().toLowerCase().startsWith("https")) { + return getHttpsConnection(request); + } else { + return getHttpConnection(request.getRequestUrl()); + } + } catch (Throwable ex) { + throw new JbootException(ex); + } + } + + private static HttpURLConnection getHttpConnection(String urlStr) throws Exception { + URL url = new URL(urlStr); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + return conn; + } + + private static HttpsURLConnection getHttpsConnection(JbootHttpRequest request) throws Exception { + URL url = new URL(request.getRequestUrl()); + HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); + + if (request.getCertPath() != null && request.getCertPass() != null) { + + KeyStore clientStore = KeyStore.getInstance("PKCS12"); + clientStore.load(new FileInputStream(request.getCertPath()), request.getCertPass().toCharArray()); + + KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + keyManagerFactory.init(clientStore, request.getCertPass().toCharArray()); + KeyManager[] keyManagers = keyManagerFactory.getKeyManagers(); + + + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagerFactory.init(clientStore); + + SSLContext sslContext = SSLContext.getInstance("TLSv1"); + sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), new SecureRandom()); + + conn.setSSLSocketFactory(sslContext.getSocketFactory()); + + } else { + conn.setHostnameVerifier(hnv); + SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); + if (sslContext != null) { + TrustManager[] tm = {trustAnyTrustManager}; + sslContext.init(null, tm, null); + SSLSocketFactory ssf = sslContext.getSocketFactory(); + conn.setSSLSocketFactory(ssf); + } + } + return conn; + } + + private static X509TrustManager trustAnyTrustManager = new X509TrustManager() { + public void checkClientTrusted(X509Certificate[] chain, String authType) { + } + + public void checkServerTrusted(X509Certificate[] chain, String authType) { + } + + public X509Certificate[] getAcceptedIssuers() { + return null; + } + }; + + private static HostnameVerifier hnv = new HostnameVerifier() { + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + + +} diff --git a/src/main/java/io/jboot/core/rpc/JbootrpcServiceConfig.java b/src/main/java/io/jboot/core/rpc/JbootrpcServiceConfig.java index b7573f576d83c6cd0fdb7e8314455c31e040b1df..136637054475819044d2742ab7d549101e5777b1 100644 --- a/src/main/java/io/jboot/core/rpc/JbootrpcServiceConfig.java +++ b/src/main/java/io/jboot/core/rpc/JbootrpcServiceConfig.java @@ -1,204 +1,204 @@ -/** - * Copyright (c) 2015-2018, Michael Yang 杨福海 (fuhai999@gmail.com). - *

- * 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 - *

- * http://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. - */ -package io.jboot.core.rpc; - -import io.jboot.Jboot; -import io.jboot.core.rpc.annotation.JbootrpcService; -import io.jboot.utils.StringUtils; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -/** - * @author Michael Yang 杨福海 (fuhai999@gmail.com) - * @version V1.0 - * @Package io.jboot.core.rpc - */ -public class JbootrpcServiceConfig implements Serializable { - - - private int port = 0; - private String group; - private String version; - private Integer timeout; - private Integer retries; - private Integer actives; - private String loadbalance; - private Boolean async; - private Boolean check; - - - private String proxy; - private String filter; - - // 用于扩展,用户通过SPI扩展获取自定义的 Service的时候, - // 若以字段不满足,此时通过 params 自行扩展 - private Map params; - - private static JbootrpcConfig defaultConfig = Jboot.config(JbootrpcConfig.class); - - - public JbootrpcServiceConfig() { - this.port = defaultConfig.getDefaultPort(); - this.group = defaultConfig.getDefaultGroup(); - this.version = defaultConfig.getDefaultVersion(); - this.timeout = defaultConfig.getRequestTimeOut(); - this.retries = defaultConfig.getRetries(); - } - - public JbootrpcServiceConfig(JbootrpcService annotation) { - this(); - - if (annotation.port() > 0) { - this.port = annotation.port(); - } - - if (StringUtils.isNotBlank(annotation.group())) { - this.group = annotation.group(); - } - - if (StringUtils.isNotBlank(annotation.version())) { - this.version = annotation.version(); - } - - if (annotation.retries() >= 0) { - this.retries = annotation.retries(); - } - - if (annotation.actives() >= 0) { - this.actives = annotation.actives(); - } - - if (StringUtils.isNotBlank(annotation.loadbalance())) { - this.loadbalance = annotation.loadbalance(); - } - - if (StringUtils.isNotBlank(annotation.async())) { - this.async = Boolean.getBoolean(annotation.async()); - } - - if (StringUtils.isNotBlank(annotation.check())) { - this.check = Boolean.getBoolean(annotation.check()); - } - - } - - - public String getGroup() { - return group; - } - - public void setGroup(String group) { - this.group = group; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public Integer getTimeout() { - return timeout; - } - - public void setTimeout(Integer timeout) { - this.timeout = timeout; - } - - public Integer getRetries() { - return retries; - } - - public void setRetries(Integer retries) { - this.retries = retries; - } - - public Integer getActives() { - return actives; - } - - public void setActives(Integer actives) { - this.actives = actives; - } - - public String getLoadbalance() { - return loadbalance; - } - - public void setLoadbalance(String loadbalance) { - this.loadbalance = loadbalance; - } - - public Boolean getAsync() { - return async; - } - - public void setAsync(Boolean async) { - this.async = async; - } - - public Boolean getCheck() { - return check; - } - - public void setCheck(Boolean check) { - this.check = check; - } - - public Map getParams() { - return params; - } - - public void setParams(Map params) { - this.params = params; - } - - public void addParam(Object key, Object value) { - if (params == null) { - params = new HashMap(); - } - - params.put(key, value); - } - - public String getProxy() { - return proxy; - } - - public void setProxy(String proxy) { - this.proxy = proxy; - } - - public String getFilter() { - return filter; - } - - public void setFilter(String filter) { - this.filter = filter; - } -} +/** + * Copyright (c) 2015-2018, Michael Yang 杨福海 (fuhai999@gmail.com). + *

+ * 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 + *

+ * http://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. + */ +package io.jboot.core.rpc; + +import io.jboot.Jboot; +import io.jboot.core.rpc.annotation.JbootrpcService; +import io.jboot.utils.StringUtils; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; + +/** + * @author Michael Yang 杨福海 (fuhai999@gmail.com) + * @version V1.0 + * @Package io.jboot.core.rpc + */ +public class JbootrpcServiceConfig implements Serializable { + + + private int port = 0; + private String group; + private String version; + private Integer timeout; + private Integer retries; + private Integer actives; + private String loadbalance; + private Boolean async; + private Boolean check; + + + private String proxy; + private String filter; + + // 用于扩展,用户通过SPI扩展获取自定义的 Service的时候, + // 若以字段不满足,此时通过 params 自行扩展 + private Map params; + + private static JbootrpcConfig defaultConfig = Jboot.config(JbootrpcConfig.class); + + + public JbootrpcServiceConfig() { + this.port = defaultConfig.getDefaultPort(); + this.group = defaultConfig.getDefaultGroup(); + this.version = defaultConfig.getDefaultVersion(); + this.timeout = defaultConfig.getRequestTimeOut(); + this.retries = defaultConfig.getRetries(); + } + + public JbootrpcServiceConfig(JbootrpcService annotation) { + this(); + + if (annotation.port() > 0) { + this.port = annotation.port(); + } + + if (StringUtils.isNotBlank(annotation.group())) { + this.group = annotation.group(); + } + + if (StringUtils.isNotBlank(annotation.version())) { + this.version = annotation.version(); + } + + if (annotation.retries() >= 0) { + this.retries = annotation.retries(); + } + + if (annotation.actives() >= 0) { + this.actives = annotation.actives(); + } + + if (StringUtils.isNotBlank(annotation.loadbalance())) { + this.loadbalance = annotation.loadbalance(); + } + + if (StringUtils.isNotBlank(annotation.async())) { + this.async = Boolean.valueOf(annotation.async()); + } + + if (StringUtils.isNotBlank(annotation.check())) { + this.check = Boolean.valueOf(annotation.check()); + } + + } + + + public String getGroup() { + return group; + } + + public void setGroup(String group) { + this.group = group; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public Integer getTimeout() { + return timeout; + } + + public void setTimeout(Integer timeout) { + this.timeout = timeout; + } + + public Integer getRetries() { + return retries; + } + + public void setRetries(Integer retries) { + this.retries = retries; + } + + public Integer getActives() { + return actives; + } + + public void setActives(Integer actives) { + this.actives = actives; + } + + public String getLoadbalance() { + return loadbalance; + } + + public void setLoadbalance(String loadbalance) { + this.loadbalance = loadbalance; + } + + public Boolean getAsync() { + return async; + } + + public void setAsync(Boolean async) { + this.async = async; + } + + public Boolean getCheck() { + return check; + } + + public void setCheck(Boolean check) { + this.check = check; + } + + public Map getParams() { + return params; + } + + public void setParams(Map params) { + this.params = params; + } + + public void addParam(Object key, Object value) { + if (params == null) { + params = new HashMap(); + } + + params.put(key, value); + } + + public String getProxy() { + return proxy; + } + + public void setProxy(String proxy) { + this.proxy = proxy; + } + + public String getFilter() { + return filter; + } + + public void setFilter(String filter) { + this.filter = filter; + } +} diff --git a/src/main/java/io/jboot/utils/FileUtils.java b/src/main/java/io/jboot/utils/FileUtils.java index b4833858d8535f2b65371dc34fa0c369e249acc7..1eb0743945e43691d1af9e6c98a524eb46f117b1 100644 --- a/src/main/java/io/jboot/utils/FileUtils.java +++ b/src/main/java/io/jboot/utils/FileUtils.java @@ -1,132 +1,137 @@ -/** - * Copyright (c) 2015-2018, Michael Yang 杨福海 (fuhai999@gmail.com). - *

- * 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 - *

- * http://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. - */ -package io.jboot.utils; - -import com.jfinal.core.JFinal; -import com.jfinal.kit.PathKit; - -import java.io.*; -import java.util.Enumeration; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - - -public class FileUtils { - - public static String getSuffix(String fileName) { - if (fileName != null && fileName.contains(".")) { - return fileName.substring(fileName.lastIndexOf(".")); - } - return null; - } - - - public static String removePrefix(String src, String prefix) { - if (src != null && src.startsWith(prefix)) { - return src.substring(prefix.length()); - } - return src; - } - - - public static String removeRootPath(String src){ - return removePrefix(src, PathKit.getWebRootPath()); - } - - public static String readString(File file) { - ByteArrayOutputStream baos = null; - FileInputStream fis = null; - try { - fis = new FileInputStream(file); - baos = new ByteArrayOutputStream(); - byte[] buffer = new byte[1024]; - for (int len = 0; (len = fis.read(buffer)) > 0;) { - baos.write(buffer, 0, len); - } - return new String(baos.toByteArray(), JFinal.me().getConstants().getEncoding()); - } catch (Exception e) { - } finally { - close(fis, baos); - } - return null; - } - - public static void writeString(File file, String string) { - FileOutputStream fos = null; - try { - fos = new FileOutputStream(file, false); - fos.write(string.getBytes(JFinal.me().getConstants().getEncoding())); - } catch (Exception e) { - } finally { - close(null, fos); - } - } - - private static void close(InputStream is, OutputStream os) { - if (is != null) - try { - is.close(); - } catch (IOException e) { - } - if (os != null) - try { - os.close(); - } catch (IOException e) { - } - } - - public static void unzip(String zipFilePath) throws IOException { - String targetPath = zipFilePath.substring(0, zipFilePath.lastIndexOf(".")); - unzip(zipFilePath, targetPath); - } - - public static void unzip(String zipFilePath, String targetPath) throws IOException { - ZipFile zipFile = new ZipFile(zipFilePath); - try{ - Enumeration entryEnum = zipFile.entries(); - if (null != entryEnum) { - while (entryEnum.hasMoreElements()) { - OutputStream os = null; - InputStream is = null; - try { - ZipEntry zipEntry = (ZipEntry) entryEnum.nextElement(); - if (!zipEntry.isDirectory()) { - File targetFile = new File(targetPath + File.separator + zipEntry.getName()); - if (!targetFile.getParentFile().exists()) { - targetFile.getParentFile().mkdirs(); - } - os = new BufferedOutputStream(new FileOutputStream(targetFile)); - is = zipFile.getInputStream(zipEntry); - byte[] buffer = new byte[4096]; - int readLen = 0; - while ((readLen = is.read(buffer, 0, 4096)) > 0) { - os.write(buffer, 0, readLen); - } - } - } finally { - if (is != null) - is.close(); - if (os != null) - os.close(); - } - } - } - }finally{ - zipFile.close(); - } - } - +/** + * Copyright (c) 2015-2018, Michael Yang 杨福海 (fuhai999@gmail.com). + *

+ * 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 + *

+ * http://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. + */ +package io.jboot.utils; + +import com.jfinal.core.JFinal; +import com.jfinal.kit.PathKit; + +import java.io.*; +import java.util.Enumeration; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + + +public class FileUtils { + + public static String getSuffix(String fileName) { + if (fileName != null && fileName.contains(".")) { + return fileName.substring(fileName.lastIndexOf(".")); + } + return null; + } + + + public static String removePrefix(String src, String prefix) { + if (src != null && src.startsWith(prefix)) { + return src.substring(prefix.length()); + } + return src; + } + + + public static String removeRootPath(String src){ + return removePrefix(src, PathKit.getWebRootPath()); + } + + public static String readString(File file) { + ByteArrayOutputStream baos = null; + FileInputStream fis = null; + try { + fis = new FileInputStream(file); + baos = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + for (int len = 0; (len = fis.read(buffer)) > 0;) { + baos.write(buffer, 0, len); + } + return new String(baos.toByteArray(), JFinal.me().getConstants().getEncoding()); + } catch (Exception e) { + } finally { + close(fis, baos); + } + return null; + } + + public static void writeString(File file, String string) { + FileOutputStream fos = null; + try { + fos = new FileOutputStream(file, false); + fos.write(string.getBytes(JFinal.me().getConstants().getEncoding())); + } catch (Exception e) { + } finally { + close(null, fos); + } + } + + private static void close(InputStream is, OutputStream os) { + if (is != null) + try { + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + if (os != null) + try { + os.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static void unzip(String zipFilePath) throws IOException { + String targetPath = zipFilePath.substring(0, zipFilePath.lastIndexOf(".")); + unzip(zipFilePath, targetPath); + } + + public static void unzip(String zipFilePath, String targetPath) throws IOException { + ZipFile zipFile = new ZipFile(zipFilePath); + try{ + Enumeration entryEnum = zipFile.entries(); + if (null != entryEnum) { + while (entryEnum.hasMoreElements()) { + OutputStream os = null; + InputStream is = null; + try { + ZipEntry zipEntry = (ZipEntry) entryEnum.nextElement(); + if (!zipEntry.isDirectory()) { + File targetFile = new File(targetPath + File.separator + zipEntry.getName()); + if (!targetFile.getParentFile().exists()) { + targetFile.getParentFile().mkdirs(); + } + os = new BufferedOutputStream(new FileOutputStream(targetFile)); + is = zipFile.getInputStream(zipEntry); + byte[] buffer = new byte[4096]; + int readLen = 0; + while ((readLen = is.read(buffer, 0, 4096)) > 0) { + os.write(buffer, 0, readLen); + } + } + } finally { + close(is,os); + } + } + } + }finally{ + if(zipFile != null) { + try { + zipFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + } \ No newline at end of file