@NotNull
 public static String getLibraryName(@NotNull Library library) {
   final String result = library.getName();
   if (result != null) {
     return result;
   }
   String[] endingsToStrip = {"/", "!", ".jar"};
   StringBuilder buffer = new StringBuilder();
   for (OrderRootType type : OrderRootType.getAllTypes()) {
     for (String url : library.getUrls(type)) {
       buffer.setLength(0);
       buffer.append(url);
       for (String ending : endingsToStrip) {
         if (buffer.lastIndexOf(ending) == buffer.length() - ending.length()) {
           buffer.setLength(buffer.length() - ending.length());
         }
       }
       final int i = buffer.lastIndexOf(PATH_SEPARATOR);
       if (i < 0 || i >= buffer.length() - 1) {
         continue;
       }
       String candidate = buffer.substring(i + 1);
       if (!StringUtil.isEmpty(candidate)) {
         return candidate;
       }
     }
   }
   assert false;
   return "unknown-lib";
 }
Beispiel #2
1
  private String getSegment() {

    String segment = null;

    int pos = m_sb.indexOf(SEPARATOR);
    int sl = SEPARATOR.length();

    if (pos > 0 && pos + sl < m_sb.length() && m_sb.charAt(pos + sl) == '\r') {
      sl++;
    }

    if (pos > 0 && pos + sl < m_sb.length() && m_sb.charAt(pos + sl) == '\n') {
      sl++;
    }

    if (pos >= 0) {
      segment = m_sb.substring(0, pos);

      m_sb.delete(0, pos + sl);
    } else {
      pos = m_sb.indexOf(TERMINATOR);

      if (pos >= 0) {
        m_last = true;
        segment = m_sb.substring(0, pos);
      }
    }

    return segment;
  }
