Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update #586

Merged
merged 6 commits into from
Aug 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions jcommon/docean/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,13 @@
<version>2.8.5</version>
</dependency>

<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.10.0</version>
<scope>test</scope>
</dependency>

</dependencies>

</project>
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import com.xiaomi.youpin.docean.mvc.*;
import com.xiaomi.youpin.docean.mvc.common.MvcConst;
import com.xiaomi.youpin.docean.mvc.util.ExceptionUtil;
import com.xiaomi.youpin.docean.mvc.util.Jump;
import io.netty.handler.codec.http.*;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
Expand Down Expand Up @@ -183,12 +184,7 @@ public void callMethod(MvcContext context, MvcRequest request, MvcResponse respo
}
// need to jump (302)
if (mr.getCode() == HttpResponseStatus.FOUND.code()) {
FullHttpResponse response302 = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FOUND);
response302.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
response302.headers().set(HttpHeaderNames.CONNECTION, "keep-alive");
response302.headers().set(HttpHeaderNames.LOCATION, mr.getData());
HttpUtil.setKeepAlive(response302, true);
response.getCtx().writeAndFlush(response302);
Jump.jump(response,mr.getData());
return;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,7 @@
package com.xiaomi.youpin.docean.mvc;

import com.xiaomi.youpin.docean.Ioc;
import com.xiaomi.youpin.docean.common.Cons;
import com.xiaomi.youpin.docean.common.DoceanVersion;
import com.xiaomi.youpin.docean.common.NamedThreadFactory;
import com.xiaomi.youpin.docean.common.NetUtils;
import com.xiaomi.youpin.docean.common.*;
import com.xiaomi.youpin.docean.config.HttpServerConfig;
import com.xiaomi.youpin.docean.exception.DoceanException;
import com.xiaomi.youpin.docean.mvc.upload.HttpUploadHandler;
Expand All @@ -41,6 +38,7 @@
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.net.InetSocketAddress;
import java.util.concurrent.CountDownLatch;

Expand Down Expand Up @@ -68,12 +66,26 @@ public DoceanHttpServer(HttpServerConfig config) {
}

