public int countImagesInSector(Sector sector, int levelNumber) {
    if (sector == null) {
      String msg = Logging.getMessage("nullValue.SectorIsNull");
      Logging.logger().severe(msg);
      throw new IllegalArgumentException(msg);
    }

    Level targetLevel = this.levels.getLastLevel();
    if (levelNumber >= 0) {
      for (int i = levelNumber; i < this.getLevels().getLastLevel().getLevelNumber(); i++) {
        if (this.levels.isLevelEmpty(i)) continue;

        targetLevel = this.levels.getLevel(i);
        break;
      }
    }

    // Collect all the tiles intersecting the input sector.
    LatLon delta = targetLevel.getTileDelta();
    Angle latOrigin = this.levels.getTileOrigin().getLatitude();
    Angle lonOrigin = this.levels.getTileOrigin().getLongitude();
    final int nwRow = Tile.computeRow(delta.getLatitude(), sector.getMaxLatitude(), latOrigin);
    final int nwCol = Tile.computeColumn(delta.getLongitude(), sector.getMinLongitude(), lonOrigin);
    final int seRow = Tile.computeRow(delta.getLatitude(), sector.getMinLatitude(), latOrigin);
    final int seCol = Tile.computeColumn(delta.getLongitude(), sector.getMaxLongitude(), lonOrigin);

    int numRows = nwRow - seRow + 1;
    int numCols = seCol - nwCol + 1;

    return numRows * numCols;
  }
  /**
   * Main Method
   *
   * @param args command line arguments
   */
  public static void main(String[] args) {
    // init logging
    try {
      Logging.init("lucane.log", "ALL");
    } catch (IOException ioe) {
      System.err.println("Unable to init logging, exiting.");
      System.exit(1);
    }

    Server server = null;
    ServerConfig config = null;

    try {
      config = new ServerConfig(CONFIG_FILE);
    } catch (Exception e) {
      Logging.getLogger().severe("Unable to read or parse the config file.");
      e.printStackTrace();
      System.exit(1);
    }

    // Server creation
    server = new Server(config);
    server.generateKeys();
    Logging.getLogger().info("Server is ready.");
    server.run();
  }
  /**
   * Creates a new Server object.
   *
   * @param sqlDriver JDBC driver
   * @param dbURL JDBC connection url
   * @param dbLogin database login
   * @param dbPasswd database password
   */
  private Server(ServerConfig config) {
    Server.instance = this;
    this.connections = new ArrayList();
    this.services = new ArrayList();
    this.port = config.getPort();
    this.socket = null;
    this.dbLayer = null;

    try {
      dbLayer = DatabaseAbstractionLayer.createLayer(config);
      Logging.getLogger().finer("dbLayer   : " + dbLayer);

      this.store = new Store(config);
    } catch (Exception ex) {
      Logging.getLogger().severe("#Err > Unable to connect to the database : " + ex.getMessage());
      ex.printStackTrace();
      System.exit(1);
    }

    try {
      this.serverIp = InetAddress.getLocalHost().getHostAddress();
      this.socket = new ServerSocket(this.port);
    } catch (IOException e) {
      Logging.getLogger().severe("#Err > Unable to listen on the port " + port + ".");
      e.printStackTrace();
      System.exit(1);
    }

    loadInternalServices();
  }
  public synchronized void logUnavailableHost(URL url) {
    if (this.offlineMode) return;

    if (url == null) {
      String message = Logging.getMessage("nullValue.URLIsNull");
      Logging.error(message);
      throw new IllegalArgumentException(message);
    }

    String hostName = url.getHost();
    HostInfo hi = this.hostMap.get(hostName);
    if (hi != null) {
      if (!hi.isUnavailable()) {
        hi.logCount.incrementAndGet();
        if (hi.isUnavailable()) // host just became unavailable
        this.firePropertyChange(NetworkStatus.HOST_UNAVAILABLE, null, url);
      }
      hi.lastLogTime.set(System.currentTimeMillis());
    } else {
      hi = new HostInfo(this.attemptLimit.get(), this.tryAgainInterval.get());
      hi.logCount.set(1);
      if (hi.isUnavailable()) // the attempt limit may be as low as 1, so handle that case here
      this.firePropertyChange(NetworkStatus.HOST_UNAVAILABLE, null, url);
      this.hostMap.put(hostName, hi);
    }

    this.lastUnavailableLogTime.set(System.currentTimeMillis());
  }
  /**
   * Resolves a reference to a local element identified by address and identifier, where {@code
   * linkBase} identifies a document, including the current document, and {@code linkRef} is the id
   * of the desired element.
   *
   * <p>If {@code linkBase} refers to a local COLLADA file and {@code linkRef} is non-null, the
   * return value is the element identified by {@code linkRef}. If {@code linkRef} is null, the
   * return value is a parsed {@link ColladaRoot} for the COLLADA file identified by {@code
   * linkBase}. Otherwise, {@code linkBase} is returned.
   *
   * @param linkBase the address of the document containing the requested element.
   * @param linkRef the element's identifier.
   * @return the requested element, or null if the element is not found.
   * @throws IllegalArgumentException if the address is null.
   */
  protected Object resolveLocalReference(String linkBase, String linkRef) {
    if (linkBase == null) {
      String message = Logging.getMessage("nullValue.DocumentSourceIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    try {
      File file = new File(linkBase);

      if (!file.exists()) return null;

      // Determine whether the file is a COLLADA document. If not, just return the file path.
      if (!WWIO.isContentType(file, ColladaConstants.COLLADA_MIME_TYPE))
        return file.toURI().toString();

      // Attempt to open and parse the COLLADA file.
      ColladaRoot refRoot = ColladaRoot.createAndParse(file);
      // An exception is thrown if parsing fails, so no need to check for null.

      // Add the parsed file to the session cache so it doesn't have to be parsed again.
      WorldWind.getSessionCache().put(linkBase, refRoot);

      // Now check the newly opened COLLADA file for the referenced item, if a reference was
      // specified.
      if (linkRef != null) return refRoot.getItemByID(linkRef);
      else return refRoot;
    } catch (Exception e) {
      String message =
          Logging.getMessage("generic.UnableToResolveReference", linkBase + "/" + linkRef);
      Logging.logger().warning(message);
      return null;
    }
  }
  public void setTryAgainInterval(long interval) {
    if (interval < 0) {
      String message = Logging.getMessage("NetworkStatus.InvalidTryAgainInterval");
      Logging.error(message);
      throw new IllegalArgumentException(message);
    }

    this.tryAgainInterval.set(interval);
  }
  /**
   * Specifies this shape's geographic position. The position's altitude is relative to this shape's
   * altitude mode.
   *
   * @param position this shape's geographic position.
   * @throws IllegalArgumentException if the position is null.
   */
  public void setPosition(Position position) {
    if (position == null) {
      String message = Logging.getMessage("nullValue.PositionIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    this.position = position;
  }
 /** Closes the event stream associated with this context's XML event reader. */
 protected void closeEventStream() {
   try {
     this.eventStream.close();
     this.eventStream = null;
   } catch (IOException e) {
     String message = Logging.getMessage("generic.ExceptionClosingXmlEventReader");
     Logging.logger().warning(message);
   }
 }
  public void setAttemptLimit(int limit) {
    if (limit < 1) {
      String message = Logging.getMessage("NetworkStatus.InvalidAttemptLimit");
      Logging.error(message);
      throw new IllegalArgumentException(message);
    }

    this.attemptLimit.set(limit);
  }
  /**
   * Create a new <code>ColladaRoot</code> for a {@link ColladaDoc} instance. A ColladaDoc
   * represents COLLADA files from either files or input streams.
   *
   * @param docSource the ColladaDoc instance representing the COLLADA document.
   * @throws IllegalArgumentException if the document source is null.
   * @throws IOException if an error occurs while reading the COLLADA document.
   */
  public ColladaRoot(ColladaDoc docSource) throws IOException {
    super(ColladaConstants.COLLADA_NAMESPACE);

    if (docSource == null) {
      String message = Logging.getMessage("nullValue.DocumentSourceIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    this.colladaDoc = docSource;
    this.initialize();
  }
  /**
   * Create a new <code>ColladaRoot</code> for a {@link URL}.
   *
   * @param docSource the URL of the document.
   * @throws IllegalArgumentException if the document source is null.
   * @throws IOException if an error occurs while reading the Collada document.
   */
  public ColladaRoot(URL docSource) throws IOException {
    super(ColladaConstants.COLLADA_NAMESPACE);

    if (docSource == null) {
      String message = Logging.getMessage("nullValue.DocumentSourceIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    URLConnection conn = docSource.openConnection();
    this.colladaDoc = new ColladaInputStream(conn.getInputStream(), WWIO.makeURI(docSource));

    this.initialize();
  }
  /** Generates server's keys for signature */
  public void generateKeys() {
    Logging.getLogger().info("Generating keypair");

    try {
      String[] pair = KeyGenerator.generateKeyPair();
      myConnectInfo =
          new ConnectInfo("server", this.serverIp, this.serverIp, this.port, pair[1], "Server");
      this.connections.add(myConnectInfo);
      this.signer = new Signer(pair[0]);
    } catch (SignatureException e) {
      Logging.getLogger().severe("Unable to generate keypair : " + e);
      System.exit(1);
    }
  }
  protected static AVList wmsGetParamsFromCapsDoc(Capabilities caps, AVList params) {
    if (caps == null) {
      String message = Logging.getMessage("nullValue.WMSCapabilities");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    if (params == null) {
      String message = Logging.getMessage("nullValue.LayerConfigParams");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    try {
      DataConfigurationUtils.getWMSLayerParams(caps, formatOrderPreference, params);
    } catch (IllegalArgumentException e) {
      String message = Logging.getMessage("WMS.MissingLayerParameters");
      Logging.logger().log(java.util.logging.Level.SEVERE, message, e);
      throw new IllegalArgumentException(message, e);
    } catch (WWRuntimeException e) {
      String message = Logging.getMessage("WMS.MissingCapabilityValues");
      Logging.logger().log(java.util.logging.Level.SEVERE, message, e);
      throw new IllegalArgumentException(message, e);
    }

    setFallbacks(params);

    // Setup WMS URL builder.
    params.setValue(AVKey.WMS_VERSION, caps.getVersion());
    params.setValue(AVKey.TILE_URL_BUILDER, new URLBuilder(params));
    // Setup default WMS tiled image layer behaviors.
    params.setValue(AVKey.USE_TRANSPARENT_TEXTURES, true);

    return params;
  }
  // TODO: Consider implementing this method using Android's ConnectivityManager
  public synchronized boolean isNetworkUnavailable(long checkInterval) {
    if (this.offlineMode) return true;

    // If there's been success since failure, network assumed to be reachable.
    if (this.lastAvailableLogTime.get() > this.lastUnavailableLogTime.get()) {
      this.lastNetworkUnavailableResult.set(false);
      return this.lastNetworkUnavailableResult.get();
    }

    long now = System.currentTimeMillis();

    // If there's been success recently, network assumed to be reachable.
    if (!this.lastNetworkUnavailableResult.get()
        && now - this.lastAvailableLogTime.get() < checkInterval) {
      return this.lastNetworkUnavailableResult.get();
    }

    // If query comes too soon after an earlier one that addressed the network, return the earlier
    // result.
    if (now - this.lastNetworkCheckTime.get() < checkInterval) {
      return this.lastNetworkUnavailableResult.get();
    }

    this.lastNetworkCheckTime.set(now);

    if (!this.isWorldWindServerUnavailable()) {
      this.lastNetworkUnavailableResult.set(false); // network not unreachable
      return this.lastNetworkUnavailableResult.get();
    }

    for (String testHost : networkTestSites) {
      if (isHostReachable(testHost)) {
        {
          this.lastNetworkUnavailableResult.set(false); // network not unreachable
          return this.lastNetworkUnavailableResult.get();
        }
      }
    }

    if (now - this.lastNetworkStatusReportTime.get() > NETWORK_STATUS_REPORT_INTERVAL) {
      this.lastNetworkStatusReportTime.set(now);
      String message = Logging.getMessage("NetworkStatus.NetworkUnreachable");
      Logging.info(message);
    }

    this.lastNetworkUnavailableResult.set(
        true); // if no successful contact then network is unreachable
    return this.lastNetworkUnavailableResult.get();
  }
  public WMSTiledImageLayer(String stateInXml) {
    this(wmsRestorableStateToParams(stateInXml));

    RestorableSupport rs;
    try {
      rs = RestorableSupport.parse(stateInXml);
    } catch (Exception e) {
      // Parsing the document specified by stateInXml failed.
      String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml);
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message, e);
    }

    this.doRestoreState(rs, null);
  }
    public void run() {
      if (Thread.currentThread().isInterrupted())
        return; // the task was cancelled because it's a duplicate or for some other reason

      try {
        this.placemark.retrieveModel(this.address);
      } catch (IOException e) {
        String message = Logging.getMessage("generic.ExceptionWhileReading", e.getMessage());
        Logging.logger().warning(message);
      } catch (XMLStreamException e) {
        String message =
            Logging.getMessage("generic.ExceptionAttemptingToParseXml", e.getMessage());
        Logging.logger().warning(message);
      }
    }
  /**
   * Resolves a reference to a local or remote file or element. If the link refers to an element in
   * the current document, this method returns that element. If the link refers to a remote
   * document, this method will initiate asynchronous retrieval of the document, and return a URL of
   * the downloaded document in the file cache, if it is available locally. If the link identifies a
   * COLLADA document, the document will be returned as a parsed ColladaRoot.
   *
   * @param link the address of the document or element to resolve. This may be a full URL, a URL
   *     fragment that identifies an element in the current document ("#myElement"), or a URL and a
   *     fragment identifier ("http://server.com/model.dae#myElement").
   * @return the requested element, or null if the element is not found.
   * @throws IllegalArgumentException if the address is null.
   */
  public Object resolveReference(String link) {
    if (link == null) {
      String message = Logging.getMessage("nullValue.DocumentSourceIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    try {
      String[] linkParts = link.split("#");
      String linkBase = linkParts[0];
      String linkRef = linkParts.length > 1 ? linkParts[1] : null;

      // See if it's a reference to an internal element.
      if (WWUtil.isEmpty(linkBase) && !WWUtil.isEmpty(linkRef)) return this.getItemByID(linkRef);

      // Interpret the path relative to the current document.
      String path = this.getSupportFilePath(linkBase);
      if (path == null) path = linkBase;

      // See if it's an already found and parsed COLLADA file.
      Object o = WorldWind.getSessionCache().get(path);
      if (o != null && o instanceof ColladaRoot)
        return linkRef != null ? ((ColladaRoot) o).getItemByID(linkRef) : o;

      URL url = WWIO.makeURL(path);
      if (url == null) {
        // See if the reference can be resolved to a local file.
        o = this.resolveLocalReference(path, linkRef);
      }

      // If we didn't find a local file, treat it as a remote reference.
      if (o == null) o = this.resolveRemoteReference(path, linkRef);

      if (o != null) return o;

      // If the reference was not resolved as a remote reference, look for a local element
      // identified by the
      // reference string. This handles the case of malformed internal references that omit the #
      // sign at the
      // beginning of the reference.
      return this.getItemByID(link);
    } catch (Exception e) {
      String message = Logging.getMessage("generic.UnableToResolveReference", link);
      Logging.logger().warning(message);
    }

    return null;
  }
  public boolean isLayerInView(DrawContext dc) {
    if (dc == null) {
      String message = Logging.getMessage("nullValue.DrawContextIsNull");
      Logging.logger().severe(message);
      throw new IllegalStateException(message);
    }

    if (dc.getView() == null) {
      String message = Logging.getMessage("layers.AbstractLayer.NoViewSpecifiedInDrawingContext");
      Logging.logger().severe(message);
      throw new IllegalStateException(message);
    }

    return !(dc.getVisibleSector() != null
        && !this.levels.getSector().intersects(dc.getVisibleSector()));
  }
  public MercatorTiledImageLayer(LevelSet levelSet) {
    if (levelSet == null) {
      String message = Logging.getMessage("nullValue.LevelSetIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    this.levels =
        new LevelSet(levelSet); // the caller's levelSet may change internally, so we copy it.

    this.createTopLevelTiles();

    this.setPickEnabled(
        false); // textures are assumed to be terrain unless specifically indicated otherwise.
    this.tileCountName = this.getName() + " Tiles";
  }
    /**
     * Construct a request task for a specified network link resource.
     *
     * @param placemark the placemark for which to construct the request task.
     * @param address the address of the resource to request.
     */
    protected RequestTask(KMLModelPlacemarkImpl placemark, String address) {
      if (placemark == null) {
        String message = Logging.getMessage("nullValue.ObjectIsNull");
        Logging.logger().severe(message);
        throw new IllegalArgumentException(message);
      }

      if (address == null) {
        String message = Logging.getMessage("nullValue.PathIsNull");
        Logging.logger().severe(message);
        throw new IllegalArgumentException(message);
      }

      this.placemark = placemark;
      this.address = address;
    }
  protected static AVList wmsGetParamsFromDocument(Element domElement, AVList params) {
    if (domElement == null) {
      String message = Logging.getMessage("nullValue.DocumentIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    if (params == null) params = new AVListImpl();

    LayerConfiguration.getWMSTiledImageLayerParams(domElement, params);
    BasicTiledImageLayer.getParamsFromDocument(domElement, params);

    params.setValue(AVKey.TILE_URL_BUILDER, new URLBuilder(params));

    return params;
  }
  /** Accepts connections */
  public void run() {
    Socket client = null;

    try {
      client = socket.accept();
      new Thread(this).start();
      getMessage(client);
    } catch (IOException ex) {
      Logging.getLogger().warning("#Err > Unable to accept connections.");
    }

    try {
      client.close();
    } catch (Exception ex) {
      Logging.getLogger().warning("#Err > Socket::close()");
    }
  }
  @Override
  public BufferedImage composeImageForSector(
      Sector sector,
      int canvasWidth,
      int canvasHeight,
      double aspectRatio,
      int levelNumber,
      String mimeType,
      boolean abortOnError,
      BufferedImage image,
      int timeout)
      throws Exception {
    if (sector == null) {
      String message = Logging.getMessage("nullValue.SectorIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    ComposeImageTile tile =
        new ComposeImageTile(
            sector, mimeType, this.getLevels().getLastLevel(), canvasWidth, canvasHeight);
    try {
      if (image == null)
        image = new BufferedImage(canvasWidth, canvasHeight, BufferedImage.TYPE_INT_RGB);

      downloadImage(tile, mimeType, timeout);
      Thread.sleep(1); // generates InterruptedException if thread has been interupted

      BufferedImage tileImage = ImageIO.read(tile.getFile());
      Thread.sleep(1); // generates InterruptedException if thread has been interupted

      ImageUtil.mergeImage(sector, tile.getSector(), aspectRatio, tileImage, image);
      Thread.sleep(1); // generates InterruptedException if thread has been interupted

      this.firePropertyChange(AVKey.PROGRESS, 0d, 1d);
    } catch (InterruptedIOException e) {
      throw e;
    } catch (Exception e) {
      if (abortOnError) throw e;

      String message = Logging.getMessage("generic.ExceptionWhileRequestingImage", tile.getPath());
      Logging.logger().log(java.util.logging.Level.WARNING, message, e);
    }

    return image;
  }
  /** Send the user list to all users */
  public void sendUserList() {
    String data = "";
    Socket sock = null;
    ObjectConnection oc = null;
    byte[] signature = {};

    /* receiver list */
    for (int i = 0; i < this.connections.size(); i++) {
      if (((ConnectInfo) this.connections.get(i)).type.equalsIgnoreCase("Client")) {
        data = "";

        /* users list */
        for (int j = 0; j < this.connections.size(); j++) {
          if (((ConnectInfo) this.connections.get(j)).type.equalsIgnoreCase("Client"))
            data = data + " " + ((ConnectInfo) this.connections.get(j)).getName();
        }

        try {
          sock =
              new Socket(
                  ((ConnectInfo) this.connections.get(i)).hostname,
                  ((ConnectInfo) this.connections.get(i)).port);
          oc = new ObjectConnection(sock);
          Message msg =
              new Message(
                  myConnectInfo,
                  (ConnectInfo) this.connections.get(i),
                  "Client",
                  "USER_LIST " + data);

          try {
            signature = this.signer.sign(msg);
          } catch (SignatureException e) {
            Logging.getLogger().warning("Unable to sign: " + e);
          }

          oc.write(msg);
          oc.write(signature);
          oc.close();
        } catch (IOException ex) {
          Logging.getLogger().warning("Unable to connect to host");
          continue;
        }
      }
    }
  }
  /**
   * Resolves a reference to a remote element identified by address and identifier, where {@code
   * linkBase} identifies a remote document, and {@code linkRef} is the id of the desired element.
   * This method retrieves resources asynchronously using the {@link
   * gov.nasa.worldwind.cache.FileStore}.
   *
   * <p>The return value is null if the file is not yet available in the FileStore. If {@code
   * linkBase} refers to a COLLADA file and {@code linkRef} is non-null, the return value is the
   * element identified by {@code linkRef}. If {@code linkBase} refers to a COLLADA file and {@code
   * linkRef} is null, the return value is a parsed {@link ColladaRoot} for the COLLADA file
   * identified by {@code linkBase}. Otherwise the return value is a {@link URL} to the file in the
   * file cache.
   *
   * @param linkBase the address of the document containing the requested element.
   * @param linkRef the element's identifier.
   * @return URL to the requested file, parsed ColladaRoot, or COLLADA element. Returns null if the
   *     document is not yet available in the FileStore.
   * @throws IllegalArgumentException if the {@code linkBase} is null.
   */
  public Object resolveRemoteReference(String linkBase, String linkRef) {
    if (linkBase == null) {
      String message = Logging.getMessage("nullValue.DocumentSourceIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    try {
      // See if it's in the cache. If not, requestFile will start another thread to retrieve it and
      // return null.
      URL url = WorldWind.getDataFileStore().requestFile(linkBase);
      if (url == null) return null;

      // It's in the cache. If it's a COLLADA file try to parse it so we can search for the
      // specified reference.
      // If it's not COLLADA, just return the url for the cached file.
      String contentType = WorldWind.getDataFileStore().getContentType(linkBase);
      if (contentType == null) {
        String suffix = WWIO.getSuffix(linkBase.split(";")[0]); // strip of trailing garbage
        if (!WWUtil.isEmpty(suffix)) contentType = WWIO.makeMimeTypeForSuffix(suffix);
      }

      if (!this.canParseContentType(contentType)) return url;

      // If the file is a COLLADA document, attempt to open it. We can't open it as a File with
      // createAndParse
      // because the ColladaRoot that will be created needs to have the remote address in order to
      // resolve any
      // relative references within it.
      ColladaRoot refRoot = this.parseCachedColladaFile(url, linkBase);

      // Add the parsed file to the session cache so it doesn't have to be parsed again.
      WorldWind.getSessionCache().put(linkBase, refRoot);

      // Now check the newly opened COLLADA file for the referenced item, if a reference was
      // specified.
      if (linkRef != null) return refRoot.getItemByID(linkRef);
      else return refRoot;
    } catch (Exception e) {
      String message =
          Logging.getMessage("generic.UnableToResolveReference", linkBase + "/" + linkRef);
      Logging.logger().warning(message);
      return null;
    }
  }
  public synchronized void logAvailableHost(URL url) {
    if (this.offlineMode) return;

    if (url == null) {
      String message = Logging.getMessage("nullValue.URLIsNull");
      Logging.error(message);
      throw new IllegalArgumentException(message);
    }

    String hostName = url.getHost();
    HostInfo hi = this.hostMap.get(hostName);
    if (hi != null) {
      this.hostMap.remove(hostName); // host is available again
      firePropertyChange(NetworkStatus.HOST_AVAILABLE, null, url);
    }

    this.lastAvailableLogTime.set(System.currentTimeMillis());
  }
  /**
   * Called just before the constructor returns. If overriding this method be sure to invoke <code>
   * super.initialize()</code>.
   *
   * @throws java.io.IOException if an I/O error occurs attempting to open the document source.
   */
  protected void initialize() throws IOException {
    this.eventStream = new BufferedInputStream(this.getColladaDoc().getInputStream());
    this.eventReader = this.createReader(this.eventStream);
    if (this.eventReader == null)
      throw new WWRuntimeException(
          Logging.getMessage("XML.UnableToOpenDocument", this.getColladaDoc()));

    this.parserContext = this.createParserContext(this.eventReader);
  }
  /** Loads internal services */
  private void loadInternalServices() {
    try {
      Iterator services;
      String servicename;
      String baseURL = System.getProperty("user.dir") + "/" + APPLICATIONS_DIRECTORY;

      LucaneClassLoader loader = LucaneClassLoader.getInstance();
      services = store.getServiceStore().getAllServices();

      while (services.hasNext()) {
        ServiceConcept service = (ServiceConcept) services.next();
        servicename = service.getName();
        try {
          loader.addUrl(new URL("jar:file:///" + baseURL + servicename + ".jar!/"));
          String className =
              (new JarFile(baseURL + servicename + ".jar"))
                  .getManifest()
                  .getMainAttributes()
                  .getValue("Service-Class");

          if (className == null) continue;

          Service serv = (Service) Class.forName(className, true, loader).newInstance();
          this.services.add(serv);
          serv.init(this);

          if (!service.isInstalled()) {
            serv.install();
            service.setInstalled();
            store.getServiceStore().updateService(service);
          }

          Logging.getLogger().info("Service '" + servicename + "' loaded.");
          this.connections.add(
              new ConnectInfo(servicename, serverIp, serverIp, port, "nokey", "service"));
        } catch (Exception e) {
          Logging.getLogger().warning("Unable to load service '" + servicename);
        }
      }
    } catch (Exception e) {
      Logging.getLogger().warning("Unable to load internal services : " + e);
      e.printStackTrace();
    }
  }
  private MercatorTextureTile[][] getTilesInSector(Sector sector, int levelNumber) {
    if (sector == null) {
      String msg = Logging.getMessage("nullValue.SectorIsNull");
      Logging.logger().severe(msg);
      throw new IllegalArgumentException(msg);
    }

    Level targetLevel = this.levels.getLastLevel();
    if (levelNumber >= 0) {
      for (int i = levelNumber; i < this.getLevels().getLastLevel().getLevelNumber(); i++) {
        if (this.levels.isLevelEmpty(i)) continue;

        targetLevel = this.levels.getLevel(i);
        break;
      }
    }

    // Collect all the tiles intersecting the input sector.
    LatLon delta = targetLevel.getTileDelta();
    Angle latOrigin = this.levels.getTileOrigin().getLatitude();
    Angle lonOrigin = this.levels.getTileOrigin().getLongitude();
    final int nwRow = Tile.computeRow(delta.getLatitude(), sector.getMaxLatitude(), latOrigin);
    final int nwCol = Tile.computeColumn(delta.getLongitude(), sector.getMinLongitude(), lonOrigin);
    final int seRow = Tile.computeRow(delta.getLatitude(), sector.getMinLatitude(), latOrigin);
    final int seCol = Tile.computeColumn(delta.getLongitude(), sector.getMaxLongitude(), lonOrigin);

    int numRows = nwRow - seRow + 1;
    int numCols = seCol - nwCol + 1;
    MercatorTextureTile[][] sectorTiles = new MercatorTextureTile[numRows][numCols];

    for (int row = nwRow; row >= seRow; row--) {
      for (int col = nwCol; col <= seCol; col++) {
        TileKey key =
            new TileKey(targetLevel.getLevelNumber(), row, col, targetLevel.getCacheName());
        Sector tileSector = this.levels.computeSectorForKey(key);
        MercatorSector mSector = MercatorSector.fromSector(tileSector); // TODO: check
        sectorTiles[nwRow - row][col - nwCol] =
            new MercatorTextureTile(mSector, targetLevel, row, col);
      }
    }

    return sectorTiles;
  }
  public boolean isHostUnavailable(URL url) {
    if (this.offlineMode) return true;

    if (url == null) {
      String message = Logging.getMessage("nullValue.URLIsNull");
      Logging.error(message);
      throw new IllegalArgumentException(message);
    }

    String hostName = url.getHost();
    HostInfo hi = this.hostMap.get(hostName);
    if (hi == null) return false;

    if (hi.isTimeToTryAgain()) {
      hi.logCount.set(0); // info removed from table in logAvailableHost
      return false;
    }

    return hi.isUnavailable();
  }