Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.client.cli;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import com.beust.jcommander.Parameters;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.util.concurrent.RateLimiter;
import com.google.gson.JsonParseException;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.io.Encoder;
import org.apache.avro.io.EncoderFactory;
import org.apache.avro.io.JsonDecoder;
import org.apache.pulsar.client.api.Authentication;
import org.apache.pulsar.client.api.AuthenticationDataProvider;
import org.apache.pulsar.client.api.ClientBuilder;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.ProducerBuilder;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.Schema;
import org.apache.pulsar.client.api.TypedMessageBuilder;
import org.apache.pulsar.client.api.schema.KeyValueSchema;
import org.apache.pulsar.client.impl.schema.SchemaInfoImpl;
import org.apache.pulsar.common.naming.TopicName;
import org.apache.pulsar.common.schema.KeyValue;
import org.apache.pulsar.common.schema.KeyValueEncodingType;
import org.apache.pulsar.common.schema.SchemaType;
import org.apache.pulsar.common.util.ObjectMapperFactory;
import org.apache.pulsar.websocket.data.ProducerMessage;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.websocket.api.RemoteEndpoint;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* pulsar-client produce command implementation.
*
*/
@Parameters(commandDescription = "Produce messages to a specified topic")
public class CmdProduce {
private static final Logger LOG = LoggerFactory.getLogger(PulsarClientTool.class);
private static final int MAX_MESSAGES = 1000;
static final String KEY_VALUE_ENCODING_TYPE_NOT_SET = "";
private static final String KEY_VALUE_ENCODING_TYPE_SEPARATED = "separated";
private static final String KEY_VALUE_ENCODING_TYPE_INLINE = "inline";
@Parameter(description = "TopicName", required = true)
private List mainOptions;
@Parameter(names = { "-m", "--messages" },
description = "Messages to send, either -m or -f must be specified. Specify -m for each message.",
splitter = NoSplitter.class)
private List messages = new ArrayList<>();
@Parameter(names = { "-f", "--files" },
description = "Comma separated file paths to send, either -m or -f must be specified.")
private List messageFileNames = new ArrayList<>();
@Parameter(names = { "-n", "--num-produce" },
description = "Number of times to send message(s), the count of messages/files * num-produce "
+ "should below than " + MAX_MESSAGES + ".")
private int numTimesProduce = 1;
@Parameter(names = { "-r", "--rate" },
description = "Rate (in msg/sec) at which to produce,"
+ " value 0 means to produce messages as fast as possible.")
private double publishRate = 0;
@Parameter(names = { "-db", "--disable-batching" }, description = "Disable batch sending of messages")
private boolean disableBatching = false;
@Parameter(names = { "-c",
"--chunking" }, description = "Should split the message and publish in chunks if message size is "
+ "larger than allowed max size")
private boolean chunkingAllowed = false;
@Parameter(names = { "-s", "--separator" },
description = "Character to split messages string on default is comma")
private String separator = ",";
@Parameter(names = { "-p", "--properties"}, description = "Properties to add, Comma separated "
+ "key=value string, like k1=v1,k2=v2.")
private List properties = new ArrayList<>();
@Parameter(names = { "-k", "--key"}, description = "Partitioning key to add to each message")
private String key;
@Parameter(names = { "-kvk", "--key-value-key"}, description = "Value to add as message key in KeyValue schema")
private String keyValueKey;
@Parameter(names = { "-kvkf", "--key-value-key-file"},
description = "Path to file containing the value to add as message key in KeyValue schema. "
+ "JSON and AVRO files are supported.")
private String keyValueKeyFile;
@Parameter(names = { "-vs", "--value-schema"}, description = "Schema type (can be bytes,avro,json,string...)")
private String valueSchema = "bytes";
@Parameter(names = { "-ks", "--key-schema"}, description = "Schema type (can be bytes,avro,json,string...)")
private String keySchema = "string";
@Parameter(names = { "-kvet", "--key-value-encoding-type"},
description = "Key Value Encoding Type (it can be separated or inline)")
private String keyValueEncodingType = null;
@Parameter(names = { "-ekn", "--encryption-key-name" }, description = "The public key name to encrypt payload")
private String encKeyName = null;
@Parameter(names = { "-ekv",
"--encryption-key-value" }, description = "The URI of public key to encrypt payload, for example "
+ "file:///path/to/public.key or data:application/x-pem-file;base64,*****")
private String encKeyValue = null;
@Parameter(names = { "-dr",
"--disable-replication" }, description = "Disable geo-replication for messages.")
private boolean disableReplication = false;
private ClientBuilder clientBuilder;
private Authentication authentication;
private String serviceURL;
public CmdProduce() {
// Do nothing
}
/**
* Set Pulsar client configuration.
*
*/
public void updateConfig(ClientBuilder newBuilder, Authentication authentication, String serviceURL) {
this.clientBuilder = newBuilder;
this.authentication = authentication;
this.serviceURL = serviceURL;
}
/*
* Generate a list of message bodies which can be used to build messages
*
* @param stringMessages List of strings to send
*
* @param messageFileNames List of file names to read and send
*
* @return list of message bodies
*/
static List generateMessageBodies(List stringMessages, List messageFileNames,
Schema schema) {
List messageBodies = new ArrayList<>();
for (String m : stringMessages) {
if (schema.getSchemaInfo().getType() == SchemaType.AVRO) {
// JSON TO AVRO
org.apache.avro.Schema avroSchema = ((Optional) schema.getNativeSchema()).get();
byte[] encoded = jsonToAvro(m, avroSchema);
messageBodies.add(encoded);
} else {
messageBodies.add(m.getBytes());
}
}
try {
for (String filename : messageFileNames) {
byte[] fileBytes = Files.readAllBytes(Paths.get(filename));
messageBodies.add(fileBytes);
}
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
return messageBodies;
}
private static byte[] jsonToAvro(String m, org.apache.avro.Schema avroSchema){
try {
GenericDatumReader