コード例 #1
0
  /**
   * @param IPv4to
   * @param Port
   * @param back
   */
  public static synchronized void arrangePort(String IPv4to, String Port, boolean back) {
    try {
      boolean kicked = CheckKicked.checkKicked();
      if (kicked) {
        outMsg.print(
            "(Interface - FileCreate) : " + "Network Offline or You get Kicked from Network", 3);
      } else if (PingServer.PingServer(IPv4to) == false) {
        outMsg.print("(Dynamic Ports) IP " + IPv4to + "zur Zeit nicht erreichbar!", 3);
      } else {
        /** interface to create a file */
        String doWhat = "arrangePort";
        /** arguments needed */
        String[] args = new String[4];

        if (!back) {
          args[0] = IPv4to;
          args[1] = Config.getCurrentIp();
        } else {
          args[0] = Config.getCurrentIp();
          args[1] = IPv4to;
        }
        args[2] = getIdentbyString(args[1]) + "." + Port;
        args[3] = doWhat;

        StartClientServer.startClient(args);
      }
    } catch (UnknownHostException ex) {
      outMsg.print("(Dynamic Ports) " + ex.toString(), 3);
    }
  }
コード例 #2
0
ファイル: Barrier.java プロジェクト: snowmanxxf/h2rdf
  /**
   * Barrier constructor
   *
   * @param address
   * @param root
   * @param size
   */
  Barrier(String address, String root, int size) {
    super(address);
    this.input = input;
    this.size = size;

    // Create barrier node
    if (zk != null) {
      try {
        Stat s = zk.exists(root, false);
        if (s == null) {
          zk.create(input, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
      } catch (KeeperException e) {
        System.out.println("Keeper exception when instantiating queue: " + e.toString());
      } catch (InterruptedException e) {
        System.out.println("Interrupted exception");
      }
    }

    // My node name
    try {
      name = new String(InetAddress.getLocalHost().getCanonicalHostName().toString());
    } catch (UnknownHostException e) {
      System.out.println(e.toString());
    }
  }
コード例 #3
0
 String getLocalIPAddr() {
   if (localAddr == null) {
     try {
       IPAddr localHost = IPAddr.getLocalHost();
       localAddr = localHost.getHostAddress();
     } catch (UnknownHostException e) {
       // shouldn't happen
       log.error("LockssServlet: getLocalHost: " + e.toString());
       return "???";
     }
   }
   return localAddr;
 }
コード例 #4
0
  private boolean compareHosts(GeneralName generalName, String hostname) {
    try {
      if (generalName.getType() == GeneralNameInterface.NAME_DNS) {
        String name = generalName.toString();
        name = name.substring(name.indexOf(':') + 1).trim();
        return InetAddress.getByName(name).equals(InetAddress.getByName(hostname));
      }
    } catch (UnknownHostException e) {
      if (debug.messageEnabled()) {
        debug.message(e.toString());
      }
    }

    return false;
  }
コード例 #5
0
 public void envoyerMessage(byte[] msg) {
   try {
     if (requestSocket.isConnected()) {
       Log.d("Client", "Element envoyé");
       dos.writeInt(512);
       dos.write(msg, 0, 512);
     }
   } catch (UnknownHostException e) {
     Log.d("Deconnection", "Serveur Inconnue");
     this.etatConnection = false;
     Log.d("Description", e.toString());
     e.printStackTrace();
   } catch (IOException e) {
     Log.d("Deconnection", "Erreur Socket");
     this.etatConnection = false;
     Log.d("Descritpion", e.toString());
     e.printStackTrace();
   }
 }
コード例 #6
0
 public void envoyerMessage(byte msg) {
   try {
     if (requestSocket.isConnected()) {
       byte[] tab = new byte[1];
       tab[0] = msg;
       dos.writeInt(1);
       dos.write(tab, 0, 1);
     }
   } catch (UnknownHostException e) {
     Log.d("Deconnection", "Serveur Inconnue");
     this.etatConnection = false;
     Log.d("Description", e.toString());
     e.printStackTrace();
   } catch (IOException e) {
     Log.d("Deconnection", "Erreur Socket");
     this.etatConnection = false;
     Log.d("Descritpion", e.toString());
     e.printStackTrace();
   }
 }
コード例 #7
0
 public void run() {
   try {
     Log.d("TCP", "准备连接");
     InetAddress serverAddr = InetAddress.getByName("192.168.1.101"); // TCP服务器IP地址
     socket = new Socket(serverAddr, 9091);
     Log.d("TCP", "服务器:正在连接...");
     OutputStream out = socket.getOutputStream();
     String msg = "Hello World123";
     out.write(msg.getBytes());
     Log.d("TCP", "success");
     socket.close();
   } catch (UnknownHostException e) {
     // TODO 自动生成的 catch 块
     e.printStackTrace();
     Log.e("TCP 3333", "ERROR:" + e.toString());
   } catch (IOException e) {
     // TODO 自动生成的 catch 块
     e.printStackTrace();
     Log.e("TCP 4444", "ERROR:" + e.toString());
   }
 }
コード例 #8
0
 public void envoyerMessage() {
   try {
     if (requestSocket.isConnected()) {
       // Log.d("Client","Element envoyé");
       // this.dos.writeInt(512);
       this.dos.write(this.tabEntier, 0, 512);
     } else {
       Log.d("Client", "Deconnecter");
       // new Exception() ;
     }
   } catch (UnknownHostException e) {
     Log.d("Client", "Erreur Serveur Introuvable");
     Log.d("Descritpion", e.toString());
     this.etatConnection = false;
     e.printStackTrace();
   } catch (IOException e) {
     Log.d("Client", "Erreur d'envoi");
     this.etatConnection = false;
     Log.d("Descritpion", e.toString());
   }
 }
コード例 #9
0
ファイル: ReplicaManagerX.java プロジェクト: DLMSXXX/DLMS
    @Override
    public void run() {
      try {
        DatagramSocket clientSocket = new DatagramSocket();
        InetAddress IPAddress = InetAddress.getByName("localhost");
        byte[] sendData = new byte[1024];

        sendData = content.getBytes();

        DatagramPacket sendPacket =
            new DatagramPacket(sendData, sendData.length, IPAddress, otherBankPort);
        clientSocket.send(sendPacket);
        clientSocket.close();

      } catch (SocketException ex) {
        System.out.println(ex.toString());
      } catch (UnknownHostException ex) {
        System.out.println(ex.toString());
      } catch (IOException ex) {
        System.out.println(ex.toString());
      }
    }
コード例 #10
0
 /** Open the connection to the given url, using a proxy. */
 public void open(String url, ProxyConfig proxyConfig) throws IOException {
   URL u;
   try {
     Proxy proxy = ProxyFactory.createProxyInstance(proxyConfig);
     // On Android there are networks errors if the keep Alive is left
     // enabled. Especially in https. For this reason we turn the flag
     // off, as it seems a platform bug.
     System.setProperty("http.keepAlive", "false");
     u = new URL(url);
     if (proxy != null) {
       conn = (HttpURLConnection) u.openConnection(proxy);
     } else {
       conn = (HttpURLConnection) u.openConnection();
     }
     conn.setDoOutput(true);
   } catch (MalformedURLException e) {
     Log.error(TAG_LOG, "Invalid url: " + url, e);
     throw new IllegalArgumentException(e.toString());
   } catch (UnknownHostException e) {
     Log.error(TAG_LOG, "Unknown host exception", e);
     throw new ConnectionNotFoundException(e.toString());
   }
 }
コード例 #11
0
 @JsonCreator
 public KafkaSplit(
     @JsonProperty("clientId") String clientId,
     @JsonProperty("topicName") String topicName,
     @JsonProperty("partitionId") int partitionId,
     @JsonProperty("brokerHost") String brokerHost,
     @JsonProperty("brokerPort") int brokerPort,
     @JsonProperty("sampleRate") int sampleRate,
     @JsonProperty("startTs") long startTs,
     @JsonProperty("endTs") long endTs,
     @JsonProperty("zookeeper") String zookeeper,
     @JsonProperty("zkSessionTimeout") int zkSessionTimeout,
     @JsonProperty("zkConnectTimeout") int zkConnectTimeout) {
   checkNotNull(clientId, "clientId is null");
   checkNotNull(topicName, "topicName is null");
   checkNotNull(partitionId, "partitionId is null");
   checkNotNull(startTs, "startTs is null");
   checkNotNull(endTs, "endTs is null");
   this.clientId = clientId;
   this.topicName = topicName;
   this.partitionId = partitionId;
   this.brokerHost = brokerHost;
   this.brokerPort = brokerPort;
   this.sampleRate = sampleRate;
   this.startTs = startTs;
   this.endTs = endTs;
   this.zookeeper = zookeeper;
   this.zkSessionTimeout = zkSessionTimeout;
   this.zkConnectTimeout = zkConnectTimeout;
   try {
     InetAddress address = InetAddress.getByName(brokerHost);
     this.address = HostAddress.fromParts(address.getHostAddress(), 8080);
   } catch (UnknownHostException ex) {
     throw new RuntimeException(ex.toString());
   }
 }
コード例 #12
0
  @Override
  public void execute()
      throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException,
          ConcurrentOperationException, ResourceAllocationException {
    // param checks
    if (snapshotReservation != null && (snapshotReservation < 0 || snapshotReservation > 100))
      throw new InvalidParameterValueException("Invalid snapshot reservation");

    ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name);
    NetappManager netappMgr = locator.getManager(NetappManager.class);

    StringBuilder s = new StringBuilder(getVolSize().toString());
    s.append("g");

    try {
      netappMgr.createVolumeOnFiler(
          ipAddress,
          aggrName,
          poolName,
          volName,
          s.toString(),
          snapshotPolicy,
          snapshotReservation,
          userName,
          password);
      CreateVolumeOnFilerCmdResponse response = new CreateVolumeOnFilerCmdResponse();
      response.setResponseName(getCommandName());
      this.setResponseObject(response);
    } catch (ServerException e) {
      throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.toString());
    } catch (InvalidParameterValueException e) {
      throw new ServerApiException(ApiErrorCode.PARAM_ERROR, e.toString());
    } catch (UnknownHostException e) {
      throw new ServerApiException(ApiErrorCode.PARAM_ERROR, e.toString());
    }
  }
コード例 #13
0
  /**
   * connect: connect to the master
   *
   * @return: true for success and false for failure
   */
  protected boolean connect() {

    boolean connected = true;
    try {
      _sock = new Socket(_serverIP, _serverPort);
      _out = new PrintWriter(_sock.getOutputStream(), true);
      _in = new BufferedReader(new InputStreamReader(_sock.getInputStream()));
      String reply = sendAll();
      if (!reply.equals(ProtocolConstants.PACK_STR_CONFIRM_HEAD)) {
        /* Tokenize */
        StringTokenizer st = new StringTokenizer(reply);
        if (st.nextToken().equals(ProtocolConstants.PACK_STR_ERRMES_HEAD)) {
          _elog(st.nextToken());
          return false;
        }
      }

      _userSock = new Socket(_serverIP, _serverPort);
      _userOut = new PrintWriter(_userSock.getOutputStream(), true);
      _userIn = new BufferedReader(new InputStreamReader(_userSock.getInputStream()));
      String replyUser = sendUserID();
      if (!replyUser.equals(ProtocolConstants.PACK_STR_CONFIRM_HEAD)) {
        throw new Exception("Not confirmed");
      }
    } catch (UnknownHostException e) {
      if (!_server.noException()) {
        _elog(e.toString());
      }
      if (_server.debugMode()) {
        e.printStackTrace();
      }
      connected = false;
    } catch (IOException e) {
      if (!_server.noException()) {
        _elog(e.toString());
      }
      if (_server.debugMode()) {
        e.printStackTrace();
      }
      connected = false;
    } catch (Exception e) {
      if (!_server.noException()) {
        _elog(e.toString());
      }
      if (_server.debugMode()) {
        e.printStackTrace();
      }
      connected = false;
    }
    if (!connected) {
      return connected;
    }

    if (!connected) {
      /* Remove the pair of socket */
      _sock = null;
      _in = null;
      _out = null;

      _userSock = null;
      _userOut = null;
      _userIn = null;
    }
    return connected;
  }
コード例 #14
0
 /**
  * @param ticker The ticker of the stock to look up.
  * @return A retrieval.CSV that contains the given stock's data over the past year.
  * @throws ConnectionException if it has problems connecting to Yahoo.
  * @throws exceptions.MissingCSVDataException if Yahoo does not have any data for the given stock.
  */
 public synchronized YahooCSV getStockData(String ticker)
     throws ConnectionException, MissingCSVDataException {
   boolean connectionsuccess = false;
   while (!connectionsuccess) {
     try {
       String contents =
           client
               .getPage(
                   new StringBuilder("http://real-chart.finance.yahoo.com/table.csv?s=")
                       .append(ticker)
                       .toString())
               .getWebResponse()
               .getContentAsString();
       if (contents.charAt(0) == '<') {
         throw new MissingCSVDataException("No data exists for this stock");
       }
       final YahooCSV csv = new YahooCSV(contents, ticker);
       connectionsuccess = true;
       client.close();
       System.out.println(new StringBuilder(ticker).append(" connected to Yahoo").toString());
       return csv;
     } catch (UnknownHostException uhe) {
       // Connection error.
       System.out.println(
           new StringBuilder("Exception in retrieval.")
               .append("InternetConnection.getStockData(")
               .append(ticker)
               .append(")")
               .toString());
       System.out.println(uhe.toString());
       System.out.println("Waiting to reconnect.");
       try {
         Thread.sleep(5000);
       } catch (Exception e) {
         System.out.println(
             new StringBuilder("Exception in ")
                 .append("retrieval.InternetConnection.getStockData(")
                 .append(ticker)
                 .append(")")
                 .toString());
         System.out.println(uhe.toString());
       }
     } catch (MissingCSVDataException mcsvde) {
       // There is no CSV data for this stock.
       System.out.println(
           new StringBuilder("Exception in ")
               .append("retrieval.InternetConnection.getStockData(")
               .append(ticker)
               .append(")")
               .toString());
       System.out.println(mcsvde.toString());
       connectionsuccess = true;
       client.close();
     } catch (Exception e) {
       System.out.println(
           new StringBuilder("Exception in ")
               .append("retrieval.InternetConnection.getStockData(")
               .append(ticker)
               .append(")")
               .toString());
       System.out.println(e.toString());
     }
   }
   throw new ConnectionException(
       new StringBuilder("Unable to find CSV File for ").append(ticker).toString());
 }
コード例 #15
0
 /**
  * @param ticker The ticker of the stock to look up.
  * @param startdate The first date of the range of dates over which to search.
  * @return A retrieval.CSV that contains the given stock's data over the past year.
  * @throws ConnectionException if it has problems connecting to Yahoo.
  * @throws exceptions.MissingCSVDataException if Yahoo does not have any data for the given stock.
  * @throws exceptions.InvalidStartDateException if the start date is equal to or after the current
  *     date.
  */
 public synchronized YahooCSV getStockData(String ticker, GregorianCalendar startdate)
     throws ConnectionException, MissingCSVDataException, InvalidStartDateException {
   // Make sure that the start date is before today!
   GregorianCalendar today = new GregorianCalendar();
   if (!startdate.before(today)) {
     throw new InvalidStartDateException("The start date must be before the current date.");
   }
   // This connection loop will re-connect to Yahoo if the initial and
   // subsequent attempts fail.
   boolean connectionsuccess = false;
   while (!connectionsuccess) {
     try {
       String contents =
           client
               .getPage(
                   new StringBuilder("http://real-chart.finance.yahoo.com/table.csv?s=")
                       .append(ticker)
                       .append("&a=")
                       .append(startdate.get(Calendar.MONTH))
                       .append("&b=")
                       .append(startdate.get(Calendar.DATE))
                       .append("&c=")
                       .append(startdate.get(Calendar.YEAR))
                       .toString())
               .getWebResponse()
               .getContentAsString();
       if (contents.charAt(0) == '<') {
         // There is no stock data for the given ticker, and Yahoo
         // has responded with an error page rather than a CSV.
         throw new MissingCSVDataException("No data exists for this stock");
       }
       final YahooCSV csv = new YahooCSV(contents, ticker);
       connectionsuccess = true;
       client.close();
       System.out.println(ticker + " connected to Yahoo.");
       return csv;
     } catch (UnknownHostException uhe) {
       // Connection error.
       System.out.println(
           new StringBuilder("Exception in ")
               .append("retrieval.InternetConnection.getStockData(")
               .append(ticker)
               .append(")")
               .toString());
       System.out.println(uhe.toString());
       System.out.println("Waiting to reconnect.");
       try {
         Thread.sleep(5000);
       } catch (Exception e) {
         System.out.println(
             new StringBuilder("Exception in ")
                 .append("retrieval.InternetConnection.getStockData(")
                 .append(ticker)
                 .append(")")
                 .toString());
         System.out.println(uhe.toString());
       }
     } catch (MissingCSVDataException mcsvde) {
       // There is no CSV data for this stock.
       System.out.println(
           new StringBuilder("Exception in ")
               .append("retrieval.InternetConnection.getStockData(")
               .append(ticker)
               .append(")")
               .toString());
       System.out.println(mcsvde.toString());
       connectionsuccess = true;
       client.close();
     } catch (Exception e) {
       System.out.println(
           new StringBuilder("Exception in ")
               .append("retrieval.InternetConnection.getStockData(")
               .append(ticker)
               .append(")")
               .toString());
       System.out.println(e.toString());
     }
   }
   throw new ConnectionException(
       new StringBuilder("Unable to find CSV File for ").append(ticker).toString());
 }
コード例 #16
0
  public void run() {
    // Variables for setting up connection and communication
    Socket Socket = null; // socket to connect with ServerRouter
    PrintWriter out = null; // for writing to ServerRouter
    BufferedReader in = null; // for reading form ServerRouter
    InetAddress addr;
    String host = "";
    try {
      addr = InetAddress.getLocalHost();
      host = addr.getHostAddress(); // Client machine's IP
    } catch (UnknownHostException e1) {
      _message = e1.toString();
      _flag = true;
      while (!_kill) {
        try {
          Thread.sleep(100);
        } catch (InterruptedException ex) {
        }
      }
      return;
    }
    // String routerName = "192.168.1.6"; // ServerRouter host name
    // int SockNum = 5555; // port number

    // Tries to connect to the ServerRouter
    try {
      Socket = new Socket(_routerName, _sockNum);
      out = new PrintWriter(Socket.getOutputStream(), true);
      in = new BufferedReader(new InputStreamReader(Socket.getInputStream()));
    } catch (UnknownHostException e) {
      _message = "Don't know about router: " + _routerName + ".";
      _flag = true;
      while (!_kill) {
        try {
          Thread.sleep(100);
        } catch (InterruptedException e1) {
        }
      }
      return;
    } catch (IOException e) {
      _message = "Couldn't get I/O for the connection.";
      _flag = true;
      while (!_kill) {
        try {
          Thread.sleep(100);
        } catch (InterruptedException e1) {
        }
      }
      return;
    }

    BufferedReader fromFile;
    try {
      // Variables for message passing
      Reader reader = new FileReader("file.txt");
      fromFile = new BufferedReader(reader); // reader for the string file
      String fromServer; // messages received from ServerRouter
      String fromUser; // messages sent to ServerRouter
      long t0, t1, t;

      // Communication process (initial sends/receives
      out.println(_destinationIP); // initial send (IP of the destination Server)
      fromServer = in.readLine(); // initial receive from router (verification of connection)
      report("ServerRouter: " + fromServer);
      out.println(host); // Client sends the IP of its machine as initial send
      t0 = System.currentTimeMillis();

      // Communication while loop
      while ((fromServer = in.readLine()) != null) {
        report("Server: " + fromServer);
        t1 = System.currentTimeMillis();
        t = t1 - t0;
        report("Cycle time: " + t);

        fromUser = fromFile.readLine(); // reading strings from a file
        if (fromUser != null) {
          report("Client: " + fromUser);
          out.println(fromUser); // sending the strings to the Server via ServerRouter
          t0 = System.currentTimeMillis();
        }
        if (fromServer.equals("Bye.") || fromServer.equals("BYE.")) { // exit statement
          report("Connection Ended.");
          break;
        }
      }
      // closing connections
      out.close();
      in.close();
      fromFile.close();
      Socket.close();
      _kill = true;
    } catch (Exception e) {
      _message = "Sending Error: " + e.toString() + ".";
      _flag = true;
    }
    return;
  }