/**
   * Create a target URL from given parameters, adding the template name.
   *
   * @param space space name to use, "Main" is used if null
   * @param page page name to use, "WebHome" is used if null
   * @param parameter parameter name to add, omitted if null or empty string
   * @param value parameter value, empty string is used if null
   * @return the resulting absolute URL
   * @see #createUrl(String, String, String, java.util.Map)
   */
  protected String createUrl(String space, String page, String parameter, String value) {
    String skin = "default";
    if (this.name.startsWith("skins")) {
      skin = this.name.replaceFirst("^\\w+/", "").replaceAll("/.+$", "");
    }

    final String TEMPLATES_DIR = "templates" + File.separator;
    final String SKINS_DIR = "skins" + File.separator;
    String template;
    if (this.name.startsWith(TEMPLATES_DIR)) {
      template = StringUtils.removeStart(this.name, TEMPLATES_DIR);
    } else if (this.name.startsWith(SKINS_DIR)) {
      template = StringUtils.removeStart(this.name, SKINS_DIR + skin + File.separator);
    } else {
      template = this.name.replaceAll("^(.+)/", "");
    }

    HashMap<String, String> parameters = new HashMap<String, String>();
    parameters.put("skin", skin);
    if ("xpart".equals(parameter)) {
      // xpart=something must be tested differently
      parameters.put("xpage", template).replaceAll("\\.\\w+$", "");
    } else {
      // this variant initializes some commonly used variables
      parameters.put("xpage", "xpart");
      parameters.put("vm", template);
    }
    if (parameter != null) {
      parameters.put(parameter, value);
    }
    return createUrl(null, space, page, parameters);
  }
Exemple #2
0
  public static String trimLeadingAndTrailingSpaces(String markdown) {
    StringBuilder markdownSB = new StringBuilder();

    StringBuilder currentLine = new StringBuilder();

    String firstLineIndent = null;
    for (int i = 0; i < markdown.length(); i++) {
      char currentChar = markdown.charAt(i);
      if (currentChar == '\r' || currentChar == '\n') {
        String currentLineString = currentLine.toString();
        if (firstLineIndent == null && !StringUtils.isEmpty(currentLineString)) {
          int firstNonWhitespaceIndex = StringUtils.indexOfAnyBut(currentLineString, " \t");
          if (firstNonWhitespaceIndex != -1)
            firstLineIndent = currentLineString.substring(0, firstNonWhitespaceIndex);
        }
        if (firstLineIndent != null)
          currentLineString = StringUtils.removeStart(currentLineString, firstLineIndent);

        markdownSB.append(currentLineString).append(SystemUtils.LINE_SEPARATOR);

        currentLine.setLength(0);

        // skip the next line separator for \r\n cases
        if (currentChar == '\r' && markdown.length() > (i + 1) && markdown.charAt(i + 1) == '\n') {
          i++;
        }
      } else {
        currentLine.append(currentChar);
      }
    }
    markdownSB.append(currentLine);

    return markdownSB.toString();
  }
 @Override
 public String getDocumentationUrl(Method method, Object content) {
   final Expose expose = AnnotationUtils.getAnnotation(method, Expose.class);
   // TODO can we support Mixins from here?
   //        final Class<?> mixin = provider.getConfig()
   //                .findMixInClassFor(bean.getClass());
   //        final Expose mixinExpose = getAnnotation(mixin, Expose.class);
   String methodName = method.getName();
   String propertyName;
   if (methodName.startsWith("get")) {
     propertyName = StringUtils.uncapitalize(StringUtils.removeStart(methodName, "get"));
   } else {
     propertyName = StringUtils.uncapitalize(StringUtils.removeStart(methodName, "is"));
   }
   return getExposedUrl(propertyName, vocabFromBean(content), termsFromBean(content), expose);
 }
