I am trying to retrieve Map content via WFS Geoserver connection in Java with Geotools 18.4. But I am getting the following error: Content type is required for org.geotools.data.ows.Response.
The idea is that i want to map features (Position and Heartrate of a running person) of a WFS Layer with the java processing library.
I would be very grateful if someone can help me with this error.
here is the code:
`
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.geotools.data.DataStore;
import org.geotools.data.wfs.WFSDataStoreFactory;
public class Heartrate2 {
public static void main(String[] args) throws IOException {
Heartrate2 me = new Heartrate2();
DataStore ds = me.dataStoreWFS();
for (String n:ds.getTypeNames()) {
System.out.println(n);
}
}
public DataStore dataStoreWFS() {
DataStore dataStore = null;
try {
Map<String, Serializable> connectionParameters = new HashMap<>();
String getCapabilities = "http://webgis.regione.sardegna.it/geoserver/ows?service=WFS&request=GetCapabilities";
String variableCapabilities = "WFSDataStoreFactory:GET_CAPABILITIES_URL";
connectionParameters.put(variableCapabilities, getCapabilities);
dataStore = (new WFSDataStoreFactory()).createDataStore(connectionParameters);
} catch (IOException e) {
e.printStackTrace();
}
return dataStore;
}
}
`
Related
I have mongodb 4.0 install in my Ubuntu 18.04.
I am using java-mongo-driver 3.12.1
I am uploading my code you can see that i have check different type of connections but it's not working.
How to solve this problem?
Give this a try, let me know what you think...
package test;
public class Main {
public static void main(String[] args) {
com.mongodb.client.MongoClient client = connectToStandAlone();
com.mongodb.client.MongoDatabase db = client.getDatabase("javatest");
QueryData(db);
}
private static com.mongodb.client.MongoClient connectToStandAlone() {
// STANDALONE STILL REQUIRES HOSTS LIST WITH ONE ELEMENT...
java.util.ArrayList<com.mongodb.ServerAddress> hosts = new java.util.ArrayList<com.mongodb.ServerAddress>();
hosts.add(new com.mongodb.ServerAddress("127.0.0.1", 27017));
com.mongodb.MongoCredential mongoCredential = com.mongodb.MongoCredential.createScramSha1Credential("testuser", "admin", "mysecret".toCharArray());
com.mongodb.MongoClientSettings mongoClientSettings = com.mongodb.MongoClientSettings.builder()
.applyToClusterSettings(clusterSettingsBuilder -> clusterSettingsBuilder.hosts(hosts))
.credential(mongoCredential)
.writeConcern(com.mongodb.WriteConcern.W1)
.readConcern(com.mongodb.ReadConcern.MAJORITY)
.readPreference(com.mongodb.ReadPreference.nearest())
.retryWrites(true)
.build();
com.mongodb.client.MongoClient client = com.mongodb.client.MongoClients.create(mongoClientSettings);
return client;
}
private static void QueryData(com.mongodb.client.MongoDatabase db) {
// DRIVER DOES NOT HAVE collection.findOne().
com.mongodb.client.MongoCollection<org.bson.Document> collection = db.getCollection("people");
com.mongodb.client.MongoCursor<org.bson.Document> cursor = collection.find(com.mongodb.client.model.Filters.eq("testfield", true))
.sort(new org.bson.Document("review_date", -1))
.skip(5)
.limit(20)
.iterator();
while(cursor.hasNext()) {
org.bson.Document document = cursor.next();
String json = document.toJson();
System.out.println(json);
boolean testfieldValue = document.getBoolean("testfield");
String ssnValue = document.getString("ssn");
}
}
}
I found simple solution.
I have added more jar files,in total we need (bson-3.12.1.jar, mongodb-driver-core-3.12.1.jar, mongodb-driver-sync-3.12.1.jar, mongodb-driver-sync-3.12.1-javadoc.jar). These are available in enter link description here
Now my code is working fine
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Arrays;
public class MongoConnection {
public static void main(String[] args) {
try {
// Create Connection
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
System.out.println("MongoDB connected successfully");
//Accessing the database
MongoDatabase database = mongoClient.getDatabase("java");
System.out.println("MongoDB database connection ");
//Creating a collection
database.createCollection("first");
System.out.println("Collection created successfully");
//Accessing collection
MongoCollection<Document> collection = database.getCollection("first");
Document document = new Document("name", "Café Con Leche")
.append("contact", new Document("phone", "228-555-0149")
.append("email", "cafeconleche#example.com")
.append("location",Arrays.asList(-73.92502, 40.8279556)))
.append("stars", 3)
.append("categories", Arrays.asList("Bakery", "Coffee", "Pastries"));
collection.insertOne(document);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Intellij keeps saying Undefined Step when running my feature file. However, I have copied the steps and put them into another package and added that package name in the "glue" parameter for Edit configurations. Still not working.
I've added the feature file and it doesn't show any missing step references. I am adding a screenshot. I have added all the steps in another package.
Please see below
The code for CountriesSteps is as follows
package Steps;
import Fixtures.Countries;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.junit.Assert;
public class CountriesSteps {
Countries countriesclass = new Countries();
#Given("^I generate a restful request for countries$")
public void iGenerateARestfulRequestForCountries() throws Throwable {
countriesclass.GetCountries();
}
#When("^I receive a successful country response (.*)$")
public void iReceiveASuccessfulCountryResponseResponse(int code) throws Throwable {
Assert.assertEquals(code, countriesclass.getsCode());
}
#When("^I receive a successful country response$")
public void iReceiveASuccessfulCountryResponse() throws Throwable {
Assert.assertEquals(200, countriesclass.getsCode());
}
#Then("^the api country response returns (.*)$")
public void theApiCountryResponseReturnsCountries(int countries) throws Throwable {
Assert.assertEquals(countries, countriesclass.getCount());
}
#Then("^the api country response returns (.*),(.*),(.*),(.*),(.*)$")
public void theApiCountryResponseReturnsCountriesNameCapitalPopulation(int countries, int index, String name, String capital, int population) throws Throwable {
Assert.assertEquals(countries, countriesclass.getCount());
}
#Then("^the api country response for Index (.*) returns (.*),(.*),(.*)$")
public void theApiCountryResponseForIndexIndexReturnsNameCapitalPopulation(int index, String name, String capital, int population) throws Throwable {
//Validate a few values from response
Assert.assertEquals(name, countriesclass.getcList().get(index).name);
Assert.assertEquals(capital, countriesclass.getcList().get(index).capital);
Assert.assertEquals(population, countriesclass.getcList().get(index).population);
}
}
And code for Countries is
package Fixtures;
import Models.CountriesData;
import com.jayway.restassured.response.Response;
import gherkin.deps.com.google.gson.Gson;
import gherkin.deps.com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import static com.jayway.restassured.RestAssured.get;
public class Countries {
private static String url;
private static int count;
private static int sCode;
private static List<CountriesData> cList;
public void GetCountries() throws Exception
{
try {
url = "http://restcountries.eu/rest/v1/all";
// make get request to fetch json response from restcountries
Response resp = get(url);
//Fetching response in JSON as a string then convert to JSON Array
JSONArray jsonResponse = new JSONArray(resp.asString());
count = jsonResponse.length(); // how many items in the array
sCode = resp.statusCode(); // status code of 200
//create new arraylist to match CountriesData
List<CountriesData> cDataList = new ArrayList<CountriesData>();
Gson gson = new Gson();
Type listType = new TypeToken<List<CountriesData>>() {}.getType();
cDataList = gson.fromJson(jsonResponse.toString(), listType);
cList = cDataList;
}
catch (Exception e)
{
System.out.println("There is an error connecting to the API: " + e);
e.getStackTrace();
}
}
//getters to return ('get) the values
public int getsCode() {
return sCode;
}
public int getCount() {
return count;
}
public List<CountriesData> getcList() {
return cList;
}
}
When creating a new step definition file, IntelliJ by default proposes file path of \IdeaProjects\RestAPI\src\main\resources\stepmethods.
Your step definition folder is \IdeaProjects\RestAPI\src\test\java\Steps. Make sure cucumber isn't looking in the wrong place.
As per ChromeDriver site, the user can use the emulators created/present in the chrome for Selenium execution.
Detailed View Here.
I wanted to display all the created/available emulators from Chrome. Chrome could be storing that details in some json file or something.If so how to access it and print it in Java
Did a Notepad++ Find in Files and found it.
The data is stored in JSON format in file
C:\Users\Your UserName\AppData\Local\Google\Chrome\User Data\Default\Preferences
Under Key
devtools>preferences>standardEmulatedDeviceList
I have used Jackson to parse the JSON
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Test {
public static void main(String[] args) {
try {
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readValue(
new File("C:\\Users\\<UserName>\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Preferences"),
Map.class);
Map devTools = (Map) map.get("devtools");
Map preferences = (Map) devTools.get("preferences");
String standardEmulatedDeviceList = (String) preferences.get("standardEmulatedDeviceList");
List emulatorMap = mapper.readValue(standardEmulatedDeviceList, List.class);
System.out.println(emulatorMap.size());
for (Object object : emulatorMap) {
Map device = (Map) object;
System.out.println(device.get("title"));
}
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I am writing a local java application which is to access my google datastore. I followed the tutorial here http://googlecloudplatform.github.io/gcloud-java/0.2.0/index.html
This is my basic code
package myproject;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import com.google.cloud.AuthCredentials;
import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.DatastoreOptions;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.Key;
import com.google.cloud.datastore.KeyFactory;
public class Main {
private String projID = "myID";
public static void main(String[] args) throws IOException {
System.out.println("correct");
Main test = new Main();
Datastore dstore = test.getDatastore();
KeyFactory keyFactory = dstore.newKeyFactory().kind("keyKind");
Key key = keyFactory.newKey("keyName");
Entity entity = Entity.builder(key)
.set("name", "John Doe")
.set("age", 30)
.build();
dstore.put(entity);
}
private Datastore getDatastore() throws IOException {
File file = new File("./resource/mycredential.json");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
System.out.println("Total file size to read (in bytes) : "
+ fis.available());
} catch (IOException e) {
e.printStackTrace();
}
DatastoreOptions options = DatastoreOptions.builder()
.projectId(projID)
.authCredentials(AuthCredentials.createForJson(fis)).build();
Datastore datastore = options.service();
return datastore;
}
}
I created the json credential key from cloud console. After I run the program, it shows com.google.datastore.v1beta3.client.DatastoreFactory makeClient
??: Not using any credentials
I am really trapped here. How to create the right credential and use it correctly?
Thanks in advance.
This is "INFO" message which means nothing. I agree that it's confusing, but this message shows up every time I start my local program, which works fine - connects to the Datastore, retrieves and saves data, etc.
This has been most likely answered earlier, but all my searches did not get me a definite answer. What I've got is a Java application that currently uses ssh keys to run a script on a remote machine and save the results. I'm in the process of changing this to a Kerberos authentication using keytabs. I have the keytab set up and tested it using a perl script. If someone could point me to examples that tell me how to use kerberos keytabs in a Java application, that would be very helpful.
Thanks,
Kiran
Here's a full implementation of using a keytab in Java.
import javax.security.auth.Subject;
import javax.security.auth.kerberos.KerberosPrincipal;
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import java.security.Principal;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class SecurityUtils {
public static class LoginConfig extends Configuration {
private String keyTabLocation;
private String servicePrincipalName;
private boolean debug;
public LoginConfig(String keyTabLocation, String servicePrincipalName, boolean debug) {
this.keyTabLocation = keyTabLocation;
this.servicePrincipalName = servicePrincipalName;
this.debug = debug;
}
#Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
HashMap<String, String> options = new HashMap<String, String>();
options.put("useKeyTab", "true");
options.put("keyTab", this.keyTabLocation);
options.put("principal", this.servicePrincipalName);
options.put("storeKey", "true");
options.put("doNotPrompt", "true");
if (this.debug) {
options.put("debug", "true");
}
options.put("isInitiator", "false");
return new AppConfigurationEntry[]{new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule",
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options),};
}
}
public static Subject loginAs(String keyTabLocation, String servicePrincipal) {
try {
LoginConfig loginConfig = new LoginConfig(keyTabLocation, servicePrincipal, true);
Set<Principal> princ = new HashSet<Principal>(1);
princ.add(new KerberosPrincipal(servicePrincipal));
Subject sub = new Subject(false, princ, new HashSet<Object>(), new HashSet<Object>());
LoginContext lc;
lc = new LoginContext("", sub, null, loginConfig);
lc.login();
return lc.getSubject();
} catch (LoginException e) {
e.printStackTrace();
}
return null;
}
}
The loginAs method will return you a Subject which can be used to execute a privileged action:
result = Subject.doAs(subject,
new PrivilegedExceptionAction<NamingEnumeration<SearchResult>>() {
public NamingEnumeration<SearchResult> run() throws NamingException {
return context.search(directoryBase, filterBuilder.toString(), searchCtls);
}
});