Пример #1
0
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.TEXT_PLAIN)
  @Path("/userList")
  public String getHotTalkList() throws Exception {
    JSONObject jsonData = new JSONObject();
    JSONArray jsonArray = new JSONArray();

    try {
      List<Map<String, Object>> lst = new ArrayList<Map<String, Object>>();
      lst = m_userDao.getUserList();
      if (lst.isEmpty()) {
        jsonData.put("err", "데이터가 없습니다.");
        return jsonData.toString();
      }
      Iterator<Map<String, Object>> itr = lst.iterator();
      int i = 0;
      while (itr.hasNext()) {
        itr.next();
        jsonArray.put(lst.get(i++));
      }
      jsonData.put("userList", jsonArray);
      jsonData.put("err", "");
    } catch (Exception ex) {
      ex.printStackTrace();
      System.out.println(ex.getMessage());
      jsonData.put("err", "시스템오류.");
    }
    // System.out.println("result : " + jsonData.toString());
    return jsonData.toString();
  }
Пример #2
0
 public synchronized void send(JSONObject obj) {
   try {
     logger.info("Sending to client: " + obj.toString());
     writer.write(response, obj.toString());
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Пример #3
0
  private void setResponse(HttpServletResponse response, String id_c, String date)
      throws JSONException, IOException, ClassNotFoundException {
    JSONObject json = new JSONObject();
    JSONArray ja = new JSONArray();
    JSONArray jae = new JSONArray();
    try {
      int idcour = Integer.parseInt(id_c);
      SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");

      java.util.Date date1 = (java.util.Date) sdf1.parse(date);
      Date sqlStartDate = new Date(date1.getTime());
      System.out.println(sqlStartDate);
      System.out.println(date1);
      System.out.println(date);
      System.out.println(idcour);
      ConnectionBD maco = new ConnectionBD();
      ArrayList<Presence> cours = maco.getPresence(sqlStartDate, idcour);
      for (int i = 0; i < cours.size(); i++) {
        JSONObject jsonCour = new JSONObject();
        jsonCour.put("libelle", cours.get(i).getLibelle());
        jsonCour.put("nomE", cours.get(i).getNomEtud());
        jsonCour.put("prenomE", cours.get(i).getPrenomEtud());
        jsonCour.put("date", cours.get(i).getDate());
        jsonCour.put("presence", cours.get(i).getPresence());
        ja.put(jsonCour);
      }
      ArrayList<Eleve> eleves = maco.getEtudiants();
      for (int i = 0; i < eleves.size(); i++) {
        JSONObject jsonEleve = new JSONObject();
        jsonEleve.put("id", eleves.get(i).getId());
        jsonEleve.put("nom", eleves.get(i).getNom());
        jsonEleve.put("prenom", eleves.get(i).getPrenom());
        jsonEleve.put("historisation", eleves.get(i).getHistorisation());
        jsonEleve.put("idCarte", eleves.get(i).getIdCarte());
        jae.put(jsonEleve);
      }
      json.put("etat", "success");
      json.put("Presences", ja);
      json.put("Eleves", jae);
      response.setStatus(200);
      response.setContentType("application/json");
      response.getWriter().write(json.toString());
    } catch (SQLException e) {
      json.put("etat", "Erreur accès base de données !");
      response.setStatus(200);
      response.setContentType("application/json");
      response.getWriter().write(json.toString());
    } catch (ParseException e) {
      // TODO Auto-generated catch block
      json.put("etat", "Erreur de parsing de date !");
      response.setStatus(200);
      response.setContentType("application/json");
      response.getWriter().write(json.toString());
    }
  }
  @Override
  protected int checkResponse(URI uri, ClientResponse response) {
    ClientResponse.Status status = response.getClientResponseStatus();
    int errorCode = status.getStatusCode();
    if (errorCode >= 300) {
      JSONObject obj = null;
      int code = 0;
      try {
        obj = response.getEntity(JSONObject.class);
        code = obj.getInt(ScaleIOConstants.ERROR_CODE);
      } catch (Exception e) {
        log.error("Parsing the failure response object failed", e);
      }

      if (code == 404 || code == 410) {
        throw ScaleIOException.exceptions.resourceNotFound(uri.toString());
      } else if (code == 401) {
        throw ScaleIOException.exceptions.authenticationFailure(uri.toString());
      } else {
        throw ScaleIOException.exceptions.internalError(uri.toString(), obj.toString());
      }
    } else {
      return errorCode;
    }
  }
  /**
   * Metodo web para calculo da rota
   *
   * @param json
   * @return json
   * @throws JSONException
   * @throws IOException
   * @throws JsonMappingException
   * @throws JsonParseException
   */
  @POST
  @Path("/searchZipCode")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public Response zipFind(String json)
      throws JSONException, JsonParseException, JsonMappingException, IOException {
    RespostaWebService result = new RespostaWebService();
    Response response = null;
    try {
      final JSONObject jsonObj = new JSONObject(json);
      final ObjectMapper objectMapper = new ObjectMapper();
      final RequestFindZipCode request =
          objectMapper.readValue(jsonObj.toString(), RequestFindZipCode.class);

      searchZipBusiness.validZipCode(request.getCep());

      result = searchZipBusiness.tryToFindZipCode(request.getCep(), objectMapper);

      return Response.status(Response.Status.OK).entity(result).build();
    } catch (final BusinessException e) {
      response = new ExceptionMapperImpl().toResponse(e);
    } catch (Exception e) {
      response = new ExceptionMapperImpl().toResponse(e);
    }
    return response;
  }
Пример #6
0
  @POST
  @Produces(MediaType.APPLICATION_JSON)
  @Path("select")
  public String getUserData(String json) {
    JSONObject jObj = null;
    try {
      jObj = new JSONObject(json);
      Integer userID = Integer.parseInt(jObj.getString("userID"));
      User user = dbManager.getUserbyAccountId(userID);

      jObj.put("middle_name", user.getMiddleName());
      jObj.put("last_name", user.getLastName());
      jObj.put("street", user.getStreet());
      jObj.put("house_number", user.getHouseNumber());
      jObj.put("city", user.getCity());
      jObj.put("postal_code", user.getPostalCode());
      jObj.put("country", user.getCountry());
      Account account = user.getAccountId();
      jObj.put("email", account.getUserName());

    } catch (JSONException ex) {
      Logger.getLogger(ChangeAccount.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      return jObj.toString();
    }
  }
 public void sendJson(Object jsonData) throws Log4AllException {
   HttpPut addLogPut;
   if (jsonData instanceof JSONArray) {
     addLogPut = new HttpPut(url + "/api/logs");
   } else {
     addLogPut = new HttpPut(url + "/api/log");
   }
   String rawResponse = "";
   JSONObject jsonResp;
   try {
     JSONObject jsonReq;
     if (jsonData instanceof JSONArray) {
       jsonReq = new JSONObject();
       jsonReq.put("logs", jsonData);
     } else {
       jsonReq = (JSONObject) jsonData;
     }
     jsonReq.put("application", this.application);
     if (token != null) {
       jsonReq.put("application_token", this.token);
     }
     HttpEntity postData = new StringEntity(jsonReq.toString());
     addLogPut.setEntity(postData);
     HttpResponse resp = getHttpClient().execute(addLogPut);
     rawResponse = IOUtils.toString(resp.getEntity().getContent());
     jsonResp = new JSONObject(rawResponse);
     if (!jsonResp.getBoolean("success")) {
       throw new Log4AllException(jsonResp.getString("message"));
     }
   } catch (IOException e) {
     throw new Log4AllException(e.getMessage() + "httpResp:" + rawResponse, e);
   } catch (JSONException e) {
     throw new Log4AllException(e.getMessage() + "httpResp:" + rawResponse, e);
   }
 }
Пример #8
0
 /**
  * Reads an individual Vertex from JSON. The vertex must match the accepted GraphSON format.
  *
  * @param json a single vertex in GraphSON format
  * @param factory the factory responsible for constructing graph elements
  * @param hasEmbeddedTypes the GraphSON has embedded types
  */
 public static Vertex vertexFromJson(
     final JSONObject json, final ElementFactory factory, final boolean hasEmbeddedTypes)
     throws IOException {
   final JsonParser jp = jsonFactory.createJsonParser(json.toString());
   final JsonNode node = jp.readValueAsTree();
   return vertexFromJson(node, factory, hasEmbeddedTypes);
 }
Пример #9
0
 @Test
 public void test() throws JSONException {
   Map<String, String> map = new HashMap<String, String>();
   map.put("serviceurl", "http:/");
   JSONObject jo = new JSONObject(map);
   System.out.println(jo.get("serviceurl"));
   assertEquals("http:/", jo.get("serviceurl"));
   System.out.println((DBObject) JSON.parse(jo.toString()));
 }
Пример #10
0
  public static void register(JSONObject obj) {
    pro = getOptsPro();
    if (null != pro && pro.getProperty("a", null).equals(obj.optString("a", ""))) {
      return;
    }

    URL url = null;
    HttpURLConnection connection = null;
    OutputStream out = null;
    BufferedReader reader = null;
    try {
      url = new URL(RIGSTER_URL);

      connection = (HttpURLConnection) url.openConnection();

      connection.setDoOutput(true);
      connection.setDoInput(true);
      connection.setRequestMethod("POST");
      connection.setUseCaches(false);
      connection.setInstanceFollowRedirects(true);

      connection.setRequestProperty("Content-Type", "application/json");
      // connection.setRequestProperty("Content-Type", "text/xml");
      connection.setRequestProperty("Accept", "application/json");
      connection.connect();
      // System.out.println(obj.toString());
      out = connection.getOutputStream();
      out.write(obj.toString().getBytes());
      out.flush();

      reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
      String lines;
      StringBuffer sb = new StringBuffer("");
      while ((lines = reader.readLine()) != null) {
        lines = new String(lines.getBytes(), "utf-8"); // 中文
        sb.append(lines);
      }
      // System.out.println(sb.toString());
      JSONObject obj2 = new JSONObject(sb.toString());
      obj2.put("a", obj.get("a"));
      saveOpts(obj2);
      // return sb.toString();
    } catch (Exception e) {
      System.out.println(e.getMessage());
    } finally {
      try {
        if (null != out) out.close();
      } catch (Exception e) {
      }
      try {
        if (null != reader) reader.close();
      } catch (Exception e) {
      }
      connection.disconnect();
    }
  }
Пример #11
0
  @Test
  public void shouldServeListOfWorkspacesForValidRepository() throws Exception {
    URL postUrl = new URL(SERVER_URL + "/mode%3arepository");
    HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);
    String body = getResponseFor(connection);

    JSONObject objFromResponse = new JSONObject(body);
    JSONObject expected =
        new JSONObject(
            "{\"default\":{\"workspace\":{\"name\":\"default\",\"resources\":{\"query\":\"/resources/mode%3arepository/default/query\",\"items\":\"/resources/mode%3arepository/default/items\"}}}}");

    assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_OK));
    assertThat(objFromResponse.toString(), is(expected.toString()));
    connection.disconnect();
  }
