Name: processfetch/AdventureCloudComm.java 
1:
import java.util.ArrayList;
2:
import java.util.HashMap;
3:
import java.util.List;
4:
import java.util.Map;
5:
 
6:
import javax.xml.bind.JAXBException;
7:
 
8:
import org.apache.log4j.Logger;
9:
 
10:
 
11:
import CloudStorageClientLibrary.CloudStorageClient;
12:
import adventure.messagerouting.AdventureMessage;
13:
import adventure.messagerouting.MessageClient;
14:
import adventure.messagerouting.XmppExtensions.HeaderExtension;
15:
import adventure.messagerouting.XmppExtensions.PartExtension;
16:
import adventure.messagerouting.exceptions.MessageRoutingException;
17:
import adventure.messagerouting.interfaces.OnAuthErrorListener;
18:
import adventure.messagerouting.interfaces.OnDisconnectListener;
19:
import adventure.messagerouting.interfaces.OnErrorListener;
20:
import adventure.messagerouting.interfaces.OnHttpMessageListener;
21:
import adventure.messagerouting.interfaces.OnMessageListener;
22:
import org.jbpm.designer.repository.impl.AdventureAsset;
23:
 
24:
public class AdventureCloudComm implements OnMessageListener, OnErrorListener,
25:
    OnAuthErrorListener, OnDisconnectListener {
26:
 
27:
  // Logger
28:
  private static Logger logger = Logger.getLogger(AdventureCloudComm.class);
29:
 
30:
  // Singleton
31:
  protected static AdventureCloudComm cloud;
32:
 
33:
  // Connectors & data
34:
  protected static MessageClient messageClient;
35:
 
36:
  private static final String SERVER = "fp7-adventure.eu";
37:
  private static final String STORAGE = "adventure_cloudstorage";
38:
  private static final String USERNAME = "david";
39:
  private static final String PASSWORD = "TuronBes";
40:
  private static final String RESOURCE = "resource1";
41:
 
42:
  // Buckets
43:
  public static final String BUCKET_PROCESS = "ds-bin";
44:
  public static final String BUCKET_TEMPLATE = "ds-template";
45:
  public static final String BUCKET_DATA = "ds-binaries";
46:
 
47:
  /* ====================================================================== */
48:
  /**
49:
   * WORKING WITH THE CLOUD
50:
   */
51:
 
52:
  /**
53:
   * For creating a new asset
54:
   *
55:
   * @param bucket
56:
   * @param object
57:
   * @return ID of the object
58:
   * @throws MessageRoutingException
59:
   * @throws JAXBException
60:
   * @throws IllegalArgumentException
61:
   */
62:
  protected String create(String bucket, AdventureAsset object)
63:
      throws MessageRoutingException, IllegalArgumentException,
64:
      JAXBException {
65:
 
66:
    String message = CloudStorageClient.generateSimpleNoSqlCreateOperation(
67:
        bucket, object);
68:
 
69:
    String response = cloud.sendMessage(message);
70:
 
71:
    if (CloudStorageClient.errorOccurs(response)) {
72:
      logger.error("Cloud error creating a new file: "
73:
          + CloudStorageClient.getError(response));
74:
      return null;
75:
    } else {
76:
      logger.debug("File created: "
77:
          + CloudStorageClient.getObjectIdentifier(response));
78:
      return CloudStorageClient.getObjectIdentifier(response);
79:
    }
80:
  }
81:
 
82:
  /**
83:
   * For updating one asset
84:
   *
85:
   * @param bucket
86:
   * @param id
87:
   * @return
88:
   * @throws MessageRoutingException
89:
   * @throws IllegalArgumentException
90:
   * @throws JAXBException
91:
   */
92:
  protected boolean update(String bucket, String id, AdventureAsset object)
93:
      throws MessageRoutingException, IllegalArgumentException,
94:
      JAXBException {
95:
 
96:
    String message = CloudStorageClient.generateSimpleNoSqlUpdateOperation(
97:
        bucket, id, object);
98:
 
99:
    String response = cloud.sendMessage(message);
100:
 
101:
    if (CloudStorageClient.errorOccurs(response)) {
102:
      logger.error("Cloud error updating file: "
103:
          + CloudStorageClient.getError(response));
104:
      return false;
105:
    } else {
106:
      logger.debug("File updated: "
107:
          + CloudStorageClient.getObjectIdentifier(response));
108:
      return true;
109:
    }
110:
  }
111:
 
112:
  /**
113:
   * For removing one asset
114:
   *
115:
   * @param bucket
116:
   * @param id
117:
   * @return
118:
   * @throws MessageRoutingException
119:
   * @throws IllegalArgumentException
120:
   * @throws JAXBException
121:
   */
122:
  protected boolean delete(String bucket, String id)
123:
      throws MessageRoutingException, IllegalArgumentException,
124:
      JAXBException {
125:
 
126:
    String message = CloudStorageClient.generateSimpleDeleteOperation(
127:
        bucket, id);
128:
 
129:
    String response = cloud.sendMessage(message);
130:
 
131:
    if (CloudStorageClient.errorOccurs(response)) {
132:
      logger.error("Cloud error deleting a file: "
133:
          + CloudStorageClient.getError(response));
134:
      return false;
135:
    } else {
136:
      logger.debug("File created: "
137:
          + CloudStorageClient.getObjectIdentifier(response));
138:
      return true;
139:
    }
140:
  }
141:
 
142:
  /* ====================================================================== */
143:
  /*
144:
   * READ OPERATIONS
145:
   */
146:
 
147:
  /**
148:
   * Get an object from the bucket
149:
   *
150:
   * @param bucket
151:
   * @param uuid
152:
   * @return
153:
   * @throws MessageRoutingException
154:
   * @throws JAXBException
155:
   */
156:
  protected Object get(String bucket, String uuid, Class<?> type)
157:
      throws MessageRoutingException, JAXBException {
158:
 
159:
    String message = CloudStorageClient.generateSimpleReadOperation(bucket,
160:
        uuid);
161:
 
162:
    String response = cloud.sendMessage(message);
163:
 
164:
    return CloudStorageClient.getNoSqlObject(type, response);
165:
  }
166:
 
167:
  /**
168:
   * List the bucket's assets with the criteria specified by the asset
169:
   *
170:
   * @param bucket
171:
   * @param asset
172:
   * @return
173:
   * @throws MessageRoutingException
174:
   * @throws JAXBException
175:
   */
176:
  protected List<AdventureAsset> search(String bucket, AdventureAsset asset)
177:
      throws MessageRoutingException, JAXBException {
178:
 
179:
    // Security check (if makes this op. the server freezes OutOfMemory)
180:
    if (bucket.equals(BUCKET_DATA))
181:
      throw new MessageRoutingException(
182:
          "List operations are forbidden in this bucket");
183:
 
184:
    String message = CloudStorageClient.generateSimpleNoSqlReadOperation(
185:
        bucket, asset);
186:
 
187:
    String response = cloud.sendMessage(message);
188:
 
189:
    List<AdventureAsset> list = CloudStorageClient.getNoSqlObjectList(
190:
        AdventureAsset.class, response);
191:
 
192:
    return list;
193:
  }
194:
 
195:
  /**
196:
   * List the bucket's assets
197:
   *
198:
   * @param bucket
199:
   *            name
200:
   * @return List of AdventureAsset s
201:
   * @throws JAXBException
202:
   * @throws MessageRoutingException
203:
   */
204:
  protected List<AdventureAsset> list(String bucket) throws JAXBException,
205:
      MessageRoutingException {
206:
 
207:
    // Security check (if makes this op. the server freezes OutOfMemory)
208:
    if (bucket.equals(BUCKET_DATA))
209:
      throw new MessageRoutingException(
210:
          "List operations are forbidden in this bucket");
211:
 
212:
    String message = CloudStorageClient
213:
        .generateSimpleReadAllOperation(bucket);
214:
 
215:
    String response = cloud.sendMessage(message);
216:
 
217:
    List<AdventureAsset> list = CloudStorageClient.getNoSqlObjectList(
218:
        AdventureAsset.class, response);
219:
 
220:
    return list;
221:
  }
222:
 
223:
  /* ====================================================================== */
224:
  /*
225:
   * SOME TESTS
226:
   */
227:
 
228:
  // Test main
229:
  public static void main(String[] args) {
230:
 
231:
    try {
232:
      System.out.println("Testing Adventure Cloud Communication:\n");
233:
 
234:
      System.out.println("Connection:");
235:
      AdventureCloudComm cs = AdventureCloudComm.getInstance();
236:
 
237:
      System.out.println("\nList assets:");
238:
 
239:
      List<AdventureAsset> listProcesses = cs.list(BUCKET_PROCESS);
240:
      int totalProcesses = (listProcesses != null ? listProcesses.size()
241:
          : 0);
242:
      System.out.println("\t> Total of processes: " + totalProcesses);
243:
 
244:
      System.out.println("\nSearch criteria:");
245:
 
246:
      AdventureAsset asset = new AdventureAsset();
247:
      AdventureAsset search = new AdventureAsset();
248:
      search.setAdventureStatus("draft");
249:
 
250:
      List<AdventureAsset> listCriteria = cs.search(BUCKET_PROCESS,
251:
          search);
252:
      int totalCriteria = (listCriteria != null ? listCriteria.size() : 0);
253:
      System.out.println("\t> Total for criteria: " + totalCriteria);
254:
 
255:
      System.out.println("\nCreating 2 new assets:");
256:
      asset = new AdventureAsset();
257:
      asset.setAdventureName("Adventure asset test 1");
258:
      asset.setAdventureStatus("draft");
259:
      String id1 = cs.create(BUCKET_PROCESS, asset);
260:
      System.out.println("\t> Asset 1: " + id1);
261:
 
262:
      asset.setAdventureName("Adventure asset test 2");
263:
      asset.setAdventureStatus("draft");
264:
      String id2 = cs.create(BUCKET_PROCESS, asset);
265:
      System.out.println("\t> Asset 2: " + id2);
266:
 
267:
      listProcesses = cs.list(BUCKET_PROCESS);
268:
      totalProcesses = (listProcesses != null ? listProcesses.size() : 0);
269:
      System.out.println("\t> Total of processes: " + totalProcesses);
270:
 
271:
      listCriteria = cs.search(BUCKET_PROCESS, search);
272:
      totalCriteria = (listCriteria != null ? listCriteria.size() : 0);
273:
      System.out.println("\t> Total for criteria: " + totalCriteria);
274:
 
275:
      try {
276:
        System.out.println("\nUpdating 1 asset:");
277:
        AdventureAsset loaded = (AdventureAsset) cs.get(BUCKET_PROCESS,
278:
            id2, AdventureAsset.class);
279:
        System.out.println("\t> Loaded asset: " + loaded.getId()
280:
            + " / status: " + loaded.getAdventureStatus());
281:
 
282:
        loaded.setAdventureStatus("ready");
283:
        boolean updated = cs.update(BUCKET_PROCESS, id2, loaded);
284:
        System.out.println("\t> Updated     : " + updated);
285:
 
286:
        listProcesses = cs.list(BUCKET_PROCESS);
287:
        totalProcesses = (listProcesses != null ? listProcesses.size()
288:
            : 0);
289:
        System.out.println("\t> Total of processes: " + totalProcesses);
290:
 
291:
        listCriteria = cs.search(BUCKET_PROCESS, search);
292:
        totalCriteria = (listCriteria != null ? listCriteria.size() : 0);
293:
        System.out.println("\t> Total for criteria: " + totalCriteria);
294:
 
295:
        loaded = (AdventureAsset) cs.get(BUCKET_PROCESS, id2,
296:
            AdventureAsset.class);
297:
        System.out.println("\t> Loaded asset: " + loaded.getId()
298:
            + " / status: " + loaded.getAdventureStatus());
299:
 
300:
        loaded.setAdventureStatus("draft");
301:
        updated = cs.update(BUCKET_PROCESS, id2, loaded);
302:
        System.out.println("\t> Restored   : " + updated);
303:
      } catch (Exception ex) {
304:
        logger.error(ex);
305:
        ex.printStackTrace();
306:
      }
307:
 
308:
      System.out.println("\nRemoving 2 new assets:");
309:
      cs.delete(BUCKET_PROCESS, id1);
310:
      cs.delete(BUCKET_PROCESS, id2);
311:
 
312:
      listProcesses = cs.list(BUCKET_PROCESS);
313:
      totalProcesses = (listProcesses != null ? listProcesses.size() : 0);
314:
      System.out.println("\t> Total of processes: " + totalProcesses);
315:
 
316:
      listCriteria = cs.search(BUCKET_PROCESS, search);
317:
      totalCriteria = (listCriteria != null ? listCriteria.size() : 0);
318:
      System.out.println("\t> Total for criteria: " + totalCriteria);
319:
 
320:
      System.out.println("\nDisconnecting...");
321:
      cs.disconnect();
322:
 
323:
    } catch (Exception e) {
324:
      // TODO Auto-generated catch block
325:
      e.printStackTrace();
326:
    }
327:
 
328:
  }
329:
 
330:
  /* ====================================================================== */
331:
  /**
332:
   * INTERNAL METHODS
333:
   */
334:
 
335:
  // Singleton
336:
  protected AdventureCloudComm() {
337:
  }
338:
 
339:
  // Initialize connection
340:
  protected void init() {
341:
    if (messageClient == null) {
342:
      messageClient = new MessageClient(USERNAME, PASSWORD, SERVER,
343:
          RESOURCE);
344:
      messageClient.AddOnMessageEventListener(this);
345:
      messageClient.AddOnErrorEventListener(this);
346:
      messageClient.AddOnAuthErrorEventListener(this);
347:
      messageClient.AddOnDisconnectEventListener(this);
348:
      
349:
      String proxyHost = null;
350:
      String proxyPort = null;
351:
 
352:
      // proxy host/port can be set as JVM system properties or using the
353:
      // profiles/<profile>.xml <repository> properties configuration
354:
      if ((proxyHost = System.getProperty("http.proxy.host")) != null
355:
          && (proxyPort = System.getProperty("http.proxy.port")) != null) {
356:
        messageClient.SetProxyBeforeLogin(proxyHost, proxyPort, null,
357:
            null);
358:
      }
359:
      messageClient.login();
360:
    }
361:
  }
362:
 
363:
  // Instance of the communication module
364:
  protected static AdventureCloudComm getInstance() {
365:
    if (cloud == null) {
366:
      cloud = new AdventureCloudComm();
367:
      cloud.init();
368:
    } else {
369:
      if (!messageClient.getWrappedConnection().isConnected()) {
370:
        messageClient.login();
371:
 
372:
      }
373:
    }
374:
 
375:
    return cloud;
376:
  }
377:
 
378:
  /**
379:
   * Sends a synchronized message to the cloud
380:
   *
381:
   * @param message
382:
   * @return response from the cloud
383:
   * @throws MessageRoutingException
384:
   */
385:
  private String sendMessage(String message) throws MessageRoutingException {
386:
 
387:
    if (!messageClient.getWrappedConnection().isConnected()) {
388:
      messageClient.login();
389:
    }
390:
 
391:
    // You can send a synchronous message, which returns the answer
392:
    AdventureMessage arg0 = messageClient.sendMessageSync(20000, message,
393:
        STORAGE + "@" + SERVER);
394:
 
395:
    int length = arg0.getMessageBody().getBytes().length;
396:
 
397:
    if (length > 1048576) {
398:
      logger.warn("Response from SERVER: "
399:
          + Double.toString(length / 1048576) + " Mb (" + length
400:
          + " bytes)");
401:
    } else if (length > 1024) {
402:
      logger.debug("Response from SERVER: "
403:
          + Double.toString(length / 1024) + " Kb (" + length
404:
          + " bytes)");
405:
    } else {
406:
      logger.debug("Response from SERVER: " + length + " bytes");
407:
    }
408:
 
409:
    return arg0.getMessageBody();
410:
 
411:
  }
412:
 
413:
  // Other control methods
414:
  protected void disconnect() {
415:
    messageClient.Disconnect();
416:
  }
417:
 
418:
  public void OnDisconnect() {
419:
    System.out.println("Disconnected from the cloud");
420:
    logger.warn("Disconnected!");
421:
  }
422:
 
423:
  public void OnAuthError(Exception arg0) {
424:
    logger.error(arg0.getStackTrace().toString(), arg0);
425:
  }
426:
 
427:
  public void OnError(Exception arg0) {
428:
  }
429:
 
430:
  public void OnMessage(AdventureMessage arg0) {
431:
  }
432:
 
433:
  
434:
}