Esempio n. 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();
  }
Esempio n. 2
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
Esempio n. 3
0
  /**
   * Method to update database on the server with new and changed hazards given as a JSONObject
   * instance
   *
   * @param uploadHazards A JSONObject instance with encoded new and update hazards
   * @throws IOException
   */
  public static void uploadHazards(JSONObject uploadHazards) throws IOException {
    // upload hazards in json to php (to use json_decode)
    // Hazard parameter should be encoded as json already

    // Set Post connection
    URL url = new URL(site + "/update.php");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    conn.setRequestMethod("POST");

    OutputStream writer = conn.getOutputStream();
    writer.write(
        uploadHazards.toString().getBytes("UTF-8")); // toString produces compact JSONString
    // no white space
    writer.close();
    // read response (success / error)

    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuffer response = new StringBuffer();
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
      response.append(inputLine);
    }
    in.close();
  }
Esempio n. 4
0
 public void run() {
   String line;
   String id = null;
   seqs = new HashMap<String, StringBuffer>();
   try {
     //      System.err.println("quality read start");  // debug
     while (true) {
       line = br.readLine();
       // FIX ME: update to use reader...
       if (line == null) break;
       // EOF
       if (line.indexOf(">") == 0) {
         String[] stuff = line.substring(1).split("\\s+");
         id = new String(stuff[0]);
         // HACK, WRONG if line contains comments...
       } else {
         // sequence
         StringBuffer sb = seqs.get(id);
         if (sb == null) seqs.put(id, sb = new StringBuffer());
         sb.append(line);
       }
     }
     data_loaded = true;
     //      System.err.println("quality read end");  // debug
   } catch (Exception e) {
     System.err.println("FASTASequenceReader load error: " + e); // debug
     System.exit(1);
   }
 }
Esempio n. 5
0
    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();
      }
    }
Esempio n. 6
0
    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();
      }
    }
Esempio n. 7
0
 public String toString() {
   StringBuffer sb = new StringBuffer(url.length() + 17);
   sb.append("[MyMockCachedUrl: ");
   sb.append(url);
   sb.append("]");
   return sb.toString();
 }
Esempio n. 8
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();
  }
Esempio n. 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();
 }
Esempio n. 10
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();
  }
Esempio n. 11
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();
  }
  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));
  }
Esempio n. 13
0
  /**
   * 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());
  }
Esempio n. 14
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;
  }
Esempio n. 15
0
 /**
  * ** 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;
   }
 }
Esempio n. 16
0
 /**
  * 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);
       }
     }
   }
 }
Esempio n. 17
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();
 }
Esempio n. 18
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();
 }
Esempio n. 19
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();
 }
Esempio n. 20
0
 /**
  * 把用'拼接的ascci码转换为字符串
  *
  * @param str
  * @return
  */
 public static String dec(String str) {
   String[] strarr = str.split("\\'");
   StringBuffer sb = new StringBuffer();
   for (int i = 0; i < strarr.length; i++) {
     sb.append((char) Integer.parseInt(strarr[i]));
   }
   return sb + "";
 }
Esempio n. 21
0
  /** 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());
  }
Esempio n. 22
0
 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();
 }
Esempio n. 23
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);
 }
Esempio n. 24
0
 public String toString() {
   StringBuffer sb = new StringBuffer();
   sb.append(this.key);
   if (this.hasValue()) {
     sb.append("=").append(this.val);
   }
   return sb.toString();
 }
Esempio n. 25
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();
 }
Esempio n. 26
0
  /**
   * 请求xml数据
   *
   * @param url
   * @param soapAction
   * @param xml
   * @return
   */
  public static String sendXMl(String url, String soapAction, String xml) {
    HttpURLConnection conn = null;
    InputStream in = null;
    InputStreamReader isr = null;
    OutputStream out = null;
    StringBuffer result = null;
    try {
      byte[] sendbyte = xml.getBytes("UTF-8");
      URL u = new URL(url);
      conn = (HttpURLConnection) u.openConnection();
      conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
      conn.setRequestProperty("SOAPAction", soapAction);
      conn.setRequestProperty("Content-Length", sendbyte.length + "");
      conn.setDoInput(true);
      conn.setDoOutput(true);
      conn.setConnectTimeout(5000);
      conn.setReadTimeout(5000);

      out = conn.getOutputStream();
      out.write(sendbyte);

      if (conn.getResponseCode() == 200) {
        result = new StringBuffer();
        in = conn.getInputStream();
        isr = new InputStreamReader(in, "UTF-8");
        char[] c = new char[1024];
        int a = isr.read(c);
        while (a != -1) {
          result.append(new String(c, 0, a));
          a = isr.read(c);
        }
      }

    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (conn != null) {
        conn.disconnect();
      }
      try {
        if (in != null) {
          in.close();
        }
        if (isr != null) {
          isr.close();
        }
        if (out != null) {
          out.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    return result == null ? null : result + "";
  }
 private static String readStreamToString(InputStream in, String encoding) throws IOException {
   StringBuffer b = new StringBuffer();
   InputStreamReader r = new InputStreamReader(in, encoding);
   int c;
   while ((c = r.read()) != -1) {
     b.append((char) c);
   }
   return b.toString();
 }
Esempio n. 28
0
 private void checkMD(StringBuffer sb, NameValueRecord nvr, String name, String value) {
   String id = nvr.getString(name);
   if (id == null) {
     sb.append("#e  no ").append(name).append(" in metadata\n");
   } else if (!id.equals(value)) {
     sb.append("#e  original/md ").append(name).append(": ");
     sb.append(value).append(" / ").append(id).append("\n");
   }
 }
Esempio n. 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();
 }
Esempio n. 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();
  }