Ejemplo n.º 1
4
  protected String getRallyXML(String apiUrl) throws Exception {
    String responseXML = "";

    DefaultHttpClient httpClient = new DefaultHttpClient();

    Base64 base64 = new Base64();
    String encodeString =
        new String(base64.encode((rallyApiHttpUsername + ":" + rallyApiHttpPassword).getBytes()));

    HttpGet httpGet = new HttpGet(apiUrl);
    httpGet.addHeader("Authorization", "Basic " + encodeString);
    HttpResponse response = httpClient.execute(httpGet);
    HttpEntity entity = response.getEntity();

    if (entity != null) {

      InputStreamReader reader = new InputStreamReader(entity.getContent());
      BufferedReader br = new BufferedReader(reader);

      StringBuilder sb = new StringBuilder();
      String line = "";
      while ((line = br.readLine()) != null) {
        sb.append(line);
      }

      responseXML = sb.toString();
    }

    log.debug("responseXML=" + responseXML);

    return responseXML;
  }
Ejemplo n.º 2
2
  @Override
  protected Transferable createTransferable(JComponent c) {
    JTextPane aTextPane = (JTextPane) c;

    HTMLEditorKit kit = ((HTMLEditorKit) aTextPane.getEditorKit());
    StyledDocument sdoc = aTextPane.getStyledDocument();
    int sel_start = aTextPane.getSelectionStart();
    int sel_end = aTextPane.getSelectionEnd();

    int i = sel_start;
    StringBuilder output = new StringBuilder();
    while (i < sel_end) {
      Element e = sdoc.getCharacterElement(i);
      Object nameAttr = e.getAttributes().getAttribute(StyleConstants.NameAttribute);
      int start = e.getStartOffset(), end = e.getEndOffset();
      if (nameAttr == HTML.Tag.BR) {
        output.append("\n");
      } else if (nameAttr == HTML.Tag.CONTENT) {
        if (start < sel_start) {
          start = sel_start;
        }
        if (end > sel_end) {
          end = sel_end;
        }
        try {
          String str = sdoc.getText(start, end - start);
          output.append(str);
        } catch (BadLocationException ble) {
          Debug.error(me + "Copy-paste problem!\n%s", ble.getMessage());
        }
      }
      i = end;
    }
    return new StringSelection(output.toString());
  }
Ejemplo n.º 3
1
 /**
  * Removes comments from the specified string and returns the first characters of a query.
  *
  * @param qu query string
  * @param max maximum length of string to return
  * @return result
  */
 public static String removeComments(final String qu, final int max) {
   final StringBuilder sb = new StringBuilder();
   int m = 0;
   boolean s = false;
   final int cl = qu.length();
   for (int c = 0; c < cl && sb.length() < max; ++c) {
     final char ch = qu.charAt(c);
     if (ch == 0x0d) continue;
     if (ch == '(' && c + 1 < cl && qu.charAt(c + 1) == ':') {
       if (m == 0 && !s) {
         sb.append(' ');
         s = true;
       }
       ++m;
       ++c;
     } else if (m != 0 && ch == ':' && c + 1 < cl && qu.charAt(c + 1) == ')') {
       --m;
       ++c;
     } else if (m == 0) {
       if (ch > ' ') sb.append(ch);
       else if (!s) sb.append(' ');
       s = ch <= ' ';
     }
   }
   if (sb.length() >= max) sb.append("...");
   return sb.toString().trim();
 }
Ejemplo n.º 4
1
 /**
  * Returns a map with variable bindings.
  *
  * @param opts main options
  * @return bindings
  */
 public static HashMap<String, String> bindings(final MainOptions opts) {
   final HashMap<String, String> bindings = new HashMap<>();
   final String bind = opts.get(MainOptions.BINDINGS).trim();
   final StringBuilder key = new StringBuilder();
   final StringBuilder val = new StringBuilder();
   boolean first = true;
   final int sl = bind.length();
   for (int s = 0; s < sl; s++) {
     final char ch = bind.charAt(s);
     if (first) {
       if (ch == '=') {
         first = false;
       } else {
         key.append(ch);
       }
     } else {
       if (ch == ',') {
         if (s + 1 == sl || bind.charAt(s + 1) != ',') {
           bindings.put(key.toString().trim(), val.toString());
           key.setLength(0);
           val.setLength(0);
           first = true;
           continue;
         }
         // literal commas are escaped by a second comma
         s++;
       }
       val.append(ch);
     }
   }
   if (key.length() != 0) bindings.put(key.toString().trim(), val.toString());
   return bindings;
 }