Beispiel #3
1
  /*
   * Assumes valid xml
   */
  private String getElement(Reader reader) throws IOException {
    StringBuilder result = new StringBuilder();
    result.append('<');

    boolean done = false;

    while (!done) {
      int current = reader.read();
      while (current != '>') {
        if (current < 0) {
          throw new EOFException();
        }
        result.append((char) current);
        current = reader.read();
      }
      result.append((char) current);

      int len = result.length();
      if (len > 4 && result.substring(0, 4).equals("<!--")) {
        // This is a comment - make sure we are at the end
        if (len >= 7 && result.substring(len - 3, len).equals("-->")) {
          done = true;
        }
      } else {
        done = true;
      }
    }

    return result.toString();
  }
  private String createUnion(
      int index, Collection<Object> params, String fieldName, String operator) {
    StringBuilder queryUnion = new StringBuilder();
    StringBuilder queryFilter = new StringBuilder();

    for (Object param : params) {
      String letName = "$q" + index++;
      queryFilter
          .append(", ")
          .append(letName)
          .append(" = (SELECT FROM MeIdentification WHERE ")
          .append(fieldName)
          .append(' ')
          .append(operator)
          .append(" '")
          .append(param)
          .append("')");
      queryUnion.append(",").append(letName);
    }

    if (params.size() == 1) return queryFilter.toString();
    else
      return ", $q"
          + index
          + " = (SELECT FROM MeIdentification WHERE @rid IN ( SELECT UNIONALL("
          + queryUnion.substring(1)
          + ") LET "
          + queryFilter.substring(2)
          + " ))";
  }
  public static UUID generateUuidForName(String name) {
    TFM_Log.info("Generating spoof UUID for " + name);
    name = name.toLowerCase();
    try {
      final MessageDigest mDigest = MessageDigest.getInstance("SHA1");
      byte[] result = mDigest.digest(name.getBytes());
      final StringBuilder sb = new StringBuilder();
      for (int i = 0; i < result.length; i++) {
        sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
      }

      return UUID.fromString(
          sb.substring(0, 8)
              + "-"
              + sb.substring(8, 12)
              + "-"
              + sb.substring(12, 16)
              + "-"
              + sb.substring(16, 20)
              + "-"
              + sb.substring(20, 32));
    } catch (NoSuchAlgorithmException ex) {
      TFM_Log.severe(ex);
    }

    return UUID.randomUUID();
  }
  @Override
  public String toSourceString() {

    StringBuilder sb = new StringBuilder();

    appendSourceStringForChildren(sb);

    if (userSuppliedPlaceholderName != null) {
      int indexBeforeClose;
      if (isSelfEnding) {
        indexBeforeClose = sb.length() - 2;
        if (!sb.substring(indexBeforeClose).equals("/>")) {
          throw new AssertionError();
        }
      } else {
        indexBeforeClose = sb.length() - 1;
        if (!sb.substring(indexBeforeClose).equals(">")) {
          throw new AssertionError();
        }
      }
      sb.insert(indexBeforeClose, " phname=\"" + userSuppliedPlaceholderName + "\"");
    }

    return sb.toString();
  }
  private static ORMSQLContext buildCreateColumnList(
      Object obj, com.corm.mapping.generated.Class clazz, String action, String ignoreFor) {

    //		String catalog = clazz.getKeyspace();
    String table = clazz.getColumnFamily();
    StringBuilder builder = new StringBuilder();
    builder.append(action + " ").append(table + " (");
    Set<String> columns = ORMPropertyListBuilder.build(obj, clazz.getName(), ignoreFor);
    Set<com.corm.mapping.generated.Column> refined =
        new LinkedHashSet<com.corm.mapping.generated.Column>();

    for (String column : columns) {
      //			String name = column.getName();
      builder.append(column + ',');
    }

    builder.trimToSize();
    builder = new StringBuilder(builder.substring(0, builder.length() - 1));
    builder.append(") VALUES (");

    for (int i = 0; i < columns.size(); i++) {
      //			if(column.isInject() && !canIgnore(column,ignoreFor)){
      //				builder.append(column.getHint()+",");
      //			}else{
      //				refined.add(column);
      builder.append("?,");
      //			}
    }

    String sql = builder.substring(0, builder.length() - 1) + ")";
    builder.setLength(0);
    builder = null;
    return new ORMSQLContext(sql, refined);
  }
  public String siguienteInstruccion() throws IOException {
    String instruccion = null;

    if (buffer.length() > 0) {
      int pos = buscaChar(buffer, 0, buffer.length(), ';');
      if (pos > 0) {
        instruccion = buffer.substring(0, pos);
        buffer = new StringBuilder(buffer.substring(pos + 1, buffer.length()));
      }
    } else {
      char[] cbuf = new char[4 * 1024];
      int leidos = 0;
      while ((instruccion == null) && ((leidos = reader.read(cbuf)) != -1)) {
        leidos = reemplazaSeparadorDeLinea(' ', cbuf, 0, leidos);
        int pos = buscaChar(cbuf, 0, leidos, ';');
        if (pos > 0) {
          buffer.append(cbuf, 0, pos);
          instruccion = buffer.toString();
          buffer.setLength(0);
          buffer.append(cbuf, pos + 1, leidos);
        } else {
          buffer.append(cbuf, 0, leidos);
        }
      }
      if (leidos == -1 && buffer.length() > 0) {
        instruccion = buffer.toString();
        buffer.setLength(0);
      }
    }
    return instruccion;
  }
  public String getUrl() {
    StringBuilder sb = new StringBuilder();
    StringBuilder ori = getOut();
    this.setOut(sb);
    TreeMap<Integer, cn.bran.japid.template.ActionRunner> parentActionRunners = actionRunners;
    actionRunners = new TreeMap<Integer, cn.bran.japid.template.ActionRunner>();
    // line 48, japidviews\AdminController\flashPurchaseList.html
    p("            	"); // line 48, japidviews\AdminController\flashPurchaseList.html
    p(
        lookup(
            "AdminController.flashPurchaseList",
            new Object[] {})); // line 49, japidviews\AdminController\flashPurchaseList.html
    p("            "); // line 49, japidviews\AdminController\flashPurchaseList.html

    this.setOut(ori);
    if (actionRunners.size() > 0) {
      StringBuilder _sb2 = new StringBuilder();
      int segStart = 0;
      for (Map.Entry<Integer, cn.bran.japid.template.ActionRunner> _arEntry :
          actionRunners.entrySet()) {
        int pos = _arEntry.getKey();
        _sb2.append(sb.substring(segStart, pos));
        segStart = pos;
        cn.bran.japid.template.ActionRunner _a_ = _arEntry.getValue();
        _sb2.append(_a_.run().getContent().toString());
      }
      _sb2.append(sb.substring(segStart));
      actionRunners = parentActionRunners;
      return _sb2.toString();
    } else {
      actionRunners = parentActionRunners;
      return sb.toString();
    }
  }
  public Map<String, String> getDiscoveryMap() {
    NetBenchClient nbc = new NetBenchClient();
    Map<String, String> dhm = null;
    try {
      Map<String, ArrayList<String>> tmphm = new HashMap<String, ArrayList<String>>();
      dhm = new HashMap<String, String>();
      List<MsgEvent> dlist = discover();
      for (MsgEvent me : dlist) {
        String agentpath = me.getMsgRegion() + "_" + me.getMsgAgent();
        String ippath = me.getParam("clientip") + "_" + me.getParam("serverip");
        // Benchmark connection here.. will have to do self-terminating code at some point
        String netBenchResult =
            nbc.benchmarkThroughput(me.getParam("serverip"), "benchmark-throughput", 3, 1);
        if (netBenchResult != null) {
          ippath = ippath + "_" + netBenchResult;
        }

        //
        if (!tmphm.containsKey(agentpath)) {
          ArrayList<String> newList = new ArrayList<String>();
          newList.add(ippath);
          tmphm.put(agentpath, newList);
        } else {
          ArrayList<String> newList = tmphm.get(agentpath);
          if (!newList.contains(ippath)) {
            newList.add(ippath);
            tmphm.put(agentpath, newList);
          }
        }
      }

      if (!tmphm.isEmpty()) {
        StringBuilder keylist = new StringBuilder();
        for (Entry<String, ArrayList<String>> entry : tmphm.entrySet()) {
          String agentpath = entry.getKey();
          keylist.append(agentpath + ",");
          ArrayList<String> ipList = entry.getValue();
          // System.out.println(agentpath);
          StringBuilder sb = new StringBuilder();

          for (String ip : ipList) {
            // System.out.println(ip);
            sb.append(ip + ",");
          }
          String ips = sb.substring(0, sb.length() - 1);
          dhm.put(agentpath, ips);
          // do what you have to do here
          // In your case, an other loop.
        }

        String keyfound = keylist.substring(0, keylist.length() - 1);
        dhm.put("discoveredagents", keyfound);
      }

    } catch (Exception ex) {
      System.out.println("DiscoveryClient : getDiscovery : " + ex.toString());
    }

    return dhm;
  }
 // random test
 public static void main(String[] args) {
   Random rnd = new Random(1);
   for (int step = 0; step < 100000; step++) {
     int n = rnd.nextInt(100);
     StringBuilder s = new StringBuilder();
     for (int i = 0; i < n; i++) s.append((char) ('\0' + rnd.nextInt(10)));
     Integer[] sa = suffixArray(s);
     for (int i = 0; i + 1 < n; i++)
       if (s.substring(sa[i]).compareTo(s.substring(sa[i + 1])) >= 0) throw new RuntimeException();
   }
   System.out.println("Test passed");
 }
 private static String generateToken() {
   final StringBuilder builder = new StringBuilder(260);
   while (builder.length() < 256) {
     builder.append(Long.toHexString(TOKEN_GENERATOR.nextLong()));
   }
   return builder.substring(0, 256);
 }
  public String getPositionAndAffiliationString(int limit, int additionalLength, String tail) {
    if (null == tail) {
      tail = "...";
    }
    StringBuilder sb = new StringBuilder();
    if (!Strings.isEmpty(this.get_sPosition())) {
      sb.append(this.get_sPosition());
    }
    if (!Strings.isEmpty(this.get_sPosition()) && !Strings.isEmpty(this.get_sAffiliation())) {
      sb.append(", ");
    }
    if (!Strings.isEmpty(this.get_sAffiliation())) {
      sb.append(this.get_sAffiliation());
    }
    int max = limit - additionalLength;

    // capitalize
    if (sb.length() > 0) {
      sb.replace(0, 1, new Character(sb.charAt(0)).toString().toUpperCase());
    }

    String result = null;
    if (sb.length() > max) {
      result = sb.substring(0, max) + tail;
    } else {
      result = sb.toString();
    }
    return result;
  }
