private String ask(String cmd) {
    BufferedWriter out = null;
    BufferedReader in = null;
    Socket sock = null;
    String ret = "";
    try {
      System.out.println(server);
      sock = new Socket(server, ServerListener.PORT);
      out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
      out.write(cmd, 0, cmd.length());
      out.flush();
      in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
      int inr = in.read();
      while (inr != ';') {
        ret += Character.toString((char) inr);
        inr = in.read();
      }
    } catch (IOException io) {
      io.printStackTrace();
    } finally {
      try {
        out.close();
        in.close();
        sock.close();
      } catch (IOException io) {
        io.printStackTrace();
      }
    }

    return ret;
  }
  public static char[] readData(BufferedReader in) throws IOException {
    char[] c1 = new char[PACKET_SIZE];
    int i;
    int c_temp = in.read(); // c_temp is an int and not a char;
    if (c_temp != -1) {
      c1[0] = (char) c_temp;
    }

    for (i = 1; i < PACKET_SIZE && c_temp != -1; i++) {
      c_temp = in.read();
      c1[i] = (char) c_temp;
    }
    return c1;
  }
Exemple #3
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;
  }
  /**
   * Empfaengt einen String (blockiert solange, bis der eingestellte TimeOut ueberschritten wurde)
   * ueber die Socket-Verbindung vom Communicator-Objekt des Clients.
   *
   * @return <code>String</code> empfangene Daten
   */
  public String receive() throws InterruptedIOException, IOException {
    String s;
    int len;
    char[] c;
    StringWriter w = new StringWriter();
    PrintWriter result = new PrintWriter(w);

    // falls nichts zu lesen ist
    s = in.readLine();
    if (s == null) return null;

    // zuerst L"ange der zu empfangenen Daten lesen, dann Daten selbst
    len = Integer.parseInt(s);
    c = new char[len];
    if (in.read(c, 0, len) == -1)
      System.out.println("ServerThread " + myNumber + " : error reading from socket!");

    /*
     * while (s.equals("")) { while(in.ready()) {
     * result.print(in.readLine()); if (in.ready()) result.println(); }
     * result.flush(); w.flush(); s = w.toString(); }
     */

    return new String(c);
  }
Exemple #5
0
  /** Read one tag. Adapted from code by Elliotte Rusty Harold */
  protected String readTag() throws IOException {
    StringBuffer theTag = new StringBuffer("<");
    int i = '<';

    while (i != '>' && (i = inrdr.read()) != -1) {
      theTag.append((char) i);
    }
    return theTag.toString();
  }
Exemple #6
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();
 }
Exemple #7
0
 /** Read the next tag. */
 public String nextTag() throws IOException {
   int i;
   while ((i = inrdr.read()) != -1) {
     char thisChar = (char) i;
     if (thisChar == '<') {
       String tag = readTag();
       return tag;
     }
   }
   return null;
 }
 private String getResponse(InputStream in) {
   StringBuilder response = new StringBuilder();
   try {
     BufferedReader rd = new BufferedReader(new InputStreamReader(in));
     char[] buf = new char[1024];
     int read = 0;
     while ((read = rd.read(buf)) > 0) {
       response.append(buf, 0, read);
     }
     rd.close();
     in.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
   return response.toString();
 }
Exemple #9
0
 /**
  * Adds an entire documents to the 'brain'. Useful for feeding in stray theses, but be careful not
  * to put too much in, or you may run out of memory!
  */
 public void addDocument(String uri) throws IOException {
   BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(uri).openStream()));
   StringBuffer buffer = new StringBuffer();
   int ch = 0;
   while ((ch = reader.read()) != -1) {
     buffer.append((char) ch);
     if (END_CHARS.indexOf((char) ch) >= 0) {
       String sentence = buffer.toString();
       sentence = sentence.replace('\r', ' ');
       sentence = sentence.replace('\n', ' ');
       add(sentence);
       buffer = new StringBuffer();
     }
   }
   add(buffer.toString());
   reader.close();
 }
  private byte[] readMultiPartChunk(ServletInputStream requestStream, String contentType)
      throws IOException {
    // fast forward stream past multi-part header
    int boundaryOff = contentType.indexOf("boundary="); // $NON-NLS-1$
    String boundary = contentType.substring(boundaryOff + 9);
    BufferedReader reader =
        new BufferedReader(new InputStreamReader(requestStream, "ISO-8859-1")); // $NON-NLS-1$
    StringBuffer out = new StringBuffer();
    // skip headers up to the first blank line
    String line = reader.readLine();
    while (line != null && line.length() > 0) line = reader.readLine();
    // now process the file

    char[] buf = new char[1000];
    int read;
    while ((read = reader.read(buf)) > 0) {
      out.append(buf, 0, read);
    }
    // remove the boundary from the output (end of input is \r\n--<boundary>--\r\n)
    out.setLength(out.length() - (boundary.length() + 8));
    return out.toString().getBytes("ISO-8859-1"); // $NON-NLS-1$
  }
