java.util.regex.Pattern Java Examples

The following examples show how to use java.util.regex.Pattern. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CommonUtils.java    From sealtalk-android with MIT License 6 votes vote down vote up
/**
 * 邮箱格式是否正确
 *
 * @param email
 * @return
 */
public static boolean isEmail(String email) {

    if (TextUtils.isEmpty(email))
        return false;

    String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";

    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(email);

    if (matcher.matches())
        return true;
    else
        return false;

}
 
Example #2
Source File: GenerateEnumSchema.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider="schemagenGenerationData")
public void schemangenGenerationTestCase(String shortTestName,
        String inputFileName, String regexp) throws IOException {
    //Create test case directory
    Path testCaseDir = testWorkDir.resolve(shortTestName);
    Files.createDirectories(testCaseDir);
    //Copy java source from test.src to the test case dir
    Files.copy(testSrcDir.resolve(inputFileName), testCaseDir.resolve(inputFileName), REPLACE_EXISTING);
    //Run schemagen
    runSchemaGen(inputFileName, testCaseDir);
    //Check if schema file generated
    Assert.assertTrue(Files.exists(testCaseDir.resolve(SCHEMA_FILE)));
    //Read schema content from file
    String content = Files.lines(testCaseDir.resolve(SCHEMA_FILE)).collect(Collectors.joining(""));
    System.out.println("Generated schema: " + content);
    //Check if schema contains expected content
    Assert.assertTrue(Pattern.matches(regexp, content));
}
 
Example #3
Source File: KotlinSparkInterpreter.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
private static List<String> sparkClasspath() {
  String sparkJars = System.getProperty("spark.jars");
  Pattern isKotlinJar = Pattern.compile("/kotlin-[a-z]*(-.*)?\\.jar");

  Stream<File> addedJars = Arrays.stream(Utils.resolveURIs(sparkJars).split(","))
      .filter(s -> !s.trim().equals(""))
      .filter(s -> !isKotlinJar.matcher(s).find())
      .map(s -> {
        int p = s.indexOf(':');
        return new File(s.substring(p + 1));
      });

  Stream<File> systemJars = Arrays.stream(
      System.getProperty("java.class.path").split(File.pathSeparator))
      .map(File::new);

  return Stream.concat(addedJars, systemJars)
      .map(file -> {
        try {
          return file.getCanonicalPath();
        } catch (IOException e) {
          return "";
        }
      })
      .collect(Collectors.toList());
}
 
Example #4
Source File: TwigTypeResolveUtil.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
private static Map<String, String> getInlineCommentDocsVars(@NotNull PsiElement twigCompositeElement) {
    Map<String, String> variables = new HashMap<>();

    for(PsiElement psiComment: YamlHelper.getChildrenFix(twigCompositeElement)) {
        if(!(psiComment instanceof PsiComment)) {
            continue;
        }

        String text = psiComment.getText();
        if(StringUtils.isBlank(text)) {
            continue;
        }

        for (Pattern pattern : INLINE_DOC_REGEX) {
            Matcher matcher = pattern.matcher(text);
            while (matcher.find()) {
                variables.put(matcher.group("var"), matcher.group("class"));
            }
        }
    }

    return variables;
}
 
Example #5
Source File: TwigTemplateGoToDeclarationHandler.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
/**
 * Extract class from inline variables
 *
 * {# @var \AppBundle\Entity\Foo variable #}
 * {# @var variable \AppBundle\Entity\Foo #}
 */
@NotNull
private Collection<PhpClass> getVarClassGoto(@NotNull PsiElement psiElement) {
    String comment = psiElement.getText();

    if(StringUtils.isBlank(comment)) {
        return Collections.emptyList();
    }

    for(String pattern: TwigTypeResolveUtil.DOC_TYPE_PATTERN_SINGLE) {
        Matcher matcher = Pattern.compile(pattern).matcher(comment);
        if (matcher.find()) {
            String className = matcher.group("class");
            if(StringUtils.isNotBlank(className)) {
                return PhpElementsUtil.getClassesInterface(psiElement.getProject(), className);
            }
        }
    }

    return Collections.emptyList();
}
 