Beispiel #14
1
 @Override
 public String getHeaderField(final String field) {
   final List<String> values = headers.get(field);
   final StringBuilder sb = new StringBuilder();
   for (final String v : values) sb.append(v).append(';');
   return sb.substring(0, sb.length() - 1);
 }
Beispiel #15
1
 private String getTag(Document d) {
   StringBuilder ab =
       new StringBuilder(
           d.getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0].replace(
               "E:\\I:\\ACM_complete_dataset\\", ""));
   return ab.substring(0, ab.indexOf("\\")).toString();
 }
Beispiel #16
0
  private StringBuilder getNextPerm(StringBuilder s) {
    int n = s.length();

    // find the highest index i such that s[i] < s[i+1]
    int i = n;
    for (int t = 0; t < n - 1; t++) {
      if (s.charAt(t) < s.charAt(t + 1)) i = t;
    }

    // no such i, return null;
    if (i == n) return null;

    // find highest index j such that s[i] < s[j]. j exists as at least it's i+1
    int j = 0;
    for (int t = i + 1; t < n; t++) {
      if (s.charAt(i) < s.charAt(t)) j = t;
    }

    // swap s[i], s[j]
    char tmp = s.charAt(i);
    s.setCharAt(i, s.charAt(j));
    s.setCharAt(j, tmp);

    // now reverse char from i+1
    StringBuilder res =
        new StringBuilder(s.substring(0, i + 1))
            .append(new StringBuilder(s.substring(i + 1)).reverse());
    return res;
  }
  private String buildGuidingsInformation(final Collection<PhdParticipant> guidings) {
    final StringBuilder result = new StringBuilder();
    List<PhdParticipant> guidingsList = new ArrayList<>(guidings);
    for (int i = 0; i < guidingsList.size(); i++) {
      final PhdParticipant guiding = guidingsList.get(i);
      result.append(guiding.getNameWithTitle());
      if (i == guidings.size() - 2) {
        result.append(" ").append(getMessageFromResource("label.and")).append(" ");
      } else {
        result.append(", ");
      }
    }

    if (result.length() > 0) {
      if (result.toString().endsWith(getMessageFromResource("label.and"))) {
        return result.substring(0, result.length() - getMessageFromResource("label.and").length());
      }

      if (result.toString().endsWith(", ")) {
        return result.substring(0, result.length() - 2);
      }
    }

    return result.toString();
  }
