Get EC2 Instance instance description using Java SDK?

We have a scenario in which we need to get information about the description of EC2 instances running on AWS. For this we use the SDK for Java AWS. In 90% of our use case, class com.amazonaws.services.ec2.model.Instanceis exactly what we need. However, there is also a small use case where it would be useful to get raw XML describing the instance. That is, the XML data before converting it to an object Instance. Is there a way to get both an object Instanceand an XML string using the AWS Java SDK? Is there a way to convert manually from one to another? Or will we be forced to make a separate call using HttpClientor something similar to retrieve XML data?

+4
source share
4 answers

If you have xml (for example, directly using the AWS rest API), you can use classes com.amazonaws.services.ec2.model.transform.*to convert xml to java objects. Unfortunately, it provides only the classes necessary for the SDK itself. Thus, for example, you can convert raw XML to an instance using InstanceStaxUnmarshaller, but you cannot convert an instance to XML if you do not write such a converter.

Here is an example of how to parse an XML instance:

XMLEventReader eventReader = XMLInputFactory.newInstance().createXMLEventReader(new StringReader(instanceXml));
StaxUnmarshallerContext suc = new StaxUnmarshallerContext(eventReader, new TreeMap<>());
InstanceStaxUnmarshaller isu = new InstanceStaxUnmarshaller();
Instance i = isu.unmarshall(suc);
System.out.println(i.toString());

, AWS-, XML, SDK . , .

+1

EC2Client, beforeUnmarshalling(),

AmazonEC2ClientBuilder.standard().withRegion("us-east-1")
    .withRequestHandlers(
            new RequestHandler2() {
                  @Override
                    public HttpResponse beforeUnmarshalling(Request<?> request, HttpResponse httpResponse) {
                        // httpResponse.getContent() is the raw xml response from AWS
                        // you either save it to a file or to a XML document
                        return new HTTPResponse(...);
                        // if you consumed httpResponse.getContent(), you need to provide new HTTPResponse
                    }
                }
        ).build():
+2

JAXB.marshal, . JAXB ( Java XML) Java / XML .

StringWriter sw = new StringWriter();
JAXB.marshal(instance, sw);
String xmlString = sw.toString();
+1

API AWS rest Java SDK. , Amazon, SDK.

0

Source: https://habr.com/ru/post/1685181/


All Articles