I am new to java HttpClient and am currently trying to create a RestServiceApplication, but i am unable to convert a HttpResponse to a String array in order to access the elements of the array.
package com.example.restservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class RestServiceApplication {
public static void main(String[] args) {
SpringApplication.run(RestServiceApplication.class, args);
}
}
I have implemented the following controller for the application which has different methods that each return an array of String.
package com.example.restservice;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class ConfigurationController {
#GetMapping("/getlenkertypen")
public String[] getLenkertypen() {
String[] lenker = new String[3];
lenker[0] = "Flatbarlenker";
lenker[1] = "Rennradlenker";
lenker[2] = "Bullhornlenker";
return lenker;
}
#GetMapping("/getmaterial")
public String[] getMaterial() {
String[] material = new String[3];
material[0] = "Aluminium";
material[1] = "Stahl";
material[2] = "Kunststoff";
return material;
}
#GetMapping("/getschaltung")
public String[] getSchaltung() {
String[] schaltung = new String[3];
schaltung[0] = "Kettenschaltung";
schaltung[1] = "Nabenschaltung";
schaltung[2] = "Tretlagerschaltung";
return schaltung;
}
#GetMapping("/getgriff")
public String[] getGriff() {
String[] griff = new String[3];
griff[0] = "Ledergriff";
griff[1] = "Schaumstoffgriff";
griff[2] = "Kunststoffgriff";
return griff;
}
#GetMapping("/test")
public String test() {
String[] griff = new String[3];
griff[0] = "Ledergriff";
griff[1] = "Schaumstoffgriff";
griff[2] = "Kunststoffgriff";
return "test";
}
}
Now i want the HttpClient to request those methods and access the Strings of the array.
My problem is that the returned String[] arrays are not arrays but a single String (BodyHandler.ofString()), so i cannot access the elements anymore. I hoped to solve this with the BodyHander.ofLine()-method, converting the response to a Stream and then call the toArray() function on the stream. But it is still creating an array that has only one element, containing the same String i get from the ofString()-method.
Here is my client:
package com.example.restservice;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Scanner;
import java.util.stream.Stream;
public class GetRequest {
public static void main(String[] args) throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
/*
* Abfrage Lenkertypen
*/
HttpRequest requestLenkertypen = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:8081/getlenkertypen"))
.build();
HttpResponse<Stream<String>> lenkerResponse = client.send(requestLenkertypen,
HttpResponse.BodyHandlers.ofLines());
String[] lenkerArray = lenkerResponse.body().toArray(String[]::new);
System.out.println("Bitte wählen Sie als erstes den Lenker aus: ");
for (int i = 0; i < lenkerArray.length; i++) {
System.out.println(lenkerArray[i] + " " + i);
}
System.out.println(lenkerArray[0]);
Scanner scanner = new Scanner(System.in);
int answer = scanner.nextInt();
System.out.println(answer);
HttpRequest requestSchaltung = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:8081/getschaltung"))
.build();
HttpResponse<String> response = client.send(requestSchaltung,
HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}
By googling i found out that i somehow need to parse the response JSON, but i do not know how. I downloaded the project structure from spring.io so i think the response returns as JSON, but i am new to this and any help would be appreaciated.
Thanks!
If you want to get the lines of the response one at a time use a BufferedReader and the lines() method.
However, it seems what you really want is to parse the JSON data that is returned. For that there are many possibilities. Consider using Jackson: https://www.baeldung.com/jackson
Related
I'm pretty new to Springboot and Java in general and because we got this in school I'm fiddeling arround.
I'm now trying to save an entity outside of the Springboot Entities, Repositories or RestController with the following code:
InfMApplication.java:
package com.domain.springboot;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.domain.springboot.repositories.MovieRepository;
import com.domain.springboot.services.MovieImport;
#SpringBootApplication
public class InfMApplication {
public static void main(String[] args) {
SpringApplication.run(InfMApplication.class, args);
MovieImport movieImport = new MovieImport();
movieImport.saveToDb();
}
}
MovieImport.java:
package com.domain.springboot.services;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.CrossOrigin;
import java.io.*;
import java.net.URL;
import com.google.gson.Gson;
import com.domain.omdbapi.entities.Movie;
import com.domain.omdbapi.entities.SearchResponse;
import com.domain.omdbapi.entities.SearchResult;
import com.domain.springboot.repositories.ComplexRepository;
import com.domain.springboot.repositories.DocumentRepository;
import com.domain.springboot.repositories.MovieRepository;
import com.domain.springboot.repositories.SimpleRepository;
#Service
public class MovieImport {
private final MovieRepository movieRepository;
public MovieImport(MovieRepository movieRepository){
this.movieRepository = movieRepository;
}
public void main() {
String randomImdbId = fetchRandomMovie();
Movie movie = fetchMovieDetails(randomImdbId);
saveToDb(movie);
}
public void saveToDb(Movie movie) {
com.domain.springboot.entities.Movie springbootMovie = new com.domain.springboot.entities.Movie(movie.Title, movie.imdbID);
this.movieRepository.save(springbootMovie);
}
public String fetchRandomMovie() {
String randomWord = getRandomWord();
String url = "https://www.omdbapi.com/?apikey=<API_KEY>&type=movie&s=" + randomWord;
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(
URI.create(url))
.header("accept", "application/json")
.build();
HttpResponse<String> response = null;
try {
response = client.send(request, BodyHandlers.ofString());
} catch (Exception e) {
System.out.println(e);
}
Gson gson = new Gson();
SearchResponse searchResponse = gson.fromJson(response.body(), SearchResponse.class);
int randomIndex = new Random().nextInt(0, searchResponse.getSearch().length);
SearchResult randomResult = searchResponse.getSearch()[randomIndex];
return randomResult.getImdbID();
}
public Movie fetchMovieDetails(String imdbId) {
String url = "https://www.omdbapi.com/?apikey=<API_KEY>&type=movie&plot=full&i=" + imdbId;
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(
URI.create(url))
.header("accept", "application/json")
.build();
HttpResponse<String> response = null;
try {
response = client.send(request, BodyHandlers.ofString());
} catch (Exception e) {
System.out.println(e);
}
Gson gson = new Gson();
Movie movie = gson.fromJson(response.body(), Movie.class);
return movie;
}
public String getRandomWord() {
URL resource = getClass().getClassLoader().getResource("Wordlist.txt");
List<String> words = new ArrayList<>();
try {
File file = new File(resource.toURI());
words = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
}
int randomIndex = new Random().nextInt(0, words.size());
return words.get(randomIndex);
}
}
If I use "this.movieRepository.save(movieObject);" to save a movie in the MovieRestController the same way, it works. I also tried adding the "#Autowire" annotation, but this didn't work.
I always get the error
java.lang.NullPointerException: Cannot invoke "com.domain.springboot.repositories.MovieRepository.save(Object)" because "this.movieRepository" is null
How can I get to use the movieRepository in other Java classes like in the RestControllers?
java.lang.NullPointerException: Cannot invoke
"com.domain.springboot.repositories.MovieRepository.save(Object)"
because "this.movieRepository" is null
Above is perfectly valid if we look at your following shared code.
public class MovieImport {
private MovieRepository movieRepository;
public void saveToDb() {
// Create movie
com.domain.springboot.entities.Movie springbootMovie = new com.domain.springboot.entities.Movie("Iron Man", "284cb8fgf");
this.movieRepository.save(springbootMovie);
}
}
You've to correct certain things in your code base.
First you're not initializing the movieRepository and therefore, you're getting the null pointer exception. As you've been using the springboot you can use construction injection to initialized the field by spring container. Also. this class should be scanned by spring and you should also put some annotation such as Component or Service on top of it.
Following will work if your MovieImport and MovieRepository classess will scan by springboot.
package com.domain;
import com.domain.omdbapi.entities.Movie;
import com.domain.springboot.repositories.MovieRepository;
#Service
public class MovieImport {
private final MovieRepository movieRepository;
public MovieImport(MovieRepository movieRepository){
this.movieRepository = movieRepository;
}
public void saveToDb() {
// Create movie
com.domain.springboot.entities.Movie springbootMovie = new com.domain.springboot.entities.Movie("Iron Man", "284cb8fgf");
this.movieRepository.save(springbootMovie);
}
}
Updated
#SpringBootApplication
public class InfMApplication implements CommandLineRunner {
#Autowired
private MovieImport movieImport;
public static void main(String[] args) {
SpringApplication.run(InfMApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
movieImport.saveToDb();
}
}
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.
I'm having this error :
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
ContentModel cannot be resolved to a variable
at test2CMIS.Test.main(Test.java:39)"
And I dont understand from where it comes, here is my code :
public class Test {
public static void main(String[] args){
Test atest = new Test();
Session session = atest.iniSession();
AuthenticationService authenticationService=null;
PersonService personService = null;
if (authenticationService.authenticationExists("test") == false)
{
authenticationService.createAuthentication("test", "changeMe".toCharArray());
PropertyMap ppOne = new PropertyMap(4);
ppOne.put(ContentModel.PROP_USERNAME, "test");
ppOne.put(ContentModel.PROP_FIRSTNAME, "firstName");
ppOne.put(ContentModel.PROP_LASTNAME, "lastName");
ppOne.put(ContentModel.PROP_EMAIL, "test"+"#example.com");
personService.createPerson(ppOne);
}
}
I did import the : import org.alfresco.model.ContentModel; and a lot of others librarys for my code.
Thx for help.
The code I'm using and I left some things that I tried too in comments so you can see what things I have done:
import java.io.File;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import org.alfresco.service.cmr.security.*;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import java.util.Iterator;
import org.alfresco.repo.jscript.People;
import org.alfresco.repo.security.authentication.AuthenticationException;
import org.alfresco.service.cmr.security.AuthenticationService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.PropertyMap;
import org.apache.chemistry.opencmis.client.api.CmisObject;
import org.apache.chemistry.opencmis.client.api.Document;
import org.apache.chemistry.opencmis.client.api.Folder;
import org.apache.chemistry.opencmis.client.api.Session;
import org.apache.chemistry.opencmis.commons.PropertyIds;
import org.apache.chemistry.opencmis.commons.SessionParameter;
import org.apache.chemistry.opencmis.commons.enums.BindingType;
import org.apache.chemistry.opencmis.commons.enums.VersioningState;
import org.apache.chemistry.opencmis.commons.exceptions.CmisContentAlreadyExistsException;
import org.apache.chemistry.opencmis.commons.exceptions.CmisUnauthorizedException;
import org.apache.chemistry.opencmis.client.util.FileUtils;
import org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl;
public class Test {
public static void main(String[] args){
Test atest = new Test();
Session session = atest.iniSession();
AuthenticationService authenticationService=new AuthenticationServiceImpl();
PersonService personService = new PersonServiceImpl();
HashMap<QName, Serializable> properties = new HashMap<QName, Serializable>();
properties.put(ContentModel.PROP_USERNAME, "test");
properties.put(ContentModel.PROP_FIRSTNAME, "test");
properties.put(ContentModel.PROP_LASTNAME, "qsdqsd");
properties.put(ContentModel.PROP_EMAIL, "wshAlors#gmail.com");
properties.put(ContentModel.PROP_ENABLED, Boolean.valueOf(true));
properties.put(ContentModel.PROP_ACCOUNT_LOCKED, Boolean.valueOf(false));
personService.createPerson(properties);
authenticationService.createAuthentication("test", "changeme".toCharArray());
authenticationService.setAuthenticationEnabled("test", true);
authenticationService.getAuthenticationEnabled("Admin");
//String testAuthen = authenticationService.getCurrentTicket();
//System.out.println(testAuthen);
//QName username = QName.createQName("test");
//Map<QName,Serializable> propertiesUser = new HashMap<QName,Serializable>();
//propertiesUser.put(ContentModel.PROP_USERNAME,username);
//propertiesUser.put(ContentModel.PROP_FIRSTNAME,"test");
//propertiesUser.put(ContentModel.PROP_LASTNAME,"test");
//propertiesUser.put(ContentModel.PROP_EMAIL, "test#example.com");
//propertiesUser.put(ContentModel.PROP_PASSWORD,"0000");
//personService.createPerson(propertiesUser);
//if (authenticationService.authenticationExists("test") == false)
//{
// authenticationService.createAuthentication("test", "changeMe".toCharArray());
// PropertyMap ppOne = new PropertyMap(4);
// ppOne.put(ContentModel.PROP_USERNAME, "test");
// ppOne.put(ContentModel.PROP_FIRSTNAME, "test");
// ppOne.put(ContentModel.PROP_LASTNAME, "test");
// ppOne.put(ContentModel.PROP_EMAIL, "test#example.com");
//ppOne.put(ContentModel.PROP_JOBTITLE, "jobTitle");
// personService.createPerson(ppOne);
//}
}
public Session iniSession() {
Session session;
SessionFactoryImpl sf = SessionFactoryImpl.newInstance();
Map<String, String> parameters = new HashMap<String, String>();
Scanner reader = new Scanner(System.in);
System.out.println("Enter your logging : ");
String log = reader.nextLine();
System.out.println("Enter your password : ");
String pass = reader.nextLine();
parameters.put(SessionParameter.USER, log);
parameters.put(SessionParameter.PASSWORD, pass);
parameters.put(SessionParameter.BROWSER_URL, "http://127.0.0.1:8080/alfresco/api/-default-/public/cmis/versions/1.1/browser");
parameters.put(SessionParameter.BINDING_TYPE, BindingType.BROWSER.value());
parameters.put(SessionParameter.REPOSITORY_ID, "-default-");
try{
session = sf.createSession(parameters);
}catch(CmisUnauthorizedException cue){
session = null;
System.out.println("Wrong logging OR password !");
}
return session;
}
You are writing a runnable class which is not running the same process as Alfresco. In that sense, your class is running "remotely".
Because your class is running remotely to Alfresco, you are correct in using CMIS. But CMIS will only allow you to perform Create, Read, Update, and Delete (CRUD) functions against documents and folders in Alfresco. CMIS does not know how to create users or groups.
Your class will not be able to instantiate the AuthenticationService or PersonService. Those are part of the Alfresco Foundation API which only works when you are running in the same process as Alfresco, such as in an Action, a Behavior, or a Java-backed web script. In those cases, you will use Spring Dependency Injection to inject those services into your Java class. You would then put your class in a JAR that gets deployed into the Alfresco web application and loaded by the same classloader as Alfresco's.
If you want to create users remotely you should consider using the Alfresco REST API. Your runnable class can then use an HTTP client to invoke REST calls to create people and groups.
Thanks you for everything ! Thanks to you and researches I found out how to do it ! For the others who wonder how to do I'll post how I did and what site I used to understand it !
So you just need to manipulate JSON with Java because your alfresco people page (127.0.0.1:8080/alfresco/service/api/people) returns a JSON object, and you'll be able to create, delete, search... users! Thx again !
Sites :
https://api-explorer.alfresco.com/api-explorer/#/people
http://crunchify.com/json-manipulation-in-java-examples/
The code :
This is for creating an user :
public User createUser(String firstN, String lastN, String email, String pass, String authTicket) throws Exception{
try{
String url = "http://127.0.0.1:8080/alfresco/service/api/people?alf_ticket="+authTicket;
HttpClient httpclient = new HttpClient();
PostMethod mPost = new PostMethod(url);
//JSONObject obj = new JSONObject();
//JSONArray people = obj.getJSONArray("people");
JSONObject newUser = new JSONObject();
newUser.put("userName", firstN.toLowerCase().charAt(0)+lastN.toLowerCase());
newUser.put("enabled",true);
newUser.put("firstName",firstN);
newUser.put("lastName", lastN);
newUser.put("email", email);
newUser.put("quota",-1);
newUser.put("emailFreedDisable",false);
newUser.put("isDeleted",false);
newUser.put("isAdminAuthority",false);
newUser.put("password", pass);
//people.put(newUser);
//Response response = PostRequest(newUser.toString()));
StringRequestEntity requestEntity = new StringRequestEntity(
newUser.toString(),
"application/json",
"UTF-8");
mPost.setRequestEntity(requestEntity);
int statusCode2 = httpclient.executeMethod(mPost);
mPost.releaseConnection();
}catch(Exception e){
System.err.println("[ERROR] "+e);
}
return new User(firstN, lastN);
}
And if you want to get all the users you have on alfresco :
public ArrayList<User> getAllUsers(String authTicket)
{
ArrayList<User> allUsers = new ArrayList<>();
String lastName, firstName;
try{
String url = "http://127.0.0.1:8080/alfresco/service/api/people?alf_ticket="+authTicket;
HttpClient httpclient = new HttpClient();
GetMethod mPost = new GetMethod(url);
int statusCode1 = httpclient.executeMethod(mPost);
System.out.println("statusLine >>> "+statusCode1+"....."
+"\n status line \n"
+mPost.getStatusLine()+"\nbody \n"+mPost.getResponseBodyAsString());
JSONObject obj = new JSONObject(mPost.getResponseBodyAsString());
JSONArray people = obj.getJSONArray("people");
int n = people.length();
for(int i =0 ; i < n ; i++)
{
JSONObject peoples = people.getJSONObject(i);
User u = new User(peoples.getString("firstName"), peoples.getString("lastName"));
if (!allUsers.contains(u)){
allUsers.add(u);
}
}
}catch(Exception e){
System.err.println("[ERROR] "+e);
}
return(allUsers);
}
I am creating a sample program using protocol buffer and protobuf-java-format.My proto file is
package com.sample;
option java_package = "com.sample";
option java_outer_classname = "PersonProtos";
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
}
My Sample program is
package com.sample;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import com.google.protobuf.Message;
import com.googlecode.protobuf.format.XmlFormat;
import com.sample.PersonProtos.Person;
/**
* This class generate XML out put from Object and vice-versa
*
* #author mcapatna
*
*/
public class Demo
{
public static void main(String[] args) throws IOException
{
// get the message type from protocol buffer generated class.set the
// required property
Message personProto = Person.newBuilder().setEmail("a").setId(1).setName("as").build();
// use protobuf-java-format to generate XMl from Object.
String toXml = XmlFormat.printToString(personProto);
System.out.println(toXml);
// Create the Object from XML
Message.Builder builder = Person.newBuilder();
String fileContent = "";
Person person = Person.parseFrom(new FileInputStream("C:\\file3.xml"));
System.out.println(XmlFormat.printToString(person));
System.out.println("-Done-");
}
}
XmlFormat.printToString() is working fine.but creating object from XML not working
I also tried XmlFormat.merge(toXml, builder); .but since merge() return void.so how can we get the object of Person class.
Both the above method merge() and parseFrom() giving the same exception
com.google.protobuf.InvalidProtocolBufferException: Protocol message end-group tag did not match expected tag.
NOTE: "C:\\file3.xml" have the same content as toXml.
After a lots of effort,I found the solution...Here is the answer
package com.sample;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.protobuf.Message;
import com.googlecode.protobuf.format.XmlFormat;
import com.sample.PersonProtos.Person;
/**
* This class generate XML output from Object and vice-versa
*
* #author mcapatna
*
*/
public class Demo
{
public static void main(String[] args) throws IOException
{
long startDate=System.currentTimeMillis();
// get the message type from protocol buffer generated class.set the
// required property
Message personProto = Person.newBuilder().setEmail("a").setId(1).setName("as").build();
// use protobuf-java-format to generate XMl from Object.
String toXml = XmlFormat.printToString(personProto);
System.out.println("toXMl "+toXml);
// Create the Object from XML
Message.Builder builder = Person.newBuilder();
String fileContent = "";
// file3 contents same XML String as toXml
fileContent = readFileAsString("C:\\file3.xml");
// call protobuf-java-format method to generate Object
XmlFormat.merge(fileContent, builder);
Message msg= builder.build();
System.out.println("From XML"+XmlFormat.printToString(msg));
long endDate=System.currentTimeMillis();
System.out.println("Time Taken: "+(endDate-startDate));
System.out.println("-Done-");
}
private static String readFileAsString(String filePath) throws IOException
{
StringBuffer fileData = new StringBuffer();
BufferedReader reader = new BufferedReader(new FileReader(filePath));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1)
{
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
return fileData.toString();
}
}
Here is the Output of program:
toXMl <Person><name>as</name><id>1</id><email>a</email></Person>
From XML<Person><name>Deepak</name><id>1</id><email>a</email></Person>
Time Taken: 745
-Done-
Hope it will be useful for other members.
I am currently trying to read a certain cookie from my Java desktop application. I have used a chrome extension to create the cookie and using the chrome console I can view that it has been created and has the correct value.
The problem arises when I try to read it from my Java application, my current code gets 3 seemingly random cookies, which wouldn't be a problem if it included mine. I have ensured my cookie is not host only and it is not secure, it actually has the same properties as the other 3 but it just is not being returned.
Here's my current code:
Java Application Code:
import java.io.IOException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Spud
*/
public class Reading_My_Created_Cookie
{
/**
* #param args the command line arguments
*/
private static final String SEARCH_TERM = "Tab";
private static final String ADDRESS = "http://www.youtube.com/";
private static final CookieManager COOKIEMANAGER = new CookieManager();
private static Object myCookie;
public static void main(String[] args)
{
try
{
COOKIEMANAGER.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(COOKIEMANAGER);
URL url = new URL(ADDRESS);
URLConnection connection = url.openConnection();
connection.getContent();
CookieStore cookieStore = COOKIEMANAGER.getCookieStore();
Object[] cookieJar = cookieStore.getCookies().toArray();
for (int i = 0; i < cookieJar.length; ++i)
{
System.out.println(cookieJar[i]);
}
//myCookie = checkForCookie(cookieJar);
//System.out.println(myCookie);
}
catch (IOException ex)
{
Logger.getLogger(Reading_My_Created_Cookie.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static Object checkForCookie(Object[] cookieJar)
{
for (int i = 0; i < cookieJar.length; ++i)
{
if (cookieJar[i].equals(SEARCH_TERM))
{
return cookieJar[i];
}
}
return "Cookie not found";
}
}
This currently outputs the following:
run:
YSC=6EIDrzvf02s
PREF=f1=50000000
VISITOR_INFO1_LIVE=qKCoNVZQMi8
BUILD SUCCESSFUL (total time: 4 seconds)
For anyone who wants it, this is my current extension JavaScript code:
chrome.browserAction.onClicked.addListener(run);
function run()
{
var cookieName, cookieValue, cookieURL;
cookieName = "Tab";
chrome.tabs.getSelected(null, function(tab)
{
cookieValue = tab.title;
cookieURL = tab.url;
createCookie(cookieName, cookieValue, cookieURL);
});
}
function createCookie(cookieName, cookieValue, cookieURL)
{
chrome.cookies.set({name: cookieName, value: cookieValue, domain: ".youtube.com", url: cookieURL});
alert("cookieName = " + cookieName + " cookieValue/tabTitle = " + cookieValue + " tabURL = " + cookieURL);
}
Thank you for your time, I really hope I can get this sorted as it is currently a key part of my A-level computing project.