Fetching data from zookeeper znode - java

I tried to get the data from zookeeper's znode using Java API. Followed below link
https://www.tutorialspoint.com/zookeeper/zookeeper_api.htm
Program: ZKGetData.java
I'm getting results like this
"(clusterSecondarynn1node4.test.com �>(�>)"
How to get "node4.test.com" alone.

It is strongly recommended to use some layer against ZK, like Apache Curator, or ZkClient.
Here's an example
CuratorFramework zkClient = CuratorFrameworkFactory.builder().connectString("localhost:2181").build();
zkClient.start();
boolean isExist = zkClient.checkExists().forPath("/myNode") != null;
if (isExist) {
byte[] myNodeBytes = zkClient.getData().forPath("/myNode");
if (myNodeBytes != null && myNodeBytes.length > 0) {
System.out.println(new String(myNodeBytes));
}
}
else {
zkClient.create().withMode(CreateMode.PERSISTENT).forPath("/myNode", "foo".getBytes());
}

Related

How to set next continuation token on AWS ListObjectsV2Request object

I am using AWS SDK for Java 2.15.66. I am trying to list all the objects under a particular folder. I am following code sample here https://docs.aws.amazon.com/AmazonS3/latest/userguide/ListingKeysUsingAPIs.html and had to modify since the classes in the sample are not available in my version of SDK. Following is the code I have to list objects
ListObjectsV2Request req = ListObjectsV2Request.builder()
.bucket(S3_BUCKET_NAME)
.prefix(pathBuilder.toString())
.maxKeys(2)
.build();
ListObjectsV2Response result;
do {
result = s3Client.listObjectsV2(req);
for (S3Object s3Object : result.contents()) {
System.out.printf(" - %s (size: %d)\n", s3Object.key(), s3Object.size());
}
req.toBuilder().continuationToken(result.nextContinuationToken());
} while (result.isTruncated());
This code always prints out the same two objects in each while loop. That is the nextContinuationToken() is never set. I am not able to find any other way to set the continuation token. Help appreciated.
Try with below code, reference link from official aws documentation
ListObjectsV2Request listObjectsReqManual = ListObjectsV2Request.builder()
.bucket(bucketName)
.maxKeys(1)
.build();
boolean done = false;
while (!done) {
ListObjectsV2Response listObjResponse = s3.listObjectsV2(listObjectsReqManual);
for (S3Object content : listObjResponse.contents()) {
System.out.println(content.key());
}
if (listObjResponse.nextContinuationToken() == null) {
done = true;
}
listObjectsReqManual = listObjectsReqManual.toBuilder()
.continuationToken(listObjResponse.nextContinuationToken())
.build();
}
You need to assign the result of .toBuilder().continuationToken(…) method to a variable

Java Jackson DeserializationFeature

I have problem with Jackson and DeserializationFeature. From WebService I get JSON field like:
"location":null,
OR
"location":{
"code":"YYYYYY",
"label":"XXXXXX"
},
When I try get code or label eg.
project.getLocation().getCode();
Java return NullPointerException.
My current code is written like eg. and its work fine.
if (project.getLocation() != null) {
location_code = project.getLocation().getCode();
location_label = project.getLocation().getLabel();
} else {
location_code = null;
location_label = null;
}
Which option of DeserializationFeature is right for this problem?
Not sure about DeserializationFuture option, but simple null check could do the job:
String code = null;
Location location = project.getLocation(); // maybe, some yours location type
if (location != null) {
code = location.getCode();
}

CRM Dynamics Online 2016 Azure SDK for Java receive BrokeredMessages with 500 error code

I have a problem with CRM Dynamics Online 2016 Azure SDK for Java.
I can connect to Azure Service Bus, I can see queues and message count in queues, but cannot receive messages. Message Id is null and message body contain 500 error
500The server was unable to process the
request; please retry the operation. If the problem persists, please
contact your Service Bus administrator and provide the tracking id.
TrackingId:acf8a543-33c9-486d-b13b-443823e6c394_G9,TimeStamp:4/13/2016
7:26:22 AM. If the problem persists, please contact
your Service Bus administrator and provide the tracking id.
TrackingId:acf8a543-33
Is there any working sample on the Internet to solve the problem?
Test code:
#Test
public void readAllExistedMessagesFromAllQueue() {
try {
ServiceBusContract serviceBusContract = ServiceBusConfiguration.configureWithConnectionString(null, Configuration.load(), ASB_CONNECTION_STRING).create(ServiceBusContract.class);
ReceiveMessageOptions opts = ReceiveMessageOptions.DEFAULT;
opts.setReceiveMode(ReceiveMode.PEEK_LOCK);
ListQueuesResult result = serviceBusContract.listQueues();
if (result != null && result.getItems().size() > 0) {
for (QueueInfo queueInfo : result.getItems()) {
logger.debug("queu: " + queueInfo.getPath() + " MessageCount: " + queueInfo.getMessageCount());
for (int i = 0; i < result.getItems().size(); i++) {
BrokeredMessage message = serviceBusContract.receiveQueueMessage(queueInfo.getPath(),
opts).getValue();
if (message == null) {
continue;
}
System.out.print("__________________________________________");
System.out.println("MessageID: " + message.getMessageId());
System.out.print("From queue: ");
byte[] b = new byte[200];
String s = null;
int numRead = message.getBody().read(b);
while (-1 != numRead) {
s = new String(b);
s = s.trim();
System.out.print(s);
numRead = message.getBody().read(b);
}
System.out.println();
}
}
}
} catch (IOException e) {
logger.error(e);
} catch (ServiceException e) {
logger.error(e);
}
}
Per my experience, according to the source code and javadocs of Service Bus, the ServiceBusContract is a Java interface, that you can't directly create an instance of the interface ServiceBusContract.
So please try to use the code below from the section Create a queue of the document "How to use Service Bus queues".
Configuration config =
ServiceBusConfiguration.configureWithSASAuthentication(
"<your-servicebus-namespace>",
"RootManageSharedAccessKey",
"<SAS-key-value>",
".servicebus.windows.net"
);
ServiceBusContract serviceBusContract = ServiceBusService.create(config);
Update
You can find the SharedAccessKeyName & SharedAccessKey in the connection string via click the button below at the bottom of your service bus page.
Then, show the view below and copy the CONNECTION STRING.
The connection string like this below.
Endpoint=sb://<your-servicebus-namespace>.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=<SAS-key-value>
Please copy the correct part of connection string instead of the related part of the code.