Пример #12
0
 @Override
 public String toString() {
   try {
     JSONObject jsonObj = new JSONObject();
     jsonObj.put("i", i);
     jsonObj.put("s", s);
     return jsonObj.toString();
   } catch (JSONException e) {
     throw new RuntimeException("failed to construct JSONObject for toString", e);
   }
 }
Пример #13
0
  private void getAndCompareJson(String address, String resourcePath, String type)
      throws Exception {
    GetMethod get = new GetMethod(address);
    get.setRequestHeader("Content-Type", "*/*");
    get.setRequestHeader("Accept", type);
    HttpClient httpClient = new HttpClient();
    try {
      httpClient.executeMethod(get);
      String jsonContent = getStringFromInputStream(get.getResponseBodyAsStream());
      String expected = getStringFromInputStream(getClass().getResourceAsStream(resourcePath));
      expected = expected.replaceAll("9080", PORT);

      JSONObject obj1 = new JSONObject(jsonContent);
      JSONObject obj2 = new JSONObject(expected);

      assertEquals("Atom entry should've been formatted as json", obj1.toString(), obj2.toString());
    } finally {
      get.releaseConnection();
    }
  }
  public <T extends Element> JsonObject serializeElement(T element) throws IOException {
    JSONObject elementJson;
    try {
      elementJson = GraphSONUtility.jsonFromElement(element, null, graphsonMode);
    } catch (JSONException e) {
      throw new IOException(e);
    } finally {
    }

    return new JsonObject(elementJson.toString());
  }