Beispiel #18
0
  protected void printColumns(HardcopyWriter w, String columnStrings[], int columnSize) {
    // create a base string the width of the column
    StringBuilder spaces = new StringBuilder(""); // NOI18N
    for (int i = 0; i < columnSize; i++) {
      spaces.append(" "); // NOI18N
    }
    // loop through each column
    boolean complete = false;
    while (!complete) {
      StringBuilder lineString = new StringBuilder(""); // NOI18N
      complete = true;
      for (int i = 0; i < columnStrings.length; i++) {
        String columnString = ""; // NOI18N
        // if the column string is too wide cut it at word boundary (valid delimiters are space, -
        // and _)
        // use the intial part of the text,pad it with spaces and place the remainder back in the
        // array
        // for further processing on next line
        // if column string isn't too wide, pad it to column width with spaces if needed
        if (columnStrings[i].length() > columnSize) {
          boolean noWord = true;
          for (int k = columnSize; k >= 1; k--) {
            if (columnStrings[i].substring(k - 1, k).equals(" ")
                || columnStrings[i].substring(k - 1, k).equals("-")
                || columnStrings[i].substring(k - 1, k).equals("_")) {
              columnString =
                  columnStrings[i].substring(0, k)
                      + spaces.substring(columnStrings[i].substring(0, k).length());
              columnStrings[i] = columnStrings[i].substring(k);
              noWord = false;
              complete = false;
              break;
            }
          }
          if (noWord) {
            columnString = columnStrings[i].substring(0, columnSize);
            columnStrings[i] = columnStrings[i].substring(columnSize);
            complete = false;
          }

        } else {
          columnString = columnStrings[i] + spaces.substring(columnStrings[i].length());
          columnStrings[i] = "";
        }
        lineString.append(columnString).append(" "); // NOI18N
      }
      try {
        w.write(lineString.toString());
        // write vertical dividing lines
        for (int i = 0; i < w.getCharactersPerLine(); i = i + columnSize + 1) {
          w.write(w.getCurrentLineNumber(), i, w.getCurrentLineNumber() + 1, i);
        }
        w.write("\n"); // NOI18N
      } catch (IOException e) {
        log.warn("error during printing: " + e);
      }
    }
  }
