private JsonObject updateStatus(
      JsonObject notif, HashMap<String, JsonObject> response, JsonObject multicastResult) {
    JsonArray returned = multicastResult.getArray("results");
    JsonArray regIds = notif.getArray("registration_ids");
    // should never happen, unless there is a flaw in gcm algorithm
    if (returned.size() != regIds.size()) {
      throw new RuntimeException(
          "Internal error: sizes do not match. regIds: "
              + regIds.size()
              + "; returned: "
              + returned.size());
    }

    JsonArray reTryRegIds = new JsonArray();
    for (int i = returned.size() - 1; i >= 0; i--) {
      response.put((String) regIds.get(i), (JsonObject) returned.get(i));
      boolean resend = doResubmit((JsonObject) returned.get(i));
      if (resend) {
        reTryRegIds.addString((String) regIds.get(i));
      }
    }
    notif.putArray("registration_ids", reTryRegIds);

    return notif;
  }
 @Override
 public void process(JsonObject object) {
   String[][] classes = createClasses(object.getArray("classes"));
   String[][] groups = createGroups(object.getArray("groups"));
   JsonArray relative = parseRelativeField(object.getArray("relative"));
   importer.createOrUpdateStudent(
       object,
       DefaultProfiles.STUDENT_PROFILE_EXTERNAL_ID,
       null,
       null,
       classes,
       groups,
       relative,
       false,
       true);
 }
 private JsonObject setDefaults(JsonObject config) {
   config = config.copy();
   // Set the defaults
   if (config.getNumber("session_timeout") == null) {
     config.putNumber("session_timeout", 5l * 1000);
   }
   if (config.getBoolean("insert_JSESSIONID") == null) {
     config.putBoolean("insert_JSESSIONID", true);
   }
   if (config.getNumber("heartbeat_period") == null) {
     config.putNumber("heartbeat_period", 25l * 1000);
   }
   if (config.getNumber("max_bytes_streaming") == null) {
     config.putNumber("max_bytes_streaming", 128 * 1024);
   }
   if (config.getString("prefix") == null) {
     config.putString("prefix", "/");
   }
   if (config.getString("library_url") == null) {
     config.putString("library_url", "http://cdn.sockjs.org/sockjs-0.2.1.min.js");
   }
   if (config.getArray("disabled_transports") == null) {
     config.putArray("disabled_transports", new JsonArray());
   }
   return config;
 }
Beispiel #4
0
 private static JsonObject findFirstTrain(JsonObject result) {
   JsonArray trains = result.getArray("trains");
   if (trains != null) {
     Optional<Object> first = stream(trains.spliterator(), false).findFirst();
     if (first.isPresent()) {
       return (JsonObject) first.get();
     }
   }
   return result;
 }
Beispiel #5
0
  @Test
  public void testJsonArrayToClone() {
    JsonArray array = new JsonArray();
    array.add("test");
    JsonObject object = new JsonObject();
    object.putArray("array", array);

    // want to clone
    JsonObject object2 = new JsonObject(object.toMap());
    // this shouldn't throw an exception, it does before patch
    JsonArray array2 = object2.getArray("array");
  }
  @SuppressWarnings("ConstantConditions")
  @Override
  public void handle(Message<JsonObject> message) {
    if (uri == null) {
      sendError(message, "'" + gcm_url + "' is an illegal value for config parameter 'gcm_url'");
      return;
    }

    String apiKey = voidNull(message.body().getString("api_key"));
    if (apiKey.isEmpty()) {
      sendError(message, "Missing mandatory field 'api_key'");
      return;
    }

    JsonObject n = message.body().getObject("notification");
    if (n == null) {
      sendError(message, "Missing mandatory field 'notification'");
      return;
    }

    int ttl = n.getInteger("time_to_live");
    if (ttl > gcm_max_seconds_to_leave) {
      sendError(
          message,
          "Max value of 'time_to_live' exceeded: " + ttl + " > " + gcm_max_seconds_to_leave);
      return;
    }

    JsonArray regIds = n.getArray("registration_ids");
    if (regIds == null || regIds.size() == 0) {
      sendError(message, "Missing mandatory non-empty field 'registration_ids'");
      return;
    }
    if (regIds.size() > gcm_registration_ids_limit) {
      sendError(
          message,
          "Max size of 'registration_ids' exceeded: "
              + regIds.size()
              + " > "
              + gcm_registration_ids_limit);
      return;
    }
    logger.debug("Ready to push notification: " + message.body().encode());
    JsonObject notif = n.copy();

    try {
      send(message, notif, apiKey);
    } catch (Exception e) {
      sendError(message, e.getMessage());
    }
    message.reply("BusMod responded!");
  }
