Getting Started with Amazon Web Services in NetBeans IDE
자바 IDE인 넷빈즈를 이용하여 아마존 웹 서비스 쉽게 작업하기
When you need to connect to Amazon Web Services, NetBeans IDE gives you a nice start. You can drag and drop the "itemSearch" service into a Java source file and then various Amazon files are generated for you.
From there, you need to do a little bit of work because the request to Amazon needs to be signed before it can be used.
Here are some references and places that got me started:
•http://associates-amazon.s3.amazonaws.com/signed-requests/helper/index.html
•http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSGettingStartedGuide/AWSCredentials.html
•https://affiliate-program.amazon.com/gp/flex/advertising/api/sign-in.html
You definitely need to sign up to the Amazon Associates program and also register/create an Access Key ID, which will also get you a Secret Key, as well.
Here's a simple Main class that I created that hooks into the generated RestConnection/RestResponse code created by NetBeans IDE:
public static void main(String[] args) {
try {
String searchIndex = "Books";
String keywords = "Romeo and Juliet";
RestResponse result = AmazonAssociatesService.itemSearch(searchIndex, keywords);
String dataAsString = result.getDataAsString();
int start = dataAsString.indexOf("<Author>")+8;
int end = dataAsString.indexOf("</Author>");
System.out.println(dataAsString.substring(start,end));
} catch (Exception ex) {
ex.printStackTrace();
}
}
Then I deleted the generated properties file and the authenticator and changed the generated AmazonAssociatesService.java file to the following:
public class AmazonAssociatesService {
private static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (Throwable th) {
}
}
public static RestResponse itemSearch(String searchIndex, String keywords) throws IOException {
SignedRequestsHelper helper;
RestConnection conn = null;
Map queryMap = new HashMap();
queryMap.put("Service", "AWSECommerceService");
queryMap.put("AssociateTag", "myAssociateTag");
queryMap.put("AWSAccessKeyId", "myAccessKeyId");
queryMap.put("Operation", "ItemSearch");
queryMap.put("SearchIndex", searchIndex);
queryMap.put("Keywords", keywords);
try {
helper = SignedRequestsHelper.getInstance(
"ecs.amazonaws.com",
"myAccessKeyId",
"mySecretKey");
String sign = helper.sign(queryMap);
conn = new RestConnection(sign);
} catch (IllegalArgumentException | UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException ex) {
}
sleep(1000);
return conn.get(null);
}
}
Finally, I copied this class into my application, which you can see is referred to above:
Here's the completed app, mostly generated via the drag/drop shown at the start, but slightly edited as shown above:
That's all, now everything works as you'd expect.
** Integrating Amazon S3 in Java via NetBeans IDE
To continue from yesterday, let's set up a scenario that enables us to make use of this drag/drop service in NetBeans IDE:
The above service is applicable to Amazon S3, an Amazon storage provider that is typically used to store large binary files. In Amazon S3, every object stored is contained in a bucket. Buckets partition the namespace of objects stored in Amazon S3. More on buckets here. Let's use the tools in NetBeans IDE to create a Java application that accesses our Amazon S3 buckets.
Create a Java application named "AmazonBuckets" with a main class named "AmazonBuckets". Open the main class and then drag the above service into the main method of the class. Now, NetBeans IDE will create all the other classes and the properties file that you see in the screenshot below.
The first thing to do is to open the properties file above and enter the access key and secret:
access_key=SOMETHING
secret=SOMETHINGELSE
Now you're all set up. Make sure to, of course, actually have some buckets available:
Then rewrite the Java class to parse the XML that is returned via the generated code:
package amazonbuckets;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.netbeans.saas.amazon.AmazonS3Service;
import org.netbeans.saas.RestResponse;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class AmazonBuckets {
public static void main(String[] args) {
try {
RestResponse result = AmazonS3Service.getBuckets();
String dataAsString = result.getDataAsString();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(
new InputSource(new ByteArrayInputStream(dataAsString.getBytes("utf-8"))));
NodeList bucketList = doc.getElementsByTagName("Bucket");
for (int i = 0; i < bucketList.getLength(); i++) {
Node node = bucketList.item(i);
System.out.println("Bucket Name: " + node.getFirstChild().getTextContent());
}
} catch (IOException | ParserConfigurationException | SAXException | DOMException ex) {
}
}
}
That's all. This is simpler to setup than the scenario described yesterday.
Also notice that there are other Amazon S3 services you can interact with from your Java code, again after generating a heap of code after drag/drop into a Java source file:
I tried the above, e.g., I created a new Amazon S3 bucket after dragging "createBucket", adding my credentials in the properties file, and then running the code that had been created. I.e., without adding a single line of code I was able to programmatically create new buckets.
The above outlines a handy set of tools and techniques to use if you want to let your users store and access data in Amazon S3 buckets directly from the application you've created for them.
** Integrating Amazon EC2 in Java via NetBeans IDE
Next, having looked at how to integrate from Java with Amazon Associates and Amazon S3, let's take a look at Amazon EC2, the elastic compute cloud which provides remote computing services. I started by launching an instance of Ubuntu Server 14.04 on Amazon EC2, which looks a bit like this in the on-line AWS Management Console, though I whitened out most of the details:
Now that I have at least one running instance available on Amazon EC2, it makes sense to use the services that are integrated into NetBeans IDE:
I created a new application with one class, named "AmazonEC2Demo". Then I dragged the "describeInstances" service that you see above, with the mouse, into the class. Then the IDE automatically created all the other files you see below, i.e., 4 Java classes and one properties file:
In the properties file, register the access ID and secret keys. These are read by the other generated Java classes. Signing and authentication are done automatically by the code that is generated, i.e., there's nothing generic you need to do and you can immediately begin working on your domain-specific code.
Finally, you're now able to rewrite the code in "AmazonEC2Demo" to connect to Amazon EC2 and obtain information about your running instance:
public class AmazonEC2Demo {
public static void main(String[] args) {
String instanceId1 = "i-something";
RestResponse result;
try {
result = AmazonEC2Service.describeInstances(instanceId1);
System.out.println(result.getDataAsString());
} catch (IOException ex) {
Logger.getLogger(AmazonEC2Demo.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
From the above, you'll receive a chunk of XML with data about the running instance, it's name, status, dates, etc. In other words, you're now ready to integrate Amazon EC2 features directly into the applications you're writing, without very much work to get started. Within about 5 minutes, you're working on your business logic, rather than on the generic code that anyone needs when integrating with Amazon EC2.
'개발' 카테고리의 다른 글
자바 메시지(메시징) 웹소켓 : JMS over WebSocket (0) | 2014.06.20 |
---|---|
자바 JAVA ZIP UNZIP 압축파일 압축, 해제, 풀기, 비밀번호 파일 풀기 등의 소스와 방법 (0) | 2014.06.17 |
자바7 Java SDK JDK7 u60 업데이트 릴리즈 7u60 배포 (0) | 2014.05.30 |
자바 EE8 SSE Server Sent Event 지원 (0) | 2014.05.28 |
오라클 자바FX JavaFX의 씬빌더 SceneBuilder 2.0 발표 (0) | 2014.05.20 |