I have an xml content as string how can i pass that to jaxb parser to populate the pojo class
<?xml version="1.0" encoding="UTF-8"?><breakfast_menu<food>
<name>Belgian Waffles</name><food>
To pass XML content, you need to wrap the content in a Reader, and unmarshal that instead:
JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader("xml string here");
Person person = (Person) unmarshaller.unmarshal(reader);
Related
In Restassured we can pass the request payload in the body method by different ways like
String
POJO Object
Map Object
JsonObject (from GSON library)
File and
FileInputStream
So, I created following one method using generics to accommodate all these types: -
public <T> Response postAMember(T body) {
return given().spec(this.spec).body(body).when().post(EndPoints.GET_ALL_POST_A_MEMBER).andReturn();
}
Now, this is how I'm consuming it for respective Type (Not all in one go...one at a time): -
#Test
public void postMember() throws IOException {
// Using Hashmap
Map<String, String> body = new HashMap<>();
body.put("name", "Rocky");
body.put("gender", "Male");
// Using Model and GSON
Member imember = new Member("Rocky", "Male");
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String body = gson.toJson(imember);
// Using JsonObject (GSON)
JsonObject body = new JsonObject();
body.addProperty("name", "Rocky");
body.addProperty("gender", "Male");
// Using Payload JSON File
File body = new File("src/test/resources/Payloads/postmemberpayload.json");
// Using Raw String
String body = "{\r\n" +
" \"name\": \"Rocky\",\r\n" +
" \"gender\": \"Male\"\r\n" +
"}";
// Using FileInputStream
FileInputStream fis = new FileInputStream(body); // in this case I would pass fis to body method
Response resp = MemberService.getMemberServiceInstance().postAMember(body);
Assert.assertEquals(resp.getStatusCode(), StatusCode.CREATED_201);
Member omember = resp.getBody().as(Member.class);
System.out.println(omember.toString());
}
postAMember method works fine only with : -
String
POJO Object
Map Object
JsonObject (from GSON library)
But fails with remaining two: -
File - Output is bad request 400
FileInputStream - Output is java.lang.IllegalArgumentException: jdk.internal.ref.PhantomCleanable<?> declares multiple JSON fields named next
And for now I've to make following two more overloaded version of postAMember: -
public Response postAMember(File body) {
return given().spec(this.spec).body(body).when().post(EndPoints.GET_ALL_POST_A_MEMBER).andReturn();
}
public Response postAMember(FileInputStream body) {
return given().spec(this.spec).body(body).when().post(EndPoints.GET_ALL_POST_A_MEMBER).andReturn();
}
Now above two methods generate the response. Any clue what's wrong here? Why the method with generics is not able to take File and FileInputStream?
I've fetched the latest Restassured libraries from maven central repo.
As far as I understand, your generics method will map to body(Object object) of RequestSpecification, then this object will be serialized.
class RequestSpecificationImpl
...
RequestSpecification body(Object object) {
...
this.requestBody = ObjectMapping.serialize(object, requestContentType,
findEncoderCharsetOrReturnDefault(requestContentType), null,
objectMappingConfig(), restAssuredConfig().getEncoderConfig());
...
}
All below kinds of object has no problem with serialization.
String
POJO Object
Map Object
JsonObject (from GSON library)
But
File ---serialize---> full path of FILE
FileInputStream ---serialize---> exception (from Gson/Jackson)
When you add 2 methods, then Rest-Assured correctly map to body(File body) and body(InputStream body) --> no serialization for them --> no issue.
Doing a project in .Net Core 2, using MVC, I'm attempting to incorporate a project from GitHub that generates the XML for an RSS feed. It is TAlex.RSSFeedGenerator.
To generate the actual document, the FeedGenerator's only option is serializing its RSS object to a MemoryStream:
public void Generate(Rss rss, Stream output)
{
XmlSerializer serializer = new XmlSerializer(typeof(Rss));
serializer.Serialize(output, rss);
}
So FeedGenerator has already serialized the RSS content as XML in Stream, and I want to return that content as XML from an MVC Controller ( return Ok(content_here) ).
How can I do this?
As incorporated originally / currently:
var rss = new Rss();
// ...
var RssFeedGenerator = new FeedGenerator();
var output = new MemoryStream();
RssFeedGenerator.Generate(rss, output);
output.Position = 0;
var sreader = new StreamReader(output);
return Ok(sreader.ReadToEnd());
This puts out a string and is seen as a string by the browser. It is not seen as XML or RSS.
The MVC Controller is defined and decorated like so:
[HttpGet()]
[Produces("text/xml")]
public async Task<IActionResult> GetAsync() {...}
So, I need the string that is already an XML document to be recognized as an XML document, not a string. My goal is also to send the contents as a response directly, not save it to a file and then have to redirect the user to that file or have to have Ok() read from the file.
Also, I can't send the MemoryStream directly to Ok(), because I get an error that one can't access a closed stream.
The browser is currently showing this:
<string><?xml version="1.0" encoding="utf-16"?> ... </string>
(Originally, it was properly decoding the HTML entities, so you'd see:
<string><?xml version="1.0" encoding="utf-16"?> ... </string>
but now it's not even doing that.)
Thanks for clarifying.
Please return ContentResult in order to see the RSS XML. You can have "application/xml" or "application/RSS+XML" or "text/xml"
public async Task<IActionResult> GetAsync()
{
string rssFeed = "<?xml >...";
return new ContentResult
{
Content = rssFeed,
ContentType = "application/RSS+xml"
};
}
I want to parse the following XML file and print the list of all the attributes for the tag book. I am parsing with SAX parser. The problem is it is printing only the first attributes. The other attribute is not getting printed.
The XML is as follows.
<?xml version="1.0"?>
<catalog>
<book id="bk101" action="lock">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
</book>
</catalog>
How should I write the code for printing all the attributes for the tag book.
The SAX callback for startElement can look like this. Here the attributes are parsed in a loop:
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts)
throws SAXException
{
System.out.print("<"+qName);
for(int i=0; i<atts.getLength(); i++) {
System.out.print(" "+atts.getQName(i)+"=\""+atts.getValue(i)+"\"");
}
System.out.println(">");
}
how can I get the json being returned from mvc4 web platform
below is my function:
Public Function insertReg()
dim res as new resObj()
res.id=1
res.name="test"
return res
End Function
public class resObj
Public Property id As Integer
Public Property name As String
End Class
when I return the res object my mvc4 solution converts it directly to json, but I need to retrieve this json and put it in a variable for another use.
You can import the following Namespace, you will probably need to add the relevant assembly. And then you can serialize into a JSON string
import System.Web.Script.Serialization;
Public Function insertReg()
dim res as new resObj()
res.id=1
res.name="test"
var json = new JavaScriptSerializer().Serialize(res);
return res
End Function
If you want the root object to go along with the JSON than create a dynamic wrapper class.
TestModel model = new TestModel();
model.pass = "PassMe";
dynamic Wrapper = new
{
TestModel = model
};
var JSON = new JavaScriptSerializer().Serialize(Wrapper);
JSON will = {"TestModel":{"pass":"PassMe"}}
does somebody know whats wrong with the next method?
public static String getMessageBundleString(String key, String localeAcronym) throws MissingResourceException {
FacesContext facesContext = FacesContext.getCurrentInstance();
String messageBundleName = facesContext.getApplication().getMessageBundle();
ResourceBundle bundle = ResourceBundle.getBundle(messageBundleName, new Locale(localeAcronym));
//THE LOCALE OF THIS BUNDLE IS ALWAYS 'es_ES' !!!
return bundle.getString(key);
}
In a Primefaces/JSF environment, I want to retrieve a key from the proper i18n properties file.
But it always take it from the messages_es_ES.properties file.
Following invocations return same value (='Inicio'):
getMessageBundleString("home", "es_ES")
getMessageBundleString("home", "uk_UK")
messages_es_ES.properties:
home=Inicio
messages_uk_UK.properties:
home=Home
Thanks
Here some of my faces-config.xml content:
<application>
<locale-config>
<supported-locale>es_ES</supported-locale>
<supported-locale>uk_UK</supported-locale>
</locale-config>
<message-bundle>cfg.i18n.messages</message-bundle>
<resource-bundle>
<base-name>cfg.i18n.messages</base-name>
<var>msgs</var>
</resource-bundle>
</application>
This variant works (separating country and language):
public static String getMessageBundleString(String key, String language, String country) throws MissingResourceException {
FacesContext facesContext = FacesContext.getCurrentInstance();
String messageBundleName = facesContext.getApplication().getMessageBundle();
ResourceBundle bundle = ResourceBundle.getBundle(messageBundleName, new Locale(language, country));
//Valid ones: "es","ES"; "en","GB"!!!
return bundle.getString(key);
}
Did you try this variation?
getMessageBundleString("home", "es")
getMessageBundleString("home", "en")
messages_es.properties:
home=Inicio
messages_en.properties:
home=Home