Esempio n. 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;
 }
Esempio n. 2
0
  /**
   * 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);
    }
  }
Esempio n. 3
0
 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());
 }
  @Test
  public void testArreglo() {
    JsonParser parser =
        Json.createParser(
            Thread.currentThread().getContextClassLoader().getResourceAsStream("3.json"));

    assertEquals(JsonParser.Event.START_ARRAY, parser.next());
    assertEquals(JsonParser.Event.START_OBJECT, parser.next());
    assertEquals(JsonParser.Event.KEY_NAME, parser.next());
    assertEquals(JsonParser.Event.VALUE_STRING, parser.next());
    assertEquals(JsonParser.Event.END_OBJECT, parser.next());
    assertEquals(JsonParser.Event.START_OBJECT, parser.next());
    assertEquals(JsonParser.Event.KEY_NAME, parser.next());
    assertEquals(JsonParser.Event.VALUE_STRING, parser.next());
    assertEquals(JsonParser.Event.END_OBJECT, parser.next());
    assertEquals(JsonParser.Event.END_ARRAY, parser.next());
  }
Esempio n. 5
0
  @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();
  }
Esempio n. 6
0
 /** 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 : ");
     }
   }
 }
Esempio n. 7
0
  @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;
  }
  /**
   * 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";
    }
  }