Example #6
Source File: MaxWarns.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
void check(String out, int count) {
    System.err.println(out);
    Pattern warn = Pattern.compile("warning - @param argument \"i[0-9]+\" is not a parameter name");
    Matcher m = warn.matcher(out);
    int n = 0;
    for (int start = 0; m.find(start); start = m.start() + 1) {
        n++;
    }
    if (n != count)
        error("unexpected number of warnings reported: " + n + "; expected: " + count);

    Pattern warnCount = Pattern.compile("(?ms).*^([0-9]+) warnings$.*");
    m = warnCount.matcher(out);
    if (m.matches()) {
        n = Integer.parseInt(m.group(1));
        if (n != count)
            error("unexpected number of warnings reported: " + n + "; expected: " + count);
    } else
        error("total count not found");
}
 
Example #7
Source File: ReUtil.java    From t-io with Apache License 2.0 6 votes vote down vote up
/**
 * 正则替换指定值<br>
 * 通过正则查找到字符串,然后把匹配到的字符串加入到replacementTemplate中,$1表示分组1的字符串
 * 
 * @param content 文本
 * @param pattern {@link Pattern}
 * @param replacementTemplate 替换的文本模板,可以使用$1类似的变量提取正则匹配出的内容
 * @return 处理后的文本
 * @since 3.0.4
 */
public static String replaceAll(String content, Pattern pattern, String replacementTemplate) {
	if (StrUtil.isEmpty(content)) {
		return content;
	}

	final Matcher matcher = pattern.matcher(content);
	boolean result = matcher.find();
	if (result) {
		final Set<String> varNums = findAll(PatternPool.GROUP_VAR, replacementTemplate, 1, new HashSet<String>());
		final StringBuffer sb = new StringBuffer();
		do {
			String replacement = replacementTemplate;
			for (String var : varNums) {
				int group = Integer.parseInt(var);
				replacement = replacement.replace("$" + var, matcher.group(group));
			}
			matcher.appendReplacement(sb, escape(replacement));
			result = matcher.find();
		} while (result);
		matcher.appendTail(sb);
		return sb.toString();
	}
	return content;
}
 
Example #8
Source File: Invoker.java    From knox with Apache License 2.0 6 votes vote down vote up
private static String resolveValue( Properties properties, String name ) {
  String value = properties.getProperty( name );
  Pattern pattern = Pattern.compile( ".*?(\\$\\{)(.*?)(\\}).*" );
  Matcher matcher = pattern.matcher( value );
  while( matcher.matches() ) {
    StringBuilder resolvedValue = new StringBuilder( value.length() );
    resolvedValue.append( value.substring( 0, matcher.start( 1 ) ) );
    String varName = matcher.group( 2 );
    String varVal = properties.getProperty( varName );
    if( varVal != null ) {
      resolvedValue.append( varVal );
    }
    resolvedValue.append( value.substring( matcher.end( 3 ) ) );
    value = resolvedValue.toString();
    matcher = pattern.matcher( value );
  }
  return value;
}
 
Example #9
Source File: BinaryDictionaryUtils.java    From AOSP-Kayboard-7.1.2 with Apache License 2.0 6 votes vote down vote up
public static boolean renameDict(final File dictFile, final File newDictFile) {
    if (dictFile.isFile()) {
        return dictFile.renameTo(newDictFile);
    } else if (dictFile.isDirectory()) {
        final String dictName = dictFile.getName();
        final String newDictName = newDictFile.getName();
        if (newDictFile.exists()) {
            return false;
        }
        for (final File file : dictFile.listFiles()) {
            if (!file.isFile()) {
                continue;
            }
            final String fileName = file.getName();
            final String newFileName = fileName.replaceFirst(
                    Pattern.quote(dictName), Matcher.quoteReplacement(newDictName));
            if (!file.renameTo(new File(dictFile, newFileName))) {
                return false;
            }
        }
        return dictFile.renameTo(newDictFile);
    }
    return false;
}
 
