// parse and set params
    public void setParams(String paramString) {
      if (paramString == null || paramString.isEmpty()) return;
      JsonReader jsonReader = null;
      try {
        jsonReader =
            javax.json.Json.createReader(new java.io.ByteArrayInputStream(paramString.getBytes()));
        JsonObject jsonObject = jsonReader.readObject();
        jsonReader.close();

        String thresholdString = jsonObject.getString("threshold", null);
        if (thresholdString != null && !thresholdString.isEmpty())
          try {
            threshold = Float.parseFloat(thresholdString);
          } catch (Exception ex) {
          }

        JsonArray paramList = jsonObject.getJsonArray("params");
        if (paramList != null) {
          int mlen = paramList.size();
          for (int i = 0; i < mlen; i++) {
            JsonObject mobj = paramList.getJsonObject(i);
            params.put(mobj.getString("name"), mobj.getString("value"));
          }
        }
      } catch (Exception ex) {
        logger.log(Level.WARNING, "Error to parse alert subscription params: " + paramString, ex);
      }
    }
示例#2
0
 /**
  * Parse a json message collection to create a Message
  *
  * @param arg json collection
  * @return Message
  */
 public static Message readMessage(String arg) {
   JsonReader jsonReader = Json.createReader(new StringReader(arg));
   JsonObject msgValues = jsonReader.readObject();
   jsonReader.close();
   if (null == msgValues.getJsonArray(ATTACHMENTS)) {
     return new Message(
         msgValues.getString(ID),
         msgValues.getString(SENDER),
         msgValues.getString(TOPIC),
         msgValues.getJsonNumber(TIMESTAMP).longValue(),
         msgValues.getString(CONTENT));
   } else {
     JsonArray attachmentsJson = msgValues.getJsonArray(ATTACHMENTS);
     Byte[] attachmentByte = new Byte[attachmentsJson.size()];
     for (int i = 0; i < attachmentByte.length; i++) {
       attachmentByte[i] = Byte.valueOf(attachmentsJson.getString(i));
     }
     return new Message(
         msgValues.getString(ID),
         msgValues.getString(SENDER),
         msgValues.getString(TOPIC),
         msgValues.getJsonNumber(TIMESTAMP).longValue(),
         msgValues.getString(CONTENT),
         attachmentByte);
   }
 }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    resp.setCharacterEncoding("UTF-8");
    HttpSession user = req.getSession();
    PrintWriter out = resp.getWriter();
    SpejdResultAnalyser result = null;
    JsonObject response;

    JsonReader jsonReader =
        Json.createReader(new InputStreamReader(req.getInputStream(), StandardCharsets.ISO_8859_1));
    JsonObject jsonObject = jsonReader.readObject();
    jsonReader.close();
    System.out.println("REQUEST");
    System.out.println(jsonObject);
    String originalText = jsonObject.getString("text");
    int space = jsonObject.getInt("space");

    String xml = getXml(originalText, user.getId());
    try {
      result = new SpejdResultAnalyser(xml.replace("SYSTEM \"xcesAnaIPI.dtd\"", ""));
    } catch (ParserConfigurationException | SAXException e) {
      out.println(e.toString());
    }

    assert result != null;
    /** do analysis of xml spejd result */
    SubstantivePairs pairs = result.doAnalysis().makePair(space);

    /**
     * create json response { text: ... xml: ... pairs: [ { subst1: ... subst2: ... quantity: ... },
     * ...] }
     */
    JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
    for (SubstantivePair pair : pairs) {
      arrayBuilder.add(
          Json.createObjectBuilder()
              .add("subst1", pair.getSubst1())
              .add("subst2", pair.getSubst2())
              .add("quantity", pair.getQuantity()));
    }

    Charset.forName("UTF-8").encode(originalText);
    JsonArray array = arrayBuilder.build();
    response =
        Json.createObjectBuilder()
            .add("text", originalText)
            .add("xml", xml)
            .add("pairs", array)
            .build();
    System.out.println("RESPONSE");
    System.out.println(response);
    out.print(response);
  }
  // TODO: unicity of field name, better nested array/object handling
  private void generate(
      final JsonReaderFactory readerFactory,
      final File source,
      final Writer writer,
      final String javaName)
      throws MojoExecutionException {
    JsonReader reader = null;
    try {
      reader = readerFactory.createReader(new FileReader(source));
      final JsonStructure structure = reader.read();
      if (JsonArray.class.isInstance(structure)
          || !JsonObject.class.isInstance(
              structure)) { // quite redundant for now but to avoid surprises in future
        throw new MojoExecutionException(
            "This plugin doesn't support array generation, generate the model (generic) and handle arrays in your code");
      }

      final JsonObject object = JsonObject.class.cast(structure);
      final Collection<String> imports = new TreeSet<String>();

      // while we browse the example tree just store imports as well, avoids a 2 passes processing
      // duplicating imports logic
      final StringWriter memBuffer = new StringWriter();
      generateFieldsAndMethods(memBuffer, object, "    ", imports);

      if (header != null) {
        writer.write(header);
        writer.write('\n');
      }

      writer.write("package " + packageBase + ";\n\n");

      if (!imports.isEmpty()) {
        for (final String imp : imports) {
          writer.write("import " + imp + ";\n");
        }
        writer.write('\n');
      }

      writer.write("public class " + javaName + " {\n");
      writer.write(memBuffer.toString());
      writer.write("}\n");
    } catch (final IOException e) {
      throw new MojoExecutionException(e.getMessage(), e);
    } finally {
      if (reader != null) {
        reader.close();
      }
    }
  }
