Exemplo n.º 1
0
 /** Sends the next speakable to Avatar. */
 private void sendNextSpeakable() {
   final QueuedSpeakable next = speakables.peek();
   final SpeakableText speakable = next.getSpeakable();
   final String utterance;
   final SsmlDocument document;
   if (speakable instanceof SpeakableSsmlText) {
     final SpeakableSsmlText ssml = (SpeakableSsmlText) speakable;
     document = ssml.getDocument();
     final Speak speak = document.getSpeak();
     utterance = speak.getTextContent();
   } else {
     utterance = speakable.getSpeakableText();
     document = null;
   }
   ErrorEvent error = null;
   try {
     final String bml = createBML(utterance, document);
     sendToAvatar(bml);
   } catch (SocketException e) {
     error = new BadFetchError(e.getMessage(), e);
   } catch (UnknownHostException e) {
     error = new BadFetchError(e.getMessage(), e);
   } catch (IOException e) {
     error = new BadFetchError(e.getMessage(), e);
   } catch (XMLStreamException e) {
     error = new BadFetchError(e.getMessage(), e);
   }
   if (error != null) {
     synchronized (listeners) {
       for (SynthesizedOutputListener listener : listeners) {
         listener.outputError(error);
       }
     }
   }
 }
  @Override
  public ILogin checkLogin(String usuario, String senha) {
    LoginImpl login = new LoginImpl();
    String hostname = JSFContextHelper.getContextParam("Authentication_hostname");
    String domain = JSFContextHelper.getContextParam("Authentication_domain");

    if (hostname == null) {
      login.setStatus(Status.FAIL);
      login.setMessage("Authentication_hostname não configurado no web.xml");
    } else if (domain == null) {
      login.setStatus(Status.FAIL);
      login.setMessage("Authentication_domain não configurado no web.xml");
    } else {
      UniAddress dc;
      try {
        dc = UniAddress.getByName(hostname);
        NtlmPasswordAuthentication auth =
            new NtlmPasswordAuthentication(domain + usuario + ":" + senha);
        SmbSession.logon(dc, auth);

        login.setLogin(usuario);
        login.setStatus(Status.SUCESS);
        login.setMessage("");
      } catch (UnknownHostException ex) {
        login.setStatus(Status.FAIL);
        login.setMessage(ex.getMessage());
      } catch (SmbException ex) {
        login.setStatus(Status.FAIL);
        login.setMessage(ex.getMessage());
      }
    }
    return login;
  }
Exemplo n.º 3
0
  /**
   * Resolve the host address property into a hostname. The mechanics of this are mostly
   * encapsulated in NetworkAddress
   *
   * @param prop the property value to base our lookup on (may be null)
   * @return the public address we found
   */
  private static String resolveAddress(String prop) {
    String hostAddress = null;

    try {
      hostAddress = NetworkAddress.getPrivateLocalAddress(prop).getHostAddress();

      if (prop == null || prop.length() == 0) {
        logger.info("Local address " + hostAddress + " was chosen from the list of interfaces");
      } else {
        logger.info("Local address " + hostAddress + " was determined by using " + prop);
      }

      return hostAddress;
    } catch (UnknownHostException e) {
      logger.log(Level.WARNING, "Unable to get Local address using " + prop, e);

      try {
        hostAddress = NetworkAddress.getPrivateLocalAddress().getHostAddress();
        logger.info(
            "chose private local address "
                + hostAddress
                + " from the list of interfaces: "
                + e.getMessage());
      } catch (UnknownHostException ee) {
        logger.log(
            Level.WARNING, "Unable to determine private " + "local address, using localhost", ee);

        hostAddress = "localhost";
      }
    }

    return hostAddress;
  }
