) Class.forName(providerClass);
provider = clazz.getConstructor().newInstance();
} else {
logger.info("Using default metrics provider (logs to org.hyperledger.Performance)");
provider = new DefaultProvider();
}
- } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
- | NoSuchMethodException | SecurityException e) {
+ } catch (ClassNotFoundException
+ | InstantiationException
+ | IllegalAccessException
+ | IllegalArgumentException
+ | InvocationTargetException
+ | NoSuchMethodException
+ | SecurityException e) {
throw new RuntimeException("Unable to start metrics", e);
}
} else {
// return a 'null' provider
logger.info("Metrics disabled");
provider = new NullProvider();
-
}
provider.initialize(props);
return provider;
}
- /**
- *
- * @return MetricsProvider
- */
+ /** @return MetricsProvider */
public static MetricsProvider getProvider() {
if (provider == null) {
throw new IllegalStateException("No provider set, this should have been set");
}
return provider;
}
-
}
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/MetricsProvider.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/MetricsProvider.java
index 482fbbdf..9609ea87 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/MetricsProvider.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/MetricsProvider.java
@@ -9,20 +9,16 @@
import java.util.Properties;
/**
- * Interface to be implemented to send metrics on the chaincode to the
- * 'backend-of-choice'.
+ * Interface to be implemented to send metrics on the chaincode to the 'backend-of-choice'.
*
- * An instance of this will be created, and provided with the resources from
- * which chaincode specific metrics can be collected. (via the no-argument
- * constructor).
+ * An instance of this will be created, and provided with the resources from which chaincode specific metrics can be
+ * collected. (via the no-argument constructor).
*
- * The choice of when, where and what to collect etc are within the remit of the
- * provider.
+ *
The choice of when, where and what to collect etc are within the remit of the provider.
*
- * This is the effective call sequence.
+ *
This is the effective call sequence.
*
- * MyMetricsProvider mmp = new MyMetricsProvider()
- * mmp.initialize(props_from_environment); // short while later....
+ *
MyMetricsProvider mmp = new MyMetricsProvider() mmp.initialize(props_from_environment); // short while later....
* mmp.setTaskMetricsCollector(taskService);
*/
public interface MetricsProvider {
@@ -32,17 +28,15 @@ public interface MetricsProvider {
*
* @param props
*/
- default void initialize(final Properties props) {
- };
+ default void initialize(final Properties props) {}
+ ;
/**
- * Pass a reference to this task service for information gathering. This is
- * related specifically to the handling of tasks within the chaincode. i.e. how
- * individual transactions are dispatched for execution.
+ * Pass a reference to this task service for information gathering. This is related specifically to the handling of
+ * tasks within the chaincode. i.e. how individual transactions are dispatched for execution.
*
* @param taskService
*/
- default void setTaskMetricsCollector(final TaskMetricsCollector taskService) {
- };
-
+ default void setTaskMetricsCollector(final TaskMetricsCollector taskService) {}
+ ;
}
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/TaskMetricsCollector.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/TaskMetricsCollector.java
index bb2c6065..ef59d6a4 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/TaskMetricsCollector.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/TaskMetricsCollector.java
@@ -8,11 +8,9 @@
/**
* Collect metrics relating to the task execution.
*
- * The task execution (of which each fabric transaction is one) is backed by a
- * thread pool that implements this interface. As that is an implementation
- * class this interface abstracts the information available from it (as far as
+ *
The task execution (of which each fabric transaction is one) is backed by a thread pool that implements this
+ * interface. As that is an implementation class this interface abstracts the information available from it (as far as
* metrics go).
- *
*/
public interface TaskMetricsCollector {
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/DefaultProvider.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/DefaultProvider.java
index a2dc8a78..841e4164 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/DefaultProvider.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/DefaultProvider.java
@@ -9,24 +9,17 @@
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;
-
import org.hyperledger.fabric.Logging;
import org.hyperledger.fabric.metrics.MetricsProvider;
import org.hyperledger.fabric.metrics.TaskMetricsCollector;
-/**
- * Simple default provider that logs to the org.hyperledger.Performance logger
- * the basic metrics.
- *
- */
+/** Simple default provider that logs to the org.hyperledger.Performance logger the basic metrics. */
public final class DefaultProvider implements MetricsProvider {
private static Logger perflogger = Logger.getLogger(Logging.PERFLOGGER);
private TaskMetricsCollector taskService;
- /**
- *
- */
+ /** */
public DefaultProvider() {
perflogger.info("Default Metrics Provider started");
}
@@ -41,13 +34,15 @@ public void setTaskMetricsCollector(final TaskMetricsCollector taskService) {
@Override
public void initialize(final Properties props) {
final Timer metricTimer = new Timer(true);
- metricTimer.scheduleAtFixedRate(new TimerTask() {
- @Override
- public void run() {
- DefaultProvider.this.logMetrics();
- }
- }, 0, TIME_INTERVAL);
-
+ metricTimer.scheduleAtFixedRate(
+ new TimerTask() {
+ @Override
+ public void run() {
+ DefaultProvider.this.logMetrics();
+ }
+ },
+ 0,
+ TIME_INTERVAL);
}
protected void logMetrics() {
@@ -58,14 +53,18 @@ protected void logMetrics() {
}
final StringBuilder sb = new StringBuilder();
sb.append('{');
- sb.append(String.format(" \"active_count\":%d ", DefaultProvider.this.taskService.getActiveCount())).append(',');
- sb.append(String.format(" \"pool_size\":%d ", DefaultProvider.this.taskService.getPoolSize())).append(',');
- sb.append(String.format(" \"core_pool_size\":%d ", DefaultProvider.this.taskService.getCorePoolSize())).append(',');
- sb.append(String.format(" \"current_task_count\":%d ", DefaultProvider.this.taskService.getCurrentTaskCount())).append(',');
- sb.append(String.format(" \"current_queue_depth\":%d ", DefaultProvider.this.taskService.getCurrentQueueCount()));
+ sb.append(String.format(" \"active_count\":%d ", DefaultProvider.this.taskService.getActiveCount()))
+ .append(',');
+ sb.append(String.format(" \"pool_size\":%d ", DefaultProvider.this.taskService.getPoolSize()))
+ .append(',');
+ sb.append(String.format(" \"core_pool_size\":%d ", DefaultProvider.this.taskService.getCorePoolSize()))
+ .append(',');
+ sb.append(String.format(
+ " \"current_task_count\":%d ", DefaultProvider.this.taskService.getCurrentTaskCount()))
+ .append(',');
+ sb.append(String.format(
+ " \"current_queue_depth\":%d ", DefaultProvider.this.taskService.getCurrentQueueCount()));
return sb.append('}').toString();
});
-
}
-
}
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/NullProvider.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/NullProvider.java
index f977ac67..19639009 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/NullProvider.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/NullProvider.java
@@ -7,17 +7,9 @@
import org.hyperledger.fabric.metrics.MetricsProvider;
-/**
- * Very simple provider that does absolutely nothing. Used when metrics are
- * disabled.
- *
- */
+/** Very simple provider that does absolutely nothing. Used when metrics are disabled. */
public class NullProvider implements MetricsProvider {
- /**
- *
- */
- public NullProvider() {
- }
-
+ /** */
+ public NullProvider() {}
}
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/package-info.java
index 30152965..59afe468 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/package-info.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/impl/package-info.java
@@ -4,7 +4,5 @@
* SPDX-License-Identifier: Apache-2.0
*/
-/**
- *
- */
+/** */
package org.hyperledger.fabric.metrics.impl;
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/package-info.java
index ec9d196a..f9cf1f7b 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/package-info.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/metrics/package-info.java
@@ -7,24 +7,17 @@
/**
* Provides interfaces and classes to support collection of metrics.
*
- *
- * The main metrics that are available are the statistics around the number of
- * tasks that are running, and how the thread pool is handling these.
+ *
The main metrics that are available are the statistics around the number of tasks that are running, and how the
+ * thread pool is handling these.
*
- *
- * Note a 'task' is a message from the Peer to the Chaincode - this message is
- * either a new transaction, or a response from a stub API, eg getState(). Query
- * apis may return more than one response.
+ *
Note a 'task' is a message from the Peer to the Chaincode - this message is either a new transaction, or a
+ * response from a stub API, eg getState(). Query apis may return more than one response.
*
- *
- * To enable metrics, add a CHAINCODE_METRICS_ENABLED=true
setting
- * to the config.props
chaincode configuration file.
- * See the Overview for details of how to
- * configure chaincode.
+ *
To enable metrics, add a CHAINCODE_METRICS_ENABLED=true
setting to the config.props
+ * chaincode configuration file. See the Overview for details of how to configure
+ * chaincode.
*
- *
Open Telemetry
- *
- * To use Open Telemetry, set the following properties:
+ * Open Telemetry To use Open Telemetry, set the following properties:
*
*
* CHAINCODE_METRICS_ENABLED=true
@@ -34,7 +27,8 @@
* Additionally, you can set properties after the specification:
* https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/sdk-environment-variables.md
*
- * Example:
+ * Example:
+ *
*
* OTEL_EXPORTER_OTLP_ENDPOINT=otelcollector:4317
* OTEL_EXPORTER_OTLP_INSECURE=true
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/package-info.java
index cb5d58f6..dfeb5e02 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/package-info.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/package-info.java
@@ -4,7 +4,5 @@
* SPDX-License-Identifier: Apache-2.0
*/
-/**
- * Provides logging classes.
- */
+/** Provides logging classes. */
package org.hyperledger.fabric;
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/Chaincode.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/Chaincode.java
index 046595df..b8882487 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/Chaincode.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/Chaincode.java
@@ -11,13 +11,11 @@
import java.util.HashMap;
import java.util.Map;
-/**
- * Defines methods that all chaincodes must implement.
- */
+/** Defines methods that all chaincodes must implement. */
public interface Chaincode {
/**
- * Called during an instantiate transaction after the container has been
- * established, allowing the chaincode to initialize its internal data.
+ * Called during an instantiate transaction after the container has been established, allowing the chaincode to
+ * initialize its internal data.
*
* @param stub the chaincode stub
* @return the chaincode response
@@ -25,8 +23,7 @@ public interface Chaincode {
Response init(ChaincodeStub stub);
/**
- * Called for every Invoke transaction. The chaincode may change its state
- * variables.
+ * Called for every Invoke transaction. The chaincode may change its state variables.
*
* @param stub the chaincode stub
* @return the chaincode response
@@ -34,9 +31,8 @@ public interface Chaincode {
Response invoke(ChaincodeStub stub);
/**
- * Wrapper around protobuf Response, contains status, message and payload.
- * Object returned by call to {@link #init(ChaincodeStub)}
- * and{@link #invoke(ChaincodeStub)}
+ * Wrapper around protobuf Response, contains status, message and payload. Object returned by call to
+ * {@link #init(ChaincodeStub)} and{@link #invoke(ChaincodeStub)}
*/
class Response {
private final int statusCode;
@@ -45,6 +41,7 @@ class Response {
/**
* Constructor.
+ *
* @param status a status object.
* @param message a response message.
* @param payload a response payload.
@@ -57,6 +54,7 @@ public Response(final Status status, final String message, final byte[] payload)
/**
* Constructor.
+ *
* @param statusCode a status code.
* @param message a response message.
* @param payload a response payload.
@@ -69,6 +67,7 @@ public Response(final int statusCode, final String message, final byte[] payload
/**
* Get the response status.
+ *
* @return status.
*/
public Status getStatus() {
@@ -81,6 +80,7 @@ public Status getStatus() {
/**
* Get the response status code.
+ *
* @return status code.
*/
public int getStatusCode() {
@@ -89,6 +89,7 @@ public int getStatusCode() {
/**
* Get the response message.
+ *
* @return a message.
*/
public String getMessage() {
@@ -97,6 +98,7 @@ public String getMessage() {
/**
* Get the response payload.
+ *
* @return payload bytes.
*/
public byte[] getPayload() {
@@ -105,27 +107,20 @@ public byte[] getPayload() {
/**
* Get the response payload as a UTF-8 string.
+ *
* @return a string.
*/
public String getStringPayload() {
return (payload == null) ? null : new String(payload, UTF_8);
}
- /**
- * {@link Response} status enum.
- */
+ /** {@link Response} status enum. */
public enum Status {
- /**
- * Successful response status.
- */
+ /** Successful response status. */
SUCCESS(200),
- /**
- * Minimum threshold for as error status code.
- */
+ /** Minimum threshold for as error status code. */
ERROR_THRESHOLD(400),
- /**
- * Server-side error status.
- */
+ /** Server-side error status. */
INTERNAL_SERVER_ERROR(500);
private static final Map CODETOSTATUS = new HashMap<>();
@@ -137,6 +132,7 @@ public enum Status {
/**
* Get the status code associated with this status object.
+ *
* @return a status code.
*/
public int getCode() {
@@ -145,6 +141,7 @@ public int getCode() {
/**
* Get a status object for a given status code.
+ *
* @param code a status code.
* @return a status object.
*/
@@ -158,6 +155,7 @@ public static Status forCode(final int code) {
/**
* Whether a status exists for a given status code.
+ *
* @param code a status code.
* @return True if a status for the code exists; otherwise false.
*/
@@ -170,8 +168,6 @@ public static boolean hasStatusForCode(final int code) {
CODETOSTATUS.put(status.code, status);
}
}
-
}
-
}
}
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeBase.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeBase.java
index da8da55e..0ce76bc4 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeBase.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeBase.java
@@ -9,6 +9,14 @@
import static java.lang.String.format;
import static java.util.logging.Level.ALL;
+import com.google.protobuf.InvalidProtocolBufferException;
+import com.google.protobuf.util.JsonFormat;
+import io.grpc.ManagedChannelBuilder;
+import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
+import io.grpc.netty.shaded.io.grpc.netty.NegotiationType;
+import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder;
+import io.grpc.netty.shaded.io.netty.handler.ssl.SslContext;
+import io.grpc.stub.StreamObserver;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
@@ -26,10 +34,6 @@
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
-
-import com.google.protobuf.InvalidProtocolBufferException;
-import com.google.protobuf.util.JsonFormat;
-
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
@@ -43,35 +47,21 @@
import org.hyperledger.fabric.shim.impl.InvocationTaskManager;
import org.hyperledger.fabric.traces.Traces;
-import io.grpc.ManagedChannelBuilder;
-import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
-import io.grpc.netty.shaded.io.grpc.netty.NegotiationType;
-import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder;
-import io.grpc.netty.shaded.io.netty.handler.ssl.SslContext;
-import io.grpc.stub.StreamObserver;
-
/**
* Abstract implementation of {@link Chaincode}.
*
- *
- * All chaincode implementations must extend the abstract class
- * ChaincodeBase
. It is possible to implement chaincode by
- * extending ChaincodeBase
directly however new projects should
- * implement {@link org.hyperledger.fabric.contract.ContractInterface} and use
- * the contract programming model instead.
+ *
All chaincode implementations must extend the abstract class ChaincodeBase
. It is possible to
+ * implement chaincode by extending ChaincodeBase
directly however new projects should implement
+ * {@link org.hyperledger.fabric.contract.ContractInterface} and use the contract programming model instead.
*
* @see org.hyperledger.fabric.contract
*/
public abstract class ChaincodeBase implements Chaincode {
- /**
- *
- */
+ /** */
public static final String CORE_CHAINCODE_LOGGING_SHIM = "CORE_CHAINCODE_LOGGING_SHIM";
- /**
- *
- */
+ /** */
public static final String CORE_CHAINCODE_LOGGING_LEVEL = "CORE_CHAINCODE_LOGGING_LEVEL";
@Override
@@ -82,19 +72,13 @@ public abstract class ChaincodeBase implements Chaincode {
private static final Logger LOGGER = Logger.getLogger(ChaincodeBase.class.getName());
- /**
- *
- */
+ /** */
public static final String DEFAULT_HOST = "127.0.0.1";
- /**
- *
- */
+ /** */
public static final int DEFAULT_PORT = 7051;
- /**
- * Default to 100MB for maximum inbound grpc message size.
- */
+ /** Default to 100MB for maximum inbound grpc message size. */
public static final String DEFAULT_MAX_INBOUND_MESSAGE_SIZE = "104857600";
private String host = DEFAULT_HOST;
@@ -132,10 +116,10 @@ private int getMaxInboundMessageSize() {
if (this.props == null) {
throw new IllegalStateException("Chaincode config not available");
}
- final int maxMsgSize = Integer
- .parseInt(this.props.getProperty(MAX_INBOUND_MESSAGE_SIZE, DEFAULT_MAX_INBOUND_MESSAGE_SIZE));
- final String msgSizeInfo = String.format("Maximum Inbound Message Size [%s] = %d", MAX_INBOUND_MESSAGE_SIZE,
- maxMsgSize);
+ final int maxMsgSize =
+ Integer.parseInt(this.props.getProperty(MAX_INBOUND_MESSAGE_SIZE, DEFAULT_MAX_INBOUND_MESSAGE_SIZE));
+ final String msgSizeInfo =
+ String.format("Maximum Inbound Message Size [%s] = %d", MAX_INBOUND_MESSAGE_SIZE, maxMsgSize);
LOGGER.info(msgSizeInfo);
return maxMsgSize;
}
@@ -145,7 +129,6 @@ private int getMaxInboundMessageSize() {
*
* @param args command line arguments
*/
-
public void start(final String[] args) {
try {
initializeLogging();
@@ -173,7 +156,8 @@ protected final void connectToPeer() throws IOException {
// This is then passed to the ChaincodeSupportClient to be connected to the
// gRPC streams
- final ChaincodeID chaincodeId = ChaincodeID.newBuilder().setName(this.id).build();
+ final ChaincodeID chaincodeId =
+ ChaincodeID.newBuilder().setName(this.id).build();
final ManagedChannelBuilder> channelBuilder = newChannelBuilder();
final ChaincodeSupportClient chaincodeSupportClient = new ChaincodeSupportClient(channelBuilder);
@@ -202,9 +186,9 @@ protected final void connectToPeer() throws IOException {
// for any error - shut everything down
// as this is long lived (well forever) then any completion means something
// has stopped in the peer or the network comms, so also shutdown
- final StreamObserver requestObserver = chaincodeSupportClient.getStub().register(
-
- new StreamObserver() {
+ final StreamObserver requestObserver = chaincodeSupportClient
+ .getStub()
+ .register(new StreamObserver() {
@Override
public void onNext(final ChaincodeMessage chaincodeMessage) {
// message off to the ITM...
@@ -225,24 +209,20 @@ public void onCompleted() {
LOGGER.severe("Chaincode stream is complete. Shutting down the chaincode stream.");
chaincodeSupportClient.shutdown(itm);
}
- }
-
- );
+ });
chaincodeSupportClient.start(itm, requestObserver);
-
}
/**
* connect external chaincode to peer for chat.
*
* @param requestObserver reqeust from peer
- * @return itm - The InnvocationTask Manager handles the message level
- * communication with the peer.
+ * @return itm - The InnvocationTask Manager handles the message level communication with the peer.
* @throws IOException validation fields exception
*/
- protected StreamObserver connectToPeer(
- final StreamObserver requestObserver) throws IOException {
+ protected StreamObserver connectToPeer(final StreamObserver requestObserver)
+ throws IOException {
validateOptions();
if (requestObserver == null) {
throw new IOException("StreamObserver 'requestObserver' for chat with peer can't be null");
@@ -256,7 +236,8 @@ protected StreamObserver connectToPeer(
// This is then passed to the ChaincodeSupportClient to be connected to the
// gRPC streams
- final ChaincodeID chaincodeId = ChaincodeID.newBuilder().setName(this.id).build();
+ final ChaincodeID chaincodeId =
+ ChaincodeID.newBuilder().setName(this.id).build();
final ManagedChannelBuilder> channelBuilder = newChannelBuilder();
final ChaincodeSupportClient chaincodeSupportClient = new ChaincodeSupportClient(channelBuilder);
@@ -288,8 +269,8 @@ public void onCompleted() {
protected final void initializeLogging() {
// the VM wide formatting string.
- System.setProperty("java.util.logging.SimpleFormatter.format",
- "%1$tH:%1$tM:%1$tS:%1$tL %4$-7.7s %2$-80.80s %5$s%6$s%n");
+ System.setProperty(
+ "java.util.logging.SimpleFormatter.format", "%1$tH:%1$tM:%1$tS:%1$tL %4$-7.7s %2$-80.80s %5$s%6$s%n");
final Logger rootLogger = Logger.getLogger("");
for (final java.util.logging.Handler handler : rootLogger.getHandlers()) {
@@ -300,7 +281,6 @@ protected final void initializeLogging() {
public synchronized String format(final LogRecord record) {
return Thread.currentThread() + " " + super.format(record);
}
-
});
}
@@ -322,33 +302,31 @@ public synchronized String format(final LogRecord record) {
final Level shimLogLevel = mapLevel(System.getenv(CORE_CHAINCODE_LOGGING_SHIM));
Logger.getLogger(ChaincodeBase.class.getPackage().getName()).setLevel(shimLogLevel);
Logger.getLogger(ContractRouter.class.getPackage().getName()).setLevel(chaincodeLogLevel);
-
}
private Level mapLevel(final String level) {
if (level != null) {
switch (level.toUpperCase().trim()) {
- case "CRITICAL":
- case "ERROR":
- return Level.SEVERE;
- case "WARNING":
- case "WARN":
- return Level.WARNING;
- case "INFO":
- return Level.INFO;
- case "NOTICE":
- return Level.CONFIG;
- case "DEBUG":
- return Level.FINEST;
- default:
- break;
+ case "CRITICAL":
+ case "ERROR":
+ return Level.SEVERE;
+ case "WARNING":
+ case "WARN":
+ return Level.WARNING;
+ case "INFO":
+ return Level.INFO;
+ case "NOTICE":
+ return Level.CONFIG;
+ case "DEBUG":
+ return Level.FINEST;
+ default:
+ break;
}
}
return Level.INFO;
}
-
private SocketAddress parseHostPort(final String hostAddrStr) throws URISyntaxException {
// WORKAROUND: add any scheme to make the resulting URI valid.
@@ -357,8 +335,7 @@ private SocketAddress parseHostPort(final String hostAddrStr) throws URISyntaxEx
int port = uri.getPort();
if (uri.getHost() == null || uri.getPort() == -1) {
- throw new URISyntaxException(uri.toString(),
- "URI must have host and port parts");
+ throw new URISyntaxException(uri.toString(), "URI must have host and port parts");
}
// validation succeeded
@@ -374,9 +351,7 @@ public boolean isServer() {
return !chaincodeServerAddress.isEmpty();
}
- /**
- * Validate init parameters from env chaincode base.
- */
+ /** Validate init parameters from env chaincode base. */
public void validateOptions() {
if (this.id == null || this.id.isEmpty()) {
throw new IllegalArgumentException(format(
@@ -435,12 +410,9 @@ protected final void processCommandLineOptions(final String[] args) {
LOGGER.info("<<<<<<<<<<<<>>>>>>>>>>>");
LOGGER.info("CORE_CHAINCODE_ID_NAME: " + this.id);
LOGGER.info("CORE_PEER_ADDRESS: " + this.host + ":" + this.port);
-
}
- /**
- * set fields from env.
- */
+ /** set fields from env. */
public final void processEnvironmentOptions() {
if (System.getenv().containsKey(CORE_CHAINCODE_ID_NAME)) {
@@ -492,9 +464,8 @@ public final void processEnvironmentOptions() {
}
/**
- * Obtains configuration specifically for running the chaincode and settable on
- * a per chaincode basis rather than taking properties from the Peers'
- * configuration.
+ * Obtains configuration specifically for running the chaincode and settable on a per chaincode basis rather than
+ * taking properties from the Peers' configuration.
*
* @return Configuration
*/
@@ -579,8 +550,10 @@ final SslContext createSSLContext() throws IOException {
final byte[] ckb = Files.readAllBytes(Paths.get(this.tlsClientKeyPath));
final byte[] ccb = Files.readAllBytes(Paths.get(this.tlsClientCertPath));
- return GrpcSslContexts.forClient().trustManager(new File(this.tlsClientRootCertPath))
- .keyManager(new ByteArrayInputStream(Base64.getDecoder().decode(ccb)),
+ return GrpcSslContexts.forClient()
+ .trustManager(new File(this.tlsClientRootCertPath))
+ .keyManager(
+ new ByteArrayInputStream(Base64.getDecoder().decode(ccb)),
new ByteArrayInputStream(Base64.getDecoder().decode(ckb)))
.build();
}
@@ -663,12 +636,9 @@ String getId() {
return id;
}
- /**
- * Chaincode State.
- */
+ /** Chaincode State. */
public enum CCState {
- /**
- * */
+ /** */
CREATED,
/** */
ESTABLISHED,
@@ -678,18 +648,12 @@ public enum CCState {
private CCState state = CCState.CREATED;
- /**
- *
- * @return State
- */
+ /** @return State */
public final CCState getState() {
return this.state;
}
- /**
- *
- * @param newState
- */
+ /** @param newState */
public final void setState(final CCState newState) {
this.state = newState;
}
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeException.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeException.java
index fe73b570..7a4b5312 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeException.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeException.java
@@ -8,18 +8,13 @@
import static java.nio.charset.StandardCharsets.UTF_8;
/**
- * Contracts should use {@code ChaincodeException} to indicate when an error
- * occurs in Smart Contract logic.
+ * Contracts should use {@code ChaincodeException} to indicate when an error occurs in Smart Contract logic.
*
- *
- * When a {@code ChaincodeException} is thrown an error response will be
- * returned from the chaincode container containing the exception message and
- * payload, if specified.
+ *
When a {@code ChaincodeException} is thrown an error response will be returned from the chaincode container
+ * containing the exception message and payload, if specified.
*
- *
- * {@code ChaincodeException} may be extended to provide application specific
- * error information. Subclasses should ensure that {@link #getPayload} returns
- * a serialized representation of the error in a suitable format for client
+ *
{@code ChaincodeException} may be extended to provide application specific error information. Subclasses should
+ * ensure that {@link #getPayload} returns a serialized representation of the error in a suitable format for client
* applications to process.
*/
public class ChaincodeException extends RuntimeException {
@@ -28,16 +23,13 @@ public class ChaincodeException extends RuntimeException {
private byte[] payload;
- /**
- * Constructs a new {@code ChaincodeException} with no detail message.
- */
+ /** Constructs a new {@code ChaincodeException} with no detail message. */
public ChaincodeException() {
super();
}
/**
- * Constructs a new {@code ChaincodeException} with the specified detail
- * message.
+ * Constructs a new {@code ChaincodeException} with the specified detail message.
*
* @param message the detail message.
*/
@@ -55,19 +47,17 @@ public ChaincodeException(final Throwable cause) {
}
/**
- * Constructs a new {@code ChaincodeException} with the specified detail message
- * and cause.
+ * Constructs a new {@code ChaincodeException} with the specified detail message and cause.
*
* @param message the detail message.
- * @param cause the cause.
+ * @param cause the cause.
*/
public ChaincodeException(final String message, final Throwable cause) {
super(message, cause);
}
/**
- * Constructs a new {@code ChaincodeException} with the specified detail message
- * and response payload.
+ * Constructs a new {@code ChaincodeException} with the specified detail message and response payload.
*
* @param message the detail message.
* @param payload the response payload.
@@ -79,12 +69,11 @@ public ChaincodeException(final String message, final byte[] payload) {
}
/**
- * Constructs a new {@code ChaincodeException} with the specified detail
- * message, response payload and cause.
+ * Constructs a new {@code ChaincodeException} with the specified detail message, response payload and cause.
*
* @param message the detail message.
* @param payload the response payload.
- * @param cause the cause.
+ * @param cause the cause.
*/
public ChaincodeException(final String message, final byte[] payload, final Throwable cause) {
super(message, cause);
@@ -93,8 +82,7 @@ public ChaincodeException(final String message, final byte[] payload, final Thro
}
/**
- * Constructs a new {@code ChaincodeException} with the specified detail message
- * and response payload.
+ * Constructs a new {@code ChaincodeException} with the specified detail message and response payload.
*
* @param message the detail message.
* @param payload the response payload.
@@ -106,12 +94,11 @@ public ChaincodeException(final String message, final String payload) {
}
/**
- * Constructs a new {@code ChaincodeException} with the specified detail
- * message, response payload and cause.
+ * Constructs a new {@code ChaincodeException} with the specified detail message, response payload and cause.
*
* @param message the detail message.
* @param payload the response payload.
- * @param cause the cause.
+ * @param cause the cause.
*/
public ChaincodeException(final String message, final String payload, final Throwable cause) {
super(message, cause);
@@ -122,12 +109,9 @@ public ChaincodeException(final String message, final String payload, final Thro
/**
* Returns the response payload or {@code null} if there is no response.
*
- *
- * The payload should represent the chaincode error in a way that client
- * applications written in different programming languages can interpret. For
- * example it could include a domain specific error code, in addition to any
- * state information which would allow client applications to respond
- * appropriately.
+ *
The payload should represent the chaincode error in a way that client applications written in different
+ * programming languages can interpret. For example it could include a domain specific error code, in addition to
+ * any state information which would allow client applications to respond appropriately.
*
* @return the response payload or {@code null} if there is no response.
*/
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeServer.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeServer.java
index 8c8ff2b3..81c7ce29 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeServer.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeServer.java
@@ -8,9 +8,7 @@
import java.io.IOException;
-/**
- * External chaincode server.
- */
+/** External chaincode server. */
public interface ChaincodeServer {
/**
@@ -21,9 +19,6 @@ public interface ChaincodeServer {
*/
void start() throws IOException, InterruptedException;
- /**
- * shutdown now grpc server.
- */
+ /** shutdown now grpc server. */
void stop();
-
}
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeServerProperties.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeServerProperties.java
index 27c84257..af81bfb7 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeServerProperties.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeServerProperties.java
@@ -22,28 +22,33 @@ public final class ChaincodeServerProperties {
private String trustCertCollectionFile;
private boolean tlsEnabled = false;
- /**
- * Constructor using default configuration.
- */
- public ChaincodeServerProperties() {
- }
+ /** Constructor using default configuration. */
+ public ChaincodeServerProperties() {}
/**
* Constructor.
+ *
* @param portChaincodeServer ignored.
* @param maxInboundMetadataSize the maximum metadata size allowed to be received by the server.
* @param maxInboundMessageSize the maximum message size allowed to be received by the server.
* @param maxConnectionAgeSeconds the maximum connection age in seconds.
* @param keepAliveTimeoutSeconds timeout for a keep-alive ping request in seconds.
- * @param permitKeepAliveTimeMinutes the most aggressive keep-alive time clients are permitted to configure in minutes.
+ * @param permitKeepAliveTimeMinutes the most aggressive keep-alive time clients are permitted to configure in
+ * minutes.
* @param keepAliveTimeMinutes delay before server sends a keep-alive in minutes.
- * @param permitKeepAliveWithoutCalls whether clients are allowed to send keep-alive HTTP/2 PINGs even if there are no outstanding RPCs on the connection.
+ * @param permitKeepAliveWithoutCalls whether clients are allowed to send keep-alive HTTP/2 PINGs even if there are
+ * no outstanding RPCs on the connection.
*/
// checkstyle:ignore-next-line:ParameterNumber
public ChaincodeServerProperties(
- final int portChaincodeServer, final int maxInboundMetadataSize, final int maxInboundMessageSize,
- final int maxConnectionAgeSeconds, final int keepAliveTimeoutSeconds, final int permitKeepAliveTimeMinutes,
- final int keepAliveTimeMinutes, final boolean permitKeepAliveWithoutCalls) {
+ final int portChaincodeServer,
+ final int maxInboundMetadataSize,
+ final int maxInboundMessageSize,
+ final int maxConnectionAgeSeconds,
+ final int keepAliveTimeoutSeconds,
+ final int permitKeepAliveTimeMinutes,
+ final int keepAliveTimeMinutes,
+ final boolean permitKeepAliveWithoutCalls) {
this.serverAddress = null;
this.maxInboundMetadataSize = maxInboundMetadataSize;
@@ -57,6 +62,7 @@ public ChaincodeServerProperties(
/**
* The maximum size of metadata allowed to be received.
+ *
* @return The maximum metadata size allowed.
*/
public int getMaxInboundMetadataSize() {
@@ -65,6 +71,7 @@ public int getMaxInboundMetadataSize() {
/**
* Sets the maximum metadata size allowed to be received by the server.
+ *
* @param maxInboundMetadataSize The new maximum size allowed for incoming metadata.
*/
public void setMaxInboundMetadataSize(final int maxInboundMetadataSize) {
@@ -73,6 +80,7 @@ public void setMaxInboundMetadataSize(final int maxInboundMetadataSize) {
/**
* The maximum message size allowed to be received by the server.
+ *
* @return the maximum message size allowed.
*/
public int getMaxInboundMessageSize() {
@@ -81,6 +89,7 @@ public int getMaxInboundMessageSize() {
/**
* Sets the maximum message size allowed to be received by the server.
+ *
* @param maxInboundMessageSize The new maximum size allowed for incoming messages.
*/
public void setMaxInboundMessageSize(final int maxInboundMessageSize) {
@@ -89,6 +98,7 @@ public void setMaxInboundMessageSize(final int maxInboundMessageSize) {
/**
* The maximum connection age.
+ *
* @return The maximum connection age in seconds.
*/
public int getMaxConnectionAgeSeconds() {
@@ -97,6 +107,7 @@ public int getMaxConnectionAgeSeconds() {
/**
* Specify a maximum connection age.
+ *
* @param maxConnectionAgeSeconds The maximum connection age in seconds.
*/
public void setMaxConnectionAgeSeconds(final int maxConnectionAgeSeconds) {
@@ -105,6 +116,7 @@ public void setMaxConnectionAgeSeconds(final int maxConnectionAgeSeconds) {
/**
* The timeout for a keep-alive ping requests.
+ *
* @return timeout in seconds.
*/
public int getKeepAliveTimeoutSeconds() {
@@ -113,6 +125,7 @@ public int getKeepAliveTimeoutSeconds() {
/**
* Set the timeout for keep-alive ping requests.
+ *
* @param keepAliveTimeoutSeconds timeout in seconds.
*/
public void setKeepAliveTimeoutSeconds(final int keepAliveTimeoutSeconds) {
@@ -121,6 +134,7 @@ public void setKeepAliveTimeoutSeconds(final int keepAliveTimeoutSeconds) {
/**
* The most aggressive keep-alive time clients are permitted to configure.
+ *
* @return time in minutes.
*/
public int getPermitKeepAliveTimeMinutes() {
@@ -129,6 +143,7 @@ public int getPermitKeepAliveTimeMinutes() {
/**
* Specify the most aggressive keep-alive time clients are permitted to configure.
+ *
* @param permitKeepAliveTimeMinutes time in minutes.
*/
public void setPermitKeepAliveTimeMinutes(final int permitKeepAliveTimeMinutes) {
@@ -137,6 +152,7 @@ public void setPermitKeepAliveTimeMinutes(final int permitKeepAliveTimeMinutes)
/**
* The delay before the server sends a keep-alive.
+ *
* @return delay in minutes.
*/
public int getKeepAliveTimeMinutes() {
@@ -145,6 +161,7 @@ public int getKeepAliveTimeMinutes() {
/**
* Set the delay before the server sends a keep-alive.
+ *
* @param keepAliveTimeMinutes delay in minutes.
*/
public void setKeepAliveTimeMinutes(final int keepAliveTimeMinutes) {
@@ -152,7 +169,9 @@ public void setKeepAliveTimeMinutes(final int keepAliveTimeMinutes) {
}
/**
- * Whether clients are allowed to send keep-alive HTTP/2 PINGs even if there are no outstanding RPCs on the connection.
+ * Whether clients are allowed to send keep-alive HTTP/2 PINGs even if there are no outstanding RPCs on the
+ * connection.
+ *
* @return true if clients are allowed to send keep-alive requests without calls; otherwise false.
*/
public boolean getPermitKeepAliveWithoutCalls() {
@@ -161,6 +180,7 @@ public boolean getPermitKeepAliveWithoutCalls() {
/**
* Get the server socket address.
+ *
* @return a socket address.
*/
public SocketAddress getServerAddress() {
@@ -169,6 +189,7 @@ public SocketAddress getServerAddress() {
/**
* Set the server socket address.
+ *
* @param address a socket address.
*/
public void setServerAddress(final SocketAddress address) {
@@ -176,7 +197,9 @@ public void setServerAddress(final SocketAddress address) {
}
/**
- * Whether clients are allowed to send keep-alive HTTP/2 PINGs even if there are no outstanding RPCs on the connection.
+ * Whether clients are allowed to send keep-alive HTTP/2 PINGs even if there are no outstanding RPCs on the
+ * connection.
+ *
* @return true if clients are allowed to send keep-alive requests without calls; otherwise false.
*/
public boolean isPermitKeepAliveWithoutCalls() {
@@ -184,7 +207,9 @@ public boolean isPermitKeepAliveWithoutCalls() {
}
/**
- * Specify whether clients are allowed to send keep-alive HTTP/2 PINGs even if there are no outstanding RPCs on the connection.
+ * Specify whether clients are allowed to send keep-alive HTTP/2 PINGs even if there are no outstanding RPCs on the
+ * connection.
+ *
* @param permitKeepAliveWithoutCalls Whether to allow clients to send keep-alive requests without calls.
*/
public void setPermitKeepAliveWithoutCalls(final boolean permitKeepAliveWithoutCalls) {
@@ -193,6 +218,7 @@ public void setPermitKeepAliveWithoutCalls(final boolean permitKeepAliveWithoutC
/**
* Password used to access the server key.
+ *
* @return a password.
*/
public String getKeyPassword() {
@@ -201,6 +227,7 @@ public String getKeyPassword() {
/**
* Set the password used to access the server key.
+ *
* @param keyPassword a password.
*/
public void setKeyPassword(final String keyPassword) {
@@ -209,6 +236,7 @@ public void setKeyPassword(final String keyPassword) {
/**
* Server keychain file name.
+ *
* @return a file name.
*/
public String getKeyCertChainFile() {
@@ -217,6 +245,7 @@ public String getKeyCertChainFile() {
/**
* Set the server keychain file name.
+ *
* @param keyCertChainFile a file name.
*/
public void setKeyCertChainFile(final String keyCertChainFile) {
@@ -225,6 +254,7 @@ public void setKeyCertChainFile(final String keyCertChainFile) {
/**
* Server key file name.
+ *
* @return a file name.
*/
public String getKeyFile() {
@@ -233,6 +263,7 @@ public String getKeyFile() {
/**
* Set the server key file name.
+ *
* @param keyFile a file name.
*/
public void setKeyFile(final String keyFile) {
@@ -241,6 +272,7 @@ public void setKeyFile(final String keyFile) {
/**
* Server trust certificate collection file name.
+ *
* @return a file name.
*/
public String getTrustCertCollectionFile() {
@@ -249,6 +281,7 @@ public String getTrustCertCollectionFile() {
/**
* Set the server trust certificate collection file name.
+ *
* @param trustCertCollectionFile a file name.
*/
public void setTrustCertCollectionFile(final String trustCertCollectionFile) {
@@ -257,6 +290,7 @@ public void setTrustCertCollectionFile(final String trustCertCollectionFile) {
/**
* Whether TLS is enabled for the server.
+ *
* @return true if TLS is enabled; otherwise false.
*/
public boolean isTlsEnabled() {
@@ -265,6 +299,7 @@ public boolean isTlsEnabled() {
/**
* Set whether TLS is enabled for the server.
+ *
* @param tlsEnabled true to enable TLS; otherwise false.
*/
public void setTlsEnabled(final boolean tlsEnabled) {
@@ -273,6 +308,7 @@ public void setTlsEnabled(final boolean tlsEnabled) {
/**
* Check that all the server property values are valid.
+ *
* @throws IllegalArgumentException if any properties are not valid.
*/
public void validate() {
@@ -280,30 +316,37 @@ public void validate() {
throw new IllegalArgumentException("chaincodeServerProperties.getServerAddress() must be set");
}
if (this.getKeepAliveTimeMinutes() <= 0) {
- throw new IllegalArgumentException("chaincodeServerProperties.getKeepAliveTimeMinutes() must be more then 0");
+ throw new IllegalArgumentException(
+ "chaincodeServerProperties.getKeepAliveTimeMinutes() must be more then 0");
}
if (this.getKeepAliveTimeoutSeconds() <= 0) {
- throw new IllegalArgumentException("chaincodeServerProperties.getKeepAliveTimeoutSeconds() must be more then 0");
+ throw new IllegalArgumentException(
+ "chaincodeServerProperties.getKeepAliveTimeoutSeconds() must be more then 0");
}
if (this.getPermitKeepAliveTimeMinutes() <= 0) {
- throw new IllegalArgumentException("chaincodeServerProperties.getPermitKeepAliveTimeMinutes() must be more then 0");
+ throw new IllegalArgumentException(
+ "chaincodeServerProperties.getPermitKeepAliveTimeMinutes() must be more then 0");
}
if (this.getMaxConnectionAgeSeconds() <= 0) {
- throw new IllegalArgumentException("chaincodeServerProperties.getMaxConnectionAgeSeconds() must be more then 0");
+ throw new IllegalArgumentException(
+ "chaincodeServerProperties.getMaxConnectionAgeSeconds() must be more then 0");
}
if (this.getMaxInboundMetadataSize() <= 0) {
- throw new IllegalArgumentException("chaincodeServerProperties.getMaxInboundMetadataSize() must be more then 0");
+ throw new IllegalArgumentException(
+ "chaincodeServerProperties.getMaxInboundMetadataSize() must be more then 0");
}
if (this.getMaxInboundMessageSize() <= 0) {
- throw new IllegalArgumentException("chaincodeServerProperties.getMaxInboundMessageSize() must be more then 0");
+ throw new IllegalArgumentException(
+ "chaincodeServerProperties.getMaxInboundMessageSize() must be more then 0");
}
- if (this.isTlsEnabled() && (this.getKeyCertChainFile() == null || this.getKeyCertChainFile().isEmpty()
- || this.getKeyFile() == null || this.getKeyFile().isEmpty())) {
+ if (this.isTlsEnabled()
+ && (this.getKeyCertChainFile() == null
+ || this.getKeyCertChainFile().isEmpty()
+ || this.getKeyFile() == null
+ || this.getKeyFile().isEmpty())) {
throw new IllegalArgumentException("if chaincodeServerProperties.isTlsEnabled() must be more specified"
- + " chaincodeServerProperties.getKeyCertChainFile() and chaincodeServerProperties.getKeyFile()"
- + " with optional chaincodeServerProperties.getKeyPassword()");
+ + " chaincodeServerProperties.getKeyCertChainFile() and chaincodeServerProperties.getKeyFile()"
+ + " with optional chaincodeServerProperties.getKeyPassword()");
}
}
-
-
}
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeStub.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeStub.java
index 7c77f5da..8c223fc4 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeStub.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChaincodeStub.java
@@ -13,7 +13,6 @@
import java.util.Arrays;
import java.util.List;
import java.util.Map;
-
import org.hyperledger.fabric.protos.peer.ChaincodeEvent;
import org.hyperledger.fabric.protos.peer.SignedProposal;
import org.hyperledger.fabric.shim.Chaincode.Response;
@@ -24,23 +23,21 @@
import org.hyperledger.fabric.shim.ledger.QueryResultsIteratorWithMetadata;
/**
- * An object which manages the transaction context, provides access to state variables, and supports calls to other chaincode implementations.
+ * An object which manages the transaction context, provides access to state variables, and supports calls to other
+ * chaincode implementations.
*/
public interface ChaincodeStub {
/**
- * Returns the arguments corresponding to the call to
- * {@link Chaincode#init(ChaincodeStub)} or
- * {@link Chaincode#invoke(ChaincodeStub)}, each argument represented as byte
- * array.
+ * Returns the arguments corresponding to the call to {@link Chaincode#init(ChaincodeStub)} or
+ * {@link Chaincode#invoke(ChaincodeStub)}, each argument represented as byte array.
*
* @return a list of arguments (bytes arrays)
*/
List getArgs();
/**
- * Returns the arguments corresponding to the call to
- * {@link Chaincode#init(ChaincodeStub)} or
+ * Returns the arguments corresponding to the call to {@link Chaincode#init(ChaincodeStub)} or
* {@link Chaincode#invoke(ChaincodeStub)}, cast to UTF-8 string.
*
* @return a list of arguments cast to UTF-8 strings
@@ -48,22 +45,19 @@ public interface ChaincodeStub {
List getStringArgs();
/**
- * A convenience method that returns the first argument of the chaincode
- * invocation for use as a function name.
- *
- * The bytes of the first argument are decoded as a UTF-8 string.
+ * A convenience method that returns the first argument of the chaincode invocation for use as a function name.
+ *
+ *
The bytes of the first argument are decoded as a UTF-8 string.
*
* @return the function name
*/
String getFunction();
/**
- * A convenience method that returns all except the first argument of the
- * chaincode invocation for use as the parameters to the function returned by
- * #{@link ChaincodeStub#getFunction()}.
- *
- * The bytes of the arguments are decoded as a UTF-8 strings and returned as a
- * list of string parameters.
+ * A convenience method that returns all except the first argument of the chaincode invocation for use as the
+ * parameters to the function returned by #{@link ChaincodeStub#getFunction()}.
+ *
+ *
The bytes of the arguments are decoded as a UTF-8 strings and returned as a list of string parameters.
*
* @return a list of parameters
*/
@@ -71,9 +65,8 @@ public interface ChaincodeStub {
/**
* Returns the transaction id for the current chaincode invocation request.
- *
- * The transaction id uniquely identifies the transaction within the scope of
- * the channel.
+ *
+ *
The transaction id uniquely identifies the transaction within the scope of the channel.
*
* @return the transaction id
*/
@@ -81,49 +74,45 @@ public interface ChaincodeStub {
/**
* Returns the channel id for the current proposal.
- *
- * This would be the 'channel_id' of the transaction proposal except where the
- * chaincode is calling another on a different channel.
+ *
+ *
This would be the 'channel_id' of the transaction proposal except where the chaincode is calling another on a
+ * different channel.
*
* @return the channel id
*/
String getChannelId();
/**
- * Locally calls the specified chaincode invoke()
using the same
- * transaction context.
- *
- * chaincode calling chaincode doesn't create a new transaction message.
- *
- * If the called chaincode is on the same channel, it simply adds the called
- * chaincode read set and write set to the calling transaction.
- *
- * If the called chaincode is on a different channel, only the Response is
- * returned to the calling chaincode; any putState
calls from the
- * called chaincode will not have any effect on the ledger; that is, the called
- * chaincode on a different channel will not have its read set and write set
- * applied to the transaction. Only the calling chaincode's read set and write
- * set will be applied to the transaction. Effectively the called chaincode on a
- * different channel is a `Query`, which does not participate in state
- * validation checks in subsequent commit phase.
- *
- * If `channel` is empty, the caller's channel is assumed.
- *
- * Invoke another chaincode using the same transaction context.
+ * Locally calls the specified chaincode invoke()
using the same transaction context.
+ *
+ *
chaincode calling chaincode doesn't create a new transaction message.
+ *
+ *
If the called chaincode is on the same channel, it simply adds the called chaincode read set and write set to
+ * the calling transaction.
+ *
+ *
If the called chaincode is on a different channel, only the Response is returned to the calling chaincode; any
+ * putState
calls from the called chaincode will not have any effect on the ledger; that is, the called
+ * chaincode on a different channel will not have its read set and write set applied to the transaction. Only the
+ * calling chaincode's read set and write set will be applied to the transaction. Effectively the called chaincode
+ * on a different channel is a `Query`, which does not participate in state validation checks in subsequent commit
+ * phase.
+ *
+ *
If `channel` is empty, the caller's channel is assumed.
+ *
+ *
Invoke another chaincode using the same transaction context.
*
* @param chaincodeName Name of chaincode to be invoked.
- * @param args Arguments to pass on to the called chaincode.
- * @param channel If not specified, the caller's channel is assumed.
+ * @param args Arguments to pass on to the called chaincode.
+ * @param channel If not specified, the caller's channel is assumed.
* @return {@link Response} object returned by called chaincode
*/
Response invokeChaincode(String chaincodeName, List args, String channel);
/**
* Returns the value of the specified key
from the ledger.
- *
- * Note that getState doesn't read data from the writeset, which has not been
- * committed to the ledger. In other words, GetState doesn't consider data
- * modified by PutState that has not been committed.
+ *
+ *
Note that getState doesn't read data from the writeset, which has not been committed to the ledger. In other
+ * words, GetState doesn't consider data modified by PutState that has not been committed.
*
* @param key name of the value
* @return value the value read from the ledger
@@ -131,9 +120,8 @@ public interface ChaincodeStub {
byte[] getState(String key);
/**
- * retrieves the key-level endorsement policy for key
. Note that
- * this will introduce a read dependency on key
in the
- * transaction's readset.
+ * retrieves the key-level endorsement policy for key
. Note that this will introduce a read dependency
+ * on key
in the transaction's readset.
*
* @param key key to get key level endorsement
* @return endorsement policy
@@ -141,15 +129,14 @@ public interface ChaincodeStub {
byte[] getStateValidationParameter(String key);
/**
- * Puts the specified key
and value
into the
- * transaction's writeset as a data-write proposal.
- *
- * putState doesn't effect the ledger until the transaction is validated and
- * successfully committed. Simple keys must not be an empty string and must not
- * start with 0x00 character, in order to avoid range query collisions with
+ * Puts the specified key
and value
into the transaction's writeset as a data-write
+ * proposal.
+ *
+ *
putState doesn't effect the ledger until the transaction is validated and successfully committed. Simple keys
+ * must not be an empty string and must not start with 0x00 character, in order to avoid range query collisions with
* composite keys
*
- * @param key name of the value
+ * @param key name of the value
* @param value the value to write to the ledger
*/
void putState(String key, byte[] value);
@@ -157,79 +144,66 @@ public interface ChaincodeStub {
/**
* Sets the key-level endorsement policy for key
.
*
- * @param key key to set key level endorsement
+ * @param key key to set key level endorsement
* @param value endorsement policy
*/
void setStateValidationParameter(String key, byte[] value);
/**
- * Records the specified key
to be deleted in the writeset of the
- * transaction proposal.
- *
- * The key
and its value will be deleted from the ledger when the
- * transaction is validated and successfully committed.
+ * Records the specified key
to be deleted in the writeset of the transaction proposal.
+ *
+ *
The key
and its value will be deleted from the ledger when the transaction is validated and
+ * successfully committed.
*
* @param key name of the value to be deleted
*/
void delState(String key);
/**
- * Returns all existing keys, and their values, that are lexicographically
- * between startkey
(inclusive) and the endKey
- * (exclusive).
- *
- * The keys are returned by the iterator in lexical order. Note that startKey
- * and endKey can be empty string, which implies unbounded range query on start
- * or end.
- *
- * Call close() on the returned {@link QueryResultsIterator#close()} object when
- * done.
+ * Returns all existing keys, and their values, that are lexicographically between startkey
(inclusive)
+ * and the endKey
(exclusive).
+ *
+ *
The keys are returned by the iterator in lexical order. Note that startKey and endKey can be empty string,
+ * which implies unbounded range query on start or end.
+ *
+ *
Call close() on the returned {@link QueryResultsIterator#close()} object when done.
*
* @param startKey key as the start of the key range (inclusive)
- * @param endKey key as the end of the key range (exclusive)
+ * @param endKey key as the end of the key range (exclusive)
* @return an {@link Iterable} of {@link KeyValue}
*/
QueryResultsIterator getStateByRange(String startKey, String endKey);
/**
- * Returns a range iterator over a set of keys in the ledger. The iterator can
- * be used to fetch keys between the startKey
(inclusive) and
- * endKey
(exclusive). When an empty string is passed as a value to
- * the bookmark
argument, the returned iterator can be used to
- * fetch the first pageSize
keys between the startKey
- * and endKey
. When the bookmark
is a non-empty
- * string, the iterator can be used to fetch first pageSize
keys
- * between the bookmark
and endKey
. Note that only the
- * bookmark present in a prior page of query results
- * ({@link org.hyperledger.fabric.protos.peer.QueryResponseMetadata})
- * can be used as a value to the bookmark argument. Otherwise, an empty string
- * must be passed as bookmark. The keys are returned by the iterator in lexical
- * order. Note that startKey
and endKey
can be empty
- * string, which implies unbounded range query on start or end. This call is
- * only supported in a read only transaction.
+ * Returns a range iterator over a set of keys in the ledger. The iterator can be used to fetch keys between the
+ * startKey
(inclusive) and endKey
(exclusive). When an empty string is passed as a value
+ * to the bookmark
argument, the returned iterator can be used to fetch the first pageSize
+ * keys between the startKey
and endKey
. When the bookmark
is a non-empty
+ * string, the iterator can be used to fetch first pageSize
keys between the bookmark
and
+ * endKey
. Note that only the bookmark present in a prior page of query results
+ * ({@link org.hyperledger.fabric.protos.peer.QueryResponseMetadata}) can be used as a value to the bookmark
+ * argument. Otherwise, an empty string must be passed as bookmark. The keys are returned by the iterator in lexical
+ * order. Note that startKey
and endKey
can be empty string, which implies unbounded range
+ * query on start or end. This call is only supported in a read only transaction.
*
* @param startKey the start key
- * @param endKey the end key
+ * @param endKey the end key
* @param pageSize the page size
* @param bookmark the bookmark
* @return QueryIterator
*/
- QueryResultsIteratorWithMetadata getStateByRangeWithPagination(String startKey, String endKey, int pageSize, String bookmark);
+ QueryResultsIteratorWithMetadata getStateByRangeWithPagination(
+ String startKey, String endKey, int pageSize, String bookmark);
/**
- * Returns all existing keys, and their values, that are prefixed by the
- * specified partial {@link CompositeKey}.
- *
- * If a full composite key is specified, it will not match itself, resulting in
- * no keys being returned.
- *
- * This method takes responsibility to correctly parse the {@link CompositeKey}
- * from a String and behaves exactly as
- * {@link ChaincodeStub#getStateByPartialCompositeKey(CompositeKey)}.
- *
- *
- * Call close() on the returned {@link QueryResultsIterator#close()} object when
- * done.
+ * Returns all existing keys, and their values, that are prefixed by the specified partial {@link CompositeKey}.
+ *
+ *
If a full composite key is specified, it will not match itself, resulting in no keys being returned.
+ *
+ *
This method takes responsibility to correctly parse the {@link CompositeKey} from a String and behaves exactly
+ * as {@link ChaincodeStub#getStateByPartialCompositeKey(CompositeKey)}.
+ *
+ *
Call close() on the returned {@link QueryResultsIterator#close()} object when done.
*
* @param compositeKey partial composite key
* @return an {@link Iterable} of {@link KeyValue}
@@ -237,21 +211,15 @@ public interface ChaincodeStub {
QueryResultsIterator getStateByPartialCompositeKey(String compositeKey);
/**
- * Returns all existing keys, and their values, that are prefixed by the
- * specified partial {@link CompositeKey}.
- *
- * It combines the attributes and the objectType to form a partial composite
- * key.
- *
- * If a full composite key is specified, it will not match itself, resulting in
- * no keys being returned.
- *
- * This method takes responsibility to correctly combine Object type and
- * attributes creating a {@link CompositeKey} and behaves exactly as
- * {@link ChaincodeStub#getStateByPartialCompositeKey(CompositeKey)}.
- *
- * Call close() on the returned {@link QueryResultsIterator#close()} object when
- * done.
+ * Returns all existing keys, and their values, that are prefixed by the specified partial {@link CompositeKey}.
+ *
+ * It combines the attributes and the objectType to form a partial composite key.
+ *
+ *
If a full composite key is specified, it will not match itself, resulting in no keys being returned.
+ *
+ *
This method takes responsibility to correctly combine Object type and attributes creating a
+ * {@link CompositeKey} and behaves exactly as {@link ChaincodeStub#getStateByPartialCompositeKey(CompositeKey)}.
+ * Call close() on the returned {@link QueryResultsIterator#close()} object when done.
*
* @param objectType ObjectType of the compositeKey
* @param attributes Attributes of the composite key
@@ -260,11 +228,9 @@ public interface ChaincodeStub {
QueryResultsIterator getStateByPartialCompositeKey(String objectType, String... attributes);
/**
- * Returns all existing keys, and their values, that are prefixed by the
- * specified partial {@link CompositeKey}.
- *
- * If a full composite key is specified, it will not match itself, resulting in
- * no keys being returned.
+ * Returns all existing keys, and their values, that are prefixed by the specified partial {@link CompositeKey}.
+ *
+ *
If a full composite key is specified, it will not match itself, resulting in no keys being returned.
*
* @param compositeKey partial composite key
* @return an {@link Iterable} of {@link KeyValue}
@@ -272,36 +238,32 @@ public interface ChaincodeStub {
QueryResultsIterator getStateByPartialCompositeKey(CompositeKey compositeKey);
/**
- * Queries the state in the ledger based on a given partial composite key. This
- * function returns an iterator which can be used to iterate over the composite
- * keys whose prefix matches the given partial composite key.
- *
- * When an empty string is passed as a value to the bookmark
- * argument, the returned iterator can be used to fetch the first
- * pageSize
composite keys whose prefix matches the given partial
- * composite key.
- *
- * When the bookmark
is a non-empty string, the iterator can be
- * used to fetch first pageSize
keys between the
- * bookmark
(inclusive) and and the last matching composite key.
- *
- * Note that only the bookmark present in a prior page of query results
- * ({@link org.hyperledger.fabric.protos.peer.QueryResponseMetadata})
- * can be used as a value to the bookmark argument. Otherwise, an empty string
- * must be passed as bookmark.
- *
- * This call is only supported in a read only transaction.
+ * Queries the state in the ledger based on a given partial composite key. This function returns an iterator which
+ * can be used to iterate over the composite keys whose prefix matches the given partial composite key.
+ *
+ *
When an empty string is passed as a value to the bookmark
argument, the returned iterator can be
+ * used to fetch the first pageSize
composite keys whose prefix matches the given partial composite
+ * key.
+ *
+ *
When the bookmark
is a non-empty string, the iterator can be used to fetch first pageSize
+ *
keys between the bookmark
(inclusive) and and the last matching composite key.
+ *
+ *
Note that only the bookmark present in a prior page of query results
+ * ({@link org.hyperledger.fabric.protos.peer.QueryResponseMetadata}) can be used as a value to the bookmark
+ * argument. Otherwise, an empty string must be passed as bookmark.
+ *
+ *
This call is only supported in a read only transaction.
*
* @param compositeKey the composite key
- * @param pageSize the page size
- * @param bookmark the bookmark
+ * @param pageSize the page size
+ * @param bookmark the bookmark
* @return QueryIterator
*/
- QueryResultsIteratorWithMetadata getStateByPartialCompositeKeyWithPagination(CompositeKey compositeKey, int pageSize, String bookmark);
+ QueryResultsIteratorWithMetadata getStateByPartialCompositeKeyWithPagination(
+ CompositeKey compositeKey, int pageSize, String bookmark);
/**
- * Given a set of attributes, this method combines these attributes to return a
- * composite key.
+ * Given a set of attributes, this method combines these attributes to return a composite key.
*
* @param objectType A string used as the prefix of the resulting key
* @param attributes List of attribute values to concatenate into the key
@@ -319,53 +281,46 @@ public interface ChaincodeStub {
/**
* Performs a "rich" query against a state database.
- *
- * It is only supported for state databases that support rich query, e.g.
- * CouchDB. The query string is in the native syntax of the underlying state
- * database. An {@link QueryResultsIterator} is returned which can be used to
+ *
+ *
It is only supported for state databases that support rich query, e.g. CouchDB. The query string is in the
+ * native syntax of the underlying state database. An {@link QueryResultsIterator} is returned which can be used to
* iterate (next) over the query result set.
*
- * @param query query string in a syntax supported by the underlying state
- * database
+ * @param query query string in a syntax supported by the underlying state database
* @return {@link QueryResultsIterator} object contains query results
- * @throws UnsupportedOperationException if the underlying state database does
- * not support rich queries.
+ * @throws UnsupportedOperationException if the underlying state database does not support rich queries.
*/
QueryResultsIterator getQueryResult(String query);
/**
- * Performs a "rich" query against a state database. It is only supported for
- * state databases that support rich query, e.g., CouchDB. The query string is
- * in the native syntax of the underlying state database. An iterator is
- * returned which can be used to iterate over keys in the query result set. When
- * an empty string is passed as a value to the bookmark
argument,
- * the returned iterator can be used to fetch the first pageSize
of
- * query results..
- *
- * When the bookmark
is a non-empty string, the iterator can be
- * used to fetch first pageSize
keys between the
- * bookmark
(inclusive) and the last key in the query result.
- *
- * Note that only the bookmark present in a prior page of query results
- * ({@link org.hyperledger.fabric.protos.peer.QueryResponseMetadata})
- * can be used as a value to the bookmark argument. Otherwise, an empty string
- * must be passed as bookmark.
- *
- * This call is only supported in a read only transaction.
- *
- * @param query the query
+ * Performs a "rich" query against a state database. It is only supported for state databases that support rich
+ * query, e.g., CouchDB. The query string is in the native syntax of the underlying state database. An iterator is
+ * returned which can be used to iterate over keys in the query result set. When an empty string is passed as a
+ * value to the bookmark
argument, the returned iterator can be used to fetch the first pageSize
+ *
of query results..
+ *
+ *
When the bookmark
is a non-empty string, the iterator can be used to fetch first pageSize
+ *
keys between the bookmark
(inclusive) and the last key in the query result.
+ *
+ *
Note that only the bookmark present in a prior page of query results
+ * ({@link org.hyperledger.fabric.protos.peer.QueryResponseMetadata}) can be used as a value to the bookmark
+ * argument. Otherwise, an empty string must be passed as bookmark.
+ *
+ *
This call is only supported in a read only transaction.
+ *
+ * @param query the query
* @param pageSize the page size
* @param bookmark the bookmark
* @return QueryIterator
*/
- QueryResultsIteratorWithMetadata getQueryResultWithPagination(String query, int pageSize, String bookmark);
+ QueryResultsIteratorWithMetadata getQueryResultWithPagination(
+ String query, int pageSize, String bookmark);
/**
* Returns a history of key values across time.
- *
- * For each historic key update, the historic value and associated transaction
- * id and timestamp are returned. The timestamp is the timestamp provided by the
- * client in the proposal header. This method requires peer configuration
+ *
+ *
For each historic key update, the historic value and associated transaction id and timestamp are returned. The
+ * timestamp is the timestamp provided by the client in the proposal header. This method requires peer configuration
* core.ledger.history.enableHistoryDatabase
to be true.
*
* @param key The state variable key
@@ -374,227 +329,197 @@ public interface ChaincodeStub {
QueryResultsIterator getHistoryForKey(String key);
/**
- * Returns the value of the specified key
from the specified
- * collection
.
- *
- * Note that {@link #getPrivateData(String, String)} doesn't read data from the
- * private writeset, which has not been committed to the
- * collection
. In other words,
- * {@link #getPrivateData(String, String)} doesn't consider data modified by
- * {@link #putPrivateData(String, String, byte[])} * that has not been
- * committed.
+ * Returns the value of the specified key
from the specified collection
.
+ *
+ *
Note that {@link #getPrivateData(String, String)} doesn't read data from the private writeset, which has not
+ * been committed to the collection
. In other words, {@link #getPrivateData(String, String)} doesn't
+ * consider data modified by {@link #putPrivateData(String, String, byte[])} * that has not been committed.
*
* @param collection name of the collection
- * @param key name of the value
+ * @param key name of the value
* @return value the value read from the collection
*/
byte[] getPrivateData(String collection, String key);
/**
* @param collection name of the collection
- * @param key name of the value
+ * @param key name of the value
* @return the private data hash
*/
byte[] getPrivateDataHash(String collection, String key);
/**
- * Retrieves the key-level endorsement policy for the private data specified by
- * key
. Note that this introduces a read dependency on
- * key
in the transaction's readset.
+ * Retrieves the key-level endorsement policy for the private data specified by key
. Note that this
+ * introduces a read dependency on key
in the transaction's readset.
*
* @param collection name of the collection
- * @param key key to get endorsement policy
+ * @param key key to get endorsement policy
* @return Key Level endorsement as byte array
*/
byte[] getPrivateDataValidationParameter(String collection, String key);
/**
- * Puts the specified key
and value
into the
- * transaction's private writeset.
- *
- * Note that only hash of the private writeset goes into the transaction
- * proposal response (which is sent to the client who issued the transaction)
- * and the actual private writeset gets temporarily stored in a transient store.
- * putPrivateData doesn't effect the collection
until the
- * transaction is validated and successfully committed. Simple keys must not be
- * an empty string and must not start with null character (0x00), in order to
- * avoid range query collisions with composite keys, which internally get
- * prefixed with 0x00 as composite key namespace.
+ * Puts the specified key
and value
into the transaction's private writeset.
+ *
+ *
Note that only hash of the private writeset goes into the transaction proposal response (which is sent to the
+ * client who issued the transaction) and the actual private writeset gets temporarily stored in a transient store.
+ * putPrivateData doesn't effect the collection
until the transaction is validated and successfully
+ * committed. Simple keys must not be an empty string and must not start with null character (0x00), in order to
+ * avoid range query collisions with composite keys, which internally get prefixed with 0x00 as composite key
+ * namespace.
*
* @param collection name of the collection
- * @param key name of the value
- * @param value the value to write to the ledger
+ * @param key name of the value
+ * @param value the value to write to the ledger
*/
void putPrivateData(String collection, String key, byte[] value);
/**
- * Sets the key-level endorsement policy for the private data specified by
- * key
.
+ * Sets the key-level endorsement policy for the private data specified by key
.
*
* @param collection name of the collection
- * @param key key to set endorsement policy
- * @param value endorsement policy
+ * @param key key to set endorsement policy
+ * @param value endorsement policy
*/
void setPrivateDataValidationParameter(String collection, String key, byte[] value);
/**
- * Records the specified key
to be deleted in the private writeset
- * of the transaction.
- *
- * Note that only hash of the private writeset goes into the transaction
- * proposal response (which is sent to the client who issued the transaction)
- * and the actual private writeset gets temporarily stored in a transient store.
- * The key
and its value will be deleted from the collection when
- * the transaction is validated and successfully committed.
+ * Records the specified key
to be deleted in the private writeset of the transaction.
+ *
+ *
Note that only hash of the private writeset goes into the transaction proposal response (which is sent to the
+ * client who issued the transaction) and the actual private writeset gets temporarily stored in a transient store.
+ * The key
and its value will be deleted from the collection when the transaction is validated and
+ * successfully committed.
*
* @param collection name of the collection
- * @param key name of the value to be deleted
+ * @param key name of the value to be deleted
*/
void delPrivateData(String collection, String key);
/**
- * Reqauests purging of the specified key
to be from
- * the private data stores.
- *
- * Note that only hash of the private writeset goes into the transaction
- * proposal response (which is sent to the client who issued the transaction)
- * and the actual private writeset gets temporarily stored in a transient store.
- * The key
and its value will be purged from the collection. This is an
- * asynchronous activity.
- *
- * Purge is a complete removal of the history of the key. There is existing purge
- * possible mased on block height. This API allows the contract to be pro-active in
- * requesting data be purged. This can contribute towards meeting privacy requirements.
+ * Reqauests purging of the specified key
to be from the private data stores.
+ *
+ *
Note that only hash of the private writeset goes into the transaction proposal response (which is sent to the
+ * client who issued the transaction) and the actual private writeset gets temporarily stored in a transient store.
+ * The key
and its value will be purged from the collection. This is an asynchronous activity.
+ *
+ *
Purge is a complete removal of the history of the key. There is existing purge possible mased on block height.
+ * This API allows the contract to be pro-active in requesting data be purged. This can contribute towards meeting
+ * privacy requirements.
*
* @param collection name of the collection
- * @param key name of the value to be deleted
+ * @param key name of the value to be deleted
*/
void purgePrivateData(String collection, String key);
/**
- * Returns all existing keys, and their values, that are lexicographically
- * between startkey
(inclusive) and the endKey
- * (exclusive) in a given private collection.
- *
- * Note that startKey and endKey can be empty string, which implies unbounded
- * range query on start or end. The query is re-executed during validation phase
- * to ensure result set has not changed since transaction endorsement (phantom
- * reads detected).
+ * Returns all existing keys, and their values, that are lexicographically between startkey
(inclusive)
+ * and the endKey
(exclusive) in a given private collection.
+ *
+ *
Note that startKey and endKey can be empty string, which implies unbounded range query on start or end. The
+ * query is re-executed during validation phase to ensure result set has not changed since transaction endorsement
+ * (phantom reads detected).
*
* @param collection name of the collection
- * @param startKey private data variable key as the start of the key range
- * (inclusive)
- * @param endKey private data variable key as the end of the key range
- * (exclusive)
+ * @param startKey private data variable key as the start of the key range (inclusive)
+ * @param endKey private data variable key as the end of the key range (exclusive)
* @return an {@link Iterable} of {@link KeyValue}
*/
QueryResultsIterator getPrivateDataByRange(String collection, String startKey, String endKey);
/**
- * Returns all existing keys, and their values, that are prefixed by the
- * specified partial {@link CompositeKey} in a given private collection.
- *
- * If a full composite key is specified, it will not match itself, resulting in
- * no keys being returned.
- *
- * The query is re-executed during validation phase to ensure result set has not
- * changed since transaction endorsement (phantom reads detected).
- *
- * This method takes responsibility to correctly parse the {@link CompositeKey}
- * from a String and behaves exactly as
- * {@link ChaincodeStub#getPrivateDataByPartialCompositeKey(String, CompositeKey)}.
- *
- *
- * @param collection name of the collection
+ * Returns all existing keys, and their values, that are prefixed by the specified partial {@link CompositeKey} in a
+ * given private collection.
+ *
+ * If a full composite key is specified, it will not match itself, resulting in no keys being returned.
+ *
+ *
The query is re-executed during validation phase to ensure result set has not changed since transaction
+ * endorsement (phantom reads detected).
+ *
+ *
This method takes responsibility to correctly parse the {@link CompositeKey} from a String and behaves exactly
+ * as {@link ChaincodeStub#getPrivateDataByPartialCompositeKey(String, CompositeKey)}.
+ *
+ * @param collection name of the collection
* @param compositeKey partial composite key
* @return an {@link Iterable} of {@link KeyValue}
*/
QueryResultsIterator getPrivateDataByPartialCompositeKey(String collection, String compositeKey);
/**
- * Returns all existing keys, and their values, that are prefixed by the
- * specified partial {@link CompositeKey} in a given private collection.
- *
- * If a full composite key is specified, it will not match itself, resulting in
- * no keys being returned.
- *
- * The query is re-executed during validation phase to ensure result set has not
- * changed since transaction endorsement (phantom reads detected).
+ * Returns all existing keys, and their values, that are prefixed by the specified partial {@link CompositeKey} in a
+ * given private collection.
+ *
+ *
If a full composite key is specified, it will not match itself, resulting in no keys being returned.
+ *
+ *
The query is re-executed during validation phase to ensure result set has not changed since transaction
+ * endorsement (phantom reads detected).
*
- * @param collection name of the collection
+ * @param collection name of the collection
* @param compositeKey partial composite key
* @return an {@link Iterable} of {@link KeyValue}
*/
QueryResultsIterator getPrivateDataByPartialCompositeKey(String collection, CompositeKey compositeKey);
/**
- * Returns all existing keys, and their values, that are prefixed by the
- * specified partial {@link CompositeKey} in a given private collection.
- *
- * If a full composite key is specified, it will not match itself, resulting in
- * no keys being returned.
- *
- * The query is re-executed during validation phase to ensure result set has not
- * changed since transaction endorsement (phantom reads detected).
- *
- * This method takes responsibility to correctly combine Object type and
- * attributes creating a {@link CompositeKey} and behaves exactly as
- * {@link ChaincodeStub#getPrivateDataByPartialCompositeKey(String, CompositeKey)}.
- *
+ * Returns all existing keys, and their values, that are prefixed by the specified partial {@link CompositeKey} in a
+ * given private collection.
+ *
+ * If a full composite key is specified, it will not match itself, resulting in no keys being returned.
+ *
+ *
The query is re-executed during validation phase to ensure result set has not changed since transaction
+ * endorsement (phantom reads detected).
+ *
+ *
This method takes responsibility to correctly combine Object type and attributes creating a
+ * {@link CompositeKey} and behaves exactly as {@link ChaincodeStub#getPrivateDataByPartialCompositeKey(String,
+ * CompositeKey)}.
*
* @param collection name of the collection
* @param objectType ObjectType of the compositeKey
* @param attributes Attributes of the composite key
* @return an {@link Iterable} of {@link KeyValue}
*/
- QueryResultsIterator getPrivateDataByPartialCompositeKey(String collection, String objectType, String... attributes);
+ QueryResultsIterator getPrivateDataByPartialCompositeKey(
+ String collection, String objectType, String... attributes);
/**
* Perform a rich query against a given private collection.
- *
- * It is only supported for state databases that support rich query,
- * e.g.CouchDB. The query string is in the native syntax of the underlying state
- * database. An iterator is returned which can be used to iterate (next) over
- * the query result set. The query is NOT re-executed during validation phase,
- * phantom reads are not detected. That is, other committed transactions may
- * have added, updated, or removed keys that impact the result set, and this
- * would not be detected at validation/commit time. Applications susceptible to
- * this should therefore not use GetQueryResult as part of transactions that
- * update ledger, and should limit use to read-only chaincode operations.
+ *
+ *
It is only supported for state databases that support rich query, e.g.CouchDB. The query string is in the
+ * native syntax of the underlying state database. An iterator is returned which can be used to iterate (next) over
+ * the query result set. The query is NOT re-executed during validation phase, phantom reads are not detected. That
+ * is, other committed transactions may have added, updated, or removed keys that impact the result set, and this
+ * would not be detected at validation/commit time. Applications susceptible to this should therefore not use
+ * GetQueryResult as part of transactions that update ledger, and should limit use to read-only chaincode
+ * operations.
*
* @param collection name of the collection
- * @param query query string in a syntax supported by the underlying state
- * database
+ * @param query query string in a syntax supported by the underlying state database
* @return {@link QueryResultsIterator} object contains query results
- * @throws UnsupportedOperationException if the underlying state database does
- * not support rich queries.
+ * @throws UnsupportedOperationException if the underlying state database does not support rich queries.
*/
QueryResultsIterator getPrivateDataQueryResult(String collection, String query);
/**
- * Allows the chaincode to propose an event on the transaction proposal response.
- * When the transaction is included in a block and the block is successfully committed to the ledger,
- * the block event (including transaction level chaincode events)
- * will be delivered to the current client application event listeners that have been registered with the peer's event producer.
- * Consult each SDK's documentation for details.
- * Only a single chaincode event can be included in a transaction.
- * If setEvent() is called multiple times only the last event will be included in the transaction.
- * The event must originate from the outer-most invoked chaincode in chaincode-to-chaincode scenarios.
+ * Allows the chaincode to propose an event on the transaction proposal response. When the transaction is included
+ * in a block and the block is successfully committed to the ledger, the block event (including transaction level
+ * chaincode events) will be delivered to the current client application event listeners that have been registered
+ * with the peer's event producer. Consult each SDK's documentation for details. Only a single chaincode event can
+ * be included in a transaction. If setEvent() is called multiple times only the last event will be included in the
+ * transaction. The event must originate from the outer-most invoked chaincode in chaincode-to-chaincode scenarios.
* The marshaled ChaincodeEvent will be available in the transaction's ChaincodeAction.events field.
*
- * @param name Name of event. Cannot be null or empty string.
+ * @param name Name of event. Cannot be null or empty string.
* @param payload Optional event payload.
*/
void setEvent(String name, byte[] payload);
/**
* Invoke another chaincode using the same transaction context.
- *
- * Same as {@link #invokeChaincode(String, List, String)} using channelId to
- * null
+ *
+ *
Same as {@link #invokeChaincode(String, List, String)} using channelId to null
*
* @param chaincodeName Name of chaincode to be invoked.
- * @param args Arguments to pass on to the called chaincode.
+ * @param args Arguments to pass on to the called chaincode.
* @return {@link Response} object returned by called chaincode
*/
default Response invokeChaincode(final String chaincodeName, final List args) {
@@ -603,28 +528,29 @@ default Response invokeChaincode(final String chaincodeName, final List
/**
* Invoke another chaincode using the same transaction context.
- *
- * This is a convenience version of
- * {@link #invokeChaincode(String, List, String)}. The string args will be
+ *
+ *
This is a convenience version of {@link #invokeChaincode(String, List, String)}. The string args will be
* encoded into as UTF-8 bytes.
*
* @param chaincodeName Name of chaincode to be invoked.
- * @param args Arguments to pass on to the called chaincode.
- * @param channel If not specified, the caller's channel is assumed.
+ * @param args Arguments to pass on to the called chaincode.
+ * @param channel If not specified, the caller's channel is assumed.
* @return {@link Response} object returned by called chaincode
*/
- default Response invokeChaincodeWithStringArgs(final String chaincodeName, final List args, final String channel) {
- return invokeChaincode(chaincodeName, args.stream().map(x -> x.getBytes(UTF_8)).collect(toList()), channel);
+ default Response invokeChaincodeWithStringArgs(
+ final String chaincodeName, final List args, final String channel) {
+ return invokeChaincode(
+ chaincodeName, args.stream().map(x -> x.getBytes(UTF_8)).collect(toList()), channel);
}
/**
* Invoke another chaincode using the same transaction context.
- *
- * This is a convenience version of {@link #invokeChaincode(String, List)}. The
- * string args will be encoded into as UTF-8 bytes.
+ *
+ *
This is a convenience version of {@link #invokeChaincode(String, List)}. The string args will be encoded into
+ * as UTF-8 bytes.
*
* @param chaincodeName Name of chaincode to be invoked.
- * @param args Arguments to pass on to the called chaincode.
+ * @param args Arguments to pass on to the called chaincode.
* @return {@link Response} object returned by called chaincode
*/
default Response invokeChaincodeWithStringArgs(final String chaincodeName, final List args) {
@@ -633,12 +559,12 @@ default Response invokeChaincodeWithStringArgs(final String chaincodeName, final
/**
* Invoke another chaincode using the same transaction context.
- *
- * This is a convenience version of {@link #invokeChaincode(String, List)}. The
- * string args will be encoded into as UTF-8 bytes.
+ *
+ *
This is a convenience version of {@link #invokeChaincode(String, List)}. The string args will be encoded into
+ * as UTF-8 bytes.
*
* @param chaincodeName Name of chaincode to be invoked.
- * @param args Arguments to pass on to the called chaincode.
+ * @param args Arguments to pass on to the called chaincode.
* @return {@link Response} object returned by called chaincode
*/
default Response invokeChaincodeWithStringArgs(final String chaincodeName, final String... args) {
@@ -646,10 +572,9 @@ default Response invokeChaincodeWithStringArgs(final String chaincodeName, final
}
/**
- * Returns the byte array value specified by the key and decoded as a UTF-8
- * encoded string, from the ledger.
- *
- * This is a convenience version of {@link #getState(String)}
+ * Returns the byte array value specified by the key and decoded as a UTF-8 encoded string, from the ledger.
+ *
+ *
This is a convenience version of {@link #getState(String)}
*
* @param key name of the value
* @return value the value read from the ledger
@@ -659,24 +584,22 @@ default String getStringState(final String key) {
}
/**
- * Writes the specified value and key into the sidedb collection value converted
- * to byte array.
+ * Writes the specified value and key into the sidedb collection value converted to byte array.
*
* @param collection collection name
- * @param key name of the value
- * @param value the value to write to the ledger
+ * @param key name of the value
+ * @param value the value to write to the ledger
*/
-
default void putPrivateData(final String collection, final String key, final String value) {
putPrivateData(collection, key, value.getBytes(UTF_8));
}
/**
- * Returns the byte array value specified by the key and decoded as a UTF-8
- * encoded string, from the sidedb collection.
+ * Returns the byte array value specified by the key and decoded as a UTF-8 encoded string, from the sidedb
+ * collection.
*
* @param collection collection name
- * @param key name of the value
+ * @param key name of the value
* @return value the value read from the ledger
*/
default String getPrivateDataUTF8(final String collection, final String key) {
@@ -686,7 +609,7 @@ default String getPrivateDataUTF8(final String collection, final String key) {
/**
* Writes the specified value and key into the ledger.
*
- * @param key name of the value
+ * @param key name of the value
* @param value the value to write to the ledger
*/
default void putStringState(final String key, final String value) {
@@ -694,8 +617,8 @@ default void putStringState(final String key, final String value) {
}
/**
- * Returns the CHAINCODE type event that will be posted to interested clients
- * when the chaincode's result is committed to the ledger.
+ * Returns the CHAINCODE type event that will be posted to interested clients when the chaincode's result is
+ * committed to the ledger.
*
* @return the chaincode event or null
*/
@@ -704,8 +627,7 @@ default void putStringState(final String key, final String value) {
/**
* Returns the signed transaction proposal currently being executed.
*
- * @return null if the current transaction is an internal call to a system
- * chaincode.
+ * @return null if the current transaction is an internal call to a system chaincode.
*/
SignedProposal getSignedProposal();
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChatChaincodeWithPeer.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChatChaincodeWithPeer.java
index 88bf0361..f53d0ad1 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChatChaincodeWithPeer.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ChatChaincodeWithPeer.java
@@ -6,13 +6,12 @@
package org.hyperledger.fabric.shim;
import io.grpc.stub.StreamObserver;
+import java.io.IOException;
+import java.util.logging.Logger;
import org.hyperledger.fabric.Logging;
import org.hyperledger.fabric.protos.peer.ChaincodeGrpc;
import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
-import java.io.IOException;
-import java.util.logging.Logger;
-
public class ChatChaincodeWithPeer extends ChaincodeGrpc.ChaincodeImplBase {
private static Logger logger = Logger.getLogger(ChatChaincodeWithPeer.class.getName());
@@ -28,8 +27,8 @@ public class ChatChaincodeWithPeer extends ChaincodeGrpc.ChaincodeImplBase {
}
/**
- * Chaincode as a server - peer establishes a connection to the chaincode as a client
- * Currently only supports a stream connection.
+ * Chaincode as a server - peer establishes a connection to the chaincode as a client Currently only supports a
+ * stream connection.
*
* @param responseObserver
* @return
@@ -43,7 +42,8 @@ public StreamObserver connect(final StreamObserver "catch exception while chaincodeBase.connectToPeer(responseObserver)." + Logging.formatError(e));
+ logger.severe(() ->
+ "catch exception while chaincodeBase.connectToPeer(responseObserver)." + Logging.formatError(e));
return null;
}
}
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/GrpcServer.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/GrpcServer.java
index aa10efc3..9460dd22 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/GrpcServer.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/GrpcServer.java
@@ -8,9 +8,7 @@
import java.io.IOException;
-/**
- * Common interface for grpc server.
- */
+/** Common interface for grpc server. */
public interface GrpcServer {
/**
@@ -20,9 +18,7 @@ public interface GrpcServer {
*/
void start() throws IOException;
- /**
- * shutdown now grpc server.
- */
+ /** shutdown now grpc server. */
void stop();
/**
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/NettyChaincodeServer.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/NettyChaincodeServer.java
index a7073d78..df594ed2 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/NettyChaincodeServer.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/NettyChaincodeServer.java
@@ -10,9 +10,7 @@
public class NettyChaincodeServer implements ChaincodeServer {
- /**
- * Server.
- */
+ /** Server. */
private final GrpcServer grpcServer;
/**
@@ -22,7 +20,9 @@ public class NettyChaincodeServer implements ChaincodeServer {
* @param chaincodeServerProperties - setting for grpc server
* @throws IOException
*/
- public NettyChaincodeServer(final ChaincodeBase chaincodeBase, final ChaincodeServerProperties chaincodeServerProperties) throws IOException {
+ public NettyChaincodeServer(
+ final ChaincodeBase chaincodeBase, final ChaincodeServerProperties chaincodeServerProperties)
+ throws IOException {
// create listener and grpc server
grpcServer = new NettyGrpcServer(chaincodeBase, chaincodeServerProperties);
}
@@ -30,7 +30,7 @@ public NettyChaincodeServer(final ChaincodeBase chaincodeBase, final ChaincodeSe
/**
* run external chaincode server.
*
- * @throws IOException problem while start grpc server
+ * @throws IOException problem while start grpc server
* @throws InterruptedException thrown when block and awaiting shutdown gprc server
*/
public void start() throws IOException, InterruptedException {
@@ -38,9 +38,7 @@ public void start() throws IOException, InterruptedException {
grpcServer.blockUntilShutdown();
}
- /**
- * shutdown now grpc server.
- */
+ /** shutdown now grpc server. */
public void stop() {
grpcServer.stop();
}
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/NettyGrpcServer.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/NettyGrpcServer.java
index 4d6e9c33..bb142337 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/NettyGrpcServer.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/NettyGrpcServer.java
@@ -6,23 +6,19 @@
package org.hyperledger.fabric.shim;
-
import io.grpc.Server;
import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder;
import io.grpc.netty.shaded.io.netty.handler.ssl.ApplicationProtocolConfig;
import io.grpc.netty.shaded.io.netty.handler.ssl.ApplicationProtocolNames;
import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth;
import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder;
-import java.util.logging.Logger;
-
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;
+import java.util.logging.Logger;
-/**
- * implementation grpc server with NettyGrpcServer.
- */
+/** implementation grpc server with NettyGrpcServer. */
public final class NettyGrpcServer implements GrpcServer {
private static final Logger LOGGER = Logger.getLogger(NettyGrpcServer.class.getName());
@@ -32,11 +28,12 @@ public final class NettyGrpcServer implements GrpcServer {
/**
* init netty grpc server.
*
- * @param chaincodeBase - chaincode implementation (invoke, init)
+ * @param chaincodeBase - chaincode implementation (invoke, init)
* @param chaincodeServerProperties - setting for grpc server
* @throws IOException
*/
- public NettyGrpcServer(final ChaincodeBase chaincodeBase, final ChaincodeServerProperties chaincodeServerProperties) throws IOException {
+ public NettyGrpcServer(final ChaincodeBase chaincodeBase, final ChaincodeServerProperties chaincodeServerProperties)
+ throws IOException {
if (chaincodeBase == null) {
throw new IllegalArgumentException("chaincode must be specified");
}
@@ -45,7 +42,8 @@ public NettyGrpcServer(final ChaincodeBase chaincodeBase, final ChaincodeServerP
}
chaincodeServerProperties.validate();
- final NettyServerBuilder serverBuilder = NettyServerBuilder.forAddress(chaincodeServerProperties.getServerAddress())
+ final NettyServerBuilder serverBuilder = NettyServerBuilder.forAddress(
+ chaincodeServerProperties.getServerAddress())
.addService(new ChatChaincodeWithPeer(chaincodeBase))
.keepAliveTime(chaincodeServerProperties.getKeepAliveTimeMinutes(), TimeUnit.MINUTES)
.keepAliveTimeout(chaincodeServerProperties.getKeepAliveTimeoutSeconds(), TimeUnit.SECONDS)
@@ -56,14 +54,18 @@ public NettyGrpcServer(final ChaincodeBase chaincodeBase, final ChaincodeServerP
.maxInboundMessageSize(chaincodeServerProperties.getMaxInboundMessageSize());
if (chaincodeServerProperties.isTlsEnabled()) {
- final File keyCertChainFile = Paths.get(chaincodeServerProperties.getKeyCertChainFile()).toFile();
- final File keyFile = Paths.get(chaincodeServerProperties.getKeyFile()).toFile();
+ final File keyCertChainFile =
+ Paths.get(chaincodeServerProperties.getKeyCertChainFile()).toFile();
+ final File keyFile =
+ Paths.get(chaincodeServerProperties.getKeyFile()).toFile();
SslContextBuilder sslContextBuilder;
- if (chaincodeServerProperties.getKeyPassword() == null || chaincodeServerProperties.getKeyPassword().isEmpty()) {
+ if (chaincodeServerProperties.getKeyPassword() == null
+ || chaincodeServerProperties.getKeyPassword().isEmpty()) {
sslContextBuilder = SslContextBuilder.forServer(keyCertChainFile, keyFile);
} else {
- sslContextBuilder = SslContextBuilder.forServer(keyCertChainFile, keyFile, chaincodeServerProperties.getKeyPassword());
+ sslContextBuilder = SslContextBuilder.forServer(
+ keyCertChainFile, keyFile, chaincodeServerProperties.getKeyPassword());
}
ApplicationProtocolConfig apn = new ApplicationProtocolConfig(
@@ -74,7 +76,8 @@ public NettyGrpcServer(final ChaincodeBase chaincodeBase, final ChaincodeServerP
sslContextBuilder.applicationProtocolConfig(apn);
if (chaincodeServerProperties.getTrustCertCollectionFile() != null) {
- final File trustCertCollectionFile = Paths.get(chaincodeServerProperties.getTrustCertCollectionFile()).toFile();
+ final File trustCertCollectionFile = Paths.get(chaincodeServerProperties.getTrustCertCollectionFile())
+ .toFile();
sslContextBuilder.clientAuth(ClientAuth.REQUIRE);
sslContextBuilder.trustManager(trustCertCollectionFile);
}
@@ -83,7 +86,8 @@ public NettyGrpcServer(final ChaincodeBase chaincodeBase, final ChaincodeServerP
}
LOGGER.info("<<<<<<<<<<<<>>>>>>>>>>>:\n");
- LOGGER.info("ServerAddress:" + chaincodeServerProperties.getServerAddress().toString());
+ LOGGER.info(
+ "ServerAddress:" + chaincodeServerProperties.getServerAddress().toString());
LOGGER.info("MaxInboundMetadataSize:" + chaincodeServerProperties.getMaxInboundMetadataSize());
LOGGER.info("MaxInboundMessageSize:" + chaincodeServerProperties.getMaxInboundMessageSize());
LOGGER.info("MaxConnectionAgeSeconds:" + chaincodeServerProperties.getMaxConnectionAgeSeconds());
@@ -107,14 +111,12 @@ public NettyGrpcServer(final ChaincodeBase chaincodeBase, final ChaincodeServerP
*/
public void start() throws IOException {
LOGGER.info("start grpc server");
- Runtime.getRuntime()
- .addShutdownHook(
- new Thread(() -> {
- // Use stderr here since the logger may have been reset by its JVM shutdown hook.
- System.err.println("*** shutting down gRPC server since JVM is shutting down");
- NettyGrpcServer.this.stop();
- System.err.println("*** server shut down");
- }));
+ Runtime.getRuntime().addShutdownHook(new Thread(() -> {
+ // Use stderr here since the logger may have been reset by its JVM shutdown hook.
+ System.err.println("*** shutting down gRPC server since JVM is shutting down");
+ NettyGrpcServer.this.stop();
+ System.err.println("*** server shut down");
+ }));
server.start();
}
@@ -128,9 +130,7 @@ public void blockUntilShutdown() throws InterruptedException {
server.awaitTermination();
}
- /**
- * shutdown now grpc server.
- */
+ /** shutdown now grpc server. */
public void stop() {
LOGGER.info("shutdown now grpc server.");
server.shutdownNow();
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ResponseUtils.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ResponseUtils.java
index c46e1a78..bd6ee06e 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ResponseUtils.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ResponseUtils.java
@@ -14,8 +14,7 @@ public final class ResponseUtils {
private static Logger logger = Logger.getLogger(ResponseUtils.class.getName());
- private ResponseUtils() {
- }
+ private ResponseUtils() {}
/**
* @param message
@@ -26,9 +25,7 @@ public static Chaincode.Response newSuccessResponse(final String message, final
return new Chaincode.Response(SUCCESS, message, payload);
}
- /**
- * @return Chaincode.Response
- */
+ /** @return Chaincode.Response */
public static Chaincode.Response newSuccessResponse() {
return newSuccessResponse(null, null);
}
@@ -58,9 +55,7 @@ public static Chaincode.Response newErrorResponse(final String message, final by
return new Chaincode.Response(INTERNAL_SERVER_ERROR, message, payload);
}
- /**
- * @return Chaincode.Response
- */
+ /** @return Chaincode.Response */
public static Chaincode.Response newErrorResponse() {
return newErrorResponse(null, null);
}
@@ -100,7 +95,5 @@ public static Chaincode.Response newErrorResponse(final Throwable throwable) {
message = "Unexpected error";
return ResponseUtils.newErrorResponse(message, payload);
}
-
-
}
}
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/StateBasedEndorsement.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/StateBasedEndorsement.java
index a7b25020..c390ef90 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/StateBasedEndorsement.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/StateBasedEndorsement.java
@@ -10,10 +10,9 @@
import java.util.Map;
/**
- * StateBasedEndorsement provides a set of convenience methods to create and
- * modify a state-based endorsement policy. Endorsement policies created by this
- * convenience layer will always be a logical AND of "ORG.peer" principals for
- * one or more ORGs specified by the caller.
+ * StateBasedEndorsement provides a set of convenience methods to create and modify a state-based endorsement policy.
+ * Endorsement policies created by this convenience layer will always be a logical AND of "ORG.peer" principals for one
+ * or more ORGs specified by the caller.
*/
public interface StateBasedEndorsement {
/**
@@ -24,20 +23,18 @@ public interface StateBasedEndorsement {
byte[] policy();
/**
- * Adds the specified orgs to the list of orgs that are required to endorse. All
- * orgs MSP role types will be set to the role that is specified in the first
- * parameter. Among other aspects the desired role depends on the channel's
- * configuration: if it supports node OUs, it is likely going to be the PEER
- * role, while the MEMBER role is the suited one if it does not.
+ * Adds the specified orgs to the list of orgs that are required to endorse. All orgs MSP role types will be set to
+ * the role that is specified in the first parameter. Among other aspects the desired role depends on the channel's
+ * configuration: if it supports node OUs, it is likely going to be the PEER role, while the MEMBER role is the
+ * suited one if it does not.
*
- * @param roleType the MSP role type
+ * @param roleType the MSP role type
* @param organizations the list of organizations
*/
void addOrgs(RoleType roleType, String... organizations);
/**
- * deletes the specified channel orgs from the existing key-level endorsement
- * policy for this KVS key.
+ * deletes the specified channel orgs from the existing key-level endorsement policy for this KVS key.
*
* @param organizations the list of organizations
*/
@@ -50,17 +47,11 @@ public interface StateBasedEndorsement {
*/
List listOrgs();
- /**
- * RoleType of an endorsement policy's identity.
- */
+ /** RoleType of an endorsement policy's identity. */
enum RoleType {
- /**
- * RoleTypeMember identifies an org's member identity.
- */
+ /** RoleTypeMember identifies an org's member identity. */
RoleTypeMember("MEMBER"),
- /**
- * RoleTypePeer identifies an org's peer identity.
- */
+ /** RoleTypePeer identifies an org's peer identity. */
RoleTypePeer("PEER");
private final String val;
@@ -69,10 +60,7 @@ enum RoleType {
this.val = val;
}
- /**
- *
- * @return String value
- */
+ /** @return String value */
public String getVal() {
return val;
}
@@ -86,7 +74,6 @@ public String getVal() {
}
/**
- *
* @param val
* @return RoleType
*/
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementFactory.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementFactory.java
index da1db8ca..f93fc6ce 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementFactory.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementFactory.java
@@ -7,16 +7,11 @@
import org.hyperledger.fabric.shim.ext.sbe.StateBasedEndorsement;
-/**
- * Factory for {@link StateBasedEndorsement} objects.
- */
+/** Factory for {@link StateBasedEndorsement} objects. */
public class StateBasedEndorsementFactory {
private static StateBasedEndorsementFactory instance;
- /**
- *
- * @return Endorsement Factory
- */
+ /** @return Endorsement Factory */
public static synchronized StateBasedEndorsementFactory getInstance() {
if (instance == null) {
instance = new StateBasedEndorsementFactory();
@@ -25,8 +20,8 @@ public static synchronized StateBasedEndorsementFactory getInstance() {
}
/**
- * Constructs a state-based endorsement policy from a given serialized EP byte
- * array. If the byte array is empty, a new EP is created.
+ * Constructs a state-based endorsement policy from a given serialized EP byte array. If the byte array is empty, a
+ * new EP is created.
*
* @param ep serialized endorsement policy
* @return New StateBasedEndorsement instance
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementImpl.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementImpl.java
index 6dbdbd26..68a67369 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementImpl.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementImpl.java
@@ -5,12 +5,12 @@
*/
package org.hyperledger.fabric.shim.ext.sbe.impl;
+import com.google.protobuf.InvalidProtocolBufferException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hyperledger.fabric.protos.common.MSPPrincipal;
@@ -21,11 +21,7 @@
import org.hyperledger.fabric.protos.common.SignaturePolicyEnvelope;
import org.hyperledger.fabric.shim.ext.sbe.StateBasedEndorsement;
-import com.google.protobuf.InvalidProtocolBufferException;
-
-/**
- * Implements {@link StateBasedEndorsement}.
- */
+/** Implements {@link StateBasedEndorsement}. */
public final class StateBasedEndorsementImpl implements StateBasedEndorsement {
private static Log logger = LogFactory.getLog(StateBasedEndorsementImpl.class);
@@ -44,7 +40,6 @@ public final class StateBasedEndorsementImpl implements StateBasedEndorsement {
} catch (final InvalidProtocolBufferException e) {
throw new IllegalArgumentException("error unmarshalling endorsement policy bytes", e);
}
-
}
@Override
@@ -81,7 +76,9 @@ public List listOrgs() {
}
private void setMSPIDsFromSP(final SignaturePolicyEnvelope spe) {
- spe.getIdentitiesList().stream().filter(identity -> Classification.ROLE.equals(identity.getPrincipalClassification())).forEach(this::addOrg);
+ spe.getIdentitiesList().stream()
+ .filter(identity -> Classification.ROLE.equals(identity.getPrincipalClassification()))
+ .forEach(this::addOrg);
}
private void addOrg(final MSPPrincipal identity) {
@@ -102,15 +99,23 @@ private SignaturePolicyEnvelope policyFromMSPIDs() {
final List sigpolicy = new ArrayList<>();
for (int i = 0; i < mspids.size(); i++) {
final String mspid = mspids.get(i);
- principals.add(MSPPrincipal.newBuilder().setPrincipalClassification(Classification.ROLE)
- .setPrincipal(MSPRole.newBuilder().setMspIdentifier(mspid).setRole(orgs.get(mspid)).build().toByteString()).build());
+ principals.add(MSPPrincipal.newBuilder()
+ .setPrincipalClassification(Classification.ROLE)
+ .setPrincipal(MSPRole.newBuilder()
+ .setMspIdentifier(mspid)
+ .setRole(orgs.get(mspid))
+ .build()
+ .toByteString())
+ .build());
sigpolicy.add(StateBasedEndorsementUtils.signedBy(i));
}
// create the policy: it requires exactly 1 signature from all of the principals
- return SignaturePolicyEnvelope.newBuilder().setVersion(0).setRule(StateBasedEndorsementUtils.nOutOf(mspids.size(), sigpolicy))
- .addAllIdentities(principals).build();
+ return SignaturePolicyEnvelope.newBuilder()
+ .setVersion(0)
+ .setRule(StateBasedEndorsementUtils.nOutOf(mspids.size(), sigpolicy))
+ .addAllIdentities(principals)
+ .build();
}
-
}
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementUtils.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementUtils.java
index 4234a70c..845056bc 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementUtils.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/StateBasedEndorsementUtils.java
@@ -7,7 +7,6 @@
import java.util.Arrays;
import java.util.List;
-
import org.hyperledger.fabric.protos.common.MSPPrincipal;
import org.hyperledger.fabric.protos.common.MSPPrincipal.Classification;
import org.hyperledger.fabric.protos.common.MSPRole;
@@ -16,15 +15,10 @@
import org.hyperledger.fabric.protos.common.SignaturePolicy.NOutOf;
import org.hyperledger.fabric.protos.common.SignaturePolicyEnvelope;
-/**
- * Utility to create {@link SignaturePolicy} and
- * {@link SignaturePolicyEnvelope}.
- */
+/** Utility to create {@link SignaturePolicy} and {@link SignaturePolicyEnvelope}. */
public final class StateBasedEndorsementUtils {
- private StateBasedEndorsementUtils() {
-
- }
+ private StateBasedEndorsementUtils() {}
/**
* Creates a SignaturePolicy requiring a given signer's signature.
@@ -39,20 +33,21 @@ static SignaturePolicy signedBy(final int index) {
/**
* Create a policy.
*
- * Creates a policy which requires N out of the slice of policies to evaluate to
- * true
+ * Creates a policy which requires N out of the slice of policies to evaluate to true
*
* @param n
* @param policies
* @return SignaturePolicy
*/
static SignaturePolicy nOutOf(final int n, final List policies) {
- return SignaturePolicy.newBuilder().setNOutOf(NOutOf.newBuilder().setN(n).addAllRules(policies).build()).build();
+ return SignaturePolicy.newBuilder()
+ .setNOutOf(NOutOf.newBuilder().setN(n).addAllRules(policies).build())
+ .build();
}
/**
- * Creates a {@link SignaturePolicyEnvelope} requiring 1 signature from any
- * fabric entity, having the passed role, of the specified MSP.
+ * Creates a {@link SignaturePolicyEnvelope} requiring 1 signature from any fabric entity, having the passed role,
+ * of the specified MSP.
*
* @param mspId
* @param role
@@ -60,13 +55,21 @@ static SignaturePolicy nOutOf(final int n, final List policies)
*/
static SignaturePolicyEnvelope signedByFabricEntity(final String mspId, final MSPRoleType role) {
// specify the principal: it's a member of the msp we just found
- final MSPPrincipal principal = MSPPrincipal.newBuilder().setPrincipalClassification(Classification.ROLE)
- .setPrincipal(MSPRole.newBuilder().setMspIdentifier(mspId).setRole(role).build().toByteString()).build();
+ final MSPPrincipal principal = MSPPrincipal.newBuilder()
+ .setPrincipalClassification(Classification.ROLE)
+ .setPrincipal(MSPRole.newBuilder()
+ .setMspIdentifier(mspId)
+ .setRole(role)
+ .build()
+ .toByteString())
+ .build();
// create the policy: it requires exactly 1 signature from the first (and only)
// principal
- return SignaturePolicyEnvelope.newBuilder().setVersion(0).setRule(nOutOf(1, Arrays.asList(signedBy(0)))).addIdentities(principal).build();
-
+ return SignaturePolicyEnvelope.newBuilder()
+ .setVersion(0)
+ .setRule(nOutOf(1, Arrays.asList(signedBy(0))))
+ .addIdentities(principal)
+ .build();
}
-
}
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/package-info.java
index f4f3bb51..329c3a35 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/package-info.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/impl/package-info.java
@@ -1,6 +1,6 @@
-/*
- * Copyright 2023 IBM All Rights Reserved.
- *
- * SPDX-License-Identifier: Apache-2.0
- */
-package org.hyperledger.fabric.shim.ext.sbe.impl;
+/*
+ * Copyright 2023 IBM All Rights Reserved.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ */
+package org.hyperledger.fabric.shim.ext.sbe.impl;
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/package-info.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/package-info.java
index 50735e07..15c86c68 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/package-info.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/ext/sbe/package-info.java
@@ -4,7 +4,5 @@
* SPDX-License-Identifier: Apache-2.0
*/
-/**
- * Provides an interface for creating and modifying state-based endorsement policies.
- */
+/** Provides an interface for creating and modifying state-based endorsement policies. */
package org.hyperledger.fabric.shim.ext.sbe;
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeInvocationTask.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeInvocationTask.java
index 8cafebdb..b2c3c916 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeInvocationTask.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeInvocationTask.java
@@ -9,27 +9,22 @@
import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.ERROR;
import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.RESPONSE;
+import com.google.protobuf.ByteString;
+import com.google.protobuf.InvalidProtocolBufferException;
+import io.opentelemetry.api.trace.Span;
+import io.opentelemetry.api.trace.StatusCode;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
import java.util.logging.Logger;
-
-import io.opentelemetry.api.trace.Span;
-import io.opentelemetry.api.trace.StatusCode;
import org.hyperledger.fabric.Logging;
import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
import org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type;
import org.hyperledger.fabric.shim.Chaincode;
import org.hyperledger.fabric.shim.ChaincodeStub;
-
-import com.google.protobuf.ByteString;
-import com.google.protobuf.InvalidProtocolBufferException;
import org.hyperledger.fabric.traces.Traces;
-/**
- * A 'Callable' implementation the has the job of invoking the chaincode, and
- * matching the response and requests.
- */
+/** A 'Callable' implementation the has the job of invoking the chaincode, and matching the response and requests. */
public class ChaincodeInvocationTask implements Callable {
private static Logger logger = Logger.getLogger(ChaincodeInvocationTask.class.getName());
@@ -51,17 +46,16 @@ public class ChaincodeInvocationTask implements Callable {
private final Chaincode chaincode;
/**
- *
- * @param message The incoming message that has triggered this task into
- * execution
- * @param type Is this init or invoke? (v2 Fabric deprecates init)
- * @param outgoingMessage The Consumer functional interface to send any requests
- * for ledger state
- * @param chaincode A instance of the end users chaincode
- *
+ * @param message The incoming message that has triggered this task into execution
+ * @param type Is this init or invoke? (v2 Fabric deprecates init)
+ * @param outgoingMessage The Consumer functional interface to send any requests for ledger state
+ * @param chaincode A instance of the end users chaincode
*/
- public ChaincodeInvocationTask(final ChaincodeMessage message, final Type type,
- final Consumer outgoingMessage, final Chaincode chaincode) {
+ public ChaincodeInvocationTask(
+ final ChaincodeMessage message,
+ final Type type,
+ final Consumer outgoingMessage,
+ final Chaincode chaincode) {
this.key = message.getChannelId() + message.getTxid();
this.type = type;
@@ -71,9 +65,7 @@ public ChaincodeInvocationTask(final ChaincodeMessage message, final Type type,
this.message = message;
}
- /**
- * Main method to power the invocation of the chaincode.
- */
+ /** Main method to power the invocation of the chaincode. */
@Override
public ChaincodeMessage call() {
ChaincodeMessage finalResponseMessage;
@@ -95,7 +87,6 @@ public ChaincodeMessage call() {
// result is what will be sent to the peer as a response to this invocation
final Chaincode.Response result;
-
perfLogger.fine(() -> "> task:invoke TX::" + this.txId);
// Call chaincode's invoke
@@ -110,24 +101,27 @@ public ChaincodeMessage call() {
if (result.getStatus().getCode() >= Chaincode.Response.Status.INTERNAL_SERVER_ERROR.getCode()) {
// Send ERROR with entire result.Message as payload
- logger.severe(() -> String.format("[%-8.8s] Invoke failed with error code %d. Sending %s",
+ logger.severe(() -> String.format(
+ "[%-8.8s] Invoke failed with error code %d. Sending %s",
message.getTxid(), result.getStatus().getCode(), ERROR));
- finalResponseMessage = ChaincodeMessageFactory.newCompletedEventMessage(message.getChannelId(),
- message.getTxid(), result, stub.getEvent());
+ finalResponseMessage = ChaincodeMessageFactory.newCompletedEventMessage(
+ message.getChannelId(), message.getTxid(), result, stub.getEvent());
if (span != null) {
span.setStatus(StatusCode.ERROR, result.getMessage());
}
} else {
// Send COMPLETED with entire result as payload
- logger.fine(() -> String.format("[%-8.8s] Invoke succeeded. Sending %s", message.getTxid(), COMPLETED));
- finalResponseMessage = ChaincodeMessageFactory.newCompletedEventMessage(message.getChannelId(),
- message.getTxid(), result, stub.getEvent());
+ logger.fine(
+ () -> String.format("[%-8.8s] Invoke succeeded. Sending %s", message.getTxid(), COMPLETED));
+ finalResponseMessage = ChaincodeMessageFactory.newCompletedEventMessage(
+ message.getChannelId(), message.getTxid(), result, stub.getEvent());
}
} catch (InvalidProtocolBufferException | RuntimeException e) {
- logger.severe(() -> String.format("[%-8.8s] Invoke failed. Sending %s: %s", message.getTxid(), ERROR, e));
- finalResponseMessage = ChaincodeMessageFactory.newErrorEventMessage(message.getChannelId(),
- message.getTxid(), e);
+ logger.severe(
+ () -> String.format("[%-8.8s] Invoke failed. Sending %s: %s", message.getTxid(), ERROR, e));
+ finalResponseMessage =
+ ChaincodeMessageFactory.newErrorEventMessage(message.getChannelId(), message.getTxid(), e);
if (span != null) {
span.setStatus(StatusCode.ERROR, e.getMessage());
}
@@ -165,11 +159,11 @@ public boolean equals(final ChaincodeInvocationTask task) {
}
/**
- * Posts the message that the peer has responded with to this task's request
- * Uses an 'ArrayBlockingQueue'. This lets the producer post messages without waiting
- * for the consumer. And the consumer can block until a message is posted.
+ * Posts the message that the peer has responded with to this task's request Uses an 'ArrayBlockingQueue'. This lets
+ * the producer post messages without waiting for the consumer. And the consumer can block until a message is
+ * posted.
*
- * In this case the data is only passed to the executing tasks.
+ * In this case the data is only passed to the executing tasks.
*
* @param msg Chaincode message to pass pack
* @throws InterruptedException should something really really go wrong
@@ -182,17 +176,16 @@ public void postMessage(final ChaincodeMessage msg) throws InterruptedException
/**
* Send the chaincode message back to the peer.
*
- * Implementation of the Functional interface 'InvokeChaincodeSupport'
+ *
Implementation of the Functional interface 'InvokeChaincodeSupport'
*
- * It will send the message, via the outgoingMessageConsumer, and then block on
- * the 'Exchanger' to wait for the response to come.
+ *
It will send the message, via the outgoingMessageConsumer, and then block on the 'Exchanger' to wait for the
+ * response to come.
*
- * This Exchange is an atomic operation between the thread that is running this
- * task, and the thread that is handling the communication from the peer.
+ *
This Exchange is an atomic operation between the thread that is running this task, and the thread that is
+ * handling the communication from the peer.
*
* @param message The chaincode message from the peer
* @return ByteString to be parsed by the caller
- *
*/
protected ByteString invoke(final ChaincodeMessage message) {
@@ -220,12 +213,12 @@ protected ByteString invoke(final ChaincodeMessage message) {
logger.severe(() -> String.format("[%-8.8s] Unsuccessful response received.", txId));
throw new RuntimeException(String.format("[%-8.8s]Unsuccessful response received.", txId));
default:
- logger.severe(() -> String.format("[%-8.8s] Unexpected %s response received. Expected %s or %s.", txId,
- response.getType(), RESPONSE, ERROR));
- throw new RuntimeException(String.format("[%-8.8s] Unexpected %s response received. Expected %s or %s.",
+ logger.severe(() -> String.format(
+ "[%-8.8s] Unexpected %s response received. Expected %s or %s.",
+ txId, response.getType(), RESPONSE, ERROR));
+ throw new RuntimeException(String.format(
+ "[%-8.8s] Unexpected %s response received. Expected %s or %s.",
txId, response.getType(), RESPONSE, ERROR));
}
-
}
-
}
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeMessageFactory.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeMessageFactory.java
index 831e2277..651bc81a 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeMessageFactory.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeMessageFactory.java
@@ -16,11 +16,11 @@
import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.PUT_STATE_METADATA;
import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.REGISTER;
+import com.google.protobuf.ByteString;
import java.io.PrintWriter;
import java.io.StringWriter;
-
-import org.hyperledger.fabric.protos.peer.ChaincodeID;
import org.hyperledger.fabric.protos.peer.ChaincodeEvent;
+import org.hyperledger.fabric.protos.peer.ChaincodeID;
import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
import org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type;
import org.hyperledger.fabric.protos.peer.DelState;
@@ -28,82 +28,170 @@
import org.hyperledger.fabric.protos.peer.GetStateMetadata;
import org.hyperledger.fabric.protos.peer.PutState;
import org.hyperledger.fabric.protos.peer.PutStateMetadata;
-import org.hyperledger.fabric.protos.peer.StateMetadata;
import org.hyperledger.fabric.protos.peer.Response;
import org.hyperledger.fabric.protos.peer.Response.Builder;
+import org.hyperledger.fabric.protos.peer.StateMetadata;
import org.hyperledger.fabric.shim.Chaincode;
-import com.google.protobuf.ByteString;
-
public final class ChaincodeMessageFactory {
- private ChaincodeMessageFactory() {
- }
-
- protected static ChaincodeMessage newGetPrivateDataHashEventMessage(final String channelId, final String txId, final String collection, final String key) {
- return newEventMessage(GET_PRIVATE_DATA_HASH, channelId, txId, GetState.newBuilder().setCollection(collection).setKey(key).build().toByteString());
- }
-
- protected static ChaincodeMessage newGetStateEventMessage(final String channelId, final String txId, final String collection, final String key) {
- return newEventMessage(GET_STATE, channelId, txId, GetState.newBuilder().setCollection(collection).setKey(key).build().toByteString());
- }
-
- protected static ChaincodeMessage newGetStateMetadataEventMessage(final String channelId, final String txId, final String collection, final String key) {
- return newEventMessage(GET_STATE_METADATA, channelId, txId, GetStateMetadata.newBuilder().setCollection(collection).setKey(key).build().toByteString());
- }
-
- protected static ChaincodeMessage newPutStateEventMessage(final String channelId, final String txId, final String collection, final String key,
+ private ChaincodeMessageFactory() {}
+
+ protected static ChaincodeMessage newGetPrivateDataHashEventMessage(
+ final String channelId, final String txId, final String collection, final String key) {
+ return newEventMessage(
+ GET_PRIVATE_DATA_HASH,
+ channelId,
+ txId,
+ GetState.newBuilder()
+ .setCollection(collection)
+ .setKey(key)
+ .build()
+ .toByteString());
+ }
+
+ protected static ChaincodeMessage newGetStateEventMessage(
+ final String channelId, final String txId, final String collection, final String key) {
+ return newEventMessage(
+ GET_STATE,
+ channelId,
+ txId,
+ GetState.newBuilder()
+ .setCollection(collection)
+ .setKey(key)
+ .build()
+ .toByteString());
+ }
+
+ protected static ChaincodeMessage newGetStateMetadataEventMessage(
+ final String channelId, final String txId, final String collection, final String key) {
+ return newEventMessage(
+ GET_STATE_METADATA,
+ channelId,
+ txId,
+ GetStateMetadata.newBuilder()
+ .setCollection(collection)
+ .setKey(key)
+ .build()
+ .toByteString());
+ }
+
+ protected static ChaincodeMessage newPutStateEventMessage(
+ final String channelId,
+ final String txId,
+ final String collection,
+ final String key,
final ByteString value) {
- return newEventMessage(PUT_STATE, channelId, txId, PutState.newBuilder().setCollection(collection).setKey(key).setValue(value).build().toByteString());
- }
-
- protected static ChaincodeMessage newPutStateMetadataEventMessage(final String channelId, final String txId, final String collection, final String key,
- final String metakey, final ByteString value) {
- return newEventMessage(PUT_STATE_METADATA, channelId, txId, PutStateMetadata.newBuilder().setCollection(collection).setKey(key)
- .setMetadata(StateMetadata.newBuilder().setMetakey(metakey).setValue(value).build()).build().toByteString());
- }
-
- protected static ChaincodeMessage newDeleteStateEventMessage(final String channelId, final String txId, final String collection, final String key) {
- return newEventMessage(DEL_STATE, channelId, txId, DelState.newBuilder().setCollection(collection).setKey(key).build().toByteString());
- }
-
- protected static ChaincodeMessage newPurgeStateEventMessage(final String channelId, final String txId, final String collection, final String key) {
- return newEventMessage(Type.PURGE_PRIVATE_DATA, channelId, txId, DelState.newBuilder().setCollection(collection).setKey(key).build().toByteString());
- }
-
- protected static ChaincodeMessage newErrorEventMessage(final String channelId, final String txId, final Throwable throwable) {
+ return newEventMessage(
+ PUT_STATE,
+ channelId,
+ txId,
+ PutState.newBuilder()
+ .setCollection(collection)
+ .setKey(key)
+ .setValue(value)
+ .build()
+ .toByteString());
+ }
+
+ protected static ChaincodeMessage newPutStateMetadataEventMessage(
+ final String channelId,
+ final String txId,
+ final String collection,
+ final String key,
+ final String metakey,
+ final ByteString value) {
+ return newEventMessage(
+ PUT_STATE_METADATA,
+ channelId,
+ txId,
+ PutStateMetadata.newBuilder()
+ .setCollection(collection)
+ .setKey(key)
+ .setMetadata(StateMetadata.newBuilder()
+ .setMetakey(metakey)
+ .setValue(value)
+ .build())
+ .build()
+ .toByteString());
+ }
+
+ protected static ChaincodeMessage newDeleteStateEventMessage(
+ final String channelId, final String txId, final String collection, final String key) {
+ return newEventMessage(
+ DEL_STATE,
+ channelId,
+ txId,
+ DelState.newBuilder()
+ .setCollection(collection)
+ .setKey(key)
+ .build()
+ .toByteString());
+ }
+
+ protected static ChaincodeMessage newPurgeStateEventMessage(
+ final String channelId, final String txId, final String collection, final String key) {
+ return newEventMessage(
+ Type.PURGE_PRIVATE_DATA,
+ channelId,
+ txId,
+ DelState.newBuilder()
+ .setCollection(collection)
+ .setKey(key)
+ .build()
+ .toByteString());
+ }
+
+ protected static ChaincodeMessage newErrorEventMessage(
+ final String channelId, final String txId, final Throwable throwable) {
return newErrorEventMessage(channelId, txId, printStackTrace(throwable));
}
- protected static ChaincodeMessage newErrorEventMessage(final String channelId, final String txId, final String message) {
+ protected static ChaincodeMessage newErrorEventMessage(
+ final String channelId, final String txId, final String message) {
return newErrorEventMessage(channelId, txId, message, null);
}
- protected static ChaincodeMessage newErrorEventMessage(final String channelId, final String txId, final String message, final ChaincodeEvent event) {
+ protected static ChaincodeMessage newErrorEventMessage(
+ final String channelId, final String txId, final String message, final ChaincodeEvent event) {
return newEventMessage(ERROR, channelId, txId, ByteString.copyFromUtf8(message), event);
}
- protected static ChaincodeMessage newCompletedEventMessage(final String channelId, final String txId, final Chaincode.Response response,
- final ChaincodeEvent event) {
- final ChaincodeMessage message = newEventMessage(COMPLETED, channelId, txId, toProtoResponse(response).toByteString(), event);
+ protected static ChaincodeMessage newCompletedEventMessage(
+ final String channelId, final String txId, final Chaincode.Response response, final ChaincodeEvent event) {
+ final ChaincodeMessage message = newEventMessage(
+ COMPLETED, channelId, txId, toProtoResponse(response).toByteString(), event);
return message;
}
- protected static ChaincodeMessage newInvokeChaincodeMessage(final String channelId, final String txId, final ByteString payload) {
+ protected static ChaincodeMessage newInvokeChaincodeMessage(
+ final String channelId, final String txId, final ByteString payload) {
return newEventMessage(INVOKE_CHAINCODE, channelId, txId, payload, null);
}
protected static ChaincodeMessage newRegisterChaincodeMessage(final ChaincodeID chaincodeId) {
- return ChaincodeMessage.newBuilder().setType(REGISTER).setPayload(chaincodeId.toByteString()).build();
+ return ChaincodeMessage.newBuilder()
+ .setType(REGISTER)
+ .setPayload(chaincodeId.toByteString())
+ .build();
}
- protected static ChaincodeMessage newEventMessage(final Type type, final String channelId, final String txId, final ByteString payload) {
+ protected static ChaincodeMessage newEventMessage(
+ final Type type, final String channelId, final String txId, final ByteString payload) {
return newEventMessage(type, channelId, txId, payload, null);
}
- protected static ChaincodeMessage newEventMessage(final Type type, final String channelId, final String txId, final ByteString payload,
+ protected static ChaincodeMessage newEventMessage(
+ final Type type,
+ final String channelId,
+ final String txId,
+ final ByteString payload,
final ChaincodeEvent event) {
- final ChaincodeMessage.Builder builder = ChaincodeMessage.newBuilder().setType(type).setChannelId(channelId).setTxid(txId).setPayload(payload);
+ final ChaincodeMessage.Builder builder = ChaincodeMessage.newBuilder()
+ .setType(type)
+ .setChannelId(channelId)
+ .setTxid(txId)
+ .setPayload(payload);
if (event != null) {
builder.setChaincodeEvent(event);
}
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeSupportClient.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeSupportClient.java
index 7216ad30..d3a6190d 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeSupportClient.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/ChaincodeSupportClient.java
@@ -5,21 +5,19 @@
*/
package org.hyperledger.fabric.shim.impl;
+import io.grpc.ClientInterceptor;
+import io.grpc.ManagedChannel;
+import io.grpc.ManagedChannelBuilder;
+import io.grpc.stub.StreamObserver;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.logging.Logger;
-
-import io.grpc.ClientInterceptor;
import org.hyperledger.fabric.Logging;
import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
import org.hyperledger.fabric.protos.peer.ChaincodeSupportGrpc;
import org.hyperledger.fabric.protos.peer.ChaincodeSupportGrpc.ChaincodeSupportStub;
-
-import io.grpc.ManagedChannel;
-import io.grpc.ManagedChannelBuilder;
-import io.grpc.stub.StreamObserver;
import org.hyperledger.fabric.traces.Traces;
public class ChaincodeSupportClient {
@@ -29,9 +27,7 @@ public class ChaincodeSupportClient {
private final ManagedChannel channel;
private final ChaincodeSupportStub stub;
- /**
- * @param channelBuilder
- */
+ /** @param channelBuilder */
public ChaincodeSupportClient(final ManagedChannelBuilder> channelBuilder) {
ClientInterceptor interceptor = Traces.getProvider().createInterceptor();
if (interceptor != null) {
@@ -41,10 +37,7 @@ public ChaincodeSupportClient(final ManagedChannelBuilder> channelBuilder) {
this.stub = ChaincodeSupportGrpc.newStub(channel);
}
- /**
- *
- * @param itm
- */
+ /** @param itm */
public void shutdown(final InvocationTaskManager itm) {
// first shutdown the thread pool
@@ -59,16 +52,15 @@ public void shutdown(final InvocationTaskManager itm) {
channel.shutdownNow();
Thread.currentThread().interrupt();
}
-
}
/**
- *
* @param itm
* @param requestObserver
* @throws IOException verify parameters error
*/
- public void start(final InvocationTaskManager itm, final StreamObserver requestObserver) throws IOException {
+ public void start(final InvocationTaskManager itm, final StreamObserver requestObserver)
+ throws IOException {
if (requestObserver == null) {
throw new IOException("StreamObserver 'requestObserver' for chat with peer can't be null");
}
@@ -110,6 +102,7 @@ public void accept(final ChaincodeMessage t) {
/**
* ChaincodeSupportStub.
+ *
* @return stub
*/
public ChaincodeSupportStub getStub() {
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationStubImpl.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationStubImpl.java
index 08783272..809b36a5 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationStubImpl.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationStubImpl.java
@@ -13,6 +13,9 @@
import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.GET_QUERY_RESULT;
import static org.hyperledger.fabric.protos.peer.ChaincodeMessage.Type.GET_STATE_BY_RANGE;
+import com.google.protobuf.ByteString;
+import com.google.protobuf.InvalidProtocolBufferException;
+import com.google.protobuf.Timestamp;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.MessageDigest;
@@ -25,28 +28,27 @@
import java.util.function.Function;
import java.util.logging.Logger;
import java.util.stream.Collectors;
-
import org.hyperledger.fabric.protos.common.ChannelHeader;
import org.hyperledger.fabric.protos.common.Header;
import org.hyperledger.fabric.protos.common.HeaderType;
import org.hyperledger.fabric.protos.common.SignatureHeader;
import org.hyperledger.fabric.protos.ledger.queryresult.KV;
+import org.hyperledger.fabric.protos.peer.ChaincodeEvent;
import org.hyperledger.fabric.protos.peer.ChaincodeID;
import org.hyperledger.fabric.protos.peer.ChaincodeInput;
-import org.hyperledger.fabric.protos.peer.ChaincodeSpec;
-import org.hyperledger.fabric.protos.peer.ChaincodeEvent;
-import org.hyperledger.fabric.protos.peer.QueryMetadata;
import org.hyperledger.fabric.protos.peer.ChaincodeMessage;
+import org.hyperledger.fabric.protos.peer.ChaincodeProposalPayload;
+import org.hyperledger.fabric.protos.peer.ChaincodeSpec;
import org.hyperledger.fabric.protos.peer.GetQueryResult;
import org.hyperledger.fabric.protos.peer.GetState;
import org.hyperledger.fabric.protos.peer.GetStateByRange;
-import org.hyperledger.fabric.protos.peer.QueryResultBytes;
-import org.hyperledger.fabric.protos.peer.StateMetadataResult;
-import org.hyperledger.fabric.protos.peer.ChaincodeProposalPayload;
+import org.hyperledger.fabric.protos.peer.MetaDataKeys;
import org.hyperledger.fabric.protos.peer.Proposal;
-import org.hyperledger.fabric.protos.peer.SignedProposal;
+import org.hyperledger.fabric.protos.peer.QueryMetadata;
+import org.hyperledger.fabric.protos.peer.QueryResultBytes;
import org.hyperledger.fabric.protos.peer.Response;
-import org.hyperledger.fabric.protos.peer.MetaDataKeys;
+import org.hyperledger.fabric.protos.peer.SignedProposal;
+import org.hyperledger.fabric.protos.peer.StateMetadataResult;
import org.hyperledger.fabric.shim.Chaincode;
import org.hyperledger.fabric.shim.ChaincodeStub;
import org.hyperledger.fabric.shim.ledger.CompositeKey;
@@ -55,10 +57,6 @@
import org.hyperledger.fabric.shim.ledger.QueryResultsIterator;
import org.hyperledger.fabric.shim.ledger.QueryResultsIteratorWithMetadata;
-import com.google.protobuf.ByteString;
-import com.google.protobuf.InvalidProtocolBufferException;
-import com.google.protobuf.Timestamp;
-
class InvocationStubImpl implements ChaincodeStub {
private static final String UNSPECIFIED_START_KEY = new String(Character.toChars(0x000001));
@@ -79,7 +77,6 @@ class InvocationStubImpl implements ChaincodeStub {
private ChaincodeEvent event;
/**
- *
* @param message
* @param handler
* @throws InvalidProtocolBufferException
@@ -93,7 +90,8 @@ class InvocationStubImpl implements ChaincodeStub {
this.args = Collections.unmodifiableList(input.getArgsList());
this.signedProposal = message.getProposal();
- if (this.signedProposal == null || this.signedProposal.getProposalBytes().isEmpty()) {
+ if (this.signedProposal == null
+ || this.signedProposal.getProposalBytes().isEmpty()) {
this.creator = null;
this.txTimestamp = null;
this.transientMap = Collections.emptyMap();
@@ -105,8 +103,8 @@ class InvocationStubImpl implements ChaincodeStub {
final ChannelHeader channelHeader = ChannelHeader.parseFrom(header.getChannelHeader());
validateProposalType(channelHeader);
final SignatureHeader signatureHeader = SignatureHeader.parseFrom(header.getSignatureHeader());
- final ChaincodeProposalPayload chaincodeProposalPayload = ChaincodeProposalPayload
- .parseFrom(proposal.getPayload());
+ final ChaincodeProposalPayload chaincodeProposalPayload =
+ ChaincodeProposalPayload.parseFrom(proposal.getPayload());
final Timestamp timestamp = channelHeader.getTimestamp();
this.txTimestamp = Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos());
@@ -124,8 +122,8 @@ private byte[] computeBinding(final ChannelHeader channelHeader, final Signature
final MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(signatureHeader.getNonce().asReadOnlyByteBuffer());
messageDigest.update(this.creator.asReadOnlyByteBuffer());
- final ByteBuffer epochBytes = ByteBuffer.allocate(Long.BYTES).order(ByteOrder.LITTLE_ENDIAN)
- .putLong(channelHeader.getEpoch());
+ final ByteBuffer epochBytes =
+ ByteBuffer.allocate(Long.BYTES).order(ByteOrder.LITTLE_ENDIAN).putLong(channelHeader.getEpoch());
epochBytes.flip();
messageDigest.update(epochBytes);
return messageDigest.digest();
@@ -133,12 +131,12 @@ private byte[] computeBinding(final ChannelHeader channelHeader, final Signature
private void validateProposalType(final ChannelHeader channelHeader) {
switch (HeaderType.forNumber(channelHeader.getType())) {
- case ENDORSER_TRANSACTION:
- case CONFIG:
- return;
- default:
- throw new RuntimeException(
- String.format("Unexpected transaction type: %s", HeaderType.forNumber(channelHeader.getType())));
+ case ENDORSER_TRANSACTION:
+ case CONFIG:
+ return;
+ default:
+ throw new RuntimeException(String.format(
+ "Unexpected transaction type: %s", HeaderType.forNumber(channelHeader.getType())));
}
}
@@ -168,7 +166,9 @@ public void setEvent(final String name, final byte[] payload) {
throw new IllegalArgumentException("event name can not be nil string");
}
if (payload != null) {
- this.event = ChaincodeEvent.newBuilder().setEventName(name).setPayload(ByteString.copyFrom(payload))
+ this.event = ChaincodeEvent.newBuilder()
+ .setEventName(name)
+ .setPayload(ByteString.copyFrom(payload))
.build();
} else {
this.event = ChaincodeEvent.newBuilder().setEventName(name).build();
@@ -192,23 +192,26 @@ public String getTxId() {
@Override
public byte[] getState(final String key) {
- return this.handler.invoke(ChaincodeMessageFactory.newGetStateEventMessage(channelId, txId, "", key))
+ return this.handler
+ .invoke(ChaincodeMessageFactory.newGetStateEventMessage(channelId, txId, "", key))
.toByteArray();
}
@Override
public byte[] getStateValidationParameter(final String key) {
- final ByteString payload = handler
- .invoke(ChaincodeMessageFactory.newGetStateMetadataEventMessage(channelId, txId, "", key));
+ final ByteString payload =
+ handler.invoke(ChaincodeMessageFactory.newGetStateMetadataEventMessage(channelId, txId, "", key));
try {
final StateMetadataResult stateMetadataResult = StateMetadataResult.parseFrom(payload);
final Map stateMetadataMap = new HashMap<>();
- stateMetadataResult.getEntriesList()
+ stateMetadataResult
+ .getEntriesList()
.forEach(entry -> stateMetadataMap.put(entry.getMetakey(), entry.getValue()));
if (stateMetadataMap.containsKey(MetaDataKeys.VALIDATION_PARAMETER.toString())) {
- return stateMetadataMap.get(MetaDataKeys.VALIDATION_PARAMETER.toString())
+ return stateMetadataMap
+ .get(MetaDataKeys.VALIDATION_PARAMETER.toString())
.toByteArray();
}
} catch (final InvalidProtocolBufferException e) {
@@ -217,7 +220,6 @@ public byte[] getStateValidationParameter(final String key) {
}
return null;
-
}
@Override
@@ -230,8 +232,8 @@ public void putState(final String key, final byte[] value) {
@Override
public void setStateValidationParameter(final String key, final byte[] value) {
validateKey(key);
- final ChaincodeMessage msg = ChaincodeMessageFactory.newPutStateMetadataEventMessage(channelId, txId, "", key,
- MetaDataKeys.VALIDATION_PARAMETER.toString(), ByteString.copyFrom(value));
+ final ChaincodeMessage msg = ChaincodeMessageFactory.newPutStateMetadataEventMessage(
+ channelId, txId, "", key, MetaDataKeys.VALIDATION_PARAMETER.toString(), ByteString.copyFrom(value));
this.handler.invoke(msg);
}
@@ -257,19 +259,22 @@ public QueryResultsIterator getStateByRange(final String startKey, fin
return executeGetStateByRange("", start, end);
}
- private QueryResultsIterator executeGetStateByRange(final String collection, final String startKey,
- final String endKey) {
+ private QueryResultsIterator executeGetStateByRange(
+ final String collection, final String startKey, final String endKey) {
- final ByteString requestPayload = GetStateByRange.newBuilder().setCollection(collection).setStartKey(startKey)
- .setEndKey(endKey).build().toByteString();
+ final ByteString requestPayload = GetStateByRange.newBuilder()
+ .setCollection(collection)
+ .setStartKey(startKey)
+ .setEndKey(endKey)
+ .build()
+ .toByteString();
- final ChaincodeMessage requestMessage = ChaincodeMessageFactory.newEventMessage(GET_STATE_BY_RANGE, channelId,
- txId, requestPayload);
+ final ChaincodeMessage requestMessage =
+ ChaincodeMessageFactory.newEventMessage(GET_STATE_BY_RANGE, channelId, txId, requestPayload);
final ByteString response = handler.invoke(requestMessage);
- return new QueryResultsIteratorImpl(this.handler, channelId, txId, response,
- queryResultBytesToKv.andThen(KeyValueImpl::new));
-
+ return new QueryResultsIteratorImpl(
+ this.handler, channelId, txId, response, queryResultBytesToKv.andThen(KeyValueImpl::new));
}
private final Function queryResultBytesToKv = new Function() {
@@ -281,12 +286,11 @@ public KV apply(final QueryResultBytes queryResultBytes) {
throw new RuntimeException(e);
}
}
-
};
@Override
- public QueryResultsIteratorWithMetadata getStateByRangeWithPagination(final String startKey,
- final String endKey, final int pageSize, final String bookmark) {
+ public QueryResultsIteratorWithMetadata getStateByRangeWithPagination(
+ final String startKey, final String endKey, final int pageSize, final String bookmark) {
String start = startKey;
String end = endKey;
@@ -300,26 +304,32 @@ public QueryResultsIteratorWithMetadata getStateByRangeWithPagination(
CompositeKey.validateSimpleKeys(start, end);
- final QueryMetadata queryMetadata = QueryMetadata.newBuilder().setBookmark(bookmark)
- .setPageSize(pageSize).build();
+ final QueryMetadata queryMetadata = QueryMetadata.newBuilder()
+ .setBookmark(bookmark)
+ .setPageSize(pageSize)
+ .build();
return executeGetStateByRangeWithMetadata("", start, end, queryMetadata.toByteString());
}
- private QueryResultsIteratorWithMetadataImpl executeGetStateByRangeWithMetadata(final String collection,
- final String startKey, final String endKey, final ByteString metadata) {
+ private QueryResultsIteratorWithMetadataImpl executeGetStateByRangeWithMetadata(
+ final String collection, final String startKey, final String endKey, final ByteString metadata) {
- final ByteString payload = GetStateByRange.newBuilder().setCollection(collection).setStartKey(startKey)
- .setEndKey(endKey).setMetadata(metadata).build().toByteString();
+ final ByteString payload = GetStateByRange.newBuilder()
+ .setCollection(collection)
+ .setStartKey(startKey)
+ .setEndKey(endKey)
+ .setMetadata(metadata)
+ .build()
+ .toByteString();
- final ChaincodeMessage requestMessage = ChaincodeMessageFactory.newEventMessage(GET_STATE_BY_RANGE, channelId,
- txId, payload);
+ final ChaincodeMessage requestMessage =
+ ChaincodeMessageFactory.newEventMessage(GET_STATE_BY_RANGE, channelId, txId, payload);
final ByteString response = this.handler.invoke(requestMessage);
- return new QueryResultsIteratorWithMetadataImpl<>(this.handler, getChannelId(), getTxId(), response,
- queryResultBytesToKv.andThen(KeyValueImpl::new));
-
+ return new QueryResultsIteratorWithMetadataImpl<>(
+ this.handler, getChannelId(), getTxId(), response, queryResultBytesToKv.andThen(KeyValueImpl::new));
}
@Override
@@ -337,8 +347,8 @@ public QueryResultsIterator getStateByPartialCompositeKey(final String
}
@Override
- public QueryResultsIterator getStateByPartialCompositeKey(final String objectType,
- final String... attributes) {
+ public QueryResultsIterator getStateByPartialCompositeKey(
+ final String objectType, final String... attributes) {
return getStateByPartialCompositeKey(new CompositeKey(objectType, attributes));
}
@@ -368,11 +378,13 @@ public QueryResultsIteratorWithMetadata getStateByPartialCompositeKeyW
cKeyAsString = compositeKey.toString();
}
- final QueryMetadata queryMetadata = QueryMetadata.newBuilder().setBookmark(bookmark)
- .setPageSize(pageSize).build();
+ final QueryMetadata queryMetadata = QueryMetadata.newBuilder()
+ .setBookmark(bookmark)
+ .setPageSize(pageSize)
+ .build();
- return executeGetStateByRangeWithMetadata("", cKeyAsString, cKeyAsString + MAX_UNICODE_RUNE,
- queryMetadata.toByteString());
+ return executeGetStateByRangeWithMetadata(
+ "", cKeyAsString, cKeyAsString + MAX_UNICODE_RUNE, queryMetadata.toByteString());
}
@Override
@@ -388,63 +400,82 @@ public CompositeKey splitCompositeKey(final String compositeKey) {
@Override
public QueryResultsIterator getQueryResult(final String query) {
- final ByteString requestPayload = GetQueryResult.newBuilder().setCollection("").setQuery(query).build()
+ final ByteString requestPayload = GetQueryResult.newBuilder()
+ .setCollection("")
+ .setQuery(query)
+ .build()
.toByteString();
- final ChaincodeMessage requestMessage = ChaincodeMessageFactory.newEventMessage(GET_QUERY_RESULT, channelId,
- txId, requestPayload);
+ final ChaincodeMessage requestMessage =
+ ChaincodeMessageFactory.newEventMessage(GET_QUERY_RESULT, channelId, txId, requestPayload);
final ByteString response = handler.invoke(requestMessage);
- return new QueryResultsIteratorImpl(this.handler, channelId, txId, response,
- queryResultBytesToKv.andThen(KeyValueImpl::new));
+ return new QueryResultsIteratorImpl(
+ this.handler, channelId, txId, response, queryResultBytesToKv.andThen(KeyValueImpl::new));
}
@Override
- public QueryResultsIteratorWithMetadata getQueryResultWithPagination(final String query,
- final int pageSize, final String bookmark) {
+ public QueryResultsIteratorWithMetadata getQueryResultWithPagination(
+ final String query, final int pageSize, final String bookmark) {
- final ByteString queryMetadataPayload = QueryMetadata.newBuilder().setBookmark(bookmark)
- .setPageSize(pageSize).build().toByteString();
- final ByteString requestPayload = GetQueryResult.newBuilder().setCollection("").setQuery(query)
- .setMetadata(queryMetadataPayload).build().toByteString();
- final ChaincodeMessage requestMessage = ChaincodeMessageFactory.newEventMessage(GET_QUERY_RESULT, channelId,
- txId, requestPayload);
+ final ByteString queryMetadataPayload = QueryMetadata.newBuilder()
+ .setBookmark(bookmark)
+ .setPageSize(pageSize)
+ .build()
+ .toByteString();
+ final ByteString requestPayload = GetQueryResult.newBuilder()
+ .setCollection("")
+ .setQuery(query)
+ .setMetadata(queryMetadataPayload)
+ .build()
+ .toByteString();
+ final ChaincodeMessage requestMessage =
+ ChaincodeMessageFactory.newEventMessage(GET_QUERY_RESULT, channelId, txId, requestPayload);
final ByteString response = handler.invoke(requestMessage);
- return new QueryResultsIteratorWithMetadataImpl(this.handler, channelId, txId, response,
- queryResultBytesToKv.andThen(KeyValueImpl::new));
-
+ return new QueryResultsIteratorWithMetadataImpl(
+ this.handler, channelId, txId, response, queryResultBytesToKv.andThen(KeyValueImpl::new));
}
@Override
public QueryResultsIterator getHistoryForKey(final String key) {
- final ByteString requestPayload = GetQueryResult.newBuilder().setCollection("").setQuery(key).build()
+ final ByteString requestPayload = GetQueryResult.newBuilder()
+ .setCollection("")
+ .setQuery(key)
+ .build()
.toByteString();
- final ChaincodeMessage requestMessage = ChaincodeMessageFactory.newEventMessage(GET_HISTORY_FOR_KEY, channelId,
- txId, requestPayload);
+ final ChaincodeMessage requestMessage =
+ ChaincodeMessageFactory.newEventMessage(GET_HISTORY_FOR_KEY, channelId, txId, requestPayload);
final ByteString response = handler.invoke(requestMessage);
- return new QueryResultsIteratorImpl(this.handler, channelId, txId, response,
+ return new QueryResultsIteratorImpl(
+ this.handler,
+ channelId,
+ txId,
+ response,
queryResultBytesToKeyModification.andThen(KeyModificationImpl::new));
-
}
- private final Function queryResultBytesToKeyModification =
- new Function() {
- @Override
- public org.hyperledger.fabric.protos.ledger.queryresult.KeyModification apply(final QueryResultBytes queryResultBytes) {
- try {
- return org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.parseFrom(queryResultBytes.getResultBytes());
- } catch (final InvalidProtocolBufferException e) {
- throw new RuntimeException(e);
- }
- }
- };
+ private final Function
+ queryResultBytesToKeyModification =
+ new Function() {
+ @Override
+ public org.hyperledger.fabric.protos.ledger.queryresult.KeyModification apply(
+ final QueryResultBytes queryResultBytes) {
+ try {
+ return org.hyperledger.fabric.protos.ledger.queryresult.KeyModification.parseFrom(
+ queryResultBytes.getResultBytes());
+ } catch (final InvalidProtocolBufferException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ };
@Override
public byte[] getPrivateData(final String collection, final String key) {
validateCollection(collection);
- return this.handler.invoke(ChaincodeMessageFactory.newGetStateEventMessage(channelId, txId, collection, key))
+ return this.handler
+ .invoke(ChaincodeMessageFactory.newGetStateEventMessage(channelId, txId, collection, key))
.toByteArray();
}
@@ -453,10 +484,13 @@ public byte[] getPrivateDataHash(final String collection, final String key) {
validateCollection(collection);
- final ByteString requestPayload = GetState.newBuilder().setCollection(collection).setKey(key).build()
+ final ByteString requestPayload = GetState.newBuilder()
+ .setCollection(collection)
+ .setKey(key)
+ .build()
.toByteString();
- final ChaincodeMessage requestMessage = ChaincodeMessageFactory.newEventMessage(GET_PRIVATE_DATA_HASH,
- channelId, txId, requestPayload);
+ final ChaincodeMessage requestMessage =
+ ChaincodeMessageFactory.newEventMessage(GET_PRIVATE_DATA_HASH, channelId, txId, requestPayload);
return handler.invoke(requestMessage).toByteArray();
}
@@ -465,16 +499,18 @@ public byte[] getPrivateDataHash(final String collection, final String key) {
public byte[] getPrivateDataValidationParameter(final String collection, final String key) {
validateCollection(collection);
- final ByteString payload = handler
- .invoke(ChaincodeMessageFactory.newGetStateMetadataEventMessage(channelId, txId, collection, key));
+ final ByteString payload = handler.invoke(
+ ChaincodeMessageFactory.newGetStateMetadataEventMessage(channelId, txId, collection, key));
try {
final StateMetadataResult stateMetadataResult = StateMetadataResult.parseFrom(payload);
final Map stateMetadataMap = new HashMap<>();
- stateMetadataResult.getEntriesList()
+ stateMetadataResult
+ .getEntriesList()
.forEach(entry -> stateMetadataMap.put(entry.getMetakey(), entry.getValue()));
if (stateMetadataMap.containsKey(MetaDataKeys.VALIDATION_PARAMETER.toString())) {
- return stateMetadataMap.get(MetaDataKeys.VALIDATION_PARAMETER.toString())
+ return stateMetadataMap
+ .get(MetaDataKeys.VALIDATION_PARAMETER.toString())
.toByteArray();
}
} catch (final InvalidProtocolBufferException e) {
@@ -489,16 +525,20 @@ public byte[] getPrivateDataValidationParameter(final String collection, final S
public void putPrivateData(final String collection, final String key, final byte[] value) {
validateKey(key);
validateCollection(collection);
- this.handler.invoke(ChaincodeMessageFactory.newPutStateEventMessage(channelId, txId, collection, key,
- ByteString.copyFrom(value)));
+ this.handler.invoke(ChaincodeMessageFactory.newPutStateEventMessage(
+ channelId, txId, collection, key, ByteString.copyFrom(value)));
}
@Override
public void setPrivateDataValidationParameter(final String collection, final String key, final byte[] value) {
validateKey(key);
validateCollection(collection);
- final ChaincodeMessage msg = ChaincodeMessageFactory.newPutStateMetadataEventMessage(channelId, txId,
- collection, key, MetaDataKeys.VALIDATION_PARAMETER.toString(),
+ final ChaincodeMessage msg = ChaincodeMessageFactory.newPutStateMetadataEventMessage(
+ channelId,
+ txId,
+ collection,
+ key,
+ MetaDataKeys.VALIDATION_PARAMETER.toString(),
ByteString.copyFrom(value));
this.handler.invoke(msg);
}
@@ -506,22 +546,22 @@ public void setPrivateDataValidationParameter(final String collection, final Str
@Override
public void delPrivateData(final String collection, final String key) {
validateCollection(collection);
- final ChaincodeMessage msg = ChaincodeMessageFactory.newDeleteStateEventMessage(channelId, txId, collection,
- key);
+ final ChaincodeMessage msg =
+ ChaincodeMessageFactory.newDeleteStateEventMessage(channelId, txId, collection, key);
this.handler.invoke(msg);
}
@Override
public void purgePrivateData(final String collection, final String key) {
validateCollection(collection);
- final ChaincodeMessage msg = ChaincodeMessageFactory.newPurgeStateEventMessage(channelId, txId, collection,
- key);
+ final ChaincodeMessage msg =
+ ChaincodeMessageFactory.newPurgeStateEventMessage(channelId, txId, collection, key);
this.handler.invoke(msg);
}
@Override
- public QueryResultsIterator getPrivateDataByRange(final String collection, final String startKey,
- final String endKey) {
+ public QueryResultsIterator getPrivateDataByRange(
+ final String collection, final String startKey, final String endKey) {
String start = startKey;
String end = endKey;
@@ -538,8 +578,8 @@ public QueryResultsIterator getPrivateDataByRange(final String collect
}
@Override
- public QueryResultsIterator getPrivateDataByPartialCompositeKey(final String collection,
- final String compositeKey) {
+ public QueryResultsIterator getPrivateDataByPartialCompositeKey(
+ final String collection, final String compositeKey) {
CompositeKey key;
@@ -555,8 +595,8 @@ public QueryResultsIterator getPrivateDataByPartialCompositeKey(final
}
@Override
- public QueryResultsIterator getPrivateDataByPartialCompositeKey(final String collection,
- final CompositeKey compositeKey) {
+ public QueryResultsIterator getPrivateDataByPartialCompositeKey(
+ final String collection, final CompositeKey compositeKey) {
String cKeyAsString;
if (compositeKey == null) {
cKeyAsString = new CompositeKey(UNSPECIFIED_START_KEY).toString();
@@ -568,26 +608,30 @@ public QueryResultsIterator getPrivateDataByPartialCompositeKey(final
}
@Override
- public QueryResultsIterator getPrivateDataByPartialCompositeKey(final String collection,
- final String objectType, final String... attributes) {
+ public QueryResultsIterator getPrivateDataByPartialCompositeKey(
+ final String collection, final String objectType, final String... attributes) {
return getPrivateDataByPartialCompositeKey(collection, new CompositeKey(objectType, attributes));
}
@Override
public QueryResultsIterator getPrivateDataQueryResult(final String collection, final String query) {
validateCollection(collection);
- final ByteString requestPayload = GetQueryResult.newBuilder().setCollection(collection).setQuery(query).build()
+ final ByteString requestPayload = GetQueryResult.newBuilder()
+ .setCollection(collection)
+ .setQuery(query)
+ .build()
.toByteString();
- final ChaincodeMessage requestMessage = ChaincodeMessageFactory.newEventMessage(GET_QUERY_RESULT, channelId,
- txId, requestPayload);
+ final ChaincodeMessage requestMessage =
+ ChaincodeMessageFactory.newEventMessage(GET_QUERY_RESULT, channelId, txId, requestPayload);
final ByteString response = handler.invoke(requestMessage);
- return new QueryResultsIteratorImpl(this.handler, channelId, txId, response,
- queryResultBytesToKv.andThen(KeyValueImpl::new));
+ return new QueryResultsIteratorImpl(
+ this.handler, channelId, txId, response, queryResultBytesToKv.andThen(KeyValueImpl::new));
}
@Override
- public Chaincode.Response invokeChaincode(final String chaincodeName, final List args, final String channel) {
+ public Chaincode.Response invokeChaincode(
+ final String chaincodeName, final List args, final String channel) {
// internally we handle chaincode name as a composite name
final String compositeName;
if (channel != null && !channel.trim().isEmpty()) {
@@ -600,11 +644,13 @@ public Chaincode.Response invokeChaincode(final String chaincodeName, final List
final ByteString invocationSpecPayload = ChaincodeSpec.newBuilder()
.setChaincodeId(ChaincodeID.newBuilder().setName(compositeName).build())
.setInput(ChaincodeInput.newBuilder()
- .addAllArgs(args.stream().map(ByteString::copyFrom).collect(Collectors.toList())).build())
- .build().toByteString();
+ .addAllArgs(args.stream().map(ByteString::copyFrom).collect(Collectors.toList()))
+ .build())
+ .build()
+ .toByteString();
- final ChaincodeMessage invokeChaincodeMessage = ChaincodeMessageFactory
- .newInvokeChaincodeMessage(this.channelId, this.txId, invocationSpecPayload);
+ final ChaincodeMessage invokeChaincodeMessage =
+ ChaincodeMessageFactory.newInvokeChaincodeMessage(this.channelId, this.txId, invocationSpecPayload);
final ByteString response = this.handler.invoke(invokeChaincodeMessage);
try {
@@ -613,14 +659,15 @@ public Chaincode.Response invokeChaincode(final String chaincodeName, final List
final ChaincodeMessage responseMessage = ChaincodeMessage.parseFrom(response);
// the actual response message must be of type COMPLETED
- LOGGER.fine(String.format("[%-8.8s] %s response received from other chaincode.", txId,
- responseMessage.getType()));
+ LOGGER.fine(String.format(
+ "[%-8.8s] %s response received from other chaincode.", txId, responseMessage.getType()));
if (responseMessage.getType() == COMPLETED) {
// success
- final Response r = Response
- .parseFrom(responseMessage.getPayload());
- return new Chaincode.Response(Chaincode.Response.Status.forCode(r.getStatus()), r.getMessage(),
+ final Response r = Response.parseFrom(responseMessage.getPayload());
+ return new Chaincode.Response(
+ Chaincode.Response.Status.forCode(r.getStatus()),
+ r.getMessage(),
r.getPayload() == null ? null : r.getPayload().toByteArray());
} else {
// error
@@ -630,7 +677,6 @@ public Chaincode.Response invokeChaincode(final String chaincodeName, final List
} catch (final InvalidProtocolBufferException e) {
throw new RuntimeException(e);
}
-
}
@Override
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationTaskExecutor.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationTaskExecutor.java
index 97d68fbd..c2402e48 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationTaskExecutor.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationTaskExecutor.java
@@ -12,19 +12,13 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
-
import org.hyperledger.fabric.metrics.TaskMetricsCollector;
-/**
- *
- *
- *
- */
+/** */
public final class InvocationTaskExecutor extends ThreadPoolExecutor implements TaskMetricsCollector {
private static Logger logger = Logger.getLogger(InvocationTaskExecutor.class.getName());
/**
- *
* @param corePoolSize
* @param maximumPoolSize
* @param keepAliveTime
@@ -33,8 +27,14 @@ public final class InvocationTaskExecutor extends ThreadPoolExecutor implements
* @param factory
* @param handler
*/
- public InvocationTaskExecutor(final int corePoolSize, final int maximumPoolSize, final long keepAliveTime, final TimeUnit unit,
- final BlockingQueue workQueue, final ThreadFactory factory, final RejectedExecutionHandler handler) {
+ public InvocationTaskExecutor(
+ final int corePoolSize,
+ final int maximumPoolSize,
+ final long keepAliveTime,
+ final TimeUnit unit,
+ final BlockingQueue workQueue,
+ final ThreadFactory factory,
+ final RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, factory, handler);
prestartCoreThread();
logger.info("Thread pool created");
@@ -46,7 +46,6 @@ public InvocationTaskExecutor(final int corePoolSize, final int maximumPoolSize,
protected void beforeExecute(final Thread thread, final Runnable task) {
super.beforeExecute(thread, task);
count.incrementAndGet();
-
}
@Override
@@ -64,5 +63,4 @@ public int getCurrentTaskCount() {
public int getCurrentQueueCount() {
return this.getQueue().size();
}
-
}
diff --git a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationTaskManager.java b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationTaskManager.java
index 424f3a84..2de85597 100644
--- a/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationTaskManager.java
+++ b/fabric-chaincode-shim/src/main/java/org/hyperledger/fabric/shim/impl/InvocationTaskManager.java
@@ -22,7 +22,6 @@
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.logging.Logger;
-
import org.hyperledger.fabric.Logging;
import org.hyperledger.fabric.metrics.Metrics;
import org.hyperledger.fabric.protos.peer.ChaincodeID;
@@ -31,13 +30,10 @@
import org.hyperledger.fabric.shim.ChaincodeBase;
/**
- * The InvocationTask Manager handles the message level communication with the
- * peer.
- *
- * In the current 1.4 Fabric Protocol this is in practice a singleton - because
- * the peer will ignore multiple 'register' calls. And an instance of this will
- * be created per register call for a given chaincodeID.
+ * The InvocationTask Manager handles the message level communication with the peer.
*
+ * In the current 1.4 Fabric Protocol this is in practice a singleton - because the peer will ignore multiple
+ * 'register' calls. And an instance of this will be created per register call for a given chaincodeID.
*/
public final class InvocationTaskManager {
@@ -47,7 +43,7 @@ public final class InvocationTaskManager {
/**
* Get an instance of the Invocation Task Manager.
*
- * @param chaincode Chaincode Instance
+ * @param chaincode Chaincode Instance
* @param chaincodeId ID of the chaincode
* @return InvocationTaskManager
*/
@@ -84,7 +80,6 @@ public Thread newThread(final Runnable r) {
Thread thread = Executors.defaultThreadFactory().newThread(r);
thread.setName("fabric-txinvoke:" + next.incrementAndGet());
return thread;
-
}
};
@@ -102,7 +97,7 @@ public Thread newThread(final Runnable r) {
/**
* New InvocationTaskManager.
*
- * @param chaincode Chaincode Instance
+ * @param chaincode Chaincode Instance
* @param chaincodeId ID of the chaincode
*/
public InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID chaincodeId) {
@@ -128,11 +123,10 @@ public InvocationTaskManager(final ChaincodeBase chaincode, final ChaincodeID ch
logger.info(() -> "Keep Alive Time [TP_KEEP_ALIVE_MS]" + keepAliveTime);
workQueue = new LinkedBlockingQueue(queueSize);
- taskService = new InvocationTaskExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
- threadFactory, handler);
+ taskService = new InvocationTaskExecutor(
+ corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
Metrics.getProvider().setTaskMetricsCollector(taskService);
-
}
/**
@@ -145,35 +139,38 @@ public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) throws I
if (chaincodeMessage == null) {
throw new IllegalArgumentException("chaincodeMessage is null");
}
- logger.fine(() -> String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage)));
+ logger.fine(() ->
+ String.format("[%-8.8s] %s", chaincodeMessage.getTxid(), ChaincodeBase.toJsonString(chaincodeMessage)));
try {
final Type msgType = chaincodeMessage.getType();
switch (chaincode.getState()) {
case CREATED:
if (msgType == REGISTERED) {
chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.ESTABLISHED);
- logger.fine(() -> String.format("[%-8.8s] Received REGISTERED: moving to established state",
+ logger.fine(() -> String.format(
+ "[%-8.8s] Received REGISTERED: moving to established state",
chaincodeMessage.getTxid()));
} else {
- logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle",
- chaincodeMessage.getTxid(), msgType));
+ logger.warning(() -> String.format(
+ "[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType));
}
break;
case ESTABLISHED:
if (msgType == READY) {
chaincode.setState(org.hyperledger.fabric.shim.ChaincodeBase.CCState.READY);
- logger.fine(() -> String.format("[%-8.8s] Received READY: ready for invocations",
- chaincodeMessage.getTxid()));
+ logger.fine(() -> String.format(
+ "[%-8.8s] Received READY: ready for invocations", chaincodeMessage.getTxid()));
} else {
- logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle",
- chaincodeMessage.getTxid(), msgType));
+ logger.warning(() -> String.format(
+ "[%-8.8s] Received %s: cannot handle", chaincodeMessage.getTxid(), msgType));
}
break;
case READY:
handleMsg(chaincodeMessage, msgType);
break;
default:
- logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle",
+ logger.warning(() -> String.format(
+ "[%-8.8s] Received %s: cannot handle",
chaincodeMessage.getTxid(), chaincodeMessage.getType()));
break;
}
@@ -187,8 +184,7 @@ public void onChaincodeMessage(final ChaincodeMessage chaincodeMessage) throws I
}
/**
- * Key method to take the message, determine if it is a new transaction or an
- * answer (good or bad) to a stub api.
+ * Key method to take the message, determine if it is a new transaction or an answer (good or bad) to a stub api.
*
* @param message
* @param msgType
@@ -205,15 +201,14 @@ private void handleMsg(final ChaincodeMessage message, final Type msgType) {
newTask(message, msgType);
break;
default:
- logger.warning(() -> String.format("[%-8.8s] Received %s: cannot handle", message.getTxid(),
- message.getType()));
+ logger.warning(() ->
+ String.format("[%-8.8s] Received %s: cannot handle", message.getTxid(), message.getType()));
break;
}
}
/**
- * Send a message from the peer to the correct task. This will be a response to
- * something like a getState() call.
+ * Send a message from the peer to the correct task. This will be a response to something like a getState() call.
*
* @param message ChaincodeMessage from the peer
*/
@@ -233,8 +228,8 @@ private void sendToTask(final ChaincodeMessage message) {
logger.severe(
() -> "Failed to send response to the task task " + message.getTxid() + Logging.formatError(e));
- final ChaincodeMessage m = ChaincodeMessageFactory.newErrorEventMessage(message.getChannelId(),
- message.getTxid(), "Failed to send response to task");
+ final ChaincodeMessage m = ChaincodeMessageFactory.newErrorEventMessage(
+ message.getChannelId(), message.getTxid(), "Failed to send response to task");
this.outgoingMessage.accept(m);
}
}
@@ -243,14 +238,13 @@ private void sendToTask(final ChaincodeMessage message) {
* Create a new task to handle this transaction function.
*
* @param message ChaincodeMessage to process
- * @param type Type of message = INIT or INVOKE. INIT is deprecated in future
- * versions
+ * @param type Type of message = INIT or INVOKE. INIT is deprecated in future versions
* @throws InterruptedException
*/
private void newTask(final ChaincodeMessage message, final Type type) {
String txid = message.getTxid();
- final ChaincodeInvocationTask task = new ChaincodeInvocationTask(message, type, this.outgoingMessage,
- this.chaincode);
+ final ChaincodeInvocationTask task =
+ new ChaincodeInvocationTask(message, type, this.outgoingMessage, this.chaincode);
perflogger.fine(() -> "> newTask:created TX::" + txid);
@@ -260,9 +254,11 @@ private void newTask(final ChaincodeMessage message, final Type type) {
// submit the task to run, with the taskService providing the
// threading support.
- final CompletableFuture response = CompletableFuture.runAsync(() -> {
- task.call();
- }, taskService);
+ final CompletableFuture