Пример #15
0
 private String createDagInfo(String script) throws IOException {
   String dagInfo;
   try {
     JSONObject jsonObject = new JSONObject();
     jsonObject.put("context", "Pig");
     jsonObject.put("description", script);
     dagInfo = jsonObject.toString();
   } catch (JSONException e) {
     throw new IOException("Error when trying to convert Pig script to JSON", e);
   }
   log.debug("DagInfo: " + dagInfo);
   return dagInfo;
 }
  /*
   * get a list type of request
   * e.g. GET /api/types/system/instances
   *
   * @param resource WebResource
   *
   * @param valueType class type
   *
   * @return list of objects
   *
   * @throws VnxeException unexpectedDataError
   */
  public List<T> getDataForObjects(Class<T> valueType) throws VNXeException {
    _logger.info("getting data: {}", _url);
    ClientResponse response = sendGetRequest(_resource);
    String emcCsrfToken = response.getHeaders().getFirst(EMC_CSRF_HEADER);
    if (emcCsrfToken != null) {
      saveEmcCsrfToken(emcCsrfToken);
    }

    saveClientCookies();
    String resString = response.getEntity(String.class);
    _logger.info("got data: " + resString);
    JSONObject res;
    List<T> returnedObjects = new ArrayList<T>();
    try {
      res = new JSONObject(resString);
      if (res != null) {
        JSONArray entries = res.getJSONArray(VNXeConstants.ENTRIES);
        if (entries != null && entries.length() > 0) {
          for (int i = 0; i < entries.length(); i++) {
            JSONObject entry = entries.getJSONObject(i);
            JSONObject object = (JSONObject) entry.get(VNXeConstants.CONTENT);
            if (object != null) {
              String objectString = object.toString();
              ObjectMapper mapper = new ObjectMapper();
              try {
                T returnedObject = mapper.readValue(objectString, valueType);
                returnedObjects.add(returnedObject);
              } catch (JsonParseException e) {
                _logger.error(
                    String.format("unexpected data returned: %s from: %s", objectString, _url), e);
                throw VNXeException.exceptions.unexpectedDataError(objectString, e);

              } catch (JsonMappingException e) {
                _logger.error(
                    String.format("unexpected data returned: %s from: %s", objectString, _url), e);
                throw VNXeException.exceptions.unexpectedDataError(objectString, e);
              } catch (IOException e) {
                _logger.error(
                    String.format("unexpected data returned: %s from: %s", objectString, _url), e);
                throw VNXeException.exceptions.unexpectedDataError(objectString, e);
              }
            }
          }
        }
      }
    } catch (JSONException e) {
      _logger.error(String.format("unexpected data returned: %s from: %s", resString, _url), e);
      throw VNXeException.exceptions.unexpectedDataError(resString, e);
    }
    return returnedObjects;
  }
 private <T> List<T> getResponseObjects(Class<T> clazz, ClientResponse response)
     throws JSONException {
   JSONArray resp = response.getEntity(JSONArray.class);
   List<T> result = null;
   if (resp != null && resp.length() > 0) {
     result = new ArrayList<T>();
     for (int i = 0; i < resp.length(); i++) {
       JSONObject entry = resp.getJSONObject(i);
       T respObject = new Gson().fromJson(entry.toString(), clazz);
       result.add(respObject);
     }
   }
   return result;
 }