Exemplo n.º 4
0
  private boolean connectSPPMon() {
    if (state == ConnectionEvent.CONNECTION_PENDING) {
      ExpCoordinator.print(
          new String("NCCPConnection(" + host + ", " + port + ").connect connection pending"), 0);
      while (state == ConnectionEvent.CONNECTION_PENDING) {
        try {
          Thread.sleep(500);
        } catch (java.lang.InterruptedException e) {
        }
      }
      return (isConnected());
    }

    state = ConnectionEvent.CONNECTION_PENDING;
    if (nonProxy != null) {
      try {
        nonProxy.connect();
      } catch (UnknownHostException e) {
        boolean rtn = informUserError("Don't know about host: " + host + ":" + e.getMessage());
        return rtn;
      } catch (SocketTimeoutException e) {
        boolean rtn = informUserError("Socket time out for " + host + ":" + e.getMessage());
        return rtn;
      } catch (IOException e) {
        boolean rtn = informUserError("Couldnt get I/O for " + host + ":" + e.getMessage());
        return rtn;
      }
    }
    return (isConnected());
  }
Exemplo n.º 5
0
  /** {@inheritDoc} */
  @Override
  public void open() {
    logger.debug("open(): Opening TCP Connection");

    try {
      tcpSocket = new Socket();
      SocketAddress TPIsocketAddress = new InetSocketAddress(ipAddress, tcpPort);
      tcpSocket.connect(TPIsocketAddress, connectTimeout);

      setInput(tcpSocket.getInputStream());
      setOutput(tcpSocket.getOutputStream());

      setReaderThread(new PowerMaxReaderThread(getInput(), this));
      getReaderThread().start();

      setConnected(true);
    } catch (UnknownHostException exception) {
      logger.debug("open(): Unknown Host Exception: {}", exception.getMessage());
      setConnected(false);
    } catch (SocketException socketException) {
      logger.debug("open(): Socket Exception: {}", socketException.getMessage());
      setConnected(false);
    } catch (IOException ioException) {
      logger.debug("open(): IO Exception: {}", ioException.getMessage());
      setConnected(false);
    } catch (Exception exception) {
      logger.debug("open(): Exception: {}", exception.getMessage());
      setConnected(false);
    }
  }
Exemplo n.º 6
0
  @Override
  public void run() {

    if (clientIP.length() > 0) {
      Integer portTo =
          Integer.parseInt(JRadiusConfigurator.getInstance().getProperty("send2ip_port"));

      if (JRadiusConfigurator.getInstance().getProperty("send_by_self").equals("enabled")) {

        Socket toServer;
        try {
          toServer = new Socket(clientIP, portTo);
          OutputStream serverOut = new BufferedOutputStream(toServer.getOutputStream());
          serverOut.write(message.getBytes());
          toServer.close();
        } catch (UnknownHostException e) {
          logger.error("Send2ip Unknown host error: " + e.getMessage());
        } catch (IOException e) {
          logger.error("Send2ip error: " + e.getMessage());
        }
      } else {
        try {
          String execStr = JRadiusConfigurator.getInstance().getProperty("send_program");
          execStr = String.format(execStr + " %s %s '%s'", clientIP, portTo, message);
          Process p = Runtime.getRuntime().exec(execStr);
          p.waitFor();
          logger.info("Execute send2ip program result: " + p.exitValue());
        } catch (Exception e) {
          logger.error("Error executing send2ip program: " + e.getMessage());
        }
      }
    }
  }
  public RConQueryThread(IServer par1IServer) {
    queryPort = ModuleSnooper.port;
    serverHostname = ModuleSnooper.hostname;
    serverPort = par1IServer.getPort();
    queryHostname = "0.0.0.0";
    server = par1IServer;

    if (0 != serverHostname.length() && !queryHostname.equals(serverHostname)) {
      queryHostname = serverHostname;
    } else {
      serverHostname = "0.0.0.0";

      try {
        InetAddress var2 = InetAddress.getLocalHost();
        queryHostname = var2.getHostAddress();
      } catch (UnknownHostException var3) {
        logWarning(
            "Unable to determine local host IP, please set server-ip/hostname in the snooper config : "
                + var3.getMessage());
      }
    }

    if (0 == queryPort) {
      queryPort = serverPort;
      logInfo("Setting default query port to " + queryPort);
    }

    field_72644_p = new HashMap();

    queryClients = new HashMap();
    time = (new Date()).getTime();
  }