Ejemplo n.º 5
1
Archivo: Macro.java Proyecto: bramk/bnd
  public String _range(String args[]) {
    verifyCommand(args, _rangeHelp, _rangePattern, 2, 3);
    Version version = null;
    if (args.length >= 3) version = new Version(args[2]);
    else {
      String v = domain.getProperty("@");
      if (v == null) return null;
      version = new Version(v);
    }
    String spec = args[1];

    Matcher m = RANGE_MASK.matcher(spec);
    m.matches();
    String floor = m.group(1);
    String floorMask = m.group(2);
    String ceilingMask = m.group(3);
    String ceiling = m.group(4);

    String left = version(version, floorMask);
    String right = version(version, ceilingMask);
    StringBuilder sb = new StringBuilder();
    sb.append(floor);
    sb.append(left);
    sb.append(",");
    sb.append(right);
    sb.append(ceiling);

    String s = sb.toString();
    VersionRange vr = new VersionRange(s);
    if (!(vr.includes(vr.getHigh()) || vr.includes(vr.getLow()))) {
      domain.error(
          "${range} macro created an invalid range %s from %s and mask %s", s, version, spec);
    }
    return sb.toString();
  }
Ejemplo n.º 6
1
Archivo: Macro.java Proyecto: bramk/bnd
 public static void verifyCommand(
     String args[],
     @SuppressWarnings("unused") String help,
     Pattern[] patterns,
     int low,
     int high) {
   String message = "";
   if (args.length > high) {
     message = "too many arguments";
   } else if (args.length < low) {
     message = "too few arguments";
   } else {
     for (int i = 0; patterns != null && i < patterns.length && i < args.length; i++) {
       if (patterns[i] != null) {
         Matcher m = patterns[i].matcher(args[i]);
         if (!m.matches())
           message +=
               String.format(
                   "Argument %s (%s) does not match %s%n", i, args[i], patterns[i].pattern());
       }
     }
   }
   if (message.length() != 0) {
     StringBuilder sb = new StringBuilder();
     String del = "${";
     for (String arg : args) {
       sb.append(del);
       sb.append(arg);
       del = ";";
     }
     sb.append("}, is not understood. ");
     sb.append(message);
     throw new IllegalArgumentException(sb.toString());
   }
 }
Ejemplo n.º 7
1
  /**
   * If the outbound level is BINARY, convert the string field to binary, then pad to the left with
   * the appropriate number of zero bits to reach a number of bits specified by the bitLength
   * attribute of the TDT definition file.
   */
  private void binaryPadding(Map<String, String> extraparams, Field tdtfield) {
    String fieldname = tdtfield.getName();
    int reqbitlength = tdtfield.getBitLength();
    String value;

    String binaryValue = fieldToBinary(tdtfield, extraparams);
    if (binaryValue.length() < reqbitlength) {
      int extraBitLength = reqbitlength - binaryValue.length();

      StringBuilder zeroPaddedBinaryValue = new StringBuilder("");
      for (int i = 0; i < extraBitLength; i++) {
        zeroPaddedBinaryValue.append("0");
      }
      zeroPaddedBinaryValue.append(binaryValue);
      value = zeroPaddedBinaryValue.toString();
    } else {
      if (binaryValue.length() > reqbitlength)
        throw new TDTException(
            "Binary value ["
                + binaryValue
                + "] for field "
                + fieldname
                + " exceeds maximum allowed "
                + reqbitlength
                + " bits.  Decimal value was "
                + extraparams.get(fieldname));

      value = binaryValue;
    }
    extraparams.put(fieldname, value);
  }
