예제 #1
1
 private static StringBuffer printCollectionOrArray(StringBuffer out, Object o, Conf conf) {
   if (o.getClass().isArray()) {
     if (java.lang.reflect.Array.getLength(o) == 0) return out.append("[]");
   } else {
     if (((java.util.Collection) o).size() == 0) return out.append("[]");
   }
   indent(out, conf);
   out.append('[');
   newline(out, conf);
   conf.currentIndent++;
   if (o.getClass().isArray())
     for (int i = 0, len = java.lang.reflect.Array.getLength(o); i < len; i++) {
       Object value = java.lang.reflect.Array.get(o, i);
       if (!conf.showNull && value == null) continue;
       indent(out, conf);
       print(out, value, conf);
       if (out.charAt(out.length() - 1) == '\n') out.delete(out.length() - 1, out.length());
       out.append(',');
       newline(out, conf);
     }
   else
     for (java.util.Iterator it = ((java.util.Collection) o).iterator(); it.hasNext(); ) {
       Object value = it.next();
       if (!conf.showNull && value == null) continue;
       indent(out, conf);
       print(out, value, conf);
       if (out.charAt(out.length() - 1) == '\n') out.delete(out.length() - 1, out.length());
       out.append(',');
       newline(out, conf);
     }
   conf.currentIndent--;
   indent(out, conf);
   out.append(']');
   return newline(out, conf);
 }
예제 #2
1
  private String trim(final StringBuffer buffer, final TextPresentation presentation) {

    int length = buffer.length();

    int end = length - 1;
    while (end >= 0 && Character.isWhitespace(buffer.charAt(end))) {
      --end;
    }

    if (end == -1) {
      return ""; //$NON-NLS-1$
    }

    if (end < length - 1) {
      buffer.delete(end + 1, length);
    } else {
      end = length;
    }

    int start = 0;
    while (start < end && Character.isWhitespace(buffer.charAt(start))) {
      ++start;
    }

    buffer.delete(0, start);
    presentation.setResultWindow(new Region(start, buffer.length()));
    return buffer.toString();
  }
예제 #3
1
 /**
  * This is for debug only: print out training matrices in a CSV type format so that the matrices
  * can be examined in a spreadsheet program for debugging purposes.
  */
 private void WriteCSVfile(
     List<String> rowNames, List<String> colNames, float[][] buf, String fileName) {
   p("tagList.size()=" + tagList.size());
   try {
     FileWriter fw = new FileWriter(fileName + ".txt");
     PrintWriter bw = new PrintWriter(new BufferedWriter(fw));
     // write the first title row:
     StringBuffer sb = new StringBuffer(500);
     for (int i = 0, size = colNames.size(); i < size; i++) {
       sb.append("," + colNames.get(i));
     }
     bw.println(sb.toString());
     // loop on remaining rows:
     for (int i = 0, size = buf.length; i < size; i++) {
       sb.delete(0, sb.length());
       sb.append(rowNames.get(i));
       for (int j = 0, size2 = buf[i].length; j < size2; j++) {
         sb.append("," + buf[i][j]);
       }
       bw.println(sb.toString());
     }
     bw.close();
   } catch (IOException ioe) {
     ioe.printStackTrace();
   }
 }
예제 #4
0
  /**
   * 解析url{@link StringBuffer}返回一个新的实例
   *
   * @param url
   * @return UrlRole
   */
  public static UrlRole parse(StringBuffer url) {

    UrlRole def = new UrlRole();

    int point = url.lastIndexOf(".");
    if (point != -1) url.delete(point, url.length());

    int a = url.indexOf("!");

    if (a == url.length() - 1) {
      def.className = url.deleteCharAt(url.length() - 1);
      def.methodName = "execute";
    } else if (a != -1) {
      def.methodName = url.substring(a + 1);
      def.className = url.delete(a, url.length());
    } else {
      def.className = url;
      def.methodName = "execute";
    }

    int b = def.className.lastIndexOf("/");

    char c = def.className.charAt(b + 1);

    if (c >= 'a' && c <= 'z') def.className.setCharAt(b + 1, (char) (c - 32));
    def.className.replace(b, b + 1, ".action.").append("Action");

    while ((b = def.className.indexOf("/")) != -1) {
      def.className.setCharAt(b, '.');
    }

    def.className.insert(0, P3Filter.ACTION_PACKAGE);
    if (logger.isDebugEnabled()) logger.debug("action define : " + def);
    return def;
  }
 /**
  * Process mrn and get score2.
  *
  * @param mrn the mrn
  * @param dbMRN the db mrn
  * @return the int
  */
 private int processMRNAndGetScore2(String mrn, String dbMRN) {
   int i, j;
   char[] charArray = null;
   char digit = 0;
   int score = 0;
   StringBuffer tempssnStr = new StringBuffer();
   charArray = mrn.toCharArray();
   for (i = 0; i < mrn.length(); i++) {
     digit = charArray[i];
     if (digit < '9') {
       charArray[i] = ++charArray[i];
       tempssnStr.append(charArray);
       charArray[i] = --charArray[i];
       score = getMRNPartialScore(tempssnStr.toString(), dbMRN);
       if (score > 0) {
         break;
       }
     }
     tempssnStr = tempssnStr.delete(0, tempssnStr.length());
     if (digit > '0') {
       charArray[i] = --charArray[i];
       tempssnStr.append(charArray);
       score = getMRNPartialScore(tempssnStr.toString(), dbMRN);
       if (score > 0) {
         break;
       }
       charArray[i] = ++charArray[i];
     }
     tempssnStr = tempssnStr.delete(0, tempssnStr.length());
   }
   return score;
 }