Exemplo n.º 8
0
 /**
  * 获取本机ip
  *
  * @return
  */
 public static String GetIpAdd() {
   try {
     return InetAddress.getLocalHost().getHostAddress();
   } catch (UnknownHostException e) { // TODO 自动生成 catch 块
     return e.getMessage(); // e.printStackTrace();
   }
 }
Exemplo n.º 9
0
 /**
  * gets the time from the creeperhost servers
  *
  * @return - the time in the DDMMYY format
  */
 public static String getTime() {
   String content = null;
   Scanner scanner = null;
   int retries = 1;
   try {
     HttpURLConnection connection =
         (HttpURLConnection) new URL("http://repo.creeperhost.net/getdate").openConnection();
     while (connection.getResponseCode() != 200 && retries <= 3) {
       connection.disconnect();
       connection =
           (HttpURLConnection)
               new URL("http://repo" + retries + ".creeperhost.net/getdate").openConnection();
       retries++;
     }
     scanner = new Scanner(connection.getInputStream());
     scanner.useDelimiter("\\Z");
     content = scanner.next();
     connection.disconnect();
   } catch (java.net.UnknownHostException uhe) {
     Logger.logError(uhe.getMessage(), uhe);
   } catch (Exception ex) {
     Logger.logError(ex.getMessage(), ex);
   } finally {
     if (scanner != null) {
       scanner.close();
     }
   }
   return content;
 }
