Ejemplo n.º 1
1
  /**
   * @param url
   * @param request
   * @param resContentHeaders
   * @param timeout
   * @return
   * @throws java.lang.Exception
   * @deprecated As of proxy release 1.0.10, replaced by {@link #sendRequestoverHTTPS( boolean
   *     isBusReq, URL url, String request, Map resContentHeaders, int timeout)}
   */
  public static String sendRequestOverHTTPS(
      URL url, String request, Map resContentHeaders, int timeout) throws Exception {

    // Set up buffers and streams
    StringBuffer buffy = null;
    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    try {
      HttpsURLConnection urlc = (HttpsURLConnection) url.openConnection();
      urlc.setConnectTimeout(timeout);
      urlc.setReadTimeout(timeout);
      urlc.setAllowUserInteraction(false);
      urlc.setDoInput(true);
      urlc.setDoOutput(true);
      urlc.setUseCaches(false);

      // Set request header properties
      urlc.setRequestMethod(FastHttpClientConstants.HTTP_REQUEST_HDR_POST);
      urlc.setRequestProperty(
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_TYPE_KEY,
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_TYPE_VALUE);
      urlc.setRequestProperty(
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_LENGTH_KEY,
          String.valueOf(request.length()));

      // Request
      // this makes the assumption that all https requests are going to the bus using UTF-8 encoding
      String encodedString =
          URLEncoder.encode(request, FastHttpClientConstants.HTTP_REQUEST_ENCODING);
      out = new BufferedOutputStream(urlc.getOutputStream(), OUTPUT_BUFFER_LEN);
      out.write(FastHttpClientConstants.HTTP_REQUEST_POST_KEY.getBytes());
      out.write(encodedString.getBytes());
      out.flush();

      // Response
      // this mangles 2 or more byte characters
      in = new BufferedInputStream(urlc.getInputStream(), INPUT_BUFFER_LEN);
      buffy = new StringBuffer(INPUT_BUFFER_LEN);
      int ch = 0;
      while ((ch = in.read()) > -1) {
        buffy.append((char) ch);
      }

      populateHTTPSHeaderContentMap(urlc, resContentHeaders);
    } catch (Exception e) {
      throw e;
    } finally {
      try {
        if (out != null) {
          out.close();
        }
        if (in != null) {
          in.close();
        }
      } catch (Exception ex) {
        // Ignore as want to throw exception from the catch block
      }
    }
    return buffy == null ? null : buffy.toString();
  }
Ejemplo n.º 2
1
 static void initWords(int size, Object[] key, Object[] abs) {
   String fileName = "testwords.txt";
   int ki = 0;
   int ai = 0;
   try {
     FileInputStream fr = new FileInputStream(fileName);
     BufferedInputStream in = new BufferedInputStream(fr);
     while (ki < size || ai < size) {
       StringBuffer sb = new StringBuffer();
       for (; ; ) {
         int c = in.read();
         if (c < 0) {
           if (ki < size) randomWords(key, ki, size);
           if (ai < size) randomWords(abs, ai, size);
           in.close();
           return;
         }
         if (c == '\n') {
           String s = sb.toString();
           if (ki < size) key[ki++] = s;
           else abs[ai++] = s;
           break;
         }
         sb.append((char) c);
       }
     }
     in.close();
   } catch (IOException ex) {
     System.out.println("Can't read words file:" + ex);
     throw new Error(ex);
   }
 }
Ejemplo n.º 3
1
 public static void addBullet(StringBuffer buffer, String bullet) {
   if (bullet != null) {
     buffer.append("<li>"); // $NON-NLS-1$
     buffer.append(bullet);
     buffer.append("</li>"); // $NON-NLS-1$
   }
 }