Exemple #4
0
    public static void copyJarResourcesRecursively(File destination, JarURLConnection jarConnection) {
        JarFile jarFile;
        try {
            jarFile = jarConnection.getJarFile();
        } catch (Exception e) {
            _.die("Failed to get jar file)");
            return;
        }

        Enumeration<JarEntry> em = jarFile.entries();
        while (em.hasMoreElements()) {
            JarEntry entry = em.nextElement();
            if (entry.getName().startsWith(jarConnection.getEntryName())) {
                String fileName = StringUtils.removeStart(entry.getName(), jarConnection.getEntryName());
                if (!fileName.equals("/")) {  // exclude the directory
                    InputStream entryInputStream = null;
                    try {
                        entryInputStream = jarFile.getInputStream(entry);
                        FileUtils.copyInputStreamToFile(entryInputStream, new File(destination, fileName));
                    } catch (Exception e) {
                        die("Failed to copy resource: " + fileName);
                    } finally {
                        if (entryInputStream != null) {
                            try {
                                entryInputStream.close();
                            } catch (Exception e) {
                            }
                        }
                    }
                }
            }
        }
    }
Exemple #5
0
 /**
  * Get the next page of tagged media objects from a previously executed request
  *
  * @param pagination
  * @throws InstagramException
  */
 public TagMediaFeed getTagMediaInfoNextPage(Pagination pagination) throws InstagramException {
   return createInstagramObject(
       Verbs.GET,
       TagMediaFeed.class,
       StringUtils.removeStart(pagination.getNextUrl(), config.getApiURL()),
       null);
 }
 /**
  * Get the next page of user feed objects from a previously executed request
  *
  * @param pagination
  * @throws InstagramException
  */
 public UserFeed getUserFeedInfoNextPage(Pagination pagination) throws InstagramException {
   return createInstagramObject(
       Verbs.GET,
       UserFeed.class,
       StringUtils.removeStart(pagination.getNextUrl(), Constants.API_URL),
       null);
 }
Exemple #7
0
 private static void writeZipEntry(ZipOutputStream out, String name, byte[] data)
     throws IOException {
   final ZipEntry entry = new ZipEntry(StringUtils.removeStart(name, "/"));
   out.putNextEntry(entry);
   out.write(data, 0, data.length);
   out.closeEntry();
 }