Ejemplo n.º 8
1
  public String getCoordinates(RevisionRef r) {
    StringBuilder sb = new StringBuilder(r.groupId).append(":").append(r.artifactId).append(":");
    if (r.classifier != null) sb.append(r.classifier).append("@");
    sb.append(r.version);

    return sb.toString();
  }
Ejemplo n.º 9
1
 private static String convert(List<List<Particle>> lists) {
   StringBuilder sb = new StringBuilder();
   for (List<Particle> list : lists) {
     if (list.isEmpty()) sb.append('.');
     else sb.append('X');
   }
   return sb.toString();
 }
Ejemplo n.º 10
1
  /** Takes a string and hides its extension */
  public static String hideExtension(final String str) {
    String[] arr = str.split("\\.");

    if (arr.length <= 1) return str; // there was no "." in str.

    StringBuilder sb = new StringBuilder("");
    for (int i = 0; i < arr.length - 1; ++i) {
      if (sb.length() > 0) sb.append(".");
      sb.append(arr[i]);
    }
    return sb.toString();
  }
Ejemplo n.º 11
0
  private static String expand(String str) {
    if (str == null) {
      return null;
    }

    StringBuilder result = new StringBuilder();
    Pattern re = Pattern.compile("^(.*?)\\$\\{([^}]*)\\}(.*)");
    while (true) {
      Matcher matcher = re.matcher(str);
      if (matcher.matches()) {
        result.append(matcher.group(1));
        String property = matcher.group(2);
        if (property.equals("/")) {
          property = "file.separator";
        }
        String value = System.getProperty(property);
        if (value != null) {
          result.append(value);
        }
        str = matcher.group(3);
      } else {
        result.append(str);
        break;
      }
    }
    return result.toString();
  }
Ejemplo n.º 12
0
 public String toString() {
   StringBuilder sb = new StringBuilder(this.getClass().getSimpleName()).append('{');
   for (TypedValues typed : _values) {
     sb.append(typed);
   }
   return sb.append('}').toString();
 }
Ejemplo n.º 13
0
  @SuppressWarnings("deprecation")
  public void testAllResolved() {
    assertNotNull("Expected a Bundle Context", context);
    StringBuilder sb = new StringBuilder();

    for (Bundle b : context.getBundles()) {
      if (b.getState() == Bundle.INSTALLED
          && b.getHeaders().get(aQute.bnd.osgi.Constants.FRAGMENT_HOST) == null) {
        try {
          b.start();
        } catch (BundleException e) {
          sb.append(b.getBundleId())
              .append(" ")
              .append(b.getSymbolicName())
              .append(";")
              .append(b.getVersion())
              .append("\n");
          sb.append("    ").append(e.getMessage()).append("\n\n");
          System.err.println(e.getMessage());
        }
      }
    }
    Matcher matcher = IP_P.matcher(sb);
    String out =
        matcher.replaceAll(
            "\n\n         " + aQute.bnd.osgi.Constants.IMPORT_PACKAGE + ": $1;version=[$2,$3)\n");
    assertTrue("Unresolved bundles\n" + out, sb.length() == 0);
  }
Ejemplo n.º 14
0
  private String blankSectionHeaders(String markup, StringBuffer context) {

    Pattern p = Pattern.compile("(={2,})([^=]+)\\1");
    Matcher m = p.matcher(markup);

    int lastPos = 0;
    StringBuilder sb = new StringBuilder();

    while (m.find()) {
      sb.append(markup.substring(lastPos, m.start()));
      sb.append(getSpaceString(m.group().length()));

      String title = m.group(2).trim();

      if (!title.equalsIgnoreCase("see also")
          && !title.equalsIgnoreCase("external links")
          && !title.equalsIgnoreCase("references")
          && !title.equalsIgnoreCase("further reading")) context.append("\n").append(title);

      lastPos = m.end();
    }

    sb.append(markup.substring(lastPos));
    return sb.toString();
  }
