Exemple #1
0
  /**
   * POSTs the given content to the given URL.
   *
   * @param String the url to post to
   * @param content the body of the post
   * @param contentType the content-type of the request
   * @exception IOException if post fails
   */
  public static String post(String urlString, String contentType, String content)
      throws IOException {

    Debug.log(
        Debug.MSG_LIFECYCLE,
        "HTTPUtils: Trying to post " + content + " to web server at [ " + urlString + "]");

    StringBuffer responseBuffer = new StringBuffer();

    URL url = new URL(urlString);

    ClientSocket cs = new ClientSocket();

    HTTPUtils.Response resp = post(cs, url, new Hashtable(), contentType, content);

    while (true) {
      String line = resp.content.readLine();
      if (line == null) break;

      responseBuffer.append(line);
    }

    Debug.log(
        Debug.MSG_LIFECYCLE,
        "HTTPUtils: Obtained response from web server : " + responseBuffer.toString());

    cleanUp(cs);

    return responseBuffer.toString();
  }
Exemple #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();
  }
    public void run() {
      try {
        while (true) {
          StringBuffer sb = new StringBuffer();
          DataInputStream is = new DataInputStream(new BufferedInputStream(s.getInputStream()));
          String inputLine = "";
          int i;
          // System.out.println("server prepare accept msg");
          while ((i = is.read()) != 59) {

            if (i == -1) {

              continue;
            }
            sb.append((char) i);
          }
          if (sb.toString().indexOf("NETTST") == -1) {
            System.out.println("服务器收到信息为" + sb.toString());
          }
          System.out.println("服务器收到信息为" + sb.toString());
          // System.out.println("server has accept msg");
          this.sleep(2000);
          // is.close();
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  /**
   * Method to return a set of hazard data within CACHE_DISTANCE of given location
   *
   * @param location An instance of Location that stores latitude and longitude data
   * @return JSONObject an instance of JSONObject with json encoded hazard data
   * @throws IOException
   * @throws JSONException
   */
  public static JSONObject getHazards(LatLng location) throws IOException, JSONException {
    // request hazards from long / lat data and retrieve json hazards
    // tested and working!

    String longitude = String.valueOf(location.longitude);
    String latitude = String.valueOf(location.latitude);

    String query = String.format("longitude=%s&latitude=%s", longitude, latitude);
    // encode the post query

    // Set a POST connection
    URL url = new URL(site + "/request.php");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    System.out.println(query);
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    conn.setDoInput(true);

    // Send post request
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    writer.write(query);
    writer.flush();
    writer.close();

    BufferedReader response = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuffer hazards = new StringBuffer();
    String inputLine;
    while ((inputLine = response.readLine()) != null) {
      hazards.append(inputLine);
    }

    response.close();

    return new JSONObject(hazards.toString());
  }
 /**
  * Convert a String in xs:anyURI to an xs:base64Binary.
  *
  * <p>The URI has to be a URL. It is read entirely
  */
 public static String anyURIToBase64Binary(String value) {
   InputStream is = null;
   try {
     // Read from URL and convert to Base64
     is = URLFactory.createURL(value).openStream();
     final StringBuffer sb = new StringBuffer();
     XMLUtils.inputStreamToBase64Characters(
         is,
         new ContentHandlerAdapter() {
           public void characters(char ch[], int start, int length) {
             sb.append(ch, start, length);
           }
         });
     // Return Base64 String
     return sb.toString();
   } catch (IOException e) {
     throw new OXFException(e);
   } finally {
     if (is != null) {
       try {
         is.close();
       } catch (IOException e) {
         throw new OXFException(e);
       }
     }
   }
 }
Exemple #6
0
 /** List file names */
 public Enumeration nlst(String s) throws IOException {
   InetAddress inetAddress = InetAddress.getLocalHost();
   byte ab[] = inetAddress.getAddress();
   serverSocket_ = new ServerSocket(0, 1);
   StringBuffer sb = new StringBuffer(32);
   sb.append("PORT ");
   for (int i = 0; i < ab.length; i++) {
     sb.append(String.valueOf(ab[i] & 255));
     sb.append(",");
   }
   sb.append(String.valueOf(serverSocket_.getLocalPort() >>> 8 & 255));
   sb.append(",");
   sb.append(String.valueOf(serverSocket_.getLocalPort() & 255));
   if (issueCommand(sb.toString()) != FTP_SUCCESS) {
     serverSocket_.close();
     throw new IOException(getResponseString());
   } else if (issueCommand("NLST " + ((s == null) ? "" : s)) != FTP_SUCCESS) {
     serverSocket_.close();
     throw new IOException(getResponseString());
   }
   dataSocket_ = serverSocket_.accept();
   serverSocket_.close();
   serverSocket_ = null;
   Vector v = readServerResponse_(dataSocket_.getInputStream());
   dataSocket_.close();
   dataSocket_ = null;
   return (v == null) ? null : v.elements();
 }
    public void run() {
      StringBuffer data = new StringBuffer();
      Print.logDebug("Client:InputThread started");

      while (true) {
        data.setLength(0);
        boolean timeout = false;
        try {
          if (this.readTimeout > 0L) {
            this.socket.setSoTimeout((int) this.readTimeout);
          }
          ClientSocketThread.socketReadLine(this.socket, -1, data);
        } catch (InterruptedIOException ee) { // SocketTimeoutException ee) {
          // error("Read interrupted (timeout) ...");
          if (getRunStatus() != THREAD_RUNNING) {
            break;
          }
          timeout = true;
          // continue;
        } catch (Throwable t) {
          Print.logError("Client:InputThread - " + t);
          t.printStackTrace();
          break;
        }
        if (!timeout || (data.length() > 0)) {
          ClientSocketThread.this.handleMessage(data.toString());
        }
      }

      synchronized (this.threadLock) {
        this.isRunning = false;
        Print.logDebug("Client:InputThread stopped");
        this.threadLock.notify();
      }
    }
 /**
  * ** Reads a line from the specified socket's input stream ** @param socket The socket to read a
  * line from ** @param maxLen The maximum length of of the line to read ** @param sb The string
  * buffer to use ** @throws IOException if an error occurs or the server has stopped
  */
 protected static String socketReadLine(Socket socket, int maxLen, StringBuffer sb)
     throws IOException {
   if (socket != null) {
     int dataLen = 0;
     StringBuffer data = (sb != null) ? sb : new StringBuffer();
     InputStream input = socket.getInputStream();
     while ((maxLen < 0) || (maxLen > dataLen)) {
       int ch = input.read();
       // Print.logInfo("ReadLine char: " + ch);
       if (ch < 0) {
         // this means that the server has stopped
         throw new IOException("End of input");
       } else if (ch == LineTerminatorChar) {
         // include line terminator in String
         data.append((char) ch);
         dataLen++;
         break;
       } else {
         // append character
         data.append((char) ch);
         dataLen++;
       }
     }
     return data.toString();
   } else {
     return null;
   }
 }
Exemple #9
0
 /** Converts a normal string to a html conform string */
 public static String conv2Html(String st) {
   StringBuffer buf = new StringBuffer();
   for (int i = 0; i < st.length(); i++) {
     buf.append(conv2Html(st.charAt(i)));
   }
   return buf.toString();
 }
Exemple #10
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;
  }
 public String toString() {
   StringBuffer sb = new StringBuffer(url.length() + 17);
   sb.append("[MyMockCachedUrl: ");
   sb.append(url);
   sb.append("]");
   return sb.toString();
 }
Exemple #12
0
  public static void main(String[] args) {

    String hostname;

    if (args.length > 0) {
      hostname = args[0];
    } else {
      hostname = "tock.usno.navy.mil";
    }

    try {
      Socket theSocket = new Socket(hostname, 13);
      InputStream timeStream = theSocket.getInputStream();
      StringBuffer time = new StringBuffer();
      int c;
      while ((c = timeStream.read()) != -1) time.append((char) c);
      String timeString = time.toString().trim();
      System.out.println("It is " + timeString + " at " + hostname);
    } // end try
    catch (UnknownHostException e) {
      System.err.println(e);
    } catch (IOException e) {
      System.err.println(e);
    }
  } // end main
  public static void main(String[] args) {

    StringBuffer result = new StringBuffer("<html><body><h1>Fibonacci Sequence</h1><ol>");

    long f1 = 0;
    long f2 = 1;

    for (int i = 0; i < 50; i++) {
      result.append("<li>");
      result.append(f1);
      long temp = f2;
      f2 = f1 + f2;
      f1 = temp;
    }

    result.append("</ol></body></html>");

    JEditorPane jep = new JEditorPane("text/html", result.toString());
    jep.setEditable(false);

    //  new FibonocciRectangles().execute();
    JScrollPane scrollPane = new JScrollPane(jep);
    JFrame f = new JFrame("Fibonacci Sequence");
    f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    f.setContentPane(scrollPane);
    f.setSize(512, 342);
    EventQueue.invokeLater(new FrameShower(f));
  }
 public String toString() {
   StringBuffer sb = new StringBuffer();
   sb.append(this.getClass().getSuperclass().getName());
   sb.append('[');
   if (!isOpen()) sb.append("closed");
   else {
     synchronized (stateLock) {
       switch (state) {
         case ST_UNCONNECTED:
           sb.append("unconnected");
           break;
         case ST_PENDING:
           sb.append("connection-pending");
           break;
         case ST_CONNECTED:
           sb.append("connected");
           if (!isInputOpen) sb.append(" ishut");
           if (!isOutputOpen) sb.append(" oshut");
           break;
       }
       if (localAddress() != null) {
         sb.append(" local=");
         sb.append(localAddress().toString());
       }
       if (remoteAddress() != null) {
         sb.append(" remote=");
         sb.append(remoteAddress().toString());
       }
     }
   }
   sb.append(']');
   return sb.toString();
 }
Exemple #15
0
  private String md5(String data) {

    StringBuffer sb = new StringBuffer();

    try {
      MessageDigest messageDigest = MessageDigest.getInstance("MD5");
      messageDigest.update(data.getBytes());
      byte[] digestBytes = messageDigest.digest();

      /* convert to hexstring */
      String hex = null;

      for (int i = 0; i < digestBytes.length; i++) {
        hex = Integer.toHexString(0xFF & digestBytes[i]);

        if (hex.length() < 2) {
          sb.append("0");
        }
        sb.append(hex);
      }
    } catch (Exception ex) {
      System.out.println(ex.getMessage());
    }

    return sb.toString();
  }
Exemple #16
0
  private String ReadWholeFileToString(String filename) {

    File file = new File(filename);
    StringBuffer contents = new StringBuffer();
    BufferedReader reader = null;

    try {
      reader = new BufferedReader(new FileReader(file));
      String text = null;

      // repeat until all lines is read
      while ((text = reader.readLine()) != null) {
        contents.append(text).append(System.getProperty("line.separator"));
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (reader != null) {
          reader.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    // show file contents here
    return contents.toString();
  }
Exemple #17
0
  // createPageString -
  // Create list of pages for search results
  private String createPageString(
      int numberOfItems, int itemsPerPage, int currentPage, String baseUrl) {
    StringBuffer pageString = new StringBuffer();

    // Calculate the total number of pages
    int totalPages = 1;
    if (numberOfItems > itemsPerPage) {
      double pages = Math.ceil(numberOfItems / (double) itemsPerPage);
      totalPages = (int) Math.ceil(pages);
    }

    //
    if (totalPages > 1) {
      for (int i = 1; i <= totalPages; i++) {
        if (i == currentPage) {
          pageString.append(i);
        } else {
          pageString.append("<a href=\"" + baseUrl + i + "\" title=\"" + i + "\">" + i + "</a>");
        }

        if (i != totalPages) pageString.append(" ");
      }
    } else {
      pageString.append("1");
    }

    return pageString.toString();
  }
 public String getNameString() {
   StringBuffer str = new StringBuffer();
   for (int i = 0; i < nameStrings.length; i++) {
     if (i > 0) str.append("/");
     str.append(nameStrings[i]);
   }
   return str.toString();
 }
Exemple #19
0
 /**
  * ** A String reperesentation of this URI (with arguments) ** @return A String representation of
  * this URI
  */
 public String toString() {
   StringBuffer sb = new StringBuffer(this.getURI());
   if (!ListTools.isEmpty(this.getKeyValList())) {
     sb.append("?");
     this.getArgString(sb);
   }
   return sb.toString();
 }
Exemple #20
0
 /**
  * @param s
  * @return
  */
 public static String mask(final String s) {
   final StringBuffer buffer = new StringBuffer(25);
   final int count = (s != null ? s.length() : 0);
   for (int n = 0; n < count; n++) {
     buffer.append('*');
   }
   return buffer.toString();
 }
Exemple #21
0
 /**
  * ** A String reperesentation of this URI (with arguments) ** @param includeBlankValues True to
  * include keys for blank values. ** @return A String representation of this URI
  */
 public String toString(boolean includeBlankValues) {
   StringBuffer sb = new StringBuffer(this.getURI());
   if (!ListTools.isEmpty(this.getKeyValList())) {
     sb.append("?");
     this.getArgString(sb, includeBlankValues);
   }
   return sb.toString();
 }
Exemple #22
0
 /** Get the name of the present working directory on the ftp file system */
 public String pwd() throws IOException {
   issueCommandCheck("PWD");
   StringBuffer result = new StringBuffer();
   for (Enumeration e = serverResponse.elements(); e.hasMoreElements(); ) {
     result.append((String) e.nextElement());
   }
   return result.toString();
 }
	public void sendXHeader() throws IOException
	{
		StringBuffer header1 = new StringBuffer();
		StringBuffer header2 = new StringBuffer();
		int lengthOfXA = param.getRandomLengthOfXA();
		int lengthOfXB = param.getRandomLengthOfXB();
		for (int i=0 ; i<lengthOfXA ; i++) 
		{
			header1.append(Misc.getRandomByte());
		}
		for (int i=0 ; i<lengthOfXB ; i++) 
		{
			header2.append(Misc.getRandomByte());
		}
		socket.getOutputStream().write(("X-" + header1.toString() + ": " + header2.toString() + "\r\n").getBytes());
		socket.getOutputStream().flush();
	}
  /** Return a String representation of this object. */
  public String toString() {

    if (filterConfig == null) return ("KeepSession()");
    StringBuffer sb = new StringBuffer("KeepSession(");
    sb.append(filterConfig);
    sb.append(")");
    return (sb.toString());
  }
Exemple #25
0
 public String toString() {
   StringBuffer sb = new StringBuffer();
   sb.append(this.key);
   if (this.hasValue()) {
     sb.append("=").append(this.val);
   }
   return sb.toString();
 }
Exemple #26
0
 /**
  * 构造访问sms url需要参数
  *
  * @param title
  * @param content
  */
 public void alert(String title, String content) {
   StringBuffer param = new StringBuffer("");
   param.append("function=").append(title).append("&");
   param.append("ms=").append(content).append("&");
   param.append("mo=").append(this.phone).append("&");
   param.append("priority=Z");
   this.sendPost(param.toString(), false);
 }
Exemple #27
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();
 }
  /**
   * Used to write Resources for a Subject. Resources will use "ObjectNode" method.
   *
   * @param predicate PredicateNode
   * @param object Literal
   * @param writer PrintWriter
   * @throws GraphException
   */
  protected void writeStatement(
      Graph graph, SubjectNode subject, PredicateNode predicate, Literal object, PrintWriter writer)
      throws GraphException {

    // determine if the Literal has a datatype
    URI datatype = object.getDatatypeURI();

    // Get the lexical form of the literal
    String literalObject = object.getLexicalForm();

    // Create the StringBuffer to hold the resultant string
    StringBuffer buffer = new StringBuffer();

    // Escape the XML string
    StringUtil.quoteAV(literalObject, buffer);

    if (datatype != null) {

      // write as:  <predicateURI rdf:datatype="datatype">"Literal value"
      //           </predicateURI>
      writer.println(
          "    <"
              + this.getURI(predicate)
              + " "
              + RDF_PREFIX
              + ":datatype=\""
              + datatype
              + "\">"
              + buffer.toString()
              + "</"
              + this.getURI(predicate)
              + ">");
    } else {

      // write as:  <predicateURI>"Literal value"</predicateURI>
      writer.println(
          "    <"
              + this.getURI(predicate)
              + ">"
              + buffer.toString()
              + "</"
              + this.getURI(predicate)
              + ">");
    }
  }
Exemple #29
0
 private static String generateSendString(int seq) {
   StringBuffer buf = new StringBuffer("PING ");
   buf.append(seq);
   buf.append(' ');
   SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
   buf.append(fmt.format(new Date()));
   buf.append('\n');
   return buf.toString();
 }
Exemple #30
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();
  }