Exemple #11
0
 public static void GetDownloadIndex() throws Exception {
   BufferedReader in = new BufferedReader(new InputStreamReader(ylink.openStream()));
   // BufferedWriter out = new BufferedWriter(new FileWriter("output.html"));
   int b;
   String op = null;
   while ((b = in.read()) != -1) {
     //	out.write(b);
     op = op + (char) b;
   }
   String[] list = op.split("url=");
   for (String i : list) {
     if (i.startsWith("https")) {
       set.add(i.split(",")[0]);
     }
   }
   String url = null, itag = null, quality_label = null, type = null;
   for (String i : set) {
     String temp = i;
     temp = temp.replace("\\", "\\\\");
     for (String sdata : temp.split("\\\\")) {
       if (sdata.startsWith("https")) url = sdata;
     }
     if (url != null) {
       if (url.startsWith("https")) {
         url = url.split(" ")[0];
         url = URLDecoder.decode(url, "UTF-8");
         if (url.contains("mime=")) type = (url.split("mime=")[1]).split("&")[0];
         if (url.contains("itag")) itag = (url.split("itag=")[1]).split("&")[0];
         if (url.contains("&gir=yes")) {
           if (type.startsWith("video"))
             video_set.add(url + "\ntype: " + type + "\nitag: " + itag);
           else if (type.startsWith("audio"))
             audio_set.add(url + "\ntype: " + type + "\nitag: " + itag);
         } else av_set.add(url + "\ntype: " + type + "\nitag: " + itag);
       }
     }
   }
 }
