Пример #1
0
 public static Json getReply(Json msg) {
   Json s =
       object(
           ACTIVITY_TYPE, msg.at(ACTIVITY_TYPE),
           CONVERSATION_ID, msg.at(CONVERSATION_ID));
   if (msg.has(PARENT_SCOPE))
     s.set(PARENT_SCOPE, msg.at(PARENT_SCOPE)).set(PARENT_TYPE, msg.at(PARENT_TYPE));
   return msg.has(REPLY_WITH) ? s.set(IN_REPLY_TO, msg.at(REPLY_WITH)) : s;
 }
Пример #2
0
  @Test
  public void testSubscribe() throws Exception {
    // fill the model with data
    SignalKModel model = SignalKModelFactory.getMotuTestInstance();
    model.putAll(TestHelper.getBasicModel().getFullData());

    // create STOMP connection
    StompConnection connection = new StompConnection();
    connection.open("localhost", 61613);
    logger.debug("Opened STOMP socket, connecting.. ");
    StompFrame connect = connection.connect("system", "manager");
    // StompFrame connect = connection.receive();
    if (!connect.getAction().equals(Stomp.Responses.CONNECTED)) {
      throw new Exception("Not connected");
    }
    logger.debug("connected" + connect.getHeaders());

    // create a private receive queue
    String uuid = UUID.randomUUID().toString();
    connection.subscribe(
        "/queue/signalk." + uuid + ".vessels.motu.navigation", Subscribe.AckModeValues.AUTO);

    // subscribe
    Json subMsg =
        getSubscribe(
            "vessels." + SignalKConstants.self, "navigation", 1000, 0, FORMAT_DELTA, POLICY_FIXED);
    subMsg.set(
        nz.co.fortytwo.signalk.util.ConfigConstants.OUTPUT_TYPE,
        nz.co.fortytwo.signalk.util.ConfigConstants.OUTPUT_STOMP);
    subMsg.set(WebsocketConstants.CONNECTION_KEY, uuid);
    HashMap<String, String> headers = new HashMap<String, String>();

    // queue>signalk.3202a939-1681-4a74-ad4b-3a90212e4f33.vessels.motu.navigation
    // set private queue to receive data
    headers.put("reply-to", "/queue/signalk." + uuid + ".vessels.motu.navigation");
    headers.put(WebsocketConstants.CONNECTION_KEY, uuid);
    connection.send("/queue/signalk.put", subMsg.toString(), null, headers);

    // listen for messages
    StompFrame message = connection.receive();
    logger.debug("Body: " + message.getBody());
    assertNotNull(message);
    Json reply = Json.read(message.getBody());

    assertNotNull(reply.at(SignalKConstants.CONTEXT));
    assertNotNull(reply.at(SignalKConstants.UPDATES));
    // unsubscribe
    subMsg =
        getSubscribe(
            "vessels." + SignalKConstants.self, "navigation", 1000, 0, FORMAT_DELTA, POLICY_FIXED);
    connection.send("/queue/signalk.subscribe", subMsg.toString(), null, headers);
    connection.unsubscribe("/queue/signalk." + uuid + ".vessels.motu.navigation");
    // disconnect
    connection.disconnect();
  }
Пример #3
0
 /**
  * Authenticate within a given realm (user provider).
  *
  * @param form
  * @return
  */
 @POST
 @Path("/authenticate")
 public Json authenticate(Json form) {
   if (!form.has("provider") || form.is("provider", ""))
     form.set("provider", desc.at("authenticatesWith").at("hasName"));
   if (form.is("provider", authenticateProvider())) {
     if (!form.has("password") || form.is("password", "")) return ko("Please provide a password.");
     Json userdata = userProfile(form);
     if (userdata.is("error", "No profile")) return ko("User not found or invalid password.");
     else if (!userdata.is("ok", true)) return userdata;
     else if (!StartUp.getConfig().is("ignorePasswords", true)) {
       if (!provider(form.at("provider").asString())
           .authenticate(
               userdata.at("profile").at("hasUsername").asString(),
               form.at("password").asString())) return ko("User not found or invalid password.");
     }
     if (dbg()) {
       String msg =
           (userdata.at("profile").has("hasUsername"))
               ? userdata.at("profile").at("hasUsername").asString()
               : "Unknown";
       msg += " | lastname: " + (userdata.at("profile").at("lastName", " no lastname")).toString();
       msg +=
           "\r\n | groups: "
               + (userdata.at("profile").at("groups", " no groups")).toString()
               + "\r\n";
       ThreadLocalStopwatch.getWatch().time("Auth success: " + msg);
       ThreadLocalStopwatch.dispose();
     }
     return ok().set("user", prepareReturn(userdata.at("profile")));
   }
   // other realms/providers...
   else return ko("Unknown realm");
 }