Пример #18
0
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.TEXT_PLAIN)
  @Path("/login/{userSeq}")
  public String getHotTalkList(@PathParam("userSeq") int userSeq) throws Exception {
    JSONObject jsonData = new JSONObject();

    try {
      Map<String, Object> map = new HashMap<String, Object>();
      map = m_userDao.getLoginUser(userSeq);
      if (map.isEmpty()) {
        jsonData.put("err", "데이터가 없습니다.");
        return jsonData.toString();
      }
      jsonData.put("user", map);

    } catch (Exception ex) {
      ex.printStackTrace();
      System.out.println(ex.getMessage());
      jsonData.put("err", "시스템오류.");
    }
    // System.out.println("result : " + jsonData.toString());
    return jsonData.toString();
  }
Пример #19
0
  public boolean update(String yarnAppId, String jobId, Map<String, String> tags, AppInfo app) {
    String path = this.zkRoot + "/" + yarnAppId + "/" + jobId;
    Map<String, String> appInfo = new HashMap<>();
    appInfo.put("id", app.getId());
    appInfo.put("user", app.getUser());
    appInfo.put("name", app.getName());
    appInfo.put("queue", app.getQueue());
    appInfo.put("state", app.getState());
    appInfo.put("finalStatus", app.getFinalStatus());
    appInfo.put("progress", app.getProgress() + "");
    appInfo.put("trackingUI", app.getTrackingUI());
    appInfo.put("diagnostics", app.getDiagnostics());
    appInfo.put("trackingUrl", app.getTrackingUrl());
    appInfo.put("clusterId", app.getClusterId());
    appInfo.put("applicationType", app.getApplicationType());
    appInfo.put("startedTime", app.getStartedTime() + "");
    appInfo.put("finishedTime", app.getFinishedTime() + "");
    appInfo.put("elapsedTime", app.getElapsedTime() + "");
    appInfo.put(
        "amContainerLogs", app.getAmContainerLogs() == null ? "" : app.getAmContainerLogs());
    appInfo.put(
        "amHostHttpAddress", app.getAmHostHttpAddress() == null ? "" : app.getAmHostHttpAddress());
    appInfo.put("allocatedMB", app.getAllocatedMB() + "");
    appInfo.put("allocatedVCores", app.getAllocatedVCores() + "");
    appInfo.put("runningContainers", app.getRunningContainers() + "");

    Map<String, String> fields = new HashMap<>();
    fields.put(ENTITY_TAGS_KEY, (new JSONObject(tags)).toString());
    fields.put(APP_INFO_KEY, (new JSONObject(appInfo)).toString());
    try {
      lock.acquire();
      JSONObject object = new JSONObject(fields);
      if (curator.checkExists().forPath(path) == null) {
        curator.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path);
      }
      curator.setData().forPath(path, object.toString().getBytes("UTF-8"));

    } catch (Exception e) {
      LOG.error("failed to update job {} for yarn app {} ", jobId, yarnAppId);
    } finally {
      try {
        lock.release();
      } catch (Exception e) {
        LOG.error("fail releasing lock", e);
      }
    }
    return true;
  }
  /*
   * get one instance request
   * e.g. GET /api/instances/nasServer/<id>
   *
   * @param resource WebResource
   *
   * @param Class<T> class type
   *
   * @throws VnexException unexpectedDataError
   */
  public T getDataForOneObject(Class<T> valueType) throws VNXeException {
    _logger.debug("getting data: " + _url);
    ClientResponse response = sendGetRequest(_resource);
    String emcCsrfToken = response.getHeaders().getFirst(EMC_CSRF_HEADER);
    if (emcCsrfToken != null) {
      saveEmcCsrfToken(emcCsrfToken);
    }

    saveClientCookies();
    String resString = response.getEntity(String.class);
    _logger.debug("got data: " + resString);
    JSONObject res;
    String objectString = null;
    T returnedObject = null;
    try {
      res = new JSONObject(resString);
      if (res != null) {
        JSONObject object = (JSONObject) res.get(VNXeConstants.CONTENT);
        if (object != null) {
          objectString = object.toString();
          ObjectMapper mapper = new ObjectMapper();
          try {
            returnedObject = mapper.readValue(objectString, valueType);
          } catch (JsonParseException e) {
            _logger.error(
                String.format("unexpected data returned: %s from: %s", objectString, _url), e);
            throw VNXeException.exceptions.unexpectedDataError(
                "unexpected data returned:" + objectString, e);
          } catch (JsonMappingException e) {
            _logger.error(
                String.format("unexpected data returned: %s from: %s", objectString, _url), e);
            throw VNXeException.exceptions.unexpectedDataError(
                "unexpected data returned:" + objectString, e);
          } catch (IOException e) {
            _logger.error(
                String.format("unexpected data returned: %s from: %s", objectString, _url), e);
            throw VNXeException.exceptions.unexpectedDataError(
                "unexpected data returned:" + objectString, e);
          }
        }
      }
    } catch (JSONException e) {
      _logger.error(String.format("unexpected data returned: %s from: %s", resString, _url), e);
      throw VNXeException.exceptions.unexpectedDataError(
          "unexpected data returned:" + objectString, e);
    }
    return returnedObject;
  }