Beispiel #19
0
 /**
  * 转换为JS获取对象值,生成三目运算返回结果
  *
  * @param objectString 对象串 例如:row.user.id 返回:!row?'':!row.user?'':!row.user.id?'':row.user.id
  */
 public static String jsGetVal(String objectString) {
   StringBuilder result = new StringBuilder();
   StringBuilder val = new StringBuilder();
   String[] vals = split(objectString, ".");
   for (int i = 0; i < vals.length; i++) {
     val.append("." + vals[i]);
     result.append("!" + (val.substring(1)) + "?'':");
   }
   result.append(val.substring(1));
   return result.toString();
 }
Beispiel #20
0
  private String[] makeJsonArraysForClient() {
    int il = listTasks.size();
    if (il == 0) {
      if (debug) Log.d(TAG, "size of taskList returned from server is 0");
    } else {
      for (TaskProxy task : listTasks) {
        if (debug) Log.d(TAG, "for adding in json id:" + task.getId());

        // Json string should be made at last afer the conflict resolution.
        long gId = task.getId();
        long localId =
            SyncUtil.mapTheMatrix(
                idMapMatrix,
                idMapMatrix.length,
                gId,
                ID_MAP_MATRIX_GOOGLE_ID,
                ID_MAP_MATRIX_LOCAL_ID); // getLocalIdFromMapMatrix(gId, idMapMatrix);
        String jsonString = task.getJsonStringData();
        if (task.getTag() == 'D' & localId > -1) {
          jsonDeleteBuilder = SyncUtil.addToJson(jsonDeleteBuilder, localId, gId, jsonString);
        } else if (task.getTag() == 'D' & localId == -1) {
          // This note from server has tag 'D' but it not found on the local client.
          // Do nothing.
          continue;
        } else {
          jsonBuilder = SyncUtil.addToJson(jsonBuilder, localId, gId, jsonString);
        }
      } // loop
    }

    String jsonBuilderString = "";
    String jsonDeleteBuilderString = "";

    if (jsonBuilder.length() > 1) {
      jsonBuilderString = jsonBuilder.substring(0, jsonBuilder.length() - 1);
    }
    String jsonDataRet = "{ \"data\" : [" + jsonBuilderString + "] }";

    if (jsonDeleteBuilder.length() > 1) {
      jsonDeleteBuilderString = jsonDeleteBuilder.substring(0, jsonDeleteBuilder.length() - 1);
    }
    String jsonDeleteDataRet = "{ \"data\" : [" + jsonDeleteBuilderString + "] }";

    if (debug) Log.d(TAG, jsonDataRet);
    if (debug) Log.d(TAG, jsonDeleteDataRet);

    Ulg.d("vincent", "the data to be returned is");
    Ulg.d("vincent", "jsondata is:-> " + jsonDataRet);
    Ulg.d("vincent", "delete for the client is:-> " + jsonDeleteDataRet);
    return new String[] {jsonDataRet, jsonDeleteDataRet};
  }
  protected String buildInsertSQL1(T t) {
    StringBuilder sb = new StringBuilder("insert into ");
    StringBuilder srowName = new StringBuilder();
    StringBuilder srowVal = new StringBuilder();
    String clzName = getEntityClass().getName();
    clzName = getEntityClass().getName().substring(clzName.lastIndexOf(".") + 1, clzName.length());
    sb.append(clzName);
    sb.append(" ( ");
    Field f[] = getEntityClass().getDeclaredFields();
    for (int i = 0; i < f.length; i++) {
      //            System.out.println( f[i].getName() );
      try {
        String rowName = f[i].getName();

        //                String rowVal = (String) f[i].get(user);
        if (!"id".equalsIgnoreCase(rowName)) {

          // 参数1为person类中属性的名(首字母大写),参数2为person类转化的Class
          String methodName =
              rowName.substring(0, 1).toUpperCase() + rowName.substring(1, rowName.length());
          PropertyDescriptor pd = new PropertyDescriptor(methodName, getEntityClass());
          // 获取PropertyDescriptor 类的写入方法
          Method m = pd.getReadMethod();
          // 因为是读取属性中的方法,所以不需要传值进去
          //                    Object o = new Object();
          Object obj = m.invoke(t, null);
          String rowVal = (String) obj;
          rowVal = rowVal == null ? "" : rowVal;
          srowName.append(" [" + rowName + "], ");
          srowVal.append("'" + rowVal + "', ");
        }

      } catch (IllegalAccessException ex) {
        Logger.getLogger(BaseService.class.getName()).log(Level.SEVERE, null, ex);
      } catch (InvocationTargetException ex) {
        Logger.getLogger(BaseService.class.getName()).log(Level.SEVERE, null, ex);
      } catch (IllegalArgumentException ex) {
        Logger.getLogger(UserService.class.getName()).log(Level.SEVERE, null, ex);
      } catch (IntrospectionException ex) {
        Logger.getLogger(UserService.class.getName()).log(Level.SEVERE, null, ex);
      }
    }

    sb.append(srowName.substring(0, srowName.lastIndexOf(",")));
    sb.append(" ) values ( ");
    sb.append(srowVal.substring(0, srowVal.lastIndexOf(",")));
    sb.append(" ) ");

    return sb.toString();
  }
 public String genLocateRootParentSQL() {
   TableConfig tb = this;
   StringBuilder tableSb = new StringBuilder();
   StringBuilder condition = new StringBuilder();
   TableConfig prevTC = null;
   int level = 0;
   String latestCond = null;
   while (tb.parentTC != null) {
     tableSb.append(tb.parentTC.name).append(',');
     String relation = null;
     if (level == 0) {
       latestCond = " " + tb.parentTC.getName() + '.' + tb.parentKey + "=";
     } else {
       relation = tb.parentTC.getName() + '.' + tb.parentKey + '=' + tb.name + '.' + tb.joinKey;
       condition.append(relation).append(" AND ");
     }
     level++;
     prevTC = tb;
     tb = tb.parentTC;
   }
   String sql =
       "SELECT "
           + prevTC.parentTC.name
           + '.'
           + prevTC.parentKey
           + " FROM "
           + tableSb.substring(0, tableSb.length() - 1)
           + " WHERE "
           + ((level < 2) ? latestCond : condition.toString() + latestCond);
   return sql;
 }
  @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");
      }
    }
  }
