public JMXServiceURL getRemoteJMXURL() {
   try {
     if (mgmtProtocol.equals("http-remoting")) {
       return new JMXServiceURL(
           "service:jmx:remote+http://"
               + NetworkUtils.formatPossibleIpv6Address(mgmtAddress)
               + ":"
               + mgmtPort);
     } else if (mgmtProtocol.equals("https-remoting")) {
       return new JMXServiceURL(
           "service:jmx:remote+https://"
               + NetworkUtils.formatPossibleIpv6Address(mgmtAddress)
               + ":"
               + mgmtPort);
     } else {
       return new JMXServiceURL(
           "service:jmx:remoting-jmx://"
               + NetworkUtils.formatPossibleIpv6Address(mgmtAddress)
               + ":"
               + mgmtPort);
     }
   } catch (Exception e) {
     throw new RuntimeException("Could not create JMXServiceURL:" + this, e);
   }
 }
Example #2
0
  public static String replaceImageURLs(String content, final long entryId) {

    if (!TextUtils.isEmpty(content)) {
      boolean needDownloadPictures = NetworkUtils.needDownloadPictures();
      final ArrayList<String> imagesToDl = new ArrayList<>();

      Matcher matcher = IMG_PATTERN.matcher(content);
      while (matcher.find()) {
        String match = matcher.group(1).replace(" ", URL_SPACE);

        String imgPath = NetworkUtils.getDownloadedImagePath(entryId, match);
        if (new File(imgPath).exists()) {
          content = content.replace(match, "file://" + imgPath);
        } else if (needDownloadPictures) {
          imagesToDl.add(match);
        }
      }

      // Download the images if needed
      //			if (!imagesToDl.isEmpty()) {
      //				new Thread(new Runnable() {
      //					@Override
      //					public void run() {
      //						FetcherService.addImagesToDownload(String.valueOf(entryId), imagesToDl);
      //						Context context = MainApplication.getContext();
      //						context.startService(new Intent(context, FetcherService.class)
      //								.setAction(FetcherService.ACTION_DOWNLOAD_IMAGES));
      //					}
      //				}).start();
      //			}
    }

    return content;
  }
Example #3
0
  private String getBlobURL() {
    String blobUrl = "";
    HttpURLConnection httpUrlConnection = null;

    try {
      httpUrlConnection = (HttpURLConnection) new URL(Constants.UPLOAD_FORM_URL).openConnection();
      switch (httpUrlConnection.getResponseCode()) {
        case HttpURLConnection.HTTP_OK:
          InputStream in = new BufferedInputStream(httpUrlConnection.getInputStream());

          blobUrl = NetworkUtils.readStream(in);
          break;
        case HttpURLConnection.HTTP_NOT_FOUND:
          InputStream err = new BufferedInputStream(httpUrlConnection.getErrorStream());
          blobUrl = NetworkUtils.readStream(err);
          break;
      }
    } catch (MalformedURLException exception) {
      Log.e(TAG, "MalformedURLException");
    } catch (IOException exception) {
      Log.e(TAG, "IOException");
    } finally {
      if (null != httpUrlConnection) httpUrlConnection.disconnect();
    }
    return blobUrl;
  }