Ejemplo n.º 4
1
 /**
  * @param str 原字符
  * @param prefix 前几位(0,表示不做替换)
  * @param postfix 后几位(0,表示不做替换)
  * @param character 替换字符(若替换字符为一位,则保持长度不变)
  * @return 替换后的字符
  */
 public static String stringSwitch(String str, int prefix, int postfix, String character) {
   if (prefix < 0 || postfix < 0) {
     return str;
   }
   if (prefix == 0 && postfix == 0) {
     return str;
   }
   if (str != null && str.trim().length() > 0) {
     StringBuffer buf = new StringBuffer();
     int argsLength = str.length();
     // 保证被替换的长度大于原字符长度
     if (argsLength > prefix + postfix) {
       if (prefix != 0) {
         String stringPrefix = str.substring(0, prefix);
         buf.append(stringPrefix);
       }
       for (int i = prefix; i < argsLength - postfix; i++) {
         buf.append(character);
       }
       if (postfix != 0) {
         String stringPostfix = str.substring(argsLength - postfix);
         buf.append(stringPostfix);
       }
       return buf.toString();
     } else {
       return str;
     }
   }
   return null;
 }
 // FIXME cosmically ineffective not to implemente the other write methods.
 @Override
 public void write(int b) throws IOException {
   this.buffer.append((char) b);
   String s = buffer.toString();
   // This next line is an optimisation. Only convert the whole buffer to string
   // if the most recent character might be the end of the line separator.
   if ((lineSeparator.indexOf(b) != -1) && s.contains(lineSeparator)) {
     s = prefix + "'" + s + "'";
     switch (loggingLevel) {
       case TRACE:
         logger.trace(s);
         break;
       case DEBUG:
         logger.debug(s);
         break;
       case INFO:
         logger.info(s);
         break;
       case WARN:
         logger.warn(s);
         break;
       case ERROR:
         logger.error(s);
         break;
     }
     buffer.setLength(0);
   }
 }
Ejemplo n.º 6
1
  /**
   * 是否财付通签名,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
   *
   * @return boolean
   */
  public boolean isTenpaySign() {
    StringBuffer sb = new StringBuffer();
    Set es = this.parameters.entrySet();
    Iterator it = es.iterator();
    while (it.hasNext()) {
      Map.Entry entry = (Map.Entry) it.next();
      String k = (String) entry.getKey();
      String v = (String) entry.getValue();
      if (!"sign".equals(k) && null != v && !"".equals(v)) {
        sb.append(k + "=" + v + "&");
      }
    }

    sb.append("key=" + this.getKey());

    // 算出摘要
    String enc = "UTF-8";
    String sign = MD5Util.MD5Encode(sb.toString(), enc).toLowerCase();

    String tenpaySign = this.getParameter("sign").toLowerCase();

    // debug信息
    this.setDebugInfo(sb.toString() + " => sign:" + sign + " tenpaySign:" + tenpaySign);

    return tenpaySign.equals(sign);
  }
  /**
   * dummy toString method
   *
   * @return the String representation of the operator
   */
  public String toString() {
    StringBuffer strBuf = new StringBuffer();
    strBuf.append("Impute: Punct: " + pSpec.toString() + " Attr: " + pAttr.getName());

    strBuf.append("Stream Punctuating Attr: " + spAttr.getName());
    return strBuf.toString();
  }
Ejemplo n.º 8
1
  static String getSpaces(int num) {
    try {
      // 99.9% of the time num is going to be
      // smaller than 50, so just try it
      return SPACES[num];
    } catch (ArrayIndexOutOfBoundsException e) {
      if (num < 0) return "";

      // too big!
      int len = SPACES.length;
      StringBuffer buf;
      buf = new StringBuffer(num);
      int rem = num;
      while (true) {
        if (rem < len) {
          buf.append(SPACES[rem]);
          break;
        } else {
          buf.append(SPACES[len - 1]);
          rem -= len - 1;
        }
      }
      return buf.toString();
    }
  }
Ejemplo n.º 9
0
 private int getFieldErrorMsgByErrorType(
     StringBuffer allErrorMsg, List<Field> list, FormComp fc, int index, String titleError) {
   List<FormElement> fes = fc.getElementList();
   if (fes != null && fes.size() > 0) {
     boolean isNeedToShowError = false;
     FormElement[] formElements = new FormElement[fes.size()];
     int size = list.size();
     for (int i = 0; i < size; i++) {
       Field f = list.get(i);
       int fieldIndex = fc.idToIndex(f.getId());
       if (fieldIndex != -1 && fc.getElementById(f.getId()).isVisible()) {
         formElements[fieldIndex] = fes.get(fieldIndex);
         isNeedToShowError = true;
       }
     }
     if (isNeedToShowError) {
       allErrorMsg.append(((index > 1) ? " " : "") + index + ")");
       index++;
       allErrorMsg.append(titleError);
       boolean temp = false;
       for (int i = 0; i < formElements.length; i++) {
         if (formElements[i] != null) {
           String text = formElements[i].getText();
           allErrorMsg.append(((temp) ? "," : "") + "“" + text + "”");
           temp = true;
         }
       }
     }
   }
   return index;
 }