Пример #21
0
  @GET
  @Path("/")
  @Produces(MediaType.APPLICATION_JSON)
  public Response getStatisticsIndex(@Context final UriInfo uriInfo)
      throws IllegalArgumentException, UriBuilderException, JSONException {

    final JSONObject result = new JSONObject();
    result.put(
        MAX_RESULTS_PATH,
        uriInfo.getBaseUriBuilder().path(Settings.class).path(MAX_RESULTS_PATH).build());
    result.put(
        PAGE_REFRESH_PATH,
        uriInfo.getBaseUriBuilder().path(Settings.class).path(PAGE_REFRESH_PATH).build());

    return Response.ok(result.toString()).build();
  }
 /**
  * Metodo responsavel por salvar um novo endereço
  *
  * @param json
  * @return
  */
 @POST
 @Path("/salvar")
 @Consumes(MediaType.APPLICATION_JSON)
 @Produces(MediaType.APPLICATION_JSON)
 public Response salvar(String json) {
   Response response = null;
   try {
     final JSONObject jsonObj = new JSONObject(json);
     final ObjectMapper objectMapper = new ObjectMapper();
     final AdressVO request = objectMapper.readValue(jsonObj.toString(), AdressVO.class);
     int id = searchZipBusiness.save(request);
     return Response.status(Response.Status.OK).entity(id).build();
   } catch (Exception e) {
     return new ExceptionMapperImpl().toResponse(e);
   }
 }
  /**
   * Serviço de cadastro de usuários
   *
   * @param json
   * @return
   */
  @POST
  @Path("/saveUser")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public Response newUser(String json) {
    JSONObject jsonObj;
    try {
      jsonObj = new JSONObject(json);
      final ObjectMapper objectMapper = new ObjectMapper();
      final AuthUser request = objectMapper.readValue(jsonObj.toString(), AuthUser.class);
      Integer findUserId = userBusiness.saveUser(request);
      return Response.status(Response.Status.OK).entity(findUserId).build();

    } catch (Exception e) {
      return new ExceptionMapperImpl().toResponse(e);
    }
  }
