How do I pass the result from httpget to SAX parser - saxparser

I'm want to make a request to google API and pass the resulting XML to SAX parser here are both codes...
First the request:
HttpClient hclient = new DefaultHttpClient();
HttpGet get = new HttpGet("http://www.google.com/ig/api?weather=Cardiff");
HttpResponse hrep = hclient.execute(get);
HttpEntity httpEntity = hrep.getEntity();
Then the parser:
SAXParserFactory saxpf = SAXParserFactory.newInstance();
SAXParser saxp = saxpf.newSAXParser();
XMLReader xr = saxp.getXMLReader();
ExHandler myHandler = new ExHandler();
xr.setContentHandler(myHandler);
xr.parse();
Is this the right way to do this and how do I connect both codes.
Thanks in advance

The SAXParser object can take in an input stream and the handler. So something like:
SAXParser saxParser = factory.newSAXParser();
XMLParser parser = new XMLParser();
saxParser.parse(httpEntity.getContent(),parser);
The getContent() method returns and input stream from the HttpRequest, and the XMLParser object is just a class I created (supposedly) that contains the definition of how to parse the XML.
EDIT*
You really should read the entire API for SAXParser, it has several overloaded methods:
void parse(InputSource is, DefaultHandler dh)
Parse the content given InputSource as XML using the specified DefaultHandler.
void parse(InputSource is, HandlerBase hb)
Parse the content given InputSource as XML using the specified HandlerBase.
void parse(InputStream is, DefaultHandler dh)
Parse the content of the given InputStream instance as XML using the specified DefaultHandler.
void parse(InputStream is, DefaultHandler dh, String systemId)
Parse the content of the given InputStream instance as XML using the specified DefaultHandler.
void parse(InputStream is, HandlerBase hb)
Parse the content of the given InputStream instance as XML using the specified HandlerBase.
void parse(InputStream is, HandlerBase hb, String systemId)
Parse the content of the given InputStream instance as XML using the specified HandlerBase.
Some of the methods take an InputSource, some take an InputStream, as I stated earlier.

Related

Apache Camel with Spring Boot - Zip process

