/** 标准请求 */
  public void getDataByNet() {

    //        flag = true;
    // TODO 判断网络情况,1 是否能上网;2 是否是wifi 如果不是wifi就弹出对话框判断是否请求
    if (!NetUtils.hasConnectedNetwork()) {
      UIUtils.showToastSafe("无法连接网络");
      //            Toast.makeText(UIUtils.getContext(), "无法联网。。", Toast.LENGTH_LONG).show();
      return;
    } else if (!NetUtils.isWifiConnected()) {
      // 不是wifi
      AlertDialog.Builder builder = new AlertDialog.Builder(context);
      builder.setMessage("没有连接 WIFI 是否继续加载?");
      builder.setPositiveButton(
          "继续",
          new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
              // 请求
              get();
            }
          });
      builder.setNegativeButton("取消", null);
      builder.show();
    } else {
      // 是wifi,正常请求
      // 请求
      get();
    }
  }
  /**
   * spawn a thread to read in a torrent file
   *
   * <p>(called by ClientConnectionCallbackThread)
   */
  protected void getTorrent() {
    byte[] msg = new byte[12];

    NetUtils.intToBytes(MessageCode.SRV_READY_FOR_TORRENT.ordinal(), msg, 0);
    NetUtils.intToBytes(4, msg, 4);

    /** create a thread to listen */
    RecieveTorrentThread tfct = new RecieveTorrentThread(server, pw);

    int port = 0;
    if ((port = tfct.bind()) < 1) {
      if (Util.DEBUG) {
        System.err.println("getTorrent() couldn't grab a port!");
      }
      return;
    }

    NetUtils.intToBytes(port, msg, 8);

    new Thread(tfct).start();

    try {
      out.write(msg);
    } catch (IOException e) {
      ServerLog.log.log(Level.INFO, "Couldn't send getTorrents()", e);
    }
  }
  /** @see edu.iastate.cs309.comminterfaces.Client#torrentRemoved(int) */
  public void torrentRemoved(int refID) throws FailedMessageException {
    byte[] msg = new byte[12];

    NetUtils.intToBytes(MessageCode.SRV_TORREMOVED.ordinal(), msg, 0);
    NetUtils.intToBytes(4, msg, 4);
    NetUtils.intToBytes(refID, msg, 8);

    try {
      out.write(msg);
    } catch (Exception e) {
      ServerLog.log.log(Level.INFO, "Couldn't send torrentRemoved()", e);
    }
  }
  /**
   * @see
   *     edu.iastate.cs309.comminterfaces.Client#updateServerStatus(edu.iastate.cs309.communication.ServerProperties)
   */
  public void updateServerStatus(ServerProperties settings) throws FailedMessageException {
    try {
      byte[] raw = settings.toBytes();

      byte[] msg = new byte[8 + raw.length];
      NetUtils.intToBytes(MessageCode.SRV_CONFIG.ordinal(), msg, 0);
      NetUtils.intToBytes(raw.length, msg, 4);

      System.arraycopy(raw, 0, msg, 8, raw.length);
      out.write(msg);
    } catch (Exception e) {
      ServerLog.log.log(Level.INFO, "Couldn't send updateServerStatus()", e);
    }
  }
  /**
   * @see edu.iastate.cs309.comminterfaces.Client#updateTorrentProperties(int,
   *     edu.iastate.cs309.communication.TorrentProp)
   */
  public void updateTorrentProperties(int refID, TorrentProp info) throws FailedMessageException {
    try {
      byte[] raw = info.toBytes();

      byte[] msg = new byte[12 + raw.length];
      NetUtils.intToBytes(MessageCode.SRV_TORPROP.ordinal(), msg, 0);
      NetUtils.intToBytes(raw.length + 4, msg, 4);
      NetUtils.intToBytes(refID, msg, 8);

      System.arraycopy(raw, 0, msg, 12, raw.length);
      out.write(msg);
    } catch (Exception e) {
      ServerLog.log.log(Level.INFO, "Couldn't send updatePropInformation()", e);
    }
  }
 /** 获取验证码 */
 public static void getVerificationForPwd(
     Context context, String dri_tel, NetUtils.NetUtilsHandler handler) {
   HashMap<String, String> params = new HashMap<>();
   params.put("dri_tel", dri_tel);
   NetUtils.baseRequest(
       context, "driappconsultclientWeb/getVerificationForPwd", params, true, handler);
 }
  /**
   * 驾校信息
   *
   * @param campusId
   */
  public static void loadCampusState(
      Context context, String campusId, NetUtils.NetUtilsHandler handler) {

    HashMap<String, String> params = new HashMap<>();
    params.put("campusId", campusId);
    NetUtils.baseRequest(context, "driappcommentweb/loadCampusState", params, true, handler);
  }
 /** 给服务器传字符串 */
 public void pushString() {
   if (!NetUtils.hasConnectedNetwork()) {
     UIUtils.showToastSafe("无法连接网络");
     //            Toast.makeText(UIUtils.getContext(), "无法联网。。", Toast.LENGTH_LONG).show();
     return;
   }
   // 请求
   get();
 }
  /**
   * send a list refIDs down the pipe
   *
   * @param allTorrents list of torrents to sendd
   * @throws FailedSendMessageException
   */
  public void torrentList(List<Integer> allTorrents) throws FailedSendMessageException {
    int size = allTorrents.size();

    byte[] msg = new byte[size * 4 + 8];
    NetUtils.intToBytes(MessageCode.SRV_TORLIST.ordinal(), msg, 0);
    NetUtils.intToBytes(size * 4, msg, 4);

    int offset = 8;
    for (int i = 0; i < size; ++i) {
      NetUtils.intToBytes(allTorrents.get(i), msg, offset);
      offset += 4;
    }

    try {
      out.write(msg);
    } catch (IOException e) {
      ServerLog.log.log(Level.INFO, "Couldn't send torrentList()", e);
    }
  }
