Java Jackson DeserializationFeature - java

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();
}

Related

how to fix file .json not found when it is there

I am trying here to consume the data from a json file:
DATA.json
[
{"Label"
:"USA",
"Adress":"This is the us",
"Lat":"36.9628066",
"Lng":"-122.0194722"
},
{ "Label" :"USA",
"Address":"2020",
"Lat":"36.9628066",
"Lng":"-122.0194722" }
]
Then applying it in my Mainclass:
using System.Collections.Generic;
using Xamarin.Forms.Maps;
using Xamarin.Forms;
using System.IO;
using Newtonsoft.Json;
using System;
namespace Orbage
{
class MapPage : ContentPage
{
public MapPage()
{
CustomMap customMap = new CustomMap
{
MapType = MapType.Street
};
// ...
Content = customMap;
var json = File.ReadAllText("File.json");
var places = JsonConvert.DeserializeObject<List<File>>(json);
foreach (var place in places)
{
CustomPin pin = new CustomPin
{
Type = PinType.Place,
Position = new Position(Double.Parse(place.Lat), Double.Parse(place.Lng)),
Label = place.Label,
Address = place.Address,
Name = "Xamarin",
Url = "http://xamarin.com/about/"
};
customMap.CustomPins = new List<CustomPin> { pin };
customMap.Pins.Add(pin);
customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(37.79752, -122.40183), Distance.FromMiles(1.0)));
}
}
}
}
But when I put the file in there it says that it doesn't exist.
Error:
FilenotfoundException
Whats the fix for this.
I tried:
Changing the location of the file.
Its name
Instead of E:/-/- i even wrote file.json but I still get the same error.
Thanks alot!
Try to use the method below:
Put your File.json to your PCL project,and set its Build Action to EmbeddedResource.
var assembly = IntrospectionExtensions.GetTypeInfo(typeof(MapPage)).Assembly;
Stream stream = assembly.GetManifestResourceStream("Orbage.File.json");
string text = "";
using (var reader = new System.IO.StreamReader(stream))
{
text = reader.ReadToEnd();
}
Its better before reading the file, put check whether file exists in the location or not.
if (File.Exists("File.Json"))
With this you would become to know that your given path is correct or not.

Fetching data from zookeeper znode

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());
}

Android Rename File using Google Drive REST API v3?

How do I rename a file using the Google Drive REST API on Android? I have searched the internet however I could, but I can't find how to do this.
I am trying to write a sync method that moves and renames the cloud files if it detects that the local copy has been moved or renamed:
void syncMetadataOnly (com.google.api.services.drive.model.File cloud,
java.io.File local) throws IOException {
Workspace.FINF fileInfo = Workspace.getFileInfo (this, local); // Just my metadata object.
Map<String, String> appProperties = cloud.getAppProperties ();
// We keep track of the last rename and move in our private app properties:
long cloudLastRename = appProperties.containsKey ("last-rename") ?
Long.valueOf (appProperties.get ("last-rename")) : 0;
long cloudLastMove = appProperties.containsKey ("last-move") ?
Long.valueOf (appProperties.get ("last-move")) : 0;
boolean needUpdate = false;
boolean needName = false;
boolean needMove = false;
if (fileInfo.lastRename > cloudLastRename) {
// The file was renamed locally since the last sync.
needName = true;
needUpdate = true;
} else fileInfo.title = cloud.getName ();
String oldRecognizedParent = null;
if (fileInfo.lastMove > cloudLastMove) {
// The file was moved to a different folder locally since the last sync.
oldRecognizedParent = getFirstKnownParentId (cloud); // May be null, if not found.
needMove = true;
needUpdate = true;
}
if (needUpdate) {
cloud.setAppProperties (appProperties);
Drive.Files.Update update = mDriveService.files ().update (fileInfo.driveResourceId, null);
if (needName) update.set /// How do I rename the file?
if (needMove) {
if (oldRecognizedParent != null)
update.setRemoveParents (oldRecognizedParent);
update.setAddParents (fileInfo.driveParentId); // Set to the NEW parent's ID.
}
com.google.api.services.drive.model.File result = update.execute ();
}
}
The closest answer I have found is this, but do I really have to use raw HTTP for this?

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