Exemplo n.º 1
0
 private UserProvider provider(String name) {
   synchronized (providerMap) {
     UserProvider provider = providerMap.get(name);
     if (provider != null) return provider;
     if (!desc.at("hasUserBase").has(name)) return null;
     String classname =
         desc.at("hasUserBase")
             .at(name)
             .at("hasImplementation")
             .at("iri")
             .asString()
             .split("#")[1];
     try {
       provider = (UserProvider) Class.forName(classname).newInstance();
       // Autoconfigure is not part of the object initialisation
       // without synchronization, variables set during autoconfigure might not be readable by
       // other threads.
       synchronized (provider) {
         if (provider instanceof AutoConfigurable)
           ((AutoConfigurable) provider).autoConfigure(desc.at("hasUserBase").at(name));
       }
       providerMap.put(name, provider);
       return provider;
     } catch (Exception ex) {
       throw new RuntimeException(ex);
     }
   }
 }
Exemplo n.º 2
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;
 }
Exemplo n.º 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");
 }
Exemplo n.º 4
0
 @Override
 public Json eval(Json r) {
   for (Json doc : r.at("response").at("docs").asJsonList()) {
     List<Json> o = doc.at("ontology").asJsonList();
     for (int i = 0; i < o.size(); i++) {
       if (o.get(i).asString().startsWith("~")) {
         o.remove(i);
       }
     }
   }
   return r;
 }
Exemplo n.º 5
0
 @SuppressWarnings("unchecked")
 public Object from(Json x) {
   Collection<Object> C;
   try {
     C =
         (Collection<Object>)
             HGUtils.loadClass(graph, x.at("javaType").asString()).newInstance();
     for (Json j : x.at("data").asJsonList()) C.add(value(j));
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
   return C;
 }
Exemplo n.º 6
0
 /**
  * Consumes an array of group names and augments those groups with the corresponding access
  * policies.
  *
  * @param groups An array of names of groups.
  * @return
  */
 @POST
 @Path("/accesspolicies")
 public Json accessPolicies(Json groups) {
   groups = getAccessPolicies(groups);
   if (!groups.asList().isEmpty() && groups.at(0).has("hasAccessPolicy"))
     return ok().set("cirmusergroups", groups);
   else return ko("No Access policies are available for user.");
 }
Exemplo n.º 7
0
  @Test
  public void testSendingList() 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);
    latch.await(2, TimeUnit.SECONDS);
    // send list
    Json subMsg = getList("vessels." + SignalKConstants.self, "navigation.position.*");
    HashMap<String, String> headers = new HashMap<String, String>();
    logger.debug("sending" + subMsg);
    // 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.PATHLIST));
    // unsubscribe
    connection.unsubscribe("/queue/signalk." + uuid + ".vessels.motu.navigation");
    // disconnect
    connection.disconnect();
  }
Exemplo n.º 8
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
 }
Exemplo n.º 9
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;
 }
  public void process(Exchange exchange) throws Exception {

    if (exchange.getIn().getBody() == null) return;
    if (logger.isDebugEnabled())
      logger.debug("Processing, class=" + exchange.getIn().getBody().getClass());
    // TODO: add more filters here
    if (exchange.getIn().getBody() instanceof Json) {
      Json json = (Json) exchange.getIn().getBody();
      // remove _arduino
      try {
        json.at(SignalKConstants.vessels).at(SignalKConstants.self).delAt("_arduino");
      } catch (NullPointerException npe) {
      }
      // remove _config
      try {
        json.at(SignalKConstants.vessels).at(SignalKConstants.self).delAt("_config");
      } catch (NullPointerException npe) {
      }

      exchange.getIn().setBody(json.toString());
    }
    if (exchange.getIn().getBody() instanceof SignalKModel) {
      SignalKModel model = (SignalKModel) exchange.getIn().getBody();
      // remove _arduino
      try {
        model.put(SignalKConstants.vessels_dot_self_dot + "_arduino", null);
      } catch (NullPointerException npe) {
      }
      // remove _config
      try {
        model.put(SignalKConstants.vessels_dot_self_dot + "_config", null);
      } catch (NullPointerException npe) {
      }

      exchange.getIn().setBody(ser.write(model));
    }
    if (logger.isDebugEnabled()) {
      logger.debug("Outputting:" + exchange.getIn().getHeaders());
      logger.debug("Outputting:" + exchange.getIn());
    }
  }