Пример #24
0
 private String getResponseDetails(ClientResponse clientResp) {
   String detailedResponse = null;
   try {
     JSONObject jObj = clientResp.getEntity(JSONObject.class);
     detailedResponse =
         String.format(
             "Description:%s, Details:%s",
             jObj.getString("description"), jObj.getString("details"));
     _log.error(
         String.format(
             "HTTP error code: %d, Complete ECS error response: %s",
             clientResp.getStatus(), jObj.toString()));
   } catch (Exception e) {
     _log.error("Unable to get ECS error details");
     detailedResponse = String.format("%1$s", (clientResp == null) ? "" : clientResp);
   }
   return detailedResponse;
 }
  @Override
  public void map(IntWritable key, WeightedVectorWritable value, Context context)
      throws IOException, InterruptedException {
    String name = "";
    Vector v = value.getVector();
    if (v instanceof NamedVector) {
      name = ((NamedVector) v).getName();
    }

    JSONObject object = new JSONObject();
    try {
      object.put("a", key.get());
      object.put("fP", name);
      context.write(NullWritable.get(), new Text(object.toString()));
    } catch (JSONException e) {
      LOG.error("Error while creating JSON record.", e);
    }
  }
 public VNXeCommandResult postRequestSync(ParamBase param) {
   ClientResponse response = postRequest(param);
   if (response.getClientResponseStatus() == ClientResponse.Status.NO_CONTENT) {
     VNXeCommandResult result = new VNXeCommandResult();
     result.setSuccess(true);
     return result;
   }
   String resString = response.getEntity(String.class);
   _logger.debug("KH API returned: {} ", resString);
   JSONObject res;
   String objectString = null;
   VNXeCommandResult returnedObject = null;
   try {
     res = new JSONObject(resString);
     if (res != null) {
       JSONObject object = (JSONObject) res.get(VNXeConstants.CONTENT);
       if (object != null) {
         objectString = object.toString();
         ObjectMapper mapper = new ObjectMapper();
         try {
           returnedObject = mapper.readValue(objectString, VNXeCommandResult.class);
           returnedObject.setSuccess(true);
         } catch (JsonParseException e) {
           _logger.error(String.format("unexpected data returned: %s", objectString), e);
           throw VNXeException.exceptions.unexpectedDataError(
               String.format("unexpected data returned: %s", objectString), e);
         } catch (JsonMappingException e) {
           _logger.error(String.format("unexpected data returned: %s", objectString), e);
           throw VNXeException.exceptions.unexpectedDataError(
               String.format("unexpected data returned: %s", objectString), e);
         } catch (IOException e) {
           _logger.error(String.format("unexpected data returned: %s", objectString), e);
           throw VNXeException.exceptions.unexpectedDataError(
               String.format("unexpected data returned: %s", objectString), e);
         }
       }
     }
   } catch (JSONException e) {
     _logger.error(String.format("unexpected data returned: %s from: %s", resString, _url), e);
     throw VNXeException.exceptions.unexpectedDataError(
         String.format("unexpected data returned: %s", objectString), e);
   }
   return returnedObject;
 }
