How can I connect to ArcSDE with GeoTools? - geotools

I'm running Oracle ArcSDE 9.2 and using GeoTools 8.5, but doing what they say in the GeoTools docs doesn't seem to work. I have
Map<String, Object> params = new HashMap<String, Object>();
params.put( "dbtype", "arcsde" );
params.put( "server", "164.64.146.42" );
params.put( "port", "5151" );
params.put( "instance", "sde" );
params.put( "user", "sde_admin" );
params.put( "password", "whatever" );
DataStore dataStore;
String typeName;
try
{
dataStore = DataStoreFinder.getDataStore(params);
typeName = dataStore.getTypeNames()[0];
} catch (IOException e)
{
e.printStackTrace();
}
FeatureSource source = dataStore(typeName);
But, after dataStore = dataStoreFinder.getDataStore(params), dataStore is always still null, indicating it didn't connect. I do not get an exception unless I try to use the dataStore object which is null. And I don't expect it to work because it doesn't ask me for a schema. When you connect using GeoServer successfully to the same SDE geodatabase, it insists on a schema parameter, which in my case is "envq.nmenv.state.nm.us." Would I add that onto the server name somewhere? Or what am I missing for this not to connect? I am just trying to connect read-only for now, but eventually I want to put data in using GeoTools.

Using the software uDig, which uses the GeoTools library, has answered my question. When loading from an ArcSDE DataStore via uDig, uDig prompts to know the location of the following jars:
jsde92_sdk.jar
jpe92_sdk.jar
icu4j_3_2.jar
They are not loaded automatically via Maven by adding gt-arcsde to your pom.xml in Eclipse, but are distributed with GeoServer under the ArcSDE Data Store Extension within the filename geoserver-2.2.2-arcsde-plugin.zip
Add their location to your CLASSPATH or in Eclipse go to Project->Properties->Java Build Path and Add External JARs... and choose all three. At that point the above code will work unchanged.

Related

Gooble Cloud KMS: code freezes on calling kms client

I want to encrypt and decrypt son values by using google cloud kms and I am using this code as example https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/kms/src/main/java/com/example/CryptFile.java
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// The resource name of the cryptoKey
String resourceName = CryptoKeyName.format(projectId, locationId, keyRingId, cryptoKeyId);
// Encrypt the plaintext with Cloud KMS.
EncryptResponse response = client.encrypt(resourceName, ByteString.copyFrom(plaintext));
// Extract the ciphertext from the response.
return response.getCiphertext().toByteArray();
}
When the code executes the line client.encrypt(resourceName, ByteString.copyFrom(plaintext)); it freezes and I do not get any response.
If I use gcloud command to encrypt/decrypt it works.
I run my application on App Engine standard (runtime java8) and the dependency I am using is
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-kms</artifactId>
<version>1.29.0</version>
</dependency>
I made some changes in my code to get credentials:
AppIdentityService appIdentityService = AppIdentityServiceFactory.getAppIdentityService();
GoogleCredentials credentials = AppEngineCredentials.newBuilder().setScopes(Arrays.asList("https://www.googleapis.com/auth/cloudkms")).
setAppIdentityService(appIdentityService).build();
FixedCredentialsProvider credentialsProvider = FixedCredentialsProvider.create(credentials);
KeyManagementServiceSettings kmsSettings = KeyManagementServiceSettings.newBuilder().setCredentialsProvider(credentialsProvider).build();
try (KeyManagementServiceClient client = KeyManagementServiceClient.create(kmsSettings)) {
But I always get "UNAUTHENTICATED: Failed computing credential metadata".
Any help?
Please let me know if I'm missing something here.
Regards
Same thing, running the code from example hags on the call to encrypt
Json auth file is set to the environment
export GOOGLE_APPLICATION_CREDENTIALS="../my.json"
User is granted the correct permission as per documentation
Cloud KMS CryptoKey Encrypter/Decrypter
Verified in debugger all 4 parameters are correct:
projectId, locationId, keyRingId, cryptoKeyId
This code hangs
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
final String resourceName = CryptoKeyName.format(projectId, locationId, keyRingId, cryptoKeyId);
// Always Hangs here!!!!
final EncryptResponse response = client.encrypt(resourceName, ByteString.copyFromUtf8(data));
return response.getCiphertext().toString();
}

Read values from local.settings.json in VS 2017 Azure Function development

