示例#1
0
文件: Ion.java 项目: nishant1286/ion
  private Ion(Context context, String name) {
    httpClient = new AsyncHttpClient(new AsyncServer());
    this.context = context = context.getApplicationContext();
    this.name = name;

    try {
      responseCache =
          ResponseCacheMiddleware.addCache(
              httpClient, new File(context.getCacheDir(), name), 10L * 1024L * 1024L);
    } catch (Exception e) {
      IonLog.w("unable to set up response cache", e);
    }
    try {
      storeCache = DiskLruCache.open(new File(context.getFilesDir(), name), 1, 1, Long.MAX_VALUE);
    } catch (Exception e) {
    }

    // TODO: Support pre GB?
    if (Build.VERSION.SDK_INT >= 9) addCookieMiddleware();

    httpClient.getSocketMiddleware().setConnectAllAddresses(true);
    httpClient.getSSLSocketMiddleware().setConnectAllAddresses(true);

    bitmapCache = new IonBitmapCache(this);

    configure()
        .addLoader(new PackageIconLoader())
        .addLoader(httpLoader = new HttpLoader())
        .addLoader(contentLoader = new ContentLoader())
        .addLoader(fileLoader = new FileLoader());
  }
  public void loadPointCount() {
    String uid = URLEncoder.encode(AccountUtil.getUid(this.getActivity()));
    String url = Constants.BASE_URL + "point?uid=" + uid;
    Log.d(Constants.TAG, "current loadPointCount url " + url);
    AsyncHttpGet ahg = new AsyncHttpGet(url);
    AsyncHttpClient.getDefaultInstance()
        .executeString(
            ahg,
            new AsyncHttpClient.StringCallback() {
              @Override
              public void onCompleted(
                  Exception e, AsyncHttpResponse response, final String result) {
                if (e != null) {
                  e.printStackTrace();
                  return;
                }

                if (ReturnProductFragment.this != null
                    && ReturnProductFragment.this.getActivity() != null)
                  ReturnProductFragment.this
                      .getActivity()
                      .runOnUiThread(
                          new Runnable() {
                            public void run() {
                              if (result.indexOf("err") == -1) {
                                title.setText("目前點數:" + result + "點");
                              }
                            }
                          });
              }
            });
  }
  public void loadItmes(final boolean first) {
    String uid = URLEncoder.encode(AccountUtil.getUid(this.getActivity()));
    String url = Constants.BASE_URL + "gift/line/nlist?uid=" + uid;
    Log.d(Constants.TAG, "current line gift url " + url);
    AsyncHttpGet ahg = new AsyncHttpGet(url);
    AsyncHttpClient.getDefaultInstance()
        .executeJSONArray(
            ahg,
            new AsyncHttpClient.JSONArrayCallback() {
              @Override
              public void onCompleted(Exception e, AsyncHttpResponse response, JSONArray result) {
                if (ReturnProductFragment.this != null
                    && ReturnProductFragment.this.getActivity() != null)
                  ReturnProductFragment.this
                      .getActivity()
                      .runOnUiThread(
                          new Runnable() {
                            public void run() {
                              progressBar1.setVisibility(View.INVISIBLE);
                            }
                          });

                if (e != null) {
                  e.printStackTrace();
                  return;
                }

                //		        if(first && result.length() == 0)
                // Message.ShowMsgDialog(ActiveGiftFragment.this.getActivity(), "目前沒有進行中的遊戲");
                res = new ArrayList<GiftItem>();
                for (int index = 0; index < result.length(); index++) {
                  try {

                    JSONObject jo = result.getJSONObject(index);
                    res.add(GiftItem.genPostItem(jo));
                  } catch (JSONException e1) {
                    e1.printStackTrace();
                  }
                }
                restore(false, null);

                //				if (ReturnProductFragment.this != null &&
                // ReturnProductFragment.this.getActivity() != null)
                //					ReturnProductFragment.this.getActivity().runOnUiThread(new Runnable() {
                //						public void run() {
                //							ReturnGiftAdapter ia = (ReturnGiftAdapter) gridView.getAdapter();
                //							for (int index = 0; index < res.size(); index++)
                //								ia.add(res.get(index));
                //							ia.notifyDataSetChanged();
                //						}
                //					});
              }
            });
  }
  protected void index(
      String url, final Collection<M> collection, final IndexCallback<M> callback) {
    URI uri = URI.create(url);
    AsyncHttpRequest req = new AsyncHttpRequest(uri, "GET");
    AsyncHttpClient.getDefaultInstance()
        .executeJSONArray(
            req,
            new AsyncHttpClient.JSONArrayCallback() {

              @Override
              public void onCompleted(Exception e, AsyncHttpResponse source, JSONArray result) {
                if (e == null && result != null) {
                  String json = result.toString();
                  Collection<M> rcollection = gson.fromJson(json, getCollectionType());
                  collection.addAll(rcollection);
                  callback.onIndex(collection);
                } else {
                  callback.onError(e);
                }
              }
            });
  }
  public void testWebSocket() throws Exception {
    final Semaphore semaphore = new Semaphore(0);

    AsyncHttpClient.getDefaultInstance()
        .websocket(
            "http://localhost:5000/ws",
            null,
            new WebSocketConnectCallback() {
              @Override
              public void onCompleted(Exception ex, WebSocket webSocket) {
                webSocket.send("hello");
                webSocket.setStringCallback(
                    new StringCallback() {
                      @Override
                      public void onStringAvailable(String s) {
                        assertEquals(s, "hello");
                        semaphore.release();
                      }
                    });
              }
            });

    assertTrue(semaphore.tryAcquire(TIMEOUT, TimeUnit.MILLISECONDS));
  }
  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Initialize Builder
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    // Get arguments passed to newInstance()
    serverName = getArguments().getString("serverName");
    serverURL = getArguments().getString("serverURL");
    serverLocation = getArguments().getString("serverLocation");

    // Set title and button action
    builder.setTitle(R.string.join_game_title);
    builder.setNegativeButton(android.R.string.cancel, this);

    // Inflate the view that shows the spinner and status text
    LayoutInflater inflater = getActivity().getLayoutInflater();
    View loadingView = inflater.inflate(R.layout.dialog_join_game, null);

    // Get the 2 text views
    stateText = (TextView) loadingView.findViewById(R.id.join_game_state);
    serverText = (TextView) loadingView.findViewById(R.id.join_game_server);

    stateText.setText(R.string.join_game_state_connecting);
    serverText.setText("On server: " + serverName + " (" + serverLocation + ")");

    // Add view to dialog
    builder.setView(loadingView);

    // Connect to the server
    SocketIOClient.connect(
        AsyncHttpClient.getDefaultInstance(),
        serverURL + ":81",
        new ConnectCallback() {

          @Override
          public void onConnectCompleted(Exception e, SocketIOClient client) {
            if (e != null) {
              e.printStackTrace();
              return;
            }

            client.setStringCallback(
                new StringCallback() {

                  @Override
                  public void onString(String str, Acknowledge ack) {
                    System.out.println();
                  }
                });

            client.setJSONCallback(
                new JSONCallback() {

                  @Override
                  public void onJSON(JSONObject obj, Acknowledge ack) {
                    System.out.println();
                  }
                });
          }
        });

    return builder.create();
  }
        @Override
        public void onPictureTaken(byte[] bytes, Camera camera) {
          _capturedImageBytes = bytes;
          String fileName =
              "FT3D_"
                  + _picFrameNumber
                  + "_"
                  + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()).toString()
                  + ".jpg";

          File sdRoot = Environment.getExternalStorageDirectory();
          String dir = "/FT3D/";
          File mkDir = new File(sdRoot, dir);
          mkDir.mkdirs();
          File pictureFile = new File(sdRoot, dir + fileName);

          try {
            FileOutputStream purge = new FileOutputStream(pictureFile);
            purge.write(bytes);
            purge.close();
          } catch (FileNotFoundException e) {
            Log.d("DG_DEBUG", "File not found: " + e.getMessage());
          } catch (IOException e) {
            Log.d("DG_DEBUG", "Error accessing file: " + e.getMessage());
          }

          AsyncHttpPost reqPost =
              new AsyncHttpPost("http://" + _picTakerService.getServerIP() + ":7373/fileUpload");
          MultipartFormDataBody body = new MultipartFormDataBody();
          body.addFilePart("framePic", pictureFile);
          body.addStringPart("frameNumber", String.valueOf(_picFrameNumber));
          reqPost.setBody(body);

          Future<String> uploadReturn = AsyncHttpClient.getDefaultInstance().executeString(reqPost);
          uploadReturn.setCallback(
              new FutureCallback<String>() {
                @Override
                public void onCompleted(Exception e, String s) {
                  if (_uploadingDialog != null) {
                    _uploadingDialog.cancel();
                  }

                  if (_systemCamera != null) {
                    _systemCamera.release();
                  }

                  _mainLayout.removeView(_cameraPreviewWindow);

                  _registerStepContainer.setVisibility(View.VISIBLE);
                  _submitOrderStepContainer.setVisibility(View.VISIBLE);
                  _readyStepContainer.setVisibility(View.VISIBLE);

                  _framePreviewImageView.setImageBitmap(
                      BitmapFactory.decodeByteArray(
                          _capturedImageBytes, 0, _capturedImageBytes.length));
                  _framePreviewImageView.setVisibility(View.VISIBLE);
                  _picReadyButton.setVisibility(View.GONE);
                }
              });

          try {
            _uploadingDialog =
                ProgressDialog.show(
                    PicTakerActivity.this,
                    "Uploading Frame",
                    "Uploading your frame to FT3D server.");
            uploadReturn.get();
          } catch (Exception e) {
            // Do we need to handle the specific timeout exception?
            e.printStackTrace();
          }
        }
  /** called with the connection token */
  void createToken(String result) {
    if (result == null) {
      return;
    }
    String token = LicodeConnector.decodeToken(result);
    if (token == null) {
      return;
    }

    try {
      mRemoteStream.clear();
      final JSONObject jsonToken = new JSONObject(token);
      String host = jsonToken.getString("host");
      if (!host.startsWith("http://")) {
        host = "http://" + host;
      }
      handleTokenRefresh(jsonToken);
      SocketIOClient.connect(
          AsyncHttpClient.getDefaultInstance(),
          host,
          new ConnectCallback() {
            @Override
            public void onConnectCompleted(Exception err, SocketIOClient client) {
              if (err != null) {
                err.printStackTrace();
                return;
              }

              try {
                // workaround - 2nd connection event
                JSONObject jsonParam = new JSONObject();
                jsonParam.put("reconnect", false);
                jsonParam.put("secure", jsonToken.getBoolean("secure"));
                jsonParam.put("force new connection", true);

                JSONArray arg = new JSONArray();
                arg.put(jsonParam);
                client.emit("connection", arg);
                log("Licode: Connection established!");
              } catch (JSONException e) {
                e.printStackTrace();
              }
              synchronized (mSocketLock) {
                mIoClient = client;
                client.on("onAddStream", mOnAddStream);
                client.on("onSubscribeP2P", mOnSubscribeP2P);
                client.on("onPublishP2P", mOnPublishP2P);
                client.on("onDataStream", mOnDataStream);
                client.on("onRemoveStream", mOnRemoveStream);
                client.on("disconnect", mDisconnect);
              }

              sendMessageSocket(
                  "token",
                  jsonToken,
                  new Acknowledge() {
                    @Override
                    public void acknowledge(JSONArray result) {
                      log("Licode: createToken -> connect");
                      log(result.toString());
                      try {
                        // ["success",{"maxVideoBW":300,"id":"5384684c918b864466c853d6","streams":[],"defaultVideoBW":300,"turnServer":{"password":"","username":"","url":""},"stunServerUrl":"stun:stun.l.google.com:19302"}]
                        // ["success",{"maxVideoBW":300,"id":"5384684c918b864466c853d6","streams":[{"data":true,"id":897203996079042600,"screen":"","audio":true,"video":true},{"data":true,"id":841680482029914900,"screen":"","audio":true,"video":true}],"defaultVideoBW":300,"turnServer":{"password":"","username":"","url":""},"stunServerUrl":"stun:stun.l.google.com:19302"}]
                        if ("success".equalsIgnoreCase(result.getString(0)) == false) {
                          return;
                        }

                        JSONObject jsonObject = result.getJSONObject(1);
                        parseVideoTokenResponse(result);

                        if (jsonObject.has("turnServer")) {
                          mTurnServer = jsonObject.getJSONObject("turnServer");
                          String url = mTurnServer.getString("url");
                          String usr = mTurnServer.getString("username");
                          String pwd = mTurnServer.getString("password");
                          if (!url.isEmpty()) {
                            mIceServers.add(new PeerConnection.IceServer(url, usr, pwd));
                          }
                        }
                        if (jsonObject.has("stunServerUrl")) {
                          mStunServerUrl = jsonObject.getString("stunServerUrl");
                          if (!mStunServerUrl.isEmpty()) {
                            mIceServers.add(new PeerConnection.IceServer(mStunServerUrl));
                          }
                        }
                        if (jsonObject.has("defaultVideoBW")) {
                          mDefaultVideoBW = jsonObject.getInt("defaultVideoBW");
                        }
                        if (jsonObject.has("maxVideoBW")) {
                          mMaxVideoBW = jsonObject.getInt("maxVideoBW");
                        }

                        mState = State.kConnected;

                        // update room id
                        mRoomId = jsonObject.getString("id");

                        for (RoomObserver obs : mObservers) {
                          obs.onRoomConnected(mRemoteStream);
                        }

                        // retrieve list of streams
                        JSONArray streams = jsonObject.getJSONArray("streams");
                        for (int index = 0, n = streams.length(); index < n; ++index) {
                          // {"data":true,"id":897203996079042600,"screen":"","audio":true,"video":true}
                          JSONObject arg = streams.getJSONObject(index);
                          StreamDescription stream = StreamDescription.parseJson(arg);
                          mRemoteStream.put(stream.getId(), stream);
                          triggerStreamAdded(stream);
                        }
                      } catch (JSONException e) {
                      }
                    }
                  });
            }
          });
    } catch (JSONException e) {
    }
  }
示例#9
0
文件: Ion.java 项目: nishant1286/ion
 /**
  * Get the AsyncServer reactor in use by this Ion instance
  *
  * @return
  */
 public AsyncServer getServer() {
   return httpClient.getServer();
 }
示例#10
0
文件: Ion.java 项目: nishant1286/ion
 private void addCookieMiddleware() {
   httpClient.insertMiddleware(cookieMiddleware = new CookieMiddleware(context, name));
 }