@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";
 }
Example #2
1
  @Override
  public Object bind(
      RootParamNode rootParamNode,
      String name,
      Class clazz,
      java.lang.reflect.Type type,
      Annotation[] annotations) {
    // TODO need to be more generic in order to work with JPASupport
    if (clazz.isAnnotationPresent(Entity.class)) {

      ParamNode paramNode = rootParamNode.getChild(name, true);

      String[] keyNames = new JPAModelLoader(clazz).keyNames();
      ParamNode[] ids = new ParamNode[keyNames.length];
      // Collect the matching ids
      int i = 0;
      for (String keyName : keyNames) {
        ids[i++] = paramNode.getChild(keyName, true);
      }
      if (ids != null && ids.length > 0) {
        try {
          EntityManager em = JPABase.getJPAConfig(clazz).getJPAContext().em();
          StringBuilder q =
              new StringBuilder().append("from ").append(clazz.getName()).append(" o where");
          int keyIdx = 1;
          for (String keyName : keyNames) {
            q.append(" o.").append(keyName).append(" = ?").append(keyIdx++).append(" and ");
          }
          if (q.length() > 4) {
            q = q.delete(q.length() - 4, q.length());
          }
          Query query = em.createQuery(q.toString());
          // The primary key can be a composite.
          Class[] pk = new JPAModelLoader(clazz).keyTypes();
          int j = 0;
          for (ParamNode id : ids) {
            if (id.getValues() == null
                || id.getValues().length == 0
                || id.getFirstValue(null) == null
                || id.getFirstValue(null).trim().length() <= 0) {
              // We have no ids, it is a new entity
              return GenericModel.create(rootParamNode, name, clazz, annotations);
            }
            query.setParameter(
                j + 1,
                Binder.directBind(
                    id.getOriginalKey(), annotations, id.getValues()[0], pk[j++], null));
          }
          Object o = query.getSingleResult();
          return GenericModel.edit(rootParamNode, name, o, annotations);
        } catch (NoResultException e) {
          // ok
        } catch (Exception e) {
          throw new UnexpectedException(e);
        }
      }
      return GenericModel.create(rootParamNode, name, clazz, annotations);
    }
    return null;
  }
Example #3
1
  static Integer helper(int i, StringBuilder sb, String s) {
    if (i == s.length()) {
      return decode(sb.toString());
    }

    if (!Character.isLetter(s.charAt(i))) {
      sb.append(s.charAt(i));
      Integer result = helper(i + 1, sb, s);
      if (result != null) {
        return result;
      }
    } else {
      char ch = s.charAt(i);
      sb.append(Character.toUpperCase(ch));
      Integer result = helper(i + 1, sb, s);
      if (result != null) {
        return result;
      }
      sb.deleteCharAt(sb.length() - 1);

      sb.append(Character.toLowerCase(ch));
      result = helper(i + 1, sb, s);
      if (result != null) {
        return result;
      }
      sb.deleteCharAt(sb.length() - 1);
    }
    return null;
  }
 /**
  * Append a time to the string builder.
  *
  * @param buff the target string builder
  * @param nanos the time in nanoseconds
  * @param alwaysAddMillis whether to always add at least ".0"
  */
 static void appendTime(StringBuilder buff, long nanos, boolean alwaysAddMillis) {
   if (nanos < 0) {
     buff.append('-');
     nanos = -nanos;
   }
   long ms = nanos / 1000000;
   nanos -= ms * 1000000;
   long s = ms / 1000;
   ms -= s * 1000;
   long m = s / 60;
   s -= m * 60;
   long h = m / 60;
   m -= h * 60;
   StringUtils.appendZeroPadded(buff, 2, h);
   buff.append(':');
   StringUtils.appendZeroPadded(buff, 2, m);
   buff.append(':');
   StringUtils.appendZeroPadded(buff, 2, s);
   if (alwaysAddMillis || ms > 0 || nanos > 0) {
     buff.append('.');
     int start = buff.length();
     StringUtils.appendZeroPadded(buff, 3, ms);
     if (nanos > 0) {
       StringUtils.appendZeroPadded(buff, 6, nanos);
     }
     for (int i = buff.length() - 1; i > start; i--) {
       if (buff.charAt(i) != '0') {
         break;
       }
       buff.deleteCharAt(i);
     }
   }
 }
  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;
  }