Example #10
Source File: Script.java    From jbang with MIT License 6 votes vote down vote up
List<String> quotedStringToList(String subjectString) {
	List<String> matchList = new ArrayList<String>();
	Pattern regex = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'");
	Matcher regexMatcher = regex.matcher(subjectString);
	while (regexMatcher.find()) {
		if (regexMatcher.group(1) != null) {
			// Add double-quoted string without the quotes
			matchList.add(regexMatcher.group(1));
		} else if (regexMatcher.group(2) != null) {
			// Add single-quoted string without the quotes
			matchList.add(regexMatcher.group(2));
		} else {
			// Add unquoted word
			matchList.add(regexMatcher.group());
		}
	}
	return matchList;
}
 
Example #11
Source File: AutoCompleteEditText.java    From Android-AutoCompleteEditText with MIT License 6 votes vote down vote up
@Override
protected void replaceText(CharSequence text){
    String beforeCursor = getText().toString().substring(0, getSelectionStart());
    String afterCursor = getText().toString().substring(getSelectionStart());

    Pattern pattern = Pattern.compile("#\\S*");
    Matcher matcher = pattern.matcher(beforeCursor);
    StringBuffer sb = new StringBuffer();
    int matcherStart = 0;
    while (matcher.find()) {
        int curPos = getSelectionStart();
        if(curPos > matcher.start() &&
                curPos <= matcher.end()){
            matcherStart = matcher.start();
            matcher.appendReplacement(sb, text.toString()+" ");
        }
    }
    matcher.appendTail(sb);
    setText(sb.toString()+afterCursor);
    setSelection(matcherStart + text.length()+1);
}
 
Example #12
Source File: IOMatchers.java    From docker-compose-rule with Apache License 2.0 6 votes vote down vote up
public static Matcher<String> matchingPattern(String patternStr) {
    return new TypeSafeDiagnosingMatcher<String>() {
        @Override
        protected boolean matchesSafely(String text, Description mismatchDescription) {
            Pattern pattern = Pattern.compile(patternStr, Pattern.DOTALL);
            boolean matches = pattern.matcher(text).matches();
            if (!matches) {
                mismatchDescription.appendText(text);
            }
            return matches;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("matching '" + patternStr + "'");
        }
    };
}
 
Example #13
Source File: MessageListItem.java    From zom-android-matrix with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a list with all links contained in the input
 */
public static List<String> extractUrls(String text)
{
    List<String> containedUrls = new ArrayList<String>();
    String urlRegex = "((https?|ftp|gopher|telnet|file):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)";
    Pattern pattern = Pattern.compile(urlRegex, Pattern.CASE_INSENSITIVE);
    Matcher urlMatcher = pattern.matcher(text);

    while (urlMatcher.find())
    {
        containedUrls.add(text.substring(urlMatcher.start(0),
                urlMatcher.end(0)));
    }

    return containedUrls;
}
 
Example #14
Source File: CoTAdapter.java    From defense-solutions-proofs-of-concept with Apache License 2.0 6 votes vote down vote up
private String convertType(String type) {

		Matcher matcher;
		for (CoTTypeDef cd : this.coTTypeMap) {
			if (!cd.isPredicate()) {
				Pattern pattern = Pattern.compile(cd.getKey());
				matcher = pattern.matcher(type);
				if (matcher.find()) {

					return this.filterOutDots(appendToType(type)
							+ cd.getValue());

				}

			}

		}
		// no match was found
		return "";

	}
 
Example #15
Source File: MovieParser.java    From android-vlc-remote with GNU General Public License v3.0 6 votes vote down vote up
public Movie parse(String path) {
    Movie movie;
    String fileName = File.baseName(path);
    for(Pattern p : patternList) {
        Matcher m = p.matcher(fileName);
        if (m.find()) {
            movie = new Movie();
            movie.setMovieName(StringUtil.formatMatch(m.group(1)));
            if(m.groupCount() == 4) {
                movie.setYear(Integer.valueOf(m.group(2)));
                movie.setQuality(m.group(3));
                movie.setSource(VideoSources.getFormattedSource(m.group(4)));
            } else if(m.groupCount() == 3) {
                movie.setQuality(m.group(2));
                movie.setSource(VideoSources.getFormattedSource(m.group(3)));
            } else {
                movie.setQuality(m.group(2));
            }
            return movie;
        }
    }
    return null;
}
 
Example #16
Source File: CurrencyQueryTest.java    From jsr354-ri with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that searching currencies by regex is supported.
 */