예제 #6
0
  public String renderTool(HttpServletResponse response, Controller controller) {
    Hashtable jsImageProperties = new Hashtable();
    StringBuffer propertyValue = new StringBuffer();
    String fullEnabledImageLink = controller.getPathWithContext(enabledImageLink_);
    generateOnMouseValue(propertyValue, response, fullEnabledImageLink);
    int propertyValueLength = propertyValue.length();
    jsImageProperties.put("class", "normal");
    jsImageProperties.put("onMouseOut", propertyValue.append(";mouseout(this)").toString());
    propertyValue.delete(propertyValueLength, propertyValue.length());
    jsImageProperties.put("onMouseUp", propertyValue.append(";mouseup(this)").toString());
    propertyValue.setLength(0);
    generateOnMouseValue(
        propertyValue, response, controller.getPathWithContext(highlightedImageLink_));
    propertyValueLength = propertyValue.length();
    jsImageProperties.put("onMouseOver", propertyValue.append(";mouseover(this)").toString());
    propertyValue.delete(propertyValueLength, propertyValue.length());
    jsImageProperties.put("onMouseDOwn", propertyValue.append(";mousedown(this)").toString());

    String imageTag =
        HTMLUtils.getHTMLImageTag(
            response, fullEnabledImageLink, alt_, "16", "16", jsImageProperties);
    return HTMLUtils.getHTMLLinkTag(
        response,
        controller.getPathWithContext(getSelectToolActionHref(false)),
        getSelectToolActionTarget(),
        null,
        imageTag,
        null);
  }
예제 #7
0
 /**
  * suffix stripping (stemming) on the current term. The stripping is reduced to the seven "base"
  * suffixes "e", "s", "n", "t", "em", "er" and * "nd", from which all regular suffixes are build
  * of. The simplification causes some overstemming, and way more irregular stems, but still
  * provides unique. discriminators in the most of those cases. The algorithm is context free,
  * except of the length restrictions.
  */
 private void strip(StringBuffer buffer) {
   boolean doMore = true;
   while (doMore && buffer.length() > 3) {
     if ((buffer.length() + substCount > 5)
         && buffer.substring(buffer.length() - 2, buffer.length()).equals("nd")) {
       buffer.delete(buffer.length() - 2, buffer.length());
     } else if ((buffer.length() + substCount > 4)
         && buffer.substring(buffer.length() - 2, buffer.length()).equals("em")) {
       buffer.delete(buffer.length() - 2, buffer.length());
     } else if ((buffer.length() + substCount > 4)
         && buffer.substring(buffer.length() - 2, buffer.length()).equals("er")) {
       buffer.delete(buffer.length() - 2, buffer.length());
     } else if (buffer.charAt(buffer.length() - 1) == 'e') {
       buffer.deleteCharAt(buffer.length() - 1);
     } else if (buffer.charAt(buffer.length() - 1) == 's') {
       buffer.deleteCharAt(buffer.length() - 1);
     } else if (buffer.charAt(buffer.length() - 1) == 'n') {
       buffer.deleteCharAt(buffer.length() - 1);
     }
     // "t" occurs only as suffix of verbs.
     else if (buffer.charAt(buffer.length() - 1) == 't') {
       buffer.deleteCharAt(buffer.length() - 1);
     } else {
       doMore = false;
     }
   }
 }