Example #6
1
  @Override
  public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    StringBuilder selection = new StringBuilder();

    // create temporary copies
    final boolean isFilterFavorites = mIsFilterFavorites;
    final boolean isFilterUnwatched = mIsFilterUnwatched;
    final boolean isFilterUpcoming = mIsFilterUpcoming;
    final boolean isFilterHidden = mIsFilterHidden;

    // restrict to favorites?
    if (isFilterFavorites) {
      selection.append(Shows.FAVORITE).append("=1");
    }

    final long timeInAnHour = System.currentTimeMillis() + DateUtils.HOUR_IN_MILLIS;

    // restrict to shows with a next episode?
    if (isFilterUnwatched) {
      if (selection.length() != 0) {
        selection.append(" AND ");
      }
      selection.append(Shows.NEXTAIRDATEMS).append("!=").append(DBUtils.UNKNOWN_NEXT_AIR_DATE);

      // exclude shows with upcoming next episode
      if (!isFilterUpcoming) {
        selection.append(" AND ").append(Shows.NEXTAIRDATEMS).append("<=").append(timeInAnHour);
      }
    }
    // restrict to shows with an upcoming (yet to air) next episode?
    if (isFilterUpcoming) {
      if (selection.length() != 0) {
        selection.append(" AND ");
      }
      // Display shows upcoming within <limit> days + 1 hour
      int upcomingLimitInDays = AdvancedSettings.getUpcomingLimitInDays(getActivity());
      long latestAirtime = timeInAnHour + upcomingLimitInDays * DateUtils.DAY_IN_MILLIS;

      selection.append(Shows.NEXTAIRDATEMS).append("<=").append(latestAirtime);

      // exclude shows with no upcoming next episode if not filtered for unwatched, too
      if (!isFilterUnwatched) {
        selection.append(" AND ").append(Shows.NEXTAIRDATEMS).append(">=").append(timeInAnHour);
      }
    }

    // special: if hidden filter is disabled, exclude hidden shows
    if (selection.length() != 0) {
      selection.append(" AND ");
    }
    selection.append(Shows.HIDDEN).append(isFilterHidden ? "=1" : "=0");

    return new CursorLoader(
        getActivity(),
        Shows.CONTENT_URI,
        ShowsQuery.PROJECTION,
        selection.toString(),
        null,
        ShowsDistillationSettings.getSortQuery(mSortOrderId, mIsSortFavoritesFirst));
  }
Example #7
1
  /**
   * Break on commas, except those inside quotes, e.g.: size(300, 200, PDF, "output,weirdname.pdf");
   * No special handling implemented for escaped (\") quotes.
   */
  private static StringList breakCommas(String contents) {
    StringList outgoing = new StringList();

    boolean insideQuote = false;
    // The current word being read
    StringBuilder current = new StringBuilder();
    char[] chars = contents.toCharArray();
    for (int i = 0; i < chars.length; i++) {
      char c = chars[i];
      if (insideQuote) {
        current.append(c);
        if (c == '\"') {
          insideQuote = false;
        }
      } else {
        if (c == ',') {
          if (current.length() != 0) {
            outgoing.append(current.toString());
            current.setLength(0);
          }
        } else {
          current.append(c);
          if (c == '\"') {
            insideQuote = true;
          }
        }
      }
    }
    if (current.length() != 0) {
      outgoing.append(current.toString());
    }
    return outgoing;
  }