Ejemplo n.º 10
0
  /**
   * Reads the example file specified by the example tag of a doc member and adds it to the example
   * section of the doc
   *
   * @param doc
   * @throws IOException
   */
  void setExample(Doc doc) throws IOException {
    Tag[] exampleTag = doc.tags("@example");
    if (exampleTag.length > 0) {
      StringBuffer exampleBuffer = new StringBuffer();
      FileReader in;
      int c;
      String[] pathComponents = exampleTag[0].text().split("/");
      String filePath =
          exampleTag[0].text() + "/" + pathComponents[pathComponents.length - 1] + ".pde";
      in = new FileReader(new File(exampleFolder, filePath));

      while ((c = in.read()) != -1) {
        if ((char) c == '<') {
          exampleBuffer.append("&lt;");
        } else {
          exampleBuffer.append((char) c);
        }
      }

      in.close();

      String exampleString = exampleBuffer.toString();

      EXAMPLE_TAG.setContent(exampleString);

    } else {
      EXAMPLE_TAG.setContent("None available");
    }
  }
  // MD5加密,32位
  public static String MD5(String str) {
    MessageDigest md5 = null;
    try {
      md5 = MessageDigest.getInstance("MD5");
    } catch (Exception e) {
      e.printStackTrace();
      return "";
    }

    char[] charArray = str.toCharArray();
    byte[] byteArray = new byte[charArray.length];

    for (int i = 0; i < charArray.length; i++) {
      byteArray[i] = (byte) charArray[i];
    }
    byte[] md5Bytes = md5.digest(byteArray);

    StringBuffer hexValue = new StringBuffer();
    for (int i = 0; i < md5Bytes.length; i++) {
      int val = ((int) md5Bytes[i]) & 0xff;
      if (val < 16) {
        hexValue.append("0");
      }
      hexValue.append(Integer.toHexString(val));
    }
    return hexValue.toString();
  }
Ejemplo n.º 12
0
  /**
   * Return the REST path EG:
   * {layer}/{style}/{firstDimension}/{...}/{lastDimension}/{TileMatrixSet}/{scale}/{TileRow}/{TileCol}.{format_extension}
   */
  public String mapFromModel(IModel model) throws UnsupportedModelException {

    StringBuffer result = new StringBuffer("");

    if (model instanceof RestModel) {
      RestModel m = (RestModel) model;

      for (String propertyName : m.order) {
        String property = m.getProperties().get(propertyName);

        if (property != null) {
          if (result.length() != 0) {
            result.append("/");
          }
          result.append(property);
        }
      }
    } else {
      throw new UnsupportedModelException(
          String.format(
              "%s cannot map from model %s", getClass().getName(), model.getClass().getName()));
    }

    return result.toString();
  }
 private static StringBuffer buildSequence(LoadingOrder.Orderable[] array) {
   StringBuffer sequence = new StringBuffer();
   for (LoadingOrder.Orderable adapter : array) {
     sequence.append(((MyElement) adapter.getDescribingElement()).getID());
   }
   return sequence;
 }
Ejemplo n.º 14
0
 /**
  * 返回十六进制字符串
  *
  * @param arr
  * @return
  */
 private static String hex(byte[] arr) {
   StringBuffer sb = new StringBuffer();
   for (int i = 0; i < arr.length; ++i) {
     sb.append(Integer.toHexString((arr[i] & 0xFF) | 0x100).substring(1, 3));
   }
   return sb.toString();
 }
Ejemplo n.º 15
0
  // Algo 0: output string order.
  public String convert0(String s, int numRows) {

    if (numRows == 1) {
      return s;
    }
    StringBuffer sb = new StringBuffer();
    int borderRowStep = 2 * numRows - 2;
    for (int i = 0; i < numRows; i++) {
      if (i == 0 || i == numRows - 1) {
        for (int j = i; j < s.length(); j += borderRowStep) {
          sb.append(s.charAt(j));
        }
      } else {
        int j = i;
        boolean flag = true;
        int insideRowLargeStep = 2 * (numRows - 1 - i);
        int insideRowSmallStep = borderRowStep - insideRowLargeStep;
        while (j < s.length()) {
          sb.append(s.charAt(j));
          if (flag) j += insideRowLargeStep;
          else j += insideRowSmallStep;
          flag = !flag;
        }
      }
    }
    return sb.toString();
  }
 private Map readMap(Element l) {
   Map map = new HashMap();
   NodeList nodes = l.getChildNodes();
   Set roles = new HashSet();
   for (int i = 0; i < nodes.getLength(); i++) {
     Node item = nodes.item(i);
     if (item instanceof Element) {
       String key = item.getNodeName();
       StringBuffer value = new StringBuffer();
       NodeList vals = item.getChildNodes();
       for (int j = 0; j < vals.getLength(); j++) {
         Node val = vals.item(j);
         if (val instanceof Text) {
           value.append(val.getNodeValue());
         }
       }
       String val = value.toString();
       if (ROLE_ASSIGNMENT.equals(key)) {
         roles.add(val);
       } else {
         map.put(key, val);
       }
     }
   }
   if (roles.size() != 0) {
     map.put(ROLE_ASSIGNMENT, roles);
   }
   return map;
 }