Beispiel #7
0
 public synchronized Object[] addJointure(String externalId) {
   if (struct != null) {
     JsonArray joinKey = struct.getArray("joinKey");
     if (joinKey == null) {
       joinKey = new JsonArray();
       struct.putArray("joinKey", joinKey);
     }
     joinKey.add(externalId);
     String query =
         "MATCH (s:Structure {externalId: {externalId}}) " + "SET s.joinKey = {joinKey} ";
     JsonObject params =
         new JsonObject().putArray("joinKey", joinKey).putString("externalId", getExternalId());
     getTransaction().add(query, params);
     return joinKey.toArray();
   }
   return null;
 }
  @Override
  protected void prepareUser(User user, String userId, JsonObject data) {
    user.setUser(data.getString(principalAttributeName));
    user.setAttributes(new HashMap<String, String>());

    try {
      if (data.getString("lastName") != null && data.getString("firstName") != null) {
        user.getAttributes().put("nom", data.getString("lastName"));
        user.getAttributes().put("prenom", data.getString("firstName"));
      }

      if (data.getString("birthDate") != null) {
        user.getAttributes()
            .put(
                "dateNaissance",
                data.getString("birthDate").replaceAll("([0-9]+)-([0-9]+)-([0-9]+)", "$3/$2/$1"));
      }
      if (data.getString("postalCode") != null) {
        user.getAttributes().put("codePostal", data.getString("postalCode"));
      }

      String category = null;
      JsonArray types = data.getArray("type");
      for (Object type : types.toList()) {
        switch (type.toString()) {
          case "Student":
            category = checkProfile(category, "National_1");
            break;
          case "Teacher":
            category = checkProfile(category, "National_3");
            break;
          case "Relative":
            category = checkProfile(category, "National_2");
            break;
          case "Personnel":
            category = checkProfile(category, "National_4");
            break;
        }
      }
      if (category != null) {
        user.getAttributes().put("categories", category);
      }
    } catch (Exception e) {
      log.error("Failed to transform User for Pronote");
    }
  }
Beispiel #9
0
  public static JsonObject invoke(JsonObject json, String area) {
    JsonObject responseData = json.getObject("ResponseData");

    if (responseData == null) {
      return new JsonObject();
    }

    if (Server.l != null) {
      Server.l.info(getLatestUpdate(json) + " - " + getExecutionTime(json));
    }

    Predicate<String> isJsonArray = name -> responseData.getField(name) instanceof JsonArray;

    Function<String, List<JsonObject>> jsonArrayToList =
        name -> {
          Stream<Object> stream =
              stream(responseData.<JsonArray>getField(name).spliterator(), false);
          Stream<JsonObject> objectStream = stream.filter(getFilterFor(area));
          return objectStream.collect(toList());
        };

    Predicate<Map.Entry<String, List<JsonObject>>> nonEmpty = entry -> !entry.getValue().isEmpty();

    Stream<Map.Entry<String, List<JsonObject>>> entryStream =
        responseData
            .getFieldNames()
            .stream()
            .filter(isJsonArray)
            .collect(toMap(String::toLowerCase, jsonArrayToList))
            .entrySet()
            .stream()
            .filter(nonEmpty);

    JsonObject result = toJsonObject(entryStream);

    setUniqueKeysOn(result.getArray("trains"));
    writeHeaderFields(result);

    return result;
  }