Beispiel #24
0
  private String createToken(String subject, List<String> roles) throws JOSEException {
    StringBuilder res = new StringBuilder();
    for (String string : roles) {
      res.append(string);
      res.append(",");
    }
    String rolesAsString = res.length() > 0 ? res.substring(0, res.length() - 1) : "";

    String issuer = "semester3demo-cphbusiness.dk-computerScience";
    JWSSigner signer = new MACSigner(Secrets.ADMIN.getBytes());

    JWTClaimsSet claimsSet = new JWTClaimsSet();
    claimsSet.setSubject(subject);
    claimsSet.setClaim("username", subject);
    claimsSet.setCustomClaim("roles", rolesAsString);
    Date date = new Date();
    claimsSet.setIssueTime(date);
    claimsSet.setExpirationTime(new Date(date.getTime() + 1000 * 60 * 60));
    claimsSet.setIssuer(issuer);

    SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet);
    signedJWT.sign(signer);

    return signedJWT.serialize();
  }
 public static StringBuilder firstToLowerCase(StringBuilder builder) {
   String lower = builder.substring(0, 1).toLowerCase();
   builder.replace(0, 1, lower);
   // String post = string.substring(1, string.length());
   // String first = ("" + string.charAt(0)).toLowerCase();
   return builder;
 }