Exemple #10
0
 public Token(DataInputStream is) throws IOException {
   byte m = is.readByte();
   macBytes = new byte[6];
   is.read(macBytes);
   macAddr = NetUtils.macAddrFromBytes(macBytes);
   version = is.readInt();
   nDigits = is.readInt();
   digits = new byte[nDigits + Constants.N_DIGITS];
   is.read(digits, 0, nDigits);
 }
Exemple #11
0
 public Token(int version, byte[] macBytes, int nDigits, List<Byte> bytes) {
   this.version = version;
   this.macBytes = macBytes;
   this.nDigits = nDigits;
   digits = new byte[bytes.size() + Constants.N_DIGITS];
   for (int i = 0; i < bytes.size(); i++) {
     digits[i] = bytes.get(i);
   }
   macAddr = NetUtils.macAddrFromBytes(macBytes);
 }
  // TODO: Document this method.  It is very confusing and needs to be refactored.
  private void verifyImageCache(int pointID) {

    // On the server, images begin with 1, but here it's much easier to keep them 0 indexed.
    for (int i = 1; i <= mNumberOfImages; i++) {
      File imageFile = new File(DATA_FOLDER + pointID + "/" + (i - 1) + ".png");
      if (!imageFile.exists()) {
        NetUtils.DownloadFromUrl(
            WEB_FOLDER + pointID + "/" + i, (i - 1) + ".png", mGalleryImageFolder);
      }
    }
  }
Exemple #13
0
 public Token(byte arr[]) {
   macBytes = Arrays.copyOfRange(arr, 1, Constants.MAC_LEN + 1);
   macAddr = NetUtils.macAddrFromBytes(macBytes);
   int len = Constants.MAC_LEN + 1;
   ByteBuffer bbuf = ByteBuffer.wrap(arr, len, 4);
   version = bbuf.getInt();
   len += 4;
   bbuf = ByteBuffer.wrap(arr, len, 4);
   nDigits = bbuf.getInt();
   len += 4;
   digits = Arrays.copyOfRange(arr, len, len + nDigits);
 }