示例#5
0
  public static boolean verify(String gRecaptchaResponse) throws IOException {
    if (gRecaptchaResponse == null || "".equals(gRecaptchaResponse)) {
      return false;
    }

    try {
      URL obj = new URL(url);
      HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

      // add reuqest header
      con.setRequestMethod("POST");
      con.setRequestProperty("User-Agent", USER_AGENT);
      con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

      String postParams = "secret=" + secret + "&response=" + gRecaptchaResponse;

      // Send post request
      con.setDoOutput(true);
      DataOutputStream wr = new DataOutputStream(con.getOutputStream());
      wr.writeBytes(postParams);
      wr.flush();
      wr.close();

      int responseCode = con.getResponseCode();
      System.out.println("\nSending 'POST' request to URL : " + url);
      System.out.println("Post parameters : " + postParams);
      System.out.println("Response Code : " + responseCode);

      BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
      String inputLine;
      StringBuilder response = new StringBuilder();

      while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
      }
      in.close();

      // print result
      System.out.println(response.toString());

      // parse JSON response and return 'success' value
      JsonReader jsonReader = Json.createReader(new StringReader(response.toString()));
      JsonObject jsonObject = jsonReader.readObject();
      jsonReader.close();

      return jsonObject.getBoolean("success");
    } catch (Exception e) {
      return false;
    }
  }
  // 对接收的(click,mouseover,scroll)数据进行处理,并存入events
  @Path("/events/store")
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.TEXT_PLAIN)
  public void StoreEvents(String data, @Context HttpServletRequest request)
      throws UnsupportedEncodingException, IOException {

    String schema =
        "browser,os,url,ip,loadtime,time,element,id,text,semantics,event,left,top,height,width";
    HashSet<String> hs_log = new HashSet<String>();
    // System.out.println(data);
    // 读取获得的json数据
    JsonReader reader = Json.createReader(new StringReader(data));
    JsonObject jsonobj = reader.readObject();
    reader.close();
    // 获取来源IP,读取url,time,events等信息
    String ip = "";
    String browser = "";
    String os = "";
    String url = "";
    String loadtime = "";
    ip = getRemoteHost(request);
    browser = jsonobj.getString("browser");
    os = jsonobj.getString("os");
    url = jsonobj.getString("url").split("\\?")[0];
    url = url.replace("http://", "").replace("HTTP://", "").replace("https://", "");
    loadtime = jsonobj.getString("loadtime");
    JsonArray events = jsonobj.getJsonArray("events");

    // 整理数据
    for (int i = 0; i < events.size(); i++) {
      JsonObject obj = events.getJsonObject(i);
      StringBuffer elebuf = new StringBuffer();
      // 先存储头信息
      elebuf.append(browser);
      elebuf.append(",");
      elebuf.append(os);
      elebuf.append(",");
      elebuf.append(url);
      elebuf.append(",");
      elebuf.append(ip);
      elebuf.append(",");
      elebuf.append(loadtime);
      elebuf.append(",");
      // 各个事件的信息
      elebuf.append(obj.getString("time"));
      elebuf.append(",");
      elebuf.append(obj.getString("element"));
      elebuf.append(",");
      try {
        elebuf.append(obj.getString("id"));
      } catch (Exception e) {
        elebuf.append("");
      }
      elebuf.append(",");
      elebuf.append(obj.getString("text"));
      elebuf.append(",");
      // 在这里可以引入SVM标注,标注后在存入数据库
      // 或者可以读取数据在标注
      elebuf.append(""); // semantics,标注后更新
      elebuf.append(",");
      elebuf.append(obj.getString("event"));
      elebuf.append(",");
      elebuf.append(obj.getString("left"));
      elebuf.append(",");
      elebuf.append(obj.getString("top"));
      elebuf.append(",");
      elebuf.append(obj.getString("height"));
      elebuf.append(",");
      elebuf.append(obj.getString("width"));
      // 添加set中,去重
      hs_log.add(elebuf.toString());
    }

    eventsDAO.insertEvents(schema, hs_log);
    //  return "Post Data Success!";
  }
  // 对接收的表单数据进行处理,并存入form
  @Path("/form/store")
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.TEXT_PLAIN)
  public void StoreForm(String data, @Context HttpServletRequest request)
      throws UnsupportedEncodingException, IOException {
    String schema = "";
    //  System.out.println(data);
    // 读取获得的json数据
    JsonReader reader = Json.createReader(new StringReader(data));
    JsonObject jsonobj = reader.readObject();
    reader.close();
    // 获取来源IP,读取url,time,events等信息
    String ip = "";
    String browser = "";
    String os = "";
    String url = "";
    String loadtime = "";
    String focusTime = "";
    String blurTime = "";
    String text = "";
    String type = "";
    String id = "";
    String name = "";
    String costTime = "";
    ip = getRemoteHost(request);
    browser = jsonobj.getString("browser");
    os = jsonobj.getString("os");
    url = jsonobj.getString("url").split("\\?")[0];
    url = url.replace("http://", "").replace("HTTP://", "").replace("https://", "");
    loadtime = jsonobj.getString("loadTime");
    focusTime = jsonobj.getString("focusTime");
    blurTime = jsonobj.getString("blurTime");
    text = jsonobj.getString("text");
    type = jsonobj.getString("type");
    id = jsonobj.getString("id");
    name = jsonobj.getString("name");
    costTime = jsonobj.getString("costTime");

    schema = "browser,os,url,loadTime,blurTime,id,name,focusTime,text,type,costTime,ip";
    StringBuffer elebuf = new StringBuffer();
    // 先存储头信息
    elebuf.append(browser);
    elebuf.append(",");
    elebuf.append(os);
    elebuf.append(",");
    elebuf.append(url);
    elebuf.append(",");
    elebuf.append(loadtime);
    elebuf.append(",");
    elebuf.append(blurTime + ",");
    elebuf.append(id + ",");
    elebuf.append(name + ",");
    elebuf.append(focusTime + ",");
    elebuf.append(text + ",");
    elebuf.append(type + ",");
    elebuf.append(costTime + ",");
    elebuf.append(ip);
    formDAO.insertForm(schema, elebuf.toString());
    //  return "Post Data Success!";
  }