index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyCodecAdapter.java
/* * 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 * * 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 org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.exchange.support.MultiMessage; import java.io.IOException; import java.util.List; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.MessageToByteEncoder; /** * NettyCodecAdapter. */ public final class NettyCodecAdapter { private final ChannelHandler encoder = new InternalEncoder(); private final ChannelHandler decoder = new InternalDecoder(); private final Codec2 codec; private final URL url; private final org.apache.dubbo.remoting.ChannelHandler handler; public NettyCodecAdapter(Codec2 codec, URL url, org.apache.dubbo.remoting.ChannelHandler handler) { this.codec = codec; this.url = url; this.handler = handler; } public ChannelHandler getEncoder() { return encoder; } public ChannelHandler getDecoder() { return decoder; } private class InternalEncoder extends MessageToByteEncoder { @Override protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception { boolean encoded = false; if (msg instanceof ByteBuf) { out.writeBytes(((ByteBuf) msg)); encoded = true; } else if (msg instanceof MultiMessage) { for (Object singleMessage : ((MultiMessage) msg)) { if (singleMessage instanceof ByteBuf) { ByteBuf buf = (ByteBuf) singleMessage; out.writeBytes(buf); encoded = true; buf.release(); } } } if (!encoded) { ChannelBuffer buffer = new NettyBackedChannelBuffer(out); Channel ch = ctx.channel(); NettyChannel channel = NettyChannel.getOrAddChannel(ch, url, handler); codec.encode(channel, buffer, msg); } } } private class InternalDecoder extends ByteToMessageDecoder { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf input, List<Object> out) throws Exception { ChannelBuffer message = new NettyBackedChannelBuffer(input); NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); // decode object. do { int saveReaderIndex = message.readerIndex(); Object msg = codec.decode(channel, message); if (msg == Codec2.DecodeResult.NEED_MORE_INPUT) { message.readerIndex(saveReaderIndex); break; } else { // is it possible to go here ? if (saveReaderIndex == message.readerIndex()) { throw new IOException("Decode without read data."); } if (msg != null) { out.add(msg); } } } while (message.readable()); } } }
7,600
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettySslContextOperator.java
/* * 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 * * 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 org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.remoting.api.ssl.ContextOperator; import io.netty.handler.ssl.SslContext; public class NettySslContextOperator implements ContextOperator { @Override public SslContext buildContext() { return null; } }
7,601
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/Netty4BatchWriteQueue.java
/* * 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 * * 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 org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.BatchExecutorQueue; import org.apache.dubbo.remoting.exchange.support.MultiMessage; import java.util.LinkedList; import java.util.Queue; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelPromise; import io.netty.channel.EventLoop; /** * netty4 batch write queue */ public class Netty4BatchWriteQueue extends BatchExecutorQueue<Netty4BatchWriteQueue.MessageTuple> { private final Channel channel; private final EventLoop eventLoop; private final Queue<ChannelPromise> promises = new LinkedList<>(); private final MultiMessage multiMessage = MultiMessage.create(); private Netty4BatchWriteQueue(Channel channel) { this.channel = channel; this.eventLoop = channel.eventLoop(); } public ChannelFuture enqueue(Object message) { return enqueue(message, channel.newPromise()); } public ChannelFuture enqueue(Object message, ChannelPromise channelPromise) { MessageTuple messageTuple = new MessageTuple(message, channelPromise); super.enqueue(messageTuple, eventLoop); return messageTuple.channelPromise; } @Override protected void prepare(MessageTuple item) { multiMessage.addMessage(item.originMessage); promises.add(item.channelPromise); } @Override protected void flush(MessageTuple item) { prepare(item); Object finalMessage = multiMessage; if (multiMessage.size() == 1) { finalMessage = multiMessage.get(0); } channel.writeAndFlush(finalMessage).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { ChannelPromise cp; while ((cp = promises.poll()) != null) { if (future.isSuccess()) { cp.setSuccess(); } else { cp.setFailure(future.cause()); } } } }); this.multiMessage.removeMessages(); } public static Netty4BatchWriteQueue createWriteQueue(Channel channel) { return new Netty4BatchWriteQueue(channel); } static class MessageTuple { private final Object originMessage; private final ChannelPromise channelPromise; public MessageTuple(Object originMessage, ChannelPromise channelPromise) { this.originMessage = originMessage; this.channelPromise = channelPromise; } } }
7,602
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyConnectionClient.java
/* * 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 * * 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 org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.api.WireProtocol; import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient; import org.apache.dubbo.remoting.transport.netty4.ssl.SslClientTlsHandler; import org.apache.dubbo.remoting.transport.netty4.ssl.SslContexts; import org.apache.dubbo.remoting.utils.UrlUtils; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoop; import io.netty.channel.socket.SocketChannel; import io.netty.handler.ssl.SslContext; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.AttributeKey; import io.netty.util.concurrent.DefaultPromise; import io.netty.util.concurrent.GlobalEventExecutor; import io.netty.util.concurrent.Promise; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_CLIENT_CONNECT_TIMEOUT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CONNECT_PROVIDER; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_RECONNECT; import static org.apache.dubbo.remoting.transport.netty4.NettyEventLoopFactory.socketChannelClass; public class NettyConnectionClient extends AbstractConnectionClient { private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(NettyConnectionClient.class); private AtomicReference<Promise<Object>> connectingPromise; private Promise<Void> closePromise; private AtomicReference<io.netty.channel.Channel> channel; private ConnectionListener connectionListener; private Bootstrap bootstrap; public static final AttributeKey<AbstractConnectionClient> CONNECTION = AttributeKey.valueOf("connection"); public NettyConnectionClient(URL url, ChannelHandler handler) throws RemotingException { super(url, handler); } @Override protected void initConnectionClient() { this.protocol = getUrl().getOrDefaultFrameworkModel() .getExtensionLoader(WireProtocol.class) .getExtension(getUrl().getProtocol()); this.remote = getConnectAddress(); this.connectingPromise = new AtomicReference<>(); this.connectionListener = new ConnectionListener(); this.channel = new AtomicReference<>(); this.closePromise = new DefaultPromise<>(GlobalEventExecutor.INSTANCE); this.init = new AtomicBoolean(false); this.increase(); } @Override protected void doOpen() throws Throwable { initConnectionClient(); initBootstrap(); } private void initBootstrap() { final Bootstrap nettyBootstrap = new Bootstrap(); nettyBootstrap .group(NettyEventLoopFactory.NIO_EVENT_LOOP_GROUP.get()) .option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .remoteAddress(getConnectAddress()) .channel(socketChannelClass()); final NettyConnectionHandler connectionHandler = new NettyConnectionHandler(this); nettyBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getConnectTimeout()); SslContext sslContext = SslContexts.buildClientSslContext(getUrl()); nettyBootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { NettyChannel nettyChannel = NettyChannel.getOrAddChannel(ch, getUrl(), getChannelHandler()); final ChannelPipeline pipeline = ch.pipeline(); NettySslContextOperator nettySslContextOperator = new NettySslContextOperator(); if (sslContext != null) { pipeline.addLast("negotiation", new SslClientTlsHandler(sslContext)); } // pipeline.addLast("logging", new LoggingHandler(LogLevel.INFO)); //for debug int heartbeat = UrlUtils.getHeartbeat(getUrl()); pipeline.addLast("client-idle-handler", new IdleStateHandler(heartbeat, 0, 0, MILLISECONDS)); pipeline.addLast(Constants.CONNECTION_HANDLER_NAME, connectionHandler); NettyConfigOperator operator = new NettyConfigOperator(nettyChannel, getChannelHandler()); protocol.configClientPipeline(getUrl(), operator, nettySslContextOperator); ch.closeFuture().addListener(channelFuture -> doClose()); // TODO support Socks5 } }); this.bootstrap = nettyBootstrap; } @Override protected void doClose() { // AbstractPeer close can set closed true. if (isClosed()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("Connection:%s freed ", this)); } final io.netty.channel.Channel current = getNettyChannel(); if (current != null) { current.close(); } this.channel.set(null); closePromise.setSuccess(null); } } @Override protected void doConnect() throws RemotingException { if (isClosed()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug( String.format("%s aborted to reconnect cause connection closed. ", NettyConnectionClient.this)); } } init.compareAndSet(false, true); long start = System.currentTimeMillis(); createConnectingPromise(); final ChannelFuture promise = bootstrap.connect(); promise.addListener(this.connectionListener); boolean ret = connectingPromise.get().awaitUninterruptibly(getConnectTimeout(), TimeUnit.MILLISECONDS); // destroy connectingPromise after used synchronized (this) { connectingPromise.set(null); } if (promise.cause() != null) { Throwable cause = promise.cause(); // 6-1 Failed to connect to provider server by other reason. RemotingException remotingException = new RemotingException( this, "client(url: " + getUrl() + ") failed to connect to server " + getConnectAddress() + ", error message is:" + cause.getMessage(), cause); LOGGER.error( TRANSPORT_FAILED_CONNECT_PROVIDER, "network disconnected", "", "Failed to connect to provider server by other reason.", cause); throw remotingException; } else if (!ret || !promise.isSuccess()) { // 6-2 Client-side timeout RemotingException remotingException = new RemotingException( this, "client(url: " + getUrl() + ") failed to connect to server " + getConnectAddress() + " client-side timeout " + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client " + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()); LOGGER.error( TRANSPORT_CLIENT_CONNECT_TIMEOUT, "provider crash", "", "Client-side timeout.", remotingException); throw remotingException; } } @Override protected void doDisConnect() { NettyChannel.removeChannelIfDisconnected(getNettyChannel()); } @Override public void onConnected(Object channel) { if (!(channel instanceof io.netty.channel.Channel)) { return; } io.netty.channel.Channel nettyChannel = ((io.netty.channel.Channel) channel); if (isClosed()) { nettyChannel.close(); if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("%s is closed, ignoring connected event", this)); } return; } this.channel.set(nettyChannel); // This indicates that the connection is available. if (this.connectingPromise.get() != null) { this.connectingPromise.get().trySuccess(CONNECTED_OBJECT); } nettyChannel.attr(CONNECTION).set(this); if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("%s connected ", this)); } } @Override public void onGoaway(Object channel) { if (!(channel instanceof io.netty.channel.Channel)) { return; } io.netty.channel.Channel nettyChannel = (io.netty.channel.Channel) channel; if (this.channel.compareAndSet(nettyChannel, null)) { NettyChannel.removeChannelIfDisconnected(nettyChannel); if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("%s goaway", this)); } } } @Override protected Channel getChannel() { io.netty.channel.Channel c = getNettyChannel(); if (c == null) { return null; } return NettyChannel.getOrAddChannel(c, getUrl(), this); } io.netty.channel.Channel getNettyChannel() { return this.channel.get(); } @Override public Object getChannel(Boolean generalizable) { return Boolean.TRUE.equals(generalizable) ? getNettyChannel() : getChannel(); } @Override public boolean isAvailable() { if (isClosed()) { return false; } io.netty.channel.Channel nettyChannel = getNettyChannel(); if (nettyChannel != null && nettyChannel.isActive()) { return true; } if (init.compareAndSet(false, true)) { try { doConnect(); } catch (RemotingException e) { LOGGER.error(TRANSPORT_FAILED_RECONNECT, "", "", "Failed to connect to server: " + getConnectAddress()); } } createConnectingPromise(); connectingPromise.get().awaitUninterruptibly(getConnectTimeout(), TimeUnit.MILLISECONDS); // destroy connectingPromise after used synchronized (this) { connectingPromise.set(null); } nettyChannel = getNettyChannel(); return nettyChannel != null && nettyChannel.isActive(); } @Override public void createConnectingPromise() { connectingPromise.compareAndSet(null, new DefaultPromise<>(GlobalEventExecutor.INSTANCE)); } public Promise<Void> getClosePromise() { return closePromise; } public static AbstractConnectionClient getConnectionClientFromChannel(io.netty.channel.Channel channel) { return channel.attr(CONNECTION).get(); } public ChannelFuture write(Object request) throws RemotingException { if (!isAvailable()) { throw new RemotingException( null, null, "Failed to send request " + request + ", cause: The channel to " + remote + " is closed!"); } return ((io.netty.channel.Channel) getChannel()).writeAndFlush(request); } @Override public void addCloseListener(Runnable func) { getClosePromise().addListener(future -> func.run()); } @Override public void destroy() { close(); } @Override public String toString() { return super.toString() + " (Ref=" + this.getCounter() + ",local=" + (getChannel() == null ? null : getChannel().getLocalAddress()) + ",remote=" + getRemoteAddress(); } class ConnectionListener implements ChannelFutureListener { @Override public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { return; } final NettyConnectionClient connectionClient = NettyConnectionClient.this; if (connectionClient.isClosed() || connectionClient.getCounter() == 0) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format( "%s aborted to reconnect. %s", connectionClient, future.cause().getMessage())); } return; } if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format( "%s is reconnecting, attempt=%d cause=%s", connectionClient, 0, future.cause().getMessage())); } final EventLoop loop = future.channel().eventLoop(); loop.schedule( () -> { try { connectionClient.doConnect(); } catch (RemotingException e) { LOGGER.error( TRANSPORT_FAILED_RECONNECT, "", "", "Failed to connect to server: " + getConnectAddress()); } }, 1L, TimeUnit.SECONDS); } } }
7,603
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServerHandler.java
/* * 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 * * 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 org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import java.net.InetSocketAddress; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.handler.timeout.IdleStateEvent; /** * NettyServerHandler. */ @io.netty.channel.ChannelHandler.Sharable public class NettyServerHandler extends ChannelDuplexHandler { private static final Logger logger = LoggerFactory.getLogger(NettyServerHandler.class); /** * the cache for alive worker channel. * <ip:port, dubbo channel> */ private final Map<String, Channel> channels = new ConcurrentHashMap<>(); private final URL url; private final ChannelHandler handler; public NettyServerHandler(URL url, ChannelHandler handler) { if (url == null) { throw new IllegalArgumentException("url == null"); } if (handler == null) { throw new IllegalArgumentException("handler == null"); } this.url = url; this.handler = handler; } public Map<String, Channel> getChannels() { return channels; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); if (channel != null) { channels.put( NetUtils.toAddressString((InetSocketAddress) ctx.channel().remoteAddress()), channel); } handler.connected(channel); if (logger.isInfoEnabled()) { logger.info("The connection of " + channel.getRemoteAddress() + " -> " + channel.getLocalAddress() + " is established."); } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); try { channels.remove( NetUtils.toAddressString((InetSocketAddress) ctx.channel().remoteAddress())); handler.disconnected(channel); } finally { NettyChannel.removeChannel(ctx.channel()); } if (logger.isInfoEnabled()) { logger.info("The connection of " + channel.getRemoteAddress() + " -> " + channel.getLocalAddress() + " is disconnected."); } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); handler.received(channel, msg); // trigger qos handler ctx.fireChannelRead(msg); } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { super.write(ctx, msg, promise); NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); handler.sent(channel, msg); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { // server will close channel when server don't receive any heartbeat from client util timeout. if (evt instanceof IdleStateEvent) { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); try { logger.info("IdleStateEvent triggered, close channel " + channel); channel.close(); } finally { NettyChannel.removeChannelIfDisconnected(ctx.channel()); } } super.userEventTriggered(ctx, evt); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); try { handler.caught(channel, cause); } finally { NettyChannel.removeChannelIfDisconnected(ctx.channel()); } } }
7,604
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyBackedChannelBuffer.java
/* * 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 * * 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 org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBufferFactory; import org.apache.dubbo.remoting.buffer.ChannelBuffers; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import io.netty.buffer.ByteBuf; import io.netty.util.ReferenceCountUtil; public class NettyBackedChannelBuffer implements ChannelBuffer { private final ByteBuf buffer; public NettyBackedChannelBuffer(ByteBuf buffer) { Assert.notNull(buffer, "buffer == null"); this.buffer = buffer; } @Override public int capacity() { return buffer.capacity(); } @Override public ChannelBuffer copy(int index, int length) { return new NettyBackedChannelBuffer(buffer.copy(index, length)); } // has nothing use @Override public ChannelBufferFactory factory() { return null; } @Override public byte getByte(int index) { return buffer.getByte(index); } @Override public void getBytes(int index, byte[] dst, int dstIndex, int length) { buffer.getBytes(index, dst, dstIndex, length); } @Override public void getBytes(int index, ByteBuffer dst) { buffer.getBytes(index, dst); } @Override public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { // careful byte[] data = new byte[length]; buffer.getBytes(index, data, 0, length); dst.setBytes(dstIndex, data, 0, length); } @Override public void getBytes(int index, OutputStream dst, int length) throws IOException { buffer.getBytes(index, dst, length); } @Override public boolean isDirect() { return buffer.isDirect(); } @Override public void setByte(int index, int value) { buffer.setByte(index, value); } @Override public void setBytes(int index, byte[] src, int srcIndex, int length) { buffer.setBytes(index, src, srcIndex, length); } @Override public void setBytes(int index, ByteBuffer src) { buffer.setBytes(index, src); } @Override public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { if (length > src.readableBytes()) { throw new IndexOutOfBoundsException(); } // careful byte[] data = new byte[length]; src.getBytes(srcIndex, data, 0, length); setBytes(index, data, 0, length); } @Override public int setBytes(int index, InputStream src, int length) throws IOException { return buffer.setBytes(index, src, length); } @Override public ByteBuffer toByteBuffer(int index, int length) { return buffer.nioBuffer(index, length); } @Override public byte[] array() { return buffer.array(); } @Override public boolean hasArray() { return buffer.hasArray(); } @Override public int arrayOffset() { return buffer.arrayOffset(); } // AbstractChannelBuffer @Override public void clear() { buffer.clear(); } @Override public ChannelBuffer copy() { return new NettyBackedChannelBuffer(buffer.copy()); } @Override public void discardReadBytes() { buffer.discardReadBytes(); } @Override public void ensureWritableBytes(int writableBytes) { buffer.ensureWritable(writableBytes); } @Override public void getBytes(int index, byte[] dst) { buffer.getBytes(index, dst); } @Override public void getBytes(int index, ChannelBuffer dst) { // careful getBytes(index, dst, dst.writableBytes()); } @Override public void getBytes(int index, ChannelBuffer dst, int length) { // careful if (length > dst.writableBytes()) { throw new IndexOutOfBoundsException(); } getBytes(index, dst, dst.writerIndex(), length); dst.writerIndex(dst.writerIndex() + length); } @Override public void markReaderIndex() { buffer.markReaderIndex(); } @Override public void markWriterIndex() { buffer.markWriterIndex(); } @Override public boolean readable() { return buffer.isReadable(); } @Override public int readableBytes() { return buffer.readableBytes(); } @Override public byte readByte() { return buffer.readByte(); } @Override public void readBytes(byte[] dst) { buffer.readBytes(dst); } @Override public void readBytes(byte[] dst, int dstIndex, int length) { buffer.readBytes(dst, dstIndex, length); } @Override public void readBytes(ByteBuffer dst) { buffer.readBytes(dst); } @Override public void readBytes(ChannelBuffer dst) { // careful readBytes(dst, dst.writableBytes()); } @Override public void readBytes(ChannelBuffer dst, int length) { // careful if (length > dst.writableBytes()) { throw new IndexOutOfBoundsException(); } readBytes(dst, dst.writerIndex(), length); dst.writerIndex(dst.writerIndex() + length); } @Override public void readBytes(ChannelBuffer dst, int dstIndex, int length) { // careful if (readableBytes() < length) { throw new IndexOutOfBoundsException(); } byte[] data = new byte[length]; buffer.readBytes(data, 0, length); dst.setBytes(dstIndex, data, 0, length); } @Override public ChannelBuffer readBytes(int length) { return new NettyBackedChannelBuffer(buffer.readBytes(length)); } @Override public void resetReaderIndex() { buffer.resetReaderIndex(); } @Override public void resetWriterIndex() { buffer.resetWriterIndex(); } @Override public int readerIndex() { return buffer.readerIndex(); } @Override public void readerIndex(int readerIndex) { buffer.readerIndex(readerIndex); } @Override public void readBytes(OutputStream dst, int length) throws IOException { buffer.readBytes(dst, length); } @Override public void setBytes(int index, byte[] src) { buffer.setBytes(index, src); } @Override public void setBytes(int index, ChannelBuffer src) { // careful setBytes(index, src, src.readableBytes()); } @Override public void setBytes(int index, ChannelBuffer src, int length) { // careful if (length > src.readableBytes()) { throw new IndexOutOfBoundsException(); } setBytes(index, src, src.readerIndex(), length); src.readerIndex(src.readerIndex() + length); } @Override public void setIndex(int readerIndex, int writerIndex) { buffer.setIndex(readerIndex, writerIndex); } @Override public void skipBytes(int length) { buffer.skipBytes(length); } @Override public ByteBuffer toByteBuffer() { return buffer.nioBuffer(); } @Override public boolean writable() { return buffer.isWritable(); } @Override public int writableBytes() { return buffer.writableBytes(); } @Override public void writeByte(int value) { buffer.writeByte(value); } @Override public void writeBytes(byte[] src) { buffer.writeBytes(src); } @Override public void writeBytes(byte[] src, int index, int length) { buffer.writeBytes(src, index, length); } @Override public void writeBytes(ByteBuffer src) { buffer.writeBytes(src); } @Override public void writeBytes(ChannelBuffer src) { // careful writeBytes(src, src.readableBytes()); } @Override public void writeBytes(ChannelBuffer src, int length) { // careful if (length > src.readableBytes()) { throw new IndexOutOfBoundsException(); } writeBytes(src, src.readerIndex(), length); src.readerIndex(src.readerIndex() + length); } @Override public void writeBytes(ChannelBuffer src, int srcIndex, int length) { // careful byte[] data = new byte[length]; src.getBytes(srcIndex, data, 0, length); writeBytes(data, 0, length); } @Override public int writeBytes(InputStream src, int length) throws IOException { return buffer.writeBytes(src, length); } @Override public int writerIndex() { return buffer.writerIndex(); } @Override public void writerIndex(int writerIndex) { buffer.ensureWritable(writerIndex); buffer.writerIndex(writerIndex); } @Override public int compareTo(ChannelBuffer o) { return ChannelBuffers.compare(this, o); } public void release() { ReferenceCountUtil.safeRelease(buffer); } }
7,605
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyServer.java
/* * 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 * * 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 org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.transport.AbstractServer; import org.apache.dubbo.remoting.transport.dispatcher.ChannelHandlers; import org.apache.dubbo.remoting.transport.netty4.ssl.SslServerTlsHandler; import org.apache.dubbo.remoting.utils.UrlUtils; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.concurrent.Future; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.KEEP_ALIVE_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE; import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_BOSS_POOL_NAME; import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_WORKER_POOL_NAME; /** * NettyServer. */ public class NettyServer extends AbstractServer { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NettyServer.class); /** * the cache for alive worker channel. * <ip:port, dubbo channel> */ private Map<String, Channel> channels; /** * netty server bootstrap. */ private ServerBootstrap bootstrap; /** * the boss channel that receive connections and dispatch these to worker channel. */ private io.netty.channel.Channel channel; private EventLoopGroup bossGroup; private EventLoopGroup workerGroup; private final int serverShutdownTimeoutMills; public NettyServer(URL url, ChannelHandler handler) throws RemotingException { // you can customize name and type of client thread pool by THREAD_NAME_KEY and THREAD_POOL_KEY in // CommonConstants. // the handler will be wrapped: MultiMessageHandler->HeartbeatHandler->handler super(url, ChannelHandlers.wrap(handler, url)); // read config before destroy serverShutdownTimeoutMills = ConfigurationUtils.getServerShutdownTimeout(getUrl().getOrDefaultModuleModel()); } /** * Init and start netty server * * @throws Throwable */ @Override protected void doOpen() throws Throwable { bootstrap = new ServerBootstrap(); bossGroup = createBossGroup(); workerGroup = createWorkerGroup(); final NettyServerHandler nettyServerHandler = createNettyServerHandler(); channels = nettyServerHandler.getChannels(); initServerBootstrap(nettyServerHandler); // bind try { ChannelFuture channelFuture = bootstrap.bind(getBindAddress()); channelFuture.syncUninterruptibly(); channel = channelFuture.channel(); } catch (Throwable t) { closeBootstrap(); throw t; } } protected EventLoopGroup createBossGroup() { return NettyEventLoopFactory.eventLoopGroup(1, EVENT_LOOP_BOSS_POOL_NAME); } protected EventLoopGroup createWorkerGroup() { return NettyEventLoopFactory.eventLoopGroup( getUrl().getPositiveParameter(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS), EVENT_LOOP_WORKER_POOL_NAME); } protected NettyServerHandler createNettyServerHandler() { return new NettyServerHandler(getUrl(), this); } protected void initServerBootstrap(NettyServerHandler nettyServerHandler) { boolean keepalive = getUrl().getParameter(KEEP_ALIVE_KEY, Boolean.FALSE); bootstrap .group(bossGroup, workerGroup) .channel(NettyEventLoopFactory.serverSocketChannelClass()) .option(ChannelOption.SO_REUSEADDR, Boolean.TRUE) .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE) .childOption(ChannelOption.SO_KEEPALIVE, keepalive) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { int closeTimeout = UrlUtils.getCloseTimeout(getUrl()); NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this); ch.pipeline().addLast("negotiation", new SslServerTlsHandler(getUrl())); ch.pipeline() .addLast("decoder", adapter.getDecoder()) .addLast("encoder", adapter.getEncoder()) .addLast("server-idle-handler", new IdleStateHandler(0, 0, closeTimeout, MILLISECONDS)) .addLast("handler", nettyServerHandler); } }); } @Override protected void doClose() throws Throwable { try { if (channel != null) { // unbind. channel.close(); } } catch (Throwable e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { Collection<Channel> channels = getChannels(); if (CollectionUtils.isNotEmpty(channels)) { for (Channel channel : channels) { try { channel.close(); } catch (Throwable e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } } } catch (Throwable e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } closeBootstrap(); try { if (channels != null) { channels.clear(); } } catch (Throwable e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } private void closeBootstrap() { try { if (bootstrap != null) { long timeout = ConfigurationUtils.reCalShutdownTime(serverShutdownTimeoutMills); long quietPeriod = Math.min(2000L, timeout); Future<?> bossGroupShutdownFuture = bossGroup.shutdownGracefully(quietPeriod, timeout, MILLISECONDS); Future<?> workerGroupShutdownFuture = workerGroup.shutdownGracefully(quietPeriod, timeout, MILLISECONDS); bossGroupShutdownFuture.syncUninterruptibly(); workerGroupShutdownFuture.syncUninterruptibly(); } } catch (Throwable e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } @Override protected int getChannelsSize() { return channels.size(); } @Override public Collection<Channel> getChannels() { Collection<Channel> chs = new ArrayList<>(this.channels.size()); // pick channels from NettyServerHandler ( needless to check connectivity ) chs.addAll(this.channels.values()); return chs; } @Override public Channel getChannel(InetSocketAddress remoteAddress) { return channels.get(NetUtils.toAddressString(remoteAddress)); } @Override public boolean canHandleIdle() { return true; } @Override public boolean isBound() { return channel.isActive(); } protected EventLoopGroup getBossGroup() { return bossGroup; } protected EventLoopGroup getWorkerGroup() { return workerGroup; } protected ServerBootstrap getServerBootstrap() { return bootstrap; } protected io.netty.channel.Channel getBossChannel() { return channel; } protected Map<String, Channel> getServerChannels() { return channels; } }
7,606
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannelHandler.java
/* * 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 * * 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 org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import java.net.InetSocketAddress; import java.util.Map; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; public class NettyChannelHandler extends ChannelInboundHandlerAdapter { private static final Logger logger = LoggerFactory.getLogger(NettyChannelHandler.class); private final Map<String, Channel> dubboChannels; private final URL url; private final ChannelHandler handler; public NettyChannelHandler(Map<String, Channel> dubboChannels, URL url, ChannelHandler handler) { this.dubboChannels = dubboChannels; this.url = url; this.handler = handler; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); if (channel != null) { dubboChannels.put( NetUtils.toAddressString((InetSocketAddress) ctx.channel().remoteAddress()), channel); handler.connected(channel); if (logger.isInfoEnabled()) { logger.info("The connection of " + channel.getRemoteAddress() + " -> " + channel.getLocalAddress() + " is established."); } } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); try { dubboChannels.remove( NetUtils.toAddressString((InetSocketAddress) ctx.channel().remoteAddress())); if (channel != null) { handler.disconnected(channel); if (logger.isInfoEnabled()) { logger.info("The connection of " + channel.getRemoteAddress() + " -> " + channel.getLocalAddress() + " is disconnected."); } } } finally { NettyChannel.removeChannel(ctx.channel()); } } }
7,607
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/NettyChannel.java
/* * 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 * * 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 org.apache.dubbo.remoting.transport.netty4; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Codec; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.transport.AbstractChannel; import org.apache.dubbo.remoting.transport.codec.CodecAdapter; import org.apache.dubbo.remoting.utils.PayloadDropper; import org.apache.dubbo.rpc.model.FrameworkModel; import java.net.InetSocketAddress; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicBoolean; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.handler.codec.EncoderException; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_ENCODE_IN_IO_THREAD; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.ENCODE_IN_IO_THREAD_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE; import static org.apache.dubbo.rpc.model.ScopeModelUtil.getFrameworkModel; /** * NettyChannel maintains the cache of channel. */ final class NettyChannel extends AbstractChannel { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NettyChannel.class); /** * the cache for netty channel and dubbo channel */ private static final ConcurrentMap<Channel, NettyChannel> CHANNEL_MAP = new ConcurrentHashMap<Channel, NettyChannel>(); /** * netty channel */ private final Channel channel; private final Map<String, Object> attributes = new ConcurrentHashMap<String, Object>(); private final AtomicBoolean active = new AtomicBoolean(false); private final Netty4BatchWriteQueue writeQueue; private Codec2 codec; private final boolean encodeInIOThread; /** * The constructor of NettyChannel. * It is private so NettyChannel usually create by {@link NettyChannel#getOrAddChannel(Channel, URL, ChannelHandler)} * * @param channel netty channel * @param url * @param handler dubbo handler that contain netty handler */ private NettyChannel(Channel channel, URL url, ChannelHandler handler) { super(url, handler); if (channel == null) { throw new IllegalArgumentException("netty channel == null;"); } this.channel = channel; this.writeQueue = Netty4BatchWriteQueue.createWriteQueue(channel); this.codec = getChannelCodec(url); this.encodeInIOThread = getUrl().getParameter(ENCODE_IN_IO_THREAD_KEY, DEFAULT_ENCODE_IN_IO_THREAD); } /** * Get dubbo channel by netty channel through channel cache. * Put netty channel into it if dubbo channel don't exist in the cache. * * @param ch netty channel * @param url * @param handler dubbo handler that contain netty's handler * @return */ static NettyChannel getOrAddChannel(Channel ch, URL url, ChannelHandler handler) { if (ch == null) { return null; } NettyChannel ret = CHANNEL_MAP.get(ch); if (ret == null) { NettyChannel nettyChannel = new NettyChannel(ch, url, handler); if (ch.isActive()) { nettyChannel.markActive(true); ret = CHANNEL_MAP.putIfAbsent(ch, nettyChannel); } if (ret == null) { ret = nettyChannel; } } else { ret.markActive(true); } return ret; } /** * Remove the inactive channel. * * @param ch netty channel */ static void removeChannelIfDisconnected(Channel ch) { if (ch != null && !ch.isActive()) { NettyChannel nettyChannel = CHANNEL_MAP.remove(ch); if (nettyChannel != null) { nettyChannel.markActive(false); } } } static void removeChannel(Channel ch) { if (ch != null) { NettyChannel nettyChannel = CHANNEL_MAP.remove(ch); if (nettyChannel != null) { nettyChannel.markActive(false); } } } @Override public InetSocketAddress getLocalAddress() { return (InetSocketAddress) channel.localAddress(); } @Override public InetSocketAddress getRemoteAddress() { return (InetSocketAddress) channel.remoteAddress(); } @Override public boolean isConnected() { return !isClosed() && active.get(); } public boolean isActive() { return active.get(); } public void markActive(boolean isActive) { active.set(isActive); } /** * Send message by netty and whether to wait the completion of the send. * * @param message message that need send. * @param sent whether to ack async-sent * @throws RemotingException throw RemotingException if wait until timeout or any exception thrown by method body that surrounded by try-catch. */ @Override public void send(Object message, boolean sent) throws RemotingException { // whether the channel is closed super.send(message, sent); boolean success = true; int timeout = 0; try { Object outputMessage = message; if (!encodeInIOThread) { ByteBuf buf = channel.alloc().buffer(); ChannelBuffer buffer = new NettyBackedChannelBuffer(buf); codec.encode(this, buffer, message); outputMessage = buf; } ChannelFuture future = writeQueue.enqueue(outputMessage).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!(message instanceof Request)) { return; } ChannelHandler handler = getChannelHandler(); if (future.isSuccess()) { handler.sent(NettyChannel.this, message); } else { Throwable t = future.cause(); if (t == null) { return; } Response response = buildErrorResponse((Request) message, t); handler.received(NettyChannel.this, response); } } }); if (sent) { // wait timeout ms timeout = getUrl().getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); success = future.await(timeout); } Throwable cause = future.cause(); if (cause != null) { throw cause; } } catch (Throwable e) { removeChannelIfDisconnected(channel); throw new RemotingException( this, "Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to " + getRemoteAddress() + ", cause: " + e.getMessage(), e); } if (!success) { throw new RemotingException( this, "Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to " + getRemoteAddress() + "in timeout(" + timeout + "ms) limit"); } } @Override public void close() { try { super.close(); } catch (Exception e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { removeChannelIfDisconnected(channel); } catch (Exception e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { attributes.clear(); } catch (Exception e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } try { if (logger.isInfoEnabled()) { logger.info("Close netty channel " + channel); } channel.close(); } catch (Exception e) { logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e); } } @Override public boolean hasAttribute(String key) { return attributes.containsKey(key); } @Override public Object getAttribute(String key) { return attributes.get(key); } @Override public void setAttribute(String key, Object value) { // The null value is not allowed in the ConcurrentHashMap. if (value == null) { attributes.remove(key); } else { attributes.put(key, value); } } @Override public void removeAttribute(String key) { attributes.remove(key); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((channel == null) ? 0 : channel.hashCode()); return result; } @Override protected void setUrl(URL url) { super.setUrl(url); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } // FIXME: a hack to make org.apache.dubbo.remoting.exchange.support.DefaultFuture.closeChannel work if (obj instanceof NettyClient) { NettyClient client = (NettyClient) obj; return channel.equals(client.getNettyChannel()); } if (getClass() != obj.getClass()) { return false; } NettyChannel other = (NettyChannel) obj; if (channel == null) { if (other.channel != null) { return false; } } else if (!channel.equals(other.channel)) { return false; } return true; } @Override public String toString() { return "NettyChannel [channel=" + channel + "]"; } public Channel getNioChannel() { return channel; } /** * build a bad request's response * * @param request the request * @param t the throwable. In most cases, serialization fails. * @return the response */ private static Response buildErrorResponse(Request request, Throwable t) { Response response = new Response(request.getId(), request.getVersion()); if (t instanceof EncoderException) { response.setStatus(Response.SERIALIZATION_ERROR); } else { response.setStatus(Response.BAD_REQUEST); } response.setErrorMessage(StringUtils.toString(t)); return response; } private static Codec2 getChannelCodec(URL url) { String codecName = url.getParameter(Constants.CODEC_KEY); if (StringUtils.isEmpty(codecName)) { // codec extension name must stay the same with protocol name codecName = url.getProtocol(); } FrameworkModel frameworkModel = getFrameworkModel(url.getScopeModel()); if (frameworkModel.getExtensionLoader(Codec2.class).hasExtension(codecName)) { return frameworkModel.getExtensionLoader(Codec2.class).getExtension(codecName); } else if (frameworkModel.getExtensionLoader(Codec.class).hasExtension(codecName)) { return new CodecAdapter( frameworkModel.getExtensionLoader(Codec.class).getExtension(codecName)); } else { return frameworkModel.getExtensionLoader(Codec2.class).getExtension("default"); } } public void setCodec(Codec2 codec) { this.codec = codec; } }
7,608
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslContexts.java
/* * 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 * * 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 org.apache.dubbo.remoting.transport.netty4.ssl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.ssl.AuthPolicy; import org.apache.dubbo.common.ssl.Cert; import org.apache.dubbo.common.ssl.CertManager; import org.apache.dubbo.common.ssl.ProviderCert; import javax.net.ssl.SSLException; import java.io.IOException; import java.io.InputStream; import java.security.Provider; import java.security.Security; import io.netty.handler.ssl.ClientAuth; import io.netty.handler.ssl.OpenSsl; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslProvider; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE_STREAM; public class SslContexts { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SslContexts.class); public static SslContext buildServerSslContext(ProviderCert providerConnectionConfig) { SslContextBuilder sslClientContextBuilder; InputStream serverKeyCertChainPathStream = null; InputStream serverPrivateKeyPathStream = null; InputStream serverTrustCertStream = null; try { serverKeyCertChainPathStream = providerConnectionConfig.getKeyCertChainInputStream(); serverPrivateKeyPathStream = providerConnectionConfig.getPrivateKeyInputStream(); serverTrustCertStream = providerConnectionConfig.getTrustCertInputStream(); String password = providerConnectionConfig.getPassword(); if (password != null) { sslClientContextBuilder = SslContextBuilder.forServer(serverKeyCertChainPathStream, serverPrivateKeyPathStream, password); } else { sslClientContextBuilder = SslContextBuilder.forServer(serverKeyCertChainPathStream, serverPrivateKeyPathStream); } if (serverTrustCertStream != null) { sslClientContextBuilder.trustManager(serverTrustCertStream); if (providerConnectionConfig.getAuthPolicy() == AuthPolicy.CLIENT_AUTH) { sslClientContextBuilder.clientAuth(ClientAuth.REQUIRE); } else { sslClientContextBuilder.clientAuth(ClientAuth.OPTIONAL); } } } catch (Exception e) { throw new IllegalArgumentException("Could not find certificate file or the certificate is invalid.", e); } finally { safeCloseStream(serverTrustCertStream); safeCloseStream(serverKeyCertChainPathStream); safeCloseStream(serverPrivateKeyPathStream); } try { return sslClientContextBuilder.sslProvider(findSslProvider()).build(); } catch (SSLException e) { throw new IllegalStateException("Build SslSession failed.", e); } } public static SslContext buildClientSslContext(URL url) { CertManager certManager = url.getOrDefaultFrameworkModel().getBeanFactory().getBean(CertManager.class); Cert consumerConnectionConfig = certManager.getConsumerConnectionConfig(url); if (consumerConnectionConfig == null) { return null; } SslContextBuilder builder = SslContextBuilder.forClient(); InputStream clientTrustCertCollectionPath = null; InputStream clientCertChainFilePath = null; InputStream clientPrivateKeyFilePath = null; try { clientTrustCertCollectionPath = consumerConnectionConfig.getTrustCertInputStream(); if (clientTrustCertCollectionPath != null) { builder.trustManager(clientTrustCertCollectionPath); } clientCertChainFilePath = consumerConnectionConfig.getKeyCertChainInputStream(); clientPrivateKeyFilePath = consumerConnectionConfig.getPrivateKeyInputStream(); if (clientCertChainFilePath != null && clientPrivateKeyFilePath != null) { String password = consumerConnectionConfig.getPassword(); if (password != null) { builder.keyManager(clientCertChainFilePath, clientPrivateKeyFilePath, password); } else { builder.keyManager(clientCertChainFilePath, clientPrivateKeyFilePath); } } } catch (Exception e) { throw new IllegalArgumentException("Could not find certificate file or find invalid certificate.", e); } finally { safeCloseStream(clientTrustCertCollectionPath); safeCloseStream(clientCertChainFilePath); safeCloseStream(clientPrivateKeyFilePath); } try { return builder.sslProvider(findSslProvider()).build(); } catch (SSLException e) { throw new IllegalStateException("Build SslSession failed.", e); } } /** * Returns OpenSSL if available, otherwise returns the JDK provider. */ private static SslProvider findSslProvider() { if (OpenSsl.isAvailable()) { logger.debug("Using OPENSSL provider."); return SslProvider.OPENSSL; } if (checkJdkProvider()) { logger.debug("Using JDK provider."); return SslProvider.JDK; } throw new IllegalStateException( "Could not find any valid TLS provider, please check your dependency or deployment environment, " + "usually netty-tcnative, Conscrypt, or Jetty NPN/ALPN is needed."); } private static boolean checkJdkProvider() { Provider[] jdkProviders = Security.getProviders("SSLContext.TLS"); return (jdkProviders != null && jdkProviders.length > 0); } private static void safeCloseStream(InputStream stream) { if (stream == null) { return; } try { stream.close(); } catch (IOException e) { logger.warn(TRANSPORT_FAILED_CLOSE_STREAM, "", "", "Failed to close a stream.", e); } } }
7,609
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslClientTlsHandler.java
/* * 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 * * 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 org.apache.dubbo.remoting.transport.netty4.ssl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLSession; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.SslHandshakeCompletionEvent; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; public class SslClientTlsHandler extends ChannelInboundHandlerAdapter { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SslClientTlsHandler.class); private final SslContext sslContext; public SslClientTlsHandler(URL url) { this(SslContexts.buildClientSslContext(url)); } public SslClientTlsHandler(SslContext sslContext) { this.sslContext = sslContext; } @Override public void handlerAdded(ChannelHandlerContext ctx) { SSLEngine sslEngine = sslContext.newEngine(ctx.alloc()); ctx.pipeline().addAfter(ctx.name(), null, new SslHandler(sslEngine, false)); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt; if (handshakeEvent.isSuccess()) { SSLSession session = ctx.pipeline().get(SslHandler.class).engine().getSession(); logger.info("TLS negotiation succeed with: " + session.getPeerHost()); ctx.pipeline().remove(this); } else { logger.error( INTERNAL_ERROR, "unknown error in remoting module", "", "TLS negotiation failed when trying to accept new connection.", handshakeEvent.cause()); ctx.fireExceptionCaught(handshakeEvent.cause()); } } } }
7,610
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/ssl/SslServerTlsHandler.java
/* * 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 * * 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 org.apache.dubbo.remoting.transport.netty4.ssl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.ssl.AuthPolicy; import org.apache.dubbo.common.ssl.CertManager; import org.apache.dubbo.common.ssl.ProviderCert; import javax.net.ssl.SSLSession; import java.util.List; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.SslHandshakeCompletionEvent; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; public class SslServerTlsHandler extends ByteToMessageDecoder { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SslServerTlsHandler.class); private final URL url; private final boolean sslDetected; public SslServerTlsHandler(URL url) { this.url = url; this.sslDetected = false; } public SslServerTlsHandler(URL url, boolean sslDetected) { this.url = url; this.sslDetected = sslDetected; } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.error( INTERNAL_ERROR, "unknown error in remoting module", "", "TLS negotiation failed when trying to accept new connection.", cause); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt; if (handshakeEvent.isSuccess()) { SSLSession session = ctx.pipeline().get(SslHandler.class).engine().getSession(); logger.info("TLS negotiation succeed with: " + session.getPeerHost()); // Remove after handshake success. ctx.pipeline().remove(this); } else { logger.error( INTERNAL_ERROR, "", "", "TLS negotiation failed when trying to accept new connection.", handshakeEvent.cause()); ctx.close(); } } super.userEventTriggered(ctx, evt); } @Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception { // Will use the first five bytes to detect a protocol. if (byteBuf.readableBytes() < 5) { return; } if (sslDetected) { return; } CertManager certManager = url.getOrDefaultFrameworkModel().getBeanFactory().getBean(CertManager.class); ProviderCert providerConnectionConfig = certManager.getProviderConnectionConfig( url, channelHandlerContext.channel().remoteAddress()); if (providerConnectionConfig == null) { ChannelPipeline p = channelHandlerContext.pipeline(); p.remove(this); return; } if (isSsl(byteBuf)) { SslContext sslContext = SslContexts.buildServerSslContext(providerConnectionConfig); enableSsl(channelHandlerContext, sslContext); return; } if (providerConnectionConfig.getAuthPolicy() == AuthPolicy.NONE) { ChannelPipeline p = channelHandlerContext.pipeline(); p.remove(this); } logger.error(INTERNAL_ERROR, "", "", "TLS negotiation failed when trying to accept new connection."); channelHandlerContext.close(); } private boolean isSsl(ByteBuf buf) { return SslHandler.isEncrypted(buf); } private void enableSsl(ChannelHandlerContext ctx, SslContext sslContext) { ChannelPipeline p = ctx.pipeline(); ctx.pipeline().addAfter(ctx.name(), null, sslContext.newHandler(ctx.alloc())); p.addLast("unificationA", new SslServerTlsHandler(url, true)); p.remove(this); } }
7,611
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/MessageFormatter.java
/* * 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 * * 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 org.apache.dubbo.remoting.transport.netty4.logging; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ArrayUtils; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_UNSUPPORTED_MESSAGE; // contributors: lizongbo: proposed special treatment of array parameter values // Joern Huxhorn: pointed out double[] omission, suggested deep array copy /** * Formats messages according to very simple substitution rules. Substitutions * can be made 1, 2 or more arguments. * <p/> * <p/> * For example, * <p/> * <pre> * MessageFormatter.format(&quot;Hi {}.&quot;, &quot;there&quot;) * </pre> * <p/> * will return the string "Hi there.". * <p/> * The {} pair is called the <em>formatting anchor</em>. It serves to designate * the location where arguments need to be substituted within the message * pattern. * <p/> * In case your message contains the '{' or the '}' character, you do not have * to do anything special unless the '}' character immediately follows '{'. For * example, * <p/> * <pre> * MessageFormatter.format(&quot;Set {1,2,3} is not equal to {}.&quot;, &quot;1,2&quot;); * </pre> * <p/> * will return the string "Set {1,2,3} is not equal to 1,2.". * <p/> * <p/> * If for whatever reason you need to place the string "{}" in the message * without its <em>formatting anchor</em> meaning, then you need to escape the * '{' character with '\', that is the backslash character. Only the '{' * character should be escaped. There is no need to escape the '}' character. * For example, * <p/> * <pre> * MessageFormatter.format(&quot;Set \\{} is not equal to {}.&quot;, &quot;1,2&quot;); * </pre> * <p/> * will return the string "Set {} is not equal to 1,2.". * <p/> * <p/> * The escaping behavior just described can be overridden by escaping the escape * character '\'. Calling * <p/> * <pre> * MessageFormatter.format(&quot;File name is C:\\\\{}.&quot;, &quot;file.zip&quot;); * </pre> * <p/> * will return the string "File name is C:\file.zip". * <p/> * <p/> * The formatting conventions are different than those of {@link MessageFormat} * which ships with the Java platform. This is justified by the fact that * SLF4J's implementation is 10 times faster than that of {@link MessageFormat}. * This local performance difference is both measurable and significant in the * larger context of the complete logging processing chain. * <p/> * <p/> * See also {@link #format(String, Object)}, * {@link #format(String, Object, Object)} and * {@link #arrayFormat(String, Object[])} methods for more details. */ final class MessageFormatter { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MessageFormatter.class); static final char DELIM_START = '{'; static final char DELIM_STOP = '}'; static final String DELIM_STR = "{}"; private static final char ESCAPE_CHAR = '\\'; /** * Performs single argument substitution for the 'messagePattern' passed as * parameter. * <p/> * For example, * <p/> * <pre> * MessageFormatter.format(&quot;Hi {}.&quot;, &quot;there&quot;); * </pre> * <p/> * will return the string "Hi there.". * <p/> * * @param messagePattern The message pattern which will be parsed and formatted * @param arg The argument to be substituted in place of the formatting anchor * @return The formatted message */ static FormattingTuple format(String messagePattern, Object arg) { return arrayFormat(messagePattern, new Object[] {arg}); } /** * Performs a two argument substitution for the 'messagePattern' passed as * parameter. * <p/> * For example, * <p/> * <pre> * MessageFormatter.format(&quot;Hi {}. My name is {}.&quot;, &quot;Alice&quot;, &quot;Bob&quot;); * </pre> * <p/> * will return the string "Hi Alice. My name is Bob.". * * @param messagePattern The message pattern which will be parsed and formatted * @param argA The argument to be substituted in place of the first formatting * anchor * @param argB The argument to be substituted in place of the second formatting * anchor * @return The formatted message */ static FormattingTuple format(final String messagePattern, Object argA, Object argB) { return arrayFormat(messagePattern, new Object[] {argA, argB}); } static Throwable getThrowableCandidate(Object[] argArray) { if (ArrayUtils.isEmpty(argArray)) { return null; } final Object lastEntry = argArray[argArray.length - 1]; if (lastEntry instanceof Throwable) { return (Throwable) lastEntry; } return null; } /** * Same principle as the {@link #format(String, Object)} and * {@link #format(String, Object, Object)} methods except that any number of * arguments can be passed in an array. * * @param messagePattern The message pattern which will be parsed and formatted * @param argArray An array of arguments to be substituted in place of formatting * anchors * @return The formatted message */ static FormattingTuple arrayFormat(final String messagePattern, final Object[] argArray) { Throwable throwableCandidate = getThrowableCandidate(argArray); if (messagePattern == null) { return new FormattingTuple(null, argArray, throwableCandidate); } if (argArray == null) { return new FormattingTuple(messagePattern); } int i = 0; int j; StringBuffer sbuf = new StringBuffer(messagePattern.length() + 50); int l; for (l = 0; l < argArray.length; l++) { j = messagePattern.indexOf(DELIM_STR, i); if (j == -1) { // no more variables if (i == 0) { // this is a simple string return new FormattingTuple(messagePattern, argArray, throwableCandidate); } else { // add the tail string which contains no variables and return // the result. sbuf.append(messagePattern.substring(i)); return new FormattingTuple(sbuf.toString(), argArray, throwableCandidate); } } else { if (isEscapedDelimeter(messagePattern, j)) { if (!isDoubleEscaped(messagePattern, j)) { l--; // DELIM_START was escaped, thus should not be incremented sbuf.append(messagePattern, i, j - 1); sbuf.append(DELIM_START); i = j + 1; } else { // The escape character preceding the delimiter start is // itself escaped: "abc x:\\{}" // we have to consume one backward slash sbuf.append(messagePattern, i, j - 1); deeplyAppendParameter(sbuf, argArray[l], new HashMap<Object[], Void>()); i = j + 2; } } else { // normal case sbuf.append(messagePattern, i, j); deeplyAppendParameter(sbuf, argArray[l], new HashMap<Object[], Void>()); i = j + 2; } } } // append the characters following the last {} pair. sbuf.append(messagePattern.substring(i)); if (l < argArray.length - 1) { return new FormattingTuple(sbuf.toString(), argArray, throwableCandidate); } else { return new FormattingTuple(sbuf.toString(), argArray, null); } } static boolean isEscapedDelimeter(String messagePattern, int delimeterStartIndex) { if (delimeterStartIndex == 0) { return false; } return messagePattern.charAt(delimeterStartIndex - 1) == ESCAPE_CHAR; } static boolean isDoubleEscaped(String messagePattern, int delimeterStartIndex) { return delimeterStartIndex >= 2 && messagePattern.charAt(delimeterStartIndex - 2) == ESCAPE_CHAR; } // special treatment of array values was suggested by 'lizongbo' private static void deeplyAppendParameter(StringBuffer sbuf, Object o, Map<Object[], Void> seenMap) { if (o == null) { sbuf.append("null"); return; } if (!o.getClass().isArray()) { safeObjectAppend(sbuf, o); } else { // check for primitive array types because they // unfortunately cannot be cast to Object[] if (o instanceof boolean[]) { booleanArrayAppend(sbuf, (boolean[]) o); } else if (o instanceof byte[]) { byteArrayAppend(sbuf, (byte[]) o); } else if (o instanceof char[]) { charArrayAppend(sbuf, (char[]) o); } else if (o instanceof short[]) { shortArrayAppend(sbuf, (short[]) o); } else if (o instanceof int[]) { intArrayAppend(sbuf, (int[]) o); } else if (o instanceof long[]) { longArrayAppend(sbuf, (long[]) o); } else if (o instanceof float[]) { floatArrayAppend(sbuf, (float[]) o); } else if (o instanceof double[]) { doubleArrayAppend(sbuf, (double[]) o); } else { objectArrayAppend(sbuf, (Object[]) o, seenMap); } } } private static void safeObjectAppend(StringBuffer sbuf, Object o) { try { String oAsString = o.toString(); sbuf.append(oAsString); } catch (Throwable t) { System.err.println("SLF4J: Failed toString() invocation on an object of type [" + o.getClass().getName() + ']'); logger.error(TRANSPORT_UNSUPPORTED_MESSAGE, "", "", t.getMessage(), t); sbuf.append("[FAILED toString()]"); } } private static void objectArrayAppend(StringBuffer sbuf, Object[] a, Map<Object[], Void> seenMap) { sbuf.append('['); if (!seenMap.containsKey(a)) { seenMap.put(a, null); final int len = a.length; for (int i = 0; i < len; i++) { deeplyAppendParameter(sbuf, a[i], seenMap); if (i != len - 1) { sbuf.append(", "); } } // allow repeats in siblings seenMap.remove(a); } else { sbuf.append("..."); } sbuf.append(']'); } private static void booleanArrayAppend(StringBuffer sbuf, boolean[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) { sbuf.append(", "); } } sbuf.append(']'); } private static void byteArrayAppend(StringBuffer sbuf, byte[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) { sbuf.append(", "); } } sbuf.append(']'); } private static void charArrayAppend(StringBuffer sbuf, char[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) { sbuf.append(", "); } } sbuf.append(']'); } private static void shortArrayAppend(StringBuffer sbuf, short[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) { sbuf.append(", "); } } sbuf.append(']'); } private static void intArrayAppend(StringBuffer sbuf, int[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) { sbuf.append(", "); } } sbuf.append(']'); } private static void longArrayAppend(StringBuffer sbuf, long[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) { sbuf.append(", "); } } sbuf.append(']'); } private static void floatArrayAppend(StringBuffer sbuf, float[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) { sbuf.append(", "); } } sbuf.append(']'); } private static void doubleArrayAppend(StringBuffer sbuf, double[] a) { sbuf.append('['); final int len = a.length; for (int i = 0; i < len; i++) { sbuf.append(a[i]); if (i != len - 1) { sbuf.append(", "); } } sbuf.append(']'); } private MessageFormatter() {} }
7,612
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/FormattingTuple.java
/* * 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 * * 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 org.apache.dubbo.remoting.transport.netty4.logging; import org.apache.dubbo.common.utils.ArrayUtils; /** * Holds the results of formatting done by {@link MessageFormatter}. */ class FormattingTuple { static final FormattingTuple NULL = new FormattingTuple(null); private final String message; private final Throwable throwable; private final Object[] argArray; FormattingTuple(String message) { this(message, null, null); } FormattingTuple(String message, Object[] argArray, Throwable throwable) { this.message = message; this.throwable = throwable; if (throwable == null) { this.argArray = argArray; } else { this.argArray = trimmedCopy(argArray); } } static Object[] trimmedCopy(Object[] argArray) { if (ArrayUtils.isEmpty(argArray)) { throw new IllegalStateException("non-sensical empty or null argument array"); } final int trimmedLen = argArray.length - 1; Object[] trimmed = new Object[trimmedLen]; System.arraycopy(argArray, 0, trimmed, 0, trimmedLen); return trimmed; } public String getMessage() { return message; } public Object[] getArgArray() { return argArray; } public Throwable getThrowable() { return throwable; } }
7,613
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperTransporterTest.java
/* * 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 * * 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 org.apache.dubbo.remoting.zookeeper.curator5; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNull.nullValue; class Curator5ZookeeperTransporterTest { private ZookeeperClient zookeeperClient; private Curator5ZookeeperTransporter curatorZookeeperTransporter; private static String zookeeperConnectionAddress1; @BeforeAll public static void beforeAll() { zookeeperConnectionAddress1 = System.getProperty("zookeeper.connection.address.1"); } @BeforeEach public void setUp() { zookeeperClient = new Curator5ZookeeperTransporter().connect(URL.valueOf(zookeeperConnectionAddress1 + "/service")); curatorZookeeperTransporter = new Curator5ZookeeperTransporter(); } @Test void testZookeeperClient() { assertThat(zookeeperClient, not(nullValue())); zookeeperClient.close(); } }
7,614
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperClientTest.java
/* * 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 * * 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 org.apache.dubbo.remoting.zookeeper.curator5; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigItem; import org.apache.dubbo.remoting.zookeeper.ChildListener; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.data.Stat; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import static org.awaitility.Awaitility.await; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.mock; class Curator5ZookeeperClientTest { private static Curator5ZookeeperClient curatorClient; private static CuratorFramework client = null; private static int zookeeperServerPort1; private static String zookeeperConnectionAddress1; @BeforeAll public static void setUp() throws Exception { zookeeperConnectionAddress1 = System.getProperty("zookeeper.connection.address.1"); zookeeperServerPort1 = Integer.parseInt( zookeeperConnectionAddress1.substring(zookeeperConnectionAddress1.lastIndexOf(":") + 1)); curatorClient = new Curator5ZookeeperClient( URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")); client = CuratorFrameworkFactory.newClient( "127.0.0.1:" + zookeeperServerPort1, new ExponentialBackoffRetry(1000, 3)); client.start(); } @Test void testCheckExists() { String path = "/dubbo/org.apache.dubbo.demo.DemoService/providers"; curatorClient.create(path, false, true); assertThat(curatorClient.checkExists(path), is(true)); assertThat(curatorClient.checkExists(path + "/noneexits"), is(false)); } @Test void testChildrenPath() { String path = "/dubbo/org.apache.dubbo.demo.DemoService/providers"; curatorClient.create(path, false, true); curatorClient.create(path + "/provider1", false, true); curatorClient.create(path + "/provider2", false, true); List<String> children = curatorClient.getChildren(path); assertThat(children.size(), is(2)); } @Test @Timeout(value = 2) public void testChildrenListener() throws InterruptedException { String path = "/dubbo/org.apache.dubbo.demo.DemoListenerService/providers"; curatorClient.create(path, false, true); final CountDownLatch countDownLatch = new CountDownLatch(1); curatorClient.addTargetChildListener(path, new Curator5ZookeeperClient.CuratorWatcherImpl() { @Override public void process(WatchedEvent watchedEvent) { countDownLatch.countDown(); } }); curatorClient.createPersistent(path + "/provider1", true); countDownLatch.await(); } @Test void testWithInvalidServer() { Assertions.assertThrows(IllegalStateException.class, () -> { curatorClient = new Curator5ZookeeperClient(URL.valueOf("zookeeper://127.0.0.1:1/service?timeout=1000")); curatorClient.create("/testPath", true, true); }); } @Test void testRemoveChildrenListener() { ChildListener childListener = mock(ChildListener.class); curatorClient.addChildListener("/children", childListener); curatorClient.removeChildListener("/children", childListener); } @Test void testCreateExistingPath() { curatorClient.create("/pathOne", false, true); curatorClient.create("/pathOne", false, true); } @Test void testConnectedStatus() { curatorClient.createEphemeral("/testPath", true); boolean connected = curatorClient.isConnected(); assertThat(connected, is(true)); } @Test void testCreateContent4Persistent() { String path = "/curatorTest4CrContent/content.data"; String content = "createContentTest"; curatorClient.delete(path); assertThat(curatorClient.checkExists(path), is(false)); assertNull(curatorClient.getContent(path)); curatorClient.createOrUpdate(path, content, false); assertThat(curatorClient.checkExists(path), is(true)); assertEquals(curatorClient.getContent(path), content); } @Test void testCreateContent4Temp() { String path = "/curatorTest4CrContent/content.data"; String content = "createContentTest"; curatorClient.delete(path); assertThat(curatorClient.checkExists(path), is(false)); assertNull(curatorClient.getContent(path)); curatorClient.createOrUpdate(path, content, true); assertThat(curatorClient.checkExists(path), is(true)); assertEquals(curatorClient.getContent(path), content); } @Test void testCreatePersistentFailed() { String path = "/dubbo/test/path"; curatorClient.delete(path); curatorClient.create(path, false, true); Assertions.assertTrue(curatorClient.checkExists(path)); curatorClient.createPersistent(path, true); Assertions.assertTrue(curatorClient.checkExists(path)); curatorClient.createPersistent(path, true); Assertions.assertTrue(curatorClient.checkExists(path)); Assertions.assertThrows(IllegalStateException.class, () -> { curatorClient.createPersistent(path, false); }); Assertions.assertTrue(curatorClient.checkExists(path)); } @Test void testCreateEphemeralFailed() { String path = "/dubbo/test/path"; curatorClient.delete(path); curatorClient.create(path, true, true); Assertions.assertTrue(curatorClient.checkExists(path)); curatorClient.createEphemeral(path, true); Assertions.assertTrue(curatorClient.checkExists(path)); curatorClient.createEphemeral(path, true); Assertions.assertTrue(curatorClient.checkExists(path)); Assertions.assertThrows(IllegalStateException.class, () -> { curatorClient.createEphemeral(path, false); }); Assertions.assertTrue(curatorClient.checkExists(path)); } @Test void testAddTargetDataListener() throws Exception { String listenerPath = "/dubbo/service.name/configuration"; String path = listenerPath + "/dat/data"; String value = "vav"; curatorClient.createOrUpdate(path + "/d.json", value, true); String valueFromCache = curatorClient.getContent(path + "/d.json"); Assertions.assertEquals(value, valueFromCache); final AtomicInteger atomicInteger = new AtomicInteger(0); curatorClient.addTargetDataListener(path + "/d.json", new Curator5ZookeeperClient.NodeCacheListenerImpl() { @Override public void nodeChanged() { atomicInteger.incrementAndGet(); } }); valueFromCache = curatorClient.getContent(path + "/d.json"); Assertions.assertNotNull(valueFromCache); int currentCount1 = atomicInteger.get(); curatorClient.getClient().setData().forPath(path + "/d.json", "foo".getBytes()); await().until(() -> atomicInteger.get() > currentCount1); int currentCount2 = atomicInteger.get(); curatorClient.getClient().setData().forPath(path + "/d.json", "bar".getBytes()); await().until(() -> atomicInteger.get() > currentCount2); int currentCount3 = atomicInteger.get(); curatorClient.delete(path + "/d.json"); valueFromCache = curatorClient.getContent(path + "/d.json"); Assertions.assertNull(valueFromCache); await().until(() -> atomicInteger.get() > currentCount3); } @Test void testPersistentCas1() throws Exception { // test create failed when others create success String path = "/dubbo/mapping/org.apache.dubbo.demo.DemoService"; AtomicReference<Runnable> runnable = new AtomicReference<>(); Curator5ZookeeperClient curatorClient = new Curator5ZookeeperClient( URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { @Override protected void createPersistent(String path, String data, boolean faultTolerant) { if (runnable.get() != null) { runnable.get().run(); } super.createPersistent(path, data, faultTolerant); } @Override protected void update(String path, String data, int version) { if (runnable.get() != null) { runnable.get().run(); } super.update(path, data, version); } }; curatorClient.delete(path); runnable.set(() -> { try { client.create().forPath(path, "version x".getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { throw new RuntimeException(e); } }); Assertions.assertThrows( IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", false, 0)); Assertions.assertEquals("version x", curatorClient.getContent(path)); client.setData().forPath(path, "version 1".getBytes(StandardCharsets.UTF_8)); ConfigItem configItem = curatorClient.getConfigItem(path); runnable.set(() -> { try { client.setData().forPath(path, "version x".getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { throw new RuntimeException(e); } }); int version1 = ((Stat) configItem.getTicket()).getVersion(); Assertions.assertThrows( IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 2", false, version1)); Assertions.assertEquals("version x", curatorClient.getContent(path)); runnable.set(null); configItem = curatorClient.getConfigItem(path); int version2 = ((Stat) configItem.getTicket()).getVersion(); curatorClient.createOrUpdate(path, "version 2", false, version2); Assertions.assertEquals("version 2", curatorClient.getContent(path)); curatorClient.close(); } @Test void testPersistentCas2() { // test update failed when others create success String path = "/dubbo/mapping/org.apache.dubbo.demo.DemoService"; Curator5ZookeeperClient curatorClient = new Curator5ZookeeperClient( URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")); curatorClient.delete(path); curatorClient.createOrUpdate(path, "version x", false); Assertions.assertThrows( IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", false, null)); Assertions.assertEquals("version x", curatorClient.getContent(path)); curatorClient.close(); } @Test void testPersistentNonVersion() { String path = "/dubbo/metadata/org.apache.dubbo.demo.DemoService"; AtomicReference<Runnable> runnable = new AtomicReference<>(); Curator5ZookeeperClient curatorClient = new Curator5ZookeeperClient( URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { @Override protected void createPersistent(String path, String data, boolean faultTolerant) { if (runnable.get() != null) { runnable.get().run(); } super.createPersistent(path, data, faultTolerant); } @Override protected void update(String path, String data, int version) { if (runnable.get() != null) { runnable.get().run(); } super.update(path, data, version); } }; curatorClient.delete(path); curatorClient.createOrUpdate(path, "version 0", false); Assertions.assertEquals("version 0", curatorClient.getContent(path)); curatorClient.delete(path); runnable.set(() -> { try { client.create().forPath(path, "version x".getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { throw new RuntimeException(e); } }); curatorClient.createOrUpdate(path, "version 1", false); Assertions.assertEquals("version 1", curatorClient.getContent(path)); runnable.set(() -> { try { client.setData().forPath(path, "version x".getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { throw new RuntimeException(e); } }); curatorClient.createOrUpdate(path, "version 2", false); Assertions.assertEquals("version 2", curatorClient.getContent(path)); runnable.set(null); curatorClient.createOrUpdate(path, "version 3", false); Assertions.assertEquals("version 3", curatorClient.getContent(path)); curatorClient.close(); } @Test void testEphemeralCas1() throws Exception { // test create failed when others create success String path = "/dubbo/mapping/org.apache.dubbo.demo.DemoService"; AtomicReference<Runnable> runnable = new AtomicReference<>(); Curator5ZookeeperClient curatorClient = new Curator5ZookeeperClient( URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { @Override protected void createEphemeral(String path, String data, boolean faultTolerant) { if (runnable.get() != null) { runnable.get().run(); } super.createPersistent(path, data, faultTolerant); } @Override protected void update(String path, String data, int version) { if (runnable.get() != null) { runnable.get().run(); } super.update(path, data, version); } }; curatorClient.delete(path); runnable.set(() -> { try { client.create().forPath(path, "version x".getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { throw new RuntimeException(e); } }); Assertions.assertThrows( IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", true, 0)); Assertions.assertEquals("version x", curatorClient.getContent(path)); client.setData().forPath(path, "version 1".getBytes(StandardCharsets.UTF_8)); ConfigItem configItem = curatorClient.getConfigItem(path); runnable.set(() -> { try { client.setData().forPath(path, "version x".getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { throw new RuntimeException(e); } }); int version1 = ((Stat) configItem.getTicket()).getVersion(); Assertions.assertThrows( IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 2", true, version1)); Assertions.assertEquals("version x", curatorClient.getContent(path)); runnable.set(null); configItem = curatorClient.getConfigItem(path); int version2 = ((Stat) configItem.getTicket()).getVersion(); curatorClient.createOrUpdate(path, "version 2", true, version2); Assertions.assertEquals("version 2", curatorClient.getContent(path)); curatorClient.close(); } @Test void testEphemeralCas2() { // test update failed when others create success String path = "/dubbo/mapping/org.apache.dubbo.demo.DemoService"; Curator5ZookeeperClient curatorClient = new Curator5ZookeeperClient( URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")); curatorClient.delete(path); curatorClient.createOrUpdate(path, "version x", true); Assertions.assertThrows( IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", true, null)); Assertions.assertEquals("version x", curatorClient.getContent(path)); curatorClient.close(); } @Test void testEphemeralNonVersion() { String path = "/dubbo/metadata/org.apache.dubbo.demo.DemoService"; AtomicReference<Runnable> runnable = new AtomicReference<>(); Curator5ZookeeperClient curatorClient = new Curator5ZookeeperClient( URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { @Override protected void createPersistent(String path, String data, boolean faultTolerant) { if (runnable.get() != null) { runnable.get().run(); } super.createPersistent(path, data, faultTolerant); } @Override protected void update(String path, String data, int version) { if (runnable.get() != null) { runnable.get().run(); } super.update(path, data, version); } }; curatorClient.delete(path); curatorClient.createOrUpdate(path, "version 0", true); Assertions.assertEquals("version 0", curatorClient.getContent(path)); curatorClient.delete(path); runnable.set(() -> { try { client.create().forPath(path, "version x".getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { throw new RuntimeException(e); } }); curatorClient.createOrUpdate(path, "version 1", true); Assertions.assertEquals("version 1", curatorClient.getContent(path)); runnable.set(() -> { try { client.setData().forPath(path, "version x".getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { throw new RuntimeException(e); } }); curatorClient.createOrUpdate(path, "version 2", true); Assertions.assertEquals("version 2", curatorClient.getContent(path)); runnable.set(null); curatorClient.createOrUpdate(path, "version 3", true); Assertions.assertEquals("version 3", curatorClient.getContent(path)); curatorClient.close(); } @AfterAll public static void testWithStoppedServer() { curatorClient.close(); } }
7,615
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper/curator5
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper/curator5/support/AbstractZookeeperTransporterTest.java
/* * 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 * * 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 org.apache.dubbo.remoting.zookeeper.curator5.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.zookeeper.AbstractZookeeperTransporter; import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; import org.apache.dubbo.remoting.zookeeper.curator5.Curator5ZookeeperTransporter; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNull.nullValue; /** * AbstractZookeeperTransporterTest */ class AbstractZookeeperTransporterTest { private ZookeeperClient zookeeperClient; private AbstractZookeeperTransporter abstractZookeeperTransporter; private static int zookeeperServerPort1, zookeeperServerPort2; private static String zookeeperConnectionAddress1, zookeeperConnectionAddress2; @BeforeAll public static void beforeAll() { zookeeperConnectionAddress1 = System.getProperty("zookeeper.connection.address.1"); zookeeperConnectionAddress2 = System.getProperty("zookeeper.connection.address.2"); zookeeperServerPort1 = Integer.parseInt( zookeeperConnectionAddress1.substring(zookeeperConnectionAddress1.lastIndexOf(":") + 1)); zookeeperServerPort2 = Integer.parseInt( zookeeperConnectionAddress2.substring(zookeeperConnectionAddress2.lastIndexOf(":") + 1)); } @BeforeEach public void setUp() throws Exception { zookeeperClient = new Curator5ZookeeperTransporter().connect(URL.valueOf(zookeeperConnectionAddress1 + "/service")); abstractZookeeperTransporter = new Curator5ZookeeperTransporter(); } @Test void testZookeeperClient() { assertThat(zookeeperClient, not(nullValue())); zookeeperClient.close(); } @Test void testGetURLBackupAddress() { URL url = URL.valueOf( zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + 9099 + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT&timestamp=1547102428828"); List<String> stringList = abstractZookeeperTransporter.getURLBackupAddress(url); Assertions.assertEquals(stringList.size(), 2); Assertions.assertEquals(stringList.get(0), "127.0.0.1:" + zookeeperServerPort1); Assertions.assertEquals(stringList.get(1), "127.0.0.1:9099"); } @Test void testGetURLBackupAddressNoBack() { URL url = URL.valueOf( zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT&timestamp=1547102428828"); List<String> stringList = abstractZookeeperTransporter.getURLBackupAddress(url); Assertions.assertEquals(stringList.size(), 1); Assertions.assertEquals(stringList.get(0), "127.0.0.1:" + zookeeperServerPort1); } @Test void testFetchAndUpdateZookeeperClientCache() { URL url = URL.valueOf( zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + zookeeperServerPort1 + ",127.0.0.1:" + zookeeperServerPort2 + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT&timestamp=1547102428828"); ZookeeperClient newZookeeperClient = abstractZookeeperTransporter.connect(url); // just for connected newZookeeperClient.getContent("/dubbo/test"); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); URL url2 = URL.valueOf( "zookeeper://127.0.0.1:" + zookeeperServerPort1 + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); checkFetchAndUpdateCacheNotNull(url2); URL url3 = URL.valueOf( "zookeeper://127.0.0.1:8778/org.apache.dubbo.metadata.store.MetadataReport?backup=127.0.0.1:" + zookeeperServerPort2 + "&address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); checkFetchAndUpdateCacheNotNull(url3); } private void checkFetchAndUpdateCacheNotNull(URL url) { List<String> addressList = abstractZookeeperTransporter.getURLBackupAddress(url); ZookeeperClient zookeeperClient = abstractZookeeperTransporter.fetchAndUpdateZookeeperClientCache(addressList); Assertions.assertNotNull(zookeeperClient); } @Test void testRepeatConnect() { URL url = URL.valueOf( zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT&timestamp=1547102428828"); URL url2 = URL.valueOf( zookeeperConnectionAddress1 + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); ZookeeperClient newZookeeperClient = abstractZookeeperTransporter.connect(url); // just for connected newZookeeperClient.getContent("/dubbo/test"); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); Assertions.assertTrue(newZookeeperClient.isConnected()); ZookeeperClient newZookeeperClient2 = abstractZookeeperTransporter.connect(url2); // just for connected newZookeeperClient2.getContent("/dubbo/test"); Assertions.assertEquals(newZookeeperClient, newZookeeperClient2); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); } @Test void testNotRepeatConnect() { URL url = URL.valueOf( zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT&timestamp=1547102428828"); URL url2 = URL.valueOf( zookeeperConnectionAddress2 + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); ZookeeperClient newZookeeperClient = abstractZookeeperTransporter.connect(url); // just for connected newZookeeperClient.getContent("/dubbo/test"); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); ZookeeperClient newZookeeperClient2 = abstractZookeeperTransporter.connect(url2); // just for connected newZookeeperClient2.getContent("/dubbo/test"); Assertions.assertNotEquals(newZookeeperClient, newZookeeperClient2); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort2), newZookeeperClient2); } @Test void testRepeatConnectForBackUpAdd() { URL url = URL.valueOf( zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + zookeeperServerPort1 + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT&timestamp=1547102428828"); URL url2 = URL.valueOf( zookeeperConnectionAddress1 + "/org.apache.dubbo.metadata.store.MetadataReport?backup=127.0.0.1:" + zookeeperServerPort2 + "&address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); ZookeeperClient newZookeeperClient = abstractZookeeperTransporter.connect(url); // just for connected newZookeeperClient.getContent("/dubbo/test"); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); ZookeeperClient newZookeeperClient2 = abstractZookeeperTransporter.connect(url2); // just for connected newZookeeperClient2.getContent("/dubbo/test"); Assertions.assertEquals(newZookeeperClient, newZookeeperClient2); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort2), newZookeeperClient2); } @Test void testRepeatConnectForNoMatchBackUpAdd() { URL url = URL.valueOf( zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + zookeeperServerPort1 + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT&timestamp=1547102428828"); URL url2 = URL.valueOf( zookeeperConnectionAddress2 + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); ZookeeperClient newZookeeperClient = abstractZookeeperTransporter.connect(url); // just for connected newZookeeperClient.getContent("/dubbo/test"); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); ZookeeperClient newZookeeperClient2 = abstractZookeeperTransporter.connect(url2); // just for connected newZookeeperClient2.getContent("/dubbo/test"); Assertions.assertNotEquals(newZookeeperClient, newZookeeperClient2); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort2), newZookeeperClient2); } @Test void testSameHostWithDifferentUser() { URL url1 = URL.valueOf("zookeeper://us1:[email protected]:" + zookeeperServerPort1 + "/path1"); URL url2 = URL.valueOf("zookeeper://us2:[email protected]:" + zookeeperServerPort1 + "/path2"); ZookeeperClient client1 = abstractZookeeperTransporter.connect(url1); ZookeeperClient client2 = abstractZookeeperTransporter.connect(url2); assertThat(client1, not(client2)); } }
7,616
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperClient.java
/* * 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 * * 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 org.apache.dubbo.remoting.zookeeper.curator5; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigItem; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.zookeeper.AbstractZookeeperClient; import org.apache.dubbo.remoting.zookeeper.ChildListener; import org.apache.dubbo.remoting.zookeeper.DataListener; import org.apache.dubbo.remoting.zookeeper.EventType; import org.apache.dubbo.remoting.zookeeper.StateListener; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.ACLProvider; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.curator.framework.recipes.cache.ChildData; import org.apache.curator.framework.recipes.cache.NodeCache; import org.apache.curator.framework.recipes.cache.NodeCacheListener; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.RetryNTimes; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException.NoNodeException; import org.apache.zookeeper.KeeperException.NodeExistsException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; import static org.apache.dubbo.common.constants.CommonConstants.SESSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_CONNECT_REGISTRY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION; public class Curator5ZookeeperClient extends AbstractZookeeperClient< Curator5ZookeeperClient.NodeCacheListenerImpl, Curator5ZookeeperClient.CuratorWatcherImpl> { protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(Curator5ZookeeperClient.class); private static final Charset CHARSET = StandardCharsets.UTF_8; private final CuratorFramework client; private static Map<String, NodeCache> nodeCacheMap = new ConcurrentHashMap<>(); public Curator5ZookeeperClient(URL url) { super(url); try { int timeout = url.getParameter(TIMEOUT_KEY, DEFAULT_CONNECTION_TIMEOUT_MS); int sessionExpireMs = url.getParameter(SESSION_KEY, DEFAULT_SESSION_TIMEOUT_MS); CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder() .connectString(url.getBackupAddress()) .retryPolicy(new RetryNTimes(1, 1000)) .connectionTimeoutMs(timeout) .sessionTimeoutMs(sessionExpireMs); String userInformation = url.getUserInformation(); if (userInformation != null && userInformation.length() > 0) { builder = builder.authorization("digest", userInformation.getBytes()); builder.aclProvider(new ACLProvider() { @Override public List<ACL> getDefaultAcl() { return ZooDefs.Ids.CREATOR_ALL_ACL; } @Override public List<ACL> getAclForPath(String path) { return ZooDefs.Ids.CREATOR_ALL_ACL; } }); } client = builder.build(); client.getConnectionStateListenable().addListener(new CuratorConnectionStateListener(url)); client.start(); boolean connected = client.blockUntilConnected(timeout, TimeUnit.MILLISECONDS); if (!connected) { IllegalStateException illegalStateException = new IllegalStateException("zookeeper not connected, the address is: " + url); // 5-1 Failed to connect to configuration center. logger.error( CONFIG_FAILED_CONNECT_REGISTRY, "Zookeeper server offline", "", "Failed to connect with zookeeper", illegalStateException); throw illegalStateException; } } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override public void createPersistent(String path, boolean faultTolerant) { try { client.create().forPath(path); } catch (NodeExistsException e) { if (!faultTolerant) { logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "ZNode " + path + " already exists.", e); throw new IllegalStateException(e.getMessage(), e); } } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override public void createEphemeral(String path, boolean faultTolerant) { try { client.create().withMode(CreateMode.EPHEMERAL).forPath(path); } catch (NodeExistsException e) { if (faultTolerant) { logger.info("ZNode " + path + " already exists, since we will only try to recreate a node on a session expiration" + ", this duplication might be caused by a delete delay from the zk server, which means the old expired session" + " may still holds this ZNode and the server just hasn't got time to do the deletion. In this case, " + "we can just try to delete and create again."); deletePath(path); createEphemeral(path, true); } else { logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "ZNode " + path + " already exists.", e); throw new IllegalStateException(e.getMessage(), e); } } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override protected void createPersistent(String path, String data, boolean faultTolerant) { byte[] dataBytes = data.getBytes(CHARSET); try { client.create().forPath(path, dataBytes); } catch (NodeExistsException e) { if (faultTolerant) { logger.info("ZNode " + path + " already exists. Will be override with new data."); try { client.setData().forPath(path, dataBytes); } catch (Exception e1) { throw new IllegalStateException(e.getMessage(), e1); } } else { logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "ZNode " + path + " already exists.", e); throw new IllegalStateException(e.getMessage(), e); } } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override protected void createEphemeral(String path, String data, boolean faultTolerant) { byte[] dataBytes = data.getBytes(CHARSET); try { client.create().withMode(CreateMode.EPHEMERAL).forPath(path, dataBytes); } catch (NodeExistsException e) { if (faultTolerant) { logger.info("ZNode " + path + " already exists, since we will only try to recreate a node on a session expiration" + ", this duplication might be caused by a delete delay from the zk server, which means the old expired session" + " may still holds this ZNode and the server just hasn't got time to do the deletion. In this case, " + "we can just try to delete and create again."); deletePath(path); createEphemeral(path, data, true); } else { logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "ZNode " + path + " already exists.", e); throw new IllegalStateException(e.getMessage(), e); } } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override protected void update(String path, String data, int version) { byte[] dataBytes = data.getBytes(CHARSET); try { client.setData().withVersion(version).forPath(path, dataBytes); } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override protected void update(String path, String data) { byte[] dataBytes = data.getBytes(CHARSET); try { client.setData().forPath(path, dataBytes); } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override protected void createOrUpdatePersistent(String path, String data) { try { if (checkExists(path)) { update(path, data); } else { createPersistent(path, data, true); } } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override protected void createOrUpdateEphemeral(String path, String data) { try { if (checkExists(path)) { update(path, data); } else { createEphemeral(path, data, true); } } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override protected void createOrUpdatePersistent(String path, String data, Integer version) { try { if (checkExists(path) && version != null) { update(path, data, version); } else { createPersistent(path, data, false); } } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override protected void createOrUpdateEphemeral(String path, String data, Integer version) { try { if (checkExists(path) && version != null) { update(path, data, version); } else { createEphemeral(path, data, false); } } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override protected void deletePath(String path) { try { client.delete().deletingChildrenIfNeeded().forPath(path); } catch (NoNodeException ignored) { } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override public List<String> getChildren(String path) { try { return client.getChildren().forPath(path); } catch (NoNodeException e) { return null; } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override public boolean checkExists(String path) { try { if (client.checkExists().forPath(path) != null) { return true; } } catch (Exception ignored) { } return false; } @Override public boolean isConnected() { return client.getZookeeperClient().isConnected(); } @Override public String doGetContent(String path) { try { byte[] dataBytes = client.getData().forPath(path); return (dataBytes == null || dataBytes.length == 0) ? null : new String(dataBytes, CHARSET); } catch (NoNodeException e) { // ignore NoNode Exception. } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } return null; } @Override public ConfigItem doGetConfigItem(String path) { String content; Stat stat; try { stat = new Stat(); byte[] dataBytes = client.getData().storingStatIn(stat).forPath(path); content = (dataBytes == null || dataBytes.length == 0) ? null : new String(dataBytes, CHARSET); } catch (NoNodeException e) { return new ConfigItem(); } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } return new ConfigItem(content, stat); } @Override public void doClose() { super.doClose(); client.close(); } @Override public Curator5ZookeeperClient.CuratorWatcherImpl createTargetChildListener(String path, ChildListener listener) { return new Curator5ZookeeperClient.CuratorWatcherImpl(client, listener, path); } @Override public List<String> addTargetChildListener(String path, CuratorWatcherImpl listener) { try { return client.getChildren().usingWatcher(listener).forPath(path); } catch (NoNodeException e) { return null; } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override protected Curator5ZookeeperClient.NodeCacheListenerImpl createTargetDataListener( String path, DataListener listener) { return new NodeCacheListenerImpl(client, listener, path); } @Override protected void addTargetDataListener(String path, Curator5ZookeeperClient.NodeCacheListenerImpl nodeCacheListener) { this.addTargetDataListener(path, nodeCacheListener, null); } @Override protected void addTargetDataListener( String path, Curator5ZookeeperClient.NodeCacheListenerImpl nodeCacheListener, Executor executor) { try { NodeCache nodeCache = new NodeCache(client, path); if (nodeCacheMap.putIfAbsent(path, nodeCache) != null) { return; } if (executor == null) { nodeCache.getListenable().addListener(nodeCacheListener); } else { nodeCache.getListenable().addListener(nodeCacheListener, executor); } nodeCache.start(); } catch (Exception e) { throw new IllegalStateException("Add nodeCache listener for path:" + path, e); } } @Override protected void removeTargetDataListener( String path, Curator5ZookeeperClient.NodeCacheListenerImpl nodeCacheListener) { NodeCache nodeCache = nodeCacheMap.get(path); if (nodeCache != null) { nodeCache.getListenable().removeListener(nodeCacheListener); } nodeCacheListener.dataListener = null; } @Override public void removeTargetChildListener(String path, CuratorWatcherImpl listener) { listener.unwatch(); } static class NodeCacheListenerImpl implements NodeCacheListener { private CuratorFramework client; private volatile DataListener dataListener; private String path; protected NodeCacheListenerImpl() {} public NodeCacheListenerImpl(CuratorFramework client, DataListener dataListener, String path) { this.client = client; this.dataListener = dataListener; this.path = path; } @Override public void nodeChanged() throws Exception { ChildData childData = nodeCacheMap.get(path).getCurrentData(); String content = null; EventType eventType; if (childData == null) { eventType = EventType.NodeDeleted; } else if (childData.getStat().getVersion() == 0) { content = new String(childData.getData(), CHARSET); eventType = EventType.NodeCreated; } else { content = new String(childData.getData(), CHARSET); eventType = EventType.NodeDataChanged; } dataListener.dataChanged(path, content, eventType); } } static class CuratorWatcherImpl implements CuratorWatcher { private CuratorFramework client; private volatile ChildListener childListener; private String path; public CuratorWatcherImpl(CuratorFramework client, ChildListener listener, String path) { this.client = client; this.childListener = listener; this.path = path; } protected CuratorWatcherImpl() {} public void unwatch() { this.childListener = null; } @Override public void process(WatchedEvent event) throws Exception { // if client connect or disconnect to server, zookeeper will queue // watched event(Watcher.Event.EventType.None, .., path = null). if (event.getType() == Watcher.Event.EventType.None) { return; } if (childListener != null) { childListener.childChanged( path, client.getChildren().usingWatcher(this).forPath(path)); } } } private class CuratorConnectionStateListener implements ConnectionStateListener { private final long UNKNOWN_SESSION_ID = -1L; private long lastSessionId; private int timeout; private int sessionExpireMs; public CuratorConnectionStateListener(URL url) { this.timeout = url.getParameter(TIMEOUT_KEY, DEFAULT_CONNECTION_TIMEOUT_MS); this.sessionExpireMs = url.getParameter(SESSION_KEY, DEFAULT_SESSION_TIMEOUT_MS); } @Override public void stateChanged(CuratorFramework client, ConnectionState state) { long sessionId = UNKNOWN_SESSION_ID; try { sessionId = client.getZookeeperClient().getZooKeeper().getSessionId(); } catch (Exception e) { logger.warn( REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Curator client state changed, but failed to get the related zk session instance."); } if (state == ConnectionState.LOST) { logger.warn( REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Curator zookeeper session " + Long.toHexString(lastSessionId) + " expired."); Curator5ZookeeperClient.this.stateChanged(StateListener.SESSION_LOST); } else if (state == ConnectionState.SUSPENDED) { logger.warn( REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Curator zookeeper connection of session " + Long.toHexString(sessionId) + " timed out. " + "connection timeout value is " + timeout + ", session expire timeout value is " + sessionExpireMs); Curator5ZookeeperClient.this.stateChanged(StateListener.SUSPENDED); } else if (state == ConnectionState.CONNECTED) { lastSessionId = sessionId; logger.info("Curator zookeeper client instance initiated successfully, session id is " + Long.toHexString(sessionId)); Curator5ZookeeperClient.this.stateChanged(StateListener.CONNECTED); } else if (state == ConnectionState.RECONNECTED) { if (lastSessionId == sessionId && sessionId != UNKNOWN_SESSION_ID) { logger.warn( REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Curator zookeeper connection recovered from connection lose, " + "reuse the old session " + Long.toHexString(sessionId)); Curator5ZookeeperClient.this.stateChanged(StateListener.RECONNECTED); } else { logger.warn( REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "New session created after old session lost, " + "old session " + Long.toHexString(lastSessionId) + ", new session " + Long.toHexString(sessionId)); lastSessionId = sessionId; Curator5ZookeeperClient.this.stateChanged(StateListener.NEW_SESSION_CREATED); } } } } /** * just for unit test * * @return */ CuratorFramework getClient() { return client; } }
7,617
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperTransporter.java
/* * 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 * * 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 org.apache.dubbo.remoting.zookeeper.curator5; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.zookeeper.AbstractZookeeperTransporter; import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; public class Curator5ZookeeperTransporter extends AbstractZookeeperTransporter { @Override public ZookeeperClient createZookeeperClient(URL url) { return new Curator5ZookeeperClient(url); } }
7,618
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClientTest.java
/* * 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 * * 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 org.apache.dubbo.remoting.zookeeper.curator; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigItem; import org.apache.dubbo.remoting.zookeeper.ChildListener; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.data.Stat; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.DisabledForJreRange; import org.junit.jupiter.api.condition.JRE; import static org.awaitility.Awaitility.await; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.mock; @DisabledForJreRange(min = JRE.JAVA_16) class CuratorZookeeperClientTest { private CuratorZookeeperClient curatorClient; CuratorFramework client = null; private static int zookeeperServerPort1; private static String zookeeperConnectionAddress1; @BeforeAll public static void beforeAll() { zookeeperConnectionAddress1 = System.getProperty("zookeeper.connection.address.1"); zookeeperServerPort1 = Integer.parseInt( zookeeperConnectionAddress1.substring(zookeeperConnectionAddress1.lastIndexOf(":") + 1)); } @BeforeEach public void setUp() throws Exception { curatorClient = new CuratorZookeeperClient( URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")); client = CuratorFrameworkFactory.newClient( "127.0.0.1:" + zookeeperServerPort1, new ExponentialBackoffRetry(1000, 3)); client.start(); } @Test void testCheckExists() { String path = "/dubbo/org.apache.dubbo.demo.DemoService/providers"; curatorClient.create(path, false, true); assertThat(curatorClient.checkExists(path), is(true)); assertThat(curatorClient.checkExists(path + "/noneexits"), is(false)); } @Test void testChildrenPath() { String path = "/dubbo/org.apache.dubbo.demo.DemoService/providers"; curatorClient.create(path, false, true); curatorClient.create(path + "/provider1", false, true); curatorClient.create(path + "/provider2", false, true); List<String> children = curatorClient.getChildren(path); assertThat(children.size(), is(2)); } @Test @Disabled("Global registry center") public void testChildrenListener() throws InterruptedException { String path = "/dubbo/org.apache.dubbo.demo.DemoService/providers"; curatorClient.create(path, false, true); final CountDownLatch countDownLatch = new CountDownLatch(1); curatorClient.addTargetChildListener(path, new CuratorZookeeperClient.CuratorWatcherImpl() { @Override public void process(WatchedEvent watchedEvent) { countDownLatch.countDown(); } }); curatorClient.createPersistent(path + "/provider1", true); countDownLatch.await(); } @Test void testWithInvalidServer() { Assertions.assertThrows(IllegalStateException.class, () -> { curatorClient = new CuratorZookeeperClient(URL.valueOf("zookeeper://127.0.0.1:1/service")); curatorClient.create("/testPath", true, true); }); } @Test @Disabled("Global registry center cannot stop") public void testWithStoppedServer() { Assertions.assertThrows(IllegalStateException.class, () -> { curatorClient.create("/testPath", true, true); curatorClient.delete("/testPath"); }); } @Test void testRemoveChildrenListener() { ChildListener childListener = mock(ChildListener.class); curatorClient.addChildListener("/children", childListener); curatorClient.removeChildListener("/children", childListener); } @Test void testCreateExistingPath() { curatorClient.create("/pathOne", false, true); curatorClient.create("/pathOne", false, true); } @Test void testConnectedStatus() { curatorClient.createEphemeral("/testPath", true); boolean connected = curatorClient.isConnected(); assertThat(connected, is(true)); } @Test void testCreateContent4Persistent() { String path = "/curatorTest4CrContent/content.data"; String content = "createContentTest"; curatorClient.delete(path); assertThat(curatorClient.checkExists(path), is(false)); assertNull(curatorClient.getContent(path)); curatorClient.createOrUpdate(path, content, false); assertThat(curatorClient.checkExists(path), is(true)); assertEquals(curatorClient.getContent(path), content); } @Test void testCreateContent4Temp() { String path = "/curatorTest4CrContent/content.data"; String content = "createContentTest"; curatorClient.delete(path); assertThat(curatorClient.checkExists(path), is(false)); assertNull(curatorClient.getContent(path)); curatorClient.createOrUpdate(path, content, true); assertThat(curatorClient.checkExists(path), is(true)); assertEquals(curatorClient.getContent(path), content); } @Test void testCreatePersistentFailed() { String path = "/dubbo/test/path"; curatorClient.delete(path); curatorClient.create(path, false, true); Assertions.assertTrue(curatorClient.checkExists(path)); curatorClient.createPersistent(path, true); Assertions.assertTrue(curatorClient.checkExists(path)); curatorClient.createPersistent(path, true); Assertions.assertTrue(curatorClient.checkExists(path)); Assertions.assertThrows(IllegalStateException.class, () -> { curatorClient.createPersistent(path, false); }); Assertions.assertTrue(curatorClient.checkExists(path)); } @Test void testCreateEphemeralFailed() { String path = "/dubbo/test/path"; curatorClient.delete(path); curatorClient.create(path, true, true); Assertions.assertTrue(curatorClient.checkExists(path)); curatorClient.createEphemeral(path, true); Assertions.assertTrue(curatorClient.checkExists(path)); curatorClient.createEphemeral(path, true); Assertions.assertTrue(curatorClient.checkExists(path)); Assertions.assertThrows(IllegalStateException.class, () -> { curatorClient.createEphemeral(path, false); }); Assertions.assertTrue(curatorClient.checkExists(path)); } @AfterEach public void tearDown() throws Exception { curatorClient.close(); } @Test void testAddTargetDataListener() throws Exception { String listenerPath = "/dubbo/service.name/configuration"; String path = listenerPath + "/dat/data"; String value = "vav"; curatorClient.createOrUpdate(path + "/d.json", value, true); String valueFromCache = curatorClient.getContent(path + "/d.json"); Assertions.assertEquals(value, valueFromCache); final AtomicInteger atomicInteger = new AtomicInteger(0); curatorClient.addTargetDataListener(path + "/d.json", new CuratorZookeeperClient.NodeCacheListenerImpl() { @Override public void nodeChanged() { atomicInteger.incrementAndGet(); } }); valueFromCache = curatorClient.getContent(path + "/d.json"); Assertions.assertNotNull(valueFromCache); int currentCount1 = atomicInteger.get(); curatorClient.getClient().setData().forPath(path + "/d.json", "foo".getBytes()); await().until(() -> atomicInteger.get() > currentCount1); int currentCount2 = atomicInteger.get(); curatorClient.getClient().setData().forPath(path + "/d.json", "bar".getBytes()); await().until(() -> atomicInteger.get() > currentCount2); int currentCount3 = atomicInteger.get(); curatorClient.delete(path + "/d.json"); valueFromCache = curatorClient.getContent(path + "/d.json"); Assertions.assertNull(valueFromCache); await().until(() -> atomicInteger.get() > currentCount3); } @Test void testPersistentCas1() throws Exception { // test create failed when others create success String path = "/dubbo/mapping/org.apache.dubbo.demo.DemoService"; AtomicReference<Runnable> runnable = new AtomicReference<>(); CuratorZookeeperClient curatorClient = new CuratorZookeeperClient( URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { @Override protected void createPersistent(String path, String data, boolean faultTolerant) { if (runnable.get() != null) { runnable.get().run(); } super.createPersistent(path, data, faultTolerant); } @Override protected void update(String path, String data, int version) { if (runnable.get() != null) { runnable.get().run(); } super.update(path, data, version); } }; curatorClient.delete(path); runnable.set(() -> { try { client.create().forPath(path, "version x".getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { throw new RuntimeException(e); } }); Assertions.assertThrows( IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", false, 0)); Assertions.assertEquals("version x", curatorClient.getContent(path)); client.setData().forPath(path, "version 1".getBytes(StandardCharsets.UTF_8)); ConfigItem configItem = curatorClient.getConfigItem(path); runnable.set(() -> { try { client.setData().forPath(path, "version x".getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { throw new RuntimeException(e); } }); int version1 = ((Stat) configItem.getTicket()).getVersion(); Assertions.assertThrows( IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 2", false, version1)); Assertions.assertEquals("version x", curatorClient.getContent(path)); runnable.set(null); configItem = curatorClient.getConfigItem(path); int version2 = ((Stat) configItem.getTicket()).getVersion(); curatorClient.createOrUpdate(path, "version 2", false, version2); Assertions.assertEquals("version 2", curatorClient.getContent(path)); curatorClient.close(); } @Test void testPersistentCas2() { // test update failed when others create success String path = "/dubbo/mapping/org.apache.dubbo.demo.DemoService"; CuratorZookeeperClient curatorClient = new CuratorZookeeperClient( URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")); curatorClient.delete(path); curatorClient.createOrUpdate(path, "version x", false); Assertions.assertThrows( IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", false, null)); Assertions.assertEquals("version x", curatorClient.getContent(path)); curatorClient.close(); } @Test void testPersistentNonVersion() { String path = "/dubbo/metadata/org.apache.dubbo.demo.DemoService"; AtomicReference<Runnable> runnable = new AtomicReference<>(); CuratorZookeeperClient curatorClient = new CuratorZookeeperClient( URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { @Override protected void createPersistent(String path, String data, boolean faultTolerant) { if (runnable.get() != null) { runnable.get().run(); } super.createPersistent(path, data, faultTolerant); } @Override protected void update(String path, String data, int version) { if (runnable.get() != null) { runnable.get().run(); } super.update(path, data, version); } }; curatorClient.delete(path); curatorClient.createOrUpdate(path, "version 0", false); Assertions.assertEquals("version 0", curatorClient.getContent(path)); curatorClient.delete(path); runnable.set(() -> { try { client.create().forPath(path, "version x".getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { throw new RuntimeException(e); } }); curatorClient.createOrUpdate(path, "version 1", false); Assertions.assertEquals("version 1", curatorClient.getContent(path)); runnable.set(() -> { try { client.setData().forPath(path, "version x".getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { throw new RuntimeException(e); } }); curatorClient.createOrUpdate(path, "version 2", false); Assertions.assertEquals("version 2", curatorClient.getContent(path)); runnable.set(null); curatorClient.createOrUpdate(path, "version 3", false); Assertions.assertEquals("version 3", curatorClient.getContent(path)); curatorClient.close(); } @Test void testEphemeralCas1() throws Exception { // test create failed when others create success String path = "/dubbo/mapping/org.apache.dubbo.demo.DemoService"; AtomicReference<Runnable> runnable = new AtomicReference<>(); CuratorZookeeperClient curatorClient = new CuratorZookeeperClient( URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { @Override protected void createEphemeral(String path, String data, boolean faultTolerant) { if (runnable.get() != null) { runnable.get().run(); } super.createPersistent(path, data, faultTolerant); } @Override protected void update(String path, String data, int version) { if (runnable.get() != null) { runnable.get().run(); } super.update(path, data, version); } }; curatorClient.delete(path); runnable.set(() -> { try { client.create().forPath(path, "version x".getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { throw new RuntimeException(e); } }); Assertions.assertThrows( IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", true, 0)); Assertions.assertEquals("version x", curatorClient.getContent(path)); client.setData().forPath(path, "version 1".getBytes(StandardCharsets.UTF_8)); ConfigItem configItem = curatorClient.getConfigItem(path); runnable.set(() -> { try { client.setData().forPath(path, "version x".getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { throw new RuntimeException(e); } }); int version1 = ((Stat) configItem.getTicket()).getVersion(); Assertions.assertThrows( IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 2", true, version1)); Assertions.assertEquals("version x", curatorClient.getContent(path)); runnable.set(null); configItem = curatorClient.getConfigItem(path); int version2 = ((Stat) configItem.getTicket()).getVersion(); curatorClient.createOrUpdate(path, "version 2", true, version2); Assertions.assertEquals("version 2", curatorClient.getContent(path)); curatorClient.close(); } @Test void testEphemeralCas2() { // test update failed when others create success String path = "/dubbo/mapping/org.apache.dubbo.demo.DemoService"; CuratorZookeeperClient curatorClient = new CuratorZookeeperClient( URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")); curatorClient.delete(path); curatorClient.createOrUpdate(path, "version x", true); Assertions.assertThrows( IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", true, null)); Assertions.assertEquals("version x", curatorClient.getContent(path)); curatorClient.close(); } @Test void testEphemeralNonVersion() { String path = "/dubbo/metadata/org.apache.dubbo.demo.DemoService"; AtomicReference<Runnable> runnable = new AtomicReference<>(); CuratorZookeeperClient curatorClient = new CuratorZookeeperClient( URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) { @Override protected void createPersistent(String path, String data, boolean faultTolerant) { if (runnable.get() != null) { runnable.get().run(); } super.createPersistent(path, data, faultTolerant); } @Override protected void update(String path, String data, int version) { if (runnable.get() != null) { runnable.get().run(); } super.update(path, data, version); } }; curatorClient.delete(path); curatorClient.createOrUpdate(path, "version 0", true); Assertions.assertEquals("version 0", curatorClient.getContent(path)); curatorClient.delete(path); runnable.set(() -> { try { client.create().forPath(path, "version x".getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { throw new RuntimeException(e); } }); curatorClient.createOrUpdate(path, "version 1", true); Assertions.assertEquals("version 1", curatorClient.getContent(path)); runnable.set(() -> { try { client.setData().forPath(path, "version x".getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { throw new RuntimeException(e); } }); curatorClient.createOrUpdate(path, "version 2", true); Assertions.assertEquals("version 2", curatorClient.getContent(path)); runnable.set(null); curatorClient.createOrUpdate(path, "version 3", true); Assertions.assertEquals("version 3", curatorClient.getContent(path)); curatorClient.close(); } }
7,619
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperTransporterTest.java
/* * 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 * * 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 org.apache.dubbo.remoting.zookeeper.curator; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.DisabledForJreRange; import org.junit.jupiter.api.condition.JRE; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNull.nullValue; @DisabledForJreRange(min = JRE.JAVA_16) class CuratorZookeeperTransporterTest { private ZookeeperClient zookeeperClient; private CuratorZookeeperTransporter curatorZookeeperTransporter; private static String zookeeperConnectionAddress1; @BeforeAll public static void beforeAll() { zookeeperConnectionAddress1 = System.getProperty("zookeeper.connection.address.1"); } @BeforeEach public void setUp() throws Exception { zookeeperClient = new CuratorZookeeperTransporter().connect(URL.valueOf(zookeeperConnectionAddress1 + "/service")); curatorZookeeperTransporter = new CuratorZookeeperTransporter(); } @Test void testZookeeperClient() { assertThat(zookeeperClient, not(nullValue())); zookeeperClient.close(); } }
7,620
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-zookeeper/src/test/java/org/apache/dubbo/remoting/zookeeper/curator/support/AbstractZookeeperTransporterTest.java
/* * 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 * * 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 org.apache.dubbo.remoting.zookeeper.curator.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.zookeeper.AbstractZookeeperTransporter; import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; import org.apache.dubbo.remoting.zookeeper.curator.CuratorZookeeperTransporter; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.DisabledForJreRange; import org.junit.jupiter.api.condition.JRE; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNull.nullValue; /** * AbstractZookeeperTransporterTest */ @DisabledForJreRange(min = JRE.JAVA_16) class AbstractZookeeperTransporterTest { private ZookeeperClient zookeeperClient; private AbstractZookeeperTransporter abstractZookeeperTransporter; private static int zookeeperServerPort1, zookeeperServerPort2; private static String zookeeperConnectionAddress1, zookeeperConnectionAddress2; @BeforeAll public static void beforeAll() { zookeeperConnectionAddress1 = System.getProperty("zookeeper.connection.address.1"); zookeeperConnectionAddress2 = System.getProperty("zookeeper.connection.address.2"); zookeeperServerPort1 = Integer.parseInt( zookeeperConnectionAddress1.substring(zookeeperConnectionAddress1.lastIndexOf(":") + 1)); zookeeperServerPort2 = Integer.parseInt( zookeeperConnectionAddress2.substring(zookeeperConnectionAddress2.lastIndexOf(":") + 1)); } @BeforeEach public void setUp() throws Exception { zookeeperClient = new CuratorZookeeperTransporter() .connect(URL.valueOf("zookeeper://127.0.0.1:" + zookeeperServerPort1 + "/service")); abstractZookeeperTransporter = new CuratorZookeeperTransporter(); } @Test void testZookeeperClient() { assertThat(zookeeperClient, not(nullValue())); zookeeperClient.close(); } @Test void testGetURLBackupAddress() { URL url = URL.valueOf( zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + 9099 + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT&timestamp=1547102428828"); List<String> stringList = abstractZookeeperTransporter.getURLBackupAddress(url); Assertions.assertEquals(stringList.size(), 2); Assertions.assertEquals(stringList.get(0), "127.0.0.1:" + zookeeperServerPort1); Assertions.assertEquals(stringList.get(1), "127.0.0.1:9099"); } @Test void testGetURLBackupAddressNoBack() { URL url = URL.valueOf( zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT&timestamp=1547102428828"); List<String> stringList = abstractZookeeperTransporter.getURLBackupAddress(url); Assertions.assertEquals(stringList.size(), 1); Assertions.assertEquals(stringList.get(0), "127.0.0.1:" + zookeeperServerPort1); } @Test void testFetchAndUpdateZookeeperClientCache() { URL url = URL.valueOf( zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + zookeeperServerPort1 + ",127.0.0.1:" + zookeeperServerPort2 + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT&timestamp=1547102428828"); ZookeeperClient newZookeeperClient = abstractZookeeperTransporter.connect(url); // just for connected newZookeeperClient.getContent("/dubbo/test"); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); URL url2 = URL.valueOf( "zookeeper://127.0.0.1:" + zookeeperServerPort1 + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); checkFetchAndUpdateCacheNotNull(url2); URL url3 = URL.valueOf( "zookeeper://127.0.0.1:8778/org.apache.dubbo.metadata.store.MetadataReport?backup=127.0.0.1:" + zookeeperServerPort2 + "&address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); checkFetchAndUpdateCacheNotNull(url3); } private void checkFetchAndUpdateCacheNotNull(URL url) { List<String> addressList = abstractZookeeperTransporter.getURLBackupAddress(url); ZookeeperClient zookeeperClient = abstractZookeeperTransporter.fetchAndUpdateZookeeperClientCache(addressList); Assertions.assertNotNull(zookeeperClient); } @Test void testRepeatConnect() { URL url = URL.valueOf( zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT&timestamp=1547102428828"); URL url2 = URL.valueOf( zookeeperConnectionAddress1 + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); ZookeeperClient newZookeeperClient = abstractZookeeperTransporter.connect(url); // just for connected newZookeeperClient.getContent("/dubbo/test"); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); Assertions.assertTrue(newZookeeperClient.isConnected()); ZookeeperClient newZookeeperClient2 = abstractZookeeperTransporter.connect(url2); // just for connected newZookeeperClient2.getContent("/dubbo/test"); Assertions.assertEquals(newZookeeperClient, newZookeeperClient2); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); } @Test void testNotRepeatConnect() { URL url = URL.valueOf( zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT&timestamp=1547102428828"); URL url2 = URL.valueOf( zookeeperConnectionAddress2 + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); ZookeeperClient newZookeeperClient = abstractZookeeperTransporter.connect(url); // just for connected newZookeeperClient.getContent("/dubbo/test"); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); ZookeeperClient newZookeeperClient2 = abstractZookeeperTransporter.connect(url2); // just for connected newZookeeperClient2.getContent("/dubbo/test"); Assertions.assertNotEquals(newZookeeperClient, newZookeeperClient2); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort2), newZookeeperClient2); } @Test void testRepeatConnectForBackUpAdd() { URL url = URL.valueOf( zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + zookeeperServerPort1 + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT&timestamp=1547102428828"); URL url2 = URL.valueOf( zookeeperConnectionAddress1 + "/org.apache.dubbo.metadata.store.MetadataReport?backup=127.0.0.1:" + zookeeperServerPort2 + "&address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); ZookeeperClient newZookeeperClient = abstractZookeeperTransporter.connect(url); // just for connected newZookeeperClient.getContent("/dubbo/test"); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); ZookeeperClient newZookeeperClient2 = abstractZookeeperTransporter.connect(url2); // just for connected newZookeeperClient2.getContent("/dubbo/test"); Assertions.assertEquals(newZookeeperClient, newZookeeperClient2); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort2), newZookeeperClient2); } @Test void testRepeatConnectForNoMatchBackUpAdd() { URL url = URL.valueOf( zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + zookeeperServerPort1 + "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT&timestamp=1547102428828"); URL url2 = URL.valueOf( zookeeperConnectionAddress2 + "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true"); ZookeeperClient newZookeeperClient = abstractZookeeperTransporter.connect(url); // just for connected newZookeeperClient.getContent("/dubbo/test"); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().size(), 1); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1), newZookeeperClient); ZookeeperClient newZookeeperClient2 = abstractZookeeperTransporter.connect(url2); // just for connected newZookeeperClient2.getContent("/dubbo/test"); Assertions.assertNotEquals(newZookeeperClient, newZookeeperClient2); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().size(), 2); Assertions.assertEquals( abstractZookeeperTransporter.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort2), newZookeeperClient2); } @Test void testSameHostWithDifferentUser() { URL url1 = URL.valueOf("zookeeper://us1:[email protected]:" + zookeeperServerPort1 + "/path1"); URL url2 = URL.valueOf("zookeeper://us2:[email protected]:" + zookeeperServerPort1 + "/path2"); ZookeeperClient client1 = abstractZookeeperTransporter.connect(url1); ZookeeperClient client2 = abstractZookeeperTransporter.connect(url2); assertThat(client1, not(client2)); } }
7,621
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperTransporter.java
/* * 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 * * 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 org.apache.dubbo.remoting.zookeeper.curator; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.zookeeper.AbstractZookeeperTransporter; import org.apache.dubbo.remoting.zookeeper.ZookeeperClient; public class CuratorZookeeperTransporter extends AbstractZookeeperTransporter { @Override public ZookeeperClient createZookeeperClient(URL url) { return new CuratorZookeeperClient(url); } }
7,622
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/org/apache/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java
/* * 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 * * 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 org.apache.dubbo.remoting.zookeeper.curator; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigItem; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.zookeeper.AbstractZookeeperClient; import org.apache.dubbo.remoting.zookeeper.ChildListener; import org.apache.dubbo.remoting.zookeeper.DataListener; import org.apache.dubbo.remoting.zookeeper.EventType; import org.apache.dubbo.remoting.zookeeper.StateListener; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.ACLProvider; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.curator.framework.recipes.cache.ChildData; import org.apache.curator.framework.recipes.cache.NodeCache; import org.apache.curator.framework.recipes.cache.NodeCacheListener; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.RetryNTimes; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException.NoNodeException; import org.apache.zookeeper.KeeperException.NodeExistsException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; import static org.apache.dubbo.common.constants.CommonConstants.SESSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_CONNECT_REGISTRY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION; public class CuratorZookeeperClient extends AbstractZookeeperClient< CuratorZookeeperClient.NodeCacheListenerImpl, CuratorZookeeperClient.CuratorWatcherImpl> { protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CuratorZookeeperClient.class); private static final Charset CHARSET = StandardCharsets.UTF_8; private final CuratorFramework client; private static final Map<String, NodeCache> nodeCacheMap = new ConcurrentHashMap<>(); public CuratorZookeeperClient(URL url) { super(url); try { int timeout = url.getParameter(TIMEOUT_KEY, DEFAULT_CONNECTION_TIMEOUT_MS); int sessionExpireMs = url.getParameter(SESSION_KEY, DEFAULT_SESSION_TIMEOUT_MS); CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder() .connectString(url.getBackupAddress()) .retryPolicy(new RetryNTimes(1, 1000)) .connectionTimeoutMs(timeout) .sessionTimeoutMs(sessionExpireMs); String userInformation = url.getUserInformation(); if (StringUtils.isNotEmpty(userInformation)) { builder = builder.authorization("digest", userInformation.getBytes()); builder.aclProvider(new ACLProvider() { @Override public List<ACL> getDefaultAcl() { return ZooDefs.Ids.CREATOR_ALL_ACL; } @Override public List<ACL> getAclForPath(String path) { return ZooDefs.Ids.CREATOR_ALL_ACL; } }); } client = builder.build(); client.getConnectionStateListenable().addListener(new CuratorConnectionStateListener(url)); client.start(); boolean connected = client.blockUntilConnected(timeout, TimeUnit.MILLISECONDS); if (!connected) { IllegalStateException illegalStateException = new IllegalStateException("zookeeper not connected, the address is: " + url); // 5-1 Failed to connect to configuration center. logger.error( CONFIG_FAILED_CONNECT_REGISTRY, "Zookeeper server offline", "", "Failed to connect with zookeeper", illegalStateException); throw illegalStateException; } CuratorWatcherImpl.closed = false; } catch (Exception e) { close(); throw new IllegalStateException(e.getMessage(), e); } } @Override public void createPersistent(String path, boolean faultTolerant) { try { client.create().forPath(path); } catch (NodeExistsException e) { if (!faultTolerant) { logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "ZNode " + path + " already exists.", e); throw new IllegalStateException(e.getMessage(), e); } } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override public void createEphemeral(String path, boolean faultTolerant) { try { client.create().withMode(CreateMode.EPHEMERAL).forPath(path); } catch (NodeExistsException e) { if (faultTolerant) { logger.info("ZNode " + path + " already exists, since we will only try to recreate a node on a session expiration" + ", this duplication might be caused by a delete delay from the zk server, which means the old expired session" + " may still holds this ZNode and the server just hasn't got time to do the deletion. In this case, " + "we can just try to delete and create again."); deletePath(path); createEphemeral(path, true); } else { logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "ZNode " + path + " already exists.", e); throw new IllegalStateException(e.getMessage(), e); } } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override protected void createPersistent(String path, String data, boolean faultTolerant) { byte[] dataBytes = data.getBytes(CHARSET); try { client.create().forPath(path, dataBytes); } catch (NodeExistsException e) { if (faultTolerant) { logger.info("ZNode " + path + " already exists. Will be override with new data."); try { client.setData().forPath(path, dataBytes); } catch (Exception e1) { throw new IllegalStateException(e.getMessage(), e1); } } else { logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "ZNode " + path + " already exists.", e); throw new IllegalStateException(e.getMessage(), e); } } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override protected void createEphemeral(String path, String data, boolean faultTolerant) { byte[] dataBytes = data.getBytes(CHARSET); try { client.create().withMode(CreateMode.EPHEMERAL).forPath(path, dataBytes); } catch (NodeExistsException e) { if (faultTolerant) { logger.info("ZNode " + path + " already exists, since we will only try to recreate a node on a session expiration" + ", this duplication might be caused by a delete delay from the zk server, which means the old expired session" + " may still holds this ZNode and the server just hasn't got time to do the deletion. In this case, " + "we can just try to delete and create again."); deletePath(path); createEphemeral(path, data, true); } else { logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "ZNode " + path + " already exists.", e); throw new IllegalStateException(e.getMessage(), e); } } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override protected void update(String path, String data, int version) { byte[] dataBytes = data.getBytes(CHARSET); try { client.setData().withVersion(version).forPath(path, dataBytes); } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override protected void update(String path, String data) { byte[] dataBytes = data.getBytes(CHARSET); try { client.setData().forPath(path, dataBytes); } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override protected void createOrUpdatePersistent(String path, String data) { try { if (checkExists(path)) { update(path, data); } else { createPersistent(path, data, true); } } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override protected void createOrUpdateEphemeral(String path, String data) { try { if (checkExists(path)) { update(path, data); } else { createEphemeral(path, data, true); } } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override protected void createOrUpdatePersistent(String path, String data, Integer version) { try { if (checkExists(path) && version != null) { update(path, data, version); } else { createPersistent(path, data, false); } } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override protected void createOrUpdateEphemeral(String path, String data, Integer version) { try { if (checkExists(path) && version != null) { update(path, data, version); } else { createEphemeral(path, data, false); } } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override protected void deletePath(String path) { try { client.delete().deletingChildrenIfNeeded().forPath(path); } catch (NoNodeException ignored) { } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override public List<String> getChildren(String path) { try { return client.getChildren().forPath(path); } catch (NoNodeException e) { return null; } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override public boolean checkExists(String path) { try { if (client.checkExists().forPath(path) != null) { return true; } } catch (Exception ignored) { } return false; } @Override public boolean isConnected() { return client.getZookeeperClient().isConnected(); } @Override public String doGetContent(String path) { try { byte[] dataBytes = client.getData().forPath(path); return (dataBytes == null || dataBytes.length == 0) ? null : new String(dataBytes, CHARSET); } catch (NoNodeException e) { // ignore NoNode Exception. } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } return null; } @Override public ConfigItem doGetConfigItem(String path) { String content; Stat stat; try { stat = new Stat(); byte[] dataBytes = client.getData().storingStatIn(stat).forPath(path); content = (dataBytes == null || dataBytes.length == 0) ? null : new String(dataBytes, CHARSET); } catch (NoNodeException e) { return new ConfigItem(); } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } return new ConfigItem(content, stat); } @Override public void doClose() { super.close(); client.close(); CuratorWatcherImpl.closed = true; synchronized (CuratorWatcherImpl.class) { if (CuratorWatcherImpl.CURATOR_WATCHER_EXECUTOR_SERVICE != null) { CuratorWatcherImpl.CURATOR_WATCHER_EXECUTOR_SERVICE.shutdown(); CuratorWatcherImpl.CURATOR_WATCHER_EXECUTOR_SERVICE = null; } } } @Override public CuratorZookeeperClient.CuratorWatcherImpl createTargetChildListener(String path, ChildListener listener) { return new CuratorZookeeperClient.CuratorWatcherImpl(client, listener, path); } @Override public List<String> addTargetChildListener(String path, CuratorWatcherImpl listener) { try { return client.getChildren().usingWatcher(listener).forPath(path); } catch (NoNodeException e) { return null; } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } @Override protected CuratorZookeeperClient.NodeCacheListenerImpl createTargetDataListener( String path, DataListener listener) { return new NodeCacheListenerImpl(listener, path); } @Override protected void addTargetDataListener(String path, CuratorZookeeperClient.NodeCacheListenerImpl nodeCacheListener) { this.addTargetDataListener(path, nodeCacheListener, null); } @Override protected void addTargetDataListener( String path, CuratorZookeeperClient.NodeCacheListenerImpl nodeCacheListener, Executor executor) { try { NodeCache nodeCache = new NodeCache(client, path); if (nodeCacheMap.putIfAbsent(path, nodeCache) != null) { return; } if (executor == null) { nodeCache.getListenable().addListener(nodeCacheListener); } else { nodeCache.getListenable().addListener(nodeCacheListener, executor); } nodeCache.start(); } catch (Exception e) { throw new IllegalStateException("Add nodeCache listener for path:" + path, e); } } @Override protected void removeTargetDataListener( String path, CuratorZookeeperClient.NodeCacheListenerImpl nodeCacheListener) { NodeCache nodeCache = nodeCacheMap.get(path); if (nodeCache != null) { nodeCache.getListenable().removeListener(nodeCacheListener); } nodeCacheListener.dataListener = null; } @Override public void removeTargetChildListener(String path, CuratorWatcherImpl listener) { listener.unwatch(); } static class NodeCacheListenerImpl implements NodeCacheListener { private volatile DataListener dataListener; private String path; protected NodeCacheListenerImpl() {} public NodeCacheListenerImpl(DataListener dataListener, String path) { this.dataListener = dataListener; this.path = path; } @Override public void nodeChanged() throws Exception { ChildData childData = nodeCacheMap.get(path).getCurrentData(); String content = null; EventType eventType; if (childData == null) { eventType = EventType.NodeDeleted; } else if (childData.getStat().getVersion() == 0) { content = new String(childData.getData(), CHARSET); eventType = EventType.NodeCreated; } else { content = new String(childData.getData(), CHARSET); eventType = EventType.NodeDataChanged; } dataListener.dataChanged(path, content, eventType); } } static class CuratorWatcherImpl implements CuratorWatcher { private static volatile ExecutorService CURATOR_WATCHER_EXECUTOR_SERVICE; private static volatile boolean closed = false; private CuratorFramework client; private volatile ChildListener childListener; private String path; private static void initExecutorIfNecessary() { if (!closed && CURATOR_WATCHER_EXECUTOR_SERVICE == null) { synchronized (CuratorWatcherImpl.class) { if (!closed && CURATOR_WATCHER_EXECUTOR_SERVICE == null) { CURATOR_WATCHER_EXECUTOR_SERVICE = Executors.newSingleThreadExecutor(new NamedThreadFactory("Dubbo-CuratorWatcher")); } } } } public CuratorWatcherImpl(CuratorFramework client, ChildListener listener, String path) { this.client = client; this.childListener = listener; this.path = path; } protected CuratorWatcherImpl() {} public void unwatch() { this.childListener = null; } @Override public void process(WatchedEvent event) throws Exception { // if client connect or disconnect to server, zookeeper will queue // watched event(Watcher.Event.EventType.None, .., path = null). if (event.getType() == Watcher.Event.EventType.None) { return; } if (childListener != null) { Runnable task = () -> Optional.ofNullable(childListener).ifPresent(c -> { try { c.childChanged( path, client.getChildren() .usingWatcher(CuratorWatcherImpl.this) .forPath(path)); } catch (Exception e) { logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "client get children error", e); } }); initExecutorIfNecessary(); if (!closed && CURATOR_WATCHER_EXECUTOR_SERVICE != null) { CURATOR_WATCHER_EXECUTOR_SERVICE.execute(task); } } } } private class CuratorConnectionStateListener implements ConnectionStateListener { private final long UNKNOWN_SESSION_ID = -1L; private long lastSessionId; private int timeout; private int sessionExpireMs; public CuratorConnectionStateListener(URL url) { this.timeout = url.getParameter(TIMEOUT_KEY, DEFAULT_CONNECTION_TIMEOUT_MS); this.sessionExpireMs = url.getParameter(SESSION_KEY, DEFAULT_SESSION_TIMEOUT_MS); } @Override public void stateChanged(CuratorFramework client, ConnectionState state) { long sessionId = UNKNOWN_SESSION_ID; try { sessionId = client.getZookeeperClient().getZooKeeper().getSessionId(); } catch (Exception e) { logger.warn( REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Curator client state changed, but failed to get the related zk session instance."); } if (state == ConnectionState.LOST) { logger.warn( REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Curator zookeeper session " + Long.toHexString(lastSessionId) + " expired."); CuratorZookeeperClient.this.stateChanged(StateListener.SESSION_LOST); } else if (state == ConnectionState.SUSPENDED) { logger.warn( REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Curator zookeeper connection of session " + Long.toHexString(sessionId) + " timed out. " + "connection timeout value is " + timeout + ", session expire timeout value is " + sessionExpireMs); CuratorZookeeperClient.this.stateChanged(StateListener.SUSPENDED); } else if (state == ConnectionState.CONNECTED) { lastSessionId = sessionId; logger.info("Curator zookeeper client instance initiated successfully, session id is " + Long.toHexString(sessionId)); CuratorZookeeperClient.this.stateChanged(StateListener.CONNECTED); } else if (state == ConnectionState.RECONNECTED) { if (lastSessionId == sessionId && sessionId != UNKNOWN_SESSION_ID) { logger.warn( REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "Curator zookeeper connection recovered from connection lose, " + "reuse the old session " + Long.toHexString(sessionId)); CuratorZookeeperClient.this.stateChanged(StateListener.RECONNECTED); } else { logger.warn( REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "New session created after old session lost, " + "old session " + Long.toHexString(lastSessionId) + ", new session " + Long.toHexString(sessionId)); lastSessionId = sessionId; CuratorZookeeperClient.this.stateChanged(StateListener.NEW_SESSION_CREATED); } } } } /** * just for unit test * * @return */ CuratorFramework getClient() { return client; } }
7,623
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinderTest.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.tomcat; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.HttpServer; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import org.apache.http.client.fluent.Request; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; class TomcatHttpBinderTest { @Test void shouldAbleHandleRequestForTomcatBinder() throws Exception { int port = NetUtils.getAvailablePort(); URL url = new ServiceConfigURL( "http", "localhost", port, new String[] {Constants.BIND_PORT_KEY, String.valueOf(port)}); HttpServer httpServer = new TomcatHttpBinder() .bind(url, new HttpHandler<HttpServletRequest, HttpServletResponse>() { @Override public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { response.getWriter().write("Tomcat"); } }); String response = Request.Get(url.toJavaURL().toURI()).execute().returnContent().asString(); assertThat(response, is("Tomcat")); httpServer.close(); assertThat(NetUtils.isPortInUsed(port), is(false)); } }
7,624
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinderTest.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.jetty; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.HttpServer; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import org.apache.http.client.fluent.Request; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; class JettyHttpBinderTest { @Test void shouldAbleHandleRequestForJettyBinder() throws Exception { int port = NetUtils.getAvailablePort(); URL url = new ServiceConfigURL( "http", "localhost", port, new String[] {Constants.BIND_PORT_KEY, String.valueOf(port)}); HttpServer httpServer = new JettyHttpServer(url, new HttpHandler<HttpServletRequest, HttpServletResponse>() { @Override public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { response.getWriter().write("Jetty"); } }); String response = Request.Get(url.toJavaURL().toURI()).execute().returnContent().asString(); assertThat(response, is("Jetty")); httpServer.close(); } }
7,625
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyLoggerAdapterTest.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.jetty; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.support.FailsafeErrorTypeAwareLogger; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.HttpServer; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import org.apache.http.client.fluent.Request; import org.eclipse.jetty.util.log.Log; import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class JettyLoggerAdapterTest { @Test void testJettyUseDubboLogger() throws Exception { int port = NetUtils.getAvailablePort(); URL url = new ServiceConfigURL( "http", "localhost", port, new String[] {Constants.BIND_PORT_KEY, String.valueOf(port)}); HttpServer httpServer = new JettyHttpServer(url, new HttpHandler<HttpServletRequest, HttpServletResponse>() { @Override public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { response.getWriter().write("Jetty is using Dubbo's logger"); } }); Request.Get(url.toJavaURL().toURI()).execute().returnContent().asString(); assertThat(Log.getLog().getClass().isAssignableFrom(JettyLoggerAdapter.class), is(true)); httpServer.close(); } @Test void testSuccessLogger() throws Exception { Logger successLogger = mock(Logger.class); Class<?> clazz = Class.forName("org.apache.dubbo.remoting.http.jetty.JettyLoggerAdapter"); JettyLoggerAdapter jettyLoggerAdapter = (JettyLoggerAdapter) clazz.getDeclaredConstructor().newInstance(); Field loggerField = clazz.getDeclaredField("logger"); loggerField.setAccessible(true); loggerField.set(jettyLoggerAdapter, new FailsafeErrorTypeAwareLogger(successLogger)); jettyLoggerAdapter.setDebugEnabled(true); when(successLogger.isDebugEnabled()).thenReturn(true); when(successLogger.isWarnEnabled()).thenReturn(true); when(successLogger.isInfoEnabled()).thenReturn(true); jettyLoggerAdapter.warn("warn"); jettyLoggerAdapter.info("info"); jettyLoggerAdapter.debug("debug"); verify(successLogger).warn(anyString()); verify(successLogger).info(anyString()); verify(successLogger).debug(anyString()); jettyLoggerAdapter.warn(new Exception("warn")); jettyLoggerAdapter.info(new Exception("info")); jettyLoggerAdapter.debug(new Exception("debug")); jettyLoggerAdapter.ignore(new Exception("ignore")); jettyLoggerAdapter.warn("warn", new Exception("warn")); jettyLoggerAdapter.info("info", new Exception("info")); jettyLoggerAdapter.debug("debug", new Exception("debug")); } @Test void testNewLogger() { JettyLoggerAdapter loggerAdapter = new JettyLoggerAdapter(); org.eclipse.jetty.util.log.Logger logger = loggerAdapter.newLogger(this.getClass().getName()); assertThat(logger.getClass().isAssignableFrom(JettyLoggerAdapter.class), is(true)); } @Test void testDebugEnabled() { JettyLoggerAdapter loggerAdapter = new JettyLoggerAdapter(); loggerAdapter.setDebugEnabled(true); assertThat(loggerAdapter.isDebugEnabled(), is(true)); } @Test void testLoggerFormat() throws Exception { Class<?> clazz = Class.forName("org.apache.dubbo.remoting.http.jetty.JettyLoggerAdapter"); Object newInstance = clazz.getDeclaredConstructor().newInstance(); Method method = clazz.getDeclaredMethod("format", String.class, Object[].class); method.setAccessible(true); String print = (String) method.invoke(newInstance, "Hello,{}! I'am {}", new String[] {"World", "Jetty"}); assertThat(print, is("Hello,World! I'am Jetty")); } }
7,626
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/rest/RestClientTest.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.rest; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.http.*; import org.apache.dubbo.remoting.http.config.HttpClientConfig; import org.apache.dubbo.remoting.http.jetty.JettyHttpServer; import org.apache.dubbo.remoting.http.restclient.HttpClientRestClient; import org.apache.dubbo.remoting.http.restclient.OKHttpRestClient; import org.apache.dubbo.remoting.http.restclient.URLConnectionRestClient; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; public class RestClientTest { @Test public void testRestClient() throws Exception { int port = NetUtils.getAvailablePort(); URL url = new ServiceConfigURL( "http", "localhost", port, new String[] {Constants.BIND_PORT_KEY, String.valueOf(port)}); HttpServer httpServer = new JettyHttpServer(url, new HttpHandler<HttpServletRequest, HttpServletResponse>() { @Override public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { response.getWriter().write("Jetty"); } }); RequestTemplate requestTemplate = new RequestTemplate(null, "POST", "localhost:" + port); requestTemplate.addParam("p1", "value1"); requestTemplate.addParam("p2", "value2"); requestTemplate.addParams("p3", Arrays.asList("value3", "value3.1")); requestTemplate.addHeader("test", "dubbo"); requestTemplate.addKeepAliveHeader(60); requestTemplate.addHeaders("header", Arrays.asList("h1", "h2")); requestTemplate.path("/test"); requestTemplate.serializeBody("test".getBytes(StandardCharsets.UTF_8)); RestClient restClient = new OKHttpRestClient(new HttpClientConfig()); CompletableFuture<RestResult> send = restClient.send(requestTemplate); RestResult restResult = send.get(); assertThat(new String(restResult.getBody()), is("Jetty")); restClient = new HttpClientRestClient(new HttpClientConfig()); send = restClient.send(requestTemplate); restResult = send.get(); assertThat(new String(restResult.getBody()), is("Jetty")); restClient = new URLConnectionRestClient(new HttpClientConfig()); send = restClient.send(requestTemplate); restResult = send.get(); assertThat(new String(restResult.getBody()), is("Jetty")); httpServer.close(); } @Test public void testError() throws Exception { int port = NetUtils.getAvailablePort(); URL url = new ServiceConfigURL( "http", "localhost", port, new String[] {Constants.BIND_PORT_KEY, String.valueOf(port)}); HttpServer httpServer = new JettyHttpServer(url, new HttpHandler<HttpServletRequest, HttpServletResponse>() { @Override public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setStatus(500); response.getWriter().write("server error"); response.addHeader("Content-Type", "text/html"); } }); RequestTemplate requestTemplate = new RequestTemplate(null, null, null); requestTemplate.httpMethod("POST"); requestTemplate.setAddress("localhost:" + port); requestTemplate.setProtocol("http://"); requestTemplate.addHeader("test", "dubbo"); requestTemplate.path("/test"); requestTemplate.serializeBody("test".getBytes(StandardCharsets.UTF_8)); RestClient restClient = new OKHttpRestClient(new HttpClientConfig()); CompletableFuture<RestResult> send = restClient.send(requestTemplate); String error = "Server Error\n" + " error info is: server error"; RestResult restResult = send.get(); String contentType = "text/html;charset=iso-8859-1"; Assertions.assertEquals(500, restResult.getResponseCode()); Assertions.assertEquals(error, restResult.getMessage()); Assertions.assertEquals(contentType, restResult.getContentType()); Map<String, List<String>> headers = restResult.headers(); restClient.close(); restClient = new HttpClientRestClient(new HttpClientConfig()); send = restClient.send(requestTemplate); restResult = send.get(); Assertions.assertEquals(500, restResult.getResponseCode()); Assertions.assertEquals(error, restResult.getMessage()); Assertions.assertEquals(contentType, restResult.getContentType()); restClient.close(); restClient = new URLConnectionRestClient(new HttpClientConfig()); send = restClient.send(requestTemplate); restResult = send.get(); Assertions.assertEquals(500, restResult.getResponseCode()); Assertions.assertEquals(error, restResult.getMessage()); Assertions.assertEquals(contentType, restResult.getContentType()); restClient.close(); httpServer.close(); } @Test public void testMethod() { RequestTemplate requestTemplate = new RequestTemplate(null, null, null); requestTemplate.body(new Object(), Object.class); Assertions.assertEquals(requestTemplate.getBodyType(), Object.class); requestTemplate.addHeader("Content-Length", 1); Integer contentLength = requestTemplate.getContentLength(); Assertions.assertEquals(1, contentLength); List<String> strings = Arrays.asList("h1", "h2"); requestTemplate.addHeaders("header", strings); Assertions.assertArrayEquals( strings.toArray(new String[0]), requestTemplate.getHeaders("header").toArray(new String[0])); strings = Arrays.asList("p1", "p2"); requestTemplate.addParams("param", strings); Assertions.assertArrayEquals( strings.toArray(new String[0]), requestTemplate.getParam("param").toArray(new String[0])); } }
7,627
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpHandler.java
/* * 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 * * 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 org.apache.dubbo.remoting.http; import java.io.IOException; /** * http invocation handler. */ public interface HttpHandler<REQUEST, RESPONSE> { /** * invoke. * * @param request request. * @param response response. * @throws IOException */ void handle(REQUEST request, RESPONSE response) throws IOException; }
7,628
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/RestResult.java
/* * 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 * * 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 org.apache.dubbo.remoting.http; import java.io.IOException; import java.util.List; import java.util.Map; /** * rest response facade */ public interface RestResult { String getContentType(); byte[] getBody() throws IOException; Map<String, List<String>> headers(); byte[] getErrorResponse() throws IOException; int getResponseCode() throws IOException; String getMessage() throws IOException; default String appendErrorMessage(String message, String errorInfo) { return message + "\n error info is: " + errorInfo; } }
7,629
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpServer.java
/* * 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 * * 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 org.apache.dubbo.remoting.http; import org.apache.dubbo.common.Resetable; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.RemotingServer; import java.net.InetSocketAddress; public interface HttpServer extends Resetable, RemotingServer { /** * get http handler. * * @return http handler. */ HttpHandler getHttpHandler(); /** * get url. * * @return url */ URL getUrl(); /** * get local address. * * @return local address. */ InetSocketAddress getLocalAddress(); /** * close the channel. */ void close(); /** * Graceful close the channel. */ void close(int timeout); /** * is bound. * * @return bound */ boolean isBound(); /** * is closed. * * @return closed */ boolean isClosed(); }
7,630
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/RequestTemplate.java
/* * 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 * * 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 org.apache.dubbo.remoting.http; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Invocation; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class RequestTemplate implements Serializable { private static final long serialVersionUID = 1L; public static final String CONTENT_ENCODING = "Content-Encoding"; private static final String CONTENT_LENGTH = "Content-Length"; public static final String ENCODING_GZIP = "gzip"; public static final String ENCODING_DEFLATE = "deflate"; private static final List<String> EMPTY_ARRAYLIST = new ArrayList<>(); private final Map<String, Collection<String>> queries = new LinkedHashMap<String, Collection<String>>(); private final Map<String, Collection<String>> headers = new LinkedHashMap<String, Collection<String>>(); private String httpMethod; private String path; private String address; private Object body; private byte[] byteBody = new byte[0]; private String protocol = "http://"; private final Invocation invocation; private String contextPath = ""; private Class<?> bodyType; public RequestTemplate(Invocation invocation, String httpMethod, String address) { this(invocation, httpMethod, address, ""); } public RequestTemplate(Invocation invocation, String httpMethod, String address, String contextPath) { this.httpMethod = httpMethod; this.address = address; this.invocation = invocation; this.contextPath = contextPath; } public String getURL() { StringBuilder stringBuilder = new StringBuilder(getProtocol() + address); stringBuilder.append(getUri()); return stringBuilder.toString(); } public String getUri() { StringBuilder stringBuilder = new StringBuilder(getContextPath() + path); return stringBuilder.append(getQueryString()).toString(); } public String getQueryString() { if (queries.isEmpty()) { return ""; } StringBuilder queryBuilder = new StringBuilder("?"); for (String field : queries.keySet()) { Collection<String> queryValues = queries.get(field); if (queryValues == null || queryValues.isEmpty()) { continue; } for (String value : queryValues) { queryBuilder.append('&'); queryBuilder.append(field); if (value == null) { continue; } queryBuilder.append('='); queryBuilder.append(value); } } return queryBuilder.toString().replace("?&", "?"); } public RequestTemplate path(String path) { this.path = path; return this; } public String getHttpMethod() { return httpMethod; } public RequestTemplate httpMethod(String httpMethod) { this.httpMethod = httpMethod; return this; } public byte[] getSerializedBody() { return byteBody; } public void serializeBody(byte[] body) { addHeader(CONTENT_LENGTH, body.length); // must header this.byteBody = body; } public boolean isBodyEmpty() { return getUnSerializedBody() == null; } public RequestTemplate body(Object body, Class bodyType) { this.body = body; setBodyType(bodyType); return this; } public Object getUnSerializedBody() { return body; } public Map<String, Collection<String>> getAllHeaders() { return headers; } public Collection<String> getHeaders(String name) { return headers.get(name); } public String getHeader(String name) { if (headers.containsKey(name)) { Collection<String> headers = getHeaders(name); if (headers.isEmpty()) { return null; } String[] strings = headers.toArray(new String[0]); return strings[0]; } else { return null; } } public Collection<String> getEncodingValues() { if (headers.containsKey(CONTENT_ENCODING)) { return headers.get(CONTENT_ENCODING); } return EMPTY_ARRAYLIST; } public boolean isGzipEncodedRequest() { return getEncodingValues().contains(ENCODING_GZIP); } public boolean isDeflateEncodedRequest() { return getEncodingValues().contains(ENCODING_DEFLATE); } public void addHeader(String key, String value) { addValueByKey(key, value, this.headers); } public void addHeader(String key, Object value) { addValueByKey(key, String.valueOf(value), this.headers); } public void addKeepAliveHeader(int time) { addHeader(Constants.KEEP_ALIVE_HEADER, time); addHeader(Constants.CONNECTION, Constants.KEEP_ALIVE); } public void addHeaders(String key, Collection<String> values) { Collection<String> header = getHeaders(key); if (header == null) { header = new HashSet<>(); this.headers.put(key, header); } header.addAll(values); } public void addParam(String key, String value) { addValueByKey(key, value, this.queries); } public void addParam(String key, Object value) { addParam(key, String.valueOf(value)); } public Map<String, Collection<String>> getQueries() { return queries; } public Collection<String> getParam(String key) { return getQueries().get(key); } public void addParams(String key, Collection<String> values) { Collection<String> params = getParam(key); if (params == null) { params = new HashSet<>(); this.queries.put(key, params); } params.addAll(values); } public void addValueByKey(String key, String value, Map<String, Collection<String>> maps) { if (value == null) { return; } Collection<String> values = null; if (!maps.containsKey(key)) { values = new HashSet<>(); maps.put(key, values); } values = maps.get(key); values.add(value); } public Integer getContentLength() { if (!getAllHeaders().containsKey(CONTENT_LENGTH)) { return null; } HashSet<String> strings = (HashSet<String>) getAllHeaders().get(CONTENT_LENGTH); return Integer.parseInt(new ArrayList<>(strings).get(0)); } public String getAddress() { return address; } public void setAddress(String address) { addHeader("Host", address); // must header this.address = address; } public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public Invocation getInvocation() { return invocation; } public String getContextPath() { if (contextPath == null || contextPath.length() == 0) { return ""; } if (contextPath.startsWith("/")) { return contextPath; } else { return "/" + contextPath; } } public void setContextPath(String contextPath) { this.contextPath = contextPath; } public Class<?> getBodyType() { return bodyType; } public void setBodyType(Class<?> bodyType) { this.bodyType = bodyType; } }
7,631
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/BaseRestClient.java
/* * 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 * * 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 org.apache.dubbo.remoting.http; import org.apache.dubbo.remoting.http.config.HttpClientConfig; public abstract class BaseRestClient<CLIENT> implements RestClient { protected CLIENT client; protected HttpClientConfig clientConfig; public BaseRestClient(HttpClientConfig clientConfig) { this.clientConfig = clientConfig; client = createHttpClient(clientConfig); } protected abstract CLIENT createHttpClient(HttpClientConfig clientConfig); public HttpClientConfig getClientConfig() { return clientConfig; } public CLIENT getClient() { return client; } }
7,632
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpBinder.java
/* * 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 * * 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 org.apache.dubbo.remoting.http; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.remoting.Constants; /** * HttpBinder */ @SPI(value = "jetty", scope = ExtensionScope.FRAMEWORK) public interface HttpBinder { /** * bind the server. * * @param url server url. * @return server. */ @Adaptive({Constants.SERVER_KEY}) HttpServer bind(URL url, HttpHandler handler); }
7,633
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/RestClient.java
/* * 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 * * 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 org.apache.dubbo.remoting.http; import org.apache.dubbo.remoting.RemotingException; import java.util.concurrent.CompletableFuture; public interface RestClient { /** * send message. * * @param message * @throws RemotingException */ CompletableFuture<RestResult> send(RequestTemplate message); /** * close the channel. */ void close(); /** * Graceful close the channel. */ void close(int timeout); /** * is closed. * * @return closed */ boolean isClosed(); }
7,634
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletManager.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.servlet; import javax.servlet.ServletContext; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * TODO this may not be a pretty elegant solution, */ public class ServletManager { public static final int EXTERNAL_SERVER_PORT = -1234; private static final ServletManager INSTANCE = new ServletManager(); private final Map<Integer, ServletContext> contextMap = new ConcurrentHashMap<Integer, ServletContext>(); public static ServletManager getInstance() { return INSTANCE; } public void addServletContext(int port, ServletContext servletContext) { contextMap.put(port, servletContext); } public void removeServletContext(int port) { contextMap.remove(port); } public ServletContext getServletContext(int port) { return contextMap.get(port); } }
7,635
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/BootstrapListener.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.servlet; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * This class must be defined before something like spring's ContextLoaderListener in web.xml */ public class BootstrapListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { ServletManager.getInstance() .addServletContext(ServletManager.EXTERNAL_SERVER_PORT, servletContextEvent.getServletContext()); } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { ServletManager.getInstance().removeServletContext(ServletManager.EXTERNAL_SERVER_PORT); } }
7,636
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpBinder.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.servlet; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.http.HttpBinder; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.HttpServer; /** * ServletHttpTransporter */ public class ServletHttpBinder implements HttpBinder { @Override public HttpServer bind(URL url, HttpHandler handler) { return new ServletHttpServer(url, handler); } }
7,637
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpServer.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.servlet; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.support.AbstractHttpServer; public class ServletHttpServer extends AbstractHttpServer { public ServletHttpServer(URL url, HttpHandler handler) { super(url, handler); DispatcherServlet.addHttpHandler(url.getParameter(Constants.BIND_PORT_KEY, 8080), handler); } }
7,638
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/DispatcherServlet.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.servlet; import org.apache.dubbo.remoting.http.HttpHandler; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Service dispatcher Servlet. */ public class DispatcherServlet extends HttpServlet { private static final long serialVersionUID = 5766349180380479888L; private static final Map<Integer, HttpHandler> HANDLERS = new ConcurrentHashMap<Integer, HttpHandler>(); private static DispatcherServlet INSTANCE; public DispatcherServlet() { DispatcherServlet.INSTANCE = this; } public static void addHttpHandler(int port, HttpHandler processor) { HANDLERS.put(port, processor); } public static void removeHttpHandler(int port) { HANDLERS.remove(port); } public static DispatcherServlet getInstance() { return INSTANCE; } @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpHandler handler = HANDLERS.get(request.getLocalPort()); if (handler == null) { // service not found. response.sendError(HttpServletResponse.SC_NOT_FOUND, "Service not found."); } else { handler.handle(request, response); } } }
7,639
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.tomcat; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.servlet.DispatcherServlet; import org.apache.dubbo.remoting.http.servlet.ServletManager; import org.apache.dubbo.remoting.http.support.AbstractHttpServer; import java.io.File; import org.apache.catalina.Context; import org.apache.catalina.LifecycleException; import org.apache.catalina.connector.Connector; import org.apache.catalina.startup.Tomcat; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_STOP_HTTP_SERVER; import static org.apache.dubbo.remoting.Constants.ACCEPTS_KEY; public class TomcatHttpServer extends AbstractHttpServer { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(TomcatHttpServer.class); private final Tomcat tomcat; private final URL url; public TomcatHttpServer(URL url, final HttpHandler handler) { super(url, handler); this.url = url; DispatcherServlet.addHttpHandler(url.getPort(), handler); String baseDir = new File(System.getProperty("java.io.tmpdir")).getAbsolutePath(); tomcat = new Tomcat(); Connector connector = tomcat.getConnector(); connector.setPort(url.getPort()); connector.setProperty("maxThreads", String.valueOf(url.getParameter(THREADS_KEY, DEFAULT_THREADS))); connector.setProperty("maxConnections", String.valueOf(url.getParameter(ACCEPTS_KEY, -1))); connector.setProperty("URIEncoding", "UTF-8"); connector.setProperty("connectionTimeout", "60000"); connector.setProperty("maxKeepAliveRequests", "-1"); tomcat.setBaseDir(baseDir); tomcat.setPort(url.getPort()); Context context = tomcat.addContext("/", baseDir); Tomcat.addServlet(context, "dispatcher", new DispatcherServlet()); // Issue : https://github.com/apache/dubbo/issues/6418 // addServletMapping method will be removed since Tomcat 9 // context.addServletMapping("/*", "dispatcher"); context.addServletMappingDecoded("/*", "dispatcher"); ServletManager.getInstance().addServletContext(url.getPort(), context.getServletContext()); // tell tomcat to fail on startup failures. System.setProperty("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE", "true"); try { tomcat.start(); } catch (LifecycleException e) { throw new IllegalStateException("Failed to start tomcat server at " + url.getAddress(), e); } } @Override public void close() { super.close(); ServletManager.getInstance().removeServletContext(url.getPort()); try { tomcat.stop(); // close port by destroy() tomcat.destroy(); } catch (Exception e) { logger.warn(COMMON_FAILED_STOP_HTTP_SERVER, "", "", e.getMessage(), e); } } }
7,640
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinder.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.tomcat; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.http.HttpBinder; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.HttpServer; public class TomcatHttpBinder implements HttpBinder { @Override public HttpServer bind(URL url, HttpHandler handler) { return new TomcatHttpServer(url, handler); } }
7,641
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/config/HttpClientConfig.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.config; public class HttpClientConfig { private int readTimeout = 6 * 1000; private int writeTimeout = 6 * 1000; private int connectTimeout = 6 * 1000; private int chunkLength = 8196; private int HTTP_CLIENT_CONNECTION_MANAGER_MAX_PER_ROUTE = 20; private int HTTP_CLIENT_CONNECTION_MANAGER_MAX_TOTAL = 20; private int HTTPCLIENT_KEEP_ALIVE_DURATION = 30 * 1000; private int HTTP_CLIENT_CONNECTION_MANAGER_CLOSE_WAIT_TIME_MS = 1000; private int HTTP_CLIENT_CONNECTION_MANAGER_CLOSE_IDLE_TIME_S = 30; public HttpClientConfig() {} public int getReadTimeout() { return readTimeout; } public void setReadTimeout(int readTimeout) { this.readTimeout = readTimeout; } public int getWriteTimeout() { return writeTimeout; } public void setWriteTimeout(int writeTimeout) { this.writeTimeout = writeTimeout; } public int getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } public int getChunkLength() { return chunkLength; } }
7,642
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinder.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.jetty; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.http.HttpBinder; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.HttpServer; /** * JettyHttpTransporter */ public class JettyHttpBinder implements HttpBinder { @Override public HttpServer bind(URL url, HttpHandler handler) { return new JettyHttpServer(url, handler); } }
7,643
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.jetty; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.servlet.DispatcherServlet; import org.apache.dubbo.remoting.http.servlet.ServletManager; import org.apache.dubbo.remoting.http.support.AbstractHttpServer; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.util.thread.QueuedThreadPool; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_STOP_HTTP_SERVER; public class JettyHttpServer extends AbstractHttpServer { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(JettyHttpServer.class); private Server server; private URL url; public JettyHttpServer(URL url, final HttpHandler handler) { super(url, handler); this.url = url; // set dubbo's logger System.setProperty("org.eclipse.jetty.util.log.class", JettyLoggerAdapter.class.getName()); DispatcherServlet.addHttpHandler(url.getParameter(Constants.BIND_PORT_KEY, url.getPort()), handler); int threads = url.getParameter(THREADS_KEY, DEFAULT_THREADS); QueuedThreadPool threadPool = new QueuedThreadPool(); threadPool.setDaemon(true); threadPool.setMaxThreads(threads); threadPool.setMinThreads(threads); server = new Server(threadPool); ServerConnector connector = new ServerConnector(server); String bindIp = url.getParameter(Constants.BIND_IP_KEY, url.getHost()); if (!url.isAnyHost() && NetUtils.isValidLocalHost(bindIp)) { connector.setHost(bindIp); } connector.setPort(url.getParameter(Constants.BIND_PORT_KEY, url.getPort())); server.addConnector(connector); ServletHandler servletHandler = new ServletHandler(); ServletHolder servletHolder = servletHandler.addServletWithMapping(DispatcherServlet.class, "/*"); servletHolder.setInitOrder(2); // dubbo's original impl can't support the use of ServletContext // server.addHandler(servletHandler); // TODO Context.SESSIONS is the best option here? (In jetty 9.x, it becomes ServletContextHandler.SESSIONS) ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS); context.setServletHandler(servletHandler); ServletManager.getInstance() .addServletContext( url.getParameter(Constants.BIND_PORT_KEY, url.getPort()), context.getServletContext()); try { server.start(); } catch (Exception e) { throw new IllegalStateException( "Failed to start jetty server on " + url.getParameter(Constants.BIND_IP_KEY) + ":" + url.getParameter(Constants.BIND_PORT_KEY) + ", cause: " + e.getMessage(), e); } } @Override public void close() { super.close(); // ServletManager.getInstance().removeServletContext(url.getParameter(Constants.BIND_PORT_KEY, url.getPort())); if (server != null) { try { server.stop(); } catch (Exception e) { logger.warn(COMMON_FAILED_STOP_HTTP_SERVER, "", "", e.getMessage(), e); } } } }
7,644
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyLoggerAdapter.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.jetty; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.eclipse.jetty.util.log.AbstractLogger; import org.eclipse.jetty.util.log.Logger; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION; /** * logger adapter for jetty */ public class JettyLoggerAdapter extends AbstractLogger { protected String name; private final ErrorTypeAwareLogger logger; private static boolean debugEnabled = false; public JettyLoggerAdapter() { this("org.apache.dubbo.remoting.http.jetty"); } public JettyLoggerAdapter(Class<?> clazz) { this(clazz.getName()); } public JettyLoggerAdapter(String name) { this.name = name; this.logger = LoggerFactory.getErrorTypeAwareLogger(name); } @Override protected Logger newLogger(String name) { return new JettyLoggerAdapter(name); } @Override public String getName() { return this.name; } @Override public void warn(String msg, Object... objects) { if (logger.isWarnEnabled()) { logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", this.format(msg, objects)); } } @Override public void warn(Throwable throwable) { if (logger.isWarnEnabled()) { logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", throwable.getMessage(), throwable); } } @Override public void warn(String msg, Throwable throwable) { if (logger.isWarnEnabled()) { logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", msg, throwable); } } @Override public void info(String msg, Object... objects) { if (logger.isInfoEnabled()) { logger.info(this.format(msg, objects)); } } @Override public void info(Throwable throwable) { if (logger.isInfoEnabled()) { logger.info(throwable); } } @Override public void info(String msg, Throwable throwable) { if (logger.isInfoEnabled()) { logger.info(msg, throwable); } } @Override public boolean isDebugEnabled() { return debugEnabled; } @Override public void setDebugEnabled(boolean enabled) { debugEnabled = enabled; } @Override public void debug(String msg, Object... objects) { if (debugEnabled && logger.isDebugEnabled()) { logger.debug(this.format(msg, objects)); } } @Override public void debug(Throwable throwable) { if (debugEnabled && logger.isDebugEnabled()) { logger.debug(throwable); } } @Override public void debug(String msg, Throwable throwable) { if (debugEnabled && logger.isDebugEnabled()) { logger.debug(msg, throwable); } } @Override public void ignore(Throwable throwable) { if (logger.isWarnEnabled()) { logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "IGNORED EXCEPTION ", throwable); } } private String format(String msg, Object... args) { msg = String.valueOf(msg); // Avoids NPE String braces = "{}"; StringBuilder builder = new StringBuilder(); int start = 0; for (Object arg : args) { int bracesIndex = msg.indexOf(braces, start); if (bracesIndex < 0) { builder.append(msg.substring(start)); builder.append(' '); builder.append(arg); start = msg.length(); } else { builder.append(msg, start, bracesIndex); builder.append(arg); start = bracesIndex + braces.length(); } } builder.append(msg.substring(start)); return builder.toString(); } }
7,645
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/support/AbstractHttpServer.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.support; import org.apache.dubbo.common.Parameters; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.http.HttpHandler; import org.apache.dubbo.remoting.http.HttpServer; import java.net.InetSocketAddress; import java.util.Collection; /** * AbstractHttpServer */ public abstract class AbstractHttpServer implements HttpServer { private final URL url; private final HttpHandler handler; private volatile boolean closed; public AbstractHttpServer(URL url, HttpHandler handler) { if (url == null) { throw new IllegalArgumentException("url == null"); } if (handler == null) { throw new IllegalArgumentException("handler == null"); } this.url = url; this.handler = handler; } @Override public HttpHandler getHttpHandler() { return handler; } @Override public URL getUrl() { return url; } @Override public void reset(URL url) {} @Override public boolean isBound() { return true; } @Override public InetSocketAddress getLocalAddress() { return url.toInetSocketAddress(); } @Override public void close() { closed = true; } @Override public void close(int timeout) { close(); } @Override public boolean isClosed() { return closed; } /** * Following methods are extended from RemotingServer, useless for http servers */ @Override public boolean canHandleIdle() { return false; } @Override public Collection<Channel> getChannels() { return null; } @Override public Channel getChannel(InetSocketAddress remoteAddress) { return null; } @Override public void reset(Parameters parameters) {} @Override public ChannelHandler getChannelHandler() { return null; } @Override public void send(Object message) throws RemotingException {} @Override public void send(Object message, boolean sent) throws RemotingException {} @Override public void startClose() {} }
7,646
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/URLConnectionRestClient.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.restclient; import org.apache.dubbo.remoting.http.RequestTemplate; import org.apache.dubbo.remoting.http.RestClient; import org.apache.dubbo.remoting.http.RestResult; import org.apache.dubbo.remoting.http.config.HttpClientConfig; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.zip.DeflaterOutputStream; import java.util.zip.GZIPOutputStream; import org.apache.commons.io.IOUtils; public class URLConnectionRestClient implements RestClient { private final HttpClientConfig clientConfig; public URLConnectionRestClient(HttpClientConfig clientConfig) { this.clientConfig = clientConfig; } @Override public CompletableFuture<RestResult> send(RequestTemplate requestTemplate) { CompletableFuture<RestResult> future = new CompletableFuture<>(); try { HttpURLConnection connection = (HttpURLConnection) new URL(requestTemplate.getURL()).openConnection(); connection.setConnectTimeout(clientConfig.getConnectTimeout()); connection.setReadTimeout(clientConfig.getReadTimeout()); connection.setRequestMethod(requestTemplate.getHttpMethod()); prepareConnection(connection, requestTemplate.getHttpMethod()); // writeHeaders for (String field : requestTemplate.getAllHeaders().keySet()) { for (String value : requestTemplate.getHeaders(field)) { connection.addRequestProperty(field, value); } } // writeBody boolean gzipEncodedRequest = requestTemplate.isGzipEncodedRequest(); boolean deflateEncodedRequest = requestTemplate.isDeflateEncodedRequest(); if (requestTemplate.isBodyEmpty()) { future.complete(getRestResultFromConnection(connection)); return future; } Integer contentLength = requestTemplate.getContentLength(); if (contentLength != null) { connection.setFixedLengthStreamingMode(contentLength); } else { connection.setChunkedStreamingMode(clientConfig.getChunkLength()); } OutputStream out = connection.getOutputStream(); if (gzipEncodedRequest) { out = new GZIPOutputStream(out); } else if (deflateEncodedRequest) { out = new DeflaterOutputStream(out); } try { out.write(requestTemplate.getSerializedBody()); } finally { try { out.close(); } catch (IOException suppressed) { } } future.complete(getRestResultFromConnection(connection)); } catch (Exception e) { future.completeExceptionally(e); } return future; } @Override public void close() {} @Override public void close(int timeout) {} @Override public boolean isClosed() { return true; } private RestResult getRestResultFromConnection(HttpURLConnection connection) { return new RestResult() { @Override public String getContentType() { return connection.getContentType(); } @Override public byte[] getBody() throws IOException { return IOUtils.toByteArray(connection.getInputStream()); } @Override public Map<String, List<String>> headers() { return connection.getHeaderFields(); } @Override public byte[] getErrorResponse() throws IOException { return IOUtils.toByteArray(connection.getErrorStream()); } @Override public int getResponseCode() throws IOException { return connection.getResponseCode(); } @Override public String getMessage() throws IOException { return appendErrorMessage(connection.getResponseMessage(), new String(getErrorResponse())); } }; } private void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { connection.setDoInput(true); if ("GET".equals(httpMethod)) { connection.setInstanceFollowRedirects(true); } else { connection.setInstanceFollowRedirects(false); } if ("POST".equals(httpMethod) || "PUT".equals(httpMethod) || "PATCH".equals(httpMethod) || "DELETE".equals(httpMethod)) { connection.setDoOutput(true); } else { connection.setDoOutput(false); } connection.setRequestMethod(httpMethod); } }
7,647
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/HttpClientRestClient.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.restclient; import org.apache.dubbo.remoting.http.RequestTemplate; import org.apache.dubbo.remoting.http.RestClient; import org.apache.dubbo.remoting.http.RestResult; import org.apache.dubbo.remoting.http.config.HttpClientConfig; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import org.apache.commons.io.IOUtils; import org.apache.http.Header; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.apache.http.client.methods.HttpOptions; import org.apache.http.client.methods.HttpPatch; 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.client.methods.HttpTrace; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; public class HttpClientRestClient implements RestClient { private final CloseableHttpClient closeableHttpClient; private final HttpClientConfig httpClientConfig; public HttpClientRestClient(HttpClientConfig clientConfig) { closeableHttpClient = createHttpClient(); httpClientConfig = clientConfig; } @Override public CompletableFuture<RestResult> send(RequestTemplate requestTemplate) { HttpRequestBase httpRequest = null; String httpMethod = requestTemplate.getHttpMethod(); httpRequest = createHttpUriRequest(httpMethod, requestTemplate); if (httpRequest instanceof HttpEntityEnclosingRequest) { ((HttpEntityEnclosingRequestBase) httpRequest) .setEntity(new ByteArrayEntity(requestTemplate.getSerializedBody())); } Map<String, Collection<String>> allHeaders = requestTemplate.getAllHeaders(); allHeaders.remove("Content-Length"); // header for (String headerName : allHeaders.keySet()) { Collection<String> headerValues = allHeaders.get(headerName); for (String headerValue : headerValues) { httpRequest.addHeader(headerName, headerValue); } } httpRequest.setConfig(getRequestConfig(httpClientConfig)); CompletableFuture<RestResult> future = new CompletableFuture<>(); try { CloseableHttpResponse response = closeableHttpClient.execute(httpRequest); future.complete(new RestResult() { @Override public String getContentType() { Header header = response.getFirstHeader("Content-Type"); return header == null ? null : header.getValue(); } @Override public byte[] getBody() throws IOException { if (response.getEntity() == null) { return new byte[0]; } return IOUtils.toByteArray(response.getEntity().getContent()); } @Override public Map<String, List<String>> headers() { return Arrays.stream(response.getAllHeaders()) .collect(Collectors.toMap(Header::getName, h -> Collections.singletonList(h.getValue()))); } @Override public byte[] getErrorResponse() throws IOException { return getBody(); } @Override public int getResponseCode() { return response.getStatusLine().getStatusCode(); } @Override public String getMessage() throws IOException { return appendErrorMessage( response.getStatusLine().getReasonPhrase(), new String(getErrorResponse())); } }); } catch (IOException e) { future.completeExceptionally(e); } return future; } private RequestConfig getRequestConfig(HttpClientConfig clientConfig) { // TODO config return RequestConfig.custom().build(); } @Override public void close() { try { closeableHttpClient.close(); } catch (IOException e) { } } @Override public void close(int timeout) {} @Override public boolean isClosed() { // TODO close judge return true; } public CloseableHttpClient createHttpClient() { PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); return HttpClients.custom().setConnectionManager(connectionManager).build(); } protected HttpRequestBase createHttpUriRequest(String httpMethod, RequestTemplate requestTemplate) { String uri = requestTemplate.getURL(); HttpRequestBase httpUriRequest = null; if (HttpGet.METHOD_NAME.equals(httpMethod)) { httpUriRequest = new HttpGet(uri); } else if (HttpHead.METHOD_NAME.equals(httpMethod)) { httpUriRequest = new HttpHead(uri); } else if (HttpPost.METHOD_NAME.equals(httpMethod)) { httpUriRequest = new HttpPost(uri); } else if (HttpPut.METHOD_NAME.equals(httpMethod)) { httpUriRequest = new HttpPut(uri); } else if (HttpPatch.METHOD_NAME.equals(httpMethod)) { httpUriRequest = new HttpPatch(uri); } else if (HttpDelete.METHOD_NAME.equals(httpMethod)) { httpUriRequest = new HttpDelete(uri); } else if (HttpOptions.METHOD_NAME.equals(httpMethod)) { httpUriRequest = new HttpOptions(uri); } else if (HttpTrace.METHOD_NAME.equals(httpMethod)) { httpUriRequest = new HttpTrace(uri); } else { throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod); } return httpUriRequest; } }
7,648
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/restclient/OKHttpRestClient.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.restclient; import org.apache.dubbo.remoting.http.RequestTemplate; import org.apache.dubbo.remoting.http.RestClient; import org.apache.dubbo.remoting.http.RestResult; import org.apache.dubbo.remoting.http.config.HttpClientConfig; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; import okhttp3.internal.http.HttpMethod; // TODO add version 4.0 implements ,and default version is < 4.0,for dependency conflict public class OKHttpRestClient implements RestClient { private final OkHttpClient okHttpClient; private final HttpClientConfig httpClientConfig; public OKHttpRestClient(HttpClientConfig clientConfig) { this.okHttpClient = createHttpClient(clientConfig); this.httpClientConfig = clientConfig; } @Override public CompletableFuture<RestResult> send(RequestTemplate requestTemplate) { Request.Builder builder = new Request.Builder(); // url builder.url(requestTemplate.getURL()); Map<String, Collection<String>> allHeaders = requestTemplate.getAllHeaders(); boolean hasBody = false; RequestBody requestBody = null; // GET & HEAD body is forbidden if (HttpMethod.permitsRequestBody(requestTemplate.getHttpMethod())) { requestBody = RequestBody.create(null, requestTemplate.getSerializedBody()); hasBody = true; } // header for (String headerName : allHeaders.keySet()) { Collection<String> headerValues = allHeaders.get(headerName); if (!hasBody && "Content-Length".equals(headerName)) { continue; } for (String headerValue : headerValues) { builder.addHeader(headerName, headerValue); } } builder.method(requestTemplate.getHttpMethod(), requestBody); CompletableFuture<RestResult> future = new CompletableFuture<>(); okHttpClient.newCall(builder.build()).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { future.completeExceptionally(e); } @Override public void onResponse(Call call, Response response) throws IOException { future.complete(new RestResult() { @Override public String getContentType() { return response.header("Content-Type"); } @Override public byte[] getBody() throws IOException { ResponseBody body = response.body(); return body == null ? null : body.bytes(); } @Override public Map<String, List<String>> headers() { return response.headers().toMultimap(); } @Override public byte[] getErrorResponse() throws IOException { return getBody(); } @Override public int getResponseCode() throws IOException { return response.code(); } @Override public String getMessage() throws IOException { return appendErrorMessage(response.message(), new String(getBody())); } }); } }); return future; } @Override public void close() { okHttpClient.connectionPool().evictAll(); } @Override public void close(int timeout) {} @Override public boolean isClosed() { return okHttpClient.retryOnConnectionFailure(); } public OkHttpClient createHttpClient(HttpClientConfig httpClientConfig) { OkHttpClient client = new OkHttpClient.Builder() .readTimeout(httpClientConfig.getReadTimeout(), TimeUnit.SECONDS) .writeTimeout(httpClientConfig.getWriteTimeout(), TimeUnit.SECONDS) .connectTimeout(httpClientConfig.getConnectTimeout(), TimeUnit.SECONDS) .build(); return client; } }
7,649
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/RestClientFactory.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.factory; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Adaptive; import org.apache.dubbo.common.extension.ExtensionScope; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.http.RestClient; import org.apache.dubbo.rpc.RpcException; /** * RestClientFactory. (API/SPI, Singleton, ThreadSafe) */ @SPI(value = Constants.OK_HTTP, scope = ExtensionScope.FRAMEWORK) public interface RestClientFactory { @Adaptive({Constants.CLIENT_KEY}) RestClient createRestClient(URL url) throws RpcException; }
7,650
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/AbstractHttpClientFactory.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.factory; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.http.RestClient; import org.apache.dubbo.remoting.http.config.HttpClientConfig; import org.apache.dubbo.rpc.RpcException; /** * AbstractHttpClientFactory */ public abstract class AbstractHttpClientFactory implements RestClientFactory { protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); // TODO load config protected HttpClientConfig httpClientConfig = new HttpClientConfig(); //////////////////////////////////////// implements start /////////////////////////////////////////////// @Override public RestClient createRestClient(URL url) throws RpcException { beforeCreated(url); // create a raw client RestClient restClient = doCreateRestClient(url); // postprocessor afterCreated(restClient); return restClient; } //////////////////////////////////////// implements end /////////////////////////////////////////////// //////////////////////////////////////// inner methods /////////////////////////////////////////////// protected void beforeCreated(URL url) {} protected abstract RestClient doCreateRestClient(URL url) throws RpcException; protected void afterCreated(RestClient client) {} //////////////////////////////////////// inner methods /////////////////////////////////////////////// }
7,651
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/OkHttpClientFactory.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.factory.impl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.http.RestClient; import org.apache.dubbo.remoting.http.factory.AbstractHttpClientFactory; import org.apache.dubbo.remoting.http.restclient.OKHttpRestClient; import org.apache.dubbo.rpc.RpcException; @Activate(Constants.OK_HTTP) public class OkHttpClientFactory extends AbstractHttpClientFactory { @Override protected RestClient doCreateRestClient(URL url) throws RpcException { return new OKHttpRestClient(httpClientConfig); } }
7,652
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/URLConnectionClientFactory.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.factory.impl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.http.RestClient; import org.apache.dubbo.remoting.http.factory.AbstractHttpClientFactory; import org.apache.dubbo.remoting.http.restclient.URLConnectionRestClient; import org.apache.dubbo.rpc.RpcException; @Activate(Constants.URL_CONNECTION) public class URLConnectionClientFactory extends AbstractHttpClientFactory { @Override protected RestClient doCreateRestClient(URL url) throws RpcException { return new URLConnectionRestClient(httpClientConfig); } }
7,653
0
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/factory/impl/ApacheHttpClientFactory.java
/* * 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 * * 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 org.apache.dubbo.remoting.http.factory.impl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.http.RestClient; import org.apache.dubbo.remoting.http.factory.AbstractHttpClientFactory; import org.apache.dubbo.remoting.http.restclient.HttpClientRestClient; import org.apache.dubbo.rpc.RpcException; @Activate(Constants.APACHE_HTTP_CLIENT) public class ApacheHttpClientFactory extends AbstractHttpClientFactory { @Override protected RestClient doCreateRestClient(URL url) throws RpcException { return new HttpClientRestClient(httpClientConfig); } }
7,654
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/test/java/org/apache/dubbo/spring/boot/actuate
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/test/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboEndpointTest.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.endpoint; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.spring.boot.util.DubboUtils; import java.util.Map; import org.junit.Assert; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.apache.dubbo.common.Version.getVersion; /** * {@link DubboMetadataEndpoint} Test * * @see DubboMetadataEndpoint * @since 2.7.0 */ @ExtendWith(SpringExtension.class) @SpringBootTest( classes = {DubboMetadataEndpoint.class}, properties = {"dubbo.application.name = dubbo-demo-application"}) @EnableAutoConfiguration class DubboEndpointTest { @Autowired private DubboMetadataEndpoint dubboEndpoint; @BeforeEach public void init() { DubboBootstrap.reset(); } @AfterEach public void destroy() { DubboBootstrap.reset(); } @Test void testInvoke() { Map<String, Object> metadata = dubboEndpoint.invoke(); Assert.assertNotNull(metadata.get("timestamp")); Map<String, String> versions = (Map<String, String>) metadata.get("versions"); Map<String, String> urls = (Map<String, String>) metadata.get("urls"); Assert.assertFalse(versions.isEmpty()); Assert.assertFalse(urls.isEmpty()); Assert.assertEquals(getVersion(DubboUtils.class, "1.0.0"), versions.get("dubbo-spring-boot")); Assert.assertEquals(getVersion(), versions.get("dubbo")); Assert.assertEquals("https://github.com/apache/dubbo", urls.get("dubbo")); Assert.assertEquals("[email protected]", urls.get("mailing-list")); Assert.assertEquals("https://github.com/apache/dubbo-spring-boot-project", urls.get("github")); Assert.assertEquals("https://github.com/apache/dubbo-spring-boot-project/issues", urls.get("issues")); Assert.assertEquals("https://github.com/apache/dubbo-spring-boot-project.git", urls.get("git")); } }
7,655
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/test/java/org/apache/dubbo/spring/boot/actuate
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/test/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAnnotationAutoConfigurationTest.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.autoconfigure; import org.apache.dubbo.common.BaseServiceMetadata; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.spring.boot.actuate.endpoint.DubboConfigsMetadataEndpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.DubboMetadataEndpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.DubboPropertiesMetadataEndpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.DubboReferencesMetadataEndpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.DubboServicesMetadataEndpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.DubboShutdownEndpoint; import java.util.Map; import java.util.SortedMap; import java.util.function.Supplier; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Assert; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.web.client.RestTemplate; /** * {@link DubboEndpointAnnotationAutoConfiguration} Test * * @since 2.7.0 */ @ExtendWith(SpringExtension.class) @SpringBootTest( classes = { DubboEndpointAnnotationAutoConfigurationTest.class, DubboEndpointAnnotationAutoConfigurationTest.ConsumerConfiguration.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { "dubbo.service.version = 1.0.0", "dubbo.application.id = my-application", "dubbo.application.name = dubbo-demo-application", "dubbo.module.id = my-module", "dubbo.module.name = dubbo-demo-module", "dubbo.registry.id = my-registry", "dubbo.registry.address = N/A", "dubbo.protocol.id=my-protocol", "dubbo.protocol.name=dubbo", "dubbo.protocol.port=20880", "dubbo.provider.id=my-provider", "dubbo.provider.host=127.0.0.1", "dubbo.scan.basePackages = org.apache.dubbo.spring.boot.actuate.autoconfigure", "management.endpoint.dubbo.enabled = true", "management.endpoint.dubboshutdown.enabled = true", "management.endpoint.dubboconfigs.enabled = true", "management.endpoint.dubboservices.enabled = true", "management.endpoint.dubboreferences.enabled = true", "management.endpoint.dubboproperties.enabled = true", "management.endpoints.web.exposure.include = *", }) @EnableAutoConfiguration @Disabled class DubboEndpointAnnotationAutoConfigurationTest { @Autowired private DubboMetadataEndpoint dubboEndpoint; @Autowired private DubboConfigsMetadataEndpoint dubboConfigsMetadataEndpoint; @Autowired private DubboPropertiesMetadataEndpoint dubboPropertiesEndpoint; @Autowired private DubboReferencesMetadataEndpoint dubboReferencesMetadataEndpoint; @Autowired private DubboServicesMetadataEndpoint dubboServicesMetadataEndpoint; @Autowired private DubboShutdownEndpoint dubboShutdownEndpoint; private RestTemplate restTemplate = new RestTemplate(); @Autowired private ObjectMapper objectMapper; @Value("http://127.0.0.1:${local.management.port}${management.endpoints.web.base-path:/actuator}") private String actuatorBaseURL; @BeforeEach public void init() { DubboBootstrap.reset(); } @AfterEach public void destroy() { DubboBootstrap.reset(); } @Test void testShutdown() throws Exception { Map<String, Object> value = dubboShutdownEndpoint.shutdown(); Map<String, Object> shutdownCounts = (Map<String, Object>) value.get("shutdown.count"); Assert.assertEquals(0, shutdownCounts.get("registries")); Assert.assertEquals(1, shutdownCounts.get("protocols")); Assert.assertEquals(1, shutdownCounts.get("services")); Assert.assertEquals(0, shutdownCounts.get("references")); } @Test void testConfigs() { Map<String, Map<String, Map<String, Object>>> configsMap = dubboConfigsMetadataEndpoint.configs(); Map<String, Map<String, Object>> beansMetadata = configsMap.get("ApplicationConfig"); Assert.assertEquals( "dubbo-demo-application", beansMetadata.get("my-application").get("name")); beansMetadata = configsMap.get("ConsumerConfig"); Assert.assertTrue(beansMetadata.isEmpty()); beansMetadata = configsMap.get("MethodConfig"); Assert.assertTrue(beansMetadata.isEmpty()); beansMetadata = configsMap.get("ModuleConfig"); Assert.assertEquals("dubbo-demo-module", beansMetadata.get("my-module").get("name")); beansMetadata = configsMap.get("MonitorConfig"); Assert.assertTrue(beansMetadata.isEmpty()); beansMetadata = configsMap.get("ProtocolConfig"); Assert.assertEquals("dubbo", beansMetadata.get("my-protocol").get("name")); beansMetadata = configsMap.get("ProviderConfig"); Assert.assertEquals("127.0.0.1", beansMetadata.get("my-provider").get("host")); beansMetadata = configsMap.get("ReferenceConfig"); Assert.assertTrue(beansMetadata.isEmpty()); beansMetadata = configsMap.get("RegistryConfig"); Assert.assertEquals("N/A", beansMetadata.get("my-registry").get("address")); beansMetadata = configsMap.get("ServiceConfig"); Assert.assertFalse(beansMetadata.isEmpty()); } @Test void testServices() { Map<String, Map<String, Object>> services = dubboServicesMetadataEndpoint.services(); Assert.assertEquals(1, services.size()); Map<String, Object> demoServiceMeta = services.get( "ServiceBean:org.apache.dubbo.spring.boot.actuate.autoconfigure.DubboEndpointAnnotationAutoConfigurationTest$DemoService:1.0.0:"); Assert.assertEquals("1.0.0", demoServiceMeta.get("version")); } @Test void testReferences() { Map<String, Map<String, Object>> references = dubboReferencesMetadataEndpoint.references(); Assert.assertTrue(!references.isEmpty()); String injectedField = "private " + DemoService.class.getName() + " " + ConsumerConfiguration.class.getName() + ".demoService"; Map<String, Object> referenceMap = references.get(injectedField); Assert.assertNotNull(referenceMap); Assert.assertEquals(DemoService.class, referenceMap.get("interfaceClass")); Assert.assertEquals( BaseServiceMetadata.buildServiceKey( DemoService.class.getName(), ConsumerConfiguration.DEMO_GROUP, ConsumerConfiguration.DEMO_VERSION), referenceMap.get("uniqueServiceName")); } @Test void testProperties() { SortedMap<String, Object> properties = dubboPropertiesEndpoint.properties(); Assert.assertEquals("my-application", properties.get("dubbo.application.id")); Assert.assertEquals("dubbo-demo-application", properties.get("dubbo.application.name")); Assert.assertEquals("my-module", properties.get("dubbo.module.id")); Assert.assertEquals("dubbo-demo-module", properties.get("dubbo.module.name")); Assert.assertEquals("my-registry", properties.get("dubbo.registry.id")); Assert.assertEquals("N/A", properties.get("dubbo.registry.address")); Assert.assertEquals("my-protocol", properties.get("dubbo.protocol.id")); Assert.assertEquals("dubbo", properties.get("dubbo.protocol.name")); Assert.assertEquals("20880", properties.get("dubbo.protocol.port")); Assert.assertEquals("my-provider", properties.get("dubbo.provider.id")); Assert.assertEquals("127.0.0.1", properties.get("dubbo.provider.host")); Assert.assertEquals( "org.apache.dubbo.spring.boot.actuate.autoconfigure", properties.get("dubbo.scan.basePackages")); } @Test void testHttpEndpoints() throws JsonProcessingException { // testHttpEndpoint("/dubbo", dubboEndpoint::invoke); testHttpEndpoint("/dubbo/configs", dubboConfigsMetadataEndpoint::configs); testHttpEndpoint("/dubbo/services", dubboServicesMetadataEndpoint::services); testHttpEndpoint("/dubbo/references", dubboReferencesMetadataEndpoint::references); testHttpEndpoint("/dubbo/properties", dubboPropertiesEndpoint::properties); } private void testHttpEndpoint(String actuatorURI, Supplier<Map> resultsSupplier) throws JsonProcessingException { String actuatorURL = actuatorBaseURL + actuatorURI; String response = restTemplate.getForObject(actuatorURL, String.class); Assert.assertEquals(objectMapper.writeValueAsString(resultsSupplier.get()), response); } interface DemoService { String sayHello(String name); } @DubboService( version = "${dubbo.service.version}", application = "${dubbo.application.id}", protocol = "${dubbo.protocol.id}", registry = "${dubbo.registry.id}") static class DefaultDemoService implements DemoService { public String sayHello(String name) { return "Hello, " + name + " (from Spring Boot)"; } } @Configuration static class ConsumerConfiguration { public static final String DEMO_GROUP = "demo"; public static final String DEMO_VERSION = "1.0.0"; @DubboReference(group = DEMO_GROUP, version = DEMO_VERSION) private DemoService demoService; } }
7,656
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboShutdownEndpoint.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.endpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.AbstractDubboMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboShutdownMetadata; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.WriteOperation; /** * Dubbo Shutdown * * @since 2.7.0 */ @Endpoint(id = "dubboshutdown") public class DubboShutdownEndpoint extends AbstractDubboMetadata { @Autowired private DubboShutdownMetadata dubboShutdownMetadata; @WriteOperation public Map<String, Object> shutdown() throws Exception { return dubboShutdownMetadata.shutdown(); } }
7,657
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboReferencesMetadataEndpoint.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.endpoint; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.AbstractDubboMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboReferencesMetadata; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; /** * {@link DubboReference} Metadata {@link Endpoint} * * @since 2.7.0 */ @Endpoint(id = "dubboreferences") public class DubboReferencesMetadataEndpoint extends AbstractDubboMetadata { @Autowired private DubboReferencesMetadata dubboReferencesMetadata; @ReadOperation public Map<String, Map<String, Object>> references() { return dubboReferencesMetadata.references(); } }
7,658
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboConfigsMetadataEndpoint.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.endpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.AbstractDubboMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboConfigsMetadata; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; /** * Dubbo Configs Metadata {@link Endpoint} * * @since 2.7.0 */ @Endpoint(id = "dubboconfigs") public class DubboConfigsMetadataEndpoint extends AbstractDubboMetadata { @Autowired private DubboConfigsMetadata dubboConfigsMetadata; @ReadOperation public Map<String, Map<String, Map<String, Object>>> configs() { return dubboConfigsMetadata.configs(); } }
7,659
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboPropertiesMetadataEndpoint.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.endpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.AbstractDubboMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboPropertiesMetadata; import java.util.SortedMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; /** * Dubbo Properties {@link Endpoint} * * @since 2.7.0 */ @Endpoint(id = "dubboproperties") public class DubboPropertiesMetadataEndpoint extends AbstractDubboMetadata { @Autowired private DubboPropertiesMetadata dubboPropertiesMetadata; @ReadOperation public SortedMap<String, Object> properties() { return dubboPropertiesMetadata.properties(); } }
7,660
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboMetadataEndpoint.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.endpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboMetadata; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; /** * Actuator {@link Endpoint} to expose Dubbo Meta Data * * @see Endpoint * @since 2.7.0 */ @Endpoint(id = "dubbo") public class DubboMetadataEndpoint { @Autowired private DubboMetadata dubboMetadata; @ReadOperation public Map<String, Object> invoke() { return dubboMetadata.invoke(); } }
7,661
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboServicesMetadataEndpoint.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.endpoint; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.AbstractDubboMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboServicesMetadata; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; /** * {@link DubboService} Metadata {@link Endpoint} * * @since 2.7.0 */ @Endpoint(id = "dubboservices") public class DubboServicesMetadataEndpoint extends AbstractDubboMetadata { @Autowired private DubboServicesMetadata dubboServicesMetadata; @ReadOperation public Map<String, Map<String, Object>> services() { return dubboServicesMetadata.services(); } }
7,662
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/condition/CompatibleConditionalOnEnabledEndpoint.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.endpoint.condition; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.EndpointExtension; import org.springframework.context.annotation.Conditional; /** * {@link Conditional} that checks whether or not an endpoint is enabled, which is compatible with * org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint ([2.0.x, 2.2.x]) * org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint * * @see CompatibleOnEnabledEndpointCondition * @since 2.7.7 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) @Documented @Conditional(CompatibleOnEnabledEndpointCondition.class) public @interface CompatibleConditionalOnEnabledEndpoint { /** * The endpoint type that should be checked. Inferred when the return type of the * {@code @Bean} method is either an {@link Endpoint @Endpoint} or an * {@link EndpointExtension @EndpointExtension}. * * @return the endpoint type to check */ Class<?> endpoint() default Void.class; }
7,663
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/condition/CompatibleOnEnabledEndpointCondition.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.endpoint.condition; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.context.annotation.Conditional; import org.springframework.core.type.AnnotatedTypeMetadata; import org.springframework.util.ClassUtils; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_CLASS_NOT_FOUND; /** * {@link Conditional} that checks whether or not an endpoint is enabled, which is compatible with * org.springframework.boot.actuate.autoconfigure.endpoint.condition.OnEnabledEndpointCondition * and org.springframework.boot.actuate.autoconfigure.endpoint.condition.OnAvailableEndpointCondition * * @see CompatibleConditionalOnEnabledEndpoint * @since 2.7.7 */ class CompatibleOnEnabledEndpointCondition implements Condition { private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(CompatibleOnEnabledEndpointCondition.class); // Spring Boot [2.0.0 , 2.2.x] static String CONDITION_CLASS_NAME_OLD = "org.springframework.boot.actuate.autoconfigure.endpoint.condition.OnEnabledEndpointCondition"; // Spring Boot 2.2.0 + static String CONDITION_CLASS_NAME_NEW = "org.springframework.boot.actuate.autoconfigure.endpoint.condition.OnAvailableEndpointCondition"; @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { ClassLoader classLoader = context.getClassLoader(); if (ClassUtils.isPresent(CONDITION_CLASS_NAME_OLD, classLoader)) { Class<?> cls = ClassUtils.resolveClassName(CONDITION_CLASS_NAME_OLD, classLoader); if (Condition.class.isAssignableFrom(cls)) { Condition condition = Condition.class.cast(BeanUtils.instantiateClass(cls)); return condition.matches(context, metadata); } } // Check by org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint if (ClassUtils.isPresent(CONDITION_CLASS_NAME_NEW, classLoader)) { return true; } // No condition class found LOGGER.warn( COMMON_CLASS_NOT_FOUND, "No condition class found", "", String.format("No condition class found, Dubbo Health Endpoint [%s] will not expose", metadata)); return false; } }
7,664
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAnnotationAutoConfiguration.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.autoconfigure; import org.apache.dubbo.spring.boot.actuate.endpoint.DubboConfigsMetadataEndpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.DubboMetadataEndpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.DubboPropertiesMetadataEndpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.DubboReferencesMetadataEndpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.DubboServicesMetadataEndpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.DubboShutdownEndpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.condition.CompatibleConditionalOnEnabledEndpoint; import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; /** * Dubbo {@link Endpoint @Endpoint} Auto-{@link Configuration} for Spring Boot Actuator 2.0 * * @see Endpoint * @see Configuration * @since 2.7.0 */ @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @Configuration @PropertySource( name = "Dubbo Endpoints Default Properties", value = "classpath:/META-INF/dubbo-endpoints-default.properties") public class DubboEndpointAnnotationAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnAvailableEndpoint @CompatibleConditionalOnEnabledEndpoint public DubboMetadataEndpoint dubboEndpoint() { return new DubboMetadataEndpoint(); } @Bean @ConditionalOnMissingBean @ConditionalOnAvailableEndpoint @CompatibleConditionalOnEnabledEndpoint public DubboConfigsMetadataEndpoint dubboConfigsMetadataEndpoint() { return new DubboConfigsMetadataEndpoint(); } @Bean @ConditionalOnMissingBean @ConditionalOnAvailableEndpoint @CompatibleConditionalOnEnabledEndpoint public DubboPropertiesMetadataEndpoint dubboPropertiesEndpoint() { return new DubboPropertiesMetadataEndpoint(); } @Bean @ConditionalOnMissingBean @ConditionalOnAvailableEndpoint @CompatibleConditionalOnEnabledEndpoint public DubboReferencesMetadataEndpoint dubboReferencesMetadataEndpoint() { return new DubboReferencesMetadataEndpoint(); } @Bean @ConditionalOnMissingBean @ConditionalOnAvailableEndpoint @CompatibleConditionalOnEnabledEndpoint public DubboServicesMetadataEndpoint dubboServicesMetadataEndpoint() { return new DubboServicesMetadataEndpoint(); } @Bean @ConditionalOnMissingBean @ConditionalOnAvailableEndpoint @CompatibleConditionalOnEnabledEndpoint public DubboShutdownEndpoint dubboShutdownEndpoint() { return new DubboShutdownEndpoint(); } }
7,665
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboMetricsAutoConfiguration.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.autoconfigure; import org.apache.dubbo.spring.boot.actuate.mertics.DubboMetricsBinder; import io.micrometer.core.instrument.MeterRegistry; import org.springframework.boot.actuate.autoconfigure.metrics.CompositeMeterRegistryAutoConfiguration; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @Configuration(proxyBeanMethods = false) @ConditionalOnWebApplication @AutoConfigureAfter(CompositeMeterRegistryAutoConfiguration.class) public class DubboMetricsAutoConfiguration { @Bean @ConditionalOnBean({MeterRegistry.class}) @ConditionalOnMissingBean({DubboMetricsBinder.class}) public DubboMetricsBinder dubboMetricsBinder(MeterRegistry meterRegistry) { return new DubboMetricsBinder(meterRegistry); } }
7,666
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/mertics/DubboMetricsBinder.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.mertics; import org.apache.dubbo.metrics.MetricsGlobalRegistry; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.composite.CompositeMeterRegistry; import org.springframework.beans.factory.DisposableBean; import org.springframework.boot.context.event.ApplicationStartedEvent; import org.springframework.context.ApplicationListener; public class DubboMetricsBinder implements ApplicationListener<ApplicationStartedEvent>, DisposableBean { private final MeterRegistry meterRegistry; public DubboMetricsBinder(MeterRegistry meterRegistry) { this.meterRegistry = meterRegistry; } @Override public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) { if (meterRegistry instanceof CompositeMeterRegistry) { MetricsGlobalRegistry.setCompositeRegistry((CompositeMeterRegistry) meterRegistry); } else { MetricsGlobalRegistry.getCompositeRegistry().add(meterRegistry); } } @Override public void destroy() {} }
7,667
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/test/java/org/apache/dubbo/spring/boot/actuate
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/test/java/org/apache/dubbo/spring/boot/actuate/health/DubboHealthIndicatorTest.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.health; import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig; import java.util.Map; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.Status; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; /** * {@link DubboHealthIndicator} Test * * @see DubboHealthIndicator * @since 2.7.0 */ @RunWith(SpringRunner.class) @TestPropertySource( properties = { "dubbo.application.id = my-application-1", "dubbo.application.name = dubbo-demo-application-1", "dubbo.protocol.id = dubbo-protocol", "dubbo.protocol.name = dubbo", "dubbo.protocol.port = 12345", "dubbo.protocol.status = registry", "dubbo.provider.id = dubbo-provider", "dubbo.provider.status = server", "management.health.dubbo.status.defaults = memory", "management.health.dubbo.status.extras = load,threadpool" }) @SpringBootTest(classes = {DubboHealthIndicator.class, DubboHealthIndicatorTest.class}) @EnableConfigurationProperties(DubboHealthIndicatorProperties.class) @EnableDubboConfig public class DubboHealthIndicatorTest { @Autowired private DubboHealthIndicator dubboHealthIndicator; @Test public void testResolveStatusCheckerNamesMap() { Map<String, String> statusCheckerNamesMap = dubboHealthIndicator.resolveStatusCheckerNamesMap(); Assert.assertEquals(5, statusCheckerNamesMap.size()); Assert.assertEquals("[email protected]()", statusCheckerNamesMap.get("registry")); Assert.assertEquals("[email protected]()", statusCheckerNamesMap.get("server")); Assert.assertEquals("management.health.dubbo.status.defaults", statusCheckerNamesMap.get("memory")); Assert.assertEquals("management.health.dubbo.status.extras", statusCheckerNamesMap.get("load")); Assert.assertEquals("management.health.dubbo.status.extras", statusCheckerNamesMap.get("threadpool")); } @Test public void testHealth() { Health health = dubboHealthIndicator.health(); Assert.assertEquals(Status.UNKNOWN, health.getStatus()); } }
7,668
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/test/java/org/apache/dubbo/spring/boot/actuate
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/test/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAutoConfigurationTest.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.autoconfigure; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.spring.boot.actuate.endpoint.DubboEndpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboConfigsMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboPropertiesMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboReferencesMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboServicesMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboShutdownMetadata; import java.util.Map; import java.util.SortedMap; import java.util.function.Supplier; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; /** * {@link DubboEndpointAutoConfiguration} Test * * @since 2.7.0 */ @RunWith(SpringRunner.class) @SpringBootTest( classes = {DubboEndpointAutoConfiguration.class, DubboEndpointAutoConfigurationTest.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { "dubbo.service.version = 1.0.0", "dubbo.application.id = my-application", "dubbo.application.name = dubbo-demo-application", "dubbo.module.id = my-module", "dubbo.module.name = dubbo-demo-module", "dubbo.registry.id = my-registry", "dubbo.registry.address = N/A", "dubbo.protocol.id=my-protocol", "dubbo.protocol.name=dubbo", "dubbo.protocol.port=20880", "dubbo.provider.id=my-provider", "dubbo.provider.host=127.0.0.1", "dubbo.scan.basePackages=org.apache.dubbo.spring.boot.actuate.autoconfigure", "endpoints.enabled = true", "management.security.enabled = false", "management.contextPath = /actuator", "endpoints.dubbo.enabled = true", "endpoints.dubbo.sensitive = false", "endpoints.dubboshutdown.enabled = true", "endpoints.dubboconfigs.enabled = true", "endpoints.dubboservices.enabled = true", "endpoints.dubboreferences.enabled = true", "endpoints.dubboproperties.enabled = true", }) @EnableAutoConfiguration @Ignore public class DubboEndpointAutoConfigurationTest { @Autowired private DubboEndpoint dubboEndpoint; @Autowired private DubboConfigsMetadata dubboConfigsMetadata; @Autowired private DubboPropertiesMetadata dubboProperties; @Autowired private DubboReferencesMetadata dubboReferencesMetadata; @Autowired private DubboServicesMetadata dubboServicesMetadata; @Autowired private DubboShutdownMetadata dubboShutdownMetadata; private RestTemplate restTemplate = new RestTemplate(); @Autowired private ObjectMapper objectMapper; @Value("http://127.0.0.1:${local.management.port}${management.contextPath:}") private String actuatorBaseURL; @Test public void testShutdown() throws Exception { Map<String, Object> value = dubboShutdownMetadata.shutdown(); Map<String, Object> shutdownCounts = (Map<String, Object>) value.get("shutdown.count"); Assert.assertEquals(0, shutdownCounts.get("registries")); Assert.assertEquals(1, shutdownCounts.get("protocols")); Assert.assertEquals(1, shutdownCounts.get("services")); Assert.assertEquals(0, shutdownCounts.get("references")); } @Test public void testConfigs() { Map<String, Map<String, Map<String, Object>>> configsMap = dubboConfigsMetadata.configs(); Map<String, Map<String, Object>> beansMetadata = configsMap.get("ApplicationConfig"); Assert.assertEquals( "dubbo-demo-application", beansMetadata.get("my-application").get("name")); beansMetadata = configsMap.get("ConsumerConfig"); Assert.assertTrue(beansMetadata.isEmpty()); beansMetadata = configsMap.get("MethodConfig"); Assert.assertTrue(beansMetadata.isEmpty()); beansMetadata = configsMap.get("ModuleConfig"); Assert.assertEquals("dubbo-demo-module", beansMetadata.get("my-module").get("name")); beansMetadata = configsMap.get("MonitorConfig"); Assert.assertTrue(beansMetadata.isEmpty()); beansMetadata = configsMap.get("ProtocolConfig"); Assert.assertEquals("dubbo", beansMetadata.get("my-protocol").get("name")); beansMetadata = configsMap.get("ProviderConfig"); Assert.assertEquals("127.0.0.1", beansMetadata.get("my-provider").get("host")); beansMetadata = configsMap.get("ReferenceConfig"); Assert.assertTrue(beansMetadata.isEmpty()); beansMetadata = configsMap.get("RegistryConfig"); Assert.assertEquals("N/A", beansMetadata.get("my-registry").get("address")); beansMetadata = configsMap.get("ServiceConfig"); Assert.assertFalse(beansMetadata.isEmpty()); } @Test public void testServices() { Map<String, Map<String, Object>> services = dubboServicesMetadata.services(); Assert.assertEquals(1, services.size()); Map<String, Object> demoServiceMeta = services.get( "ServiceBean:org.apache.dubbo.spring.boot.actuate.autoconfigure.DubboEndpointAutoConfigurationTest$DemoService:1.0.0:"); Assert.assertEquals("1.0.0", demoServiceMeta.get("version")); } @Test public void testReferences() { Map<String, Map<String, Object>> references = dubboReferencesMetadata.references(); Assert.assertTrue(references.isEmpty()); } @Test public void testProperties() { SortedMap<String, Object> properties = dubboProperties.properties(); Assert.assertEquals("my-application", properties.get("dubbo.application.id")); Assert.assertEquals("dubbo-demo-application", properties.get("dubbo.application.name")); Assert.assertEquals("my-module", properties.get("dubbo.module.id")); Assert.assertEquals("dubbo-demo-module", properties.get("dubbo.module.name")); Assert.assertEquals("my-registry", properties.get("dubbo.registry.id")); Assert.assertEquals("N/A", properties.get("dubbo.registry.address")); Assert.assertEquals("my-protocol", properties.get("dubbo.protocol.id")); Assert.assertEquals("dubbo", properties.get("dubbo.protocol.name")); Assert.assertEquals("20880", properties.get("dubbo.protocol.port")); Assert.assertEquals("my-provider", properties.get("dubbo.provider.id")); Assert.assertEquals("127.0.0.1", properties.get("dubbo.provider.host")); Assert.assertEquals( "org.apache.dubbo.spring.boot.actuate.autoconfigure", properties.get("dubbo.scan.basePackages")); } @Test public void testHttpEndpoints() throws JsonProcessingException { // testHttpEndpoint("/dubbo", dubboEndpoint::invoke); testHttpEndpoint("/dubbo/configs", dubboConfigsMetadata::configs); testHttpEndpoint("/dubbo/services", dubboServicesMetadata::services); testHttpEndpoint("/dubbo/references", dubboReferencesMetadata::references); testHttpEndpoint("/dubbo/properties", dubboProperties::properties); } private void testHttpEndpoint(String actuatorURI, Supplier<Map> resultsSupplier) throws JsonProcessingException { String actuatorURL = actuatorBaseURL + actuatorURI; String response = restTemplate.getForObject(actuatorURL, String.class); Assert.assertEquals(objectMapper.writeValueAsString(resultsSupplier.get()), response); } interface DemoService { String sayHello(String name); } @DubboService( version = "${dubbo.service.version}", application = "${dubbo.application.id}", protocol = "${dubbo.protocol.id}", registry = "${dubbo.registry.id}") static class DefaultDemoService implements DemoService { public String sayHello(String name) { return "Hello, " + name + " (from Spring Boot)"; } } }
7,669
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/health/DubboHealthIndicator.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.health; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.status.StatusChecker; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.health.AbstractHealthIndicator; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.util.StringUtils; /** * Dubbo {@link HealthIndicator} * * @see HealthIndicator * @since 2.7.0 */ public class DubboHealthIndicator extends AbstractHealthIndicator { @Autowired private DubboHealthIndicatorProperties dubboHealthIndicatorProperties; // @Autowired(required = false) private Map<String, ProtocolConfig> protocolConfigs = Collections.emptyMap(); // @Autowired(required = false) private Map<String, ProviderConfig> providerConfigs = Collections.emptyMap(); @Autowired private ConfigManager configManager; @Autowired private ApplicationModel applicationModel; @Override protected void doHealthCheck(Health.Builder builder) throws Exception { ExtensionLoader<StatusChecker> extensionLoader = applicationModel.getExtensionLoader(StatusChecker.class); Map<String, String> statusCheckerNamesMap = resolveStatusCheckerNamesMap(); boolean hasError = false; boolean hasUnknown = false; // Up first builder.up(); for (Map.Entry<String, String> entry : statusCheckerNamesMap.entrySet()) { String statusCheckerName = entry.getKey(); String source = entry.getValue(); StatusChecker checker = extensionLoader.getExtension(statusCheckerName); org.apache.dubbo.common.status.Status status = checker.check(); org.apache.dubbo.common.status.Status.Level level = status.getLevel(); if (!hasError && level.equals(org.apache.dubbo.common.status.Status.Level.ERROR)) { hasError = true; builder.down(); } if (!hasError && !hasUnknown && level.equals(org.apache.dubbo.common.status.Status.Level.UNKNOWN)) { hasUnknown = true; builder.unknown(); } Map<String, Object> detail = new LinkedHashMap<>(); detail.put("source", source); detail.put("status", status); builder.withDetail(statusCheckerName, detail); } } /** * Resolves the map of {@link StatusChecker}'s name and its' source. * * @return non-null {@link Map} */ protected Map<String, String> resolveStatusCheckerNamesMap() { Map<String, String> statusCheckerNamesMap = new LinkedHashMap<>(); statusCheckerNamesMap.putAll(resolveStatusCheckerNamesMapFromDubboHealthIndicatorProperties()); statusCheckerNamesMap.putAll(resolveStatusCheckerNamesMapFromProtocolConfigs()); statusCheckerNamesMap.putAll(resolveStatusCheckerNamesMapFromProviderConfig()); return statusCheckerNamesMap; } private Map<String, String> resolveStatusCheckerNamesMapFromDubboHealthIndicatorProperties() { DubboHealthIndicatorProperties.Status status = dubboHealthIndicatorProperties.getStatus(); Map<String, String> statusCheckerNamesMap = new LinkedHashMap<>(); for (String statusName : status.getDefaults()) { statusCheckerNamesMap.put(statusName, DubboHealthIndicatorProperties.PREFIX + ".status.defaults"); } for (String statusName : status.getExtras()) { statusCheckerNamesMap.put(statusName, DubboHealthIndicatorProperties.PREFIX + ".status.extras"); } return statusCheckerNamesMap; } private Map<String, String> resolveStatusCheckerNamesMapFromProtocolConfigs() { if (protocolConfigs.isEmpty()) { protocolConfigs = configManager.getConfigsMap(ProtocolConfig.class); } Map<String, String> statusCheckerNamesMap = new LinkedHashMap<>(); for (Map.Entry<String, ProtocolConfig> entry : protocolConfigs.entrySet()) { String beanName = entry.getKey(); ProtocolConfig protocolConfig = entry.getValue(); Set<String> statusCheckerNames = getStatusCheckerNames(protocolConfig); for (String statusCheckerName : statusCheckerNames) { String source = buildSource(beanName, protocolConfig); statusCheckerNamesMap.put(statusCheckerName, source); } } return statusCheckerNamesMap; } private Map<String, String> resolveStatusCheckerNamesMapFromProviderConfig() { if (providerConfigs.isEmpty()) { providerConfigs = new LinkedHashMap<>(); for (ModuleModel moduleModel : applicationModel.getModuleModels()) { providerConfigs.putAll(moduleModel.getConfigManager().getConfigsMap(ProviderConfig.class)); } } Map<String, String> statusCheckerNamesMap = new LinkedHashMap<>(); for (Map.Entry<String, ProviderConfig> entry : providerConfigs.entrySet()) { String beanName = entry.getKey(); ProviderConfig providerConfig = entry.getValue(); Set<String> statusCheckerNames = getStatusCheckerNames(providerConfig); for (String statusCheckerName : statusCheckerNames) { String source = buildSource(beanName, providerConfig); statusCheckerNamesMap.put(statusCheckerName, source); } } return statusCheckerNamesMap; } private Set<String> getStatusCheckerNames(ProtocolConfig protocolConfig) { String status = protocolConfig.getStatus(); return StringUtils.commaDelimitedListToSet(status); } private Set<String> getStatusCheckerNames(ProviderConfig providerConfig) { String status = providerConfig.getStatus(); return StringUtils.commaDelimitedListToSet(status); } private String buildSource(String beanName, Object bean) { return beanName + "@" + bean.getClass().getSimpleName() + ".getStatus()"; } }
7,670
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/health/DubboHealthIndicatorProperties.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.health; import org.apache.dubbo.common.status.StatusChecker; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.boot.context.properties.ConfigurationProperties; import static org.apache.dubbo.spring.boot.actuate.health.DubboHealthIndicatorProperties.PREFIX; /** * Dubbo {@link HealthIndicator} Properties * * @see HealthIndicator * @since 2.7.0 */ @ConfigurationProperties(prefix = PREFIX, ignoreUnknownFields = false) public class DubboHealthIndicatorProperties { /** * The prefix of {@link DubboHealthIndicatorProperties} */ public static final String PREFIX = "management.health.dubbo"; private Status status = new Status(); public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } /** * The nested class for {@link StatusChecker}'s names * <pre> * registry= org.apache.dubbo.registry.status.RegistryStatusChecker * spring= org.apache.dubbo.config.spring.status.SpringStatusChecker * datasource= org.apache.dubbo.config.spring.status.DataSourceStatusChecker * memory= org.apache.dubbo.common.status.support.MemoryStatusChecker * load= org.apache.dubbo.common.status.support.LoadStatusChecker * server= org.apache.dubbo.rpc.protocol.dubbo.status.ServerStatusChecker * threadpool= org.apache.dubbo.rpc.protocol.dubbo.status.ThreadPoolStatusChecker * </pre> * * @see StatusChecker */ public static class Status { /** * The defaults names of {@link StatusChecker} * <p> * The defaults : "memory", "load" */ private Set<String> defaults = new LinkedHashSet<>(Arrays.asList("memory", "load")); /** * The extra names of {@link StatusChecker} */ private Set<String> extras = new LinkedHashSet<>(); public Set<String> getDefaults() { return defaults; } public void setDefaults(Set<String> defaults) { this.defaults = defaults; } public Set<String> getExtras() { return extras; } public void setExtras(Set<String> extras) { this.extras = extras; } } }
7,671
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/DubboEndpoint.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.endpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboMetadata; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.AbstractEndpoint; import org.springframework.boot.actuate.endpoint.Endpoint; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Actuator {@link Endpoint} to expose Dubbo Meta Data * * @see Endpoint * @since 2.7.0 */ @ConfigurationProperties(prefix = "endpoints.dubbo", ignoreUnknownFields = false) public class DubboEndpoint extends AbstractEndpoint<Map<String, Object>> { @Autowired private DubboMetadata dubboMetadata; public DubboEndpoint() { super("dubbo", true, false); } @Override public Map<String, Object> invoke() { return dubboMetadata.invoke(); } }
7,672
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/mvc/DubboMvcEndpoint.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.endpoint.mvc; import org.apache.dubbo.spring.boot.actuate.endpoint.DubboEndpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboConfigsMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboPropertiesMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboReferencesMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboServicesMetadata; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.DubboShutdownMetadata; import java.util.Map; import java.util.SortedMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter; import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.context.request.async.DeferredResult; /** * {@link MvcEndpoint} to expose Dubbo Metadata * * @see MvcEndpoint * @since 2.7.0 */ public class DubboMvcEndpoint extends EndpointMvcAdapter { public static final String DUBBO_SHUTDOWN_ENDPOINT_URI = "/shutdown"; public static final String DUBBO_CONFIGS_ENDPOINT_URI = "/configs"; public static final String DUBBO_SERVICES_ENDPOINT_URI = "/services"; public static final String DUBBO_REFERENCES_ENDPOINT_URI = "/references"; public static final String DUBBO_PROPERTIES_ENDPOINT_URI = "/properties"; private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private DubboShutdownMetadata dubboShutdownMetadata; @Autowired private DubboConfigsMetadata dubboConfigsMetadata; @Autowired private DubboServicesMetadata dubboServicesMetadata; @Autowired private DubboReferencesMetadata dubboReferencesMetadata; @Autowired private DubboPropertiesMetadata dubboPropertiesMetadata; public DubboMvcEndpoint(DubboEndpoint dubboEndpoint) { super(dubboEndpoint); } @RequestMapping( value = DUBBO_SHUTDOWN_ENDPOINT_URI, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public DeferredResult shutdown() throws Exception { Map<String, Object> shutdownCountData = dubboShutdownMetadata.shutdown(); return new DeferredResult(null, shutdownCountData); } @RequestMapping( value = DUBBO_CONFIGS_ENDPOINT_URI, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Map<String, Map<String, Map<String, Object>>> configs() { return dubboConfigsMetadata.configs(); } @RequestMapping( value = DUBBO_SERVICES_ENDPOINT_URI, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Map<String, Map<String, Object>> services() { return dubboServicesMetadata.services(); } @RequestMapping( value = DUBBO_REFERENCES_ENDPOINT_URI, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Map<String, Map<String, Object>> references() { return dubboReferencesMetadata.references(); } @RequestMapping( value = DUBBO_PROPERTIES_ENDPOINT_URI, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public SortedMap<String, Object> properties() { return dubboPropertiesMetadata.properties(); } }
7,673
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboMetadata.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.endpoint.metadata; import org.apache.dubbo.common.Version; import org.apache.dubbo.spring.boot.util.DubboUtils; import java.util.LinkedHashMap; import java.util.Map; import org.springframework.stereotype.Component; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_GITHUB_URL; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_MAILING_LIST; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_SPRING_BOOT_GITHUB_URL; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_SPRING_BOOT_GIT_URL; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_SPRING_BOOT_ISSUES_URL; /** * Dubbo Metadata * @since 2.7.0 */ @Component public class DubboMetadata { public Map<String, Object> invoke() { Map<String, Object> metaData = new LinkedHashMap<>(); metaData.put("timestamp", System.currentTimeMillis()); Map<String, String> versions = new LinkedHashMap<>(); versions.put("dubbo-spring-boot", Version.getVersion(DubboUtils.class, "1.0.0")); versions.put("dubbo", Version.getVersion()); Map<String, String> urls = new LinkedHashMap<>(); urls.put("dubbo", DUBBO_GITHUB_URL); urls.put("mailing-list", DUBBO_MAILING_LIST); urls.put("github", DUBBO_SPRING_BOOT_GITHUB_URL); urls.put("issues", DUBBO_SPRING_BOOT_ISSUES_URL); urls.put("git", DUBBO_SPRING_BOOT_GIT_URL); metaData.put("versions", versions); metaData.put("urls", urls); return metaData; } }
7,674
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboConfigsMetadata.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.endpoint.metadata; import org.apache.dubbo.config.AbstractConfig; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConsumerConfig; import org.apache.dubbo.config.MethodConfig; import org.apache.dubbo.config.ModuleConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.ServiceConfig; import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; import org.springframework.stereotype.Component; import static org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors; /** * Dubbo Configs Metadata * * @since 2.7.0 */ @Component public class DubboConfigsMetadata extends AbstractDubboMetadata { public Map<String, Map<String, Map<String, Object>>> configs() { Map<String, Map<String, Map<String, Object>>> configsMap = new LinkedHashMap<>(); addDubboConfigBeans(ApplicationConfig.class, configsMap); addDubboConfigBeans(ConsumerConfig.class, configsMap); addDubboConfigBeans(MethodConfig.class, configsMap); addDubboConfigBeans(ModuleConfig.class, configsMap); addDubboConfigBeans(MonitorConfig.class, configsMap); addDubboConfigBeans(ProtocolConfig.class, configsMap); addDubboConfigBeans(ProviderConfig.class, configsMap); addDubboConfigBeans(ReferenceConfig.class, configsMap); addDubboConfigBeans(RegistryConfig.class, configsMap); addDubboConfigBeans(ServiceConfig.class, configsMap); return configsMap; } private void addDubboConfigBeans( Class<? extends AbstractConfig> dubboConfigClass, Map<String, Map<String, Map<String, Object>>> configsMap) { Map<String, ? extends AbstractConfig> dubboConfigBeans = beansOfTypeIncludingAncestors(applicationContext, dubboConfigClass); String name = dubboConfigClass.getSimpleName(); Map<String, Map<String, Object>> beansMetadata = new TreeMap<>(); for (Map.Entry<String, ? extends AbstractConfig> entry : dubboConfigBeans.entrySet()) { String beanName = entry.getKey(); AbstractConfig configBean = entry.getValue(); Map<String, Object> configBeanMeta = resolveBeanMetadata(configBean); beansMetadata.put(beanName, configBeanMeta); } configsMap.put(name, beansMetadata); } }
7,675
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboShutdownMetadata.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.endpoint.metadata; import org.apache.dubbo.config.ReferenceConfigBase; import org.apache.dubbo.config.spring.ServiceBean; import org.apache.dubbo.registry.support.RegistryManager; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * Dubbo Shutdown * * @since 2.7.0 */ @Component public class DubboShutdownMetadata extends AbstractDubboMetadata { @Autowired private ApplicationModel applicationModel; public Map<String, Object> shutdown() throws Exception { Map<String, Object> shutdownCountData = new LinkedHashMap<>(); // registries RegistryManager registryManager = applicationModel.getBeanFactory().getBean(RegistryManager.class); int registriesCount = registryManager.getRegistries().size(); // protocols int protocolsCount = getProtocolConfigsBeanMap().size(); shutdownCountData.put("registries", registriesCount); shutdownCountData.put("protocols", protocolsCount); // Service Beans Map<String, ServiceBean> serviceBeansMap = getServiceBeansMap(); if (!serviceBeansMap.isEmpty()) { for (ServiceBean serviceBean : serviceBeansMap.values()) { serviceBean.destroy(); } } shutdownCountData.put("services", serviceBeansMap.size()); // Reference Beans Collection<ReferenceConfigBase<?>> references = applicationModel.getDefaultModule().getConfigManager().getReferences(); for (ReferenceConfigBase<?> reference : references) { reference.destroy(); } shutdownCountData.put("references", references.size()); // Set Result to complete Map<String, Object> shutdownData = new TreeMap<>(); shutdownData.put("shutdown.count", shutdownCountData); return shutdownData; } }
7,676
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/AbstractDubboMetadata.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.endpoint.metadata; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.spring.ServiceBean; import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor; import org.apache.dubbo.config.spring.util.DubboBeanUtils; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URL; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.EnvironmentAware; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import static org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors; import static org.springframework.util.ClassUtils.isPrimitiveOrWrapper; /** * Abstract Dubbo Meatadata * * @since 2.7.0 */ public abstract class AbstractDubboMetadata implements ApplicationContextAware, EnvironmentAware { protected ApplicationContext applicationContext; protected ConfigurableEnvironment environment; private static boolean isSimpleType(Class<?> type) { return isPrimitiveOrWrapper(type) || type == String.class || type == BigDecimal.class || type == BigInteger.class || type == Date.class || type == URL.class || type == Class.class; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public void setEnvironment(Environment environment) { if (environment instanceof ConfigurableEnvironment) { this.environment = (ConfigurableEnvironment) environment; } } protected Map<String, Object> resolveBeanMetadata(final Object bean) { final Map<String, Object> beanMetadata = new LinkedHashMap<>(); try { BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Method readMethod = propertyDescriptor.getReadMethod(); if (readMethod != null && isSimpleType(propertyDescriptor.getPropertyType())) { String name = Introspector.decapitalize(propertyDescriptor.getName()); Object value = readMethod.invoke(bean); if (value != null) { beanMetadata.put(name, value); } } } } catch (Exception e) { throw new RuntimeException(e); } return beanMetadata; } protected Map<String, ServiceBean> getServiceBeansMap() { return beansOfTypeIncludingAncestors(applicationContext, ServiceBean.class); } protected ReferenceAnnotationBeanPostProcessor getReferenceAnnotationBeanPostProcessor() { return DubboBeanUtils.getReferenceAnnotationBeanPostProcessor(applicationContext); } protected Map<String, ProtocolConfig> getProtocolConfigsBeanMap() { return beansOfTypeIncludingAncestors(applicationContext, ProtocolConfig.class); } }
7,677
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboReferencesMetadata.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.endpoint.metadata; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.spring.ReferenceBean; import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import org.springframework.beans.factory.annotation.InjectionMetadata; import org.springframework.stereotype.Component; /** * {@link DubboReference} Metadata * * @since 2.7.0 */ @Component public class DubboReferencesMetadata extends AbstractDubboMetadata { public Map<String, Map<String, Object>> references() { Map<String, Map<String, Object>> referencesMetadata = new HashMap<>(); ReferenceAnnotationBeanPostProcessor beanPostProcessor = getReferenceAnnotationBeanPostProcessor(); referencesMetadata.putAll(buildReferencesMetadata(beanPostProcessor.getInjectedFieldReferenceBeanMap())); referencesMetadata.putAll(buildReferencesMetadata(beanPostProcessor.getInjectedMethodReferenceBeanMap())); return referencesMetadata; } private Map<String, Map<String, Object>> buildReferencesMetadata( Map<InjectionMetadata.InjectedElement, ReferenceBean<?>> injectedElementReferenceBeanMap) { Map<String, Map<String, Object>> referencesMetadata = new HashMap<>(); for (Map.Entry<InjectionMetadata.InjectedElement, ReferenceBean<?>> entry : injectedElementReferenceBeanMap.entrySet()) { InjectionMetadata.InjectedElement injectedElement = entry.getKey(); ReferenceBean<?> referenceBean = entry.getValue(); ReferenceConfig referenceConfig = referenceBean.getReferenceConfig(); Map<String, Object> beanMetadata = null; if (referenceConfig != null) { beanMetadata = resolveBeanMetadata(referenceConfig); // beanMetadata.put("invoker", resolveBeanMetadata(referenceBean.get())); } else { // referenceBean is not initialized beanMetadata = new LinkedHashMap<>(); } referencesMetadata.put(String.valueOf(injectedElement.getMember()), beanMetadata); } return referencesMetadata; } }
7,678
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboServicesMetadata.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.endpoint.metadata; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.config.spring.ServiceBean; import java.util.LinkedHashMap; import java.util.Map; import org.springframework.stereotype.Component; /** * {@link DubboService} Metadata * * @since 2.7.0 */ @Component public class DubboServicesMetadata extends AbstractDubboMetadata { public Map<String, Map<String, Object>> services() { Map<String, ServiceBean> serviceBeansMap = getServiceBeansMap(); Map<String, Map<String, Object>> servicesMetadata = new LinkedHashMap<>(serviceBeansMap.size()); for (Map.Entry<String, ServiceBean> entry : serviceBeansMap.entrySet()) { String serviceBeanName = entry.getKey(); ServiceBean serviceBean = entry.getValue(); Map<String, Object> serviceBeanMetadata = resolveBeanMetadata(serviceBean); Object service = resolveServiceBean(serviceBeanName, serviceBean); if (service != null) { // Add Service implementation class serviceBeanMetadata.put("serviceClass", service.getClass().getName()); } servicesMetadata.put(serviceBeanName, serviceBeanMetadata); } return servicesMetadata; } private Object resolveServiceBean(String serviceBeanName, ServiceBean serviceBean) { int index = serviceBeanName.indexOf("#"); if (index > -1) { Class<?> interfaceClass = serviceBean.getInterfaceClass(); String serviceName = serviceBeanName.substring(index + 1); if (applicationContext.containsBean(serviceName)) { return applicationContext.getBean(serviceName, interfaceClass); } } return null; } }
7,679
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/metadata/DubboPropertiesMetadata.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.endpoint.metadata; import java.util.SortedMap; import org.springframework.stereotype.Component; import static org.apache.dubbo.config.spring.util.EnvironmentUtils.filterDubboProperties; /** * Dubbo Properties Metadata * * @since 2.7.0 */ @Component public class DubboPropertiesMetadata extends AbstractDubboMetadata { public SortedMap<String, Object> properties() { return (SortedMap) filterDubboProperties(environment); } }
7,680
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointMetadataAutoConfiguration.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.autoconfigure; import org.apache.dubbo.spring.boot.actuate.endpoint.metadata.AbstractDubboMetadata; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; /** * Dubbo Endpoints Metadata Auto-{@link Configuration} */ @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @ConditionalOnClass( name = {"org.springframework.boot.actuate.health.Health" // If spring-boot-actuator is present }) @Configuration @AutoConfigureAfter( name = { "org.apache.dubbo.spring.boot.autoconfigure.DubboAutoConfiguration", "org.apache.dubbo.spring.boot.autoconfigure.DubboRelaxedBindingAutoConfiguration" }) @ComponentScan(basePackageClasses = AbstractDubboMetadata.class) public class DubboEndpointMetadataAutoConfiguration {}
7,681
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboMvcEndpointManagementContextConfiguration.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.autoconfigure; import org.apache.dubbo.spring.boot.actuate.endpoint.DubboEndpoint; import org.apache.dubbo.spring.boot.actuate.endpoint.mvc.DubboMvcEndpoint; import org.springframework.boot.actuate.autoconfigure.ManagementContextConfiguration; import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.context.annotation.Bean; /** * Dubbo {@link MvcEndpoint} {@link ManagementContextConfiguration} for Spring Boot 1.x * * @since 2.7.0 */ @ManagementContextConfiguration @ConditionalOnClass(name = {"org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter"}) @ConditionalOnWebApplication public class DubboMvcEndpointManagementContextConfiguration { @Bean @ConditionalOnBean(DubboEndpoint.class) @ConditionalOnMissingBean public DubboMvcEndpoint dubboMvcEndpoint(DubboEndpoint dubboEndpoint) { return new DubboMvcEndpoint(dubboEndpoint); } }
7,682
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboHealthIndicatorAutoConfiguration.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.autoconfigure; import org.apache.dubbo.spring.boot.actuate.health.DubboHealthIndicator; import org.apache.dubbo.spring.boot.actuate.health.DubboHealthIndicatorProperties; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Dubbo {@link DubboHealthIndicator} Auto Configuration * * @see HealthIndicator * @since 2.7.0 */ @Configuration @ConditionalOnClass(name = {"org.springframework.boot.actuate.health.Health"}) @ConditionalOnProperty( name = {"management.health.dubbo.enabled", "dubbo.enabled"}, matchIfMissing = true, havingValue = "true") @EnableConfigurationProperties(DubboHealthIndicatorProperties.class) public class DubboHealthIndicatorAutoConfiguration { @Bean @ConditionalOnMissingBean public DubboHealthIndicator dubboHealthIndicator() { return new DubboHealthIndicator(); } }
7,683
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/autoconfigure/DubboEndpointAutoConfiguration.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.actuate.autoconfigure; import org.apache.dubbo.spring.boot.actuate.endpoint.DubboEndpoint; import org.apache.dubbo.spring.boot.autoconfigure.DubboAutoConfiguration; import org.apache.dubbo.spring.boot.autoconfigure.DubboRelaxedBindingAutoConfiguration; import org.springframework.boot.actuate.condition.ConditionalOnEnabledEndpoint; import org.springframework.boot.actuate.endpoint.Endpoint; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; /** * Dubbo {@link Endpoint} Auto Configuration is compatible with Spring Boot Actuator 1.x * * @since 2.7.0 */ @ConditionalOnProperty(prefix = DUBBO_PREFIX, name = "enabled", matchIfMissing = true) @Configuration @ConditionalOnClass( name = {"org.springframework.boot.actuate.endpoint.Endpoint" // Spring Boot 1.x }) @AutoConfigureAfter(value = {DubboAutoConfiguration.class, DubboRelaxedBindingAutoConfiguration.class}) @EnableConfigurationProperties(DubboEndpoint.class) public class DubboEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnEnabledEndpoint(value = "dubbo") public DubboEndpoint dubboEndpoint() { return new DubboEndpoint(); } }
7,684
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/TestSuite.java
/* * 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 * * 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 org.apache.dubbo.spring.boot; import org.apache.dubbo.spring.boot.autoconfigure.CompatibleDubboAutoConfigurationTest; import org.apache.dubbo.spring.boot.autoconfigure.CompatibleDubboAutoConfigurationTestWithoutProperties; import org.apache.dubbo.spring.boot.autoconfigure.DubboAutoConfigurationOnMultipleConfigTest; import org.apache.dubbo.spring.boot.autoconfigure.DubboAutoConfigurationOnSingleConfigTest; import org.apache.dubbo.spring.boot.autoconfigure.RelaxedDubboConfigBinderTest; import org.apache.dubbo.spring.boot.context.event.AwaitingNonWebApplicationListenerTest; import org.apache.dubbo.spring.boot.context.event.DubboConfigBeanDefinitionConflictApplicationListenerTest; import org.apache.dubbo.spring.boot.context.event.WelcomeLogoApplicationListenerTest; import org.apache.dubbo.spring.boot.env.DubboDefaultPropertiesEnvironmentPostProcessorTest; import org.apache.dubbo.spring.boot.util.DubboUtilsTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ CompatibleDubboAutoConfigurationTest.class, CompatibleDubboAutoConfigurationTestWithoutProperties.class, DubboAutoConfigurationOnMultipleConfigTest.class, DubboAutoConfigurationOnSingleConfigTest.class, RelaxedDubboConfigBinderTest.class, AwaitingNonWebApplicationListenerTest.class, DubboConfigBeanDefinitionConflictApplicationListenerTest.class, WelcomeLogoApplicationListenerTest.class, DubboDefaultPropertiesEnvironmentPostProcessorTest.class, DubboUtilsTest.class, }) public class TestSuite {}
7,685
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/context
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/context/event/DubboConfigBeanDefinitionConflictApplicationListenerTest.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.context.event; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig; import java.util.Map; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.PropertySource; /** * {@link DubboConfigBeanDefinitionConflictApplicationListener} Test * * @since 2.7.5 */ public class DubboConfigBeanDefinitionConflictApplicationListenerTest { @Before public void init() { DubboBootstrap.reset(); // context.addApplicationListener(new DubboConfigBeanDefinitionConflictApplicationListener()); } @After public void destroy() { DubboBootstrap.reset(); } // @Test public void testNormalCase() { System.setProperty("dubbo.application.name", "test-dubbo-application"); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DubboConfig.class); try { context.start(); ApplicationConfig applicationConfig = context.getBean(ApplicationConfig.class); Assert.assertEquals("test-dubbo-application", applicationConfig.getName()); } finally { System.clearProperty("dubbo.application.name"); context.close(); } } @Test public void testDuplicatedConfigsCase() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PropertySourceConfig.class, DubboConfig.class, XmlConfig.class); try { context.start(); Map<String, ApplicationConfig> beansMap = context.getBeansOfType(ApplicationConfig.class); ApplicationConfig applicationConfig = beansMap.get("dubbo-consumer-2.7.x"); Assert.assertEquals(1, beansMap.size()); Assert.assertEquals("dubbo-consumer-2.7.x", applicationConfig.getName()); } finally { context.close(); } } @EnableDubboConfig static class DubboConfig {} @PropertySource("classpath:/META-INF/dubbo.properties") static class PropertySourceConfig {} @ImportResource("classpath:/META-INF/spring/dubbo-context.xml") static class XmlConfig {} }
7,686
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/context
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/context/event/WelcomeLogoApplicationListenerTest.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.context.event; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; /** * {@link WelcomeLogoApplicationListener} Test * * @see WelcomeLogoApplicationListener * @since 2.7.0 */ @RunWith(SpringRunner.class) @SpringBootTest(classes = {WelcomeLogoApplicationListener.class}) public class WelcomeLogoApplicationListenerTest { @Autowired private WelcomeLogoApplicationListener welcomeLogoApplicationListener; @Test public void testOnApplicationEvent() { Assert.assertNotNull(welcomeLogoApplicationListener.buildBannerText()); } }
7,687
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/context
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/context/event/AwaitingNonWebApplicationListenerTest.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.context.event; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.junit.After; import org.junit.Before; import org.junit.Ignore; /** * {@link AwaitingNonWebApplicationListener} Test */ @Ignore public class AwaitingNonWebApplicationListenerTest { @Before public void before() { DubboBootstrap.reset(); } @After public void after() { DubboBootstrap.reset(); } // @Test // public void init() { // AtomicBoolean awaited = AwaitingNonWebApplicationListener.getAwaited(); // awaited.set(false); // } // // @Test // public void testSingleContextNonWebApplication() { // new SpringApplicationBuilder(Object.class) // .web(false) // .run() // .close(); // // ShutdownHookCallbacks.INSTANCE.addCallback(() -> { // AtomicBoolean awaited = AwaitingNonWebApplicationListener.getAwaited(); // Assert.assertTrue(awaited.get()); // System.out.println("Callback..."); // }); // } // // @Test // public void testMultipleContextNonWebApplication() { // new SpringApplicationBuilder(Object.class) // .parent(Object.class) // .web(false) // .run().close(); // AtomicBoolean awaited = AwaitingNonWebApplicationListener.getAwaited(); // Assert.assertFalse(awaited.get()); // } }
7,688
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/util/DubboUtilsTest.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.util; import org.junit.Assert; import org.junit.Test; import static org.apache.dubbo.spring.boot.util.DubboUtils.BASE_PACKAGES_PROPERTY_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.DEFAULT_MULTIPLE_CONFIG_PROPERTY_VALUE; import static org.apache.dubbo.spring.boot.util.DubboUtils.DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_APPLICATION_ID_PROPERTY; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_APPLICATION_NAME_PROPERTY; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_APPLICATION_QOS_ENABLE_PROPERTY; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_CONFIG_MULTIPLE_PROPERTY; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_CONFIG_PREFIX; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_GITHUB_URL; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_MAILING_LIST; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_SCAN_PREFIX; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_SPRING_BOOT_GITHUB_URL; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_SPRING_BOOT_GIT_URL; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_SPRING_BOOT_ISSUES_URL; import static org.apache.dubbo.spring.boot.util.DubboUtils.MULTIPLE_CONFIG_PROPERTY_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.OVERRIDE_CONFIG_FULL_PROPERTY_NAME; import static org.apache.dubbo.spring.boot.util.DubboUtils.SPRING_APPLICATION_NAME_PROPERTY; /** * {@link DubboUtils} Test * * @see DubboUtils * @since 2.7.0 */ public class DubboUtilsTest { @Test public void testConstants() { Assert.assertEquals("dubbo", DUBBO_PREFIX); Assert.assertEquals("dubbo.scan.", DUBBO_SCAN_PREFIX); Assert.assertEquals("base-packages", BASE_PACKAGES_PROPERTY_NAME); Assert.assertEquals("dubbo.config.", DUBBO_CONFIG_PREFIX); Assert.assertEquals("multiple", MULTIPLE_CONFIG_PROPERTY_NAME); Assert.assertEquals("dubbo.config.override", OVERRIDE_CONFIG_FULL_PROPERTY_NAME); Assert.assertEquals("https://github.com/apache/dubbo/tree/3.0/dubbo-spring-boot", DUBBO_SPRING_BOOT_GITHUB_URL); Assert.assertEquals("https://github.com/apache/dubbo.git", DUBBO_SPRING_BOOT_GIT_URL); Assert.assertEquals("https://github.com/apache/dubbo/issues", DUBBO_SPRING_BOOT_ISSUES_URL); Assert.assertEquals("https://github.com/apache/dubbo", DUBBO_GITHUB_URL); Assert.assertEquals("[email protected]", DUBBO_MAILING_LIST); Assert.assertEquals("spring.application.name", SPRING_APPLICATION_NAME_PROPERTY); Assert.assertEquals("dubbo.application.id", DUBBO_APPLICATION_ID_PROPERTY); Assert.assertEquals("dubbo.application.name", DUBBO_APPLICATION_NAME_PROPERTY); Assert.assertEquals("dubbo.application.qos-enable", DUBBO_APPLICATION_QOS_ENABLE_PROPERTY); Assert.assertEquals("dubbo.config.multiple", DUBBO_CONFIG_MULTIPLE_PROPERTY); Assert.assertTrue(DEFAULT_MULTIPLE_CONFIG_PROPERTY_VALUE); Assert.assertTrue(DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE); } }
7,689
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/env/DubboDefaultPropertiesEnvironmentPostProcessorTest.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.env; import java.util.HashMap; import org.junit.Assert; import org.junit.Test; import org.springframework.boot.SpringApplication; import org.springframework.core.Ordered; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource; import org.springframework.mock.env.MockEnvironment; /** * {@link DubboDefaultPropertiesEnvironmentPostProcessor} Test */ public class DubboDefaultPropertiesEnvironmentPostProcessorTest { private DubboDefaultPropertiesEnvironmentPostProcessor instance = new DubboDefaultPropertiesEnvironmentPostProcessor(); private SpringApplication springApplication = new SpringApplication(); @Test public void testOrder() { Assert.assertEquals(Ordered.LOWEST_PRECEDENCE, instance.getOrder()); } @Test public void testPostProcessEnvironment() { MockEnvironment environment = new MockEnvironment(); // Case 1 : Not Any property instance.postProcessEnvironment(environment, springApplication); // Get PropertySources MutablePropertySources propertySources = environment.getPropertySources(); // Nothing to change PropertySource defaultPropertySource = propertySources.get("defaultProperties"); Assert.assertNotNull(defaultPropertySource); Assert.assertEquals("true", defaultPropertySource.getProperty("dubbo.config.multiple")); // Assert.assertEquals("true", defaultPropertySource.getProperty("dubbo.application.qos-enable")); // Case 2 : Only set property "spring.application.name" environment.setProperty("spring.application.name", "demo-dubbo-application"); instance.postProcessEnvironment(environment, springApplication); defaultPropertySource = propertySources.get("defaultProperties"); Object dubboApplicationName = defaultPropertySource.getProperty("dubbo.application.name"); Assert.assertEquals("demo-dubbo-application", dubboApplicationName); // Case 3 : Only set property "dubbo.application.name" // Reset environment environment = new MockEnvironment(); propertySources = environment.getPropertySources(); environment.setProperty("dubbo.application.name", "demo-dubbo-application"); instance.postProcessEnvironment(environment, springApplication); defaultPropertySource = propertySources.get("defaultProperties"); Assert.assertNotNull(defaultPropertySource); dubboApplicationName = environment.getProperty("dubbo.application.name"); Assert.assertEquals("demo-dubbo-application", dubboApplicationName); // Case 4 : If "defaultProperties" PropertySource is present in PropertySources // Reset environment environment = new MockEnvironment(); propertySources = environment.getPropertySources(); propertySources.addLast(new MapPropertySource("defaultProperties", new HashMap<String, Object>())); environment.setProperty("spring.application.name", "demo-dubbo-application"); instance.postProcessEnvironment(environment, springApplication); defaultPropertySource = propertySources.get("defaultProperties"); dubboApplicationName = defaultPropertySource.getProperty("dubbo.application.name"); Assert.assertEquals("demo-dubbo-application", dubboApplicationName); // Case 5 : Reset dubbo.config.multiple and dubbo.application.qos-enable environment = new MockEnvironment(); propertySources = environment.getPropertySources(); propertySources.addLast(new MapPropertySource("defaultProperties", new HashMap<String, Object>())); environment.setProperty("dubbo.config.multiple", "false"); environment.setProperty("dubbo.application.qos-enable", "false"); instance.postProcessEnvironment(environment, springApplication); Assert.assertEquals("false", environment.getProperty("dubbo.config.multiple")); Assert.assertEquals("false", environment.getProperty("dubbo.application.qos-enable")); } }
7,690
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/DubboAutoConfigurationOnSingleConfigTest.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.autoconfigure; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConsumerConfig; import org.apache.dubbo.config.ModuleConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; /** * {@link DubboAutoConfiguration} Test On single Dubbo Configuration * * @since 2.7.0 */ @RunWith(SpringRunner.class) @TestPropertySource( properties = { "dubbo.application.name = dubbo-demo-single-application", "dubbo.module.name = dubbo-demo-module", "dubbo.registry.address = test://192.168.99.100:32770", "dubbo.protocol.name=dubbo", "dubbo.protocol.port=20880", "dubbo.monitor.address=test://127.0.0.1:32770", "dubbo.provider.host=127.0.0.1", "dubbo.consumer.client=netty" }) @SpringBootTest(classes = {DubboAutoConfigurationOnSingleConfigTest.class}) @EnableAutoConfiguration @ComponentScan public class DubboAutoConfigurationOnSingleConfigTest { @Autowired private ApplicationConfig applicationConfig; @Autowired private ModuleConfig moduleConfig; @Autowired private RegistryConfig registryConfig; @Autowired private MonitorConfig monitorConfig; @Autowired private ProviderConfig providerConfig; @Autowired private ConsumerConfig consumerConfig; @Autowired private ProtocolConfig protocolConfig; @Before public void init() { DubboBootstrap.reset(); } @After public void destroy() { DubboBootstrap.reset(); } @Test public void testSingleConfig() { // application Assert.assertEquals("dubbo-demo-single-application", applicationConfig.getName()); // module Assert.assertEquals("dubbo-demo-module", moduleConfig.getName()); // registry Assert.assertEquals("test://192.168.99.100:32770", registryConfig.getAddress()); // monitor Assert.assertEquals("test://127.0.0.1:32770", monitorConfig.getAddress()); // protocol Assert.assertEquals("dubbo", protocolConfig.getName()); Assert.assertEquals(Integer.valueOf(20880), protocolConfig.getPort()); // consumer Assert.assertEquals("netty", consumerConfig.getClient()); // provider Assert.assertEquals("127.0.0.1", providerConfig.getHost()); } }
7,691
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/CompatibleDubboAutoConfigurationTestWithoutProperties.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.autoconfigure; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor; import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor; import org.apache.dubbo.config.spring.util.DubboBeanUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.test.context.junit4.SpringRunner; /** * {@link DubboAutoConfiguration} Test * * @see DubboAutoConfiguration */ @RunWith(SpringRunner.class) @SpringBootTest( classes = CompatibleDubboAutoConfigurationTestWithoutProperties.class, properties = {"dubbo.application.name=demo"}) @EnableAutoConfiguration public class CompatibleDubboAutoConfigurationTestWithoutProperties { @Autowired(required = false) private ServiceAnnotationPostProcessor serviceAnnotationPostProcessor; @Autowired private ApplicationContext applicationContext; @Before public void init() { DubboBootstrap.reset(); } @After public void destroy() { DubboBootstrap.reset(); } @Test public void testBeans() { Assert.assertNull(serviceAnnotationPostProcessor); ReferenceAnnotationBeanPostProcessor referenceAnnotationBeanPostProcessor = DubboBeanUtils.getReferenceAnnotationBeanPostProcessor(applicationContext); Assert.assertNotNull(referenceAnnotationBeanPostProcessor); } }
7,692
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/DubboAutoConfigurationOnMultipleConfigTest.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.autoconfigure; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConsumerConfig; import org.apache.dubbo.config.ModuleConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; /** * {@link DubboAutoConfiguration} Test On multiple Dubbo Configuration * * @since 2.7.0 */ @RunWith(SpringRunner.class) @TestPropertySource( properties = { "dubbo.applications.application1.name=dubbo-demo-multi-application", "dubbo.modules.module1.name=dubbo-demo-module", "dubbo.registries.registry1.address=test://192.168.99.100:32770", "dubbo.protocols.protocol1.name=dubbo", "dubbo.protocols.protocol1.port=20880", "dubbo.monitors.monitor1.address=test://127.0.0.1:32770", "dubbo.providers.provider1.host=127.0.0.1", "dubbo.consumers.consumer1.client=netty", "dubbo.config.multiple=true", "dubbo.scan.basePackages=org.apache.dubbo.spring.boot.dubbo, org.apache.dubbo.spring.boot.condition" }) @SpringBootTest(classes = {DubboAutoConfigurationOnMultipleConfigTest.class}) @EnableAutoConfiguration @ComponentScan public class DubboAutoConfigurationOnMultipleConfigTest { /** * @see TestBeansConfiguration */ @Autowired @Qualifier("application1") ApplicationConfig application; @Autowired @Qualifier("module1") ModuleConfig module; @Autowired @Qualifier("registry1") RegistryConfig registry; @Autowired @Qualifier("monitor1") MonitorConfig monitor; @Autowired @Qualifier("protocol1") ProtocolConfig protocol; @Autowired @Qualifier("consumer1") ConsumerConfig consumer; @Autowired @Qualifier("provider1") ProviderConfig provider; @Before public void init() { DubboBootstrap.reset(); } @After public void destroy() { DubboBootstrap.reset(); } @Test public void testMultiConfig() { // application Assert.assertEquals("dubbo-demo-multi-application", application.getName()); // module Assert.assertEquals("dubbo-demo-module", module.getName()); // registry Assert.assertEquals("test://192.168.99.100:32770", registry.getAddress()); Assert.assertEquals("test", registry.getProtocol()); Assert.assertEquals(Integer.valueOf(32770), registry.getPort()); // monitor Assert.assertEquals("test://127.0.0.1:32770", monitor.getAddress()); // protocol Assert.assertEquals("dubbo", protocol.getName()); Assert.assertEquals(Integer.valueOf(20880), protocol.getPort()); // consumer Assert.assertEquals("netty", consumer.getClient()); // provider Assert.assertEquals("127.0.0.1", provider.getHost()); } }
7,693
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/TestBeansConfiguration.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.autoconfigure; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConsumerConfig; import org.apache.dubbo.config.ModuleConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.RegistryConfig; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class TestBeansConfiguration { @Bean ApplicationConfig application1() { ApplicationConfig config = new ApplicationConfig(); config.setId("application1"); return config; } @Bean ModuleConfig module1() { ModuleConfig config = new ModuleConfig(); config.setId("module1"); return config; } @Bean RegistryConfig registry1() { RegistryConfig config = new RegistryConfig(); config.setId("registry1"); return config; } @Bean MonitorConfig monitor1() { MonitorConfig config = new MonitorConfig(); config.setId("monitor1"); return config; } @Bean ProtocolConfig protocol1() { ProtocolConfig config = new ProtocolConfig(); config.setId("protocol1"); return config; } @Bean ConsumerConfig consumer1() { ConsumerConfig config = new ConsumerConfig(); config.setId("consumer1"); return config; } @Bean ProviderConfig provider1() { ProviderConfig config = new ProviderConfig(); config.setId("provider1"); return config; } }
7,694
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/RelaxedDubboConfigBinderTest.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.autoconfigure; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import java.util.Map; import com.alibaba.spring.context.config.ConfigurationBeanBinder; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import static com.alibaba.spring.util.PropertySourcesUtils.getSubProperties; /** * {@link RelaxedDubboConfigBinder} Test */ @RunWith(SpringRunner.class) @TestPropertySource( properties = { "dubbo.application.NAME=hello", "dubbo.application.owneR=world", "dubbo.registry.Address=10.20.153.17", "dubbo.protocol.pORt=20881", "dubbo.service.invoke.timeout=2000", }) @ContextConfiguration(classes = RelaxedDubboConfigBinder.class) public class RelaxedDubboConfigBinderTest { @Autowired private ConfigurationBeanBinder dubboConfigBinder; @Autowired private ConfigurableEnvironment environment; @Before public void init() { DubboBootstrap.reset(); } @After public void destroy() { DubboBootstrap.reset(); } @Test public void testBinder() { ApplicationConfig applicationConfig = new ApplicationConfig(); Map<String, Object> properties = getSubProperties(environment.getPropertySources(), "dubbo.application"); dubboConfigBinder.bind(properties, true, true, applicationConfig); Assert.assertEquals("hello", applicationConfig.getName()); Assert.assertEquals("world", applicationConfig.getOwner()); RegistryConfig registryConfig = new RegistryConfig(); properties = getSubProperties(environment.getPropertySources(), "dubbo.registry"); dubboConfigBinder.bind(properties, true, true, registryConfig); Assert.assertEquals("10.20.153.17", registryConfig.getAddress()); ProtocolConfig protocolConfig = new ProtocolConfig(); properties = getSubProperties(environment.getPropertySources(), "dubbo.protocol"); dubboConfigBinder.bind(properties, true, true, protocolConfig); Assert.assertEquals(Integer.valueOf(20881), protocolConfig.getPort()); } }
7,695
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/test/java/org/apache/dubbo/spring/boot/autoconfigure/CompatibleDubboAutoConfigurationTest.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.autoconfigure; import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor; import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor; import org.apache.dubbo.config.spring.util.DubboBeanUtils; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.PropertySource; import org.springframework.test.context.junit4.SpringRunner; /** * {@link DubboAutoConfiguration} Test * @see DubboAutoConfiguration */ @RunWith(SpringRunner.class) @SpringBootTest( classes = {CompatibleDubboAutoConfigurationTest.class}, properties = {"dubbo.scan.base-packages = org.apache.dubbo.spring.boot.autoconfigure"}) @EnableAutoConfiguration @PropertySource(value = "classpath:/META-INF/dubbo.properties") public class CompatibleDubboAutoConfigurationTest { @Autowired private ObjectProvider<ServiceAnnotationPostProcessor> serviceAnnotationPostProcessor; @Autowired private ApplicationContext applicationContext; @Test public void testBeans() { Assert.assertNotNull(serviceAnnotationPostProcessor); Assert.assertNotNull(serviceAnnotationPostProcessor.getIfAvailable()); ReferenceAnnotationBeanPostProcessor referenceAnnotationBeanPostProcessor = DubboBeanUtils.getReferenceAnnotationBeanPostProcessor(applicationContext); Assert.assertNotNull(referenceAnnotationBeanPostProcessor); } }
7,696
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/context/DubboApplicationContextInitializer.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.context; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.Ordered; /** * Dubbo {@link ApplicationContextInitializer} implementation * * @see ApplicationContextInitializer * @since 2.7.1 */ public class DubboApplicationContextInitializer implements ApplicationContextInitializer, Ordered { @Override public void initialize(ConfigurableApplicationContext applicationContext) { overrideBeanDefinitions(applicationContext); } private void overrideBeanDefinitions(ConfigurableApplicationContext applicationContext) { // @since 2.7.8 OverrideBeanDefinitionRegistryPostProcessor has been removed // applicationContext.addBeanFactoryPostProcessor(new OverrideBeanDefinitionRegistryPostProcessor()); // @since 2.7.5 DubboConfigBeanDefinitionConflictProcessor has been removed // @see {@link DubboConfigBeanDefinitionConflictApplicationListener} // applicationContext.addBeanFactoryPostProcessor(new DubboConfigBeanDefinitionConflictProcessor()); // TODO Add some components in the future ( after 2.7.8 ) } @Override public int getOrder() { return HIGHEST_PRECEDENCE; } }
7,697
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/context
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/context/event/AwaitingNonWebApplicationListener.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.context.event; import org.apache.dubbo.common.lang.ShutdownHookCallbacks; import org.apache.dubbo.config.spring.util.DubboBeanUtils; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.context.event.ApplicationFailedEvent; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.event.ContextClosedEvent; import org.springframework.context.event.SmartApplicationListener; import org.springframework.util.ClassUtils; import static java.util.concurrent.Executors.newSingleThreadExecutor; import static org.springframework.util.ObjectUtils.containsElement; /** * Awaiting Non-Web Spring Boot {@link ApplicationListener} * * @since 2.7.0 */ public class AwaitingNonWebApplicationListener implements SmartApplicationListener { private static final String[] WEB_APPLICATION_CONTEXT_CLASSES = new String[] { "org.springframework.web.context.WebApplicationContext", "org.springframework.boot.web.reactive.context.ReactiveWebApplicationContext" }; private static final Logger logger = LoggerFactory.getLogger(AwaitingNonWebApplicationListener.class); private static final Class<? extends ApplicationEvent>[] SUPPORTED_APPLICATION_EVENTS = of(ApplicationReadyEvent.class, ContextClosedEvent.class); private final AtomicBoolean awaited = new AtomicBoolean(false); private static final Integer UNDEFINED_ID = Integer.valueOf(-1); /** * Target the application id */ private final AtomicInteger applicationContextId = new AtomicInteger(UNDEFINED_ID); private final Lock lock = new ReentrantLock(); private final Condition condition = lock.newCondition(); private final ExecutorService executorService = newSingleThreadExecutor(); private static <T> T[] of(T... values) { return values; } AtomicBoolean getAwaited() { return awaited; } @Override public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) { return containsElement(SUPPORTED_APPLICATION_EVENTS, eventType); } @Override public boolean supportsSourceType(Class<?> sourceType) { return true; } @Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ApplicationReadyEvent) { onApplicationReadyEvent((ApplicationReadyEvent) event); } if (event instanceof ApplicationFailedEvent) { awaitAndRelease(((ApplicationFailedEvent) event).getApplicationContext()); } } @Override public int getOrder() { return LOWEST_PRECEDENCE; } protected void onApplicationReadyEvent(ApplicationReadyEvent event) { final ConfigurableApplicationContext applicationContext = event.getApplicationContext(); if (!isRootApplicationContext(applicationContext) || isWebApplication(applicationContext)) { return; } if (applicationContextId.compareAndSet(UNDEFINED_ID, applicationContext.hashCode())) { awaitAndRelease(event.getApplicationContext()); } } private void awaitAndRelease(ConfigurableApplicationContext applicationContext) { await(); releaseOnExit(applicationContext); } /** * @param applicationContext * @since 2.7.8 */ private void releaseOnExit(ConfigurableApplicationContext applicationContext) { ApplicationModel applicationModel = DubboBeanUtils.getApplicationModel(applicationContext); if (applicationModel == null) { return; } ShutdownHookCallbacks shutdownHookCallbacks = applicationModel.getBeanFactory().getBean(ShutdownHookCallbacks.class); if (shutdownHookCallbacks != null) { shutdownHookCallbacks.addCallback(this::release); } } private boolean isRootApplicationContext(ApplicationContext applicationContext) { return applicationContext.getParent() == null; } private boolean isWebApplication(ApplicationContext applicationContext) { boolean webApplication = false; for (String contextClass : WEB_APPLICATION_CONTEXT_CLASSES) { if (isAssignable(contextClass, applicationContext.getClass(), applicationContext.getClassLoader())) { webApplication = true; break; } } return webApplication; } private static boolean isAssignable(String target, Class<?> type, ClassLoader classLoader) { try { return ClassUtils.resolveClassName(target, classLoader).isAssignableFrom(type); } catch (Throwable ex) { return false; } } protected void await() { // has been waited, return immediately if (awaited.get()) { return; } if (!executorService.isShutdown()) { executorService.execute(() -> executeMutually(() -> { while (!awaited.get()) { if (logger.isInfoEnabled()) { logger.info(" [Dubbo] Current Spring Boot Application is await..."); } try { condition.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } })); } } protected void release() { executeMutually(() -> { while (awaited.compareAndSet(false, true)) { if (logger.isInfoEnabled()) { logger.info(" [Dubbo] Current Spring Boot Application is about to shutdown..."); } condition.signalAll(); // @since 2.7.8 method shutdown() is combined into the method release() shutdown(); } }); } private void shutdown() { if (!executorService.isShutdown()) { // Shutdown executorService executorService.shutdown(); } } private void executeMutually(Runnable runnable) { try { lock.lock(); runnable.run(); } finally { lock.unlock(); } } }
7,698
0
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/context
Create_ds/dubbo/dubbo-spring-boot/dubbo-spring-boot-compatible/autoconfigure/src/main/java/org/apache/dubbo/spring/boot/context/event/WelcomeLogoApplicationListener.java
/* * 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 * * 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 org.apache.dubbo.spring.boot.context.event; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import java.util.concurrent.atomic.AtomicBoolean; import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; import org.springframework.context.ApplicationListener; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_GITHUB_URL; import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_MAILING_LIST; import static org.apache.dubbo.spring.boot.util.DubboUtils.LINE_SEPARATOR; /** * Dubbo Welcome Logo {@link ApplicationListener} * * @see ApplicationListener * @since 2.7.0 */ @Order(Ordered.HIGHEST_PRECEDENCE + 20 + 1) // After LoggingApplicationListener#DEFAULT_ORDER public class WelcomeLogoApplicationListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> { private static AtomicBoolean processed = new AtomicBoolean(false); @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { // Skip if processed before, prevent duplicated execution in Hierarchical ApplicationContext if (processed.get()) { return; } /** * Gets Logger After LoggingSystem configuration ready * @see LoggingApplicationListener */ final Logger logger = LoggerFactory.getLogger(getClass()); String bannerText = buildBannerText(); if (logger.isInfoEnabled()) { logger.info(bannerText); } else { System.out.print(bannerText); } // mark processed to be true processed.compareAndSet(false, true); } String buildBannerText() { StringBuilder bannerTextBuilder = new StringBuilder(); bannerTextBuilder .append(LINE_SEPARATOR) .append(LINE_SEPARATOR) .append(" :: Dubbo (v") .append(Version.getVersion()) .append(") : ") .append(DUBBO_GITHUB_URL) .append(LINE_SEPARATOR) .append(" :: Discuss group : ") .append(DUBBO_MAILING_LIST) .append(LINE_SEPARATOR); return bannerTextBuilder.toString(); } }
7,699