Ejemplo n.º 1
1
  private void sendResourceFile(HttpExchange exchange) {
    StringBuilder response = new StringBuilder();

    String path = exchange.getRequestURI().getPath();
    if (path.contains("resources")) {
      path = path.substring(path.indexOf("resources") + 9);
    }
    InputStream is = MyBaseHandler.class.getResourceAsStream(path);
    if (is == null) {
      writeResponse(exchange, "File not found", 404);
      return;
    }
    InputStreamReader reader = new InputStreamReader(is);

    try {
      BufferedReader bufferedReader = new BufferedReader(reader);

      String tmp;
      while ((tmp = bufferedReader.readLine()) != null) {
        response.append(tmp);
        response.append("\n");
      }
    } catch (NullPointerException e) {
      response.append("Resource file not found");
      writeResponse(exchange, response.toString(), 404);
    } catch (IOException e) {
      response.append("Error while reading from file");
      writeResponse(exchange, response.toString(), 400);
    }
    writeResponse(exchange, response.toString(), 200);
  }
Ejemplo n.º 2
0
  private static void exec(String command) {
    try {
      System.out.println("Invoking: " + command);
      Process p = Runtime.getRuntime().exec(command);

      // get standard output
      BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
      String line;
      while ((line = input.readLine()) != null) {
        System.out.println(line);
      }
      input.close();

      // get error output
      input = new BufferedReader(new InputStreamReader(p.getErrorStream()));
      while ((line = input.readLine()) != null) {
        System.out.println(line);
      }
      input.close();

      p.waitFor();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
  public GElement generateGraph(String dotFile) throws IOException {

    BufferedReader br = new BufferedReader(new FileReader(dotFile));
    graph = null;

    /**
     * The problem here is that DOT sometime inserts a '\' at the end of a long line so we have to
     * skip it and continue to parse until a "real" EOL is reached. Example: statement ->
     * compoundStatement [pos="e,3264,507 3271,2417 3293,2392 ... 3237,565 3234,560 32\ 39,545
     * 3243,534 3249,523 3257,514"];
     */
    StringBuffer line = new StringBuffer();
    int c; // current character
    int pc = -1; // previous character
    while ((c = br.read()) != -1) {
      if (c == '\n') {
        if (pc == '\\') {
          // Remove the last \ if it was part of the DOT wrapping character
          line.deleteCharAt(line.length() - 1);
        } else {
          GElement element = parseLine(line.toString());
          if (element != null) {
            if (graph == null) graph = element;
            else graph.addElement(element);
          }
          line.delete(0, line.length());
        }
      } else if (c != '\r') {
        line.append((char) c);
      }
      pc = c;
    }
    return graph;
  }
Ejemplo n.º 4
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.º 5
0
  public String readFileFromJAR(String filepath) {

    String out = "";

    try {

      // setup input buffer
      ClassLoader cl = this.getClass().getClassLoader();
      InputStream instream = cl.getResourceAsStream(filepath);
      BufferedReader filereader = new BufferedReader(new InputStreamReader(instream));

      // read lines
      String line = filereader.readLine();
      while (line != null) {
        out += "\n" + line;
        line = filereader.readLine();
      }

      filereader.close();

    } catch (Exception e) {
      // e.printStackTrace();
    }

    return out;
  }
Ejemplo n.º 6
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.º 7
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.º 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
 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.º 10
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.º 11
0
  public void loadMap(String s) {

    try {
      InputStream in = getClass().getResourceAsStream(s);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));

      numCols = Integer.parseInt(br.readLine());
      numRows = Integer.parseInt(br.readLine());
      map = new int[numRows][numCols];
      width = numCols * tileSize;
      height = numRows * tileSize;

      xmin = GamePanel.WIDTH - width;
      xmax = 0;
      ymin = GamePanel.HEIGHT - height;
      ymax = 0;

      String delims = "\\s+";
      for (int row = 0; row < numRows; row++) {
        String line = br.readLine();
        String[] tokens = line.split(delims);
        for (int col = 0; col < numCols; col++) {
          map[row][col] = Integer.parseInt(tokens[col]);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 12
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.º 13
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.º 14
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.º 15
0
 /** This method receives the URL as input and returns the same as array of string. */
 public static String[] readStringArrayFromURL(URL u) {
   Vector vs = new Vector();
   String sdat[] = (String[]) null;
   if (u != null) {
     try {
       java.io.InputStream in = u.openStream();
       BufferedReader bis = new BufferedReader(new InputStreamReader(in));
       do {
         String line = bis.readLine();
         if (line == null) {
           break;
         }
         vs.addElement(line);
       } while (true);
     } catch (IOException ex) {
       System.out.println("URL read error ");
     }
     if (vs.size() > 0) {
       sdat = new String[vs.size()];
       for (int i = 0; i < vs.size(); i++) {
         sdat[i] = (String) (String) vs.elementAt(i);
       }
     }
   }
   return sdat;
 }
Ejemplo n.º 16
0
  /**
   * @return the clipboard content as a String (DataFlavor.stringFlavor) Code snippet adapted from
   *     jEdit (Registers.java), http://www.jedit.org. Returns null if clipboard is empty.
   */
  public static String getClipboardStringContent(Clipboard clipboard) {
    // Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    try {
      String selection =
          (String) (clipboard.getContents(null).getTransferData(DataFlavor.stringFlavor));
      if (selection == null) return null;

      boolean trailingEOL =
          (selection.endsWith("\n") || selection.endsWith(System.getProperty("line.separator")));

      // Some Java versions return the clipboard contents using the native line separator,
      // so have to convert it here , see jEdit's "registers.java"
      BufferedReader in = new BufferedReader(new StringReader(selection));
      StringBuffer buf = new StringBuffer();
      String line;
      while ((line = in.readLine()) != null) {
        buf.append(line);
        buf.append('\n');
      }
      // remove trailing \n
      if (!trailingEOL) buf.setLength(buf.length() - 1);
      return buf.toString();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
Ejemplo n.º 17
0
 /**
  * Tries to read the BoundingBox out of the EPS file. If not successful, it returns a default
  * BoundingBox
  *
  * @param epsfile
  * @return
  */
 private Rectangle2D getBoundingBox(File epsfile) {
   Rectangle.Double result = new Rectangle.Double(0, 0, 800, 600);
   try {
     BufferedReader r = new BufferedReader(new FileReader(epsfile));
     String line;
     while ((line = r.readLine()) != null) {
       // TODO: Get HighRes BoundingBox
       if (line.startsWith("%%BoundingBox:") || line.startsWith("%%PageBoundingBox:")) {
         try {
           String[] elements = line.split(" ");
           result =
               new Rectangle.Double(
                   Integer.parseInt(elements[1]),
                   Integer.parseInt(elements[2]),
                   Integer.parseInt(elements[3]),
                   Integer.parseInt(elements[4]));
           break;
         } catch (NumberFormatException e) {
         }
       }
     }
     r.close();
   } catch (Exception ex) {
     Logger.getLogger(EPSImporter.class.getName()).log(Level.SEVERE, null, ex);
   }
   return result;
 }
Ejemplo n.º 18
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.º 19
0
  public Chart(String filename) {
    try {
      // Get Stock Symbol
      this.stockSymbol = filename.substring(0, filename.indexOf('.'));

      // Create time series
      TimeSeries open = new TimeSeries("Open Price", Day.class);
      TimeSeries close = new TimeSeries("Close Price", Day.class);
      TimeSeries high = new TimeSeries("High", Day.class);
      TimeSeries low = new TimeSeries("Low", Day.class);
      TimeSeries volume = new TimeSeries("Volume", Day.class);

      BufferedReader br = new BufferedReader(new FileReader(filename));
      String key = br.readLine();
      String line = br.readLine();
      while (line != null && !line.startsWith("<!--")) {
        StringTokenizer st = new StringTokenizer(line, ",", false);
        Day day = getDay(st.nextToken());
        double openValue = Double.parseDouble(st.nextToken());
        double highValue = Double.parseDouble(st.nextToken());
        double lowValue = Double.parseDouble(st.nextToken());
        double closeValue = Double.parseDouble(st.nextToken());
        long volumeValue = Long.parseLong(st.nextToken());

        // Add this value to our series'
        open.add(day, openValue);
        close.add(day, closeValue);
        high.add(day, highValue);
        low.add(day, lowValue);

        // Read the next day
        line = br.readLine();
      }

      // Build the datasets
      dataset.addSeries(open);
      dataset.addSeries(close);
      dataset.addSeries(low);
      dataset.addSeries(high);
      datasetOpenClose.addSeries(open);
      datasetOpenClose.addSeries(close);
      datasetHighLow.addSeries(high);
      datasetHighLow.addSeries(low);

      JFreeChart summaryChart = buildChart(dataset, "Summary", true);
      JFreeChart openCloseChart = buildChart(datasetOpenClose, "Open/Close Data", false);
      JFreeChart highLowChart = buildChart(datasetHighLow, "High/Low Data", true);
      JFreeChart highLowDifChart =
          buildDifferenceChart(datasetHighLow, "High/Low Difference Chart");

      // Create this panel
      this.setLayout(new GridLayout(2, 2));
      this.add(new ChartPanel(summaryChart));
      this.add(new ChartPanel(openCloseChart));
      this.add(new ChartPanel(highLowChart));
      this.add(new ChartPanel(highLowDifChart));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 20
0
 public void getWords(String fileName) throws IOException {
   this.word = new ArrayList<String>();
   BufferedReader buf = new BufferedReader(new FileReader(fileName));
   while (buf.ready()) {
     this.word.add(buf.readLine());
   }
 }
Ejemplo n.º 21
0
  public TileMap(String s, int tileSize) {

    this.tileSize = tileSize;

    try {

      BufferedReader br = new BufferedReader(new FileReader(s));

      mapWidth = Integer.parseInt(br.readLine());
      mapHeight = Integer.parseInt(br.readLine());
      map = new int[mapHeight][mapWidth];

      minx = GamePanel.WIDTH - mapWidth * tileSize;
      miny = GamePanel.HEIGHT - mapHeight * tileSize;

      String delimiters = "\\s+";
      for (int row = 0; row < mapHeight; row++) {
        String line = br.readLine();
        String[] tokens = line.split(delimiters);
        for (int col = 0; col < mapWidth; col++) {
          map[row][col] = Integer.parseInt(tokens[col]);
        }
      }

    } catch (Exception e) {
    }
  }
Ejemplo n.º 22
0
    public static Settings init() throws Exception {
      File f = new File("galaxyviewer.ini");
      if (f.getAbsoluteFile().getParentFile().getName().equals("bin"))
        f = new File("..", "galaxyviewer.ini");
      Settings settings;
      if (f.exists()) {
        settings = new Settings();
        BufferedReader in = new BufferedReader(new FileReader(f));
        while (true) {
          String s = in.readLine();
          if (s == null) break;
          if (s.contains("=") == false) continue;
          String[] el = s.split("=", -1);
          if (el[0].equalsIgnoreCase("PlayerNr"))
            settings.playerNr = Integer.parseInt(el[1].trim()) - 1;
          if (el[0].equalsIgnoreCase("GameName")) settings.gameName = el[1].trim();
          if (el[0].equalsIgnoreCase("GameDir")) settings.directory = el[1].trim();
        }
        in.close();
      } else settings = new Settings();

      JTextField pNr = new JTextField("" + (settings.playerNr + 1));
      JTextField gName = new JTextField(settings.gameName);
      JTextField dir = new JTextField("" + settings.directory);

      JPanel p = new JPanel();
      p.setLayout(new GridLayout(3, 2));
      p.add(new JLabel("Player nr"));
      p.add(pNr);
      p.add(new JLabel("Game name"));
      p.add(gName);
      p.add(new JLabel("Game directory"));
      p.add(dir);
      gName.setToolTipText("Do not include file extensions");
      String[] el = {"Ok", "Cancel"};
      int ok =
          JOptionPane.showOptionDialog(
              null,
              p,
              "Choose settings",
              JOptionPane.OK_CANCEL_OPTION,
              JOptionPane.QUESTION_MESSAGE,
              null,
              el,
              el[0]);
      if (ok != 0) System.exit(0);
      settings.playerNr = Integer.parseInt(pNr.getText().trim()) - 1;
      settings.directory = dir.getText().trim();
      settings.gameName = gName.getText().trim();
      BufferedWriter out = new BufferedWriter(new FileWriter(f));
      out.write("PlayerNr=" + (settings.playerNr + 1) + "\n");
      out.write("GameName=" + settings.gameName + "\n");
      out.write("GameDir=" + settings.directory + "\n");
      out.flush();
      out.close();
      return settings;
    }
  public void connect(String page) {
    bf.status.setText("Connecting to server...");
    try {
      Socket socket = new Socket(server, port);
      // Set the server connect timeout to 5 seconds
      socket.setSoTimeout(5000);
      BufferedReader inputStream =
          new BufferedReader(new InputStreamReader(socket.getInputStream()));
      PrintWriter outputStream =
          new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);

      bf.status.setText("Reading URL...");
      outputStream.println("GET " + page + " HTTP/1.0");
      outputStream.println("Host: " + server);
      outputStream.println();
      String line = "";
      String text = "";
      int count = 0;
      boolean headers = true;
      while ((line = inputStream.readLine()) != null) {
        if (line.equals("")) {
          headers = false;
        }
        if (!headers && !line.equals("")) {
          text = text + parse(line) + "\n";
        }
        if (count != 1) {
          bf.status.setText("Read " + count + " lines");
        } else {
          bf.status.setText("Read " + count + " line");
        }
        count++;
      }
      bf.setText(text);
      bf.status.setText("done");

      socket.close();

    } catch (UnknownHostException e) {
      System.out.println(e);
      bf.setText("Not online");
      bf.status.setText("");
    } catch (SocketException e) {
      System.out.println("Socket Exception " + e);
      bf.setText("Socket exception");
      bf.status.setText("");
    } catch (InterruptedIOException e) {
      System.out.println("Read to server timed out " + e);
      bf.setText("Server connect timed out");
      bf.status.setText("");
    } catch (IOException e) {
      bf.setText("IO exception");
      bf.status.setText("");
      System.out.println("IOException " + e);
    }
  }
Ejemplo n.º 24
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.º 25
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.º 26
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.º 27
0
  /**
   * Locate the linux fonts based on the XML configuration file
   *
   * @param file The location of the XML file
   */
  private static void locateLinuxFonts(File file) {
    if (!file.exists()) {
      System.err.println("Unable to open: " + file.getAbsolutePath());
      return;
    }

    try {
      InputStream in = new FileInputStream(file);

      BufferedReader reader = new BufferedReader(new InputStreamReader(in));
      ByteArrayOutputStream temp = new ByteArrayOutputStream();
      PrintStream pout = new PrintStream(temp);
      while (reader.ready()) {
        String line = reader.readLine();
        if (line.indexOf("DOCTYPE") == -1) {
          pout.println(line);
        }
      }

      in = new ByteArrayInputStream(temp.toByteArray());

      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();

      Document document = builder.parse(in);

      NodeList dirs = document.getElementsByTagName("dir");
      for (int i = 0; i < dirs.getLength(); i++) {
        Element element = (Element) dirs.item(i);
        String dir = element.getFirstChild().getNodeValue();

        if (dir.startsWith("~")) {
          dir = dir.substring(1);
          dir = userhome + dir;
        }

        addFontDirectory(new File(dir));
      }

      NodeList includes = document.getElementsByTagName("include");
      for (int i = 0; i < includes.getLength(); i++) {
        Element element = (Element) dirs.item(i);
        String inc = element.getFirstChild().getNodeValue();
        if (inc.startsWith("~")) {
          inc = inc.substring(1);
          inc = userhome + inc;
        }

        locateLinuxFonts(new File(inc));
      }
    } catch (Exception e) {
      e.printStackTrace();
      System.err.println("Unable to process: " + file.getAbsolutePath());
    }
  }
Ejemplo n.º 28
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.º 29
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.º 30
0
  public Main() {
    try {
      BufferedReader in;
      in = new BufferedReader(new InputStreamReader(System.in)); // Used for CCC
      int numLights = Integer.parseInt(in.readLine());
      int[] states = new int[numLights];
      for (int i = 0; i < numLights; i++) {
        states[i] = Integer.parseInt(in.readLine());
      }
      ArrayDeque<Scenario> Q = new ArrayDeque<Scenario>();
      HashMap<String, Integer> dp = new HashMap<String, Integer>();

      int moves = 0;
      Q.addLast(new Scenario(states));
      while (!Q.isEmpty()) {
        int size = Q.size();
        for (int q = 0; q < size; q++) {
          Scenario temp = Q.removeFirst();
          if (isEmpty(temp.states)) {
            System.out.println(moves);
            return;
          } else {
            for (int i = 0; i < temp.states.length; i++) {
              if (temp.states[i] == 0) {
                int[] newArr = Arrays.copyOf(temp.states, temp.states.length);
                newArr[i] = 1;
                newArr = fixArray(newArr);
                String arr = "";
                for (int p = 0; p < newArr.length; p++) arr += newArr[p];
                if (dp.get(arr) == null) {
                  dp.put(arr, moves);
                  Q.addLast(new Scenario(newArr));
                } else {
                  int val = dp.get(arr);
                  if (val != 0 && moves < val) {
                    dp.put(arr, moves);
                    Q.addLast(new Scenario(newArr));
                  }
                }

                // outputArr(newArr);
              }
            }
          }
        }
        moves++;
      }

    } catch (IOException e) {
      System.out.println("IO: General");
    }
  }