Exemplo n.º 11
0
 @SuppressWarnings({"unchecked", "rawtypes"})
 public <T> T value(Json x) {
   if (x == null || x.isNull()) return null;
   else if (x.isPrimitive()) return (T) x.getValue();
   else if (x.isArray())
     // what to do here ... this is some sort of collection??
     return (T) x.getValue();
   else if (x.has("java.lang.Enum")) {
     try {
       return (T)
           Enum.valueOf(
               (Class<Enum>) Class.forName(x.at("java.lang.Enum").asString()),
               x.at("value").asString());
     } catch (Exception t) {
       throw new RuntimeException(t);
     }
   } else if (x.has("javaArrayType")) {
     String fullName = shortNameMap.getX(x.at("javaArrayType").asString());
     if (fullName == null) fullName = x.at("javaArrayType").asString();
     try {
       Class<?> cl = Class.forName(fullName);
       JsonConverter converter = converterMap.get(fullName);
       Object A = Array.newInstance(cl, x.at("array").asJsonList().size());
       for (int i = 0; i < x.at("array").asJsonList().size(); i++) {
         Json j = x.at("array").at(i);
         Array.set(A, i, j.isNull() ? null : converter != null ? converter.from(j) : value(j));
       }
       return (T) A;
     } catch (Exception ex) {
       throw new RuntimeException(ex);
     }
   } else if (x.has("javaType")) {
     String fullName = shortNameMap.getX(x.at("javaType").asString());
     if (fullName == null) fullName = x.at("javaType").asString();
     JsonConverter converter = converterMap.get(fullName);
     if (converter != null)
       return (T) converter.from(converter instanceof BeanJsonConverter ? x : x.at("value"));
     else return (T) beanConverter.from(x); // .at("value"));
   } else return (T) x.getValue();
 }
Exemplo n.º 12
0
 @Test
 public void testCompareEqualsInObject() {
   Json x1 = object("id", 4, "name", "Tom");
   Json x2 = object("id", 4, "name", "Hanna");
   Json a1 = array(object("person", x1));
   Json a2 = array(object("person", x2));
   a1.with(a2, new Json[0]);
   Assert.assertEquals(2, a1.asJsonList().size());
   a1 = array(object("person", x1));
   a1.with(a2, object("compareBy", "id"));
   Assert.assertEquals(1, a1.asJsonList().size());
   Assert.assertEquals(make("Tom"), a1.at(0).at("person").at("name"));
 }
Exemplo n.º 13
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());
   }
 }
Exemplo n.º 14
0
 private List<String> orderedProviders() {
   ArrayList<String> L =
       new ArrayList<String>(desc.at("hasUserBase", Json.object()).asJsonMap().keySet());
   Collections.sort(
       L,
       new Comparator<String>() {
         public int compare(String left, String right) {
           int x = desc.at("hasUserBase").at(left).at("hasOrdinal", Integer.MAX_VALUE).asInteger();
           int y =
               desc.at("hasUserBase").at(right).at("hasOrdinal", Integer.MAX_VALUE).asInteger();
           return x - y;
         }
       });
   return L;
 }
Exemplo n.º 15
0
 @Test
 public void testObjectMerge() {
   Json o1 =
       object(
           "id",
           2,
           "name",
           "John",
           "address",
           object(
               "streetName", "Main",
               "streetNumber", 20,
               "city", "Detroit"));
   Json o2 = o1.dup().set("age", 20).at("address").delAt("city").up();
   o1.with(o2, "merge");
   Assert.assertTrue(o1.is("age", 20));
   Assert.assertTrue(o1.at("address").is("city", "Detroit"));
 }
Exemplo n.º 16
0
 public Json to(Object x) {
   Json result = Json.object().set("javaType", x.getClass().getName()).set("data", array());
   for (Object item : (Collection<?>) x) result.at("data").add(make(item));
   return result;
 }