Ejemplo n.º 15
0
 protected void executeQuery(Statement stmt, String q) throws SQLException {
   q = q.replace("$PREFIX", getPrefix());
   LOG.info(" Executing " + q);
   ResultSet rs = stmt.executeQuery(q);
   StringBuilder header = new StringBuilder();
   for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
     if (i > 1) {
       header.append("|");
     }
     header.append(rs.getMetaData().getColumnName(i));
   }
   LOG.info(header);
   int seq = 0;
   while (true) {
     boolean valid = rs.next();
     if (!valid) break;
     seq++;
     StringBuilder line = new StringBuilder();
     for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
       if (i > 1) {
         line.append("|");
       }
       line.append(rs.getString(i));
     }
     LOG.info(seq + ":" + line);
   }
 }
Ejemplo n.º 16
0
 private void appendTestMethod(@Nonnull StackTraceElement current) {
   content.append("          <li>");
   content.append(current.getClassName()).append('#');
   content
       .append(LESS_THAN_CHAR.matcher(current.getMethodName()).replaceFirst("&lt;"))
       .append(": ");
   content.append(current.getLineNumber());
 }
Ejemplo n.º 17
0
 protected void selected(CharPos start, CharPos end) {
   StringBuilder buf = new StringBuilder();
   synchronized (msgs) {
     boolean sel = false;
     for (Message msg : msgs) {
       if (!(msg.text() instanceof RichText)) continue;
       RichText rt = (RichText) msg.text();
       RichText.Part part = null;
       if (sel) {
         part = rt.parts;
       } else if (msg == start.msg) {
         sel = true;
         for (part = rt.parts; part != null; part = part.next) {
           if (part == start.part) break;
         }
       }
       if (sel) {
         for (; part != null; part = part.next) {
           if (!(part instanceof RichText.TextPart)) continue;
           RichText.TextPart tp = (RichText.TextPart) part;
           CharacterIterator iter = tp.ti();
           int sch;
           if (tp == start.part) sch = tp.start + start.ch.getInsertionIndex();
           else sch = tp.start;
           int ech;
           if (tp == end.part) ech = tp.start + end.ch.getInsertionIndex();
           else ech = tp.end;
           for (int i = sch; i < ech; i++) buf.append(iter.setIndex(i));
           if (part == end.part) {
             sel = false;
             break;
           }
           buf.append(' ');
         }
         if (sel) buf.append('\n');
       }
       if (msg == end.msg) break;
     }
   }
   Clipboard cl;
   if ((cl = java.awt.Toolkit.getDefaultToolkit().getSystemSelection()) == null)
     cl = java.awt.Toolkit.getDefaultToolkit().getSystemClipboard();
   try {
     final CharPos ownsel = selstart;
     cl.setContents(
         new StringSelection(buf.toString()),
         new ClipboardOwner() {
           public void lostOwnership(Clipboard cl, Transferable tr) {
             if (selstart == ownsel) selstart = selend = null;
           }
         });
   } catch (IllegalStateException e) {
   }
 }
Ejemplo n.º 18
0
 public String toString() {
   StringBuilder sb = new StringBuilder();
   for (int i = 0; i < urls.size(); i++) {
     if (i > 0) {
       sb.append("|");
     }
     sb.append(
         String.format("%d,%d=\"%s\"", locations.get(i)[0], locations.get(i)[1], urls.get(i)));
   }
   return sb.toString();
 }
Ejemplo n.º 19
0
  private void end(StringBuilder ans, Pretty pretty, String indent) {
    if (endEncloser == null) return;
    if (!pretty.pretty) ans.append(endEncloser);
    else {
      Utilities.assureEndsWithNewLine(ans);
      ans.append(indent + endEncloser);
      if (pretty.comments && endComment.length() > 0) ans.append("#" + endComment);

      Utilities.assureEndsWithNewLine(ans);
    }
  }
Ejemplo n.º 20
0
 /**
  * Pads a binary value supplied as a string first parameter to the left with leading zeros in
  * order to reach a required number of bits, as expressed by the second parameter, reqlen. Returns
  * a string value corresponding to the binary value left padded to the required number of bits.
  */
 private String padBinary(String binary, int reqlen) {
   String rv;
   int l = binary.length();
   int pad = (reqlen - (l % reqlen)) % reqlen;
   StringBuilder buffer = new StringBuilder("");
   for (int i = 0; i < pad; i++) {
     buffer.append("0");
   }
   buffer.append(binary);
   rv = buffer.toString();
   return rv;
 }