예제 #8
0
 // Serialize the bean using the specified namespace prefix & uri
 public String serialize(Object bean) throws IntrospectionException, IllegalAccessException {
   // Use the class name as the name of the root element
   String className = bean.getClass().getName();
   String rootElementName = null;
   if (bean.getClass().isAnnotationPresent(ObjectXmlAlias.class)) {
     AnnotatedElement annotatedElement = bean.getClass();
     ObjectXmlAlias aliasAnnotation = annotatedElement.getAnnotation(ObjectXmlAlias.class);
     rootElementName = aliasAnnotation.value();
   }
   // Use the package name as the namespace URI
   Package pkg = bean.getClass().getPackage();
   nsURI = pkg.getName();
   // Remove a trailing semi-colon (;) if present (i.e. if the bean is an array)
   className = StringUtils.deleteTrailingChar(className, ';');
   StringBuffer sb = new StringBuffer(className);
   String objectName = sb.delete(0, sb.lastIndexOf(".") + 1).toString();
   domDocument = createDomDocument(objectName);
   document = domDocument.getDocument();
   Element root = document.getDocumentElement();
   // Parse the bean elements
   getBeanElements(root, rootElementName, className, bean);
   StringBuffer xml = new StringBuffer();
   if (prettyPrint)
     xml.append(domDocument.serialize(lineSeperator, indentChars, includeXmlProlog));
   else xml.append(domDocument.serialize(includeXmlProlog));
   if (!includeTypeInfo) {
     int index = xml.indexOf(root.getNodeName());
     xml.delete(index - 1, index + root.getNodeName().length() + 2);
     xml.delete(xml.length() - root.getNodeName().length() - 4, xml.length());
   }
   return xml.toString();
 }
  protected void addPlugins() {
    ContainerBase container = new ContainerBase("Plugins");
    container.initProperties();
    addChild(container);

    ComponentDescription[] desc = ComponentConnector.parseFile(filename);
    if (desc == null) {
      if (log.isWarnEnabled()) {
        log.warn("No data found in file " + filename);
      }
      return;
    }
    for (int i = 0; i < desc.length; i++) {
      StringBuffer name = new StringBuffer(desc[i].getName());
      StringBuffer className = new StringBuffer(desc[i].getClassname());
      String insertionPoint = desc[i].getInsertionPoint();
      String priority = desc[i].priorityToString(desc[i].getPriority());
      //       if(log.isDebugEnabled()) {
      //         log.debug("Insertion Point: " + insertionPoint);
      //       }

      if (insertionPoint.endsWith("Plugin")) {
        int start = 0;
        if ((start = name.indexOf("OrgRTData")) != -1) {
          name.delete(start, start + 2);
          start = className.indexOf("RT");
          className.delete(start, start + 2);
        }

        // HACK!
        // When dumping INIs we add an extra parameter to the GLSInitServlet,
        // so strip it off here
        boolean isGLS = false;
        if (className.indexOf("GLSInitServlet") != -1) {
          isGLS = true;
        }

        int index = name.lastIndexOf(".");
        if (index != -1) name.delete(0, index + 1);
        PluginBase plugin = new PluginBase(name.substring(0), className.substring(0), priority);
        plugin.initProperties();
        Iterator iter = ComponentConnector.getPluginProps(desc[i]);
        while (iter.hasNext()) {
          if (isGLS) {
            String param = (String) iter.next();
            if (param.startsWith("exptid=")) continue;
            else plugin.addParameter(param);
          } else plugin.addParameter((String) iter.next());
        }
        container.addChild(plugin);
      }
    }
  }