I am writing an Azure function in VS 2017. I need to set up a few custom configuration parameters. I added them in local.settings.json under Values.
{
"IsEncrypted":false,
"Values" : {
"CustomUrl" : "www.google.com",
"Keys": {
"Value1":"1",
"Value2" :"2"
}
}
}
Now, ConfigurationManager.AppSettings["CustomUrl"] returns null.
I'm using:
.NET Framework 4.7
Microsoft.NET.Sdk.Functions 1.0.5
System.Configuration.ConfigurationManager 4.4.0
Azure.Functions.Cli 1.0.4
Am I missing something?
Environment.GetEnvironmentVariable("key")
I was able to read values from local.settings.json using the above line of code.
Firstly, I create a sample and do a test with your local.settings.json data, as Mikhail and ahmelsayed said, it works fine.
Besides, as far as I know, Values collection is expected to be a Dictionary, if it contains any non-string values, it can cause Azure function can not read values from local.settings.json.
My Test:
ConfigurationManager.AppSettings["CustomUrl"] returns null with the following local.settings.json.
{
"IsEncrypted": false,
"Values": {
"CustomUrl": "www.google.com",
"testkey": {
"name": "kname1",
"value": "kval1"
}
}
}
If you are using TimeTrigger based Azure function than you can access your key (created in local.settings.json) from Azure Function as below.
[FunctionName("BackupTableStorageFunction")]
public static void Run([TimerTrigger("%BackUpTableStorageTriggerTime%")]TimerInfo myTimer, TraceWriter log, CancellationToken cancellationToken)
Using .Net 6 (and probably some earlier versions) it is possible to inject IConfiguration into the constructor of the function.
public Function1(IConfiguration configuration)
{
string setting = _configuration.GetValue<string>("MySetting");
}
MySetting must be in the Values section of local.settings.json:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
"MySetting": "value"
}
}
It works with Application settings in Azure Function App as well.
Azure function copies the binaries to the bin folder and runs using the azure function cli, so it searches for the local.settings.json, so make sure you have set the "Copy to Output Directory" to "Copy Always"
Hey you mmight be able to read the properties while debugging, but once you go and try to deploy that in azure, those properties are not going to work anymore. Azure functions does not allow nested properties, you must use all of them inline in the "Values" option or in "ConnectionStrings".
Look at this documentation as reference:
https://learn.microsoft.com/en-us/azure/azure-functions/functions-how-to-use-azure-function-app-settings
var value = Environment.GetEnvironmentVariable("key", EnvironmentVariableTarget.Process); should be the more appropriate answer, though EnvironmentVariableTarget.Process is the default value but it's more meaningful here.
Look at its EnvironmentVariableTarget declaration.
//
// Summary:
// Specifies the location where an environment variable is stored or retrieved in
// a set or get operation.
public enum EnvironmentVariableTarget
{
//
// Summary:
// The environment variable is stored or retrieved from the environment block associated
// with the current process.
Process = 0,
//
// Summary:
// The environment variable is stored or retrieved from the HKEY_CURRENT_USER\Environment
// key in the Windows operating system registry. This value should be used on .NET
// implementations running on Windows systems only.
User = 1,
//
// Summary:
// The environment variable is stored or retrieved from the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session
// Manager\Environment key in the Windows operating system registry. This value
// should be used on .NET implementations running on Windows systems only.
Machine = 2
}

Best way to get users folder using as-user in new Box Java SDK