if (this.config.isSsl()) {
try {
SelfSignedCertificate certificate = new SelfSignedCertificate("youpinfs.com");
sslContext = SslContextBuilder.forServer(certificate.certificate(), certificate.privateKey()).build();
} catch (Throwable ex) {
log.warn("error:{}", ex.getMessage());
}
Safe.runAndLog(() -> {
String domain = Ioc.ins().getBean("$ssl_domain");
boolean test = Boolean.valueOf(Ioc.ins().getBean("$ssl_self_sign", "true"));
if (test) {
SelfSignedCertificate certificate = new SelfSignedCertificate(domain);
sslContext = SslContextBuilder.forServer(certificate.certificate(), certificate.privateKey()).build();
} else {
String certificate = Ioc.ins().getBean("$ssl_certificate");
String privateKey = Ioc.ins().getBean("$ssl_cprivateKey");
if (StringUtils.isEmpty(certificate) || StringUtils.isEmpty(privateKey)) {
String message = "Please provide the file addresses of the public key and private key.";
log.error(message);
throw new RuntimeException(message);
}

File certChainFile = new File(certificate);
File privateKeyFile = new File(privateKey);
sslContext = SslContextBuilder.forServer(certChainFile, privateKeyFile).build();
}
});
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import com.xiaomi.youpin.docean.mvc.util.RequestUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.DecoderException;
import io.netty.handler.codec.http.FullHttpRequest;
import lombok.extern.slf4j.Slf4j;

Expand Down Expand Up @@ -69,6 +70,12 @@ protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request)

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
if (cause instanceof DecoderException) {
DecoderException ex = (DecoderException) cause;
if (ex.getMessage().contains("certificate_unknown")) {
return;
}
}
log.info("remote address:{} error:{}", ctx.channel().remoteAddress(), cause.getMessage());
if (null != ctx.channel() && ctx.channel().isOpen() && ctx.channel().isActive()) {
ctx.channel().close();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ public static FullHttpResponse create(FullHttpResponse res) {
} else {
res.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
}
res.headers().set(HttpHeaderNames.CONNECTION, "close");
return res;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

package com.xiaomi.youpin.docean.mvc;

import com.xiaomi.youpin.docean.Ioc;
import com.xiaomi.youpin.docean.common.StringUtils;
import com.xiaomi.youpin.docean.mvc.session.HttpSessionManager;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
Expand All @@ -25,8 +25,6 @@
import lombok.Getter;
import lombok.Setter;

import java.util.Objects;

/**
* @author [email protected]
* @date 2020/6/21
Expand All @@ -52,6 +50,9 @@ public void writeAndFlush(MvcContext context, HttpResponseStatus status, String
response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
}
HttpSessionManager.setSessionId(context, HttpSessionManager.isHasSessionId(context.getHeaders()), response);
if (StringUtils.isNotEmpty(context.getRequest().headers().get(HttpHeaderNames.CONNECTION))) {
response.headers().add(HttpHeaderNames.CONNECTION,context.getRequest().headers().get(HttpHeaderNames.CONNECTION));
}
ctx.writeAndFlush(response);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.xiaomi.youpin.docean.mvc.util;

import com.xiaomi.youpin.docean.mvc.MvcResponse;
import io.netty.handler.codec.http.*;

/**
* @author [email protected]
* @date 2023/8/17 10:18
*/
public class Jump {

public static void jump(MvcResponse response, String location) {
FullHttpResponse response302 = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FOUND);
response302.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
response302.headers().set(HttpHeaderNames.CONNECTION, "keep-alive");
response302.headers().set(HttpHeaderNames.LOCATION, location);
HttpUtil.setKeepAlive(response302, true);
response.getCtx().writeAndFlush(response302);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import com.xiaomi.youpin.docean.test.anno.TAnno;
import com.xiaomi.youpin.docean.test.demo.ErrorReport;
import com.xiaomi.youpin.docean.test.interceptor.TAInterceptor;
import com.xiaomi.youpin.docean.test.ssl.HttpClient;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

Expand Down Expand Up @@ -69,12 +70,21 @@ public void before(AopContext aopContext, Method method, Object[] args) {
System.exit(-1);
}


Ioc.ins().putBean("$response-original-value","true");
Ioc.ins().putBean("$ssl_domain","zzy.com");
Ioc.ins().putBean("$ssl_self_sign","false");

Mvc.ins();
DoceanHttpServer server = new DoceanHttpServer(HttpServerConfig.builder().port(8999).websocket(true)
DoceanHttpServer server = new DoceanHttpServer(HttpServerConfig.builder().port(8999).websocket(false).ssl(false)
.uploadDir("/tmp/v").upload(true)
.build());
server.start();
}


@Test
public void testClient() {
HttpClient.call();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.xiaomi.youpin.docean.test;

import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.cert.CertificateException;

/**
* @author [email protected]
* @date 2023/8/17 11:45
*/
public class KeyTest {


@Test
public void test1() throws CertificateException, IOException {
SelfSignedCertificate certificate = new SelfSignedCertificate("zzy.com");
File file = certificate.privateKey();
byte[] data = (Files.readAllBytes(Paths.get(file.getPath())));
System.out.println(new String(data));
Files.write(Paths.get("/Users/zhangzhiyong/key/zzy.com/private"),data);

Files.write(Paths.get("/Users/zhangzhiyong/key/zzy.com/public"),Files.readAllBytes(Paths.get(certificate.certificate().toURI())));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import com.xiaomi.youpin.docean.mvc.MvcContext;
import com.xiaomi.youpin.docean.mvc.MvcResult;
import com.xiaomi.youpin.docean.test.anno.TAnno;
import com.xiaomi.youpin.docean.test.bo.M;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

Expand Down Expand Up @@ -58,7 +59,7 @@ public DemoVo header(MvcContext context) {
DemoVo vo = new DemoVo();
vo.setId("1");
vo.setName("test");
context.getResHeaders().put("name","zzy");
context.getResHeaders().put("name", "zzy");
return vo;
}

Expand All @@ -75,6 +76,15 @@ public String a() {
return "a";
}


@RequestMapping(path = "/p")
public M p(MvcContext c, M m) {
log.info("{}", c.getHeaders());
m.setName("zz");
return m;
}


@RequestMapping(path = "/test2")
public DemoVo test2(MvcContext context, DemoVo req) {
log.info("{}", context);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package com.xiaomi.youpin.docean.test.ssl;

import lombok.SneakyThrows;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import javax.net.ssl.*;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

/**
* @author [email protected]
* @date 2023/8/17 14:19
*/
public class HttpClient {


@SneakyThrows
public static void call() {
CertificateFactory cf = CertificateFactory.getInstance("X.509");

InputStream caInput = new BufferedInputStream(new FileInputStream("/Users/zhangzhiyong/key/zzy.com/certificate.crt"));
Certificate ca;
try {
ca = cf.generateCertificate(caInput);
System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
caInput.close();
}

String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);

String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);

X509TrustManager trustManager = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{}; // 返回受信任的证书数组
}
public void checkClientTrusted(X509Certificate[] chain, String authType) {
// 检查客户端证书
}
public void checkServerTrusted(X509Certificate[] chain, String authType) {
// 检查服务器证书
}
};

OkHttpClient client = new OkHttpClient.Builder()
.sslSocketFactory(sslContext.getSocketFactory(), trustManager)
.hostnameVerifier((hostname, session) -> true)
.build();

Request request = new Request.Builder()
.url("https://zzy.com:8999/a?id="+System.currentTimeMillis())
.build();

Response res = client.newCall(request).execute();
ResponseBody body = res.body();
String str = body.string();
System.out.println(str);
}

}
6 changes: 2 additions & 4 deletions jcommon/http/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
# http

本模块提供了多个版本的httpclient调用的封装,以及相应的调用示例。

官网地址:https://xmmione.be.mi.com/web/index
+ http 客户端(有用apache实现的,有用netty实现的)
+ 本模块提供了多个版本的httpclient调用的封装,以及相应的调用示例。

9 changes: 5 additions & 4 deletions jcommon/http/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,13 @@
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.70</version>
<scope>compile</scope>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.11.0</version>
<scope>provided</scope>
</dependency>


</dependencies>


Expand Down
Loading
Loading