@Test
public void testSeachByRegex() {
    String dollarRegex = "\\p{Upper}{2}D";
    Pattern dollarPattern = Pattern.compile(dollarRegex);
    Collection<CurrencyUnit> allCurrencies = Monetary.getCurrencies(CurrencyQueryBuilder.of().build());
    Set<String> availableDollarCodes = allCurrencies.stream()
                                                    .map(CurrencyUnit::getCurrencyCode)
                                                    .filter(currencyCode -> dollarPattern.matcher(currencyCode).matches())
                                                    .collect(toSet());

    assertFalse(availableDollarCodes.isEmpty());

    CurrencyQuery dollarQuery = CurrencyQueryBuilder.of().setCurrencyCodes(dollarRegex).build();
    Collection<CurrencyUnit> dollarCurrencies = Monetary.getCurrencies(dollarQuery);
    for (CurrencyUnit dollarCurrency : dollarCurrencies) {
        availableDollarCodes.remove(dollarCurrency.getCurrencyCode());
    }

    assertTrue(availableDollarCodes.isEmpty());
}
 
Example #17
Source File: GrepResults.java    From LoggerPlusPlus with GNU Affero General Public License v3.0 6 votes vote down vote up
private void processMatches(Pattern pattern, byte[] content, boolean isRequest){
    final Matcher respMatcher = pattern.matcher(new String(content));
    while(respMatcher.find() && !Thread.currentThread().isInterrupted()){
        String[] groups = new String[respMatcher.groupCount()+1];
        for (int i = 0; i < groups.length; i++) {
            groups[i] = respMatcher.group(i);
        }

        if(isRequest) {
            requestMatches++;
        }else {
            responseMatches++;
        }
        results.add(new Match(groups, isRequest));
    }
}
 
Example #18
Source File: AbstractEntitySearcher.java    From webdsl with Apache License 2.0 6 votes vote down vote up
private Query createRegexQuery ( QueryDef qd ) {
    BooleanQuery query = new BooleanQuery();
    List<SpanQuery> spanClausesList = new ArrayList<SpanQuery>();
    String[] queryStrings;
    SpanQuery[] spanClausesArray;
    RegexQuery regexQuery;
    for ( String fld : qd.fields ) {
        spanClausesList.clear();
        queryStrings = qd.query.split(" ");
        spanClausesArray = new SpanQuery[queryStrings.length];
        for ( String subquery : queryStrings ) {
            regexQuery = new RegexQuery( new Term( fld, subquery ) );
            regexQuery.setRegexImplementation( new JavaUtilRegexCapabilities() );
            //if emptyable, like a query '(optional)?' or 'bla|a*', make span optional by wrapping it SpanOrQuery
            if(Pattern.matches(subquery, "")){
                spanClausesList.add( new SpanOrQuery( new SpanMultiTermQueryWrapper<RegexQuery>( regexQuery ) ) );
            } else {
                spanClausesList.add( new SpanMultiTermQueryWrapper<RegexQuery>( regexQuery ) );
            }
        }

        spanClausesList.toArray( spanClausesArray );
        query.add( new SpanNearQuery( spanClausesArray, 0, true), Occur.SHOULD );
    }
    return query;
}
 
Example #19
Source File: UKTools.java    From youkefu with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param message
 */
public static AsrResult parseAsrResult(String id,String message , int speakms) {
	AsrResult asrResult = null ;
	Pattern pattern = Pattern.compile("([\\d]{1,})[\\.]{1}([\\s\\S]*);");
	Matcher matcher = pattern.matcher(message);    	
	if(matcher.find() && matcher.groupCount() == 2) {
		asrResult = new AsrResult(id , matcher.group(2) , matcher.group(1));
		if(asrResult.getMessage().endsWith("。")) {
			asrResult.setMessage(asrResult.getMessage().substring(0 , asrResult.getMessage().length() - 1));	
		}
	}
	if(speakms > 0 && asrResult!=null) {
		asrResult.setSpeakms(speakms);
	}
	return asrResult;
}
 