Per Box example easy way to get user's root folder using below code
http://opensource.box.com/box-java-sdk/
BoxAPIConnection api = new BoxAPIConnection("your-developer-token");
BoxFolder rootFolder = BoxFolder.getRootFolder(api);
for (BoxItem.Info itemInfo : rootFolder) {
System.out.format("[%d] %s\n", itemInfo.getID(), itemInfo.getName());
}
But if i need to access someone else info using As-user, I'm unable to use BOX SDK classes (BoxFolder, BoxFile, BoxUser...) and need to get the data only from JSON directly like below.
If i do so, i'm loosing the latest features added in the new SDK. Is it the best way? How about the performance? Is there any alternative way available?
url= new URL("https://api.box.com/2.0/folders/0");
BoxAPIRequest request = new BoxAPIRequest(api,url,"GET");
request.addHeader("As-User", "12345678");
BoxJSONResponse response = (BoxJSONResponse) request.send();
JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
Later get the folder properties using JsonObject / JsonArray. If i need the folder items, i need to loop the JsonArray like below
JsonArray entries = responseJSON.get("entries").asArray();
for (JsonValue entry : entries)
{ ....}
Unfortunately, the new Java SDK beta doesn't have built-in support for "As-User" functionality yet, which makes this kind of tricky. One workaround is to use a RequestInterceptor with your BoxAPIConnection to manually add the "As-User" header to every request.
api.setRequestInterceptor(new RequestInterceptor() {
#Override
public BoxAPIResponse onRequest(BoxAPIRequest request) {
request.addHeader("As-User", "user-id");
// Returning null means the request will be sent along with our new header.
return null;
}
}
This should let you use the rest of the SDK normally and not have to worry about doing the API requests manually. I also created an issue for adding "As-User" support.

DART lang reading JSON file saved in the client, i.e. without using a server

I'm trying to read data from JSON file, using the blow code:
void makeRequest(Event e){
var path='json/config.json';
var httpRequest= new HttpRequest();
httpRequest
..open('GET', path)
..onLoadEnd.listen((e)=>requestComplete(httpRequest))
..send('');
}
this worked very well when the app run as http:// .../ index.html, but gave the below error when trying to open it as file:///.../index.html
Exception: NetworkError: Failed to load 'file:///D:/DartApp/web/json/config.json'. main.dart:53makeRequest main.dart:53<anonymous closure>
Is there another way, other than httpRequest that can read JSON file from client side!
I understand I've 3 options, 2 of them only can use HttPRequest, which are:
saving the file of the server, and reading it from the server => can use HttpRequesit
saving the file on the server, and reading it from the client => can use HttpRequesit
saving the file on the client, and reading it from the client itself => CAN NOT use HTTPRequest
I'm searching for the way to do the 3rd option, which is like making off-line Android App using webview, or making off-line Chrome packaged app, i.e I do not want to use a server at all. thanks
thanks
If all you need is the data in the json file, you can just include that data in your .dart files (as a Map variable/constant, for example).
Map config = {
"displayName": "My Display Name",
"anotherProperty": 42,
"complexProperty": {
"value_1": "actual value",
"value_2": "another value"
}
};
If you need the actual json, you can put in a String. Something like:
const configJson = '''
{ "displayName": "My Display Name",
"anotherProperty": 42,
"complexProperty": {
"value_1": "actual value",
"value_2": "another value"
}
}
''';
The json data can be in a separate .dart file, which can be included as part of the same library (through part of ...), or imported (import 'package:mypackage/json.dart';).
If you're looking for something that you can change and the changes are persisted, you're going to need to use some sort of offline storage, which can be web storage if you're running in a browser. You can use the approach above to define inital config data, store it in web storage, and from then on read and edit it from there.
[Previous answer below, before original question was edited.]
Sorry, read "client side", thought "server side". My mistake.
If by "client side" you mean "running in a browser", and you're trying to access a json file which is on the server, then no, there isn't any other way, other than an http request. In fact, that's the only way to read any file on the server, not just json ones. (Well, I guess you could open a WebSocket and stream the content, but that doesn't seem to be a solution you're looking for.)
[Old solution below, before my mistake (server vs client) was pointed out.]
Try:
// THIS DOESN'T WORK IN A BROWSER ENVIRONMENT (aka client side)
import 'dart:io';
import 'dart:convert';
// ...
new File('json/config.json')
.readAsString()
.then((fileContents) => json.decode(fileContents))
.then((jsonData) {
// do whatever you want with the data
});
This poor example works fine in the chrome dev editor dart web app example.
Using HttpRequest.getString works fine with filename and path.
Chris has a good write for json web service stuff at
https://www.dartlang.org/articles/json-web-service/
import 'dart:html';
import 'dart:convert';
void main() {
HttpRequest.getString('json/config.json').then((myjson) {
Map data = JSON.decode(myjson);
var version = data["version"];
var element = new DivElement();
element.text = "version = $version";
document.body.children.add(element);
});
}

Gson Syntax Exception causing Retrofit Error

I am in the process of connecting to a custom RESTful API using Retrofit. I have testing communicating with the device/API via Curl and with some test Java code running on a non-Android system (mac os x). The curl and java commands return the expected response.
However, using retrofit, I am unsure if I am using an inadequate configuration in my RestAdapter (i.e. RestAdapter.Builder()) to talk to this device.
The error I am getting appears to be that the entire json contents is not returned and only the first 47 bytes or so. I expect this is a behavior of the device I'm talking to, and am curious if this means I need to implement an Asynchronous callback as described in the Retrofit API docs. Before I do this I wanted to get feedback from some who have more experience with Retrofit.
The error is as follows (sanitized for public consumption):
12-06 08:50:52.962 28267-1735/com.mycompany.project D/Retrofit? [ 12-06 08:50:52.972 28267: 1735 D/Retrofit ]
{"OBJECT1":{"#Version":1,"OBJECTARRAY1":[
12-06 08:50:52.972 28267-1735/com.mycompany.project D/Retrofit? <--- END HTTP (46-byte body)
12-06 08:50:52.982 28267-1735/com.mycompany.project W/System.err retrofit.RetrofitError: retrofit.converter.ConversionException: com.google.gson.JsonSyntaxException: java.io.EOFException: End of input at line 1 column 47
I am setting up the RestAdapter as such:
RestAdapter restAdapter = new RestAdapter.Builder()
.setServer(serverUrl)
.setClient(new OkClient(RestUtils.getHttpClient(3000, 3000, username, password)))
.setRequestInterceptor(new RequestInterceptor() {
#Override
public void intercept(RequestFacade requestFacade) {
requestFacade.addHeader("Accept", "application/json");
requestFacade.addHeader("Client-Id", "12345");
}
})
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
service = restAdapter.create(OBJECT1.class);
Any insight into this problem would be greatly appreciated. I understand this error is related to the java.io.EOFException, but have been unable to verify the contents I am getting returned from the device, except for the output shown above in the error. I am heavily leaning towards the async vs. sync being the issue, but am open to any recommendations.
Cheers!