예제 #10
0
    public void execute() {
      if (!isEditable() || !isEnabled()) {
        return;
      }
      int position = lastClickPoint != null ? viewToModel(lastClickPoint) : getCaretPosition();
      lastClickPoint = null;
      Document document = getDocument();
      String selectedText = getSelectedText();

      try {
        if (selectedText != null && !CommonUtil.isEmpty(selectedText)) {
          String trimmed = selectedText.trim();
          if (trimmed.startsWith("<!--") && trimmed.endsWith("-->")) {
            StringBuffer buffer = new StringBuffer(selectedText);
            int pos = buffer.indexOf("<!--");
            buffer.delete(pos, pos + 4);
            pos = buffer.lastIndexOf("-->");
            buffer.delete(pos, pos + 3);
            replaceSelection(buffer.toString());
          } else {
            String newSelection = "<!--" + selectedText + "-->";
            replaceSelection(newSelection);
          }
        } else {
          final int docLen = document.getLength();
          int fromIndex = Math.max(0, getText(0, position).lastIndexOf('\n'));
          int toIndex = getText(fromIndex + 1, docLen - position).indexOf('\n');
          toIndex = toIndex < 0 ? docLen : fromIndex + toIndex;
          String textToComment = getText(fromIndex, toIndex - fromIndex + 1);

          if (textToComment.startsWith("\n")) {
            textToComment = textToComment.substring(1);
            fromIndex++;
          }
          if (textToComment.endsWith("\n")) {
            textToComment = textToComment.substring(0, textToComment.length() - 1);
            toIndex--;
          }
          String trimmed = textToComment.trim();
          if (trimmed.startsWith("<!--") && trimmed.endsWith("-->")) {
            int pos = textToComment.lastIndexOf("-->");
            document.remove(fromIndex + pos, 3);
            pos = textToComment.indexOf("<!--");
            document.remove(fromIndex + pos, 4);
          } else {
            document.insertString(Math.min(toIndex + 1, docLen), "-->", null);
            document.insertString(fromIndex, "<!--", null);
          }
        }
      } catch (BadLocationException e1) {
        e1.printStackTrace();
      }
    }
예제 #11
0
 public static String longestCommonPrefix(String[] strs) {
   if (strs.length == 0) return "";
   StringBuffer prefix = new StringBuffer(strs[0]);
   for (int i = 1; i < strs.length; i++) {
     if (strs[i].length() < prefix.length()) {
       prefix.delete(strs[i].length(), prefix.length());
       if (prefix.length() == 0) return "";
     }
     for (int j = 0; j < prefix.length(); j++) {
       if (prefix.charAt(j) == strs[i].charAt(j)) continue;
       else prefix.delete(j, prefix.length());
     }
   }
   return prefix.toString();
 }
예제 #12
0
  public Font toFont() {
    StringBuffer stringBuffer = new StringBuffer(getFont());
    String fontName = stringBuffer.substring(0, stringBuffer.indexOf("-"));
    stringBuffer = stringBuffer.delete(0, stringBuffer.indexOf("-") + 1);
    String dataStyle = stringBuffer.substring(0, stringBuffer.indexOf("-"));
    if (dataStyle.equalsIgnoreCase("PLAIN")) fontStyle = Font.PLAIN;
    else if (dataStyle.equalsIgnoreCase("BOLD")) fontStyle = Font.BOLD;
    else if (dataStyle.equalsIgnoreCase("")) fontStyle = Font.ITALIC;

    stringBuffer = stringBuffer.delete(0, stringBuffer.indexOf("-") + 1);
    int fontSize = Integer.parseInt(stringBuffer.toString());

    Font font = new Font(fontName, fontStyle, fontSize);
    return font;
  }
예제 #13
0
 /*
  * 根据两个hashMap中输入,进行部分更新
  * hashMap:要修改的数据项及修改值
  * hashMap2:查询待修改项的范围
  */
 public static int update(HashMap<String, String> hashMap, HashMap<String, String> hashMap2) {
   Connection dbConn = DataBaseTool.getConnection();
   StringBuffer sql = new StringBuffer("update orders set ");
   for (Entry<String, String> entry : hashMap.entrySet()) {
     sql.append(entry.getKey() + "='" + entry.getValue() + "',");
   }
   sql.delete(sql.length() - 1, sql.length());
   sql.append(" where ");
   for (Entry<String, String> entry : hashMap2.entrySet()) {
     sql.append(entry.getKey() + "='" + entry.getValue() + "' and ");
   }
   sql.delete(sql.length() - 4, sql.length());
   int result = DataBaseTool.executeSQL(dbConn, sql.toString());
   return result;
 }
예제 #14
0
  protected String[] csvRowSplit(String row, char sep) {
    // remove trailing CRLF
    if (row.endsWith("\r\n")) {
      row = row.substring(0, row.length() - 2);
    } else if (row.endsWith("\n")) {
      row = row.substring(0, row.length() - 1);
    }

    // limit is necessary to prevent split from trimming the empty values at the end of the row
    // FIXME: split() only works if no values contain the separator string
    // String[] rowValues = row.split(Pattern.quote(sep), correctValues.length);
    List<String> rowValues = new Vector<String>();

    StringBuffer aValue = new StringBuffer();
    CharacterIterator i = new StringCharacterIterator(row);
    boolean insideQuote = false;
    for (char c = i.first(); c != CharacterIterator.DONE; c = i.next()) {
      if (c == sep && !insideQuote) {
        // value is finished
        rowValues.add(aValue.toString());
        // clear buffer
        aValue.delete(0, aValue.length());
      } else {
        aValue.append(c);
      }
      // if first or last quote met
      if (c == QUOTE) {
        insideQuote = !insideQuote;
      }
    }
    // add last value
    rowValues.add(aValue.toString());

    return rowValues.toArray(new String[0]);
  }