Example #20
Source File: MatchesEvaluator.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
public MatchesEvaluator(final Evaluator<String> subject, final Evaluator<String> search) {
    this.subject = subject;
    this.search = search;

    // if the search string is a literal, we don't need to evaluate it each time; we can just
    // pre-compile it. Otherwise, it must be compiled every time.
    if (search instanceof StringLiteralEvaluator) {
        this.compiledPattern = Pattern.compile(search.evaluate(null).getValue());
    } else {
        this.compiledPattern = null;
    }
}
 
Example #21
Source File: DailyMotionUtils.java    From xGetter with Apache License 2.0 5 votes vote down vote up
private String getJson(String html){
    final String regex = "var ?config ?=(.*);";
    final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
    final Matcher matcher = pattern.matcher(html);
    if (matcher.find()) {
        return matcher.group(1);
    }
    return null;
}
 
Example #22
Source File: AppUtil.java    From weixin with Apache License 2.0 5 votes vote down vote up
/**
 * 验证输入的邮箱格式是否符合
 * 
 * @param email
 * @return 是否合法
 */
public static boolean emailFormat(String email) {
	boolean tag = true;
	final String pattern1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
	final Pattern pattern = Pattern.compile(pattern1);
	final Matcher mat = pattern.matcher(email);
	if (!mat.find()) {
		tag = false;
	}
	return tag;
}
 
Example #23
Source File: KeelToXml.java    From KEEL with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Transforms an attribute name given of the KEEL file to a valid xml tag. 
 * @param nameLabelUser attribute name with KEEL format.
 * @return valid xml tag of the attribute name given.
 * @throws Exception
 */
public String NameLabelValid(String nameLabelUser) throws Exception {
    String nameLabel = new String();

    nameLabel = nameLabelUser;

    Pattern p = Pattern.compile("\\s+");
    Matcher m = p.matcher(nameLabel);
    nameLabel = m.replaceAll("");

    nameLabel = nameLabel.replace("'", "");
    nameLabel = nameLabel.replace("\"", "");
    nameLabel = nameLabel.replace(" ", "_");
    nameLabel = nameLabel.replace(":", "_");
    nameLabel = nameLabel.replace(".", "_");
    nameLabel = nameLabel.replace("-", "_");

    String nameAux = nameLabel.toLowerCase();
    if (nameAux.startsWith("xml")) {
        nameLabel = nameLabel.substring(3);
    }
    p = Pattern.compile("[^A-ZÑa-zñ0-9_]+");
    m = p.matcher(nameLabel);
    nameLabel = m.replaceAll("");

    p = Pattern.compile("^[0-9]+");
    m = p.matcher(nameLabel);
    nameLabel = m.replaceAll("");


    return nameLabel;

}
 
Example #24
Source File: HttpServletProxyResponse.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public OutputStream getOutputStream() throws IOException {
  if (contentType != null && rewriteMap != null) {
    for (Map.Entry<Pattern, List<Pair<String, String>>> rewriteMapEntry : rewriteMap.entrySet()) {
      Matcher matcher = rewriteMapEntry.getKey().matcher(contentType);
      if (matcher.matches()) {
        return new RewriteOutputStream(httpServletResponse, rewriteMapEntry.getValue());
      }
    }
  }
  return httpServletResponse.getOutputStream();
}
 
Example #25
Source File: OutputAnalyzer.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the captured group of the first string matching the pattern.
 * stderr is searched before stdout.
 *
 * @param pattern The multi-line pattern to match
 * @param group The group to capture
 * @return The matched string or null if no match was found
 */
public String firstMatch(String pattern, int group) {
  Matcher stderrMatcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stderr);
  Matcher stdoutMatcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stdout);
  if (stderrMatcher.find()) {
    return stderrMatcher.group(group);
  }
  if (stdoutMatcher.find()) {
    return stdoutMatcher.group(group);
  }
  return null;
}
 
Example #26
Source File: CalciteMetaImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
static <T extends Named> Predicate1<T> namedMatcher(final Pat pattern) {
  if (pattern.s == null || pattern.s.equals("%")) {
    return Functions.truePredicate1();
  }
  final Pattern regex = likeToRegex(pattern);
  return v1 -> regex.matcher(v1.getName()).matches();
}
 
Example #27
Source File: Feature316.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@NoWarning("IIL_PATTERN_COMPILE_IN_LOOP")
public int countByPatternOk(List<String> list) {
    int count = 0;
    Pattern pattern = Pattern.compile("^test");
    for(String element : list) {
        if(pattern.matcher(element).matches()) count++;
    }
    return count;
}
 