Exemplo n.º 10
0
 @Override
 protected PersistentLoginDTO doInBackground(Void... params) {
   BufferedReader reader = null;
   try {
     URL hwbotRanking = new URL(BenchService.SERVER + "/api/authenticate?token=" + token);
     reader = new BufferedReader(new InputStreamReader(hwbotRanking.openStream()));
     PersistentLoginDTO loginToken = new Gson().fromJson(reader, PersistentLoginDTO.class);
     // Log.i(this.getClass().getSimpleName(), "Token: " + loginToken);
     observer.notifyPersistentLoginOk(loginToken);
     return loginToken;
   } catch (UnknownHostException e) {
     Log.w(this.getClass().getSimpleName(), "No network access: " + e.getMessage());
     networkStatusAware.showNetworkPopupOnce();
   } catch (Exception e) {
     Log.i(this.getClass().getSimpleName(), "Error: " + e.getMessage());
     e.printStackTrace();
     observer.notifyPersistentLoginFailed("Login failed: " + e.getMessage());
   } finally {
     try {
       if (reader != null) {
         reader.close();
       }
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   return null;
 }
Exemplo n.º 11
0
 public static void main(String args[]) {
   int numMsg = Integer.parseInt(args[2]);
   // arguments supply message and hostname of destination
   Socket s = null;
   try {
     int serverPort = 7896;
     s = new Socket(args[1], serverPort);
     PrintWriter out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
     for (int i = 0; i < numMsg; i++) {
       out.println(Integer.toString(i) + " " + args[0]);
       out.flush();
     }
   } catch (UnknownHostException e) {
     System.out.println("Sock:" + e.getMessage());
   } catch (EOFException e) {
     System.out.println("EOF:" + e.getMessage());
   } catch (IOException e) {
     System.out.println("IO:" + e.getMessage());
   } finally {
     if (s != null)
       try {
         s.close();
       } catch (IOException e) {
         System.out.println("close:" + e.getMessage());
       }
   }
 }
Exemplo n.º 12
0
  @GET
  @Produces("application/json")
  @Path("/v1/json/providernumber/{number}")
  public Response getProviderByProviderId(@PathParam("id") Integer number) {
    long start = System.currentTimeMillis();

    try {
      Provider provider = getProviderService().getProviderByProviderId(number);
      if (provider != null) {
        ResponsePojo res = new ResponsePojo();
        res.setSuccess(true);
        res.setMessage("");
        res.setData(provider);
        long end = System.currentTimeMillis();
        res.setTimeInSecs(String.valueOf((end - start) / 1000));
        return Response.ok().entity(res).build();
      } else {
        ResponsePojo res = new ResponsePojo();
        res.setSuccess(false);
        res.setMessage("Provider not found with this provider number");
        long end = System.currentTimeMillis();
        res.setTimeInSecs(String.valueOf((end - start) / 1000));
        return Response.status(Response.Status.NOT_FOUND).entity(res).build();
      }
    } catch (UnknownHostException e) {
      e.printStackTrace();
      ResponsePojo res = new ResponsePojo();
      res.setSuccess(false);
      res.setMessage(e.getMessage());
      long end = System.currentTimeMillis();
      res.setTimeInSecs(String.valueOf((end - start) / 1000));
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(res).build();
    }
  }
Exemplo n.º 13
0
  public boolean isAllowed(HttpServletRequest request) {
    boolean allowed = hostAcl.shouldAllowAll();

    if (!allowed) {
      try {
        final InetAddress remoteClient = InetAddress.getByName(request.getRemoteHost());

        for (InetAddress allowedAddress : hostAcl.getAllowedHosts()) {
          if (remoteClient.equals(allowedAddress)) {
            allowed = true;
            break;
          }
        }
      } catch (UnknownHostException uhe) {
        LOG.error(
            "Unknown host exception caught while trying to resolve host: "
                + request.getRemoteHost()
                + " Reason: "
                + uhe.getMessage(),
            uhe);
      }
    }

    return allowed;
  }
Exemplo n.º 14
0
  @POST
  @Produces("application/json")
  @Consumes("application/json")
  @Path("/v1/json/{id}/addrating")
  public Response addRatingsForProvider(Rating rating, @PathParam("id") String id) {
    long start = System.currentTimeMillis();

    try {
      getProviderService().addRatingForProvider(id, rating);
      ResponsePojo res = new ResponsePojo();
      res.setSuccess(true);
      res.setMessage("");
      res.setData("Saved rating");
      long end = System.currentTimeMillis();
      res.setTimeInSecs(String.valueOf((end - start) / 1000));
      return Response.ok().entity(res).build();
    } catch (UnknownHostException e) {
      e.printStackTrace();
      ResponsePojo res = new ResponsePojo();
      res.setSuccess(false);
      res.setMessage(e.getMessage());
      long end = System.currentTimeMillis();
      res.setTimeInSecs(String.valueOf((end - start) / 1000));
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(res).build();
    }
  }
Exemplo n.º 15
0
  @GET
  @Produces("application/json")
  @Path("/v1/json/{id}/cities")
  public Response getCitiesForProvider(@PathParam("id") String id) {
    long start = System.currentTimeMillis();

    try {
      List<String> cities = getProviderService().getApplicableCitiesForProvider(id);
      if (cities != null) {
        ResponsePojo res = new ResponsePojo();
        res.setSuccess(true);
        res.setMessage("");
        res.setData(cities);
        long end = System.currentTimeMillis();
        res.setTimeInSecs(String.valueOf((end - start) / 1000));
        return Response.ok().entity(res).build();
      } else {
        ResponsePojo res = new ResponsePojo();
        res.setSuccess(false);
        res.setMessage("No Ratings for this provider yet");
        long end = System.currentTimeMillis();
        res.setTimeInSecs(String.valueOf((end - start) / 1000));
        return Response.status(Response.Status.NOT_FOUND).entity(res).build();
      }
    } catch (UnknownHostException e) {
      e.printStackTrace();
      ResponsePojo res = new ResponsePojo();
      res.setSuccess(false);
      res.setMessage(e.getMessage());
      long end = System.currentTimeMillis();
      res.setTimeInSecs(String.valueOf((end - start) / 1000));
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(res).build();
    }
  }
  public boolean connectToServer(String ip, String userName) {
    try {
      socket = new Socket(ip, 45322);
      lnOut("Connected to server!");
      ;
      streamFromServer = new DataInputStream(socket.getInputStream());
      streamToServer = new DataOutputStream(socket.getOutputStream());

      // With the connection established, create the server connection module.
      serverCon = new ServerConnection(this, streamToServer);
      // next start a thread that listens to incoming
      // messages from the game server via TCP.
      listener = new TCPListenerThread(this, client, streamFromServer);

      // finally send the requested user name to the server.
      streamToServer.write(userName.getBytes());
      return true;
    } catch (UnknownHostException e) {
      System.out.println("Don't know about host: " + ip);
      System.out.println(e.getMessage());
      return false;
    } catch (IOException e) {
      System.out.println("Couldn't get I/O for the connection to: " + ip);
      System.out.println(e.getMessage());
      return false;
    } catch (Exception e) {
      System.out.println(e.getMessage());
      return false;
    }
  }
Exemplo n.º 17
0
  /** @param args the command line arguments */
  public static void main(String[] args) {

    try {
      int randomNum = (int) ((Math.random() * 100) + 1);
      Socket server = new Socket("127.0.0.1", 8888);
      BufferedReader input = new BufferedReader(new InputStreamReader(server.getInputStream()));
      PrintWriter output = new PrintWriter(server.getOutputStream(), true);
      String leggi;
      int total = 0;
      output.println(randomNum);
      while ((leggi = input.readLine()) != null) {
        System.out.println("Valore letto: " + leggi);
        total += Integer.parseInt(leggi);
      }
      System.out.println("Somma dei valori ricevuti dal Server: " + total);
      if (total % 2 == 0) {
        System.out.println("PARI");
      } else {
        System.out.println("DISPARI");
      }

    } catch (UnknownHostException ex) {
      System.out.println("Errore indirizzo sconosciuto:" + ex.getMessage());
    } catch (IOException ex) {
      System.out.println(ex);
    }
  }
 public boolean canLoad(OWLOntologyDocumentSource documentSource) {
   if (documentSource.isReaderAvailable()) {
     return true;
   }
   if (documentSource.isInputStreamAvailable()) {
     return true;
   }
   if (parsableSchemes.contains(documentSource.getDocumentIRI().getScheme())) {
     return true;
   }
   // If we can open an input stream then we can attempt to parse the ontology
   // TODO: Take into consideration the request type!
   try {
     InputStream is = documentSource.getDocumentIRI().toURI().toURL().openStream();
     is.close();
     return true;
   } catch (UnknownHostException e) {
     logger.info("Unknown host: " + e.getMessage());
   } catch (MalformedURLException e) {
     logger.info("Malformed URL: " + e.getMessage());
   } catch (FileNotFoundException e) {
     logger.info("File not found: " + e.getMessage());
   } catch (IOException e) {
     logger.info("IO Exception: " + e.getMessage());
   }
   return false;
 }
Exemplo n.º 19
0
    private long getNextVertex(String graphID) {
      long result = -1;

      try {
        String response = "";

        out.println(VertexCounterProtocol.TICKET);
        out.flush();

        response = reader.readLine();

        if ((response != null) && (response.equals(VertexCounterProtocol.SEND))) {
          out.println(graphID); // Now we send the graph id
          out.flush();
        }

        response = reader.readLine();

        // This is the culprit that closs the socket
        //				if(response != null){
        //					out.close();
        //				}

        if (!response.contains(VertexCounterProtocol.ERROR)) {
          result = Long.parseLong(response);
        }
      } catch (UnknownHostException e) {
        Logger_Java.error(e.getMessage());
      } catch (IOException ec) {
        Logger_Java.error(ec.getMessage());
      }

      return result;
    }
Exemplo n.º 20
0
  /** Program Entry Point. */
  public static void main(String args[]) {

    // Set up log
    Log log = new Log();
    log.setLogName("Client");

    // Connection object listening on 4001
    Connection conn = new ConnectionImpl2(4001);
    InetAddress addr; // will hold address of host to connect to
    try {
      // get address of local host and connect
      addr = InetAddress.getLocalHost();
      conn.connect(addr, 5555);
      // send two messages to server
      conn.send("Client: Hello Server! Are you there?");
      conn.send("Client: Hi again!");
      // write a message in the log and close the connection
      Log.writeToLog("Client is now closing the connection!", "TestApplication");
      conn.close();
    } catch (ConnectException e) {
      Log.writeToLog(e.getMessage(), "TestApplication");
      e.printStackTrace();
    } catch (UnknownHostException e) {
      Log.writeToLog(e.getMessage(), "TestApplication");
      e.printStackTrace();
    } catch (IOException e) {
      Log.writeToLog(e.getMessage(), "TestApplication");
      e.printStackTrace();
    }

    System.out.println("CLIENT TEST FINISHED");
    Log.writeToLog("CLIENT TEST FINISHED", "TestApplication");
  }
  public Process(String name, int pid, int n) {

    this.name = name;
    this.port = Utils.REGISTRAR_PORT + pid;

    this.host = "UNKNOWN";
    try {
      this.host = (InetAddress.getLocalHost()).getHostName();

    } catch (UnknownHostException e) {
      String msg = String.format("Error: getHostName() failed at %s.", this.getInfo());
      System.err.println(msg);
      System.err.println(e.getMessage());
      System.exit(1);
    }

    this.pid = pid;
    this.n = n;

    random = new Random();

    /* Accepts connections from one of Registrar's worker threads */
    new Thread(new Listener(this)).start();
    /* Connect to registrar */
    socket = connect();
    init();
    Utils.out(pid, "Connected.");
  }
Exemplo n.º 22
0
  /**
   * Figures out whether the specified address resides within the specified address range.
   *
   * @param range: A range in notation address/netmask, for example 127.0.0.1/255.0.0.0
   * @param address: An address to be tested.
   * @return true if the address is within the range, false otherwise.
   */
  protected boolean isAddressInRange(String range, String address) throws ServletException {

    String network;
    String mask;

    int slashPos = range.indexOf('/');
    if (slashPos == -1) {
      network = range;
      mask = "255.255.255.255";
    } else {
      network = range.substring(0, slashPos);
      mask = range.substring(slashPos + 1);
    }

    try {
      byte[] netBytes = InetAddress.getByName(network).getAddress();
      byte[] maskBytes = InetAddress.getByName(mask).getAddress();
      byte[] addrBytes = InetAddress.getByName(address).getAddress();
      for (int i = 0; i < netBytes.length; i++) {
        if ((netBytes[i] & maskBytes[i]) != (addrBytes[i] & maskBytes[i])) return false;
      }

    } catch (UnknownHostException e) {
      // Should never happen, because we work with raw IP addresses, not
      // with host names.
      throw new ServletException(e.getMessage());
    }

    return true;
  }
Exemplo n.º 23
0
 /**
  * Checks the file for corruption.
  *
  * @param file - File to check
  * @return - boolean representing if it is valid
  * @throws IOException
  */
 public static boolean isValid(File file) throws IOException {
   String content = null;
   Scanner scanner = null;
   int retries = 1;
   try {
     HttpURLConnection connection =
         (HttpURLConnection)
             new URL("http://repo.creeperhost.net/md5/FTB2/" + file.getName()).openConnection();
     while (connection.getResponseCode() != 200 && retries <= 3) {
       connection.disconnect();
       connection =
           (HttpURLConnection)
               new URL("http://repo" + retries + ".creeperhost.net/md5/FTB2/" + file.getName())
                   .openConnection();
       retries++;
     }
     scanner = new Scanner(connection.getInputStream());
     scanner.useDelimiter("\\Z");
     content = scanner.next();
     connection.disconnect();
   } catch (java.net.UnknownHostException uhe) {
     Logger.logError(uhe.getMessage(), uhe);
   } catch (Exception ex) {
     Logger.logError(ex.getMessage(), ex);
   } finally {
     if (scanner != null) {
       scanner.close();
     }
   }
   String result = fileMD5(file);
   Logger.logInfo(result);
   return content.equalsIgnoreCase(result);
 }
Exemplo n.º 24
0
  // Print IP addresses and network interfaces
  private static void printIPAddresses() {
    try {
      InetAddress localhost = InetAddress.getLocalHost();
      System.out.println("Server: IP Address: " + localhost.getHostAddress());
      // Just in case this host has multiple IP addresses....
      InetAddress[] allMyIps = InetAddress.getAllByName(localhost.getCanonicalHostName());
      if (allMyIps != null && allMyIps.length > 1) {
        System.out.println("Server: Full list of IP addresses:");
        for (InetAddress allMyIp : allMyIps) {
          System.out.println("    " + allMyIp);
        }
      }
    } catch (UnknownHostException ex) {
      System.out.println("Server: Cannot get IP address of local host");
      System.out.println("Server: UnknownHostException: " + ex.getMessage());
    }

    try {
      System.out.println("Server: Full list of network interfaces:");
      for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
          en.hasMoreElements(); ) {
        NetworkInterface intf = en.nextElement();
        System.out.println("    " + intf.getName() + " " + intf.getDisplayName());
        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
            enumIpAddr.hasMoreElements(); ) {
          System.out.println("        " + enumIpAddr.nextElement().toString());
        }
      }
    } catch (SocketException ex) {
      System.out.println("Server: Cannot retrieve network interface list");
      System.out.println("Server: UnknownHostException: " + ex.getMessage());
    }
  }
  /** Initializes the query system by binding it to a port */
  private boolean initQuerySystem() {
    try {
      querySocket = new DatagramSocket(queryPort, InetAddress.getByName(serverHostname));
      registerSocket(querySocket);
      querySocket.setSoTimeout(500);
      return true;
    } catch (SocketException var2) {
      logWarning(
          "Unable to initialise query system on "
              + serverHostname
              + ":"
              + queryPort
              + " (Socket): "
              + var2.getMessage());
    } catch (UnknownHostException var3) {
      logWarning(
          "Unable to initialise query system on "
              + serverHostname
              + ":"
              + queryPort
              + " (Unknown Host): "
              + var3.getMessage());
    } catch (Exception var4) {
      logWarning(
          "Unable to initialise query system on "
              + serverHostname
              + ":"
              + queryPort
              + " (E): "
              + var4.getMessage());
    }

    return false;
  }