Example #4
0
 /**
  * Get the YahooWeather instance. Use this to query weather information from Yahoo.
  *
  * @param connectTimeout in milliseconds, 5 seconds in default
  * @param socketTimeout in milliseconds, 5 seconds in default
  * @param isDebbugable set if you want some debug log in Logcat
  * @return YahooWeather instance
  */
 public static YahooWeather getInstance(
     int connectTimeout, int socketTimeout, boolean isDebuggable) {
   YahooWeatherLog.setDebuggable(isDebuggable);
   NetworkUtils.getInstance().setConnectTimeout(connectTimeout);
   NetworkUtils.getInstance().setSocketTimeout(socketTimeout);
   return mInstance;
 }
  // TODO: needs to be InetAddress[]
  public InetAddress resolvePublishHostAddresses(String publishHosts[]) throws IOException {
    if (publishHosts == null) {
      if (GLOBAL_NETWORK_PUBLISHHOST_SETTING.exists(settings)
          || GLOBAL_NETWORK_HOST_SETTING.exists(settings)) {
        // if we have settings use them (we have a fallback to GLOBAL_NETWORK_HOST_SETTING inline
        publishHosts =
            GLOBAL_NETWORK_PUBLISHHOST_SETTING.get(settings).toArray(Strings.EMPTY_ARRAY);
      } else {
        // next check any registered custom resolvers
        for (CustomNameResolver customNameResolver : customNameResolvers) {
          InetAddress addresses[] = customNameResolver.resolveDefault();
          if (addresses != null) {
            return addresses[0];
          }
        }
        // we know it's not here. get the defaults
        publishHosts =
            GLOBAL_NETWORK_PUBLISHHOST_SETTING.get(settings).toArray(Strings.EMPTY_ARRAY);
      }
    }

    InetAddress addresses[] = resolveInetAddresses(publishHosts);
    // TODO: allow publishing multiple addresses
    // for now... the hack begins

    // 1. single wildcard address, probably set by network.host: expand to all interface addresses.
    if (addresses.length == 1 && addresses[0].isAnyLocalAddress()) {
      HashSet<InetAddress> all = new HashSet<>(Arrays.asList(NetworkUtils.getAllAddresses()));
      addresses = all.toArray(new InetAddress[all.size()]);
    }

    // 2. try to deal with some (mis)configuration
    for (InetAddress address : addresses) {
      // check if its multicast: flat out mistake
      if (address.isMulticastAddress()) {
        throw new IllegalArgumentException(
            "publish address: {"
                + NetworkAddress.format(address)
                + "} is invalid: multicast address");
      }
      // check if its a wildcard address: this is only ok if its the only address!
      // (if it was a single wildcard address, it was replaced by step 1 above)
      if (address.isAnyLocalAddress()) {
        throw new IllegalArgumentException(
            "publish address: {"
                + NetworkAddress.format(address)
                + "} is wildcard, but multiple addresses specified: this makes no sense");
      }
    }

    // 3. if we end out with multiple publish addresses, select by preference.
    // don't warn the user, or they will get confused by bind_host vs publish_host etc.
    if (addresses.length > 1) {
      List<InetAddress> sorted = new ArrayList<>(Arrays.asList(addresses));
      NetworkUtils.sortAddresses(sorted);
      addresses = new InetAddress[] {sorted.get(0)};
    }
    return addresses[0];
  }
 @Test
 public void testSimplify() throws IOException {
   final File expected = new File(RESOURCE_DIR + "simplified_network.psimi.xml");
   final File input = new File(RESOURCE_DIR + "unsimplified_network.psimi.xml");
   final File output = new File("simplifiednetwork.psimi.xml.tmp");
   output.deleteOnExit();
   NetworkPreparer prep = new NetworkPreparer();
   EntrySet entrySet = NetworkUtils.readNetwork(input);
   entrySet = prep.simplify(entrySet);
   NetworkUtils.writeNetwork(entrySet, output);
   assertTrue("Simplified file is wrong", FileUtils.contentEquals(expected, output));
   output.delete();
 }
 @Test
 public void testInitConfidence() {
   final File input = new File(RESOURCE_DIR + "before_init_conf.psimi.xml");
   NetworkPreparer prep = new NetworkPreparer();
   EntrySet entrySet = NetworkUtils.readNetwork(input);
   entrySet = prep.initConfidences(entrySet, "IamaLABEL", "andImaNAME", 0.2);
   File actual = new File("withinitconf.psimi.xml.tmp");
   actual.deleteOnExit();
   NetworkUtils.writeNetwork(entrySet, actual);
   final File expected = new File(RESOURCE_DIR + "after_init_conf.psimi.xml");
   boolean similar = TestUtils.compareXml(actual, expected);
   assertTrue("Graph is wrong", similar);
   actual.delete();
 }
 public static final class TcpSettings {
   public static final Setting<Boolean> TCP_NO_DELAY =
       Setting.boolSetting("network.tcp.no_delay", true, false, Setting.Scope.CLUSTER);
   public static final Setting<Boolean> TCP_KEEP_ALIVE =
       Setting.boolSetting("network.tcp.keep_alive", true, false, Setting.Scope.CLUSTER);
   public static final Setting<Boolean> TCP_REUSE_ADDRESS =
       Setting.boolSetting(
           "network.tcp.reuse_address",
           NetworkUtils.defaultReuseAddress(),
           false,
           Setting.Scope.CLUSTER);
   public static final Setting<ByteSizeValue> TCP_SEND_BUFFER_SIZE =
       Setting.byteSizeSetting(
           "network.tcp.send_buffer_size", new ByteSizeValue(-1), false, Setting.Scope.CLUSTER);
   public static final Setting<ByteSizeValue> TCP_RECEIVE_BUFFER_SIZE =
       Setting.byteSizeSetting(
           "network.tcp.receive_buffer_size", new ByteSizeValue(-1), false, Setting.Scope.CLUSTER);
   public static final Setting<Boolean> TCP_BLOCKING =
       Setting.boolSetting("network.tcp.blocking", false, false, Setting.Scope.CLUSTER);
   public static final Setting<Boolean> TCP_BLOCKING_SERVER =
       Setting.boolSetting(
           "network.tcp.blocking_server", TCP_BLOCKING, false, Setting.Scope.CLUSTER);
   public static final Setting<Boolean> TCP_BLOCKING_CLIENT =
       Setting.boolSetting(
           "network.tcp.blocking_client", TCP_BLOCKING, false, Setting.Scope.CLUSTER);
   public static final Setting<TimeValue> TCP_CONNECT_TIMEOUT =
       Setting.timeSetting(
           "network.tcp.connect_timeout",
           new TimeValue(30, TimeUnit.SECONDS),
           false,
           Setting.Scope.CLUSTER);
 }
  /**
   * Verifies connection by creating the API URL and testing a call via the client.
   *
   * @param v
   */
  protected void onHostVerifyButtonClicked(View v) {
    if (!NetworkUtils.isOnline(getActivity())) {
      InterfaceUtils.showAlert(
          getActivity(),
          R.string.sitewhere_no_network_message,
          R.string.sitewhere_no_network_title);
      return;
    }

    // Disable button until processing is complete.
    apiVerifyButton.setEnabled(false);

    String uri = apiUri.getText().toString();
    if (uri.length() == 0) {
      apiUri.setError("Enter a value for the remote SiteWhere server address.");
      apiVerifyGroup.setVisibility(View.GONE);
      return;
    }

    // Calculate API URL and create client for testing.
    String api = "http://" + uri + "/sitewhere/api/";
    apiVerifyMessage.setTextColor(Color.parseColor(SUCCESS_COLOR));
    apiVerifyMessage.setText("Verifying SiteWhere API available for URI: '" + api + "' ...");

    // Make the group visible.
    apiVerifyGroup.setVisibility(View.VISIBLE);
    apiVerifyProgress.setVisibility(View.VISIBLE);

    SiteWhereClient client = new SiteWhereClient(api, "admin", "password", 4000);
    executor.submit(new HostVerifier(client));
  }
  public static void main(String[] args) {
    String ip = NetworkUtils.getInterface();
    if (args.length == 1) {
      ip = args[0];
    }
    System.out.println("Using interface: " + ip);

    System.setProperty("jgroups.bind_addr", ip);
    Vertx.clusteredVertx(
        new VertxOptions().setClustered(true).setClusterHost(ip),
        ar -> {
          if (ar.failed()) {
            System.err.println("Cannot create vert.x instance : " + ar.cause());
          } else {
            Vertx vertx = ar.result();
            vertx
                .eventBus()
                .consumer(
                    "news",
                    message -> {
                      System.out.println(">> " + message.body());
                    });
          }
        });
  }
  private URI getBinding(final String protocol, final String socketBinding) {
    try {
      ModelNode address = new ModelNode();
      address.add("socket-binding-group", "*");
      final ModelNode socketBindingGroups = readResource(address);
      final String socketBindingGroupName =
          socketBindingGroups.asList().get(0).get("result").get("name").asString();
      final ModelNode operation = new ModelNode();
      operation.get(OP_ADDR).get("socket-binding-group").set(socketBindingGroupName);
      operation.get(OP_ADDR).get("socket-binding").set(socketBinding);
      operation.get(OP).set(READ_RESOURCE_OPERATION);
      operation.get("include-runtime").set(true);
      ModelNode binding = executeForResult(operation);
      String ip = binding.get("bound-address").asString();
      ip = formatIP(ip);

      final int port =
          defined(
                  binding.get("bound-port"),
                  socketBindingGroupName + " -> " + socketBinding + " -> bound-port is undefined")
              .asInt();

      return URI.create(protocol + "://" + NetworkUtils.formatPossibleIpv6Address(ip) + ":" + port);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  /**
   * Initializes and binds a socket that on a random port number. The method would try to bind on a
   * random port and retry 5 times until a free port is found.
   *
   * @return the socket that we have initialized on a randomport number.
   */
  private DatagramSocket initRandomPortSocket() {
    DatagramSocket resultSocket = null;
    String bindRetriesStr =
        NetaddrActivator.getConfigurationService().getString(BIND_RETRIES_PROPERTY_NAME);

    int bindRetries = 5;

    if (bindRetriesStr != null) {
      try {
        bindRetries = Integer.parseInt(bindRetriesStr);
      } catch (NumberFormatException ex) {
        logger.error(
            bindRetriesStr
                + " does not appear to be an integer. "
                + "Defaulting port bind retries to "
                + bindRetries,
            ex);
      }
    }

    int currentlyTriedPort = NetworkUtils.getRandomPortNumber();

    // we'll first try to bind to a random port. if this fails we'll try
    // again (bindRetries times in all) until we find a free local port.
    for (int i = 0; i < bindRetries; i++) {
      try {
        resultSocket = new DatagramSocket(currentlyTriedPort);
        // we succeeded - break so that we don't try to bind again
        break;
      } catch (SocketException exc) {
        if (exc.getMessage().indexOf("Address already in use") == -1) {
          logger.fatal(
              "An exception occurred while trying to create" + "a local host discovery socket.",
              exc);
          resultSocket = null;
          return null;
        }
        // port seems to be taken. try another one.
        logger.debug("Port " + currentlyTriedPort + " seems in use.");
        currentlyTriedPort = NetworkUtils.getRandomPortNumber();
        logger.debug("Retrying bind on port " + currentlyTriedPort);
      }
    }

    return resultSocket;
  }
  //	@Test
  public void testGetCcs() throws IOException {
    final File input = new File(RESOURCE_DIR + "simplified_network.psimi.xml");
    final File output = new File("cc.xml");
    output.deleteOnExit();
    final String expectedCcs = RESOURCE_DIR + "expected_ccs/";
    NetworkPreparer prep = new NetworkPreparer();
    EntrySet entrySet = NetworkUtils.readNetwork(input);
    List<EntrySet> ccs = prep.getConnnectedComponents(entrySet);

    assertEquals("Found the wrong number of connected components", 2, ccs.size());
    for (int i = 0; i < ccs.size(); i++) {
      NetworkUtils.writeNetwork(ccs.get(i), output);
      final File expectedCc = new File(expectedCcs + i + ".xml");
      boolean similar = TestUtils.compareXml(expectedCc, output);
      assertTrue("Connected component file " + i + " is wrong", similar);
      output.delete();
    }
  }
  public void start(final boolean localOnly, final boolean anyAddress) {
    log.info("Starting proxy on port: " + this.port);
    this.stopped.set(false);
    final HttpServerPipelineFactory factory =
        new HttpServerPipelineFactory(
            authenticationManager,
            this.allChannels,
            this.chainProxyManager,
            this.ksm,
            new DefaultRelayPipelineFactoryFactory(
                chainProxyManager,
                this.responseFilters,
                this.requestFilter,
                this.allChannels,
                timer),
            timer,
            this.clientChannelFactory,
            this.cacheManager);
    serverBootstrap.setPipelineFactory(factory);

    // Binding only to localhost can significantly improve the security of
    // the proxy.
    InetSocketAddress isa;
    if (localOnly) {
      isa = new InetSocketAddress("127.0.0.1", port);
    } else if (anyAddress) {
      isa = new InetSocketAddress(port);
    } else {
      try {
        isa = new InetSocketAddress(NetworkUtils.getLocalHost(), port);
      } catch (final UnknownHostException e) {
        log.error("Could not get local host?", e);
        isa = new InetSocketAddress(port);
      }
    }
    final Channel channel = serverBootstrap.bind(isa);
    allChannels.add(channel);

    Runtime.getRuntime()
        .addShutdownHook(
            new Thread(
                new Runnable() {
                  public void run() {
                    stop();
                  }
                }));

    /*
    final ServerBootstrap sslBootstrap = new ServerBootstrap(
        new NioServerSocketChannelFactory(
            newServerThreadPool(),
            newServerThreadPool()));
    sslBootstrap.setPipelineFactory(new HttpsServerPipelineFactory());
    sslBootstrap.bind(new InetSocketAddress("127.0.0.1", 8443));
    */
  }
  /** ensure specifying wildcard ipv4 address selects reasonable publish address */
  public void testPublishAnyLocalV4() throws Exception {
    InetAddress expected = null;
    try {
      expected = NetworkUtils.getFirstNonLoopbackAddresses()[0];
    } catch (Exception e) {
      assumeNoException("test requires up-and-running non-loopback address", e);
    }

    NetworkService service = new NetworkService(Settings.EMPTY);
    assertEquals(expected, service.resolvePublishHostAddress("0.0.0.0"));
  }
 public void removeDefaultRoute() {
   if (mInterfaceName != null && mDefaultRouteSet == true) {
     if (DBG) {
       Log.d(
           TAG,
           "removeDefaultRoute for " + mNetworkInfo.getTypeName() + " (" + mInterfaceName + ")");
     }
     NetworkUtils.removeDefaultRoute(mInterfaceName);
     mDefaultRouteSet = false;
   }
 }
  /**
   * Verifies MQTT connection by trying to establish a connection.
   *
   * @param v
   */
  protected void onMqttVerifyButtonClicked(View v) {
    if (!NetworkUtils.isOnline(getActivity())) {
      InterfaceUtils.showAlert(
          getActivity(),
          R.string.sitewhere_no_network_message,
          R.string.sitewhere_no_network_title);
      return;
    }

    // Disable button until processing is complete.
    mqttVerifyButton.setEnabled(false);

    String uri = mqttUri.getText().toString();
    if (uri.length() == 0) {
      mqttUri.setError("Enter a value for the remote MQTT broker address.");
      mqttVerifyGroup.setVisibility(View.GONE);
      return;
    }

    // Calculate API URL and create client for testing.
    String api = "http://" + uri;
    mqttVerifyMessage.setTextColor(Color.parseColor(SUCCESS_COLOR));
    mqttVerifyMessage.setText("Verifying MQTT broker available for URI: '" + api + "' ...");

    // Make the group visible.
    mqttVerifyGroup.setVisibility(View.VISIBLE);
    mqttVerifyProgress.setVisibility(View.VISIBLE);

    String mqttUriStr = mqttUri.getText().toString();
    String[] mqttParts = mqttUriStr.split("[:]+");
    String broker = null;
    int port = 1883;
    if (mqttParts.length > 0) {
      broker = mqttParts[0];
    }
    if (mqttParts.length > 1) {
      try {
        port = Integer.parseInt(mqttParts[1]);
      } catch (NumberFormatException e) {
        mqttVerifyMessage.setTextColor(Color.parseColor(ERROR_COLOR));
        mqttVerifyMessage.setText("Invalid MQTT broker port value.");
        return;
      }
    }

    if (broker == null) {
      mqttVerifyMessage.setTextColor(Color.parseColor(ERROR_COLOR));
      mqttVerifyMessage.setText("Invalid MQTT broker hostname.");
      return;
    }

    executor.submit(new MqttVerifier(broker, port));
  }
 public void addPrivateDnsRoutes() {
   if (DBG) {
     Log.d(
         TAG,
         "addPrivateDnsRoutes for "
             + this
             + "("
             + mInterfaceName
             + ") - mPrivateDnsRouteSet = "
             + mPrivateDnsRouteSet);
   }
   if (mInterfaceName != null && !mPrivateDnsRouteSet) {
     for (String addrString : getNameServers()) {
       int addr = NetworkUtils.lookupHost(addrString);
       if (addr != -1 && addr != 0) {
         if (DBG) Log.d(TAG, "  adding " + addrString + " (" + addr + ")");
         NetworkUtils.addHostRoute(mInterfaceName, addr);
       }
     }
     mPrivateDnsRouteSet = true;
   }
 }
 private static String buildImagePath(Image image, int width) {
   if (image.isHatchetImage()) {
     int imageSize = Math.min(image.getHeight(), image.getWidth());
     int actualWidth;
     if (NetworkUtils.isWifiAvailable()) {
       actualWidth = Math.min(imageSize, width);
     } else {
       actualWidth = Math.min(imageSize, width * 2 / 3);
     }
     return image.getImagePath() + "?width=" + actualWidth + "&height=" + actualWidth;
   }
   return image.getImagePath();
 }
  private SearchResult runGeneManiaAlgorithm()
      throws ApplicationException, DataStoreException, NoRelatedGenesInfoException {

    RelatedGenesEngineRequestDto request = createRequest();
    response = runQuery(request);

    EnrichmentEngineRequestDto enrichmentRequest = createEnrichmentRequest(response);
    EnrichmentEngineResponseDto enrichmentResponse = computeEnrichment(enrichmentRequest);

    SearchResult options =
        networkUtils.createSearchOptions(human, request, response, enrichmentResponse, data, genes);
    return options;
  }
Example #21
0
 private void initView() {
   Calendar customdate = dateutils.createCalendar(0, 20);
   long currentdate = dateutils.getCurrentTime();
   int afternums = 0;
   if (customdate.getTimeInMillis() > currentdate) {
     afternums = 1;
   }
   context = this.getActivity();
   // ********************************TODO   URL类型:批量生成多个图片URL地址.
   NetworkUtils network = NetworkUtils.getInstance(context);
   Log.i(
       ConfigConst.NOSETURLTAG, "********************:SimgFragment[111行]" + ConfigConst.NOSETURL);
   network.showToast("*******************SimgFragment[111行]" + ConfigConst.NOSETURL);
   // *******************************************
   if (mImgIds.size() == 0) {
     for (int i = 0; i < LOAD_IMAGE_SIZE; i++) {
       Calendar ca = dateutils.rollDate(new Date(), Calendar.DAY_OF_MONTH, (0 - (i + afternums)));
       String month = dateutils.getDate(ca.getTime(), DateUtils.DATE_FORMAT_YYMM);
       String nowdate = dateutils.getDate(ca.getTime(), DateUtils.DATE_FORMAT_YYYYMMDD);
       String url = "http://localhost/" + month + "/" + nowdate + ".jpg";
       if (!TextUtils.isEmpty(url) && !TextUtils.isEmpty(nowdate)) {
         mImgIds.add(new BingImages(url, nowdate, ""));
       }
       imgDates[i] = dateutils.getDate(ca.getTime(), DateUtils.DATE_FORMAT_X_YYYY_MM_DD);
     }
     mViewPager.setAdapter(customAdapter);
     mViewPager.addOnPageChangeListener(this);
     if (tvImgDate == null) {
       tvImgDate = (TextView) view.findViewById(R.id.tv_simg_date);
       tvImgDate.setText(imgDates[0]);
     }
     if (tvImgNumber == null) {
       tvImgNumber = (TextView) view.findViewById(R.id.tv_simg_number);
       tvImgNumber.setText(1 + "/" + LOAD_IMAGE_SIZE);
     }
   }
 }
Example #22
0
  private String getWeatherString(Context context, String woeidNumber) {
    YahooWeatherLog.d("query yahoo weather with WOEID number : " + woeidNumber);

    String qResult = "";
    String queryUrl = "http://weather.yahooapis.com/forecastrss?w=" + woeidNumber;

    YahooWeatherLog.d("query url : " + queryUrl);

    HttpClient httpClient = NetworkUtils.createHttpClient();

    HttpGet httpGet = new HttpGet(queryUrl);

    try {
      HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();

      if (httpEntity != null) {
        InputStream inputStream = httpEntity.getContent();
        Reader in = new InputStreamReader(inputStream);
        BufferedReader bufferedreader = new BufferedReader(in);
        StringBuilder stringBuilder = new StringBuilder();

        String readLine = null;

        while ((readLine = bufferedreader.readLine()) != null) {
          YahooWeatherLog.d(readLine);
          stringBuilder.append(readLine + "\n");
        }

        qResult = stringBuilder.toString();
      }

    } catch (ClientProtocolException e) {
      YahooWeatherLog.printStack(e);
      if (mExceptionListener != null) mExceptionListener.onFailConnection(e);
    } catch (ConnectTimeoutException e) {
      YahooWeatherLog.printStack(e);
      if (mExceptionListener != null) mExceptionListener.onFailConnection(e);
    } catch (SocketTimeoutException e) {
      YahooWeatherLog.printStack(e);
      if (mExceptionListener != null) mExceptionListener.onFailConnection(e);
    } catch (IOException e) {
      YahooWeatherLog.printStack(e);
      if (mExceptionListener != null) mExceptionListener.onFailConnection(e);
    } finally {
      httpClient.getConnectionManager().shutdown();
    }

    return qResult;
  }
Example #23
0
  /**
   * Use your device's GPS to automatically detect where you are, then query Yahoo weather apis for
   * weather information.
   *
   * @param context app's context
   * @param result A {@link WeatherInfo} instance
   */
  public void queryYahooWeatherByGPS(final Context context, final YahooWeatherInfoListener result) {
    YahooWeatherLog.d("query yahoo weather by gps, result=" + result);

    if (!NetworkUtils.isConnected(context)) {
      if (mExceptionListener != null) {
        mExceptionListener.onFailConnection(new Exception("Network is not avaiable"));
      }

      return;
    }

    mContext = context;
    mWeatherInfoResult = result;
    (new UserLocationUtils()).findUserLocation(context, this);
  }
    public void interfaceLinkStateChanged(String iface, boolean up) {
      if (mIface.equals(iface) && mLinkUp != up) {
        Log.d(TAG, "Interface " + iface + " link " + (up ? "up" : "down"));
        mLinkUp = up;

        // use DHCP
        if (up) {
          mTracker.reconnect();
        } else {
          NetworkUtils.stopDhcp(mIface);
          mTracker.mNetworkInfo.setIsAvailable(false);
          mTracker.mNetworkInfo.setDetailedState(DetailedState.DISCONNECTED, null, null);
        }
      }
    }
 private RelatedGenesEngineResponseDto runQuery(RelatedGenesEngineRequestDto request)
     throws DataStoreException {
   try {
     request.setProgressReporter(NullProgressReporter.instance());
     RelatedGenesEngineResponseDto result;
     result = mania.findRelated(request);
     request.setCombiningMethod(result.getCombiningMethodApplied());
     networkUtils.normalizeNetworkWeights(result);
     return result;
   } catch (ApplicationException e) {
     Logger logger = Logger.getLogger(getClass());
     logger.error("Unexpected error", e); // $NON-NLS-1$
     return null;
   }
 }
Example #26
0
 /**
  * Use a name of place to query Yahoo weather apis for weather information. Querying will be run
  * on a separated thread to accessing Yahoo's apis. When it is completed, a callback will be
  * fired. See {@link YahooWeatherInfoListener} for detail.
  *
  * @param context app's context
  * @param cityAreaOrLocation A city name, like "Shanghai"; an area name, like "Mountain View"; a
  *     pair of city and country, like "Tokyo, Japan"; a location or view spot, like "Eiffel
  *     Tower"; Yahoo's apis will find a closest position for you.
  * @param result A {@link WeatherInfo} instance.
  */
 public void queryYahooWeatherByPlaceName(
     final Context context,
     final String cityAreaOrLocation,
     final YahooWeatherInfoListener result) {
   YahooWeatherLog.d("query yahoo weather by name of place");
   mContext = context;
   if (!NetworkUtils.isConnected(context)) {
     if (mExceptionListener != null)
       mExceptionListener.onFailConnection(new Exception("Network is not avaiable"));
     return;
   }
   final String convertedlocation = AsciiUtils.convertNonAscii(cityAreaOrLocation);
   mWeatherInfoResult = result;
   final WeatherQueryByPlaceTask task = new WeatherQueryByPlaceTask();
   task.execute(new String[] {convertedlocation});
 }
Example #27
0
 /**
  * Use lat & lon pair to query Yahoo weather apis for weather information. Querying will be run on
  * a separated thread to accessing Yahoo's apis. When it is completed, a callback will be fired.
  * See {@link YahooWeatherInfoListener} for detail.
  *
  * @param context app's context
  * @param lat A string of latitude value
  * @param lon A string of longitude value
  * @param result A {@link WeatherInfo} instance
  */
 public void queryYahooWeatherByLatLon(
     final Context context,
     final String lat,
     final String lon,
     final YahooWeatherInfoListener result) {
   YahooWeatherLog.d("query yahoo weather by lat lon");
   mContext = context;
   if (!NetworkUtils.isConnected(context)) {
     if (mExceptionListener != null)
       mExceptionListener.onFailConnection(new Exception("Network is not avaiable"));
     return;
   }
   mWeatherInfoResult = result;
   final WeatherQueryByLatLonTask task = new WeatherQueryByLatLonTask();
   task.execute(new String[] {lat, lon});
 }
 public void addDefaultRoute() {
   if ((mInterfaceName != null) && (mDefaultGatewayAddr != 0) && mDefaultRouteSet == false) {
     if (DBG) {
       Log.d(
           TAG,
           "addDefaultRoute for "
               + mNetworkInfo.getTypeName()
               + " ("
               + mInterfaceName
               + "), GatewayAddr="
               + mDefaultGatewayAddr);
     }
     NetworkUtils.setDefaultRoute(mInterfaceName, mDefaultGatewayAddr);
     mDefaultRouteSet = true;
   }
 }
 public void removePrivateDnsRoutes() {
   // TODO - we should do this explicitly but the NetUtils api doesnt
   // support this yet - must remove all.  No worse than before
   if (mInterfaceName != null && mPrivateDnsRouteSet) {
     if (DBG) {
       Log.d(
           TAG,
           "removePrivateDnsRoutes for "
               + mNetworkInfo.getTypeName()
               + " ("
               + mInterfaceName
               + ")");
     }
     NetworkUtils.removeHostRoutes(mInterfaceName);
     mPrivateDnsRouteSet = false;
   }
 }
  // getSta(): 获取统计信息
  // 返回json(paytimes:消费次数,paycount:支付总额,incometimes:收入次数,incomecount:收入总额)
  public static String getStaResultForHttpGet() throws ClientProtocolException, IOException {
    String path = NetworkUtils.HostIP + "recharge/getSta.html";

    // http://open.zhizhi.com/recharge/getSta.html?amount=amount&code=code
    String uri = path;
    String result = "";
    HttpResponse response = NetworkUtils.getHttpResponseResultForHttpGet(uri);

    if (response.getStatusLine().getStatusCode() == 200) {
      HttpEntity entity = response.getEntity();
      result = EntityUtils.toString(entity, HTTP.UTF_8);
    } else {
      result = "error";
    }
    Log.i(TAG, "result=" + result);

    return result;
  }