Ejemplo n.º 21
0
 private void start(StringBuilder ans, Pretty pretty, String indent) {
   if (startEncloser == null) return;
   if (!pretty.pretty) {
     ans.append(startEncloser);
   } else {
     String comment;
     if (pretty.comments && startComment.length() > 0) comment = " #" + startComment;
     else comment = "";
     ans.append(indent + startEncloser + comment);
     Utilities.assureEndsWithNewLine(ans);
   }
 }
Ejemplo n.º 22
0
Archivo: Macro.java Proyecto: bramk/bnd
 @Override
 public String toString() {
   StringBuilder sb = new StringBuilder();
   String del = "[";
   for (Link r = this; r != null; r = r.previous) {
     sb.append(del);
     sb.append(r.key);
     del = ",";
   }
   sb.append("]");
   return sb.toString();
 }
Ejemplo n.º 23
0
  // Derived from http://stackoverflow.com/a/3054692/250076
  public static File getRelativeFile(File targetFile, File baseFile) {
    try {
      targetFile = targetFile.getCanonicalFile();
      baseFile = baseFile.getCanonicalFile();
    } catch (IOException ignored) {
    }
    String pathSeparator = File.separator;
    String basePath = baseFile.getAbsolutePath();
    String normalizedTargetPath = normalize(targetFile.getAbsolutePath(), pathSeparator);
    String normalizedBasePath = normalize(basePath, pathSeparator);

    String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator));
    String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator));

    StringBuilder common = new StringBuilder();

    int commonIndex = 0;
    while (commonIndex < target.length
        && commonIndex < base.length
        && target[commonIndex].equals(base[commonIndex])) {
      common.append(target[commonIndex]).append(pathSeparator);
      commonIndex++;
    }

    if (commonIndex == 0) {
      throw new Error(
          "No common path element found for '"
              + normalizedTargetPath
              + "' and '"
              + normalizedBasePath
              + '\'');
    }

    boolean baseIsFile = true;

    if (baseFile.exists()) {
      baseIsFile = baseFile.isFile();
    } else if (basePath.endsWith(pathSeparator)) {
      baseIsFile = false;
    }

    StringBuilder relative = new StringBuilder();

    if (base.length != commonIndex) {
      int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;

      for (int i = 0; i < numDirsUp; i++) {
        relative.append("..").append(pathSeparator);
      }
    }
    relative.append(normalizedTargetPath.substring(common.length()));
    return new File(relative.toString());
  }
Ejemplo n.º 24
0
Archivo: Macro.java Proyecto: bramk/bnd
  protected String replace(String key, Link link) {
    if (link != null && link.contains(key)) return "${infinite:" + link.toString() + "}";

    if (key != null) {
      key = key.trim();
      if (key.length() > 0) {
        Processor source = domain;
        String value = null;

        if (key.indexOf(';') < 0) {
          Instruction ins = new Instruction(key);
          if (!ins.isLiteral()) {
            SortedList<String> sortedList = SortedList.fromIterator(domain.iterator());
            StringBuilder sb = new StringBuilder();
            String del = "";
            for (String k : sortedList) {
              if (ins.matches(k)) {
                String v = replace(k, new Link(source, link, key));
                if (v != null) {
                  sb.append(del);
                  del = ",";
                  sb.append(v);
                }
              }
            }
            return sb.toString();
          }
        }
        while (value == null && source != null) {
          value = source.getProperties().getProperty(key);
          source = source.getParent();
        }

        if (value != null) return process(value, new Link(source, link, key));

        value = doCommands(key, link);
        if (value != null) return process(value, new Link(source, link, key));

        if (key != null && key.trim().length() > 0) {
          value = System.getProperty(key);
          if (value != null) return value;
        }
        if (!flattening && !key.equals("@"))
          domain.warning("No translation found for macro: " + key);
      } else {
        domain.warning("Found empty macro key");
      }
    } else {
      domain.warning("Found null macro key");
    }
    return "${" + key + "}";
  }