Exemplo n.º 17
0
    @SuppressWarnings("unchecked")
    public Object from(Json x) {
      if (!x.isObject()) return x.getValue();
      Json typeName = x.at("javaType");
      if ("mjson.Json".equals(typeName)) return x.at("value");
      if (typeName == null) {
        // Not a bean, must be simply a map
        HashMap<String, Object> m = new HashMap<String, Object>();
        for (Map.Entry<String, Json> e : x.asJsonMap().entrySet())
          m.put(e.getKey(), from(e.getValue()));
        return m;
      }
      String fullName = shortNameMap.getX(typeName.asString());
      if (fullName == null) fullName = typeName.asString();

      if (fullName.equals(String.class.getName())) return x.at("value").getValue();
      else if (fullName.equals(Boolean.class.getName())) return x.at("value").getValue();

      try {
        Class<?> beanClass = HGUtils.loadClass(graph, fullName);
        if (Number.class.isAssignableFrom(beanClass)) return castNumber(beanClass, x.at("value"));
        // return beanClass.getConstructor(new
        // Class[]{String.class}).newInstance(x.at("value").getValue().toString());
        else if (Boolean.class.isAssignableFrom(beanClass)) return x.at("value").asBoolean();
        Object bean = null;
        x = x.at("value");
        if (HGLink.class.isAssignableFrom(beanClass) && x.has("_link")) {
          HGHandle[] targets = new HGHandle[x.at("_link").asJsonList().size()];
          for (int i = 0; i < targets.length; i++) targets[i] = value(x.at("_link").at(i));
          bean =
              beanClass
                  .getDeclaredConstructor(new Class[] {HGHandle[].class})
                  .newInstance(new Object[] {targets});
        } else bean = beanClass.newInstance();
        if (x.has("_collection"))
          for (Json element : x.at("_collection").asJsonList())
            ((Collection<Object>) bean).add(value(element));
        if (x.has("_map"))
          for (Json entry : x.at("_map").asJsonList())
            ((Map<Object, Object>) bean).put(value(entry.at("key")), value(entry.at("value")));
        for (Map.Entry<String, Json> entry : x.asJsonMap().entrySet()) {
          PropertyDescriptor descriptor = BonesOfBeans.getPropertyDescriptor(bean, entry.getKey());
          if (descriptor == null) continue;
          Class<?> propertyClass = descriptor.getPropertyType();
          Object value = null;

          if (descriptor instanceof IndexedPropertyDescriptor) {
            int length = entry.getValue().asJsonList().size();
            Object A =
                Array.newInstance(
                    ((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType(), length);
            for (int i = 0; i < length; i++) Array.set(A, i, from(entry.getValue().at(i)));

          } else if (propertyClass.equals(Class.class)) {
            if (entry.getValue().isString())
              value = HGUtils.loadClass(graph, entry.getValue().asString());
            else if (!entry.getValue().isNull())
              value = HGUtils.loadClass(graph, entry.getValue().at("value").asString());
          } else if (entry.getValue().isNumber())
            value = castNumber(propertyClass, entry.getValue());
          else value = value(entry.getValue());
          BonesOfBeans.setProperty(bean, entry.getKey(), value);
        }
        return bean;
      } catch (Exception ex) {
        throw new RuntimeException("Failed to JSON-deserialize bean of type " + fullName, ex);
      }
    }
Exemplo n.º 18
0
 /**
  * Return the network identity of the sender of a given message.
  *
  * @param msg
  * @return
  */
 public static Object getSender(Json msg) {
   return Messages.fromJson(msg.at(Messages.REPLY_TO));
 }
Exemplo n.º 19
0
 private String authenticateProvider() {
   return desc.at("authenticatesWith").at("hasName").asString();
 }
Exemplo n.º 20
0
 public static <T> T content(Json j) {
   return HGPeerJsonFactory.getInstance().value(j.at(CONTENT));
 }
Exemplo n.º 21
0
 public String getFullName(String userid) {
   if (userid == null || userid.isEmpty()) return "";
   Json user = searchUserById(userid);
   if (user.isNull()) return "";
   else return user.at("FirstName", "").asString() + " " + user.at("LastName", "").asString();
 }