コード例 #1
0
ファイル: GalleryPanel.java プロジェクト: ssinica/ssgallery
  private void applyWelcomeScreen(JSONObject json) {

    // clears all variables and UI for images list state
    clearImagesState();

    JSONObject jsonObj = JSONHelper.getObject(json, "data");

    // paint folders list
    List<ClientFolder> folders =
        JSONHelper.getArray(
            jsonObj,
            "folders",
            new ValueParser<ClientFolder>() {
              @Override
              public ClientFolder parse(JSONValue jsonValue) {
                JSONObject json = jsonValue.isObject();
                String caption = JSONHelper.getString(json, "caption");
                String id = JSONHelper.getString(json, "id");
                List<String> randomImagesIds = JSONHelper.getStrings(json, "images");
                long folderSize = JSONHelper.getPrimitiveLong(json, "folderSize");
                int imagesCount = JSONHelper.getPrimitiveInt(json, "imagesCount");

                ClientFolder f =
                    new ClientFolder(id, caption, randomImagesIds, folderSize, imagesCount);
                return f;
              }
            });
    String html = "";
    for (ClientFolder folder : folders) {
      html += genFolderHtml(folder);
    }
    setSmallPhotosHtml(html, false);
  }
コード例 #2
0
ファイル: ModelExporter.java プロジェクト: Legun/VoxelEngine
 private static JSONObject animationFrameToJSONObject(AnimationFrame frame) {
   JSONObject json = new JSONObject();
   json.put("time", frame.getTime());
   json.put("translate", JSONHelper.vector3fToJSONArray(frame.getTranslateValue()));
   json.put("rotate", JSONHelper.vector3fToJSONArray(frame.getRotValue()));
   json.put("scale", JSONHelper.vector3fToJSONArray(frame.getScaleValue()));
   json.put("offset", JSONHelper.vector3fToJSONArray(frame.getOffsetValue()));
   return (json);
 }
コード例 #3
0
ファイル: GalleryPanel.java プロジェクト: ssinica/ssgallery
  private void applyLogin(String name, JSONObject json) {
    JSONObject jsonObj = JSONHelper.getObject(json, "data");
    boolean found = JSONHelper.getPrimitiveBoolean(jsonObj, "found", false);
    if (!found) {
      Window.alert("Пользователь " + GWTUtils.safeString(name) + " не найден!");
    } else {
      elName.setValue("");
      setCurrentUser(name);

      Window.Location.reload();
    }
  }
コード例 #4
0
ファイル: GalleryPanel.java プロジェクト: ssinica/ssgallery
  private void initUI() {
    History.addValueChangeHandler(this);
    addDomHandler(this, ClickEvent.getType());
    GWTUtils.setUidToElement(UID_CAPTION_CLICK, elCaption);
    GWTUtils.setUidToElement(UID_LOGIN, elLogin);
    GWTUtils.setUidToElement(UID_LOGOUT, elLogout);

    JSONObject json = JSONHelper.getJsonFromElement(Actions.JSON_DATA_EL_ID);
    String loggedInUser = null;
    if (json != null) {
      loggedInUser = JSONHelper.getString(json, "user");
    }
    setCurrentUser(loggedInUser);
  }
コード例 #5
0
ファイル: GalleryPanel.java プロジェクト: ssinica/ssgallery
  protected void applyImages(String folderId, String selectedImageId, JSONObject json) {

    JSONObject jsonObj = JSONHelper.getObject(json, "data");

    totalImagesCount = JSONHelper.getInteger(jsonObj, "totalImagesCount");
    prevImageId = JSONHelper.getString(jsonObj, "prevImageId");
    nextImageId = JSONHelper.getString(jsonObj, "nextImageId");
    startIndex = JSONHelper.getPrimitiveInt(jsonObj, "startIndex");

    // parse images
    List<ClientImage> images =
        JSONHelper.getArray(
            jsonObj,
            "images",
            new ValueParser<ClientImage>() {
              @Override
              public ClientImage parse(JSONValue jsonValue) {
                JSONObject json = jsonValue.isObject();
                String id = JSONHelper.getString(json, "id");
                return new ClientImage(id);
              }
            });
    if (GWTUtils.isEmpty(images)) {
      Window.alert("Failed to load images list");
      return;
    }
    loadedImages.clear();
    loadedImages.addAll(images);

    // parse folder
    JSONObject folderJson = JSONHelper.getObject(jsonObj, "folder");
    if (folderJson == null) {
      Window.alert("Failed to get images list!");
      return;
    }
    String folderCaption = JSONHelper.getString(folderJson, "caption");
    long folderSize = JSONHelper.getPrimitiveLong(json, "folderSize");
    int imagesCount = JSONHelper.getPrimitiveInt(json, "imagesCount");
    selectedFolder = new ClientFolder(folderId, folderCaption, null, folderSize, imagesCount);

    if (GWTUtils.isEmpty(selectedImageId)) {
      selectedImageId = loadedImages.get(0).getId();
      History.newItem(folderId + "/" + selectedImageId, false);
    }

    // paint folder, big photo, small images
    showImages(selectedFolder, selectedImageId, images, true);
  }