I am trying to process a zip file with Apache Camel.
After making a call, I get a zip file and try to prepare the next call with this zip file as body.
The call requires a form data with one name and zip file as value.
I handle in this way:
process(e ->{
Object zip = e.getIn().getBody();
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file",zip);
e.getIn().setBody(body);
})
But I receive the exception:
org.apache.camel.NoTypeConversionAvailableException: No type converter available to convert from type: org.springframework.util.LinkedMultiValueMap to the required type: java.io.InputStream with value {file=[[B#2b02c691]}
Any Ideas?
Cheers!
I tried to get the response in byte[] but it still dose not work.
As Jeremy said, the error says Camel is expecting (further in the process) a body of type InputStream, whilst you are obviously preparing a body of type MultiValueMap (BTW: why use a map if you have a single object to handle ??)
I do not know what is the concrete type of your 'zip' object, but (if needed) you may have to replace current body with its inputstream equivalent:
process(e ->{
// Print concrete type
Object zip = e.getMessage().getBody();
System.out.println("Type is " + zip.getClass() );
// Convert body
InputStream is = e.getMessage().getBody(InputStream.class);
// Replace body
e.getMessage().setBody(is);
})

What is the alternative for HttpContext.Response.OutputStream to use in WebAPI's HttpResponseMessage

I'm writing a WebAPI for handling PDF documents. It was written in a ashx page earlier implementing IHttpHandler and getting the context using HttpContext. I'm now writing it using WebAPI. In WebAPI we have HttpResponseMessage. For HttpContext.Response.BinaryWrite we have new ByteArrayContent in HttpResponseMessage. But what is the alternative for HttpContext.Response.OutputStream in WebAPI? I need to have the alternative of OutputStram in WebAPI because im passing this OutputStream as a parameter to another dll.
Code in ashx:
SomeReport.PdfReport rpt = new SomeReport.PdfReport(docID);
rpt.CreateReport(context.Response.OutputStream);
Actually you can use any stream for example MemoryStream but result should be wrapped into StreamContent.
public HttpResponseMessage Get()
{
var response = Request.CreateResponse();
var outputStream = new MemoryStream();
//write data to output stream
//or passing it to somewhere
outputStream.WriteByte(83);
outputStream.Position = 0;
response.Content = new StreamContent(outputStream);
return response;
}
If you need direct writing to output stream, please consider using PushStreamContent. Example

Globally formatting .net Web Api response

I have a Web Api service that retrieves data from another service, which returns Json. I don't want to do anything to the response, I just want to return it directly to the client.
Since the response is a string, if I simply return the response, it contains escape characters and messy formatting. If I convert the response in to an object, the WebApi will use Json.Net to automatically format the response correctly.
public IHttpActionResult GetServices()
{
var data = _dataService.Get(); //retrieves data from a service
var result = JsonConvert.DeserializeObject(data); //convert to object
return Ok(result);
}
What I would like is to either A: Be able to return the exact string response from the service, without any of the escape characters and with the proper formatting, or B: Set a global settings that will automatically Deserialize the response so that the Web Api can handle it the way I am doing it already.
On Startup I am setting some values that describe how formatting should be handled, but apparently these aren't correct for what im trying to do.
HttpConfiguration configuration = new HttpConfiguration();
var settings = configuration.Formatters.JsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new DefaultContractResolver();
Do I need to create a custom ContractResolver or something? Is there one that already handles this for me?
Thanks
If you want to just pass through the json (Option A), you can do this
public IHttpActionResult GetServices() {
var json = _dataService.Get(); //retrieves data from a service
HttpContent content = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = content;
return ResponseMessage(response);
}

FileSystemResource is returned with content type json

I have the following spring mvc method that returns a file:
#RequestMapping(value = "/files/{fileName}", method = RequestMethod.GET)
public FileSystemResource getFiles(#PathVariable String fileName){
String path="/home/marios/Desktop/";
return new FileSystemResource(path+fileName);
}
I expect a ResourceHttpMessageConverter to create the appropriate response with an octet-stream type according to its documentation:
If JAF is not available, application/octet-stream is used.
However although I correctly get the file without a problem, the result has Content-Type: application/json;charset=UTF-8
Can you tell me why this happens?
(I use spring version 4.1.4. I have not set explicitly any message converters and I know that spring loads by default among others the ResourceHttpMessageConverter and also the MappingJackson2HttpMessageConverter because I have jackson 2 in my classpath due to the fact that I have other mvc methods that return json.
Also if I use HttpEntity<FileSystemResource> and set manually the content type, or specify it with produces = MediaType.APPLICATION_OCTET_STREAM it works fine.
Note also that in my request I do not specify any accept content types, and prefer not to rely on my clients to do that)
I ended up debugging the whole thing, and I found that AbstractJackson2HttpMessageConverter has a canWrite implementation that returns true in case of the FileSystemResource because it just checks if class is serializable, and the set media type which is null since I do not specify any which in that case is supposed to be supported by it.
As a result it ends up putting the json content types in a list of producible media types. Of course ResourceHttpMessageConverter.canWrite implementation also naturally returns true, but the ResourceHttpMessageConverter does not return any producible media types.
When the time to write the actual response comes, from the write method implementation, the write of the ResourceHttpMessageConverter runs first due to the fact that the ResourceHttpMessageConverter is first in the list of the available converters (if MappingJackson2HttpMessageConverter was first, it would try to call write since its canWrite returns true and throw exception), and since there was already a producible content type set, it does not default to running the ResourceHttpMessageConverter.getDefaultContentType that would set the correct content type.
If I remove json converter all would work fine, but unfortunately none of my json methods would work. Therefore specifying the content type is the only way to get rid of the returned json content type
For anyone still looking for a piece of code:
You should wrap your FileSystemResource into a ResponseEntity<>
Then determine your image's content type and append it to ResponseEntity as a header.
Here is an example:
#GetMapping("/image")
public #ResponseBody ResponseEntity<FileSystemResource> getImage() throws IOException {
File file = /* load your image file from anywhere */;
if (!file.exists()) {
//TODO: throw 404
}
FileSystemResource resource = new FileSystemResource(file);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(/* determine your image's media type or just set it as a constant using MediaType.<value> */);
headers.setContentLength(resource.contentLength());
return new ResponseEntity<>(resource, headers, HttpStatus.OK);
}

Jersey:Returning a Response with a Map containing Image Files and JSON String values

I am using Jersey JAX-RS.
I want to return a Response with a Map containing Image Files and JSON String values.
Is this the right way to do this:
Map<String,Object> map = new HashMap........
GenericEntity entity = new GenericEntity<Map<String,Object>>(map) {};
return Response.ok(entity).build();
Or is this better.I plan to use JAX-RS with Jersey only.
JResponse.ok(map).build();
I am basing this on this article:
http://aruld.info/handling-generified-collections-in-jersey-jax-rs/
I am not sure what to specify for #Produces too(planning to leave it out).
TIA,
Vijay
You better produce a multipart response:
import static com.sun.jersey.multipart.MultiPartMediaTypes.MULTIPART_MIXED_TYPE;
import static javax.ws.rs.core.MediaType.APPLICATION_XML_TYPE
#GET
#Produces(MULTIPART_MIXED_TYPE)
public Response get()
{
FileDataSource image = ... (gets the image file)
String info = ... (gets the xml structured information)
MultiPart multiPart = new MultiPart().
bodyPart(new BodyPart(info, APPLICATION_XML_TYPE)).
bodyPart(new BodyPart(image, new MediaType("image", "png")));
return Response.ok(multiPart, MULTIPART_MIXED_TYPE).build();
}
This example was taken from there.

Resources