Example #28
Source File: SearchPostFragment.java    From 4pdaClient-plus with Apache License 2.0 5 votes vote down vote up
@Override
public boolean shouldOverrideUrlLoading(WebView view, final String url) {

    if (url.contains("HTMLOUT.ru")) {
        Uri uri = Uri.parse(url);
        try {
            String function = uri.getPathSegments().get(0);
            String query = uri.getQuery();
            Class[] parameterTypes = null;
            String[] parameterValues = new String[0];
            if (!TextUtils.isEmpty(query)) {
                Matcher m = Pattern.compile("(.*?)=(.*?)(&|$)").matcher(query);
                ArrayList<String> objs = new ArrayList<>();

                while (m.find()) {
                    objs.add(m.group(2));
                }
                parameterValues = new String[objs.size()];
                parameterTypes = new Class[objs.size()];
                for (int i = 0; i < objs.size(); i++) {
                    parameterTypes[i] = String.class;
                    parameterValues[i] = objs.get(i);
                }
            }
            Method method = this.getClass().getMethod(function, parameterTypes);

            method.invoke(getMainActivity(), (Object[]) parameterValues);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    IntentActivity.tryShowUrl((Activity) getContext(), mHandler, url, true, false);

    return true;
}
 
Example #29
Source File: KafkaUtils.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
public static void waitForZkMntr(String clusterName, Pattern pattern, int... podIndexes) {
    long timeoutMs = 120_000L;
    long pollMs = 1_000L;

    for (int podIndex : podIndexes) {
        String zookeeperPod = KafkaResources.zookeeperPodName(clusterName, podIndex);
        String zookeeperPort = String.valueOf(12181);
        waitFor("mntr", pollMs, timeoutMs, () -> {
                try {
                    String output = cmdKubeClient().execInPod(zookeeperPod,
                        "/bin/bash", "-c", "echo mntr | nc localhost " + zookeeperPort).out();

                    if (pattern.matcher(output).find()) {
                        return true;
                    }
                } catch (KubeClusterException e) {
                    LOGGER.trace("Exception while waiting for ZK to become leader/follower, ignoring", e);
                }
                return false;
            },
            () -> LOGGER.info("zookeeper `mntr` output at the point of timeout does not match {}:{}{}",
                pattern.pattern(),
                System.lineSeparator(),
                indent(cmdKubeClient().execInPod(zookeeperPod, "/bin/bash", "-c", "echo mntr | nc localhost " + zookeeperPort).out()))
        );
    }
}
 
Example #30
Source File: PackingProcessor.java    From gdx-texture-packer-gui with Apache License 2.0 5 votes vote down vote up
private static void deleteOldFiles(PackModel packModel) throws Exception {
    String filename = obtainFilename(packModel);

    TexturePacker.Settings settings = packModel.getSettings();
    String atlasExtension = settings.atlasExtension == null ? "" : settings.atlasExtension;
    atlasExtension = Pattern.quote(atlasExtension);

    for (int i = 0, n = settings.scale.length; i < n; i++) {
        FileProcessor deleteProcessor = new FileProcessor() {
            protected void processFile (Entry inputFile) throws Exception {
                Files.delete(inputFile.inputFile.toPath());
            }
        };
        deleteProcessor.setRecursive(false);

        String scaledPackFileName = settings.getScaledPackFileName(filename, i);
        File packFile = new File(scaledPackFileName);

        String prefix = filename;
        int dotIndex = prefix.lastIndexOf('.');
        if (dotIndex != -1) prefix = prefix.substring(0, dotIndex);
        deleteProcessor.addInputRegex("(?i)" + prefix + "\\d*\\.(png|jpg|jpeg|ktx|zktx)");
        deleteProcessor.addInputRegex("(?i)" + prefix + atlasExtension);

        File outputRoot = new File(packModel.getOutputDir());
        String dir = packFile.getParent();
        if (dir == null)
            deleteProcessor.process(outputRoot, null);
        else if (new File(outputRoot + "/" + dir).exists()) //
            deleteProcessor.process(outputRoot + "/" + dir, null);
    }
}