Ejemplo n.º 25
0
  /**
   * Returns a string built using a particular grammar. Single-quotes strings are counted as literal
   * strings, whereas all other strings appearing in the grammar require substitution with the
   * corresponding value from the extraparams hashmap.
   */
  private String buildGrammar(String grammar, Map<String, String> extraparams) {
    StringBuilder outboundstring = new StringBuilder();
    String[] fields = Pattern.compile("\\s+").split(grammar);
    for (int i = 0; i < fields.length; i++) {
      if (fields[i].substring(0, 1).equals("'")) {
        outboundstring.append(fields[i].substring(1, fields[i].length() - 1));
      } else {
        outboundstring.append(extraparams.get(fields[i]));
      }
    }

    return outboundstring.toString();
  }
Ejemplo n.º 26
0
 /**
  * returns the multiple alignment as a string in a fashion identical to that in a file of
  * ALN/CLUSTALW format (except from the fact that info about residues' match is missing. Aka, the
  * 3rd line of a file of ALN/CLUSTALW ('*', '.', ':' chars) is missing).
  *
  * <p>(Note: CLUSTALW doesn't necessarily have the match characters... -Tim)
  */
 public String toString() {
   StringBuilder sb = new StringBuilder();
   int tl = maxTagLength();
   int i = 0, last = gappedAlignments.keySet().size() - 1;
   for (String tag : gappedAlignments.keySet()) {
     sb.append(StringUtils.padString(tag, tl));
     sb.append("  ");
     sb.append(gappedAlignments.get(tag).gappedString());
     if (i < last) {
       sb.append("\n");
     }
     i += 1;
   }
   return sb.toString();
 }
  @Override
  public synchronized void run() {
    while (!quit) {
      //			filter_input();
      try {
        Thread.sleep(1); // poll at 1kHz
        // grab data from shared buffer and move it the local one
        ourBuffer.append(sharedBuffer.take());
        // System.out.print(ourBuffer);
        // create a matcher to find an open tag in the buffer
        int endCloseTag;
        int startOpenTag;
        Matcher closeTagMatcher = closeTagPattern.matcher(ourBuffer);

        // look or a closing tag in our buffer
        if (closeTagMatcher.find()) {
          endCloseTag = closeTagMatcher.end();
          openTag = "<" + ourBuffer.charAt(closeTagMatcher.start() + 2) + ">";
          // find corresponding opening tag
          startOpenTag = ourBuffer.indexOf(openTag);
          // send the input string to the GUI for processing
          if (startOpenTag >= 0 && startOpenTag < endCloseTag) {
            gui.incoming(ourBuffer.substring(startOpenTag, endCloseTag));
            // clear our buffer
            ourBuffer.delete(startOpenTag, endCloseTag);
          } else {
            ourBuffer.delete(0, endCloseTag);
          }
        }
      } catch (Exception e) {
        System.out.print(e + "\n");
      }
    }
  }
Ejemplo n.º 28
0
 static String outputOf(Reader r) throws IOException {
   final StringBuilder sb = new StringBuilder();
   final char[] buf = new char[1024];
   int n;
   while ((n = r.read(buf)) > 0) sb.append(buf, 0, n);
   return sb.toString();
 }
Ejemplo n.º 29
0
 private String getAuthorizeUrl() {
   StringBuilder url = new StringBuilder();
   url.append(this.service_.getAuthorizationEndpoint());
   boolean hasQuery = url.toString().indexOf('?') != -1;
   url.append(hasQuery ? '&' : '?')
       .append("client_id=")
       .append(Utils.urlEncode(this.service_.getClientId()))
       .append("&redirect_uri=")
       .append(Utils.urlEncode(this.service_.getGenerateRedirectEndpoint()))
       .append("&scope=")
       .append(Utils.urlEncode(this.scope_))
       .append("&response_type=code")
       .append("&state=")
       .append(Utils.urlEncode(this.oAuthState_));
   return url.toString();
 }
Ejemplo n.º 30
0
  private void appendRepetitionCountIfNeeded(@Nonnull CallPoint callPoint) {
    int repetitionCount = callPoint.getRepetitionCount();

    if (repetitionCount > 0) {
      content.append('x').append(1 + repetitionCount);
    }
  }