Exemple #14
0
  @Inject
  public JmxAgent(JmxConfig config) throws IOException {
    if (config.getRmiRegistryPort() == null) {
      registryPort = NetUtils.findUnusedPort();
    } else {
      registryPort = config.getRmiRegistryPort();
    }

    if (config.getRmiServerPort() == null) {
      serverPort = NetUtils.findUnusedPort();
    } else {
      serverPort = config.getRmiServerPort();
    }

    try {
      // This is how the jdk jmx agent constructs its url
      url = new JMXServiceURL("rmi", null, registryPort);
    } catch (MalformedURLException e) {
      // should not happen...
      throw new AssertionError(e);
    }
  }
  /**
   * 注册
   *
   * @param dri_pass_word 密码
   * @param dri_tel 电话号码
   * @param dri_invitation_code 验证码
   */
  public static void register(
      Context context,
      String dri_pass_word,
      String dri_tel,
      String dri_invitation_code,
      NetUtils.NetUtilsHandler handler) {

    HashMap<String, String> params = new HashMap<>();
    params.put("dri_pass_word", dri_pass_word);
    params.put("dri_tel", dri_tel);
    params.put("dri_invitation_code", dri_invitation_code);

    NetUtils.baseRequest(context, "save", params, true, handler);
  }
  /**
   * @see edu.iastate.cs309.comminterfaces.Client#updateTorrentInformation(int,
   *     edu.iastate.cs309.communication.TorrentInfo)
   */
  public void updateTorrentInformation(int refID, TorrentInfo info) throws FailedMessageException {
    byte[] raw;
    try {
      raw = info.toBytes();
      byte[] msg = new byte[12 + raw.length];
      NetUtils.intToBytes(MessageCode.SRV_TORINFO.ordinal(), msg, 0);
      NetUtils.intToBytes(raw.length + 4, msg, 4);
      NetUtils.intToBytes(refID, msg, 8);

      System.arraycopy(raw, 0, msg, 12, raw.length);
      out.write(msg);
    } catch (UnsupportedEncodingException e) {
      if (Util.DEBUG) {
        e.printStackTrace();
      }
    } catch (IOException e) {
      if (Util.DEBUG) {
        e.printStackTrace();
      }
    } catch (Exception e) {
      ServerLog.log.log(Level.INFO, "Couldn't send updateTorrentInformation()", e);
    }
  }
  @Test
  public void testGetAllNetworkInterface()
      throws UnknownHostException, UnsupportedEncodingException {
    List<NetworkInterface> nis = NetUtils.getAllNetworkInterface();
    StringBuffer t = new StringBuffer("all local networkInterface:\r\n");
    int i = 0;
    for (NetworkInterface ni : nis) {
      t.append("  " + (++i) + " name: " + (ni.getName() == null ? "null" : ni.getName()));
      if (ni.getDisplayName() != null) {
        t.append(" (" + ni.getDisplayName() + ")");
      }
      t.append("; addresses:");
      for (Enumeration<InetAddress> e = ni.getInetAddresses(); e.hasMoreElements(); ) {
        t.append("\n    " + e.nextElement());
      }
      t.append("\n");
    }

    System.out.println(t);
  }
  /**
   * Get dependencies in the topology for a given host
   *
   * @param name - host name for which we are getting dependency
   * @return a list of hosts dependent on the provided host name
   */
  @Override
  public List<String> getDependency(String name) {
    // normalize all input names to be in the form of IP addresses
    name = NetUtils.normalizeHostName(name);

    if (name == null) {
      return Collections.emptyList();
    }

    List<String> dependencies = dependencyCache.get(name);
    if (dependencies == null) {
      // not cached
      dependencies = getRawMapping().getDependency(name);
      if (dependencies != null) {
        dependencyCache.put(name, dependencies);
      }
    }

    return dependencies;
  }
  /**
   * @param parentFolder
   * @return 表示了下载的返回状态
   */
  private int downloadXiaomiAds(File parentFolder) {
    // TODO: Check wheter the ads already exists.
    int ret = NotifyAdsDef.RET_OK;
    NotifyAdsCell cell = (NotifyAdsCell) mAdsCell;
    String adsImage = cell.imgUrl;

    if (null == adsImage) return NotifyAdsDef.RET_ERROR;

    ret = DownloadUtils.downFile(mContext, parentFolder, adsImage, cell);
    LogUtils.logProcess("下载广告 imgUrl: " + adsImage + " 结果: " + ret);

    if (isCancelled() || ret != NotifyAdsDef.RET_OK) {
      if (isCancelled()) {
        LogUtils.logProcess("asynctask 被cancel");
      } else {
        NetState curState = NetUtils.getNetState(mContext);
        LogUtils.logProcess("网络类型改变,中断下载: " + curState + " " + ret);
      }
    }

    return ret;
  }
  /**
   * @param s newly connected socket from (hopefully) a client
   * @param callback object which will be called asynchonously as messages come in
   * @param pass password hash to authenticate with
   * @throws IOException
   */
  public ClientConnection(SSLSocket s, IServer callback, PasswordHash pass) throws IOException {
    if (pass == null) throw new NullPointerException("Seibert LIED TO ME!");
    /** unique id for this client connection */
    ID = claimID();

    pw = pass;
    server = callback;

    out = s.getOutputStream();
    InputStream in = s.getInputStream();

    /** authenticate */
    byte[] clientPwHash = new byte[20];
    NetUtils.readFully(in, clientPwHash, 0, 20);

    if (!(new PasswordHash(clientPwHash).equals(pw)))
      throw new SecurityException("Incorrect password recieved");

    ccct = new ClientConnectionCallbackThread(in, server, this, ID);

    /** start up the callback thread */
    new Thread(ccct).start();
  }
  /** 检查版本 */
  public void checkVersion(final boolean isFromSplash) {
    // boolean hasNetwork = NetUtils.hasNetwork(context);
    // if (!hasNetwork) {
    // Utils.showToast(context, "网络未连接,请检查后重试!");
    // return;
    // }
    LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
    map.put("versionCode", localVersionCode);
    NetUtils.startTask(
        new TaskListener() {

          @Override
          public void onError(int errorCode, String message) {
            intoApplication();
          }

          @Override
          public void onComplete(String resultstr) {
            ResultVo rVo = ResultParser.parseJSON(resultstr, ResultVo.class);
            if (rVo != null) {
              String result = rVo.getResult();
              if (!TextUtils.isEmpty(result) && "success".equals(result)) {
                AppInfoVo appInfoVO =
                    ResultParser.parseJSON(rVo.getMsg().toString(), AppInfoVo.class);
                int vCode = Integer.parseInt(appInfoVO.getVno());
                if (vCode > localVersionCode) {
                  String url = appInfoVO.getUrl();
                  if (!TextUtils.isEmpty(url)) {
                    apkUrl = url;
                    String content = appInfoVO.getRemark();
                    String isUpdate = appInfoVO.getIsUpdate();
                    boolean isForcedUpdate = false;
                    if (isUpdate != null && isUpdate.equals("1")) {
                      isForcedUpdate = true;
                    }
                    showCustomNoticeDialog(isFromSplash, content, isForcedUpdate);
                  }
                } else {
                  if (isFromSplash) {
                    // 如果不需要更新并且在加载界面则走正常进入app的流程
                    intoApplication();
                  } else {
                    // 不在加载界面才会提示
                    Utils.showToast(context, "当前已是最新版本");
                  }
                }
              } else {
                if (isFromSplash) {
                  intoApplication();
                }
              }
            }
          }

          @Override
          public void onCancel() {}
        },
        map,
        MarketApp.GET_VERSION,
        MarketApp.APP_INFO_SERVICE,
        TaskConstant.GET_DATA_30);
  }