Exemplo n.º 26
0
  private boolean g() {
    try {
      this.socket = new DatagramSocket(this.bindPort, InetAddress.getByName(this.motd));
      this.a(this.socket);
      this.socket.setSoTimeout(500);
      return true;
    } catch (SocketException socketexception) {
      this.warning(
          "Unable to initialise query system on "
              + this.motd
              + ":"
              + this.bindPort
              + " (Socket): "
              + socketexception.getMessage());
    } catch (UnknownHostException unknownhostexception) {
      this.warning(
          "Unable to initialise query system on "
              + this.motd
              + ":"
              + this.bindPort
              + " (Unknown Host): "
              + unknownhostexception.getMessage());
    } catch (Exception exception) {
      this.warning(
          "Unable to initialise query system on "
              + this.motd
              + ":"
              + this.bindPort
              + " (E): "
              + exception.getMessage());
    }

    return false;
  }
Exemplo n.º 27
0
  private static boolean isLive(String aServer) {
    try {
      URL url = new URL(aServer + "health");
      HttpURLConnection uc = (HttpURLConnection) url.openConnection();

      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(BUNDLE.get("TC_STATUS_CHECK"), url);
      }

      if (uc.getResponseCode() == 200) {
        Document xml = new Builder().build(uc.getInputStream());
        Element response = (Element) xml.getRootElement();
        Element health = response.getFirstChildElement("health");
        String status = health.getValue();

        if (status.equals("dying") || status.equals("sick")) {
          if (LOGGER.isWarnEnabled()) {
            LOGGER.warn(BUNDLE.get("TC_SERVER_STATUS"), status);
          }

          return true;
        } else if (status.equals("ok")) {
          return true;
        } else {
          LOGGER.error(BUNDLE.get("TC_UNEXPECTED_STATUS"), status);
        }
      }
    } catch (UnknownHostException details) {
      LOGGER.error(BUNDLE.get("TC_UNKNOWN_HOST"), details.getMessage());
    } catch (Exception details) {
      LOGGER.error(details.getMessage());
    }

    return false;
  }
