I m new to RESTful Webservices in iOS and in Java. I read really a lot but i dont get definitiv answer how to SEND & RECEIVE a POST request in iOS & Handle that in Java.
My Situation is this:
I want to create a user on serverside. On Clientside i got for that 3 Objects that saves information (User, Usersdevice & Usersmembership). I read a lot about Objectmapping but I cant relate it with a practical example.
Seconde one is how to handle that POST on serverside with Java(Jersey) as RE.
Iknow that are two qeustions but I really need to know that.
I strongly recommend you to post a snippet of your code and clarify which restkit version uses. seems a bit outdated.
Also read the newest Object Mapping guide in order to leverage RestKit taking care if you want the KVC mapping or not. It could be tricky!!!
https://github.com/RestKit/RestKit/wiki/Object-mapping
First of all you have to determine your base URL:
RKObjectManager* manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:#"http://www.yourURL.com]];
A method to download articles using RK object mapping:
- (void)loadArticles{
RKObjectMapping* articleMapping = [RKObjectMapping mappingForClass:[Article class]];
[articleMapping addAttributeMappingsFromDictionary:#{
#"title": #"title",
#"body": #"body",
#"author": #"author",
#"publication_date": #"publicationDate"
}];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:articleMapping pathPattern:nil keyPath:#"articles" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
NSString * stringURL = #"/articles/";
[RKObjectManager.sharedManager getObjectsAtPath:stringURL parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult){
RKLogInfo(#"Load collection of Articles: %#", mappingResult.array);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
RKLogError(#"Operation failed with error: %#", error);
}];
[objectRequestOperation start];
}
In order to map this JSON
{ "articles": [
{ "title": "RestKit Object Mapping Intro",
"body": "This article details how to use RestKit object mapping...",
"author": "Blake Watters",
"publication_date": "7/4/2011"
},
{ "title": "RestKit 1.0 Released",
"body": "RestKit 1.0 has been released to much fanfare across the galaxy...",
"author": "Blake Watters",
"publication_date": "9/4/2011"
}]
}
Related
I'm attempting to integrate with Sendgrid and am having a heck of a time. I have created a dynamic template - a new one, not a legacy one - with a single handle bar (first_name) in it. It has a subject. But I'm getting a load of errors that I could use some help with.
First the code:
public void sendEmail(String toEmail, String toName) throws IOException {
String fromEmail = "validated-sendgrid-address#example.com";
String fromName = "Blah blah";
SendGrid sendGrid = new SendGrid("the_api_key");
Request request = new Request();
try {
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
String body = "see below...";
request.setBody(body);
Response response = sendGrid.api(request);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
System.out.println(response.getHeaders());
} catch (IOException ex) {
throw ex;
}
}
Taken almost entirely from the Java example code.
The JSON body, pretty printed...
{
"from": {
"email": "validated-sendgrid-address#example.com",
"name": "Blah blah"
},
"personalizations": [
{
"to": [
{
"email": "stdunbar#example.com",
"name": "Blah Blah"
}
],
"dynamic_template_data": {
"first_name": "Babaloo"
}
}
],
"template_id": "[d-lotsandlotsofcharacters]"
}
And then a bunch of errors that make no sense (all of which link to a 404):
Cannot use dynamic template data with a legacy template ID - I'm not using a legacy template id according to the UI
The template_id must be a valid GUID, you provided '[d-xxxxxxxxxxxxxx]' - I sent what I was given on the UI.
The subject is required. You can get around this requirement if you use a template with a subject defined or if every personalization has a subject defined. - My template has a subject
Unless a valid template_id is provided, the content parameter is required. There must be at least one defined content block. We typically suggest both text/plain and text/html blocks are included, but only one block is required. - A valid template_id was provided
I'm guessing the first issue is the template_id field. It's strange JSON in that the value includes the array open/close. Putting the value inside as text gives a parse error so Sendgrid must be taking that directly.
Any directional help would be most appreciated. The docs are rather challenging
Twilio SendGrid developer evangelist here.
In your example, you show the template_id as "template_id": "[d-lotsandlotsofcharacters]". The square brackets are not required in the template_id, it should just be "template_id": "d-lotsandlotsofcharacters".
The documentation for sending an email with a dynamic template does show the the template_id example as "template_id":"[template_id]" but the entire [template_id] string should be substituted for the real ID.
I was getting the same error. I had failed to copy the Template ID correctly. The Template ID is displayed when you click in the sidebar of the SendGrid control panel, "Email API ➔ Dynamic Templates". It is not the same as the ID you get from the /v3/designs endpoint, alas.
The error message is ambiguous. It says "Cannot use dynamic template data with a legacy template ID", when in fact it should say "Template ID not found". I was misled into believing that my Template was a legacy version, which it was not. Four hours I'll never get back.
I am trying to figure out what is the best practice to use Mapbox on Android with tiles stored in a server.
I know the tiles are available because I can make them appear on the web.
I can use the default styles no problem mapBox.setStyle(Style.LIGHT) but when I try to change the map style using the server tiles.
I'm creating a JsonObject:
val mapJSONObject = JsonObject()
which is the equivalent of this:
{
"version": 8,
"sources": {
"tiles-name": {
"type": "raster",
"url": "https://myserver.com/map/c16c1u38213f0db8001b1c6e8cee5f7a/{z}/{x}/{y}?token=jfsdajfdsjkfjksh34232fsd",
"tileSize": 256
}
},
"layers": [{
"id": "ee-raster",
"type": "raster",
"source": "tiles-name",
"minzoom": 0,
"maxzoom": 22
}]
}
I've tried to use this JsonObject by either calling it by:
map.setStyle(Style.Builder().fromJson(mapJSONObject.toString()))
or by creating a .json file via this function:
#Throws(IOException::class)
fun save(context: Context, jsonString: String) {
val rootFolder = context.getExternalFilesDir(null)
val jsonFile = File(rootFolder, "file.json")
val writer = FileWriter(jsonFile)
writer.write(jsonString)
writer.close()
}
then using that .json file via:
map.setStyle(Style.Builder().fromJson("file.json"))
When triggering the change map using:
map.setStyle(Style.Builder().fromJson(mapJSONObject.toString()))
I get the error message:
D/Mbgl-HttpRequest: [HTTP] Request with response = 404: No additional
information
[Style]: Failed to load source tiles-name: HTTP status code 404
When triggering the change map using:
map.setStyle(Style.Builder().fromJson("file.json"))
I get the error message:
[ParseStyle]: Failed to parse style: Invalid value. at offset 1
I have trouble debugging this, even though the error messages seem clear enough.
I have been reading through the MapBox documentation, but can't seem to find a clear example using tiles from tiles on a server.
Can anyone identify what might be the issue or point me to an example using this method?
Doesn't have to be in Kotlin, Java would be equally useful.
Its been so much of time exploring the Google vision API, I am trying to get the Vision API Response in English Language only , below is my request object to API which has language hints :
{
"requests": [
{
"features": [
{
"type": "IMAGE_PROPERTIES"
},
{
"type": "LANDMARK_DETECTION"
},
{
"type": "LABEL_DETECTION"
},
{
"type": "WEB_DETECTION"
},
{
"type": "FACE_DETECTION"
},
{
"type": "SAFE_SEARCH_DETECTION"
},
{
"type": "TEXT_DETECTION"
},
{
"type": "LOGO_DETECTION"
}
],
"image": {
"source": {
"imageUri": "https://images.dreamstream.com/prodds/prddsimg/OM_pasteIt22_12_2017_2_34_7806303.jpeg"
}
},
"imageContext": {
"languageHints": [
"en"
]
}
}
]
}
Even this request object not getting correct response(multiple languages) from Vision API ..
if there is any steps is there to get response in English only please let me know, as of now response contains multiple languages like below :
{
"url": "https://www.tummyummi.com/food/menu-aryaas-restaurant",
"pageTitle": "Aryaas India Restaurant - مطعم ارياس لبهند - TummYummi Restaurants",
"fullMatchingImages": [
{
"url": "https://www.tummyummi.com/food/upload/1509868727-Curd-Vada.jpg"
}
]
},
If I'm understanding correctly, the Vision Api is looking at your image, and determined that it has seen a similar image at https://www.tummyummi.com/food/menu-aryaas-restaurant.
The title of this website is Aryaas India Restaurant - مطعم ارياس لبهند - TummYummi Restaurants.
It is not a bug that this non-english text is being sent to you, because you asked the Api to use WEB_DETECTION.
It found a website that has that image, and gave you a link to it and its title.
From the docs, the ImageContext parameter languageHints allows you to set the expected language for text in the image, and will return an error if any other language is detected:
Text detection returns an error if one or more of the specified languages is not one of the supported languages.
It's important to note that this language setting is only affecting text detection.
If you want the text detection to only return english elements, but not error out if it detects anything else, then that document recommends the following:
For languages based on the Latin alphabet, setting languageHints is not needed. In rare cases, when the language of the text in the image is known, setting a hint will help get better results (although it will be a significant hindrance if the hint is wrong)
Instead, to filter out any text that is not english, you would instead look at the TextAnnotation's locale field, and filter out anything that isn't en on the client side.
As far as detecting the language of the title of the website during WEB_DETECTION is concerned, I think that is out of scope of the Google vision api, but you could try using the detecting lanuages feature of the cloud translation api.
Thanks for the useful answer #dustinroepsch, rather than relying on cloud translation api , we can go for regex because the only feature which is having non-english texts is WEB_DETECTION , sometimes it may vary.
In WEB_DETECTION , few objects like pagesWithMatchingImages and webEntities may have non-english texts . After Parsing JSON , we can use following regex pattern to remove non-english texts.
String regex = "[a-z,A-Z,0-9,($&+,:;=?##|'<>.^*()%!-)\\s]";
I am using goggle's search api to get topics id which is used to get JSON response from topic api.The returned response looks like this
{
"id":"/m/01d5g",
"property":{
"/amusement_parks/ride_theme/rides":{...},
"/award/ranked_item/appears_in_ranked_lists":{...},
"/book/book_character/appears_in_book":{
"valuetype":"object",
"values":[
{
"text":"Inferno",
"lang":"en",
"id":"/m/0g5qs3",
"creator":"/user/duck1123",
"timestamp":"2010-02-11T04:00:59.000Z"
},
{
"text":"Batman: Year One",
"lang":"en",
"id":"/m/0hzz_1h",
"creator":"/user/anasay",
"timestamp":"2012-01-25T11:05:03.000Z"
},
{
"text":"Batman: The Dark Knight Returns",
"lang":"en",
"id":"/m/0hzz_sb",
"creator":"/user/anasay",
"timestamp":"2012-01-25T11:22:17.001Z"
},
{
"text":"Batman: Son of the Demon",
"lang":"en",
"id":"/m/071l77",
"creator":"/user/wikimapper",
"timestamp":"2013-07-11T15:20:32.000Z"
},
{
"text":"Joker",
"lang":"en",
"id":"/m/04zxvhs",
"creator":"/user/wikimapper",
"timestamp":"2013-07-11T16:58:37.000Z"
},
{
"text":"Arkham Asylum: A Serious House on Serious Earth",
"lang":"en",
"id":"/m/0b7hyw",
"creator":"/user/wikimapper",
"timestamp":"2013-07-11T19:26:54.000Z"
}
],
"count":6.0
},
"/book/book_subject/works":{...},
"/comic_books/comic_book_character/cover_appearances":{...},
...
}
}
I want to decipher this so that i can get relevant information such as, "/book/book_character/appears_in_book" itself is a property for response and only required value that i want from it is "text" and "id" e.g. "text":"Batman: Year One" and "id":"/m/0hzz_1h".
Since the response does not have fixed properties, and which may varying according to response id. how can i covert this JSON response in java Class where i can store "/book/book_character/appears_in_book" as one serialized class and containing Collection of values such has id and text and appears_in_book as name variables for class.
I considered GSON to do this. since name of property is not constant i can not use it to covert JSON to Java Object. currently i am iterating over each property by hard coding and filling them in java variables.
If some one can provide efficient way to do so i will appreciate help.
You could do this dynamically using reflection in Java but this is an advanced feature of Java and it may make your code more complicated than it needs to be.
See: Dynamically create an object in java from a class name and set class fields by using a List with data
A simpler alternative would be to just parse the JSON into a bunch of nested Maps and Lists exactly as they're given in the JSON data.
See: How to parse JSON in Java
How can i parse the exported bookmarks file from Google Chrome and Mozilla Firefox in Java.Is there any libraries available to parse them directly and obtain the URLS in them.
Also sample codes for parsing them in Java are most welcomed .
In most cases, you don't really need to parse the HTML file. Chrome stores its bookmarks in a JSON file. It's a lot simpler to just read that file using a JSON parser.
The file you are interested in is located at (on Linux, anyway, Google around for other O/S):
/home/your_name/.config/google-chrome/Default/Bookmarks
JSON parsing is easy. Google around or start with How to parse JSON in Java.
If you want to visualize JSON data before you start digging through it, then also have a look at http://chris.photobooks.com/json/default.htm.
Per new comments posted , the solution would be to use JSOUP Open Source Program to do this.
JSOUP accepts only HTTP or HTTPS protocols so you might want to host the exported bookmark HTML on a Local Server like tomcat and obtain the DOM of it
http://yourip:<port>/<yourProject>/<bookmark.html>.
JSOUP is pretty self-explanatory.
Other simpler ways :
Chrome and Firefox bookmarks are stored as JSON like below.
Java way : I would suggest you use JSON to parse these. Make a reference Java Object based on the below structure.
or simply use UNIX Command prompt and do a
grep -i "url" <bookmark file path> | cut -d":" -f2
However if you still interested to do with Chrome APIs then please visit : http://developer.chrome.com/extensions/bookmarks.html
{
"checksum": "702d8e600a3d70beccfc78e82ca7caba",
"roots": {
"bookmark_bar": {
"children": [ {
"date_added": "12939920104154671",
"id": "3",
"name": "Development/Tutorials/Git/git-svn - KDE TechBase",
"type": "url",
"url": "http://techbase.kde.org/Development/Tutorials/Git/git-svn"
}, {
"date_added": "12939995405838705",
"id": "4",
"name": "QJson - Usage",
"type": "url",
"url": "http://qjson.sourceforge.net/usage.html"
I am a bit late to this question. But if it is still relevant: I needed to do the same (and also other bookmark sources: GitHub Stars, Netscape and Google Bookmarks as well) and build my own. You can look and take it from my repo: https://github.com/IvoLimmen/mystart.
If somebody is interested: Here's a scala snippet of how you could tackle parsing Chrome's bookmarks JSON file (not thoroughly tested though, just to get the idea):
import org.json4s.DefaultFormats
import org.json4s.native.JsonMethods
import org.junit.Test
class BookmarksImporterTest {
implicit val formats: DefaultFormats.type = DefaultFormats
def analyse(element: Node): List[Node] = {
element.children.flatMap(c => {
c.`type` match {
case Some("folder") => c.children.flatMap(r => analyse(r))
case Some("url") => List(c)
case _ => println("???"); List()
}
})
}
#Test
def test(): Unit = {
val source = scala.io.Source.fromFile("bookmarks.json")
val json = JsonMethods.parse(source.reader())
val bookmarks = json.extract[ChromeBookmarks]
val bms = bookmarks.roots.flatMap {
case (name, elements) => analyse(elements)
}
println("found " + bms.size + " entries")
}
}
case class ChromeBookmarks(checksum: String, roots: Map[String, Node], version: Int)
case class Node(
id: Option[String],
name: Option[String],
url: Option[String],
children: List[Node],
`date-added`: Option[Long],
`date-modified`: Option[Long],
`type`: Option[String]
)