コード例 #6
0
ファイル: PandoraRadio.java プロジェクト: hsingh23/pandoroid
  /**
   * Description: Gets a list of songs to be played. This function should not be called more
   * frequently than MIN_TIME_BETWEEN_PLAYLIST_CALLS allows or an error will result.
   *
   * @param station_token -A string representing the station's unique identification token.
   * @throws RPCException when a Pandora RPC error has occurred.
   * @throws IOException when Pandora's remote servers could not be reached.
   * @throws HttpResponseException when an unexpected HTTP response occurs.
   * @throws Exception when an improper call has been made, or an unexpected error occurs.
   */
  @SuppressWarnings("unchecked")
  public Vector<Song> getPlaylist(String station_token)
      throws RPCException, IOException, HttpResponseException, Exception {

    // This protects against a temporary account suspension from too many
    // playlist requests.
    if (!isGetPlaylistCallValid(station_token)) {
      throw new Exception("Playlist calls are too frequent");
    }

    if (!this.isUserAuthorized()) {
      throw new Exception(
          "Improper call to getPlaylist(), " + "the user has not been logged in yet.");
    }

    Vector<Song> songs = new Vector<Song>();

    Map<String, Object> request_args = new HashMap<String, Object>();
    request_args.put("stationToken", station_token);

    // Order matters in this URL request. The same order given here is
    // the order received.
    request_args.put("additionalAudioUrl", MP3_128 + "," + AAC_32);

    JSONObject response = this.doCall("station.getPlaylist", request_args, true, true, null);

    JSONArray songs_returned = response.getJSONArray("items");
    for (int i = 0; i < songs_returned.length(); ++i) {
      Map<String, Object> song_data = JSONHelper.toMap(songs_returned.getJSONObject(i));
      ArrayList<PandoraAudioUrl> audio_url_mappings = new ArrayList<PandoraAudioUrl>();
      if (song_data.get("additionalAudioUrl") instanceof Vector<?>) {
        Vector<String> audio_urls = (Vector<String>) song_data.get("additionalAudioUrl");

        // This has to be in the same order as the request.
        audio_url_mappings.add(new PandoraAudioUrl(MP3_128, 128, audio_urls.get(0)));
        audio_url_mappings.add(new PandoraAudioUrl(AAC_32, 32, audio_urls.get(1)));
      }
      // MP3_192 data
      if (isPandoraOneCredentials()) {
        audio_url_mappings.add(
            new PandoraAudioUrl(
                (Map<String, Object>)
                    ((Map<String, Object>) song_data.get("audioUrlMap")).get("highQuality")));
      }
      // AAC_64 data
      audio_url_mappings.add(
          new PandoraAudioUrl(
              (Map<String, Object>)
                  ((Map<String, Object>) song_data.get("audioUrlMap")).get("mediumQuality")));
      songs.add(new Song(song_data, audio_url_mappings));
    }

    this.last_acquired_playlist_time = System.currentTimeMillis() / 1000L;
    this.last_acquired_playlist_station = station_token;

    return songs;
  }
コード例 #7
0
 @Test
 public void fromJson() {
   String filename = "classpath:org/jtester/tools/commons/manager.json";
   Manager manager = JSONHelper.fromJsonFile(Manager.class, filename);
   want.object(manager)
       .propertyEq("name", "Tony Tester")
       .propertyEq("phoneNumber.number", "0571-88886666");
   want.date(manager.getDate()).isYear(2009).isMonth("08").isHour(16);
 }
