package br.com.ingenieux.picloud;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;
import org.codehaus.jackson.type.TypeReference;
import br.com.ingenieux.picloud.req.CreateVolumeRequest;
import br.com.ingenieux.picloud.req.VolumeSyncArgs;
import br.com.ingenieux.picloud.response.CreateVolumeResponse;
import br.com.ingenieux.picloud.response.Volume;
import com.sun.jersey.api.client.ClientResponse;
public class PiCloudClient extends ClientBase implements PiCloud, PiCloudConstants {
public PiCloudClient(PiCloudCreds creds) {
this.client = getClient(creds);
}
public Collection<String> listServers() {
return handleResponse(resource(SERVERS_LIST), null, new ResponseHandler<Collection<String>>() {
public Collection<String> onResponse(ClientResponse r) throws Exception {
List<String> result = new ArrayList<String>();
ArrayNode arrayNode = (ArrayNode) ((ObjectNode) OBJECT_MAPPER.readTree(r.getEntityInputStream())).get("servers");
for (int i = 0; i < arrayNode.size(); i++) {
result.add(arrayNode.get(i).asText());
}
return result;
}
});
}
public CreateVolumeResponse createVolume(CreateVolumeRequest req) {
return handleResponse(resource(VOLUME_CREATE, HttpMethod.POST), req, new ResponseHandler<CreateVolumeResponse>() {
public CreateVolumeResponse onResponse(ClientResponse r) throws Exception {
return OBJECT_MAPPER.readValue(r.getEntityInputStream(), CreateVolumeResponse.class);
}
});
}
public List<Volume> listVolumes() {
return handleResponse(resource(VOLUME_LIST), new ResponseHandler<List<Volume>>() {
public List<Volume> onResponse(ClientResponse r) throws Exception {
ObjectNode objectNode = (ObjectNode) OBJECT_MAPPER.readTree(r.getEntityInputStream());
String volumeList = OBJECT_MAPPER.writeValueAsString(objectNode.get("volumes"));
return OBJECT_MAPPER.readValue(volumeList, new TypeReference<List<Volume>>() {
});
}
});
}
public void volumeSync(VolumeSyncArgs args) {
ObjectNode syncInitiate = null;
boolean done = false;
do {
syncInitiate = handleResponse(resource(VOLUME_SYNC_INITIATE, HttpMethod.POST), args.getSyncInitiateArgs(), new ResponseHandler<ObjectNode>() {
public ObjectNode onResponse(ClientResponse r) throws Exception {
return ObjectNode.class.cast(OBJECT_MAPPER.readTree(r.getEntityInputStream()));
}
});
done = "ready".equals(syncInitiate.get("status"));
if (! done) {
try {
Thread.sleep(5000);
} catch (Exception exc) {
}
}
} while (! done);
try {
} finally {
syncInitiate.put("name", args.getSyncInitiateArgs().get("name"));
handleResponse(resource(VOLUME_SYNC_TERMINATE, HttpMethod.POST), syncInitiate, new ResponseHandler<Void>() {
public Void onResponse(ClientResponse r) throws Exception {
return null;
}
});
}
}
}