Exemple #12
0
  /**
   * Returns the result of reading an element's handler.
   *
   * @param elementName The element name.
   * @param handlerName The handler name.
   * @return Char array containing the data.
   * @exception NoSuchHandlerException If there is no such read handler.
   * @exception NoSuchElementException If there is no such element in the current configuration.
   * @exception HandlerErrorException If the handler returned an error.
   * @exception PermissionDeniedException If the router would not let us access the handler.
   * @exception IOException If there was a stream or socket error.
   * @exception ClickException If there was some other error accessing the handler (e.g., the
   *     ControlSocket returned an unknown unknown error code, or the response could otherwise not
   *     be understood).
   * @see #checkHandler
   * @see #write
   * @see #getConfigElementNames
   * @see #getElementHandlers
   */
  public char[] read(String elementName, String handlerName) throws ClickException, IOException {
    String handler = handlerName;
    if (elementName != null) handler = elementName + "." + handlerName;
    _out.write("READ " + handler + "\n");
    _out.flush();

    // make sure we read all the response lines...
    String response = "";
    String lastLine = null;
    do {
      lastLine = _in.readLine();
      if (lastLine == null) throw new IOException("ControlSocket stream closed unexpectedly");
      if (lastLine.length() < 4) throw new ClickException("Bad response line from ControlSocket");
      response = response + lastLine.substring(4);
    } while (lastLine.charAt(3) == '-');

    int code = getResponseCode(lastLine);
    if (code != CODE_OK && code != CODE_OK_WARN)
      handleErrCode(code, elementName, handlerName, response);

    response = _in.readLine();
    if (response == null) throw new IOException("ControlSocket stream closed unexpectedly");
    int num_bytes = getDataLength(response);
    if (num_bytes < 0) throw new ClickException("Bad length returned from ControlSocket");

    if (num_bytes == 0) return new char[0];

    // sometimes, read will return without completely filling the
    // buffer (e.g. on win32 JDK)
    char data[] = new char[num_bytes];
    int bytes_left = num_bytes;
    while (bytes_left > 0) {
      int bytes_read = _in.read(data, num_bytes - bytes_left, bytes_left);
      bytes_left -= bytes_read;
    }
    return data;
  }
  public static int beginGUIConfigurationTransaction(String sConfigurationFileName, String sUser) {

    String sConfigurationLockFile;
    BufferedWriter bwBufferedWriter;
    File fFile;

    sConfigurationLockFile = new String(sConfigurationFileName + ".lck");

    System.out.println("beginGUIConfigurationTransaction: " + sConfigurationFileName);

    try {
      fFile = new File(URLDecoder.decode(sConfigurationLockFile, "UTF-8"));
    } catch (IOException e) {
      JOptionPane.showMessageDialog(
          null, "URLDecoder.decode failed", "ConfigurationTransaction", JOptionPane.ERROR_MESSAGE);

      return 1;
    }

    if (fFile.exists()) {
      BufferedReader brBufferedReader;
      char cLastConfigurationUser[];

      cLastConfigurationUser = new char[((int) fFile.length())];

      try {
        brBufferedReader =
            new BufferedReader(new FileReader(URLDecoder.decode(sConfigurationLockFile, "UTF-8")));
        brBufferedReader.read(cLastConfigurationUser, 0, (int) (fFile.length()));
        brBufferedReader.close();

        System.out.println(
            "Last configuration user: "******"Operation on BufferedWriter failed (1)",
            "ConfigurationTransaction",
            JOptionPane.ERROR_MESSAGE);

        return 1;
      }

      if (String.copyValueOf(cLastConfigurationUser).compareTo(sUser) == 0) {
        System.out.println("File. delete: " + sConfigurationFileName);

        if (fFile.delete() == false) {
          JOptionPane.showMessageDialog(
              null, "fFile.delete failed", "ConfigurationTransaction", JOptionPane.ERROR_MESSAGE);

          return 2;
        }
      } else {
        JOptionPane.showMessageDialog(
            null,
            "The configuration is locked by "
                + String.copyValueOf(cLastConfigurationUser)
                + ".\nYou cannot change the configuration.",
            "ConfigurationTransaction",
            JOptionPane.PLAIN_MESSAGE);

        return 3;
      }
    }

    try {
      bwBufferedWriter =
          new BufferedWriter(new FileWriter(URLDecoder.decode(sConfigurationLockFile, "UTF-8")));
      bwBufferedWriter.write(sUser, 0, sUser.length());
      bwBufferedWriter.close();

      System.out.println("Configuration user written: " + sUser);
    } catch (IOException e) {
      JOptionPane.showMessageDialog(
          null,
          "Operation on BufferedWriter failed (" + e + ")",
          "ConfigurationTransaction",
          JOptionPane.ERROR_MESSAGE);

      return 4;
    }

    return 0;
  }
  // This uses the key to get the entire record from the web page
  // For now the fields that compose the record will be hardcoded
  // but these fields need to be checked with the advertisement
  // in future releases. It then uses the parameter passed to it
  // to decide which fields to return
  // Also put's the field values in a Hashtable that can be later accessed
  private synchronized String getRecordFields(String key, String param) {

    fieldsTable = null;

    String city = new String(key);
    displayMessage("DEBUG", "WCNForecastWeatherQueryFn::getRecordFields " + "city = " + city);

    // Add the URL extension corresponding to the city.
    StringBuffer sbuf = new StringBuffer();
    for (int i = 0; i < city.length(); i++) {
      char ch = city.charAt(i);
      if (ch != ' ' && ch != '\t' && ch != '\n') sbuf.append(ch);
    }
    String formURLString = siteURLString + new String(sbuf) + ".html";

    URL infoURL = null;
    try {
      infoURL = new URL(formURLString);
    } catch (MalformedURLException e) {
      displayMessage(
          "ERROR",
          "WCNForecastWeatherQueryFn::getRecordFields " + "Malformed URL " + formURLString);
      return null;
    }
    // displayMessage("DEBUG", "WCNForecastWeatherQueryFn::getRecordFields " +
    //	   "Got URL for site: " + formURLString);
    Object content = null;
    try {
      content = infoURL.getContent();
    } catch (IOException e) {
      displayMessage(
          "ERROR",
          "WCNForecastWeatherQueryFn::getRecordFields "
              + "Can't load content from "
              + formURLString);
      return null;
    }
    InputStreamReader input = new InputStreamReader((InputStream) content);
    BufferedReader reader = new BufferedReader(input);
    sbuf.setLength(0);
    boolean stillReading = true;
    char[] cbuf = new char[100000];
    int ccount = 0;
    long startTime = System.currentTimeMillis();
    while (stillReading) {
      try {
        ccount = reader.read(cbuf);
      } catch (IOException e) {
        displayMessage(
            "ERROR",
            "WCNForecastWeatherQueryFn::getRecordFields "
                + "IO error getting content from "
                + formURLString);
        return null;
      }
      if (ccount > 0) sbuf.append(cbuf, 0, ccount);
      if (ccount < 0) stillReading = false;
    }
    // displayMessage("DEBUG", "WCNForecastWeatherQueryFn::getRecordFields " +
    //	   "Time to read content: " + ((System.currentTimeMillis() - startTime) / 1000.0) +
    //            " seconds");
    String page = sbuf.toString();
    StringBuffer day = new StringBuffer();
    StringBuffer condition = new StringBuffer();

    int pos = page.indexOf("<!-- forecast include");
    int delimit;
    pos = page.indexOf("<TR>", pos);
    pos = page.indexOf("<TR>", pos + 1);
    pos = page.indexOf("<TR>", pos + 1);
    for (int n = 0; n < 10; n++) {
      pos = page.indexOf("<TR>", pos + 1);
      int daypos = page.indexOf("<BR>", pos) + 4;
      delimit = page.indexOf("</B>", daypos);
      day.append("(" + page.substring(daypos, delimit) + (n == 9 ? ")" : ") "));
      pos = page.indexOf("<FONT", daypos);
      int condpos = page.indexOf(">", pos) + 1;
      delimit = page.indexOf("</FONT>", condpos);
      condition.append("(" + page.substring(condpos, delimit) + (n == 9 ? ")" : ") "));
    }

    // Get the parser corresponding to the initial URL
    /*
       Parser infoParser = null;
       try {
         infoParser = new Parser(infoURL,true,display);
       } catch (Exception ex) {
         infoParser = null;
       }

       if (infoParser == null)     {
         displayMessage("ERROR",  "WCNForecastWeatherQueryFn::getRecordFields " +
    	     "Cannot initialize parser for page " + formURLString );
         return null ;
       }


       if (FILE_WRITE) {
         displayMessage("DEBUG", "WCNForecastWeatherQueryFn::getRecordFields " +
    	     "Site URL: " + formURLString +
    	     " Calling writeContent()." + FILE_WRITE_EXT_NUM);
         writeContent(infoParser.getContent());
       }


       displayMessage("DEBUG", "WCNForecastWeatherQueryFn::getRecordFields " +
    	   "ready to return record fields: " + param);

       displayMessage("DEBUG", "WCNForecastWeatherQueryFn::getRecordFields " +
    	   "city is: " + key);



       String ct = null;
       StringBuffer day = new StringBuffer();
       StringBuffer condition = new StringBuffer();
       String tag = null;

       while ((tag = infoParser.nextTag("NONE")) != null) {
         ct = infoParser.getContentBetween ();
         if ((ct == null) || (ct.length() == 0)) continue;
         ct = ct.replace('\n', ' ');
         ct = ct.replace('\r', ' ');
         if (ct.toLowerCase().indexOf("sunrise:") != -1) {
           tag = infoParser.nextTag("NONE");
    while (tag != null && !tag.equalsIgnoreCase("table"))
      tag = infoParser.nextTag("NONE");
    while (tag != null && !tag.equalsIgnoreCase("span"))
      tag = infoParser.nextTag("NONE");
           for ( int n = 0; n < 5; n++ ) {
             if (tag != null) {
               infoParser.removeContentBetween();
               tag = infoParser.nextTag("NONE");
               while (tag != null && !tag.equalsIgnoreCase("/span"))
                 tag = infoParser.nextTag("NONE");
               if (tag != null) {
                 day.append(infoParser.getContentBetween() + (n == 4 ? "" : " "));
                 tag = infoParser.nextTag("IMG");
                 while (tag != null && !tag.equalsIgnoreCase("img"))
                   tag = infoParser.nextTag("IMG");
                 if (tag != null)
                   condition.append(infoParser.getParameterValue("ALT") + (n == 4 ? "" : " "));
               }
             }
             tag = infoParser.nextTag("NONE");
             while (tag != null && !tag.equalsIgnoreCase("img"))
               tag = infoParser.nextTag("NONE");
             while (tag != null && !tag.equalsIgnoreCase("span"))
               tag = infoParser.nextTag("NONE");
             System.out.println("Content after condition = " + infoParser.getContentBetween());
           }
         }
         infoParser.removeContentBetween();
       }
       */

    // If we couldn't get at least a temperature from the page, it must
    // have been an invalid URL, ie.e, a city not in CNN database or
    // incorrectly spelled or designated.
    if (day == null) {
      displayMessage(
          "ERROR",
          "WCNForecastWeatherQueryFn::getRecordFields "
              + "URL "
              + formURLString
              + " is not a valid URL. "
              + "The \"CityCountry\" or \"CityState\" key may be wrong.");
      return null;
    }

    String weather =
        WEATHER_PERF_STRING
            + " "
            + ":"
            + DAY_STRING
            + " ("
            + day.toString()
            + ") "
            + ":"
            + CONDITION_STRING
            + " ("
            + condition.toString()
            + ")";

    if (param.equalsIgnoreCase(ALL_FIELDS)) {

      fieldsTable = new Hashtable();

      if (key != null) {
        fieldsTable.put(CITY_STRING, key);
      }
      if (day != null) {
        fieldsTable.put(DAY_STRING, day);
      }
      if (condition != null) {
        fieldsTable.put(CONDITION_STRING, condition);
      }
      if (formURLString != null) {
        fieldsTable.put(WEATHER_URL_STRING, formURLString);
      }

      if (key == null) {
        key = " ";
      }

      if (formURLString == null) {
        formURLString = " ";
      }

      String reply =
          "(reply :"
              + CITY_STRING
              + " ("
              + key
              + ") "
              + ":"
              + WEATHER_STRING
              + " ("
              + weather
              + ") "
              + ":"
              + WEATHER_URL_STRING
              + " ("
              + formURLString
              + "))";
      displayMessage(
          "DEBUG", "WCNForecastWeatherQueryFn::getRecordFields " + "Weather is: " + reply);
      return reply;
    } else if (param.equalsIgnoreCase(CITY_STRING)) {
      fieldsTable = new Hashtable();
      fieldsTable.put(CITY_STRING, key);
      return key;
    } else if (param.equalsIgnoreCase(WEATHER_STRING)) {
      fieldsTable = new Hashtable();
      fieldsTable.put(WEATHER_STRING, weather);
      return weather;
    } else if (param.equalsIgnoreCase(WEATHER_URL_STRING)) {
      fieldsTable = new Hashtable();
      fieldsTable.put(WEATHER_URL_STRING, formURLString);
      return formURLString;
    } else {
      return null;
    }
  }