コード例 #8
0
ファイル: ModelExporter.java プロジェクト: Legun/VoxelEngine
 private static JSONObject modelPartToJSONObject(ModelPart part) {
   JSONObject json = new JSONObject();
   json.put("Name", part.getName());
   json.put("Animations", animationsToJSONArray(part.getAnimations()));
   json.put("BoundingBoxes", boundingBoxesToJSONArray(part.getBoundingBoxes()));
   json.put("Vertices", JSONHelper.arrayToJSONArray(part.getPositionVertices()));
   json.put("Skins", skinsToJSONArray(part.getSkins()));
   return (json);
 }
コード例 #9
0
ファイル: ModelExporter.java プロジェクト: Legun/VoxelEngine
 private static JSONObject modelPartBuilderToJSONObject(ModelPartBuilder part) {
   JSONObject json = new JSONObject();
   json.put("Name", part.getName());
   json.put("Animations", animationsToJSONArray(part.getAnimations()));
   json.put("BoundingBoxes", boundingBoxesToJSONArray(part.getBoundingBoxes()));
   json.put("Cubes", JSONHelper.arrayToJSONArray(part.getBlocks()));
   json.put("Skins", skinsBuilderToJSONArray(part.getSkins()));
   return (json);
 }
コード例 #10
0
ファイル: ModelExporter.java プロジェクト: Legun/VoxelEngine
  /** export blocks */
  public static void saveModelBuilder(ModelBuilder model, String filepath) {
    if (model == null) {
      Logger.get().log(Level.WARNING, "Tried to export a null model");
      return;
    }

    JSONObject json = new JSONObject();
    json.put("Name", model.getName());
    json.put("ModelParts", modelPartsBuilderToJSONArray(model.getParts()));
    JSONHelper.writeJSONObjectToFile(new File(filepath), json);
  }
コード例 #11
0
ファイル: NetworkHelper.java プロジェクト: vmailru/test
 public static BaseResponse doObject(String url, String responseBody, Type t) {
   BaseResponse resp = null;
   if (url.contains("113.31.22.234:16383") || url.contains("113.31.20.67:8197")) {
     String a = "{\"data\":" + responseBody + "}";
     String b = a.replace("\"sendtime\":{},", "\"sendtime\":\"\",");
     Log.i(TAG + " Response: =====>", b);
     resp = JSONHelper.jsonToObj(b, t);
   } else if (url.contains("https://api.weixin.qq.com")) {
     String a = "{\"data\":" + responseBody + "}";
     resp = JSONHelper.jsonToObj(a, t);
   } else {
     resp = JSONHelper.jsonToObj(responseBody, t);
   }
   if (Config.DEBUG && !Config.GATEWAY_URL.contains("i.api.zhubajie.com")) {
     SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
     String time = format.format(new Date(System.currentTimeMillis()));
     String urf8body = JSONHelper.unicodeToUtf8(responseBody);
     String response = "";
     if (!urf8body.equals("")) {
       if (urf8body.startsWith("{")) {
         response = JsonFormatTool.formatJson(urf8body, " ").replace("\n", "<br>");
       } else {
         response = urf8body.replace("\n", "<br>");
       }
     }
     LogManager.getInstance()
         .addLog(
             "<p>"
                 + "==========URL=========="
                 + time
                 + "<br><font color=\"#ff0000\">"
                 + url
                 + "</p><p>[请求]</p><p> ==========RESPONSE==========<br><font color=\"#00ff00\">"
                 + response
                 + "</p>");
   }
   return resp;
 }