예제 #15
0
  private void handleClients() {
    for (Socket client : connections) {
      try {
        // From Server to Client
        // ObjectOutputStream out = outputStreams.get(client);
        // From Client to Server
        BufferedReader in = inputStreams.get(client);

        // The variables containing the information received from the Client
        StringBuffer fromClient = inputBuffers.get(client);

        if ((input = in.readLine()) != null) {
          // System.out.println("ServerProtocol " + client.toString() + " : Input = " +input);
          // Add the latest data
          fromClient.append(input);
          // Was the it the end of the file?
          if (input.equals("</WEATHERDATA>")) {
            // Add the complete weatherData to the ParserCorrectorPool
            parserCorrectorPool.addWeatherData(fromClient.toString());
            // Empty the buffer
            fromClient.delete(0, fromClient.length());
          }

          input = null;
        } else {
          removeClientConnection(client);
        }
      } catch (IOException ioex) {
        ioex.printStackTrace();
      }
    }
  }
  private void process(EmailCommand command) throws IOException {

    if (connection == null) {
      passResponseToListeners(command.createResponse("NOCON"));
    } else {
      inputBuffer3.delete(0, inputBuffer3.length());

      byte[][] requests = command.getSerialisedCommand();
      String response = null;

      for (int i = 0; i < requests.length; i++) {
        send(requests[i]);

        response = read();
      }

      while (!response.startsWith(command.getCurrentId())) {
        inputBuffer3.append(response);
        inputBuffer3.append(" \n");
        response = read();
      }
      inputBuffer3.append(response);

      passResponseToListeners(command.createResponse(inputBuffer3.toString()));
    }
  }
예제 #17
0
파일: SEG.java 프로젝트: lithomas/hbci4java
  public String toString(int zero) {
    StringBuffer ret = new StringBuffer(256);
    boolean first = true;

    if (isValid()) {
      int tooMuch = 0;
      int saveLen;
      for (ListIterator<MultipleSyntaxElements> i = getChildContainers().listIterator();
          i.hasNext(); ) {
        if (!first) ret.append('+');

        saveLen = ret.length();
        MultipleSyntaxElements dataList = i.next();
        if (dataList != null) ret.append(dataList.toString(0));

        if (ret.length() == saveLen && !first) {
          tooMuch++;
        } else {
          tooMuch = 0;
        }
        first = false;
      }

      int retlen = ret.length();
      ret.delete(retlen - tooMuch, retlen);
      ret.append('\'');
    }

    return ret.toString();
  }
  public void uploadFile(String fileName, FileInputStream instream, Integer fileLength)
      throws UpYunExcetion {
    try {
      StringBuffer url = new StringBuffer();
      for (String str : fileName.split("/")) {
        if (str == null || str.length() == 0) {
          continue;
        }
        url.append(UrlCodingUtil.encodeBase64(str.getBytes("utf-8")) + "/");
      }
      url = url.delete(url.length() - 1, url.length());
      sign.setUri(url.toString());
    } catch (UnsupportedEncodingException e) {
      LogUtil.exception(logger, e);
    }
    sign.setContentLength(fileLength);
    sign.setMethod(HttpMethodEnum.PUT.name());
    String url = autoUrl + sign.getUri();
    Map<String, String> headers = sign.getHeaders();
    headers.put("mkdir", "true");

    HttpResponse httpResponse = HttpClientUtils.putByHttp(url, headers, instream, fileLength);
    if (httpResponse.getStatusLine().getStatusCode() != 200) {
      throw new UpYunExcetion(
          httpResponse.getStatusLine().getStatusCode(),
          httpResponse.getStatusLine().getReasonPhrase());
    }
  }
예제 #19
0
 protected void resetSql() {
   if (null == sql) {
     sql = new StringBuffer();
   } else {
     sql.delete(0, sql.length());
   }
 }