Пример #27
0
 @GET
 @Path("/{setting}")
 @Produces(MediaType.APPLICATION_JSON)
 public Response settingJson(@PathParam("setting") final String setting) throws JSONException {
   final JSONObject result = new JSONObject();
   switch (setting) {
     case MAX_RESULTS_PATH:
       result.put(MAX_RESULTS_PATH, maxResults);
       break;
     case PAGE_REFRESH_PATH:
       result.put(PAGE_REFRESH_PATH, pageRefreshSecs);
       break;
     default:
       return Response.status(Status.BAD_REQUEST)
           .entity("\"settings parameter not supported\"")
           .build();
   }
   return Response.ok(result.toString()).build();
 }
Пример #28
0
  @Override
  public String getSchemaJSON() {
    if (!changed && schemaJSON != null) {
      return schemaJSON;
    }

    if (schemaKeys == null) {
      schema.remove(Schema.FIELD_SCHEMA_KEYS);
    } else {
      try {
        schema.put(Schema.FIELD_SCHEMA_KEYS, SchemaUtils.createJSONObject(schemaKeys));
      } catch (JSONException ex) {
        throw new RuntimeException(ex);
      }
    }

    schemaJSON = schema.toString();
    return schemaJSON;
  }
 @Override
 public String encodeData(Map<String, String> files) {
   JSONObject root = new JSONObject();
   String result = "";
   try {
     root.put("description", "Multiverse-Core Debug Info");
     root.put("public", !this.isPrivate);
     JSONObject fileList = new JSONObject();
     for (Map.Entry<String, String> entry : files.entrySet()) {
       JSONObject fileObject = new JSONObject();
       fileObject.put("content", entry.getValue());
       fileList.put(entry.getKey(), fileObject);
     }
     root.put("files", fileList);
     result = root.toString();
   } catch (JSONException e) {
     e.printStackTrace();
   }
   return result;
 }
  public static void main(String[] args) {

    OCCI_RestClient cl = new OCCI_RestClient("", "", "");

    List<ServiceComponent> scs = new ArrayList<ServiceComponent>();
    ServiceComponent c1 = new ServiceComponent();
    c1.setArchitecture("x86");
    c1.setCores(2);
    c1.setMemory(2.5);
    c1.setSpeed(0.6);
    c1.setImage("image");
    c1.setInstances(2);
    scs.add(c1);

    try {
      JSONObject obj = cl.renderCompute("a", c1, 1);
      System.out.println(obj.toString(1));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }