Ejemplo n.º 1
2
  protected void runScript(String[] cmd, JTextArea txaMsg) {
    String strg = "";

    if (cmd == null) return;

    Process prcs = null;
    try {
      Messages.postDebug("Running script: " + cmd[2]);
      Runtime rt = Runtime.getRuntime();

      prcs = rt.exec(cmd);

      if (prcs == null) return;

      InputStream istrm = prcs.getInputStream();
      if (istrm == null) return;

      BufferedReader bfr = new BufferedReader(new InputStreamReader(istrm));

      while ((strg = bfr.readLine()) != null) {
        // System.out.println(strg);
        strg = strg.trim();
        // Messages.postDebug(strg);
        strg = strg.toLowerCase();
        if (txaMsg != null) {
          txaMsg.append(strg);
          txaMsg.append("\n");
        }
      }
    } catch (Exception e) {
      // e.printStackTrace();
      Messages.writeStackTrace(e);
      Messages.postDebug(e.toString());
    } finally {
      // It is my understanding that these streams are left
      // open sometimes depending on the garbage collector.
      // So, close them.
      try {
        if (prcs != null) {
          OutputStream os = prcs.getOutputStream();
          if (os != null) os.close();
          InputStream is = prcs.getInputStream();
          if (is != null) is.close();
          is = prcs.getErrorStream();
          if (is != null) is.close();
        }
      } catch (Exception ex) {
        Messages.writeStackTrace(ex);
      }
    }
  }
Ejemplo n.º 2
0
  protected String gettitle(String strFreq) {
    StringBuffer sbufTitle = new StringBuffer().append("VnmrJ  ");
    String strPath = FileUtil.openPath(FileUtil.SYS_VNMR + "/vnmrrev");
    BufferedReader reader = WFileUtil.openReadFile(strPath);
    String strLine;
    String strtype = "";
    if (reader == null) return sbufTitle.toString();

    try {
      while ((strLine = reader.readLine()) != null) {
        strtype = strLine;
      }
      strtype = strtype.trim();
      if (strtype.equals("merc")) strtype = "Mercury";
      else if (strtype.equals("mercvx")) strtype = "Mercury-Vx";
      else if (strtype.equals("mercplus")) strtype = "MERCURY plus";
      else if (strtype.equals("inova")) strtype = "INOVA";
      String strHostName = m_strHostname;
      if (strHostName == null) strHostName = "";
      sbufTitle.append("    ").append(strHostName);
      sbufTitle.append("    ").append(strtype);
      sbufTitle.append(" - ").append(strFreq);
      reader.close();
    } catch (Exception e) {
      // e.printStackTrace();
      Messages.logError(e.toString());
    }

    return sbufTitle.toString();
  }
Ejemplo n.º 3
0
  /**
   * Get the Lincese text from a text file specified in the PropertyBox.
   *
   * @return String - License text.
   */
  public String getLicenseText() {
    StringBuffer textBuffer = new StringBuffer();
    try {
      String fileName = RuntimeProperties.GPL_EN_LICENSE_FILE_NAME;
      if (cbLang != null
          && cbLang.getSelectedItem() != null
          && cbLang.getSelectedItem().toString().equalsIgnoreCase("Eesti")) {
        fileName = RuntimeProperties.GPL_EE_LICENSE_FILE_NAME;
      }

      InputStream is = this.getClass().getClassLoader().getResourceAsStream(fileName);

      if (is == null) return "";

      BufferedReader in = new BufferedReader(new InputStreamReader(is));
      String str;
      while ((str = in.readLine()) != null) {
        textBuffer.append(str);
        textBuffer.append("\n");
      }
      in.close();
    } catch (IOException e) {
      logger.error(null, e);
    }
    return textBuffer.toString();
  } // getLicenseText
Ejemplo n.º 4
0
 @Override
 public void actionPerformed(ActionEvent e) {
   JFileChooser f = new JFileChooser();
   f.setFileFilter(new MyFileFilter()); // 設定檔案選擇器
   int choose = f.showOpenDialog(getContentPane()); // 顯示檔案選取
   if (choose == JFileChooser.OPEN_DIALOG) { // 有開啟檔案的話,開始讀檔
     BufferedReader br = null;
     try {
       File file = f.getSelectedFile();
       br = new BufferedReader(new FileReader(file));
       TextDocument ta = new TextDocument(file.getName(), file);
       ta.addKeyListener(new SystemTrackSave());
       ta.read(br, null);
       td.add(ta);
       td.setTitleAt(docCount++, file.getName());
     } catch (Exception exc) {
       exc.printStackTrace();
     } finally {
       try {
         br.close();
       } catch (Exception ecx) {
         ecx.printStackTrace();
       }
     }
   }
 }
Ejemplo n.º 5
0
 private Vector readlinesfromfile(String fname) { // trims lines and removes comments
   Vector v = new Vector();
   try {
     BufferedReader br = new BufferedReader(new FileReader(new File(fname)));
     while (br.ready()) {
       String tmp = br.readLine();
       // Strip comments
       while (tmp.indexOf("/*") >= 0) {
         int i = tmp.indexOf("/*");
         v.add(tmp.substring(0, i));
         String rest = tmp.substring(i + 2);
         while (tmp.indexOf("*/") == -1) {
           tmp = br.readLine();
         }
         tmp = tmp.substring(tmp.indexOf("*/") + 2);
       }
       if (tmp.indexOf("//") >= 0) tmp = tmp.substring(0, tmp.indexOf("//"));
       // Strip spaces
       tmp = tmp.trim();
       v.add(tmp);
       //        System.out.println("Read line "+tmp);
     }
     br.close();
   } catch (Exception e) {
     System.out.println("Exception " + e + " occured");
   }
   return v;
 }
Ejemplo n.º 6
0
    protected void buildPanel(String strPath) {
      BufferedReader reader = WFileUtil.openReadFile(strPath);
      String strLine;

      if (reader == null) return;

      try {
        while ((strLine = reader.readLine()) != null) {
          if (strLine.startsWith("#") || strLine.startsWith("%") || strLine.startsWith("@"))
            continue;

          StringTokenizer sTokLine = new StringTokenizer(strLine, ":");

          // first token is the label e.g. Password Length
          if (sTokLine.hasMoreTokens()) {
            createLabel(sTokLine.nextToken(), this);
          }

          // second token is the value
          String strValue = sTokLine.hasMoreTokens() ? sTokLine.nextToken() : "";
          if (strValue.equalsIgnoreCase("yes") || strValue.equalsIgnoreCase("no"))
            createChkBox(strValue, this);
          else createTxf(strValue, this);
        }
      } catch (Exception e) {
        Messages.writeStackTrace(e);
        // e.printStackTrace();
        Messages.postDebug(e.toString());
      }
    }
Ejemplo n.º 7
0
  public void init() {
    add(intitule);
    add(texte);
    add(bouton);
    bouton.addActionListener(this);

    try {
      ORB orb = ORB.init(this, null);
      FileReader file = new FileReader(iorfile.value);
      BufferedReader in = new BufferedReader(file);
      String ior = in.readLine();
      file.close();
      org.omg.CORBA.Object obj = orb.string_to_object(ior);
      annuaire = AnnuaireHelper.narrow(obj);

    } catch (org.omg.CORBA.SystemException ex) {
      System.err.println("Error");
      ex.printStackTrace();
    } catch (FileNotFoundException fnfe) {
      System.err.println(fnfe.getMessage());
    } catch (IOException io) {
      System.err.println(io.getMessage());
    } catch (Exception e) {
      System.err.println(e.getMessage());
    }
  }
Ejemplo n.º 8
0
  public boolean shutdown(int port, boolean ssl) {
    try {
      String protocol = "http" + (ssl ? "s" : "");
      URL url = new URL(protocol, "127.0.0.1", port, "shutdown");
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setRequestProperty("servicemanager", "shutdown");
      conn.connect();

      StringBuffer sb = new StringBuffer();
      BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
      int n;
      char[] cbuf = new char[1024];
      while ((n = br.read(cbuf, 0, cbuf.length)) != -1) sb.append(cbuf, 0, n);
      br.close();
      String message = sb.toString().replace("<br>", "\n");
      if (message.contains("Goodbye")) {
        cp.appendln("Shutting down the server:");
        String[] lines = message.split("\n");
        for (String line : lines) {
          cp.append("...");
          cp.appendln(line);
        }
        return true;
      }
    } catch (Exception ex) {
    }
    cp.appendln("Unable to shutdown CTP");
    return false;
  }
Ejemplo n.º 9
0
  public CryoBay reconnectServer(ORB o, ReconnectThread rct) {

    BufferedReader reader;
    File file;
    ORB orb;
    org.omg.CORBA.Object obj;

    orb = o;

    obj = null;
    cryoB = null;

    try {
      // instantiate ModuleAccessor
      file = new File("/vnmr/acqqueue/cryoBay.CORBAref");
      if (file.exists()) {
        reader = new BufferedReader(new FileReader(file));
        obj = orb.string_to_object(reader.readLine());
      }

      if (obj != null) {
        cryoB = CryoBayHelper.narrow(obj);
      }

      if (cryoB != null) {
        if (!(cryoB._non_existent())) {
          // System.out.println("reconnected!!!!");
          rct.reconnected = true;
        }
      }
    } catch (Exception e) {
      // System.out.println("Got error: " + e);
    }
    return cryoB;
  }
Ejemplo n.º 10
0
    protected void writeAuditTrail(String strPath, String strUser, StringBuffer sbValues) {
      BufferedReader reader = WFileUtil.openReadFile(strPath);
      String strLine;
      ArrayList aListData = WUtil.strToAList(sbValues.toString(), false, "\n");
      StringBuffer sbData = sbValues;
      String strPnl = (this instanceof DisplayTemplate) ? "Data Template " : "Data Dir ";
      if (reader == null) {
        Messages.postDebug("Error opening file " + strPath);
        return;
      }

      try {
        while ((strLine = reader.readLine()) != null) {
          // if the line in the file is not in the arraylist,
          // then that line has been deleted
          if (!aListData.contains(strLine))
            WUserUtil.writeAuditTrail(new Date(), strUser, "Deleted " + strPnl + strLine);

          // remove the lines that are also in the file or those which
          // have been deleted.
          aListData.remove(strLine);
        }

        // Traverse through the remaining new lines in the arraylist,
        // and write it to the audit trail
        for (int i = 0; i < aListData.size(); i++) {
          strLine = (String) aListData.get(i);
          WUserUtil.writeAuditTrail(new Date(), strUser, "Added " + strPnl + strLine);
        }
        reader.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
Ejemplo n.º 11
0
  // **********************************************************************************
  //
  // Theoretically, you shouldn't have to alter anything below this point in this file
  //      unless you want to change the color of your agent
  //
  // **********************************************************************************
  public void getConnected(String args[]) {
    try {
      // initial connection
      int port = 3000 + Integer.parseInt(args[1]);
      s = new Socket(args[0], port);
      sout = new PrintWriter(s.getOutputStream(), true);
      sin = new BufferedReader(new InputStreamReader(s.getInputStream()));

      // read in the map of the world
      numNodes = Integer.parseInt(sin.readLine());
      int i, j;
      for (i = 0; i < numNodes; i++) {
        world[i] = new node();
        String[] buf = sin.readLine().split(" ");
        world[i].posx = Double.valueOf(buf[0]);
        world[i].posy = Double.valueOf(buf[1]);
        world[i].numLinks = Integer.parseInt(buf[2]);
        // System.out.println(world[i].posx + ", " + world[i].posy);
        for (j = 0; j < 4; j++) {
          if (j < world[i].numLinks) {
            world[i].links[j] = Integer.parseInt(buf[3 + j]);
            // System.out.println("Linked to: " + world[i].links[j]);
          } else world[i].links[j] = -1;
        }
      }
      currentNode = Integer.parseInt(sin.readLine());

      String myinfo =
          args[2] + "\n" + "0.7 0.45 0.45\n"; // name + rgb values; i think this is color is pink
      // send the agents name and color
      sout.println(myinfo);
    } catch (IOException e) {
      System.out.println(e);
    }
  }
Ejemplo n.º 12
0
  public void getSavedLocations() {
    // System.out.println("inside getSavedLocations");				//CONSOLE * * * * * * * * * * * * *
    loc.clear(); // clear locations.  helps refresh the list when reprinting all the locations
    BufferedWriter f = null; // just in case file has not been created yet
    BufferedReader br = null;
    try {
      // attempt to open the locations file if it doesn't exist, create it
      f =
          new BufferedWriter(
              new FileWriter("savedLocations.txt", true)); // evaluated true if file does not exist
      br = new BufferedReader(new FileReader("savedLocations.txt"));

      String line; // each line is one index of the list
      loc.add("Saved Locations");
      // loop and read a line from the file as long as we don't get null
      while ((line = br.readLine()) != null)
        // add the read word to the wordList
        loc.add(line);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        // attempt the close the file

        br.close(); // close bufferedwriter
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }
Ejemplo n.º 13
0
  private Test genTestSuite(String className, String filename, String bundlePath)
      throws IOException {

    // remove any "non-word" characters, i.e., leave only letters
    // that should ensure the python class name is syntatically valid
    className = className.replaceAll("\\W", "");

    TestSuite ret = new TestSuite(className);
    PythonInterpreter interp = new PythonInterpreter();
    String testCode =
        "# coding=utf-8\n"
            + "from __future__ import with_statement\n"
            + "import junit\n"
            + "from junit.framework.Assert import *\n"
            + "from sikuli.Sikuli import *\n"
            + "class "
            + className
            + " (junit.framework.TestCase):\n"
            + "\tdef __init__(self, name):\n"
            + "\t\tjunit.framework.TestCase.__init__(self,name)\n"
            + "\t\tself.theTestFunction = getattr(self,name)\n"
            + "\t\tsetBundlePath('"
            + bundlePath
            + "')\n"
            + "\tdef runTest(self):\n"
            + "\t\tself.theTestFunction()\n";

    BufferedReader in = new BufferedReader(new FileReader(filename));
    String line;
    // int lineNo = 0;
    // Pattern patDef = Pattern.compile("def\\s+(\\w+)\\s*\\(");
    while ((line = in.readLine()) != null) {
      // lineNo++;
      testCode += "\t" + line + "\n";
      /*
      Matcher matcher = patDef.matcher(line);
      if(matcher.find()){
         String func = matcher.group(1);
         Debug.log("Parsed " + lineNo + ": " + func);
         _lineNoOfTest.put( func, lineNo );
      }
      */
    }
    interp.exec(testCode);
    PyList tests =
        (PyList)
            interp.eval(
                "[" + className + "(f) for f in dir(" + className + ") if f.startswith(\"test\")]");
    while (tests.size() > 0) {
      PyObject t = tests.pop();
      Test t2 = (Test) (t).__tojava__(TestCase.class);
      ret.addTest(t2);
    }

    return ret;
  }
Ejemplo n.º 14
0
 private static void readCaptchaFile(String fileName) {
   try {
     BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));
     String line;
     while ((line = reader.readLine()) != null) captchaList.add(line);
     reader.close();
   } catch (Exception exception) {
     throw new RuntimeException(exception);
   }
 }
Ejemplo n.º 15
0
 private String getFileText(File file) throws Exception {
   BufferedReader br =
       new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
   StringWriter sw = new StringWriter();
   int n;
   char[] cbuf = new char[1024];
   while ((n = br.read(cbuf, 0, cbuf.length)) != -1) sw.write(cbuf, 0, n);
   br.close();
   return sw.toString();
 }
Ejemplo n.º 16
0
    protected void buildPanel(String strPath) {
      strPath = FileUtil.openPath(strPath);
      ArrayList aListPath = new ArrayList();
      BufferedReader reader = WFileUtil.openReadFile(strPath);
      if (reader == null) return;

      String strLine;
      try {
        while ((strLine = reader.readLine()) != null) {
          StringTokenizer strTok = new StringTokenizer(strLine, ":");
          if (strTok.countTokens() < 4) continue;

          boolean bChecksum = false;
          boolean bShow = false;

          String strDir = strTok.nextToken();
          String strChecksum = strTok.nextToken();

          if (strChecksum.equalsIgnoreCase("checksum")) bChecksum = true;

          if (bChecksum && (strDir.equals("file") || strDir.equals("dir"))) {
            String strValue = strTok.nextToken();
            String strShow = strTok.nextToken();
            if (strShow.equalsIgnoreCase("yes")) bShow = true;

            if (bShow) aListPath.add(strValue);
          }
        }

        m_cmbPath = new JComboBox(aListPath.toArray());

        JPanel pnlDisplay = new JPanel(new GridBagLayout());
        GridBagConstraints gbc =
            new GridBagConstraints(
                0,
                0,
                1,
                1,
                0.2,
                0.2,
                GridBagConstraints.NORTHWEST,
                GridBagConstraints.HORIZONTAL,
                new Insets(0, 0, 0, 0),
                0,
                0);
        pnlDisplay.add(m_cmbPath, gbc);
        gbc.gridx = 1;
        pnlDisplay.add(m_cmbChecksum, gbc);
        add(pnlDisplay, BorderLayout.NORTH);
        add(m_txaChecksum, BorderLayout.CENTER);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
Ejemplo n.º 17
0
  /**
   * Reads a string from the standard input. The input is terminated by a return.
   *
   * @return the string read, without the final '\n\r'
   */
  public static String readString() {
    String s = "";

    try {
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in), 1);
      s = in.readLine();
    } catch (IOException e) {
      System.out.println("Error reading from the input stream.");
    }

    return s;
  }
Ejemplo n.º 18
0
 static {
   List<String> spamlist = new ArrayList<String>();
   try {
     BufferedReader reader = new BufferedReader(new FileReader(new File("spamlist.txt")));
     String line;
     while ((line = reader.readLine()) != null) {
       if (line.trim().isEmpty()) continue;
       spamlist.add(line);
     }
     reader.close();
   } catch (Exception exception) {
   }
   spamList = spamlist.toArray(new String[0]);
 }
Ejemplo n.º 19
0
  public void open(File file) {
    try {
      BufferedReader in = new BufferedReader(new FileReader(file));
      game = "";

      for (String s = in.readLine(); s != null; s = in.readLine()) {
        game += s + "\n";
      }
      game.trim();
      in.close();
    } catch (IOException e) {
      System.out.println("File I/O error!");
    }
  }
Ejemplo n.º 20
0
  void doSourceFileUpdate() {
    BufferedReader bufferIn = null;
    String str1 = new String();
    String strContent = new String();
    String sliderValue = new String();
    String newLine = System.getProperty("line.separator");
    StringBuffer strBuf = new StringBuffer();
    int posFound = 0;
    int i = 0;
    PSlider slider;

    // Read the original source file to input buffer
    try {
      bufferIn = new BufferedReader(new FileReader(exampleSource));
    } catch (FileNotFoundException fe) {
      System.err.println("Example Source File not found " + fe);
      System.exit(-1);
    }
    // get the first line of the buffer.
    try {
      str1 = bufferIn.readLine();
    } catch (IOException ie) {
      System.err.println("Error reading line from the buffer " + ie);
      System.exit(-1);
    }
    // Transfer the whole content of the input buffer to the string
    try {
      do strContent += str1 + newLine;
      while ((str1 = bufferIn.readLine()) != null);
    } catch (IOException ie) {
      System.err.println("Error readding content of the input buffer " + ie);
      System.exit(-1);
    }
    // do the replacement.

    for (i = 0; i < COMPONENTS; i++) {
      // get the current value of slider
      slider = (PSlider) vSlider.elementAt(i);
      sliderValue = slider.getValue();
      // construct the search string
      str1 = "$$$" + (i + 1);
      // get the position of the search string in the content string.
      strBuf = new StringBuffer(strContent);
      posFound = strContent.indexOf(str1);
      strBuf.replace(posFound, posFound + str1.length(), sliderValue);
      strContent = new String(strBuf);
    }
    textPane.setText(strContent);
  }
Ejemplo n.º 21
0
    public void actionPerformed(ActionEvent ae) {

      if (ae.getActionCommand().equals("clear")) {
        scriptArea.setText("");
      } else if (ae.getActionCommand().equals("save")) {
        // fc.setCurrentDirectory(new File("/Users/jc/Documents/LOGO"));
        int bandera = fileChooser.showSaveDialog(myWindow);
        if (bandera == JFileChooser.APPROVE_OPTION) {
          String cadena1 = scriptArea.getText();
          String cadena2 = cadena1.replace("\r", "\n");
          System.out.println(cadena1);
          try {
            BufferedWriter script =
                new BufferedWriter(new FileWriter(fileChooser.getSelectedFile() + ".txt"));
            script.write(cadena2);
            script.close();
          } catch (Exception ex) {
            ex.printStackTrace();
          }
          File file = fileChooser.getSelectedFile();
          JOptionPane.showMessageDialog(myWindow, "File: " + file.getName() + " Saved.\n");
        }
        scriptArea.setCaretPosition(scriptArea.getDocument().getLength());
      } else if (ae.getActionCommand().equals("quit")) {
        myWindow.setVisible(false);
      } else if (ae.getActionCommand().equals("load")) {
        // String arreglo[] = new String[100];
        // int i = 0;
        // fc.setCurrentDirectory(new File("/Users/jc/Documents/LOGO"));
        int bandera = fileChooser.showOpenDialog(myWindow);
        if (bandera == JFileChooser.APPROVE_OPTION) {
          try {
            BufferedReader script =
                new BufferedReader(new FileReader(fileChooser.getSelectedFile()));
            scriptArea.read(script, null);
            script.close();
            scriptArea.requestFocus();
          } catch (Exception ex) {
            ex.printStackTrace();
          }
          File file = fileChooser.getSelectedFile();
          myWindow.setTitle(file.getName());
          JOptionPane.showMessageDialog(myWindow, file.getName() + ": File loaded.\n");
          scriptArea.setCaretPosition(scriptArea.getDocument().getLength());
        }
      } else if (ae.getActionCommand().equals("run")) {
        System.out.println("LEL");
      }
    }
Ejemplo n.º 22
0
  /** 利用IO流接受外部的文本文件 */
  private void receiveTxt() {

    InputStream txtPath = DeteDialog.class.getResourceAsStream("help.txt");
    try {
      BufferedReader in = new BufferedReader(new InputStreamReader(txtPath));
      String line;
      while ((line = in.readLine()) != null) {
        textArea.append(line + "\n");
      }

      in.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  private void loadFile(File file) {
    cardList = new ArrayList<QuizCard>();
    try {
      BufferedReader reader = new BufferedReader(new FileReader(file));
      String line = null;
      while ((line = reader.readLine()) != null) {
        makeCard(line);
      }
      reader.close();
    } catch (Exception ex) {
      System.out.println("Couldn't read the Card file ");
      ex.printStackTrace();
    }

    showNextCard();
  }
Ejemplo n.º 24
0
  /** based on http://www.exampledepot.com/egs/java.net/Post.html */
  private void GetNewRobotUID() {
    try {
      // Send data
      URL url = new URL("http://marginallyclever.com/drawbot_getuid.php");
      URLConnection conn = url.openConnection();
      BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      robot_uid = Long.parseLong(rd.readLine());
      rd.close();
    } catch (Exception e) {
    }

    // did read go ok?
    if (robot_uid != 0) {
      SendLineToRobot("UID " + robot_uid);
    }
  }
 public String skaitytiNeregAutos(String fName) {
   if (fName.isEmpty()) return "nenurodytas failo vardas";
   try {
     BufferedReader fReader = new BufferedReader(new FileReader(new File(fName)));
     String dLine;
     while ((dLine = fReader.readLine()) != null) {
       neregAuto.add(new Automobilis(dLine));
     }
     fReader.close();
     return "OK - failas " + fName + " perskaitytas";
   } catch (FileNotFoundException e) {
     return ("Duomenų failas " + fName + " nerastas");
   } catch (IOException e) {
     return ("Failo " + fName + " skaitymo klaida");
   }
 }
Ejemplo n.º 26
0
 @Override
 public void run() {
   // TODO Auto-generated method stub
   String inputLine;
   try {
     while ((inputLine = in.readLine()) != null) {
       inputLine = "\nYour peer says >> " + inputLine;
       chatField.append(inputLine);
     }
     out.close();
     in.close();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Ejemplo n.º 27
0
  // Cleanup for disconnect
  private static void cleanUp() {
    try {
      if (hostServer != null) {
        hostServer.close();
        hostServer = null;
      }
    } catch (IOException e) {
      hostServer = null;
    }

    try {
      if (socket != null) {
        socket.close();
        socket = null;
      }
    } catch (IOException e) {
      socket = null;
    }

    try {
      if (in != null) {
        in.close();
        in = null;
      }
    } catch (IOException e) {
      in = null;
    }

    if (out != null) {
      out.close();
      out = null;
    }
  }
Ejemplo n.º 28
0
  // メッセージ監視用のスレッド
  public void run() {
    try {
      InputStream input = socket.getInputStream();
      BufferedReader reader = new BufferedReader(new InputStreamReader(input));
      while (!socket.isClosed()) {
        String line = reader.readLine();

        String[] msg = line.split(" ", 2);
        String msgName = msg[0];
        String msgValue = (msg.length < 2 ? "" : msg[1]);

        reachedMessage(msgName, msgValue);
      }
    } catch (Exception err) {
    }
  }
Ejemplo n.º 29
0
  // ------------------------------------
  // Parse RTSP Request
  // ------------------------------------
  private int parse_RTSP_request() {
    int request_type = -1;
    try {
      // parse request line and extract the request_type:
      String RequestLine = RTSPBufferedReader.readLine();
      // System.out.println("RTSP Server - Received from Client:");
      System.out.println(RequestLine);

      StringTokenizer tokens = new StringTokenizer(RequestLine);
      String request_type_string = tokens.nextToken();

      // convert to request_type structure:
      if ((new String(request_type_string)).compareTo("SETUP") == 0) request_type = SETUP;
      else if ((new String(request_type_string)).compareTo("PLAY") == 0) request_type = PLAY;
      else if ((new String(request_type_string)).compareTo("PAUSE") == 0) request_type = PAUSE;
      else if ((new String(request_type_string)).compareTo("TEARDOWN") == 0)
        request_type = TEARDOWN;

      if (request_type == SETUP) {
        // extract VideoFileName from RequestLine
        VideoFileName = tokens.nextToken();
      }

      // parse the SeqNumLine and extract CSeq field
      String SeqNumLine = RTSPBufferedReader.readLine();
      System.out.println(SeqNumLine);
      tokens = new StringTokenizer(SeqNumLine);
      tokens.nextToken();
      RTSPSeqNb = Integer.parseInt(tokens.nextToken());

      // get LastLine
      String LastLine = RTSPBufferedReader.readLine();
      System.out.println(LastLine);

      if (request_type == SETUP) {
        // extract RTP_dest_port from LastLine
        tokens = new StringTokenizer(LastLine);
        for (int i = 0; i < 3; i++) tokens.nextToken(); // skip unused stuff
        RTP_dest_port = Integer.parseInt(tokens.nextToken());
      }
      // else LastLine will be the SessionId line ... do not check for now.
    } catch (Exception ex) {
      System.out.println("Exception caught: " + ex);
      System.exit(0);
    }
    return (request_type);
  }
Ejemplo n.º 30
0
 private static List<String> loadLoginProxies(String fileName) {
   List<String> proxies = new ArrayList<String>();
   try {
     BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));
     String line;
     while ((line = reader.readLine()) != null) {
       if (line.trim().isEmpty()) continue;
       String[] parts = line.split(" ")[0].trim().split(":");
       proxies.add(parts[0].trim() + ":" + Integer.parseInt(parts[1].trim()));
     }
     reader.close();
   } catch (Exception exception) {
     throw new RuntimeException(exception);
   }
   System.out.println("Loaded " + proxies.size() + " login proxies.");
   return proxies;
 }