How to Decode Unicode Characters from Cookie - spring

I am saving a list in String format by encoding it to UTF-8. But I see that {, }, :... and more symbols are in cookie value.
%7B%22evt%22%3A%5B%5D%2C%22exc%22%3A%5B%5D%2C%22tourQuantity%22%3A%221%22%2C%22tourId%22%3A%22067e61623b6f4ae2a1712470b63dff00%22%2C%22room%22%3A%7B%22accId%22%3A%226%22%2C%22roomTypeId%22%3A%225%22%7D%7D
Above one is the stored value in the cookie.
public ResponseEntity < ModelAndView > saveReservation(#RequestBody String reservation, HttpServletRequest request,
HttpServletResponse response) throws Exception {
Cookie cookie = new Cookie("tourReservation", URLEncoder.encode(reservation, "UTF-8"));
cookie.setMaxAge(24 * 60 * 60);
cookie.setPath("/tour/reservation");
response.addCookie(cookie);
List < ? > list = service.saveRes(reservation);
if (list.size() > 0) {
.........
return new ResponseEntity < ModelAndView > (model, HttpStatus.OK);
}
return new ResponseEntity < ModelAndView > (new ModelAndView("tour"), HttpStatus.BAD_REQUEST);
}
How can I get my list string in a good format? I also used StringEscapeUtils, I got an error java.lang.IllegalArgumentException: An invalid character [34] was present in the Cookie value.
org.apache.commons.lang.StringEscapeUtils.unescapeJava(reservation)

Leave as it is. Get the cookie value in JavaScript and use unescape(str) or
decodeURIComponent(str) function to decode it.
Note: unescape() is deprecated so you may use decodeURIComponent() instead.

Related

Spring , update value if not null

I am working with Redmine API, and want to update an issue.
The issue has 30 variables, Subject, Description, Author, and Assignee ...
I have no problem updating the issue Subject and Description like this:
#RequestMapping(value = "/issues/update/{id}", method = RequestMethod.PUT)
public ResponseEntity<Object> issueUpdate(#RequestBody ObjectNode json, #PathVariable int id) throws RedmineException, RuntimeException, IllegalArgumentException {
String apiKey = json.get("API_KEY").asText();
RedmineManager mgr = RedmineManagerFactory.createWithApiKey("http://localhost:3001/", apiKey);
IssueManager issueManager = mgr.getIssueManager();
Issue issue = issueManager.getIssueById(id);
issue.setSubject(json.get("SUBJECT").asText())
.setDescription(json.get("DESCRIPTION").asText())
.update();
return new ResponseEntity<>(HttpStatus.OK);
}
The problem with this way is I am only allowed to change these 2 values and I have to include, SUBJECT and DESCRIPTION in my JSON request body.
If SUBJECT is not in JSON, then it will be considered as null and I get NullPointerException.
I want to make something more flexible and elegant, to allow the change of each value, and if not exist, don't set to null but keep the old values.
something logical to this but a bit smarter
if json.get("SUBJECT").asText() != null {
issue.setSubject(json.get("SUBJECT").asText()) //set if mentioned
} else {
issue.setSubject(issue.getSubject()) //set the old value
}
The idea is, now am available to have setSubject and all the other available setters in case it's mentioned in my JSON request or not.

Spring REST templates - difference between put() and exchange()

This is a test case I was writing for update calls to database:
#Test
public void testUpdateList() {
//
//... Some variables
//
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
String requestBody = "{\"id\":\"" + givenId + "\",\"listName\":\"" + listName + "\",\"owner\":\"" + owner + "\"}";
HttpEntity <String> entity = new HttpEntity<>(requestBody, headers);
// Call to update
ResponseEntity <TaskListResponse> list = template.exchange(REQUEST_URL + "/list/update/{id}", HttpMethod.PUT, entity, TaskListResponse.class, params);
}
Here params is a name-value HashMap for the REST URL.
When I wanted to update a list type, since RestTemplate.put() doesn't have a return type, I used HTTP requests.
A call with template.put would look like this:
template.put(REQUEST_URL + "/list/update/{id}", request, params);
But I don't know the difference between the two types of calls. Could someone explain it to me in reference to the above code? How can template.exchange return a value, if it's a PUT request?
What I'm looking for is that since I used template.post/get/delete for create(), search() and delete(), should I use .put() for update() as well, even though I won't get a response?

MethodNotAllowedHttpException in compiled.php line 8518