Example #8
1
  public static String prepareFilters(final SearchRequest req) {
    final StringBuilder builder = new StringBuilder(Query.FETCH_IMAGES.toString());

    // Add date filters
    builder.append(" where startedAt >= ? and endedAt <= ? ");

    if (req.getUserList() != null && req.getUserList().size() > 0) {
      // Add user name filters
      builder.append(" and userid in (");
      int count = req.getUserList().size();
      while (count-- > 0) builder.append("?,");
      builder.setLength(builder.length() - 1);
      builder.append(") ");
    }

    // Add location filters
    if (req.getLocationList() != null && req.getLocationList().size() > 0) {
      builder.append(" and location in (");
      int count = req.getLocationList().size();
      while (count-- > 0) builder.append("?,");
      builder.setLength(builder.length() - 1);
      builder.append(") ");
    }

    builder.append(" order by userid,startedAt;");

    return builder.toString();
  }
Example #9
0
 /** Converts a Record into a String representation */
 public String toString() {
   StringBuilder sb = new StringBuilder();
   sb.append(name);
   if (sb.length() < 8) {
     sb.append("\t");
   }
   if (sb.length() < 16) {
     sb.append("\t");
   }
   sb.append("\t");
   if (Options.check("BINDTTL")) {
     sb.append(TTL.format(ttl));
   } else {
     sb.append(ttl);
   }
   sb.append("\t");
   if (dclass != DClass.IN || !Options.check("noPrintIN")) {
     sb.append(dclass.getName());
     sb.append("\t");
   }
   sb.append(Type.string(type));
   String rdata = rrToString();
   if (!rdata.equals("")) {
     sb.append("\t");
     sb.append(rdata);
   }
   return sb.toString();
 }
  /**
   * Checks that the destination cluster has all the networks that the given NICs require.<br>
   * No network on a NIC is allowed (it's checked when running VM).
   *
   * @param interfaces The NICs to check networks on.
   * @return Whether the destination cluster has all networks configured or not.
   */
  private boolean validateDestinationClusterContainsNetworks(List<VmNic> interfaces) {
    List<Network> networks =
        DbFacade.getInstance().getNetworkDao().getAllForCluster(targetClusterId);
    StringBuilder missingNets = new StringBuilder();
    for (VmNic iface : interfaces) {
      Network network = NetworkHelper.getNetworkByVnicProfileId(iface.getVnicProfileId());
      if (network != null) {
        boolean exists = false;
        for (Network net : networks) {
          if (net.getName().equals(network.getName())) {
            exists = true;
            break;
          }
        }
        if (!exists) {
          if (missingNets.length() > 0) {
            missingNets.append(", ");
          }
          missingNets.append(network.getName());
        }
      }
    }
    if (missingNets.length() > 0) {
      parentCommand.addCanDoActionMessage(EngineMessage.MOVE_VM_CLUSTER_MISSING_NETWORK);
      parentCommand.addCanDoActionMessageVariable("networks", missingNets.toString());
      return false;
    }

    return true;
  }
  @Override
  public void pushToDB(Connection con) {
    Statement stmt;

    try {
      stmt = con.createStatement();
      StringBuilder sqlString = new StringBuilder("INSERT INTO question_response VALUES(null,");
      sqlString.append(statement);
      sqlString.append("\",\" ");
      for (String string : answers) {
        sqlString.append(string);
        sqlString.append(" &&& ");
      }
      sqlString.replace(sqlString.length() - 5, sqlString.length(), "");
      sqlString.append("\" ");

      System.out.print(sqlString.toString());
      ResultSet resultSet = stmt.executeQuery(sqlString.toString());

      stmt = con.createStatement();
      sqlString = new StringBuilder("SELECT * FROM question_response WHERE statement=\"");
      sqlString.append(statement);
      sqlString.append("\" ");

      System.out.print(sqlString.toString());
      resultSet = stmt.executeQuery(sqlString.toString());

      while (resultSet.next()) {
        this.setqID(resultSet.getInt("question_id")); // will always be the last one
      }
    } catch (Exception e) {

    }
  }
Example #12
0
  /**
   * This method converts the message digest into a string.
   *
   * @param hex true if the output hash is to be a hexadecimal, otherwise dotted decimal String.
   * @return a security hashed String
   */
  private String convertMD5(boolean hex) {
    StringBuilder result = new StringBuilder();
    byte[] output = md.digest();

    if (hex) {
      // convert to hex
      for (int i = 0; i < output.length; i++) {
        String s = Integer.toHexString((int) output[i] & 0xFF);
        if (s.length() == 1) {
          s = "0" + s;
        }
        result.append(s);
      }
    } else {
      // convert to dotted decimal
      for (int i = 0; i < output.length; i++) {
        String num = "" + ((int) output[i] & 0xFF);
        if (num.length() == 1) {
          num = "00" + num;
        } else if (num.length() == 2) {
          num = "0" + num;
        }
        result.append(num).append(".");
      }
      // remove the final decimal point
      result = result.delete(result.length() - 1, result.length());
    }
    return result.toString().trim();
  }
  @SuppressWarnings("rawtypes")
  public List<String> evaluateArray(String jsonString, String pathString)
      throws JsonParseException, JsonMappingException, IOException {
    List<String> list = new ArrayList<String>();
    if (jsonString == null || jsonString == "" || pathString == null || pathString == "") {
      return null;
    }

    List result = MAPPER.readValue(jsonString, new TypeReference<List>() {});
    String[] arr = pathString.split(",", -1);
    for (Object o : result) {
      if (o instanceof LinkedHashMap) {
        LinkedHashMap m = (LinkedHashMap) o;
        if (arr.length == 1) list.add(m.get(pathString).toString());
        else if (arr.length > 1) {
          StringBuilder sb = new StringBuilder();
          for (String path : arr) {
            sb.append(m.get(path).toString() + ",");
          }
          if (sb.length() > 0) sb.setLength(sb.length() - 1);
          list.add(sb.toString());
        }
      } else if (o instanceof String) {
        String str = (String) o;
        str = str.replaceAll(Const.ROWKEY_DEFAULT_SEPARATOR, ",");
        list.add(str);
      }
    }
    return list;
  }
  public void setNonStandardProperty(String propertyMapping) {
    char[] chars = propertyMapping.toCharArray();
    StringBuilder key = new StringBuilder();
    StringBuilder value = new StringBuilder();

    boolean keyProcessed = false;
    for (char ch : chars) {
      boolean isSeparator = Character.isWhitespace(ch) || ch == '=' || ch == ':';

      // if no key was processed, ignore white spaces
      if (key.length() == 0 && isSeparator) continue;

      if (!keyProcessed && !isSeparator) {
        key.append(ch);
      } else if (!keyProcessed) {
        keyProcessed = true;
      } else if (value.length() != 0 || !isSeparator) {
        value.append(ch);
      }
    }

    String keyStr = key.toString().trim();
    String valueStr = value.length() > 0 ? value.toString().trim() : null;

    setNonStandardProperty(keyStr, valueStr);
  }
  protected String buildSQL() {
    if (columnsMap.isEmpty() || table == null || "".equals(table)) {
      return null;
    }
    StringBuilder valBuf = new StringBuilder();
    StringBuilder buf = new StringBuilder(64);
    buf.append("insert into ");
    buf.append(table);
    buf.append(" (");

    valBuf.append(" values(");
    for (Entry<String, String> entry : columnsMap.entrySet()) {
      String key = entry.getKey();
      String value = entry.getValue();
      if (key == null || "".equals(key)) {
        return null;
      }
      buf.append(key);
      buf.append(',');
      valBuf.append("?,");
      ConvertPattern cp = new DefaultPattern();
      if (!cp.setPattern(value)) {
        return null;
      }
      convertors.add(cp);
    }
    buf.setLength(buf.length() - 1);
    valBuf.setLength(valBuf.length() - 1);
    buf.append(')');
    valBuf.append(')');
    buf.append(valBuf);
    return buf.toString();
  }
Example #16
0
  public static FunctionDecl getFunctionDecl(Function function) throws AsterixException {
    String functionBody = function.getFunctionBody();
    List<String> params = function.getParams();
    List<VarIdentifier> varIdentifiers = new ArrayList<VarIdentifier>();

    StringBuilder builder = new StringBuilder();
    builder.append(" use dataverse " + function.getDataverseName() + ";");
    builder.append(" declare function " + function.getName().split("@")[0]);
    builder.append("(");
    for (String param : params) {
      VarIdentifier varId = new VarIdentifier(param);
      varIdentifiers.add(varId);
      builder.append(param);
      builder.append(",");
    }
    if (params.size() > 0) {
      builder.delete(builder.length() - 1, builder.length());
    }
    builder.append(")");
    builder.append("{");
    builder.append("\n");
    builder.append(functionBody);
    builder.append("\n");
    builder.append("}");

    AQLParser parser = new AQLParser(new StringReader(new String(builder)));

    List<Statement> statements = parser.parse();
    FunctionDecl decl = (FunctionDecl) statements.get(1);
    return decl;
  }
Example #17
0
  public static String createPath(
      ConfigurationSection section, String key, ConfigurationSection relativeTo) {
    Configuration root = section.getRoot();
    if (root == null) {
      throw new IllegalStateException("Cannot create path without a root");
    }
    char separator = root.options().pathSeparator();

    StringBuilder builder = new StringBuilder();
    if (section != null) {
      for (ConfigurationSection parent = section;
          (parent != null) && (parent != relativeTo);
          parent = parent.getParent()) {
        if (builder.length() > 0) {
          builder.insert(0, separator);
        }

        builder.insert(0, parent.getName());
      }
    }

    if ((key != null) && (key.length() > 0)) {
      if (builder.length() > 0) {
        builder.append(separator);
      }

      builder.append(key);
    }

    return builder.toString();
  }
 /**
  * takes an individual line and cleans it by removing comments and extra whitespace
  *
  * @param line
  * @return cleaned line with comments removed and extra whitespace removed
  *     <p>NOTE: can handle spaces, can't currently handle tab characters
  */
 public static String cleanLine(String line) {
   line = line.replaceAll("\\s+", " ");
   line = line.replaceAll(" =", "=");
   line = line.replaceAll("= ", "=");
   StringBuilder str = new StringBuilder();
   boolean lastCharSpace = true;
   for (int i = 0; i < line.length(); i++) {
     // exit the loop if we're at a comment
     if (line.charAt(i) == '#') {
       break;
     } else if (line.charAt(i) == ' ' && !lastCharSpace) {
       lastCharSpace = true;
       str.append(line.charAt(i));
     } else if (line.charAt(i) == ' ') {
       lastCharSpace = true;
     } else if (!lastCharSpace) {
       str.append(line.charAt(i));
     } else {
       lastCharSpace = false;
       str.append(line.charAt(i));
     }
   }
   // now we're going to loop through again and just delete all the
   // extra spaces that might exist at the end of the string
   for (int i = str.length() - 1; i >= 0; --i) {
     if (str.charAt(str.length() - 1) == ' ') {
       str.deleteCharAt(str.length() - 1);
     } else {
       break;
     }
   }
   return str.toString();
 }
 private static void assertEqualsInternal(
     String msg, StringBuilder expected, CharBlockArray actual) {
   assertEquals(msg, expected.length(), actual.length());
   for (int i = 0; i < expected.length(); i++) {
     assertEquals(msg, expected.charAt(i), actual.charAt(i));
   }
 }
Example #20
0
  private void logFailedStorageConnections(Map<String, String> returnValue) {
    StringBuilder failedDomainNames = new StringBuilder();
    String namesSeparator = ",";
    for (Entry<String, String> result : returnValue.entrySet()) {
      if (!"0".equals(result.getValue())) {
        List<StorageDomain> domains =
            DbFacade.getInstance()
                .getStorageDomainDao()
                .getAllByConnectionId(new Guid(result.getKey()));
        if (!domains.isEmpty()) {
          for (StorageDomain domain : domains) {
            if (failedDomainNames.length() > 0) {
              failedDomainNames.append(namesSeparator);
            }
            failedDomainNames.append(domain.getStorageName());
          }
        }
      }
    }

    if (failedDomainNames.length() > 0) {
      AuditLogableBase logable = new AuditLogableBase(getParameters().getVdsId());
      logable.addCustomValue("failedStorageDomains", failedDomainNames.toString());
      auditLogDirector.log(logable, AuditLogType.VDS_STORAGES_CONNECTION_FAILED);
    }
  }
  public static String getAuthenticatorIdPMappingString(List<AuthenticatorConfig> authConfigList) {

    StringBuilder authenticatorIdPStr = new StringBuilder("");

    for (AuthenticatorConfig authConfig : authConfigList) {
      StringBuilder idpsOfAuthenticatorStr = new StringBuilder("");

      for (String idpName : authConfig.getIdpNames()) {

        if (idpName != null) {

          if (idpsOfAuthenticatorStr.length() != 0) {
            idpsOfAuthenticatorStr.append(":");
          }

          IdentityProvider idp = authConfig.getIdps().get(idpName);

          if (idp.isFederationHub()) {
            idpName += ".hub";
          }

          idpsOfAuthenticatorStr.append(idpName);
        }
      }

      if (authenticatorIdPStr.length() != 0) {
        authenticatorIdPStr.append(";");
      }

      authenticatorIdPStr.append(authConfig.getName()).append(":").append(idpsOfAuthenticatorStr);
    }

    return authenticatorIdPStr.toString();
  }
 @Override
 public String print(MoreTypesDemo moreTypesDemo, Locale locale) {
   if (moreTypesDemo == null) {
     return "";
   }
   StringBuilder ret = new StringBuilder(256);
   if (moreTypesDemo.getNumberInt() != null) {
     if (ret.length() != 0) {
       ret.append('/');
     }
     ret.append(moreTypesDemo.getNumberInt());
   }
   if (moreTypesDemo.getNumberLong() != null) {
     if (ret.length() != 0) {
       ret.append('/');
     }
     ret.append(moreTypesDemo.getNumberLong());
   }
   if (moreTypesDemo.getNumberDouble() != null) {
     if (ret.length() != 0) {
       ret.append('/');
     }
     ret.append(moreTypesDemo.getNumberDouble());
   }
   return ret.toString();
 }
Example #23
0
 public static String encodeParameters(
     List<NameValuePair> postParams, String splitter, boolean quot, boolean sort) {
   if (sort)
     Collections.sort(
         postParams,
         new Comparator<NameValuePair>() {
           @Override
           public int compare(NameValuePair o1, NameValuePair o2) {
             return o1.getName().compareTo(o2.getName());
           }
         });
   StringBuilder buf = new StringBuilder();
   for (NameValuePair pair : postParams) {
     if (buf.length() != 0) {
       if (quot) {
         buf.append("\"");
       }
       buf.append(splitter);
     }
     buf.append(encode(pair.getName())).append("=");
     if (quot) {
       buf.append("\"");
     }
     buf.append(encode(pair.getValue()));
   }
   if (buf.length() != 0) {
     if (quot) {
       buf.append("\"");
     }
   }
   return buf.toString();
 }
Example #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();
  }
Example #25
0
  public List<String> getDependencies() {
    List<Dependency> deps = pom.getDependencies();
    if (deps == null) return null;

    final List<String> dependencies = new ArrayList<String>();
    for (Dependency dep : deps) {
      if (!dep.isOptional()) {
        String coords =
            dep.getGroupId()
                + ":"
                + dep.getArtifactId()
                + ":"
                + dep.getVersion()
                + (dep.getClassifier() != null && !dep.getClassifier().isEmpty()
                    ? ":" + dep.getClassifier()
                    : "");
        List<Exclusion> exclusions = dep.getExclusions();
        if (exclusions != null && !exclusions.isEmpty()) {
          StringBuilder sb = new StringBuilder();
          sb.append('(');
          for (Exclusion ex : exclusions)
            sb.append(ex.getGroupId()).append(':').append(ex.getArtifactId()).append(',');
          sb.delete(sb.length() - 1, sb.length());
          sb.append(')');
          coords += sb.toString();
        }
        dependencies.add(coords);
      }
    }
    return dependencies;
  }
 @Override
 public void commitTyped() {
   if (typedText.length() > 0) {
     commitText(typedText, typedText.length());
     clearTypedText();
   }
 }
Example #27
0
  private String readString() throws IOException {
    StringBuilder line = new StringBuilder();

    // synchronized (processOut) {
    while (true) {
      String subline = processOut.readLine();
      if (subline == null) {
        StringBuilder errorMessage = new StringBuilder();
        errorMessage.append("Pipe to subprocess seems to be broken!");
        if (line.length() == 0) {
          errorMessage.append(" No output read.\n");
        } else {
          errorMessage.append(" Currently read output: " + line.toString() + "\n");
        }
        errorMessage.append("Shell Process Exception:\n");
        errorMessage.append(getErrorsString() + "\n");
        throw new RuntimeException(errorMessage.toString());
      }
      if (subline.equals("end")) {
        break;
      }
      if (line.length() != 0) {
        line.append("\n");
      }
      line.append(subline);
    }
    // }

    return line.toString();
  }
Example #28
0
  /**
   * Formats a URI by adding a forward slash and removing the last forward slash from the URI.
   *
   * <p>e.g. some/random/uri/ -> /some/random/uri e.g. some/random/uri -> /some/random/uri e.g.
   * /some/random/uri/ -> /some/random/uri e.g. / -> / e.g. ////// -> /
   *
   * @param uri
   * @return
   */
  public static String formatUri(String uri) {
    if (StringUtilities.nullSafeStartsWith(uri, "\\")) {
      // windows file system
      return uri;
    }

    if (StringUtilities.isBlank(uri) || StringUtilities.nullSafeEqualsIgnoreCase("/", uri)) {
      return "/";
    }

    final StringBuilder externalName = new StringBuilder(uri);

    if (externalName.charAt(0) != '/') {
      externalName.insert(0, "/");
    }

    int doubleSlash = externalName.indexOf("//");

    while (doubleSlash > -1) {
      // removes leading '/'
      externalName.replace(doubleSlash, doubleSlash + 2, "/");
      doubleSlash = externalName.indexOf("//");
    }

    if (externalName.charAt(externalName.length() - 1) == '/' && externalName.length() != 1) {
      externalName.deleteCharAt(externalName.length() - 1);
    }

    return externalName.toString();
  }
 public String Reduce(String w) {
   int done = 0;
   StringBuilder sb = new StringBuilder(w);
   // System.out.println("Checking "+w);
   while (done == 0) {
     done = 1;
     int i = 0;
     while (i < sb.length()) {
       //	System.out.println("*"+sb.length());
       //	System.out.println(i);
       if (sb.charAt(i) == this.barL.get(sb.charAt((i + 1) % (sb.length())))) {
         if (i == 0) {
           sb.delete(0, 2);
           done = 0;
           i = 0;
         } else if (i < sb.length() - 1) {
           sb.delete(i, i + 2);
           done = 0;
           i = 0;
         } else if (i == sb.length() - 1) {
           sb.deleteCharAt(i);
           sb.deleteCharAt(0);
           done = 0;
           i = 0;
         }
       } else i++;
     }
   }
   return sb.toString();
 }
Example #30
0
    protected Paragraph(String string) {
      super(string, "\r\n\t ");
      int count = super.countTokens();
      if (0 == count) {
        this.count = 0;
        this.list = null;
      } else if (1 == count) {
        this.count = 1;
        this.list = new String[] {super.nextToken()};
      } else {
        String[] list = null;
        StringBuilder strbuf = new StringBuilder();
        for (int cc = 0; cc < count; cc++) {
          if (0 != strbuf.length()) strbuf.append(' ');

          if (strbuf.length() < 50) strbuf.append(super.nextToken());
          else {
            list = Add(list, strbuf.toString());
            strbuf.setLength(0);
            strbuf.append(super.nextToken());
          }
        }
        if (0 != strbuf.length()) list = Add(list, strbuf.toString());

        this.list = list;
        this.count = ((null != list) ? (list.length) : (0));
      }
    }