Exemple #8
0
  public String getColumns() {
    String pluralizedName = mInflector.pluralize(name);
    String underscorePlural = mInflector.underscore(pluralizedName);
    String underscore = mInflector.underscore(name);

    StringBuilder sb = new StringBuilder();
    sb.append("public static class ").append(name).append(" implements BaseColumns {\n");

    // Content mime types
    sb.append(ONE_TAB)
        .append(PUBLIC_STATIC_FINAL)
        .append(
            "String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + /vnd.contentrovider.");
    sb.append(mInflector.pluralize(underscore.toLowerCase())).append(";\n\n");
    sb.append(ONE_TAB)
        .append(PUBLIC_STATIC_FINAL)
        .append(
            "String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + /vnd.contentrovider.");
    sb.append(underscore.toLowerCase()).append(";\n\n");

    // Content URIs

    sb.append(ONE_TAB)
        .append(PUBLIC_STATIC_FINAL)
        .append("Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_")
        .append(underscorePlural.toUpperCase())
        .append(").build();\n\n");
    if (members.contains("mId") || members.contains("mUniqueId")) {
      sb.append(ONE_TAB)
          .append(PUBLIC_STATIC_FINAL)
          .append("Uri CONTENT_BY_ID = BASE_CONTENT_URI.buildUpon().appendPath(PATH_")
          .append(underscorePlural.toUpperCase())
          .append("_BY_ID).build();\n\n");
    }

    // Table name
    sb.append(ONE_TAB)
        .append(PUBLIC_STATIC_FINAL)
        .append("String TABLE_NAME = \"")
        .append(underscore.toLowerCase())
        .append("\";\n\n");

    // column names
    for (Member member : members) {
      String simpleName = StringUtils.removeStart(member.getName(), "m");
      String underscoreMember = mInflector.underscore(simpleName);
      sb.append(ONE_TAB)
          .append(PUBLIC_STATIC_FINAL)
          .append("String COLUMN_NAME_")
          .append(underscoreMember.toUpperCase())
          .append(" = \"")
          .append(underscoreMember.toLowerCase())
          .append("\";\n\n");
    }

    sb.append("}\n");
    return sb.toString();
  }
 /**
  * Converts the received data of a complex member variable to a JSON string *
  *
  * @param data
  * @return
  */
 private String parseValue(String data) {
   StringBuilder jsonData = new StringBuilder();
   jsonData.append("{");
   data = StringUtils.removeStart(data, "{");
   data = StringUtils.removeEnd(data, "}");
   data = StringUtils.replace(data, "=", ":");
   jsonData.append(applyRegEx(data));
   jsonData.append("}");
   return jsonData.toString();
 }
  private void extractDescription(
      @NotNull Element element, String queryString, DictionaryObjectBuilder objectBuilder) {
    Element descriptionNode = element.getElementsByClass("info").first();
    if (descriptionNode != null) {
      String description = descriptionNode.text();

      description = StringUtils.removeStart(description, "(");
      description = StringUtils.removeEnd(description, ")");

      if (!StringUtils.equalsIgnoreCase(
          description, queryString)) // Set description only if it is different from request string
      objectBuilder.setDescription(StringUtils.strip(description));
    }
  }
  /**
   * Create a {@link SortField} corresponding to the field name. If the field name starts with '-',
   * then the field (excluding the leading -) will be used for reverse sorting.
   *
   * @param sortField The name of the field to sort by. If <tt>null</tt>, return a <tt>null</tt>
   *     SortField. If starts with '-', then return a SortField that does a reverse sort on the
   *     field.
   * @return A SortFiled that sorts on the given field, or <tt>null</tt>.
   */
  private SortField getSortField(String sortField) {
    SortField sort = null;
    if (!StringUtils.isEmpty(sortField)) {
      // For the moment assuming everything is a String is enough, since we don't usually want to
      // sort documents
      // on numerical object properties.
      sort =
          new SortField(
              StringUtils.removeStart(sortField, "-"),
              SortField.Type.STRING,
              sortField.startsWith("-"));
    }

    return sort;
  }
Exemple #12
0
  private String generateExtraMethods() {
    String type = StringUtils.removeEnd(StringUtils.removeStart(name, "List<"), ">");
    for (Member member : members) {
      if (member.getName().equalsIgnoreCase("mId")
          || member.getName().equalsIgnoreCase("mUniqueId")) {
        StringBuilder sb = new StringBuilder();

        sb.append(ONE_TAB + "@Override\n");
        sb.append(ONE_TAB + "public boolean equals(Object obj){\n");
        sb.append(TWO_TABS + "if(obj instanceof ").append(type).append("){\n");
        if (TypeUtils.isPrimitiveType(member.getType())) {
          sb.append(ONE_TAB + TWO_TABS + "return ((")
              .append(type)
              .append(") obj).")
              .append(member.getGetterSignature())
              .append(" == ")
              .append(member.getName())
              .append(";\n");
        } else {
          sb.append(ONE_TAB + TWO_TABS + "return ((")
              .append(type)
              .append(") obj).")
              .append(member.getGetterSignature())
              .append(".equals(")
              .append(member.getName())
              .append(");\n");
        }
        sb.append(TWO_TABS + "}\n");
        sb.append(TWO_TABS + "return false;\n");
        sb.append(ONE_TAB + "}\n\n");
        sb.append(ONE_TAB + "@Override\n");
        sb.append(ONE_TAB + "public int hashCode(){\n");
        sb.append(TWO_TABS + "return ");
        if (member.getType().equals("long")) {
          sb.append("((Long)");
        }
        sb.append(member.getName());
        if (member.getType().equals("long")) {
          sb.append(")");
        }
        sb.append(".hashCode();\n");
        sb.append(ONE_TAB + "}\n\n");
        return sb.toString();
      }
    }
    return "";
  }
  protected static MailAddress parsePath(int maxNumParams, String prefix, String str)
      throws SmtpCommandException {
    String[] params = parseParameters(1, maxNumParams, str);

    if (!StringUtils.startsWith(params[0], prefix)
        || !StringUtils.endsWith(
            params[0], ToolMailAddressUtils.MAIL_ADDR_PART_PERSONAL_ADDR_SUFFIX)) {
      throw new SmtpCommandException(
          new SmtpReplyImpl(
              SmtpReplyCode.SYNTAX_ERROR_ARGUMENTS,
              String.format(
                  "Required syntax: '%slocal@domain%s'",
                  prefix, ToolMailAddressUtils.MAIL_ADDR_PART_PERSONAL_ADDR_SUFFIX)));
    }

    int pathLen =
        (params[0] =
                StringUtils.removeEnd(
                    StringUtils.removeStart(params[0], prefix),
                    ToolMailAddressUtils.MAIL_ADDR_PART_PERSONAL_ADDR_SUFFIX))
            .length();

    if (pathLen > MAX_PATH_LEN) {
      throw new SmtpCommandException(
          new SmtpReplyImpl(
              SmtpReplyCode.SYNTAX_ERROR_ARGUMENTS,
              String.format("Path too long: %d > %d", pathLen, MAX_PATH_LEN)));
    }

    Matcher pathMatcher = PATTERN_PATH.matcher(params[0]);

    if (!pathMatcher.matches()) {
      throw new SmtpCommandException(
          new SmtpReplyImpl(
              SmtpReplyCode.SYNTAX_ERROR_ARGUMENTS,
              String.format("Malformed email address: %s", params[0])));
    }

    return new MailAddressImpl(pathMatcher.group(1));
  }
    @Bean(name = "googleAppsPublicKey", autowire = Autowire.BY_NAME)
    public PublicKey getGoogleAppsPublicKey() throws Exception {
      if (!isValidConfiguration()) {
        logger.debug(
            "Google Apps public key bean will not be created, because it's not configured");
        return null;
      }

      final PublicKeyFactoryBean bean = new PublicKeyFactoryBean();
      if (this.publicKeyLocation.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) {
        bean.setLocation(
            new ClassPathResource(
                StringUtils.removeStart(
                    this.publicKeyLocation, ResourceUtils.CLASSPATH_URL_PREFIX)));
      } else {
        bean.setLocation(new FileSystemResource(this.publicKeyLocation));
      }

      bean.setAlgorithm(this.keyAlgorithm);
      bean.afterPropertiesSet();

      logger.debug("Creating Google Apps public key instance via {}", this.publicKeyLocation);
      return bean.getObject();
    }
Exemple #15
0
  public static DockerImage parse(String uuid) {
    // if we encounter an error we will just return the raw string and
    // default registry
    boolean flag = false;
    // only strip once
    if (uuid.startsWith(KIND_PREFIX)) {
      uuid = uuid.substring(7);
      flag = true;
    }
    if (uuid.startsWith("sim:") && !flag) {
      uuid = uuid.substring(4);
    }
    String[] subMatches = findAllSubMatches(uuid, Regexp.REFERENCE_REGEXP);
    if (subMatches.length == 0) {
      if (uuid == "") {
        return null;
      }
      String[] subMatches2 = findAllSubMatches(uuid.toLowerCase(), Regexp.REFERENCE_REGEXP);
      if (subMatches2.length == 0) {
        return null;
      }
      return null;
    }

    if (subMatches[1].length() > NAME_TOTAL_LENGTH_MAX) {
      return null;
    }

    String name = subMatches[1];
    String fullname = uuid;
    String hostName = resolveHostName(name);
    if (fullname.startsWith(hostName + "/")) {
      fullname = StringUtils.removeStart(fullname, hostName + "/");
    }
    return new DockerImage(fullname, hostName);
  }
Exemple #16
0
  private String generateParcelableCode(Map<String, NewType> types) {
    StringBuilder sb = new StringBuilder();

    sb.append(ONE_TAB + "public ").append(name).append("(Parcel in) {\n");
    for (Member member : members) {

      if (member.getType().startsWith("List")) {
        String type =
            StringUtils.removeEnd(StringUtils.removeStart(member.getType(), "List<"), ">");
        if (TypeUtils.isPrimitiveType(type)) {
          sb.append(TWO_TABS + "in.readArrayList(")
              .append(type)
              .append(".class.getClassLoader());");

        } else {
          sb.append(TWO_TABS).append(member.getName());
          sb.append(" = new ArrayList<").append(type).append(">();\n");

          sb.append(TWO_TABS + "in.readTypedList(")
              .append(member.getName())
              .append(", ")
              .append(type);
          sb.append(".CREATOR);");
        }
      } else {
        sb.append(ONE_TAB + ONE_TAB);
        sb.append(member.getName()).append(" = ");
        if (member.getType().equals("boolean")) {

          sb.append("in.readInt() == 1 ? true: false;");
        } else if (types.containsKey(member.getType())) {
          sb.append("in.readParcelable(")
              .append(member.getType())
              .append(".class.getClassLoader());");
        } else {
          sb.append("in.read").append(StringUtils.capitalize(member.getType())).append("();");
        }
      }
      sb.append("\n");
    }
    sb.append(ONE_TAB + "}\n\n");

    sb.append(
        ONE_TAB
            + "@Override\n"
            + ONE_TAB
            + "public int describeContents() {\n"
            + ONE_TAB
            + ONE_TAB
            + "return 0;\n"
            + ONE_TAB
            + "}\n\n");

    sb.append(ONE_TAB + "public static final Parcelable.Creator<").append(name);
    sb.append("> CREATOR = new Parcelable.Creator<").append(name);
    sb.append(">() {\n" + ONE_TAB + ONE_TAB + "public ").append(name);
    sb.append(" createFromParcel(Parcel in) {\n            return new ").append(name);
    sb.append("(in);\n" + ONE_TAB + ONE_TAB + "}\n\n");

    sb.append(ONE_TAB + ONE_TAB + "public ").append(name);
    sb.append("[] newArray(int size) {\n" + ONE_TAB + ONE_TAB + "return new ").append(name);
    sb.append("[size];\n" + ONE_TAB + ONE_TAB + "}\n" + ONE_TAB + "};\n\n");

    sb.append(ONE_TAB + "@Override\n");
    sb.append(ONE_TAB + "public void writeToParcel(Parcel dest, int flags) {\n");
    for (Member member : members) {
      sb.append(ONE_TAB + ONE_TAB);
      if (member.getType().startsWith("List")) {
        String type =
            StringUtils.removeEnd(StringUtils.removeStart(member.getType(), "List<"), ">");
        if (TypeUtils.isPrimitiveType(type)) {
          sb.append("dest.writeList(").append(member.getName()).append(");");

        } else {
          sb.append("dest.writeTypedList(").append(member.getName()).append(");");
        }
      } else if (member.getType().equals("boolean")) {
        sb.append("dest.writeInt(").append(member.getName()).append(" ? 1 : 0);");
      } else if (types.containsKey(member.getType())) {
        sb.append("dest.writeParcelable(").append(member.getName()).append(", flags);");
      } else {
        sb.append("dest.write")
            .append(StringUtils.capitalize(member.getType()))
            .append("(")
            .append(member.getName())
            .append(");");
      }
      sb.append("\n");
    }
    sb.append(ONE_TAB + "}\n\n");

    return sb.toString();
  }
 private String stripBaseDir(String basedir, String test) {
   return StringUtils.removeStart(test, basedir);
 }
 MetricFetcher(String name) {
   this.name = StringUtils.removeStart(StringUtils.removeEnd(name, "/"), "/");
   this.accpetMetrics = Collections.singletonList(name);
 }
Exemple #19
0
 /**
  * 删除开始结束两头的特定字符
  *
  * @param str 原字符串
  * @param remover 要删除的字符
  * @return 删除后的字符串
  */
 public static String trim(String str, String remover) {
   return StringUtils.removeEnd(StringUtils.removeStart(str, remover), remover);
 }