コード例 #12
0
ファイル: GalleryPanel.java プロジェクト: ssinica/ssgallery
  private void processClickEvent(String uid, JSONObject json) {
    if (UID_FOLDER_CLICK.equals(uid)) {
      String folderId = JSONHelper.getString(json, "folderId");
      History.newItem(folderId);
    } else if (UID_CAPTION_CLICK.equals(uid)) {
      History.newItem("");
    } else if (UID_SMALL_IMAGE_CLICK.equals(uid)) {
      String folderId = JSONHelper.getString(json, "folderId");
      String imageId = JSONHelper.getString(json, "imageId");
      History.newItem(folderId + "/" + imageId);

      FullScreenHelper.startFullscreen(elBigPhotoW);

    } else if (UID_SMALL_LEFT.equals(uid)) {
      if (selectedFolder == null || GWTUtils.isEmpty(prevImageId)) {
        Window.alert("No more images");
      } else {
        loadSmallImages(selectedFolder.getId(), prevImageId, false);
        History.newItem(selectedFolder.getId() + "/" + prevImageId, false);
      }
    } else if (UID_SMALL_RIGHT.equals(uid)) {
      if (selectedFolder == null || GWTUtils.isEmpty(nextImageId)) {
        Window.alert("No more images");
      } else {
        loadSmallImages(selectedFolder.getId(), nextImageId, true);
        History.newItem(selectedFolder.getId() + "/" + nextImageId, false);
      }
    } else if (UID_LOGIN.equals(uid)) {
      login();
    } else if (UID_LOGOUT.equals(uid)) {
      logout();
    } else if (UID_ROTATE_LEFT.equals(uid)) {
      rotate(true);
    } else if (UID_ROTATE_RIGHT.equals(uid)) {
      rotate(false);
    }
  }
コード例 #13
0
ファイル: ModelExporter.java プロジェクト: Legun/VoxelEngine
  /** export vertices */
  public static void exportModel(Model model, File file) {
    if (model == null) {
      Logger.get().log(Level.WARNING, "Tried to export a null model");
      return;
    }

    if (file == null) {
      Logger.get().log(Level.WARNING, "Tried to export a model on a null file");
      return;
    }

    JSONObject json = new JSONObject();
    json.put("Name", model.getName());
    json.put("ModelParts", modelPartsToJSONArray(model.getParts()));
    JSONHelper.writeJSONObjectToFile(file, json);
  }
コード例 #14
0
ファイル: BianhuaActivity.java プロジェクト: pptk/meilijia
 @Override
 protected void onPostExecute(byte[] result) {
   super.onPostExecute(result);
   if (result == null) {
     pdDialog.dismiss();
     Toast.makeText(context, "无法连接到网络", Toast.LENGTH_LONG).show();
     return;
   }
   try {
     String JSONStr = new String(result, "UTF-8");
     Log.i(TAG, "==开始解析JSON文件,JSONStr-->" + JSONStr);
     map = JSONHelper.parserJsonAll(JSONStr, "weatherinfo");
     Log.i(TAG, "==开始把数据缓存到内存中");
     userMap.put(getCityFatherId(), map);
     Log.i(TAG, "==显示解析结果");
     showResult();
   } catch (Exception e) {
     Log.i(TAG, "==显示最终结果异常");
     e.printStackTrace();
   }
   pdDialog.dismiss();
 }
コード例 #15
0
ファイル: SearchServlet.java プロジェクト: lixdoo/Lucene
 public void complexitySearch(HttpServletRequest request, HttpServletResponse response)
     throws IllegalArgumentException, SecurityException, IllegalAccessException,
         NoSuchMethodException, InvocationTargetException, IOException, ParseException {
   JSONHelper.ResponseBean(new FileInformation(request).complexitySearch(), response);
 }
コード例 #16
0
ファイル: ModelExporter.java プロジェクト: Legun/VoxelEngine
 private static JSONObject boundingBoxToJSONObject(BoundingBox box) {
   JSONObject json = new JSONObject();
   json.put("min", JSONHelper.vector3fToJSONArray(box.getMin()));
   json.put("size", JSONHelper.vector3fToJSONArray(box.getSize()));
   return (json);
 }
コード例 #17
0
ファイル: ModelExporter.java プロジェクト: Legun/VoxelEngine
 private static JSONObject skinToJSONObject(ModelSkin skin) {
   JSONObject json = new JSONObject();
   json.put("Name", skin.getName());
   json.put("Vertices", JSONHelper.arrayToJSONArray(skin.getVBO().getContent(0)));
   return (json);
 }