Ejemplo n.º 17
0
 public static String read(Reader rd) {
   final StringBuffer buffer = new StringBuffer();
   if (read(rd, buffer)) {
     return buffer.toString();
   }
   return null;
 }
Ejemplo n.º 18
0
 public static void addSmallHeader(StringBuffer buffer, String header) {
   if (header != null) {
     buffer.append("<h5>"); // $NON-NLS-1$
     buffer.append(header);
     buffer.append("</h5>"); // $NON-NLS-1$
   }
 }
Ejemplo n.º 19
0
  private String decodeEntities(String s) {
    StringBuffer buf = new StringBuffer();

    Matcher m = P_ENTITY.matcher(s);
    while (m.find()) {
      final String match = m.group(1);
      final int decimal = Integer.decode(match).intValue();
      m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
    }
    m.appendTail(buf);
    s = buf.toString();

    buf = new StringBuffer();
    m = P_ENTITY_UNICODE.matcher(s);
    while (m.find()) {
      final String match = m.group(1);
      final int decimal = Integer.valueOf(match, 16).intValue();
      m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
    }
    m.appendTail(buf);
    s = buf.toString();

    buf = new StringBuffer();
    m = P_ENCODE.matcher(s);
    while (m.find()) {
      final String match = m.group(1);
      final int decimal = Integer.valueOf(match, 16).intValue();
      m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
    }
    m.appendTail(buf);
    s = buf.toString();

    s = validateEntities(s);
    return s;
  }
Ejemplo n.º 20
0
 /**
  * Decodes an integer from the byte array.
  *
  * @param bencoded_bytes the byte array of the bencoded integer.
  * @param offset the position of the 'i' indicating the start of the bencoded integer to be
  *     bdecoded.
  * @return an <code>Object[]</code> containing an <code>Integer</code> offset and the decoded
  *     <code>Integer</code>, in positions 0 and 1, respectively
  * @throws BencodingException if the bencoded integer in {@code bencoded_bytes} at offset {@code
  *     offset} is incorrectly encoded.
  */
 private static final Object[] decodeInteger(byte[] bencoded_bytes, int offset)
     throws BencodingException {
   StringBuffer int_chars = new StringBuffer();
   offset++;
   for (; bencoded_bytes[offset] != (byte) 'e' && bencoded_bytes.length > (offset); offset++) {
     if ((bencoded_bytes[offset] < 48 || bencoded_bytes[offset] > 57)
         && bencoded_bytes[offset] != 45)
       throw new BencodingException(
           "Expected an ASCII integer character, found " + (int) bencoded_bytes[offset]);
     int_chars.append((char) bencoded_bytes[offset]);
   }
   try {
     offset++; // Skip the 'e'
     return new Object[] {
       new Integer(offset), new Integer(Integer.parseInt(int_chars.toString()))
     };
   } catch (NumberFormatException nfe) {
     throw new BencodingException(
         "Could not parse integer at position"
             + offset
             + ".\nInvalid character at position "
             + offset
             + ".");
   }
 }
  /**
   * Load an entire resource text file into {@link String}.
   *
   * @param path the path to the resource file.
   * @return the entire content of the resource text file.
   */
  private String getResourceDocumentContent(String path) {
    InputStream in = this.getClass().getClassLoader().getResourceAsStream(path);

    if (in != null) {
      try {
        StringBuffer content = new StringBuffer(in.available());

        InputStreamReader isr = new InputStreamReader(in);
        try {
          BufferedReader reader = new BufferedReader(isr);
          for (String str = reader.readLine(); str != null; str = reader.readLine()) {
            content.append(str);
            content.append('\n');
          }
        } finally {
          isr.close();
        }

        return content.toString();
      } catch (IOException e) {
        // No resource file as been found or there is a problem when read it.
      }
    }

    return null;
  }
Ejemplo n.º 22
0
 protected void resetSql() {
   if (null == sql) {
     sql = new StringBuffer();
   } else {
     sql.delete(0, sql.length());
   }
 }
Ejemplo n.º 23
0
 private void appendLoadOnStartup(StringBuffer result, Object startupOrder) {
   if (startupOrder == null) return;
   result.append("    <load-on-startup");
   if (startupOrder instanceof Number)
     result.append(">").append(startupOrder).append("</load-on-startup>\n");
   else result.append("/>\n");
 }