Im sending request from salesforce to laravel then laravel return the result and display them on visual force page
Error Detail
Apex Method
public List<SelectOption> getItems()
{
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
req.setEndpoint('http://clozer.3spire.net/public/goclozer/country');
req.setMethod('GET');
req.setCompressed(false);
req.setBody('key1=value1&key2=value2');
req.setHeader('Content-Type', 'application/json');
try {
res = http.send(req);
} catch(System.CalloutException e) {
system.debug('Callout error: '+ e);
}
getAllCountry = (Map<String, String>)JSON.deserialize(res.getBody(),Map<String, String>.class);
List<SelectOption> option = new List<SelectOption>();
option.add(new SelectOption('0','--None--'));
for(String c : getAllCountry.values())
{
option.add(new SelectOption(c,c));
}
return option;
}
Expected Result
{"0":"Aruba","1":"Antigua and Barbuda","2":"United Arab Emirates","3":"Afghanistan","4":"Algeria","5":"Azerbaijan","6":"Albania","7":"Armenia","8":"Andorra","9":"Angola","10":"American Samoa","11":"Argentina","12":"Australia","13":"Ashmore and Cartier Islands"}
Laravel 5 Route
Route::get('/goclozer/country','GoClozerController#getCountry');
Laravel 5 Method
public function getCountry()
{
$country = \App\Country::all();
$names = array();
foreach($country as $c)
{
$names[] = $c->name;
}
echo json_encode($names,JSON_FORCE_OBJECT);
}
How can i get ride of this error
Thanks in advance
MethodNotAllowedHttpException means that you're using wrong HTTP verb ( Get, Post, Put, Delete ...). You've route defined for GET, but you may be posting data
The modification (as I assume you just want to retrieve the country names only) can be achieved by
$countries = Country::all(['name']);
this will only retrieve the names of the countries from the table, you can add more fields if you want to.
Controller gets a request, returns a response. You're not returning any response. just echoing the result. You can do the following,
return $countries;
This will simply return the JSON with country names.
You don't have to put an explicit slash at the front of route declaration. you can even write like the following and that will work too.
Route::get('goclozer/country','GoClozerController#getCountry');

Jersey Obfuscating Collections in JSON Output

In my code I can see I am returning a valid Object. This object happens to contain a collection of 'user comments'. This collection is valid and filled with entries right before I return the Response object through JAX-RS. However, when the GET request is completed that collection is mysteriously replaced by a boolean value denoting if the collection is empty or not.
Just to reiterate. Valid, non-empty collection, returned in a GET request as a boolean with field 'empty'
What gives? I know there must be some magic under the hood, but it has been escaping me.
#GET
#Path("{issue: \\w+-\\d+}")
#Produces(MediaType.APPLICATION_JSON)
public Response getIssue(#PathParam("issue") String issue) {
Issue returnedIssue = null;
try {
returnedIssue = jiraService.getIssue(issue);
}
catch (RestClientException ex) {
log.error("ERROR: Could not find issue " + issue + ": " + ex.getMessage());
throwErrorResponse(Response.Status.NOT_FOUND);
}
return getResponse(Response.Status.OK, returnedIssue);
}
This is my POJO: http://docs.atlassian.com/jira-rest-java-client/1.0/apidocs/com/atlassian/jira/rest/client/domain/Issue.html

How to add link in atom feed using spring 3, netbeans

Using spring3.2 and netbeans 7.2
Warning code :
#Override
protected List<Entry> buildFeedEntries(Map<String, Object> model,
HttpServletRequest request, HttpServletResponse response) throws Exception {
#SuppressWarnings("unchecked")
List<Feed_vo> contentList = (List<Feed_vo>) model.get("feedContent");
List<Entry> entries = new ArrayList<Entry>(contentList.size());
for (Feed_vo content : contentList) {
Entry entry = new Entry();
String date = String.format("%1$tY-%1$tm-%1$td", content.getCreatedDate());
entry.setId(String.format("tag:featuriz.com,%s:%d", date, content.getId()));
entry.setTitle(String.format("%s | on %s by %s",content.getTitle(), date, content.getAuthor()));
entry = setLink(content, entry);
entry.setUpdated(content.getCreatedDate());
Content summary = new Content();
summary.setValue(content.getSummary());
entry.setSummary(summary);
entries.add(entry);
}
return entries;
}
private Entry setLink(Feed_vo vo, Entry entry) {
ArrayList l = new ArrayList();
Link link = new Link();
link.setType("text/html");
link.setHref(vo.getUrl());
l.add(link);
entry.setAlternateLinks(l);
return entry;
}
This code works but Netbeans warning :
/home/sudhakar/**/CustomAtomViewer.java:72: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.ArrayList
l.add(link);
1 warning
How to solve this warning.
Also inform me the correct format for atom and rss feed.
(How the output should look like. ie. output source).
Warnings solved by this code:
List<Link> v = new ArrayList<Link>();
Link link = new Link();
link.setType("text/html");
link.setHref(vo.getUrl());
v.add(link);
entry.setAlternateLinks(v);

Resources