How to use custom templates in Swagger

I have this JavaJaxRs dictionary with my templates:
/templates/JavaJaxRs
I edited some of them. And want to use them for my API generation (Code was inspired from this approach from https://github.com/swagger-api/swagger-codegen/blob/master/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java):
System.out.println("Generating API for: " + location);
DefaultGenerator generator = new DefaultGenerator();
Swagger swagger = new SwaggerParser().read(location);
CodegenConfig config = CodegenConfigLoader.forName(this.language);
config.setOutputDir(new File(this.apiGeneratedSrcPath).getPath());
if (null != templateDirectory) {
config.additionalProperties().put(TEMPLATE_DIR_PARAM, templateDirectory);
}
if (null != modelPackage) {
config.additionalProperties().put(MODEL_PACKAGE_PARAM, modelPackage);
}
if (null != apiPackage) {
config.additionalProperties().put(API_PACKAGE_PARAM, apiPackage);
}
if (null != invokerPackage) {
config.additionalProperties().put(INVOKER_PACKAGE_PARAM, invokerPackage);
}
if (configOptions != null) {
for (CliOption langCliOption : config.cliOptions()) {
if (configOptions.containsKey(langCliOption.getOpt())) {
config.additionalProperties().put(langCliOption.getOpt(),
configOptions.get(langCliOption.getOpt()));
}
}
}
if (null != configurationFile) {
Config genConfig = ConfigParser.read(configurationFile);
if (null != genConfig) {
for (CliOption langCliOption : config.cliOptions()) {
if (genConfig.hasOption(langCliOption.getOpt())) {
config.additionalProperties().put(langCliOption.getOpt(), genConfig.getOption(langCliOption.getOpt()));
}
}
} else {
throw new RuntimeException("Unable to read configuration file");
}
}
ClientOptInput input = new ClientOptInput().opts(new ClientOpts()).swagger(swagger);
input.setConfig(config);
generator.opts(input).generate();
Somehow i always get the code generated with the standard template file.
UPDATE:
When i remember correctly i had a conditional bug on:
if(null != templateDirectory)
config.additionalProperties().put(TEMPLATE_DIR_PARAM, templateDirectory);
or somewhere else but with the right condition, code was working as intended.
I let the question stay here, maybe it will help some other users.
You can get the help options for the code generator like such:
java -jar swagger-codegen-cli.jar help generate
Which should tell you that you can override the template location with the -t parameter:
java -java swagger-codegen-cli.jar generate -l {language} -t path/to/templates
Regarding the above ava -java swagger-codegen-cli.jar generate -l {language} -t path/to/templates,
I've managed to make it work with current being-worked-on-release (2.2.0).
With 2.1.6 (current GA) it does not work.
I have posted the following on swagger-codegen at GitHub:
https://github.com/swagger-api/swagger-codegen/issues/3188
Did not get any attention though...

Fastest/shortest way to the root folders?

I'm using Google Drive SDK v2 on Android to get the list of root folders. Currently I see these required steps - which seem to load forever. Is there no faster way?
I tried to use the search with the q= parameter but I don't get it to work (FileList vs. Files.List) - different API levels?
FileList files = drive.files().list().setQ("'root' in parents and mimeType='application/vnd.google-apps.folder' and trashed=false");
This is what I do currently:
About about = drive.about().get().execute();
if (about != null) {
ChildList childList = drive.children().list(about.getRootFolderId()).execute();
if (childList != null) {
List<ChildReference> listChildReference = childList.getItems();
for (ChildReference childReference : listChildReference) {
File file = drive.files().get(childReference.getId()).execute();
if (file != null) {
String fileExtension = file.getFileExtension();
String mimeType = file.getMimeType();
if (mimeType != null
&& mimeType.equals("application/vnd.google-apps.folder")
&& (fileExtension == null || fileExtension.equals(""))) {
Log.d(this.getClass().getName(), file.getTitle());
}
}
}
}
}
What's the fastest for an Android app?
Thanks in advance.
My personal opinion is avoid the Drive SDK and call the REST API directly. It's a fairly simple API, and the way the documentation is structured, you are forced to understand it anyway in order to use the SDK. You have the benefit that if something doesn't work, you can directly compare your app with what's happening on the wire and resolve any problems.
Found it:
#Override
protected ArrayList<File> doInBackground(final Void... voids) {
ArrayList<File> result = new ArrayList<File>();
Files.List request = null;
boolean ok = true;
do {
try {
request = drive
.files()
.list()
.setMaxResults(200)
.setQ("'root' in parents and mimeType='application/vnd.google-apps.folder' and trashed=false");
FileList files = request.execute();
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
} catch (IOException exception) {
ok = false;
}
} while (ok && request.getPageToken() != null && request.getPageToken().length() > 0);
return result;
}

Categories

Resources