Beispiel #10
0
 public void addAttachment() {
   JsonArray functionalAttachment = struct.getArray("functionalAttachment");
   if (functionalAttachment != null
       && functionalAttachment.size() > 0
       && !externalId.equals(functionalAttachment.get(0))) {
     JsonObject params = new JsonObject().putString("externalId", externalId);
     String query;
     if (functionalAttachment.size() == 1) {
       query =
           "MATCH (s:Structure { externalId : {externalId}}), "
               + "(ps:Structure { externalId : {functionalAttachment}}) "
               + "CREATE UNIQUE s-[:HAS_ATTACHMENT]->ps";
       params.putString("functionalAttachment", (String) functionalAttachment.get(0));
     } else {
       query =
           "MATCH (s:Structure { externalId : {externalId}}), (ps:Structure) "
               + "WHERE ps.externalId IN {functionalAttachment} "
               + "CREATE UNIQUE s-[:HAS_ATTACHMENT]->ps";
       params.putArray("functionalAttachment", functionalAttachment);
     }
     getTransaction().add(query, params);
   }
 }
  public void installApp(JsonObject config, final Handler<SockJSSocket> sockHandler) {

    config = setDefaults(config);

    String prefix = config.getString("prefix");

    if (prefix == null || prefix.equals("") || prefix.endsWith("/")) {
      throw new IllegalArgumentException("Invalid prefix: " + prefix);
    }

    // Base handler for app

    rm.getWithRegEx(
        prefix + "\\/?",
        new Handler<HttpServerRequest>() {
          public void handle(HttpServerRequest req) {
            if (log.isTraceEnabled()) log.trace("Returning welcome response");
            req.response.headers().put("Content-Type", "text/plain; charset=UTF-8");
            req.response.end("Welcome to SockJS!\n");
          }
        });

    // Iframe handlers
    String iframeHTML =
        IFRAME_TEMPLATE.replace("{{ sockjs_url }}", config.getString("library_url"));
    Handler<HttpServerRequest> iframeHandler = createIFrameHandler(iframeHTML);

    // Request exactly for iframe.html
    rm.getWithRegEx(prefix + "\\/iframe\\.html", iframeHandler);

    // Versioned
    rm.getWithRegEx(prefix + "\\/iframe-[^\\/]*\\.html", iframeHandler);

    // Chunking test
    rm.postWithRegEx(prefix + "\\/chunking_test", createChunkingTestHandler());
    rm.optionsWithRegEx(
        prefix + "\\/chunking_test",
        BaseTransport.createCORSOptionsHandler(config, "OPTIONS, POST"));

    // Info
    rm.getWithRegEx(prefix + "\\/info", BaseTransport.createInfoHandler(config));
    rm.optionsWithRegEx(
        prefix + "\\/info", BaseTransport.createCORSOptionsHandler(config, "OPTIONS, GET"));

    // Transports

    Set<String> enabledTransports = new HashSet<>();
    enabledTransports.add(Transport.EVENT_SOURCE.toString());
    enabledTransports.add(Transport.HTML_FILE.toString());
    enabledTransports.add(Transport.JSON_P.toString());
    enabledTransports.add(Transport.WEBSOCKET.toString());
    enabledTransports.add(Transport.XHR.toString());
    for (Object tr : config.getArray("disabled_transports", new JsonArray())) {
      enabledTransports.remove(tr);
    }

    if (enabledTransports.contains(Transport.XHR.toString())) {
      new XhrTransport(vertx, rm, prefix, sessions, config, sockHandler);
    }
    if (enabledTransports.contains(Transport.EVENT_SOURCE.toString())) {
      new EventSourceTransport(vertx, rm, prefix, sessions, config, sockHandler);
    }
    if (enabledTransports.contains(Transport.HTML_FILE.toString())) {
      new HtmlFileTransport(vertx, rm, prefix, sessions, config, sockHandler);
    }
    if (enabledTransports.contains(Transport.JSON_P.toString())) {
      new JsonPTransport(vertx, rm, prefix, sessions, config, sockHandler);
    }
    if (enabledTransports.contains(Transport.WEBSOCKET.toString())) {
      new WebSocketTransport(vertx, wsMatcher, rm, prefix, sessions, config, sockHandler);
      new RawWebSocketTransport(vertx, wsMatcher, rm, prefix, sockHandler);
    }
    // Catch all for any other requests on this app

    rm.getWithRegEx(
        prefix + "\\/.+",
        new Handler<HttpServerRequest>() {
          public void handle(HttpServerRequest req) {
            if (log.isTraceEnabled())
              log.trace("Request: " + req.uri + " does not match, returning 404");
            req.response.statusCode = 404;
            req.response.end();
          }
        });
  }
  private void submitGCM(
      final ResponseHelper helper,
      final JsonObject notif,
      final String apiKey,
      final HttpClient client,
      final Message<JsonObject> message,
      final int attempt) {
    final Buffer toSend;
    try {
      toSend = new Buffer(notif.encode().getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
      logger.error(e.getMessage());
      return;
    }
    logger.debug(
        "Attempt #"
            + (attempt + 1)
            + " to send notification to regIds "
            + notif.getArray("registration_ids").encode());
    HttpClientRequest request =
        client
            .post(
                uri.getPath(),
                new Handler<HttpClientResponse>() {
                  @Override
                  public void handle(final HttpClientResponse resp) {
                    final Buffer body = new Buffer(0);
                    resp.dataHandler(
                        new Handler<Buffer>() {
                          @Override
                          public void handle(Buffer data) {
                            body.appendBuffer(data);
                          }
                        });
                    resp.endHandler(
                        new VoidHandler() {
                          @Override
                          public void handle() {
                            boolean tryAgain = false;
                            JsonObject[] reply = {null};
                            JsonObject newNotif = new JsonObject();
                            int status = resp.statusCode();
                            if (status == 200) {
                              logger.debug("GCM response: " + body);
                              reply[0] = new JsonObject(new String(body.getBytes()));
                            } else {
                              logger.error("GCM error response: " + body);
                            }
                            if (reply[0] != null) {
                              helper.setMulticastId(
                                  reply[0].getLong("multicast_id") == null
                                      ? 0
                                      : reply[0].getLong("multicast_id"));
                              newNotif = updateStatus(notif, helper.getResponse(), reply[0]);
                              tryAgain =
                                  newNotif.getArray("registration_ids").size() != 0
                                      && attempt < gcm_backoff_retries;
                            } else {
                              tryAgain = attempt < gcm_backoff_retries;
                            }
                            if (tryAgain) {
                              int sleepTime =
                                  helper.getBackoff() / 2
                                      + helper.getRandom().nextInt(helper.getBackoff());
                              try {
                                Thread.sleep(sleepTime);
                              } catch (InterruptedException ie) {
                              }
                              if (2 * helper.getBackoff() < gcm_max_backoff_delay) {
                                helper.setBackoff(helper.getBackoff() * 2);
                              }
                              submitGCM(helper, newNotif, apiKey, client, message, attempt + 1);
                            } else {
                              if (helper.getResponse().isEmpty()) {
                                // all JSON posts failed due to GCM unavailability
                                sendError(message, "GCM is unavailable");
                              } else {
                                //                                JsonObject sendBack =
                                // calculateSummary( message.body().getObject( "notification"
                                // ).getArray( "registration_ids" ), helper.getResponse(),
                                // helper.getMulticastId() );
                                JsonObject sendBack =
                                    calculateSummary(
                                        notif.getArray("registration_ids"),
                                        helper.getResponse(),
                                        helper.getMulticastId());
                                sendOK(message, sendBack);
                              }
                            }
                          }
                        });
                  }
                })
            .putHeader("Content-Type", "application/json")
            .putHeader("Content-Length", String.valueOf(toSend.length()))
            .putHeader("Authorization", "key=" + apiKey)
            .write(toSend);

    request.end();
  }