예제 #20
0
 private ClassLoaderStrategy getClassLoaderStrategy(String fullyQualifiedClassName)
     throws Exception {
   try {
     // Get just the package name
     StringBuffer sb = new StringBuffer(fullyQualifiedClassName);
     sb.delete(sb.lastIndexOf("."), sb.length());
     currentPackage = sb.toString();
     // Retrieve the Java classpath from the system properties
     String cp = System.getProperty("java.class.path");
     String sepChar = System.getProperty("path.separator");
     String[] paths = StringUtils.pieceList(cp, sepChar.charAt(0));
     ClassLoaderStrategy cl =
         ClassLoaderUtil.getClassLoader(ClassLoaderUtil.FILE_SYSTEM_CLASS_LOADER, new String[] {});
     // Iterate through paths until class with the specified name is found
     String classpath = StringUtils.replaceChar(currentPackage, '.', File.separatorChar);
     for (int i = 0; i < paths.length; i++) {
       Class[] classes = cl.getClasses(paths[i] + File.separatorChar + classpath, currentPackage);
       for (int j = 0; j < classes.length; j++) {
         if (classes[j].getName().equals(fullyQualifiedClassName)) {
           return ClassLoaderUtil.getClassLoader(
               ClassLoaderUtil.FILE_SYSTEM_CLASS_LOADER, new String[] {paths[i]});
         }
       }
     }
     throw new Exception("Class could not be found.");
   } catch (Exception e) {
     System.err.println("Exception creating class loader strategy.");
     System.err.println(e.getMessage());
     throw e;
   }
 }
  public void downloadFile(String path, String fileName) throws UpYunExcetion {
    try {
      StringBuffer url = new StringBuffer();
      for (String str : fileName.split("/")) {
        if (str == null || str.length() == 0) {
          continue;
        }
        url.append(UrlCodingUtil.encodeBase64(str.getBytes("utf-8")) + "/");
      }
      url = url.delete(url.length() - 1, url.length());
      sign.setUri(url.toString());
    } catch (UnsupportedEncodingException e) {
      LogUtil.exception(logger, e);
    }
    sign.setContentLength(0);
    sign.setMethod(HttpMethodEnum.GET.name());
    String url = autoUrl + sign.getUri();
    Map<String, String> headers = sign.getHeaders();

    HttpResponse httpResponse = HttpClientUtils.getByHttp(url, headers);
    if (httpResponse.getStatusLine().getStatusCode() != 200) {
      throw new UpYunExcetion(
          httpResponse.getStatusLine().getStatusCode(),
          httpResponse.getStatusLine().getReasonPhrase());
    }

    HttpEntity entity = httpResponse.getEntity();

    try {
      FileUtil.saveToFile(path + "/" + fileName, entity.getContent());
    } catch (Exception e) {
      LogUtil.exception(logger, e);
    }
  }
예제 #22
0
  public static List<QueryPVisitor> confirmTicket(List<Long> ticketList)
      throws DataException, IOException, DocumentException {
    String msgIdValue = System.currentTimeMillis() + "";
    String reqIdValue = "802";
    StringBuffer sb = new StringBuffer();
    for (Long id : ticketList) {
      sb.append(id + ",");
    }
    sb.delete(sb.length() - 1, sb.length());
    Map<String, String> ParamMap = new LinkedHashMap<String, String>();
    ParamMap.put("ReqId", reqIdValue);
    ParamMap.put("MsgId", msgIdValue);
    ParamMap.put("ReqParam", sb.toString());
    ParamMap.put("ReqKey", MD5.md5(reqIdValue + msgIdValue + sb.toString() + key).toLowerCase());

    String returnString = HttpclientUtil.Utf8HttpClientUtils(reUrl, ParamMap);
    Document doc = DocumentHelper.parseText(returnString);
    Element root = doc.getRootElement();
    Element ticket;
    QueryPVisitor queryPVisitor;
    List<QueryPVisitor> returnTicketList = Lists.newArrayList();
    for (Iterator i = root.elementIterator("Ticket"); i.hasNext(); ) {
      ticket = (Element) i.next();
      queryPVisitor = new QueryPVisitor();
      ticket.accept(queryPVisitor);
      returnTicketList.add(queryPVisitor);
    }
    if (returnTicketList.isEmpty()) {
      Document document = DocumentHelper.parseText(returnString);
      queryPVisitor = new QueryPVisitor();
      document.accept(queryPVisitor);
      returnTicketList.add(queryPVisitor);
    }
    return returnTicketList;
  }