Beispiel #26
0
  /**
   * We're about to push the info to the log, so do final adjustments on the logEntry object,
   * setting up data.
   *
   * @param logEntry LogEntry that holds the info to be logged
   * @param factory ResourceFactory the source for the DB connection
   */
  private static void prepLogEntry(LogEntry logEntry, ResourceFactory factory) {
    if (null == logEntry.serviceName) {
      logEntry.serviceName = factory.getSystemName();
    }

    StringBuilder desc = new StringBuilder(MAX_LOG_DESC);
    if (logEntry.clazz != null) {
      String className = logEntry.clazz.getName();
      int idx = className.lastIndexOf('.');

      desc.append(idx == -1 ? className : className.substring(idx + 1));
      desc.append(".");
      desc.append(logEntry.method);
    }

    if (!Str.isEmpty(logEntry.desc)) {
      desc.append(" ");
      desc.append(logEntry.desc);
    }

    if (logEntry.throwable != null) {
      desc.append(" Exception: ");
      if (logEntry.level.ordinal() >= factory.getStackTraceLevel().ordinal()) {
        desc.append(System.getProperty("line.separator"));
        desc.append(Stack.getShortStack(logEntry.throwable));
      } else {
        desc.append(logEntry.throwable.toString());
      }
    }

    logEntry.desc = desc.substring(0, Math.min(MAX_LOG_DESC, desc.length()));
  }
 public String getExclusions() {
   final StringBuilder buf = new StringBuilder();
   for (final String ex : this.exclusions) {
     buf.append(",'").append(ex).append("'");
   }
   return this.exclusions.size() > 0 ? buf.substring(1) : "";
 }
Beispiel #28
0
 protected void handleCircularRelationship(Object o) throws ConverterException {
   switch (circularReferenceBehaviour) {
     case DEFAULT:
       if (!(Map.class.isAssignableFrom(o.getClass())
           || Collection.class.isAssignableFrom(o.getClass()))) {
         Map<String, Object> props = new HashMap<String, Object>();
         props.put("class", o.getClass());
         StringBuilder ref = new StringBuilder();
         int idx = referenceStack.indexOf(o);
         for (int i = referenceStack.size() - 1; i > idx; i--) {
           ref.append("../");
         }
         props.put("_ref", ref.substring(0, ref.length() - 1));
         value(props);
       }
       break;
     case EXCEPTION:
       throw new ConverterException(
           "Circular Reference detected: class " + o.getClass().getName());
     case INSERT_NULL:
       value(null);
       break;
     case PATH:
       Map<String, Object> props = new HashMap<String, Object>();
       props.put("class", o.getClass());
       int idx = referenceStack.indexOf(o);
       PathCapturingJSONWriterWrapper pcWriter = (PathCapturingJSONWriterWrapper) writer;
       props.put("ref", String.format("root%s", pcWriter.getStackReference(idx)));
       value(props);
       break;
     case IGNORE:
       break;
   }
 }
  public static String getReadableVersion(String version) {
    try {
      String number = version.substring(version.indexOf("-") + 1, version.lastIndexOf("-"));
      String date =
          version.substring(
              version.lastIndexOf("-") + 1,
              version.endsWith(".zip") ? version.lastIndexOf(".") : version.length());

      SimpleDateFormat curFormater = new SimpleDateFormat("yyyyMMdd");
      Date dateObj = null;
      try {
        dateObj = curFormater.parse(date);
      } catch (ParseException e) {
        // ignore
      }
      SimpleDateFormat postFormater = new SimpleDateFormat("MMMM dd, yyyy");

      if (dateObj == null) {
        return number;
      }
      String newDateStr = postFormater.format(dateObj);

      StringBuilder b = new StringBuilder(newDateStr);
      int i = 0;
      do {
        b.replace(i, i + 1, b.substring(i, i + 1).toUpperCase());
        i = b.indexOf(" ", i) + 1;
      } while (i > 0 && i < b.length());
      return number + " - " + b.toString();
    } catch (Exception ex) {
      // unknown version format
      return version;
    }
  }
  public static String getCreateStatement(Class<?> clazz) {
    if (null == clazz) {
      logger.info("arguments clazz null");
      System.exit(0);
    }

    DBTable dbTable = clazz.getAnnotation(DBTable.class);
    if (null == dbTable) {
      logger.info("no DBTable annotation in class {}.", clazz.getName());
      System.exit(0);
    }

    String tableName = getTableName(clazz, dbTable);

    List<String> columnDefinitions = getColumnDefinitions(clazz);

    StringBuilder createStatement = new StringBuilder("CREATE TABLE " + tableName + "(");
    for (String columnDef : columnDefinitions) {
      createStatement.append("\n  ").append(columnDef).append(",");
    }
    String schemaCreateStatement =
        createStatement.substring(0, createStatement.length() - 1) + ");";
    logger.info("Table Creation SQL for {} is:\n\n {}", clazz.getName(), schemaCreateStatement);
    return schemaCreateStatement;
  }