Пример #4
0
 public Json to(Object x) {
   String typeName =
       shortNameMap.containsX(x.getClass().getName())
           ? shortNameMap.getY(x.getClass().getName())
           : x.getClass().getName();
   Json result = Json.object().set("javaType", typeName);
   if (x instanceof HGLink) {
     result.set("_link", array());
     for (int i = 0; i < ((HGLink) x).getArity(); i++)
       result.at("_link").add(((HGLink) x).getTargetAt(i));
   }
   if (x instanceof Collection) {
     result.set("_collection", array());
     for (Object element : (Collection<?>) x)
       result.at("_collection").add(makeProperty(element));
   }
   if (x instanceof Map) {
     result.set("_map", array());
     for (Map.Entry<?, ?> e : ((Map<?, ?>) x).entrySet())
       result
           .at("_map")
           .add(
               Json.object()
                   .set("key", makeProperty(e.getKey()))
                   .set("value", makeProperty(e.getValue())));
   }
   try {
     if (props != null) // user provided list of properties
     for (String propname : props) {
         PropertyDescriptor desc = BonesOfBeans.getPropertyDescriptor(x, propname);
         Object value = BonesOfBeans.getProperty(x, desc);
         if (!ignoreNulls || value != null) result.set(propname, makeProperty(value));
       }
     else // all introspected properties
     for (PropertyDescriptor desc : BonesOfBeans.getAllPropertyDescriptors(x).values())
         if (desc.getReadMethod() != null && desc.getWriteMethod() != null) {
           Object value = BonesOfBeans.getProperty(x, desc);
           if (!ignoreNulls || value != null) result.set(desc.getName(), makeProperty(value));
         }
     return result;
   } catch (Throwable ex) {
     HGUtils.throwRuntimeException(ex);
   }
   return null; // unreachable
 }
Пример #5
0
 @GET
 @Path("search")
 public Json search(
     @QueryParam("id") String id,
     @QueryParam("name") String searchString,
     @QueryParam("providers") String providers) {
   if (id != null && !id.isEmpty()) {
     return Json.array().add(searchUserById(id));
   }
   Json resultList = Json.array();
   final int maxResults = 15;
   try {
     if (searchString == null || searchString.length() == 0) return null;
     else searchString = searchString.trim();
     Json user = Json.object();
     String name = searchString;
     name = name.trim();
     int idx;
     // Parse search string
     if ((idx = name.indexOf(',')) > -1) { // Miller, Bob
       user.set("LastName", name.substring(0, idx).trim());
       user.set("FirstName", name.substring(idx + 1).trim());
     } else if ((idx = name.indexOf(' ')) > -1) { // Bob Miller
       user.set("LastName", name.substring(idx + 1).trim());
       user.set("FirstName", name.substring(0, idx).trim());
     } else { // Miller
       user.set("LastName", name);
     }
     if (user.is("FirstName", "")) user.delAt("FirstName");
     if (user.is("LastName", "")) user.delAt("LastName");
     if (user.asJsonMap().size() > 0) {
       Collection<String> P =
           providers != null ? Arrays.asList(providers.split(",")) : orderedProviders();
       for (String providerName : P)
         resultList.with(searchProvider(providerName, user, maxResults));
     }
   } catch (Exception e) {
     e.printStackTrace();
     return ko(e);
   }
   return prepareReturn(resultList);
 }
Пример #6
0
 private Json prepareReturn(Json user) {
   if (user.isArray()) {
     for (Json u : user.asJsonList()) prepareReturn(u);
   } else {
     user.delAt("hasPassword");
     // TODO: can we get rid of this? the fear that somewhere on the client
     // it is being used, but it shouldn't be.
     if (user.has("hasUsername")) user.set("username", user.at("hasUsername"));
   }
   return user;
 }
Пример #7
0
 public static Json makeReply(Activity activity, Performative performative, String replyWith) {
   Json s =
       object(
           ACTIVITY_TYPE,
           activity.getType(),
           CONVERSATION_ID,
           activity.getId(),
           PERFORMATIVE,
           performative.toString());
   if (replyWith != null) return s.set(IN_REPLY_TO, replyWith);
   else return s;
 }
Пример #8
0
 /**
  * This is a general method to retrieve information about a particular user. Because it's
  * expensive to fill out all information we can get about a user, the request is a more complex
  * object that specifies what is to be provided. In this way, a client can request all that is
  * needed and only that which is needed in a single network round-trip.
  *
  * <p>The basic profile (first name, email etc.) is returned regardless. Here are the expected
  * properties of the JSON <code>request</code> parameter that control what else is returned:
  *
  * <ul>
  *   <li>username - mandatory...of course
  *   <li>groups - true/false whether to include the list of groups the user belongs to
  *   <li>access - true/false whether to include the access policies for this user
  * </ul>
  *
  * @param request
  * @return
  */
 @POST
 @Path("/profile")
 public Json userProfile(Json request) {
   try {
     if (!request.isObject() || !request.has("username")) return ko("bad request.");
     if (!request.has("provider") || request.is("provider", ""))
       request.set("provider", desc.at("authenticatesWith").at("hasName"));
     UserProvider providerImpl = provider(request.at("provider").asString());
     Json profile = providerImpl.get(request.at("username").asString());
     if (profile.isNull()) return ko("No profile");
     if (request.is("groups", true) || request.is("access", true))
       profile.set("groups", providerImpl.findGroups(request.at("username").asString()));
     if (request.is("access", true))
       profile.set("access", getAccessPolicies(profile.at("groups")));
     return ok().set("profile", prepareReturn(profile));
   } catch (Throwable t) {
     if (!"unavailable"
         .equals(t.getMessage())) // error would have already been reported in the logs
     t.printStackTrace(System.err);
     return ko(t.getMessage());
   }
 }