예제 #23
0
  private void initContactsHelper() {
    mContext = LanceContactApplication.getInstance();
    setContactsChanged(true);
    if (null == mBaseContacts) {
      mBaseContacts = new ArrayList<Contacts>();
    } else {
      mBaseContacts.clear();
    }

    if (null == mSearchContacts) {
      mSearchContacts = new ArrayList<Contacts>();
    } else {
      mSearchContacts.clear();
    }

    if (null == mFirstNoSearchResultInput) {
      mFirstNoSearchResultInput = new StringBuffer();
    } else {
      mFirstNoSearchResultInput.delete(0, mFirstNoSearchResultInput.length());
    }

    if (null == mSelectedContactsHashMap) {
      mSelectedContactsHashMap = new HashMap<String, Contacts>();
    } else {
      mSelectedContactsHashMap.clear();
    }
  }
예제 #24
0
  @Override
  public void publish(LogRecord record) {
    if (record.getLevel().intValue() < getLevel().intValue()) {
      return;
    }
    if (IL.isInternalLog()) {
      return;
    }
    Runnable off = internalLog();
    try {
      StringBuffer sb = NbModuleLogHandler.toString(record);
      PrintStream ps = getLog();
      if (ps != null) {
        try {
          ps.println(sb.toString());
        } catch (LinkageError err) {
          // prevent circular references
        }
      }

      if (messages.length() + sb.length() > 20000) {
        if (sb.length() > 20000) {
          messages.setLength(0);
          sb.delete(0, sb.length() - 20000);
        } else {
          messages.setLength(20000 - sb.length());
        }
      }

      messages.append(sb.toString());
    } finally {
      off.run();
    }
  }
  protected String getLogBuffer(
      VariableSpace space, String logChannelId, LogStatus status, String limit) {

    StringBuffer buffer = KettleLogStore.getAppender().getBuffer(logChannelId, true);

    if (Const.isEmpty(limit)) {
      String defaultLimit = space.getVariable(Const.KETTLE_LOG_SIZE_LIMIT, null);
      if (!Const.isEmpty(defaultLimit)) {
        limit = defaultLimit;
      }
    }

    // See if we need to limit the amount of rows
    //
    int nrLines = Const.isEmpty(limit) ? -1 : Const.toInt(space.environmentSubstitute(limit), -1);

    if (nrLines > 0) {
      int start = buffer.length() - 1;
      for (int i = 0; i < nrLines && start > 0; i++) {
        start = buffer.lastIndexOf(Const.CR, start - 1);
      }
      if (start > 0) {
        buffer.delete(0, start + Const.CR.length());
      }
    }

    return buffer.append(Const.CR + status.getStatus().toUpperCase() + Const.CR).toString();
  }
