Exemple #1
1
 @Override
 public Movie readFrom(
     Class<Movie> type,
     Type type1,
     Annotation[] antns,
     MediaType mt,
     MultivaluedMap<String, String> mm,
     InputStream in)
     throws IOException, WebApplicationException {
   Movie movie = new Movie();
   JsonParser parser = Json.createParser(in);
   while (parser.hasNext()) {
     switch (parser.next()) {
       case KEY_NAME:
         String key = parser.getString();
         parser.next();
         switch (key) {
           case "id":
             movie.setId(parser.getInt());
             break;
           case "name":
             movie.setName(parser.getString());
             break;
           case "actors":
             movie.setActors(parser.getString());
             break;
           default:
             break;
         }
         break;
       default:
         break;
     }
   }
   return movie;
 }
  /**
   * Populates query tags list from given JSON string. All unknown tags are ignored.
   *
   * @param jsonData the string with JSON data
   * @throws Exception if JSON creation error occurs
   */
  public void populateFromJson(String jsonData) throws TagsListParsingException {
    try (JsonParser parser = Json.createParser(new StringReader(jsonData))) {
      String key = null;
      while (parser.hasNext()) {
        JsonParser.Event event = parser.next();
        switch (event) {
          case KEY_NAME:
            key = parser.getString();
            break;

          case VALUE_NUMBER:
            tags.add(new QueryTag(key, parser.getInt()));
            break;

          case START_OBJECT:
          case END_OBJECT:
            break;

          default:
            logger.log(Level.SEVERE, "Unsupported tag passed in JSON string: " + jsonData);
            break;
        }
      }
    } catch (Exception e) {
      logger.log(Level.SEVERE, "Error happen while parsing JSON string: " + jsonData, e);
      throw new TagsListParsingException("Unable to decode tags list from URL", e);
    }
  }
 public Event get(Event... events) {
   Event event = parser.next();
   if (event == Event.KEY_NAME || event == Event.VALUE_STRING) {
     logger.debug(event + ": " + parser.getString());
   } else {
     logger.debug(event);
   }
   for (Event e : events) {
     if (event == e) {
       return event;
     }
   }
   StringBuilder sb = new StringBuilder("event " + event + " is not of expected type [");
   boolean first = true;
   for (Event e : events) {
     if (!first) {
       sb.append(", ");
     } else {
       first = false;
     }
     sb.append(e);
   }
   sb.append(']');
   throw new JsonException(sb.toString());
 }
  @POST
  @Path("entityManager")
  @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  @Produces(MediaType.APPLICATION_JSON)
  public String create(@FormParam("sessionId") String sessionId, @FormParam("entities") String json)
      throws IcatException {
    List<EntityBaseBean> entities = new ArrayList<>();

    try (JsonParser parser = Json.createParser(new ByteArrayInputStream(json.getBytes()))) {
      EventChecker checker = new EventChecker(parser);
      checker.get(Event.START_ARRAY);
      while (true) {
        Event event = checker.get(Event.START_OBJECT, Event.END_ARRAY);
        if (event == Event.END_ARRAY) {
          break;
        }
        checker.get(Event.KEY_NAME);
        String entityName = parser.getString();
        checker.get(Event.START_OBJECT);
        entities.add(parseEntity(checker, entityName));
        checker.get(Event.END_OBJECT);
      }
    } catch (JsonException e) {
      throw new IcatException(IcatExceptionType.INTERNAL, e.getMessage());
    }
    String userName = beanManager.getUserName(sessionId, manager);

    List<CreateResponse> createResponses =
        beanManager.createMany(userName, entities, manager, userTransaction);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (JsonGenerator gen = Json.createGenerator(baos)) {
      gen.writeStartArray();
      for (CreateResponse createResponse : createResponses) {
        transmitter.processMessage(createResponse.getNotificationMessage());
        gen.write(createResponse.getPk());
      }
      gen.writeEnd();
    } catch (JMSException e) {
      throw new IcatException(
          IcatException.IcatExceptionType.INTERNAL, e.getClass() + " " + e.getMessage());
    }
    return baos.toString();
  }
  @Override
  public boolean didReceiveData(InputStream inputStream) {

    JsonParser parser = Json.createParser(inputStream);

    while (parser.hasNext()) {
      JsonParser.Event event = parser.next();
      switch (event) {
        case KEY_NAME:
          System.out.println("Key  =" + parser.getString());
          break;
        case VALUE_STRING:
          System.out.println("Value=" + parser.getString());
          break;
        default:
          break;
      }
    }

    return true;
  }
  @Test
  public void testObjetoSimple() {
    JsonParser parser =
        Json.createParser(
            Thread.currentThread().getContextClassLoader().getResourceAsStream("2.json"));

    assertEquals(JsonParser.Event.START_OBJECT, parser.next());
    assertEquals(JsonParser.Event.KEY_NAME, parser.next());
    assertEquals(JsonParser.Event.VALUE_STRING, parser.next());
    assertEquals(JsonParser.Event.KEY_NAME, parser.next());
    assertEquals(JsonParser.Event.VALUE_STRING, parser.next());
    assertEquals(JsonParser.Event.END_OBJECT, parser.next());
  }
  @POST
  @Path("session")
  @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  @Produces(MediaType.APPLICATION_JSON)
  public String login(@Context HttpServletRequest request, @FormParam("json") String jsonString)
      throws IcatException {
    logger.debug(jsonString);
    if (jsonString == null) {
      throw new IcatException(IcatExceptionType.BAD_PARAMETER, "json must not be null");
    }
    String plugin = null;
    Map<String, String> credentials = new HashMap<>();
    try (JsonParser parser = Json.createParser(new ByteArrayInputStream(jsonString.getBytes()))) {
      String key = null;
      boolean inCredentials = false;

      while (parser.hasNext()) {
        JsonParser.Event event = parser.next();
        if (event == Event.KEY_NAME) {
          key = parser.getString();
        } else if (event == Event.VALUE_STRING) {
          if (inCredentials) {
            credentials.put(key, parser.getString());
          } else {
            if (key.equals("plugin")) {
              plugin = parser.getString();
            }
          }
        } else if (event == Event.START_ARRAY && key.equals("credentials")) {
          inCredentials = true;
        } else if (event == Event.END_ARRAY) {
          inCredentials = false;
        }
      }
    }

    Authenticator authenticator = authPlugins.get(plugin);
    if (authenticator == null) {
      throw new IcatException(
          IcatException.IcatExceptionType.SESSION,
          "Authenticator mnemonic " + plugin + " not recognised");
    }
    logger.debug("Using " + plugin + " to authenticate");

    String userName =
        authenticator.authenticate(credentials, request.getRemoteAddr()).getUserName();
    String sessionId = beanManager.login(userName, lifetimeMinutes, manager, userTransaction);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JsonGenerator gen = Json.createGenerator(baos);
    gen.writeStartObject().write("sessionId", sessionId).writeEnd();
    gen.close();
    return baos.toString();
  }
 /** main */
 public static void main(String[] args) {
   String personJSONData =
       "  {"
           + "       \"name\": \"John\", "
           + "       \"age\" : 35, "
           + "       \"isMarried\" : true, "
           + "       \"email\": null, "
           + "       \"address\": { "
           + "           \"street\": \"#234, Pembroke Road\", "
           + "           \"city\": \"Dublin\", "
           + "           \"zipCode\": \"D4\" "
           + "       }, "
           + "       \"phoneNumbers\": [\"89-923-2342\", \"89-213-2364\"] "
           + "   }";
   JsonParser parser = Json.createParser(new StringReader(personJSONData));
   while (parser.hasNext()) {
     Event event = parser.next();
     switch (event) {
       case START_OBJECT:
         System.out.print("{/*" + event + "*/ ");
         break;
       case END_OBJECT:
         System.out.print("}/*" + event + "*/ ");
         break;
       case START_ARRAY:
         System.out.print("[/*" + event + "*/ ");
         break;
       case END_ARRAY:
         System.out.print("]/*" + event + "*/ ");
         break;
       case VALUE_NUMBER:
         System.out.print(parser.getInt() + "/*" + event + "*/, ");
         break;
       case VALUE_STRING:
         System.out.print(parser.getString() + "/*" + event + "*/, ");
         break;
       case VALUE_TRUE:
         System.out.print("true/*" + event + "*/, ");
         break;
       case VALUE_FALSE:
         System.out.print("false/*" + event + "*/, ");
         break;
       case VALUE_NULL:
         System.out.print("null/*" + event + "*/, ");
         break;
       case KEY_NAME:
         System.out.print(parser.getString() + "/*" + event + "*/: ");
         break;
       default:
         System.out.print("Unrecognized Event : ");
     }
   }
 }
  /**
   * PUT method for updating or creating an instance of ProductResource
   *
   * @param content representation for the resource
   * @return an HTTP response with content of the updated or created resource.
   */
  @PUT
  @Path("{id}")
  @Consumes(MediaType.APPLICATION_JSON)
  public String putProduct(@PathParam("id") int id, String str) throws SQLException {
    JsonParser parser = Json.createParser(new StringReader(str));
    Map<String, String> productMap = new LinkedHashMap<String, String>();
    String key = "";
    String val = "";

    while (parser.hasNext()) {
      JsonParser.Event event = parser.next();
      switch (event) {
        case KEY_NAME:
          key = parser.getString();
          break;
        case VALUE_STRING:
          val = parser.getString();
          productMap.put(key, val);
          break;
        case VALUE_NUMBER:
          val = parser.getString();
          productMap.put(key, val);
          break;
        default:
          break;
      }
    }
    if (conn == null) {
      return "Not connected";
    } else {
      String query =
          "UPDATE products SET  name = ?, SET decription = ?, SET quantity = ? WHERE id = ? ";
      PreparedStatement pstmt = conn.prepareStatement(query);
      pstmt.setInt(4, id);
      pstmt.setNString(1, productMap.get("name"));
      pstmt.setNString(2, productMap.get("description"));
      pstmt.setNString(3, productMap.get("quantity"));
      return "row has been updated into the database";
    }
  }
  @POST
  @Path("/products")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.TEXT_PLAIN)
  public String postProduct(String str) throws SQLException {
    JsonParser parser = Json.createParser(new StringReader(str));
    Map<String, String> productMap = new LinkedHashMap<String, String>();
    String key = "";
    String val = "";

    while (parser.hasNext()) {
      JsonParser.Event event = parser.next();
      switch (event) {
        case KEY_NAME:
          key = parser.getString();
          break;
        case VALUE_STRING:
          val = parser.getString();
          productMap.put(key, val);
          break;
        case VALUE_NUMBER:
          val = parser.getString();
          productMap.put(key, val);
          break;
        default:
          break;
      }
    }
    if (conn == null) {
      return "Not connected";
    } else {
      String query = "INSERT INTO products (name,decription,quantity) VALUES (?,?,?)";
      PreparedStatement pstmt = conn.prepareStatement(query);
      pstmt.setNString(1, productMap.get("product_id"));
      pstmt.setNString(2, productMap.get("name"));
      pstmt.setNString(3, productMap.get("description"));
      pstmt.setNString(4, productMap.get("quantity"));
      return "row has been inserted into the database";
    }
  }
  @Test
  public void testEstructuraCompuesta() {
    JsonParser parser =
        Json.createParser(
            Thread.currentThread().getContextClassLoader().getResourceAsStream("4.json"));

    assertEquals(JsonParser.Event.START_OBJECT, parser.next());
    assertEquals(JsonParser.Event.KEY_NAME, parser.next());
    assertEquals(JsonParser.Event.VALUE_STRING, parser.next());
    assertEquals(JsonParser.Event.KEY_NAME, parser.next());
    assertEquals(JsonParser.Event.VALUE_NUMBER, parser.next());
    assertEquals(JsonParser.Event.KEY_NAME, parser.next());
    assertEquals(JsonParser.Event.START_ARRAY, parser.next());
    assertEquals(JsonParser.Event.VALUE_STRING, parser.next());
    assertEquals(JsonParser.Event.VALUE_STRING, parser.next());
    assertEquals(JsonParser.Event.VALUE_STRING, parser.next());
    assertEquals(JsonParser.Event.END_ARRAY, parser.next());
    assertEquals(JsonParser.Event.END_OBJECT, parser.next());
  }
 // Note that the START_OBJECT has already been swallowed
 private EntityBaseBean parseEntity(EventChecker checker, String beanName) throws IcatException {
   Class<EntityBaseBean> klass = EntityInfoHandler.getClass(beanName);
   Map<Field, Method> getters = eiHandler.getGetters(klass);
   Map<Field, Method> setters = eiHandler.getSetters(klass);
   Set<Field> atts = eiHandler.getAttributes(klass);
   Set<Field> updaters = eiHandler.getSettersForUpdate(klass).keySet();
   Map<String, Field> fieldsByName = eiHandler.getFieldsByName(klass);
   EntityBaseBean bean = null;
   JsonParser parser = checker.parser;
   try {
     bean = klass.newInstance();
     while (true) {
       Event event = checker.get(Event.KEY_NAME, Event.END_OBJECT);
       if (event == Event.END_OBJECT) {
         break;
       }
       Field field = fieldsByName.get(parser.getString());
       if (field == null) {
         throw new IcatException(
             IcatExceptionType.BAD_PARAMETER,
             "Field " + parser.getString() + " not found in " + beanName);
       } else if (field.getName().equals("id")) {
         checker.get(Event.VALUE_NUMBER);
         bean.setId(Long.parseLong(parser.getString()));
       } else if (atts.contains(field)) {
         checker.get(Event.VALUE_NUMBER, Event.VALUE_STRING);
         String type = field.getType().getSimpleName();
         Object arg;
         if (type.equals("String")) {
           arg = parser.getString();
         } else if (type.equals("Integer")) {
           arg = Integer.parseInt(parser.getString());
         } else if (type.equals("Double")) {
           arg = Double.parseDouble(parser.getString());
         } else if (type.equals("Long")) {
           arg = Long.parseLong(parser.getString());
         } else if (type.equals("boolean")) {
           arg = Boolean.parseBoolean(parser.getString());
           // } else if (field.getType().isEnum()) {
           // arg =
           // gen.write(field.getName(), value.toString());
         } else if (type.equals("Date")) {
           synchronized (df8601) {
             try {
               arg = df8601.parse(parser.getString());
             } catch (ParseException e) {
               throw new IcatException(
                   IcatExceptionType.BAD_PARAMETER, "Badly formatted date " + parser.getString());
             }
           }
         } else {
           throw new IcatException(
               IcatExceptionType.BAD_PARAMETER,
               "Don't know how to parseEntity field of type " + type);
         }
         setters.get(field).invoke(bean, arg);
       } else if (updaters.contains(field)) {
         event = checker.get(Event.START_OBJECT);
         EntityBaseBean arg = parseEntity(checker, field.getType().getSimpleName());
         setters.get(field).invoke(bean, arg);
       } else {
         checker.get(Event.START_ARRAY);
         @SuppressWarnings("unchecked")
         List<EntityBaseBean> col = (List<EntityBaseBean>) getters.get(field).invoke(bean);
         while (true) {
           event = checker.get(Event.START_OBJECT, Event.END_ARRAY);
           if (event == Event.END_ARRAY) {
             break;
           }
           EntityBaseBean arg = parseEntity(checker, field.getName());
           col.add(arg);
         }
       }
     }
   } catch (InstantiationException
       | IllegalAccessException
       | IllegalArgumentException
       | InvocationTargetException
       | JsonException e) {
     throw new IcatException(
         IcatExceptionType.BAD_PARAMETER,
         e.getClass()
             + " "
             + e.getMessage()
             + " at "
             + parser.getLocation().getStreamOffset()
             + " in json");
   }
   return bean;
 }