Beispiel #1
0
 private String convertTupleToJsonString(Object[] tuple) {
   Timestamp ts = new Timestamp(((Long) tuple[0]).longValue());
   tuple[0] = ts.toString();
   JSONArray jsonArray = new JSONArray();
   jsonArray.addAll(Arrays.asList(tuple));
   return jsonArray.toString();
 }
Beispiel #2
0
  @Test
  public void DecodingJsonText() throws ParseException {
    System.out.println("=======decode=======");

    String s = "[0,{'1':{'2':{'3':{'4':[5,{'6':7}]}}}}]";
    Object obj = JSONValue.parse(s);
    JSONArray array = (JSONArray) obj;
    System.out.println("======the 2nd element of array======");
    System.out.println(array.get(1));
    System.out.println();

    JSONObject obj2 = (JSONObject) array.get(1);
    System.out.println("======field \"1\"==========");
    System.out.println(obj2.get("1"));

    s = "{}";
    obj = JSONValue.parse(s);
    System.out.println(obj);

    s = "{\"key\":\"Value\"}";
    // JSONValue.parseStrict()
    // can be use to be sure that the input is wellformed
    obj = JSONValue.parseStrict(s);
    JSONObject obj3 = (JSONObject) obj;
    System.out.println("====== Object content ======");
    System.out.println(obj3.get("key"));
    System.out.println();
  }
  protected void buildClaimMappings(
      Map<ClaimMapping, String> claims, Map.Entry<String, Object> entry, String separator) {
    String claimValue = null;
    if (StringUtils.isBlank(separator)) {
      separator = IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR_DEFAULT;
    }
    try {
      JSONArray jsonArray = (JSONArray) JSONValue.parseWithException(entry.getValue().toString());
      if (jsonArray != null && jsonArray.size() > 0) {
        Iterator attributeIterator = jsonArray.iterator();
        while (attributeIterator.hasNext()) {
          if (claimValue == null) {
            claimValue = attributeIterator.next().toString();
          } else {
            claimValue = claimValue + separator + attributeIterator.next().toString();
          }
        }
      }
    } catch (Exception e) {
      claimValue = entry.getValue().toString();
    }

    claims.put(ClaimMapping.build(entry.getKey(), entry.getKey(), null, false), claimValue);
    if (log.isDebugEnabled()
        && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.USER_CLAIMS)) {
      log.debug(
          "Adding claim mapping : "
              + entry.getKey()
              + " <> "
              + entry.getKey()
              + " : "
              + claimValue);
    }
  }
  @RequestMapping("list")
  public ModelAndView list() {
    List<Media> list = service.query(0);
    JSONArray array = new JSONArray();
    for (Media ch : list) {
      array.add(ch.toJson());
    }

    return ViewUtil.renderListView("_media.jsp", array.toJSONString());
  }
 /**
  * Get all city crime reports
  *
  * @return List<CityCrime>
  */
 public List<CityCrime> getAllCityCrime() {
   List<CityCrime> cityCrimeList = new ArrayList<CityCrime>();
   for (int i = 0; i < rawData.size(); i++) {
     try {
       cityCrimeList.add(new CityCrime((JSONObject) rawData.get(i)));
     } catch (NullPointerException e) {
       e.printStackTrace();
     }
   }
   return cityCrimeList;
 }
  public JSONObject getManufacturers() {

    JSONObject result = new JSONObject();

    Connection dbConnection = null;

    try {
      Class.forName("com.mysql.jdbc.Driver");

      dbConnection =
          DriverManager.getConnection(PathNames.DB_URL, PathNames.USERNAME, PathNames.PASSWORD);

      String query =
          "SELECT * FROM "
              + PathNames.DB_MANUFACTURER_CATEGORIES
              + " cats, "
              + PathNames.DB_MANUFACTURERS
              + " mans WHERE cats.category_key='"
              + catkey
              + "' AND mans.manufacturer_id=cats.manufacturer_id";

      System.out.println(query);
      // Execute a query
      Statement statement = dbConnection.createStatement();

      ResultSet rs = statement.executeQuery(query);

      JSONArray typeList = new JSONArray();

      while (rs.next()) {
        JSONObject curr = new JSONObject();
        curr.put("catkey", rs.getString("category_key"));
        curr.put("manufacturer_id", rs.getString("manufacturer_id"));
        curr.put("manufacturer", rs.getString("manufacturer"));
        curr.put("image", rs.getString("image_name"));
        typeList.add(curr);
      }

      result.put("manufacturers", typeList);
      manufacturers = result;

    } catch (SQLException | ClassNotFoundException ex) {
      ex.printStackTrace();
    } finally {
      try {
        dbConnection.close();
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    return result;
  }
 public static JSONObject jsonObjectFromManifest(Manifest manifest) {
   JSONObject rootObject = new JSONObject();
   rootObject.put(ManifestConstants.TIME, manifest.getTimestamp());
   rootObject.put(
       ManifestConstants.GUID, manifest.getGuid()); // unique identifier for this manifest.
   rootObject.put(ManifestConstants.URLROOT, manifest.getUrlRoot());
   rootObject.put(ManifestConstants.VERSION, manifest.getVersion());
   // let's get that array
   JSONArray array = new JSONArray();
   for (Entry entry : manifest.getEntries()) {
     array.add(jsonObjectFromEntry(entry));
   }
   rootObject.put(ManifestConstants.ENTRIES, array);
   return rootObject;
 }
  private Map<String, JSONArray> getPathFilesMap(DocumentContext context, Object json) {
    DocumentContext reader =
        new JsonReader(defaultConfiguration().addOptions(Option.REQUIRE_PROPERTIES)).parse(json);

    JSONArray paths = null;
    try {
      paths = context.read("$..obibaFiles");
    } catch (PathNotFoundException e) {
      return null;
    }

    return paths
        .stream()
        .collect(Collectors.toMap(Object::toString, p -> (JSONArray) reader.read(p.toString())));
  }
 /**
  * 根据年月获取工资条
  *
  * @param year
  * @param month
  * @return
  */
 @RequestMapping(
     value = "/getAllSaralyClipByMonth.do",
     produces = "application/json;charset=UTF-8")
 @ResponseBody
 public String getAllSaralyClipByMonth(Integer year, Integer month) {
   return JSONArray.toJSONString(saralyClipService.getAllSaralyClipByMonth(year, month));
 }
  /**
   * This method is use for create web application
   *
   * @param payload request payload for web app create api
   * @param webAppDetail bean object of the web application
   * @throws IOException Throws this when failed to create web application
   * @throws RegistryException Throws this when UUID failed while requesting
   * @throws AppManagementException Throws this when gateway port failed while retrieving
   * @throws java.lang.InterruptedException Throws this when thread failed
   */
  private String createWebApplication(String payload, WebAppDetail webAppDetail)
      throws IOException, RegistryException, AppManagementException, InterruptedException {
    String currentUserName = webAppDetail.getUserName();
    String creatorSession = webAppDetail.getCreatorSession();
    httpHandler.doPostHttps(
        httpsBackEndUrl + "/publisher/asset/webapp",
        payload,
        creatorSession,
        "application/x-www-form-urlencoded");

    JSONArray claimsAry = new JSONArray();
    ConcurrentHashMap<String, String[]> claimMap = webAppDetail.getClaims();
    Iterator entries = claimMap.entrySet().iterator();
    while (entries.hasNext()) {
      Map.Entry thisEntry = (Map.Entry) entries.next();
      String claimName = ((String[]) thisEntry.getValue())[0];
      claimsAry.add(claimName);
    }
    JSONObject configJson = new JSONObject();
    configJson.put("provider", "wso2is-5.0.0"); // use a constant
    configJson.put("logout_url", "");
    configJson.put("claims", claimsAry);
    configJson.put("app_name", webAppDetail.getWebAppName());
    configJson.put("app_verison", webAppDetail.getVersion());
    configJson.put("app_transport", "http");
    configJson.put("app_context", webAppDetail.getContext());
    configJson.put("app_provider", webAppDetail.getUserName());
    configJson.put("app_allowAnonymous", "false");
    configJson.put("app_acsURL", "");
    httpHandler.doPostHttps(
        httpsBackEndUrl + "/publisher/api/sso/addConfig",
        configJson.toJSONString(),
        creatorSession,
        "application/json; charset=UTF-8");
    String appPath =
        "/_system/governance/appmgt/applicationdata/provider/"
            + currentUserName
            + "/"
            + webAppDetail.getWebAppName()
            + "/1.0.0/webapp";
    String UUID = wsRegistryServiceClient.getUUID(appPath);
    String trackingIDResponse =
        httpHandler
            .doGet(
                httpsBackEndUrl + "/publisher/api/asset/webapp/trackingid/" + UUID,
                "",
                creatorSession,
                "")
            .split(":")[1]
            .trim();
    String trackingID = trackingIDResponse.substring(1, (trackingIDResponse.length() - 2));
    webAppDetail.setTrackingCode(trackingID);
    invokeStatistcsJavascriptBuilder =
        new InvokeStatistcsJavascriptBuilder(
            trackingID, ipAddress, Configuration.getGatewayPort("http"));
    if (webAppDetail.getWebAppName().equals("PlanYourTrip_" + currentUserName)) {
      invokeStatistcsJavascriptBuilder.buildInvokeStaticsJavascriptFile(
          appmHomePath + "/repository/deployment/server/webapps/plan-your-trip-1.2.0");
    } else if (webAppDetail.getWebAppName().equals("TravelBooking_" + currentUserName)) {
      invokeStatistcsJavascriptBuilder.buildInvokeStaticsJavascriptFile(
          appmHomePath + "/repository/deployment/server/webapps/travel-booking-1.2.0/js");
    }
    log.info(webAppDetail.getWebAppName() + " created and UUID is : " + UUID);
    return UUID;
  }
Beispiel #11
0
  private Object getObject(String path) {
    this.hitCache = false;
    if (cache.containsKey(path)) {
      this.hitCache = true;
      return cache.get(path);
    }
    String[] params = path.split("\\.");
    JSONObject json = this.root;
    JSONArray jsonArray = null;
    String currentPath = "";
    for (int i = 0; i < params.length - 1; i++) {
      String param = params[i];
      if (cachePolicy.equals(CachePolicy.CACHE_ALL_LEVELS)) {
        if (!currentPath.isEmpty()) {
          currentPath += ".";
        }
        currentPath += param;
      }
      if (param.startsWith("$")) {
        if (jsonArray == null) {
          throw new JSONOperationErrorException("Not illegal syntax at this place: " + param);
        }
        int index = getIndex(param);
        json = (JSONObject) jsonArray.get(index);
        jsonArray = null;
      } else if (param.contains("[")) {
        int find = param.indexOf("[");
        String newParam = param.substring(0, find);
        String s = param.substring(find + 1, param.indexOf("]"));
        if (s.isEmpty()) {
          jsonArray = (JSONArray) json.get(newParam);
          json = null;
        } else {
          int index = Integer.parseInt(s);
          json = (JSONObject) ((JSONArray) json.get(newParam)).get(index);
          jsonArray = null;
        }
      } else {
        Object obj = json.get(param);
        if (obj instanceof JSONObject) {
          json = (JSONObject) obj;
          jsonArray = null;
        } else if (obj instanceof JSONArray) {
          jsonArray = (JSONArray) obj;
          json = null;
        } else if (obj == null) {
          throw new IllegalStateException("json object is null");
        } else {
          throw new IllegalStateException(
              "json object ('" + param + "') has wrong type: " + obj.getClass());
        }
      }
      if (cachePolicy.equals(CachePolicy.CACHE_ALL_LEVELS)) {
        saveToCache(currentPath, json);
      }
    }
    String name = params[params.length - 1];

    Object value;
    if (name.startsWith("$")) {
      if (jsonArray == null) {
        throw new JSONOperationErrorException("Not illegal syntax at this place: " + name);
      }
      int index = getIndex(name);
      value = jsonArray.get(index);
    } else {
      value = json.get(name);
    }

    saveToCache(path, value);

    return value;
  }
Beispiel #12
0
  private void publishFnol(List<Fnol> fnolList) {
    String amqpURI = null;
    ConnectionFactory factory = null;
    Channel channel = null;
    Connection connection = null;
    String message;
    String BOUND_SERVICES_ENV_VARIABLE_NAME = "VCAP_SERVICES";
    Map<String, String> env = System.getenv();
    String boundServicesJson = env.get(BOUND_SERVICES_ENV_VARIABLE_NAME);
    // String
    // boundServicesJson="{\"staging_env_json\":{},\"running_env_json\":{},\"system_env_json\":{\"VCAP_SERVICES\":{\"cloudamqp\":[{\"name\":\"MQRabbit\",\"label\":\"cloudamqp\",\"tags\":[\"Web-based\",\"UserProvisioning\",\"MessagingandQueuing\",\"amqp\",\"Backup\",\"SingleSign-On\",\"NewProduct\",\"rabbitmq\",\"CertifiedApplications\",\"Android\",\"DeveloperTools\",\"DevelopmentandTestTools\",\"Buyable\",\"Messaging\",\"Importable\",\"ITManagement\"],\"plan\":\"lemur\",\"credentials\":{\"uri\":\"amqp://*****:*****@moose.rmq.cloudamqp.com/kujcbqju\",\"http_api_uri\":\"https://*****:*****@moose.rmq.cloudamqp.com/api/\"}}],\"newrelic\":[{\"name\":\"NewRelic\",\"label\":\"newrelic\",\"tags\":[\"Monitoring\"],\"plan\":\"standard\",\"credentials\":{\"licenseKey\":\"a8a96a124d1b58d708a2c4c07c6cff8938e2e2f4\"}}],\"mongolab\":[{\"name\":\"MongoDB\",\"label\":\"mongolab\",\"tags\":[\"DataStore\",\"document\",\"mongodb\"],\"plan\":\"sandbox\",\"credentials\":{\"uri\":\"mongodb://*****:*****@ds047315.mongolab.com:47315/CloudFoundry_31lvrquo_j44bi0vu\"}}]}},\"application_env_json\":{\"VCAP_APPLICATION\":{\"limits\":{\"mem\":512,\"disk\":1024,\"fds\":16384},\"application_id\":\"87bdc475-83c4-4df9-92d1-40ff9bf82249\",\"application_version\":\"52891578-5906-4846-9231-afe7048f29bf\",\"application_name\":\"vinservice\",\"application_uris\":[\"vinservice.cfapps.io\"],\"version\":\"52891578-5906-4846-9231-afe7048f29bf\",\"name\":\"vinservice\",\"space_name\":\"development\",\"space_id\":\"d33d438c-860a-46d3-ab33-4c2efac841be\",\"uris\":[\"vinservice.cfapps.io\"],\"users\":null}}}";

    if (StringUtils.isNotBlank(boundServicesJson)) {
      // amqpURI =  JsonPath.read(boundServicesJson,
      // "$..cloudamqp[0].credentials.uri",String.class);
      JSONArray jsonArray = JsonPath.read(boundServicesJson, "$..cloudamqp[0].credentials.uri");
      amqpURI = jsonArray.get(0).toString();
    } else {
      amqpURI = "amqp://localhost";
    }

    System.out.println("Sending messages to " + amqpURI);
    // System.exit(0);

    try {
      factory = new ConnectionFactory();
      factory.setUri(amqpURI);
      connection = factory.newConnection();
      channel = connection.createChannel();
      channel.queueDeclare("fnol", true, false, false, null);
    } catch (IOException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    } catch (TimeoutException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    } catch (KeyManagementException e1) {
      e1.printStackTrace();
    } catch (NoSuchAlgorithmException e1) {
      e1.printStackTrace();
    } catch (URISyntaxException e1) {
      e1.printStackTrace();
    }

    for (Fnol fnol : fnolList) {
      message = new Gson().toJson(fnol);

      try {
        channel.basicPublish(
            "amq.direct",
            "fnolKey",
            new AMQP.BasicProperties.Builder().contentType("text/plain").deliveryMode(2).build(),
            // MessageProperties.PERSISTENT_TEXT_PLAIN,
            message.getBytes());
        System.out.println("message " + message + " was published");
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    try {
      channel.close();
      connection.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (TimeoutException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }