/**
  * Computes the best file to save the response to the given URL.
  *
  * @param url the requested URL
  * @param extension the preferred extension
  * @return the file to create
  * @throws IOException if a problem occurs creating the file
  */
 private File createFile(final URL url, final String extension) throws IOException {
   String name = url.getPath().replaceFirst("/$", "").replaceAll(".*/", "");
   name = StringUtils.substringBefore(name, "?"); // remove query
   name = StringUtils.substringBefore(name, ";"); // remove additional info
   name = StringUtils.substring(name, 0, 30); // avoid exceptions due to too long file names
   if (!name.endsWith(extension)) {
     name += extension;
   }
   int counter = 0;
   while (true) {
     final String fileName;
     if (counter != 0) {
       fileName =
           StringUtils.substringBeforeLast(name, ".")
               + "_"
               + counter
               + "."
               + StringUtils.substringAfterLast(name, ".");
     } else {
       fileName = name;
     }
     final File f = new File(reportFolder_, fileName);
     if (f.createNewFile()) {
       return f;
     }
     counter++;
   }
 }
 /**
  * Normalize the path of a service by removing the query string and everything after a semi-colon.
  *
  * @param service the service to normalize
  * @return the normalized path
  */
 private static String normalizePath(final Service service) {
   String path = service.getId();
   path = StringUtils.substringBefore(path, "?");
   path = StringUtils.substringBefore(path, ";");
   path = StringUtils.substringBefore(path, "#");
   return path;
 }
  /**
   * @param filterName
   * @param value
   */
  public PropertyFilter(final String filterName, final String value) {

    String matchTypeStr;
    String matchPattenCode = LikeMatchPatten.ALL.toString();
    String matchTypeCode;
    String propertyTypeCode;

    if (filterName.contains("LIKE") && filterName.charAt(0) != 'L') {
      matchTypeStr = StringUtils.substringBefore(filterName, PARAM_PREFIX);
      matchPattenCode = StringUtils.substring(matchTypeStr, 0, 1);
      matchTypeCode = StringUtils.substring(matchTypeStr, 1, matchTypeStr.length() - 1);
      propertyTypeCode =
          StringUtils.substring(matchTypeStr, matchTypeStr.length() - 1, matchTypeStr.length());
    } else {
      matchTypeStr = StringUtils.substringBefore(filterName, PARAM_PREFIX);
      matchTypeCode = StringUtils.substring(matchTypeStr, 0, matchTypeStr.length() - 1);
      propertyTypeCode =
          StringUtils.substring(matchTypeStr, matchTypeStr.length() - 1, matchTypeStr.length());
    }

    try {
      matchType = Enum.valueOf(MatchType.class, matchTypeCode);
      likeMatchPatten = Enum.valueOf(LikeMatchPatten.class, matchPattenCode);
    } catch (RuntimeException e) {
      throw new IllegalArgumentException(
          "filter name: "
              + filterName
              + "Not prepared in accordance with rules, not get more types of property.",
          e);
    }

    try {
      propertyType = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue();
    } catch (RuntimeException e) {
      throw new IllegalArgumentException(
          "filter name: "
              + filterName
              + "Not prepared in accordance with the rules, attribute value types can not be.",
          e);
    }

    String propertyNameStr = StringUtils.substringAfter(filterName, PARAM_PREFIX);
    propertyNames = StringUtils.split(propertyNameStr, PropertyFilter.OR_SEPARATOR);

    Validate.isTrue(
        propertyNames.length > 0,
        "filter name: "
            + filterName
            + "Not prepared in accordance with the rules, property names can not be.");
    this.propertyValue = ConvertUtils.convert(value, propertyType);
  }
Example #4
0
 public static <T extends Comparable<T>> Range<T> parse(String value, Function<String, T> parser) {
   Validate.notNull(parser, "Parser is required");
   if (StringUtils.isBlank(value) || StringUtils.equals(SEPARATOR, value)) {
     return Ranges.all();
   } else if (!StringUtils.contains(value, SEPARATOR)) {
     T element = parser.apply(value);
     return Ranges.atMost(element);
   } else {
     String lower = StringUtils.substringBefore(value, SEPARATOR);
     String upper = StringUtils.substringAfter(value, SEPARATOR);
     if (StringUtils.isBlank(lower)) {
       // ..n
       Pair<T, BoundType> boundary = parseUpperBoundary(upper, parser);
       return Ranges.upTo(boundary.getLeft(), boundary.getRight());
     } else if (StringUtils.isBlank(upper)) {
       // n..
       Pair<T, BoundType> boundary = parseLowerBoundary(lower, parser);
       return Ranges.downTo(boundary.getLeft(), boundary.getRight());
     } else {
       // n..m
       Pair<T, BoundType> down = parseLowerBoundary(lower, parser);
       Pair<T, BoundType> up = parseUpperBoundary(upper, parser);
       return Ranges.range(down.getLeft(), down.getRight(), up.getLeft(), up.getRight());
     }
   }
 }
  protected HttpHeaders attachmentList(T entity, String category) {
    HttpServletRequest request = getRequest();
    String url = request.getServletPath();
    AttachmentFileService attachmentFileService =
        SpringContextHolder.getBean(AttachmentFileService.class);
    List<AttachmentFile> attachmentFiles =
        attachmentFileService.findBy(
            entity.getClass().getName(), String.valueOf(entity.getId()), category);
    List<Map<String, Object>> filesResponse = Lists.newArrayList();
    for (AttachmentFile attachmentFile : attachmentFiles) {
      Map<String, Object> dataMap = Maps.newHashMap();
      dataMap.put("id", attachmentFile.getId());
      dataMap.put("attachmentName", "_attachment_" + attachmentFile.getEntityFileCategory());
      dataMap.put("name", attachmentFile.getFileRealName());
      dataMap.put("size", FileUtils.byteCountToDisplaySize(attachmentFile.getFileLength()));

      dataMap.put(
          "url",
          getRequest().getContextPath()
              + StringUtils.substringBefore(url, "!attachmentList")
              + "!attachmentDownload?id="
              + entity.getId()
              + "&attachmentId="
              + attachmentFile.getId());
      filesResponse.add(dataMap);
    }
    Map<String, List<Map<String, Object>>> response = Maps.newHashMap();
    response.put("files", filesResponse);
    setModel(response);
    return buildDefaultHttpHeaders();
  }
Example #6
0
 /**
  * Build a new image.
  *
  * @param deck Deck name
  * @param repo Repo
  * @return Image name
  * @throws IOException If fails
  */
 private String build(final String deck, final XML repo) throws IOException {
   final String name = String.format("%s-%08x", deck, BuildImage.RND.nextInt());
   final String hash = "#";
   String uri = repo.xpath("uri/text()").get(0);
   final String branch;
   final String path;
   if (uri.contains(hash)) {
     final String[] tail = StringUtils.substringAfter(uri, hash).split(":", 2);
     branch = tail[0];
     path = tail[1];
     uri = StringUtils.substringBefore(uri, hash);
   } else {
     branch = "master";
     path = ".";
   }
   final long start = System.currentTimeMillis();
   this.script.exec(
       "t1.thindeck.com",
       new ArrayMap<String, String>()
           .with("image", name)
           .with("uri", uri)
           .with("branch", branch)
           .with("path", path));
   Logger.info(this, "Docker image %s built in %[ms]s", name, System.currentTimeMillis() - start);
   return name;
 }
Example #7
0
  private RoleGrantedAuthority renameProject(
      RoleGrantedAuthority authority, String projectName, String newProjectName) {
    GrantedAuthorityTarget target = authority.getTarget();
    String targetId = target.getTargetId();
    GrantedAuthorityTarget newTarget = null;
    switch (target.getType()) {
      case PROJECT:
        {
          String projName = targetId;
          if (projName.equals(projectName)) {
            newTarget =
                new GrantedAuthorityTarget(newProjectName, GrantedAuthorityTarget.Type.PROJECT);
          }
        }
        break;

      case BRANCH:
        {
          String projName = StringUtils.substringBefore(targetId, "/"); // $NON-NLS-1$
          if (projName.equals(projectName)) {
            String branchName = StringUtils.substringAfter(targetId, "/"); // $NON-NLS-1$
            String newTargetId = newProjectName + "/" + branchName; // $NON-NLS-1$
            newTarget = new GrantedAuthorityTarget(newTargetId, GrantedAuthorityTarget.Type.BRANCH);
          }
        }
        break;
    }
    return (newTarget != null)
        ? new RoleGrantedAuthority(newTarget, authority.getRoleName())
        : null;
  }
Example #8
0
  /** 分析并设置contentType与headers. */
  private static HttpServletResponse initResponseHeader(
      final String contentType, final String... headers) {
    // 分析headers参数
    String encoding = DEFAULT_ENCODING;
    boolean noCache = DEFAULT_NOCACHE;
    for (String header : headers) {
      String headerName = StringUtils.substringBefore(header, ":");
      String headerValue = StringUtils.substringAfter(header, ":");

      if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
        encoding = headerValue;
      } else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
        noCache = Boolean.parseBoolean(headerValue);
      } else {
        throw new IllegalArgumentException(headerName + "不是一个合法的header类型");
      }
    }

    HttpServletResponse response = ServletActionContext.getResponse();

    // 设置headers参数
    String fullContentType = contentType + ";charset=" + encoding;
    response.setContentType(fullContentType);
    if (noCache) {
      ServletUtils.setDisableCacheHeader(response);
    }

    return response;
  }
  static RabbitConnectionFactoryConfig uriToConnectionConfig(String uri) {
    RabbitConnectionFactoryConfig properties = new RabbitConnectionFactoryConfig();
    if (isNotEmpty(uri)) {
      String username = StringUtils.substringBetween(uri, "amqp://", ":");
      String password = StringUtils.substringBetween(uri, username + ":", "@");
      String hostWithPort = StringUtils.substringBetween(uri, "@", "/");

      // If no virtual host is specified
      if (isEmpty(hostWithPort)) {
        hostWithPort = StringUtils.substringAfter(uri, "@");
      }

      int port = properties.getPort();
      String host = hostWithPort;
      boolean hasPort = StringUtils.contains(hostWithPort, ":");
      if (hasPort) {
        host = StringUtils.substringBefore(hostWithPort, ":");
        port = NumberUtils.toInt(StringUtils.substringAfter(hostWithPort, ":"));
      }
      String virtualHost = StringUtils.substringAfter(uri, hostWithPort + "/");

      properties.setUsername(username);
      properties.setPassword(password);
      properties.setHost(host);
      properties.setPort(port);

      if (isNotEmpty(virtualHost)) {
        properties.setVirtualHost(virtualHost);
      }
    }
    return properties;
  }
  public void printNonRenames(DatabaseSnapshot reference, DatabaseSnapshot target, StringBuilder sb)
      throws Exception {
    CompareControl compareControl =
        new CompareControl(reference.getSnapshotControl().getTypesToInclude());
    DiffResult diffResult =
        DiffGeneratorFactory.getInstance().compare(reference, target, compareControl);

    DiffToChangeLog diffToChangeLog =
        new DiffToChangeLog(diffResult, new DiffOutputControl(false, false, false));

    SqlGeneratorFactory generatorFactory = SqlGeneratorFactory.getInstance();
    for (ChangeSet changeSet : diffToChangeLog.generateChangeSets()) {
      for (Change change : changeSet.getChanges()) {
        for (SqlStatement sqlStatement :
            change.generateStatements(LiquibaseModelFactory.DATABASE)) {
          for (Sql sql :
              generatorFactory.generateSql(sqlStatement, LiquibaseModelFactory.DATABASE)) {

            final String sqlString = sql.toSql();
            if (sqlString.endsWith("DROP INDEX")) {
              sb.append(StringUtils.substringBefore(sqlString, " DROP INDEX")).append(";\n");
            } else {
              sb.append(sqlString).append(";\n");
            }
          }
        }
      }
    }
  }
Example #11
0
  protected static void loadDictionary(String path) {
    Map<String, String> values = new HashMap<String, String>();
    BufferedReader br = null;
    try {
      br =
          new BufferedReader(
              new InputStreamReader(
                  Thread.currentThread()
                      .getContextClassLoader()
                      .getResourceAsStream(DEFAULT_ROOT_PATH + path),
                  "UTF-8"));
      LOG.info("Reading dictionary from stream:" + DEFAULT_ROOT_PATH + path);
      String line;

      while ((line = br.readLine()) != null) {
        String key = StringUtils.substringBefore(line, ";");

        values.put(key, line);
      }

      VALUES.put(path, values);
      // Close the input stream
      br.close();
    } catch (IOException e) {
      LOG.error("Error during loading csv file" + e.getMessage());
    } finally {
      if (br != null) {
        try {
          br.close();
        } catch (IOException e) {
          LOG.error("Erro occured while closing disctionary reader" + e.getMessage());
        }
      }
    }
  }
  // Converts title to their natural mentions
  public static String getCanonicalName(String title) {

    String naturalString = title.replaceAll("_", " ");
    if (naturalString.contains("("))
      naturalString = StringUtils.substringBefore(naturalString, "(");
    String trimmed = naturalString.trim();

    return trimmed;
  }
Example #13
0
  private String prepareCountHql(String orgHql) {
    String fromHql = orgHql;

    fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
    fromHql = StringUtils.substringBefore(fromHql, "order by");

    String countHql = "select count(*) " + fromHql;
    return countHql;
  }
Example #14
0
  private static Geopoint parseCoords(final String location) {
    final String latitude = StringUtils.substringBefore(location, SEPARATOR_STRING);
    final String longitude = StringUtils.substringAfter(location, SEPARATOR_STRING);
    if (StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)) {
      return new Geopoint(latitude, longitude);
    }

    return null;
  }
  public static String stripCommaSpace(String title) {

    String naturalString = title.replaceAll("_", " ");
    // if(naturalString.contains("("))
    // naturalString = StringUtils.substringBefore(naturalString, "(");
    if (naturalString.contains(","))
      naturalString = StringUtils.substringBefore(naturalString, ",");
    String trimmed = naturalString.trim();

    return trimmed;
  }
 /**
  * *
  * <li><b>Substring/Left/Right/Mid</b> - null-safe substring extractions
  * <li><b>SubstringBefore/SubstringAfter/SubstringBetween</b> - substring extraction relative to
  *     other strings
  */
 @Test
 public void testSubstringLeftStringUtils() {
   System.out.println(strOne + ":" + strOne.length());
   System.out.println(StringUtils.substring(strOne, 3));
   System.out.println(StringUtils.substring(strOne, 3, 7));
   System.out.println(StringUtils.substringAfter(strOne, " "));
   System.out.println(StringUtils.substringAfterLast(strOne, " "));
   System.out.println(StringUtils.substringBefore(strOne, " "));
   System.out.println(StringUtils.substringBeforeLast(strOne, " "));
   System.out.println(StringUtils.substringBetween(strOne, "the", "not"));
 }
Example #17
0
 /**
  * Get the guessed file extension of an URL. A file extension can contain up-to 4 characters in
  * addition to the dot.
  *
  * @param url the relative or absolute URL
  * @return the file extension, including the leading dot, or the empty string if none could be
  *     determined
  */
 static String getExtension(final String url) {
   final String urlExt;
   if (url.startsWith("data:")) {
     // "data:image/png;base64,i53…" -> ".png"
     urlExt = StringUtils.substringAfter(StringUtils.substringBefore(url, ";"), "/");
   } else {
     // "http://example.com/foo/bar.png" -> ".png"
     urlExt = StringUtils.substringAfterLast(url, ".");
   }
   return urlExt.length() >= 1 && urlExt.length() <= 4 ? "." + urlExt : "";
 }
  private String getSimpleCountHQL(String hql) {

    String fromHql = hql;

    // select子句与order by子句会影响count查询,进行简单的排除.
    fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
    fromHql = StringUtils.substringBefore(fromHql, "order by");

    String countHql = "select count(*) " + fromHql;
    return countHql;
  }
Example #19
0
  public static String getQuartzParametersByFormula(String quartzExpr) {
    Map<String, String> resMap = new HashMap<String, String>();

    String arrayStrings[] = quartzExpr.split("\\s+");
    if (arrayStrings.length == 6) {
      String hours = arrayStrings[2];
      String interval = arrayStrings[1];

      String startHour = StringUtils.substringBefore(hours, "-");
      String endHour = StringUtils.substringAfter(hours, "-");
      String startMinute = StringUtils.substringBefore(interval, "/");
      String endMinute = "00";
      StringBuilder sb = new StringBuilder();
      sb.append(startHour)
          .append(":")
          .append(startMinute)
          .append("-")
          .append(endHour)
          .append(":")
          .append(endMinute);
      resMap.put("sRegionTime", sb.toString());

      String weekDays =
          arrayStrings[5].indexOf("\"") > 0
              ? StringUtils.substringBefore(arrayStrings[5], "\"")
              : arrayStrings[5];
      for (DAY_OF_WEEK b : DAY_OF_WEEK.values()) {
        weekDays = StringUtils.replace(weekDays, b.getQuartzStr(), b.getInternalStr());
      }

      resMap.put("saRegionWeekDay", weekDays);

      resMap.put("nLen", StringUtils.substringAfter(interval, "/"));
    }

    JSONObject res = new JSONObject(resMap);

    return res.toString();
  }
Example #20
0
 public static List<String> parseRow(
     String rowAsString, String separator, String commentSeparator, boolean trimValues) {
   StringBuffer regex = new StringBuffer();
   for (char c : separator.toCharArray()) {
     regex.append("\\").append(c);
   }
   List<String> values = new ArrayList<String>();
   for (String value : rowAsString.split(regex.toString(), -1)) {
     String stripped = StringUtils.substringBefore(value, commentSeparator);
     String trimmed = trimValues ? stripped.trim() : stripped;
     values.add(StringUtils.substringBefore(trimmed, commentSeparator));
   }
   // ignore a leading and a trailing empty value
   if (StringUtils.isBlank(values.get(0))) {
     values.remove(0);
   }
   int lastIndex = values.size() - 1;
   if (lastIndex != -1 && StringUtils.isBlank(values.get(lastIndex))) {
     values.remove(lastIndex);
   }
   return values;
 }
Example #21
0
  public static String getQuartzFormulaByParameters(
      String sRegionTime, String saRegionWeekDay, Integer nLen) {
    // sRegionTime is in format HH:MM-HH:MM
    // saRegionWeekDay is in format "mo,tu,we,th,fr,sa". Need to convert to MON, TUE, WED, THU, FRI,
    // SAT, SUN
    String startTime = StringUtils.substringBefore(sRegionTime, "-");
    String endTime = StringUtils.substringAfter(sRegionTime, "-");
    String startHour = StringUtils.substringBefore(startTime, ":");
    String startMinute = StringUtils.substringAfter(startTime, ":");
    String endHour = StringUtils.substringBefore(endTime, ":");

    for (DAY_OF_WEEK b : DAY_OF_WEEK.values()) {
      saRegionWeekDay = saRegionWeekDay.replace(b.getInternalStr(), b.getQuartzStr());
    }

    String res = StringUtils.replace(QUARTZ_FORMAT, "[INTERVAL]", nLen.toString());
    res = StringUtils.replace(res, "[START_MINUTE]", startMinute);
    res = StringUtils.replace(res, "[HOURS_PERIOD]", startHour + "-" + endHour);
    res = StringUtils.replace(res, "[DAYS]", saRegionWeekDay);

    return res;
  }
Example #22
0
 /**
  * 将sql中问号替换成实际值
  *
  * @param sql select * from a where name=?
  * @param paramValues
  * @return
  */
 public static String formatSql(final String sql, final Object[] paramValues) {
   String fsql = sql;
   for (Object value : paramValues) {
     String tmp = fsql;
     fsql = StringUtils.substringBefore(tmp, "?");
     if (value instanceof String) {
       fsql += "'" + value + "'";
     } else {
       fsql += ClassUtil.convertValueToString(value);
     }
     fsql += StringUtils.substringAfter(tmp, "?");
   }
   return fsql;
 }
  /**
   * See class comment
   *
   * @param file file
   * @param environment environment name for the file
   * @return map with properties TO, never null
   */
  @SneakyThrows
  public List<Property> parseFile(@NonNull File file, String environment) {
    System.out.println(" - Parsing file: " + file);
    List<String> lines = FileUtils.readLines(file, "UTF-8");

    List<Property> properties = new ArrayList<>();

    StringBuilder comment = new StringBuilder();

    for (String line : lines) {

      line = line.trim();

      if (line.isEmpty()) {
        // reset current comment buffer
        comment = new StringBuilder();

      } else if (line.startsWith("#")) {
        // add next line of comment to the comment buffer
        comment.append(line).append("\n");

      } else {
        // reached the property definition - run parsing and reset the
        // buffer

        Property property = new Property();
        property.setName(StringUtils.substringBefore(line, "=").trim());
        property.setDefaultValue(StringUtils.substringAfter(line, "=").trim());

        String commentLines = comment.toString();

        System.out.println(
            " - - found property: '"
                + property.getName()
                + "' with comments: "
                + StringUtils.replace(commentLines, "\n", "\\n"));

        property.setMetadatas(commentParser.parseComment(commentLines));
        System.out.println(property);
        comment = new StringBuilder();

        property.setSourceFileName(file.getAbsolutePath());
        property.setEnvironment(environment);
        properties.add(property);
      }
    }

    return properties;
  }
  private String calculateImplicitOrExplicitRequirePrefixDirectory(
      AssetContainer assetContainer, String srcDirName) {
    MemoizedFile brjsDir = assetContainer.root().dir();
    String rootPath = srcDirName;

    MemoizedFile srcDir = assetContainer.file(srcDirName);
    if (!srcDir.isDirectory()) {
      return srcDirName;
    }

    String rootRequirePrefix = StringUtils.substringBefore(assetContainer.requirePrefix(), "/");
    MemoizedFile rootRequirePrefixDir = srcDir.file(rootRequirePrefix);

    String nestedRequirePrefixPath = srcDirName + "/" + assetContainer.requirePrefix();
    MemoizedFile nestedRequirePrefixDir = assetContainer.file(nestedRequirePrefixPath);

    MemoizedFile rootPathDir = assetContainer.file(rootPath);
    boolean explicitRequirePrefixDirsExist = nestedRequirePrefixDir.isDirectory();

    if (rootRequirePrefixDir.exists() && !explicitRequirePrefixDirsExist) {
      InvalidRequirePathException wrappedRequirePathException =
          new InvalidRequirePathException(
              String.format(
                  "The location '%s' contains a directory with the same name as the root require prefix ('%s') which suggests it's require prefix is explicitly defined"
                      + " but no folder exists that corresponds to the require prefix for this location ('%s'). Either move all source files and package folders into the directory '%s'"
                      + " to use an explicit directory structure or move all files and package folders into '%s' to allow the require prefix to be calculated automatically.",
                  brjsDir.getRelativePath(assetContainer.file(srcDirName)),
                  rootRequirePrefix,
                  assetContainer.requirePrefix(),
                  brjsDir.getRelativePath(nestedRequirePrefixDir),
                  brjsDir.getRelativePath(rootPathDir)));
      throw new RuntimeException(wrappedRequirePathException);
    }

    BRJS brjs = assetContainer.root();
    Logger logger = brjs.logger(this.getClass());
    if (explicitRequirePrefixDirsExist && useImpliedRequirePrefix(assetContainer)) {
      return nestedRequirePrefixPath;
    }
    logger.debug(
        IMPLICIT_PACKAGE_USED,
        assetContainer.root().dir().getRelativePath(srcDir),
        assetContainer.requirePrefix(),
        assetContainer.requirePrefix());
    return rootPath;
  }
 private int getShowId(String name) {
   try {
     Response response =
         client.get(
             "http://www.tvrage.com/feeds/search.php?show=" + URLEncoder.encode(name, "utf-8"));
     String responseString = response.getBodyAsString();
     String sid =
         StringUtils.substringBefore(
             StringUtils.substringAfter(responseString, "<showid>"), "</showid>");
     if (sid == null) {
       return -1;
     }
     log.debug("found id: {} for show: {}", sid, name);
     return Integer.parseInt(sid);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
Example #26
0
  @NotNull
  private DictionaryObject processSingleNode(
      @NotNull Element element, @NotNull Language language, String queryString) {
    DictionaryObjectBuilder objectBuilder = ImmutableDictionaryObject.builder();
    objectBuilder.setLanguage(language);

    // Extract entry text:
    String context =
        StringUtils.substringBefore(element.text(), element.getElementsByTag("a").first().text());
    String generalForm = context + element.getElementsByTag("a").first().text();
    objectBuilder.setGeneralForm(StringUtils.strip(generalForm));

    // Extract description:
    extractDescription(element, queryString, objectBuilder);

    // Extract gender:
    extractGender(element, objectBuilder);

    return objectBuilder.build();
  }
Example #27
0
  @Transactional(readOnly = true)
  @Override
  public A authFind(final String key) {
    if (key == null) {
      throw new NotFoundException("Null key");
    }

    A any = find(key);
    if (any == null) {
      throw new NotFoundException(
          StringUtils.substringBefore(
                  StringUtils.substringAfter(getClass().getSimpleName(), "JPA"), "DAO")
              + " "
              + key);
    }

    securityChecks(any);

    return any;
  }
Example #28
0
  static { // load img when using
    String filePath = null;
    try {
      filePath =
          URLDecoder.decode(ImgUtils.class.getClassLoader().getResource("").getPath(), "utf-8");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    File[] listFiles = new File(filePath + IMG_PATH).listFiles();
    for (File file : listFiles) {
      try {
        Image img = ImageIO.read(file);
        imgMap.put(StringUtils.substringBefore(file.getName(), "."), img);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    System.out.println(imgMap.keySet());
  }
Example #29
0
  public static void handleException(RestRequest request, RestResponse response, Throwable ex) {

    Throwable rootCause = ExceptionUtils.getRootCause(ex);
    rootCause = rootCause == null ? ex : rootCause;

    logger.error("捕获到Rest异常:request={}", request, rootCause);
    RestError restError = new RestError();
    restError.setErrorCode(2);

    if (ex instanceof RestServiceException) {

      RestServiceException rse = (RestServiceException) ex;

      if (rse.getErrorCode() != 0) {

        restError.setErrorCode(rse.getErrorCode());
      }

      restError.setErrorInfo(rse.getMessage());

    } else {

      restError.setErrorInfo(RestApiConstants.DEFAULT_ERROR_INFO);

      if (request.isDebug()) {

        String stackTrace = ExceptionUtils.getStackTrace(rootCause);
        // 截取有用的部分
        stackTrace = StringUtils.substringBefore(stackTrace, RestApiConstants.STACK_TRACE_BEFORE);
        response.setDebugInfo(stackTrace);
      }

      // 统计响应结果
      recordToErrorCounter(request.getCmd());
    }

    response.setStatusCode(500);
    response.setError(restError);
    response.setResponseTime(new Date());
  }
Example #30
0
  /**
   * Extracts an UriBuilder for the current request, taking into account the possibility of
   * header-based URI override.
   *
   * @param uriInfo
   * @param httpHeaders
   * @return
   * @throws URISyntaxException
   */
  public static UriBuilder getUriBuilder(final UriInfo uriInfo, final HttpHeaders httpHeaders)
      throws URISyntaxException {
    final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();

    final List<String> hosts = httpHeaders.getRequestHeader(HttpHeaders.HOST);
    if ((hosts != null) && (!hosts.isEmpty())) {
      final String host = hosts.get(0);
      uriBuilder.host(StringUtils.substringBefore(host, ":"));

      final String port = StringUtils.substringAfter(host, ":");
      if (StringUtils.isNotBlank(port)) {
        uriBuilder.port(Integer.valueOf(port));
      }
    }

    final String protocol = getSingleHeader(httpHeaders, Constants.FORWARDED_PROTOCOL_HTTP_HEADER);
    if (StringUtils.isNotBlank(protocol)) {
      uriBuilder.scheme(protocol);
    }

    return uriBuilder;
  }