Exemple #22
0
  /**
   * @param launchConfig
   * @param url
   * @param monitor
   * @param enableDebugging
   * @param browserLocation
   * @param browserName
   * @throws CoreException
   */
  private ListeningStream startNewBrowserProcess(
      DartLaunchConfigWrapper launchConfig,
      String url,
      IProgressMonitor monitor,
      boolean enableDebugging,
      IPath browserLocation,
      String browserName,
      StringBuilder argDescription)
      throws CoreException {

    Process process = null;
    monitor.worked(1);

    ProcessBuilder builder = new ProcessBuilder();
    Map<String, String> env = builder.environment();
    // Due to differences in 32bit and 64 bit environments, dartium 32bit launch does not work on
    // linux with this property.
    env.remove("LD_LIBRARY_PATH");

    // Add the environment variable DART_FLAGS="--enable-checked-mode"
    // to enable asserts and type checks
    if (launchConfig.getCheckedMode()) {
      env.put("DART_FLAGS", "--enable-checked-mode");
    }

    // Pass in --package-root if the preference is set
    String packageRoot = DartCore.getPlugin().getPackageRootPref();
    // TODO(keertip): if using default "packages" directory, do not set env variable
    // TODO(devoncarew): why are we only passing package root in when launching a file (not a url)?
    if (packageRoot != null && launchConfig.getShouldLaunchFile()) {
      try {
        String packageRootUri = getResourceServer().getUrlForFile(new Path(packageRoot).toFile());

        // Strip a trailing slash off the uri if the user setting didn't have one.
        if (!packageRoot.endsWith("/") && packageRootUri.endsWith("/")) {
          packageRootUri = packageRootUri.substring(0, packageRootUri.length() - 1);
        }

        env.put("DART_PACKAGE_ROOT", packageRootUri);
      } catch (IOException e) {
        DartDebugCorePlugin.logError(e);
      }
    }

    // This flag allows us to retrieve the dart: core sources from Dartium.
    env.put("DART_DEBUG_LIBS", "true");

    devToolsPortNumber = DEVTOOLS_PORT_NUMBER;

    if (enableDebugging) {
      devToolsPortNumber = NetUtils.findUnusedPort(DEVTOOLS_PORT_NUMBER);

      if (devToolsPortNumber == -1) {
        throw new CoreException(
            new Status(
                IStatus.ERROR,
                DartDebugCorePlugin.PLUGIN_ID,
                "Unable to locate an available port for the Dartium debugger"));
      }
    }

    List<String> arguments =
        buildArgumentsList(launchConfig, browserLocation, url, enableDebugging, devToolsPortNumber);
    builder.command(arguments);
    builder.directory(DartSdkManager.getManager().getSdk().getDartiumWorkingDirectory());
    builder.redirectErrorStream(true);

    describe(arguments, argDescription);

    try {
      process = builder.start();
    } catch (IOException e) {
      DartDebugCorePlugin.logError("Exception while starting Dartium", e);

      throw new CoreException(
          new Status(
              IStatus.ERROR,
              DartDebugCorePlugin.PLUGIN_ID,
              "Could not launch browser: " + e.toString()));
    }

    browserProcess = process;

    return readFromProcessPipes(browserName, browserProcess.getInputStream());
  }
  /**
   * tell the client that files are ready for pick up
   *
   * <p>spawns fileIndices.size() threads listening on the same number of ports
   *
   * <p>XXX: this method is too long
   *
   * @param refID torrent to request from
   * @param fileIndices list of file indices to transfer
   * @param data list of input streams
   * @throws FailedMessageException on failure to send message
   */
  public void transferFiles(int refID, List<Integer> fileIndices, List<InputStream> data)
      throws FailedMessageException {
    if (fileIndices.size() != data.size() || fileIndices.size() < 1)
      throw new FailedSendMessageException("passed bad data on transferFiles");

    if (Util.TDEBUG)
      System.out.println(
          "ClientConnect got request:\n\trefID: " + refID + "\n\tfileIndex" + fileIndices);

    int num = fileIndices.size();

    /** hopeful byte array */
    byte[] temp = new byte[12 + num * 8];

    /** set message id */
    NetUtils.intToBytes(MessageCode.SRV_FILE.ordinal(), temp, 0);

    /** set refID */
    NetUtils.intToBytes(refID, temp, 8);

    /** hopeful holder */
    Thread[] all = new Thread[num];

    int offset = 12;
    int count = 0;

    for (int i = 0; i < num; ++i) {
      SendFileThread ftt = new SendFileThread(refID, fileIndices.get(i), data.get(i), pw);
      int port = ftt.bind();

      /** if we got one, include this piece */
      if (port > 0) {
        NetUtils.intToBytes(fileIndices.get(i), temp, offset);
        NetUtils.intToBytes(port, temp, offset + 4);
        all[count] = new Thread(ftt);

        if (Util.DEBUG) System.out.println("Spawning SendFileThread");
        all[count].start();

        ++count;
        offset += 8;
      }
    }

    /** we didn't get any threads */
    if (offset == 12) throw new FailedMessageException("Couldn't spawn any SendFileThreads!");

    /** set actual length */
    byte[] msg = new byte[offset];
    System.arraycopy(temp, 0, msg, 0, offset);

    /** set size */
    NetUtils.intToBytes(offset - 8, msg, 4);

    try {
      out.write(msg);
    } catch (IOException e) {
      /** if we couldn't send the message, kill of the waiting threads */
      for (int i = 0; i < all.length; ++i) {
        if (all[i] != null) {
          all[i].interrupt();
        }
      }
    }
  }
 @Test
 public void testGetLocalIP() throws UnknownHostException {
   System.out.println("local hostIP=" + NetUtils.getLocalHostIP());
 }
 @Test
 public void testGetAllLocalIP() throws UnknownHostException {
   System.out.println(
       "all local ip:\r\n    "
           + StringUtils.arrayToDelimitedString(NetUtils.getAllLocalAddress(), "\r\n    "));
 }
 @Test
 public void testGetOuterNetIP() {
   System.out.println("OuterNetIP: " + NetUtils.getOuterNetIP());
 }