예제 #26
0
파일: GetHaoYouLB.java 프로젝트: weiyk/ES
  private static String getBanJi(String cids) {
    StringBuffer sql = new StringBuffer();
    StringBuffer classid = new StringBuffer();
    StringBuffer condition = new StringBuffer(63);
    if (!"".equals(cids) && cids != null) {
      if (cids.indexOf(",") != -1) {
        String[] cid = cids.split(",");
        condition.append("where classId  in (");
        for (int i = 0; i < cid.length; i++) {
          condition.append("'" + cid[i] + "',");
        }
        condition.delete(condition.length() - 1, condition.length());
        condition.append(" )");
      } else {
        condition.append("where classId ='" + cids + "'");
      }
      sql.append("select className from jcsc_BanJi ").append(condition);
      ResultSet rs = null;
      try {
        rs = dba.executeQuery(sql.toString());
        while (rs.next()) {
          classid.append(rs.getString(1) + ",");
        }
        if (classid.length() > 0) {
          classid.setLength(classid.length() - 1);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    return classid.toString();
  }
예제 #27
0
  /**
   * Reads in a PKCS7 object. This returns a ContentInfo object suitable for use with the CMS API.
   *
   * @return the X509Certificate
   * @throws IOException if an I/O error occured
   */
  private static CMSSignedData readPKCS7(BufferedReader in, char[] p, String endMarker)
      throws IOException {
    String line;
    StringBuffer buf = new StringBuffer();
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();

    while ((line = in.readLine()) != null) {
      if (line.indexOf(endMarker) != -1) {
        break;
      }
      line = line.trim();
      buf.append(line.trim());
      Base64.decode(buf.substring(0, (buf.length() / 4) * 4), bOut);
      buf.delete(0, (buf.length() / 4) * 4);
    }
    if (buf.length() != 0) {
      throw new RuntimeException("base64 data appears to be truncated");
    }
    if (line == null) {
      throw new IOException(endMarker + " not found");
    }
    try {
      ASN1InputStream aIn = new ASN1InputStream(bOut.toByteArray());
      return new CMSSignedData(ContentInfo.getInstance(aIn.readObject()));
    } catch (Exception e) {
      throw new IOException("problem parsing PKCS7 object: " + e.toString());
    }
  }
예제 #28
0
  /**
   * Redirects the user to the current url over HTTPS
   *
   * @param request a HttpServletRequest
   * @param response a HttpServletResponse
   * @param urlStr
   * @param nonSslPort the port Non-SSL requests should be forwarded to
   * @throws ServletException
   * @throws IOException
   */
  public static void redirectOverNonSSL(
      HttpServletRequest request, HttpServletResponse response, String urlStr, int nonSslPort)
      throws ServletException, IOException {

    StringBuffer url = new StringBuffer(urlStr);

    // Make sure we're on http
    if (url.charAt(4) == 's') url.deleteCharAt(4);

    // If there is a non-ssl port, make sure we're on it,
    // otherwise assume we're already on the right port
    if (nonSslPort > 0) {
      int portStart = url.indexOf(":", 8) + 1;
      int portEnd = url.indexOf("/", 8);

      if (portEnd == -1) // If their isn't a trailing slash, then the end is the last char
      portEnd = url.length() - 1;

      if (portStart > 0
          && portStart
              < portEnd) { // If we detected a : before the trailing slash or end of url, delete the
                           // port
        url.delete(portStart, portEnd);
      } else {
        url.insert(portEnd, ':'); // If the url didn't have a port, add in the :
        portStart = portEnd;
      }

      url.insert(portStart, nonSslPort); // Insert the right port where it should be
    }

    LogFactory.getLog(ServletUtils.class).debug("redirectOverSSL sending 301: " + url.toString());
    sendPermanentRedirect(response, url.toString());
  }
예제 #29
0
  /**
   * Adds a syntax to the syntaxsection
   *
   * @param doc, doc item that has to be add to the syntax section
   */
  void addSyntax(Doc doc) {
    if (doc.isConstructor() || doc.isMethod()) {
      StringBuffer syntaxBuffer = new StringBuffer();
      for (Parameter parameter : ((ExecutableMemberDoc) doc).parameters()) {
        syntaxBuffer.append(parameter.typeName() + " " + parameter.name());
        syntaxBuffer.append(", ");
      }
      if (syntaxBuffer.length() > 2) {
        syntaxBuffer.delete(syntaxBuffer.length() - 2, syntaxBuffer.length());
      }

      String returnType = "";

      if (doc.isMethod()) {
        MethodDoc methodDoc = (MethodDoc) doc;
        returnType = methodDoc.returnType().toString();
        int lastDot = returnType.lastIndexOf('.');
        if (lastDot != -1) {
          returnType = returnType.substring(lastDot + 1);
        }
        returnType += " ";
      }

      if (doc.isConstructor()) {
        addSyntax("<em>" + doc.commentText() + "</em>");
      }

      addSyntax(returnType + doc.name() + "(" + syntaxBuffer.toString() + ")");
    } else if (doc.isField()) {
      FieldDoc fieldDoc = (FieldDoc) doc;
      addSyntax(fieldDoc.type().typeName() + " " + doc.name());
    }
  }
  public void delete(String name, Boolean flag) throws UpYunExcetion {
    try {
      StringBuffer url = new StringBuffer();
      for (String str : name.split("/")) {
        if (str == null || str.length() == 0) {
          continue;
        }
        url.append(UrlCodingUtil.encodeBase64(str.getBytes("utf-8")) + "/");
      }
      if (flag) {
        url = url.delete(url.length() - 1, url.length());
      }
      sign.setUri(url.toString());
    } catch (UnsupportedEncodingException e) {
      LogUtil.exception(logger, e);
    }
    sign.setContentLength(0);
    sign.setMethod(HttpMethodEnum.DELETE.name());
    String url = autoUrl + sign.getUri();
    Map<String, String> headers = sign.getHeaders();

    HttpResponse httpResponse = HttpClientUtils.deleteByHttp(url, headers);
    if (httpResponse.getStatusLine().getStatusCode() != 200) {
      throw new UpYunExcetion(
          httpResponse.getStatusLine().getStatusCode(),
          httpResponse.getStatusLine().getReasonPhrase());
    }
  }