Ejemplo n.º 24
0
 @Override
 public String toString() {
   StringBuffer buff = new StringBuffer(getParentString());
   buff.append(", queueName=" + queueName);
   buff.append("]");
   return buff.toString();
 }
Ejemplo n.º 25
0
  public String getLauncherDetails(String prefix) {
    try {
      final String javaVersionCommand = javaCommand + " -version";
      Process proc = Runtime.getRuntime().exec(javaVersionCommand);

      try {
        InputStream inputStream = proc.getErrorStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

        String line = null;
        StringBuffer buffer = new StringBuffer();
        while ((line = reader.readLine()) != null) {
          buffer.append(prefix);
          buffer.append(line);
          buffer.append('\n');
        }

        return buffer.toString();
      } finally {
        proc.destroy();
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Ejemplo n.º 26
0
 protected String buildCallBackURL(HttpServletRequest request, Integer provider) {
   StringBuffer requestURL = request.getRequestURL();
   String callbackURL = requestURL.toString();
   callbackURL += "callback";
   // System.out.println("callback url: " + callbackURL);
   return callbackURL;
 }
Ejemplo n.º 27
0
  /** Generates the foreign key declaration for a given Constraint object. */
  private void getFKStatement(StringBuffer a) {

    if (!getName().isReservedName()) {
      a.append(Tokens.T_CONSTRAINT).append(' ');
      a.append(getName().statementName);
      a.append(' ');
    }

    a.append(Tokens.T_FOREIGN).append(' ').append(Tokens.T_KEY);

    int[] col = getRefColumns();

    getColumnList(getRef(), col, col.length, a);
    a.append(' ').append(Tokens.T_REFERENCES).append(' ');
    a.append(getMain().getName().getSchemaQualifiedStatementName());

    col = getMainColumns();

    getColumnList(getMain(), col, col.length, a);

    if (getDeleteAction() != Constraint.NO_ACTION) {
      a.append(' ').append(Tokens.T_ON).append(' ').append(Tokens.T_DELETE).append(' ');
      a.append(getDeleteActionString());
    }

    if (getUpdateAction() != Constraint.NO_ACTION) {
      a.append(' ').append(Tokens.T_ON).append(' ').append(Tokens.T_UPDATE).append(' ');
      a.append(getUpdateActionString());
    }
  }
Ejemplo n.º 28
0
Archivo: List.java Proyecto: znerd/xins
  /**
   * Converts the specified <code>ItemList</code> to a string.
   *
   * @param value the value to convert, can be <code>null</code>.
   * @return the textual representation of the value, or <code>null</code> if and only if <code>
   *     value == null</code>.
   */
  public String toString(ItemList value) {

    // Short-circuit if the argument is null
    if (value == null) {
      return null;
    }

    // Use a buffer to create the string
    StringBuffer buffer = new StringBuffer(255);

    // Iterate over the list
    int listSize = value.getSize();
    for (int i = 0; i < listSize; i++) {
      if (i != 0) {
        buffer.append('&');
      }

      Object nextItem = value.getItem(i);
      String stringItem;
      try {
        stringItem = _itemType.toString(nextItem);
      } catch (Exception ex) {

        // Should never happens as only add() is able to add items in the list.
        throw new IllegalArgumentException("Incorrect value for type: " + nextItem);
      }
      buffer.append(URLEncoding.encode(stringItem));
    }

    return buffer.toString();
  }
Ejemplo n.º 29
0
 @RequestMapping("/dumpThead")
 @ResponseBody
 public void doDumpThread(HttpServletRequest request, HttpServletResponse response) {
   try {
     String app = request.getParameter("app");
     String threadId = request.getParameter("threadId");
     ThreadMXBean tBean = JMConnManager.getThreadMBean(app);
     JSONObject data = new JSONObject();
     if (threadId != null) {
       Long id = Long.valueOf(threadId);
       ThreadInfo threadInfo = tBean.getThreadInfo(id, Integer.MAX_VALUE);
       data.put("info", threadInfo.toString());
     } else {
       ThreadInfo[] dumpAllThreads = tBean.dumpAllThreads(false, false);
       StringBuffer info = new StringBuffer();
       for (ThreadInfo threadInfo : dumpAllThreads) {
         info.append("\n").append(threadInfo);
       }
       data.put("info", info);
     }
     writeFile(request, response, data);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
Ejemplo n.º 30
0
  private static void appendStyleSheet(StringBuffer buffer, String styleSheet) {
    if (styleSheet == null) return;

    buffer.append("<head><style CHARSET=\"ISO-8859-1\" TYPE=\"text/css\">"); // $NON-NLS-1$
    buffer.append(styleSheet);
    buffer.append("</style></head>"); // $NON-NLS-1$
  }