コード例 #18
0
ファイル: NetworkHelper.java プロジェクト: vmailru/test
  public static synchronized BaseResponse doPostWithMoreFiles(
      String urlString, String data, Type t, Map<String, File> filesMap) {
    String end = System.getProperty("line.separator");
    String twoHyphens = "--";
    String boundary = "*****";

    BaseResponse resp = null;
    String urlStr = appendUrl(urlString);

    try {
      URL url = new URL(urlStr);
      HttpURLConnection con = (HttpURLConnection) url.openConnection();
      con.setDoInput(true);
      con.setDoOutput(true);
      con.setUseCaches(false);
      con.setRequestMethod("POST");
      con.setRequestProperty("Connection", "Keep-Alive");
      con.setRequestProperty("Charset", "UTF-8");
      con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
      con.connect();

      DataOutputStream ds = new DataOutputStream(con.getOutputStream());

      // 写入基本数据
      Map<Object, Object> objectMap = new HashMap<Object, Object>();
      JSONObject object = new JSONObject(data);
      Iterator<String> iterator = object.keys();
      String tempName = null;
      while (iterator.hasNext()) {
        tempName = iterator.next();
        objectMap.put(tempName, object.getString(tempName));
      }

      StringBuilder sb = new StringBuilder();
      for (Map.Entry<Object, Object> param : objectMap.entrySet()) {
        if (param.getKey().toString().equalsIgnoreCase("face")) {
          continue;
        }
        sb.append(twoHyphens + boundary + end);
        sb.append("Content-Disposition: form-data; name=\"" + param.getKey() + "\"" + end);
        sb.append(end);
        sb.append(param.getValue().toString() + end);
      }

      ds.write(sb.toString().getBytes("UTF-8")); // 发送表单字段数据
      Log.i(TAG + "=====>", sb.toString());
      ds.flush();

      // 写入文件

      Object[] keys = filesMap.keySet().toArray();

      for (Object key : keys) {

        File file = filesMap.get(key);

        StringBuilder split = new StringBuilder();
        split.append(twoHyphens + boundary + end);
        split.append(
            "Content-Disposition: form-data; name=\""
                + key.toString()
                + "\"; filename=\""
                + file.getName()
                + "\""
                + end);

        split.append(end);

        Log.i("....", split.toString());

        FileInputStream is = null;
        try {
          // 发送图片数据
          ds.writeBytes(split.toString());
          is = new FileInputStream(file);
          byte[] b = new byte[1024];
          int length = 0;
          while ((length = is.read(b)) != -1) {
            ds.write(b, 0, length);
          }
          ds.writeBytes(end);
        } catch (IOException e) {
          e.printStackTrace();
        } finally {
          if (is != null) {
            try {
              is.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
      }

      ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
      ds.flush();
      // ds.writeBytes(twoHyphens + boundary + end);
      // ds.writeBytes("Content-Disposition: form-data; " +
      // "name=\"face\";filename=\""
      // + file.getName() + "\"" + end);
      // ds.writeBytes(end);
      //
      // FileInputStream fStream = new FileInputStream(file);
      // int bufferSize = 1024;
      // byte[] buffer = new byte[bufferSize];
      // int length = -1;
      // while ((length = fStream.read(buffer)) != -1) {
      // ds.write(buffer, 0, length);
      // }
      // ds.writeBytes(end);
      // // ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
      // fStream.close();
      // ds.flush();
      ds.close();

      Log.d(TAG, "URL:" + urlStr);
      Log.d(TAG, "CODE:" + con.getResponseCode());

      if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {

        InputStream is = con.getInputStream();
        int ch;
        StringBuffer b = new StringBuffer();
        while ((ch = is.read()) != -1) {
          b.append((char) ch);
        }
        String responseBody = b.toString();

        Log.i(TAG + "=====>", responseBody);
        resp = JSONHelper.jsonToObj(responseBody, t);
        if (Config.DEBUG && Config.GATEWAY_URL.contains("mt.zhubajie.la")) {
          SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
          LogManager.getInstance()
              .addLog(
                  "<p>"
                      + "==========URL=========="
                      + format.format(new Date(System.currentTimeMillis()))
                      + "<br><font color=\"#ff0000\">"
                      + urlStr
                      + "</p><p>"
                      + "==========REQUEST==========<br><font color=\"#00ffff\">"
                      + sb.toString().replace("\n", "<br>")
                      + "</p><p> ==========RESPONSE==========<br><font color=\"#00ff00\">"
                      + JsonFormatTool.formatJson(JSONHelper.unicodeToUtf8(responseBody), " ")
                          .replace("\n", "<br>")
                      + "</p>");
        }
      } else {
        return new ErrorResponse("上传文件失败");
      }

    } catch (Exception e) {
      e.printStackTrace();
    }

    return resp;
  }