Exemplo n.º 28
0
        @Override
        public void validateValue(String hostAndPort) throws IllegalArgumentException {

          if ((hostAndPort == null) || (hostAndPort.length() == 0)) {
            throw new IllegalArgumentException("The value cannot be null or zero length: " + name);
          }
          int colonToken = hostAndPort.indexOf(":");
          String hostName = (colonToken >= 0) ? hostAndPort.substring(0, colonToken) : hostAndPort;
          ServerSocket testSocket = null;
          try {
            testSocket = new ServerSocket();
            /* The bind will fail if the hostName does not name this m/c.*/
            testSocket.bind(new InetSocketAddress(hostName, 0));
            testSocket.close();
          } catch (UnknownHostException e) {
            throw new IllegalArgumentException(
                "Property: " + name + "Invalid hostname: " + e.getMessage());
          } catch (IOException e) {

            /*
             * Server socket could not be bound to any port. Hostname is
             * not associated with this m/c.
             */
            throw new IllegalArgumentException(
                "Invalid hostname: "
                    + hostName
                    + " The host name is not associated with this machine.");
          }

          if (colonToken >= 0) {
            validatePort(hostAndPort.substring(colonToken + 1));
          }
        }
  protected void validate() {
    // TODO Validation
    if (folder.getSelectionIndex() == 0) {
      name = nameText.getText();
      userName = userNameText.getText();
      password = passwordText.getText();
      if (hostText.getText().equals(_BLANK_)) {
        showError(Messages.DefaultConnectionWizardPage_Blank_Invalid);
        return;
      }
      try {
        InetAddress.getByName(hostText.getText());
      } catch (UnknownHostException e) {
        showError(e.getMessage());
        return;
      }
      String host = hostText.getText();
      if (portText.getText().equals(_BLANK_)) {
        showError(Messages.DefaultConnectionWizardPage_Blank_Invalid);
        return;
      }
      int port;
      try {
        port = Integer.parseInt(portText.getText());
        if (port < 1 || port > 0xffff) {
          throw new NumberFormatException();
        }
      } catch (NumberFormatException e) {
        showError(e.getMessage());
        return;
      }
      url = SIMPLE_PREFIX + host + ":" + port + SIMPLE_SUFFIX; // $NON-NLS-1$
    } else if (folder.getSelectionIndex() == 1) {
      name = advancedNameText.getText();
      userName = advancedUserNameText.getText();
      password = advancedPasswordText.getText();

      if (urlText.getText().equals(_BLANK_)) {
        showError(Messages.DefaultConnectionWizardPage_Blank_Invalid);
        return;
      }
      url = urlText.getText();
    }

    // now validate name
    if (name == null || nameTaken(name)) {
      showError(Messages.DefaultConnectionWizardPage_Name_In_Use);
      return;
    }

    try {
      getConnection();
    } catch (CoreException ce) {
      showError(ce.getMessage());
      return;
    }

    clearMessage();
  }
Exemplo n.º 30
0
 /**
  * Gets the next token from a tokenizer and converts it to an IP Address.
  *
  * @param family The address family.
  * @return The next token in the stream, as an InetAddress
  * @throws TextParseException The input was invalid or not a valid address.
  * @throws IOException An I/O error occurred.
  * @see Address
  */
 public InetAddress getAddress(int family) throws IOException {
   String next = _getIdentifier("an address");
   try {
     return Address.getByAddress(next, family);
   } catch (UnknownHostException e) {
     throw exception(e.getMessage());
   }
 }