В предыдущем посте я показал вам, как создать простой клиент AtomPub с Netbeans 7, Maven, Java и Apache Abdera. Если вы еще не читали эту статью, пожалуйста, сделайте это сейчас, чтобы эта новая статья имела больше смысла. Сегодня я собираюсь взять код из моей предыдущей статьи и немного изменить его, используя Apache Abdera Extensions (в частности, JSON), чтобы преобразовать ATOM XML в JSON.
Получите исходный код из предыдущей статьи и загрузите его в Netbeans 7. Откройте файл POM проекта и добавьте зависимость для расширений Apache Abdera :
<dependency> <groupId>org.apache.abdera</groupId> <artifactId>abdera-extensions-json</artifactId> <version>1.1.2</version> </dependency>
Строки кода, необходимые для использования расширения JSON, просты, мы добавим следующее:
// JSON Output
Writer writer = abdera.getWriterFactory().getWriter("json");
try {
writer.writeTo(docFeed.getRoot(), System.out);
} catch(Exception e) {
System.out.println(e.getMessage());
}
Перейдите в файл App.java и измените его так:
/*
* Original code created by the Apache Abdera team
* http://abdera.apache.org/
*/
package com.giantflyingsaucer.atompubclient;
import java.util.Date;
import org.apache.abdera.Abdera;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.model.Document;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;
import org.apache.abdera.protocol.Response.ResponseType;
import org.apache.abdera.protocol.client.AbderaClient;
import org.apache.abdera.protocol.client.ClientResponse;
import org.apache.abdera.writer.Writer;
public class App {
public static void main(String[] args) throws Exception {
Abdera abdera = new Abdera();
AbderaClient abderaClient = new AbderaClient(abdera);
Factory factory = abdera.getFactory();
Entry entry = factory.newEntry();
entry.setId("tag:example.org,2011:foo");
entry.setTitle("This is the title");
entry.setUpdated(new Date());
entry.addAuthor("Chad");
entry.setContent("Hello World");
report("The Entry to Post", entry.toString());
Document<Entry> doc = abderaClient.post("http://localhost:9002/employee", entry).getDocument();
report("The Created Entry", doc.getRoot().toString());
ClientResponse resp = abderaClient.get("http://localhost:9002/employee");
if (resp.getType() == ResponseType.SUCCESS) {
Document<Feed> docFeed = resp.getDocument();
// JSON Output
Writer writer = abdera.getWriterFactory().getWriter("json");
try {
writer.writeTo(docFeed.getRoot(), System.out);
} catch(Exception e) {
System.out.println(e.getMessage());
}
} else {
// Error
}
}
private static void report(String title, String message) {
System.out.println("== " + title + " ==");
if (message != null)
System.out.println(message);
System.out.println();
}
}
Это все, что нужно сделать. Продолжайте и используйте код из моей другой статьи, где я показал вам, как создать сервер ATOMPub. Запустите сервер ATOMPub, а затем запустите это измененное клиентское приложение, и вы увидите свои результаты в формате JSON.
Полученные результаты:
{
"id":"tag:acme.com,2007:employee:feed",
"title":"Acme Employee Database",
"updated":"2011-09-15T15:38:38.260Z",
"authors":[{
"name":"Acme Industries"
}
],
"links":[{
"href":"http://localhost:9002/employee"
},{
"href":"http://localhost:9002/employee",
"rel":"self"
}
],
"entries":[{
"id":"tag:giantflyingsaucer.com,2011:employee:entry:1000",
"title":"Hello World",
"content":"Hello World",
"authors":[{
"name":"Acme Industries"
}
],
"links":[{
"href":"http://localhost:9002/employee/1000-Hello_World",
"rel":"edit"
}
]
}
]
}