List of usage examples for java.util.regex Pattern quote
public static String quote(String s)
From source file:com.eviware.soapui.support.Tools.java
public static boolean isSimilar(String expected, String real, char wildcard) throws ComparisonFailure { // expected == wildcard matches all if (!expected.equals(String.valueOf(wildcard))) { StringBuilder sb = new StringBuilder(); if (expected.startsWith(String.valueOf(wildcard))) { sb.append(".*"); }//from ww w. j a v a 2 s .c om boolean first = true; for (String token : expected.split(Pattern.quote(String.valueOf(wildcard)))) { if (token.isEmpty()) { continue; } if (!first) { sb.append(".*"); } first = false; sb.append(Pattern.quote(token)); } if (expected.endsWith(String.valueOf(wildcard))) { sb.append(".*"); } if (!Pattern.compile(sb.toString(), Pattern.DOTALL).matcher(real).matches()) { return false; } } return true; }
From source file:de.codesourcery.jasm16.utils.Misc.java
public static void printCompilationMarkers(ICompilationUnit unit, String source, boolean printStackTraces, final List<IMarker> errors) { if (errors.isEmpty()) { return;/*from w w w .j a v a2 s .com*/ } Collections.sort(errors, new Comparator<IMarker>() { @Override public int compare(IMarker o1, IMarker o2) { if (o1 instanceof CompilationMarker && o2 instanceof CompilationMarker) { CompilationMarker err1 = (CompilationMarker) o1; CompilationMarker err2 = (CompilationMarker) o2; final ITextRegion loc1 = err1.getLocation(); final ITextRegion loc2 = err2.getLocation(); if (loc1 != null && loc2 != null) { return Integer.valueOf(err1.getLocation().getStartingOffset()) .compareTo(Integer.valueOf(err2.getLocation().getStartingOffset())); } if (loc1 != null) { return -1; } else if (loc2 != null) { return 1; } return 0; } return 0; } }); for (Iterator<IMarker> it = errors.iterator(); it.hasNext();) { final IMarker tmp = it.next(); if (!(tmp instanceof CompilationMarker)) { continue; } final CompilationMarker error = (CompilationMarker) tmp; final int errorOffset; ITextRegion range; if (error.getLocation() != null) { range = error.getLocation(); errorOffset = range.getStartingOffset(); } else { errorOffset = error.getErrorOffset(); if (errorOffset != -1) { range = new TextRegion(errorOffset, 1); } else { range = null; } } int line = error.getLineNumber(); int column = error.getColumnNumber(); if (column == -1 && (error.getErrorOffset() != -1 && error.getLineStartOffset() != -1)) { column = error.getErrorOffset() - error.getLineStartOffset() + 1; } if ((line == -1 || column == -1) & errorOffset != -1) { try { SourceLocation location = unit.getSourceLocation(range); line = location.getLineNumber(); column = errorOffset - location.getLineStartOffset() + 1; if (column < 1) { column = -1; } } catch (Exception e) { // can't help it } } final boolean hasLocation = line != -1 && column != -1; final String severity = error.getSeverity() != null ? error.getSeverity().getLabel() + ": " : ""; final String locationString; if (hasLocation) { locationString = severity + "line " + line + ", column " + column + ": "; } else if (errorOffset != -1) { locationString = severity + "offset " + errorOffset + ": "; } else { locationString = severity + "< unknown location >: "; } boolean hasSource = false; String sourceLine = null; if (line != -1 || range != null) { Line thisLine = null; Line nextLine = null; if (line != -1) { try { thisLine = error.getCompilationUnit().getLineByNumber(line); IScanner scanner = new Scanner(source); scanner.setCurrentParseIndex(thisLine.getLineStartingOffset()); while (!scanner.eof() && scanner.peek() != '\n') { scanner.read(); } nextLine = new Line(line + 1, scanner.currentParseIndex()); } catch (Exception e) { // can't help it } if (thisLine != null && nextLine != null) { sourceLine = new TextRegion(thisLine.getLineStartingOffset(), nextLine.getLineStartingOffset() - thisLine.getLineStartingOffset()).apply(source); } else { sourceLine = range.apply(source); column = 1; } hasSource = true; } else { // range != null sourceLine = range.apply(source); column = 1; hasSource = true; } } if (hasSource) { sourceLine = sourceLine.replaceAll(Pattern.quote("\r\n"), "").replaceAll(Pattern.quote("\n"), "") .replaceAll("\t", " "); final String trimmedSourceLine = removeLeadingWhitespace(sourceLine); if (column != -1 && trimmedSourceLine.length() != sourceLine.length()) { column -= (sourceLine.length() - trimmedSourceLine.length()); } sourceLine = trimmedSourceLine; } String firstLine; String secondLine = null; if (hasLocation) { if (hasSource) { firstLine = locationString + sourceLine + "\n"; secondLine = StringUtils.repeat(" ", locationString.length()) + StringUtils.repeat(" ", (column - 1)) + "^ " + error.getMessage() + "\n"; } else { firstLine = locationString + error.getMessage(); } } else { firstLine = "Unknown error: " + error.getMessage(); } System.err.print(firstLine); if (secondLine != null) { System.err.print(secondLine); } System.out.println(); if (printStackTraces && error.getCause() != null) { error.getCause().printStackTrace(); } } }
From source file:MSUmpire.FragmentLib.FragmentLibManager.java
public void ImportFragLibByTSV(String tsv) throws IOException, XmlPullParserException, MatrixLoaderException { Logger.getRootLogger().info("Parsing " + tsv); BufferedReader reader = new BufferedReader(new FileReader(tsv)); PTMManager.GetInstance();// ww w . ja va 2s.co m String line = ""; ArrayList<FragmentPeak> FragmentPeaks = null; String[] header = reader.readLine().split("\t"); int modseqidx = -1; int seqidx = -1; int precchargeidx = -1; int precmzidx = -1; int irtidx = -1; int fragtypeidx = -1; int fragnumidx = -1; int fraglossidx = -1; int fragmzidx = -1; int fragchargeidx = -1; int fragintidx = -1; for (int i = 0; i < header.length; i++) { switch (header[i]) { case "ModifiedSequence": { modseqidx = i; break; } case "StrippedSequence": { seqidx = i; break; } case "PrecursorCharge": { precchargeidx = i; break; } case "PrecursorMz": { precmzidx = i; break; } case "iRT": { irtidx = i; break; } case "FragmentType": { fragtypeidx = i; break; } case "FragmentNumber": { fragnumidx = i; break; } case "FI.FrgLossType": { fraglossidx = i; break; } case "FragmentCharge": { fragchargeidx = i; break; } case "FragmentMz": { fragmzidx = i; break; } case "RelativeFragmentIntensity": { fragintidx = i; break; } } } String lastpep = ""; PepFragmentLib fraglib = null; while ((line = reader.readLine()) != null) { String[] info = line.split("\t"); if (!lastpep.equals(info[modseqidx])) { if (fraglib != null && FragmentPeaks != null) { fraglib.AddFragments(FragmentPeaks); if (PeptideFragmentLib.containsKey(fraglib.GetKey())) { Logger.getRootLogger().warn("Peptide ion :" + fraglib.GetKey() + " is already in the library.(" + lastpep + ")"); } else { PeptideFragmentLib.put(fraglib.GetKey(), fraglib); } } fraglib = new PepFragmentLib(); FragmentPeaks = new ArrayList<>(); fraglib.Charge = Integer.parseInt(info[precchargeidx]); fraglib.PrecursorMz = Float.parseFloat(info[precmzidx]); fraglib.RetentionTime.add(Float.parseFloat(info[irtidx])); fraglib.Sequence = info[seqidx]; fraglib.ModSequence = fraglib.Sequence; String modseq = info[modseqidx]; lastpep = modseq; modseq = modseq.substring(1, modseq.length() - 1); while (modseq.contains("[")) { if (modseq.contains("M[Ox]")) { ModificationInfo mapmod = new ModificationInfo(); mapmod.modification = PTMManager.GetInstance().GetPTM("M", 15.9f); mapmod.massdiff = (float) mapmod.modification.getMass(); mapmod.site = "M"; int temp = modseq.indexOf("M[Ox]") + 1; boolean inmod = false; int idx = 0; for (int i = 0; i < temp; i++) { if (modseq.charAt(i) == '[') { inmod = true; } else if (modseq.charAt(i) == ']') { inmod = false; continue; } if (!inmod) { idx++; } } fraglib.Modifications.add(new ModificationMatch(mapmod.modification.getName(), true, idx)); modseq = modseq.replaceFirst(Pattern.quote("M[Ox]"), "M"); fraglib.ModSequence = ModStringConvert.AddModIntoSeqBeforeSite(fraglib.ModSequence, mapmod.GetKey(), idx - 1); } else if (modseq.contains("C[CAM]")) { ModificationInfo mapmod = new ModificationInfo(); mapmod.modification = PTMManager.GetInstance().GetPTM("C", 57f); mapmod.massdiff = (float) mapmod.modification.getMass(); mapmod.site = "C"; int temp = modseq.indexOf("C[CAM]") + 1; boolean inmod = false; int idx = 0; for (int i = 0; i < temp; i++) { if (modseq.charAt(i) == '[') { inmod = true; } else if (modseq.charAt(i) == ']') { inmod = false; continue; } if (!inmod) { idx++; } } fraglib.Modifications.add(new ModificationMatch(mapmod.modification.getName(), true, idx)); modseq = modseq.replaceFirst(Pattern.quote("C[CAM]"), "C"); fraglib.ModSequence = ModStringConvert.AddModIntoSeqBeforeSite(fraglib.ModSequence, mapmod.GetKey(), idx - 1); } else if (modseq.contains("[NtermAc]")) { ModificationInfo mapmod = new ModificationInfo(); mapmod.modification = PTMManager.GetInstance().GetPTM("N-term", 42f); mapmod.massdiff = (float) mapmod.modification.getMass(); mapmod.site = "N-term"; int idx = 1; fraglib.Modifications.add(new ModificationMatch(mapmod.modification.getName(), true, idx)); modseq = modseq.replaceFirst(Pattern.quote("[NtermAc]"), ""); fraglib.ModSequence = ModStringConvert.AddModIntoSeqBeforeSite(fraglib.ModSequence, mapmod.GetKey(), idx - 1); } else { Logger.getRootLogger().error("modification is not recognized:" + modseq); System.exit(1); } } } FragmentPeak fragment = new FragmentPeak(); fragment.FragMZ = Float.parseFloat(info[fragmzidx]); fragment.intensity = Float.parseFloat(info[fragintidx]); fragment.Charge = Integer.parseInt(info[fragchargeidx]); //fragment.IonType = info[fragtypeidx] + info[fragnumidx] +"_"+ info[fraglossidx]; fragment.IonType = info[fragtypeidx] + info[fragnumidx]; FragmentPeaks.add(fragment); } if (fraglib != null && FragmentPeaks != null) { fraglib.AddFragments(FragmentPeaks); if (PeptideFragmentLib.containsKey(fraglib.GetKey())) { Logger.getRootLogger().warn("Peptide ion :" + fraglib.GetKey() + " is already in the library."); } else { PeptideFragmentLib.put(fraglib.GetKey(), fraglib); } } Logger.getRootLogger().info("No. of peptide ions in the imported library:" + PeptideFragmentLib.size()); CheckDecoys(); }
From source file:org.apache.maven.plugin.javadoc.JavadocUtil.java
/** * Method that gets the complete package names (including subpackages) of the packages that were defined * in the excludePackageNames parameter. * * @param sourceDirectory the directory where the source files are located * @param excludePackagenames package names to be excluded in the javadoc * @return a List of the packagenames to be excluded *//* w w w. jav a 2 s. c o m*/ protected static List<String> getExcludedPackages(String sourceDirectory, String[] excludePackagenames) { List<String> files = new ArrayList<String>(); for (String excludePackagename : excludePackagenames) { String[] fileList = FileUtils.getFilesFromExtension(sourceDirectory, new String[] { "java" }); for (String aFileList : fileList) { String[] excludeName = excludePackagename.split("[*]"); int u = 0; while (u < excludeName.length) { if (!"".equals(excludeName[u].trim()) && aFileList.contains(excludeName[u]) && !sourceDirectory.contains(excludeName[u])) { files.add(aFileList); } u++; } } } List<String> excluded = new ArrayList<String>(); for (String file : files) { int idx = file.lastIndexOf(File.separatorChar); String tmpStr = file.substring(0, idx); tmpStr = tmpStr.replace('\\', '/'); String[] srcSplit = tmpStr.split(Pattern.quote(sourceDirectory.replace('\\', '/') + '/')); String excludedPackage = srcSplit[1].replace('/', '.'); if (!excluded.contains(excludedPackage)) { excluded.add(excludedPackage); } } return excluded; }
From source file:net.dv8tion.jda.core.entities.impl.ReceivedMessage.java
@Override public String getContentDisplay() { if (altContent != null) return altContent; synchronized (mutex) { if (altContent != null) return altContent; String tmp = content;/*from ww w . jav a 2 s. co m*/ for (User user : getMentionedUsers()) { String name; if (isFromType(ChannelType.TEXT) && getGuild().isMember(user)) name = getGuild().getMember(user).getEffectiveName(); else name = user.getName(); tmp = tmp.replaceAll("<@!?" + Pattern.quote(user.getId()) + '>', '@' + Matcher.quoteReplacement(name)); } for (Emote emote : getEmotes()) { tmp = tmp.replace(emote.getAsMention(), ":" + emote.getName() + ":"); } for (TextChannel mentionedChannel : getMentionedChannels()) { tmp = tmp.replace(mentionedChannel.getAsMention(), '#' + mentionedChannel.getName()); } for (Role mentionedRole : getMentionedRoles()) { tmp = tmp.replace(mentionedRole.getAsMention(), '@' + mentionedRole.getName()); } return altContent = tmp; } }
From source file:com.fujitsu.dc.test.jersey.box.odatacol.batch.UserDataBatchLinkTest.java
private String retrieveChangesetErrorResponse(int statusCode, String code, String message) { return "Content-Type: multipart/mixed; " + "boundary=changeset_cLzcDEEVPwvvoxS3yJTFTpRauSK_FAQ6mQtyo0aby93-SDP3lAs2A19a2uBb\n\n" + "--changeset_cLzcDEEVPwvvoxS3yJTFTpRauSK_FAQ6mQtyo0aby93-SDP3lAs2A19a2uBb\n" + "Content-Type: application/http\n" + "Content-Transfer-Encoding: binary\n\n" + "HTTP/1.1 " + String.valueOf(statusCode) + " \n" + "Content-Type: application/json\n\n" + "\\{\"code\":\"" + code + "\",\"message\":\\{\"lang\":\"en\",\"value\":\"" + Pattern.quote(message) + ".*\n\n" + "--changeset_cLzcDEEVPwvvoxS3yJTFTpRauSK_FAQ6mQtyo0aby93-SDP3lAs2A19a2uBb--\n\n"; }
From source file:com.roche.sequencing.bioinformatics.common.utils.FileUtil.java
/** * taken from here http://codereview.stackexchange.com/questions/47923/simplifying-a-path -Kurt Heilman * //from w w w. ja va 2 s. com * @param path * @return */ public static String simplifyPath(String path) { String simplifiedPath = null; Deque<String> pathDeterminer = new ArrayDeque<String>(); path = path.replaceAll(Pattern.quote("\\"), "/"); path = path.replaceAll(Pattern.quote("\\\\"), "/"); String[] pathSplitter = path.split("/"); StringBuilder absolutePath = new StringBuilder(); for (String term : pathSplitter) { if (term == null || term.length() == 0 || term.equals(".")) { /* ignore these guys */ } else if (term.equals("..")) { if (pathDeterminer.size() > 0) { pathDeterminer.removeLast(); } } else { pathDeterminer.addLast(term); } } if (pathDeterminer.isEmpty()) { simplifiedPath = "/"; } else { while (!pathDeterminer.isEmpty()) { absolutePath.insert(0, pathDeterminer.removeLast()); absolutePath.insert(0, "/"); } simplifiedPath = absolutePath.toString(); } return simplifiedPath; }
From source file:com.adobe.acs.commons.mcp.impl.processes.PageRelocator.java
private String convertSourceToDestination(String path) { return path.replaceAll(Pattern.quote(sourcePath), destinationPath); }
From source file:dk.netarkivet.harvester.datamodel.Job.java
/** * Adds a configuration to this Job. Seedlists and settings are updated accordingly. */*from w w w . j a va2 s.c o m*/ * @param cfg the configuration to add * @throws ArgumentNotValid if cfg is null or cfg uses a different orderxml than this job or if this job already * contains a configuration associated with domain of configuration cfg. */ public void addConfiguration(DomainConfiguration cfg) { ArgumentNotValid.checkNotNull(cfg, "cfg"); if (domainConfigurationMap.containsKey(cfg.getDomainName())) { throw new ArgumentNotValid("Job already has a configuration for Domain " + cfg.getDomainName()); } if (log.isTraceEnabled()) { log.trace("Adding configuration '{}' to job '{}'", cfg, cfg.getName()); } if (!underConstruction) { final String msg = "Cannot modify job " + this + " as it is no longer under construction"; log.debug(msg); throw new IllegalState(msg); } if (!cfg.getOrderXmlName().equals(getOrderXMLName())) { throw new ArgumentNotValid("Job requires the orderxml file:'" + getOrderXMLName() + "' not:'" + cfg.getOrderXmlName() + "' used by the configuration:'" + cfg.getName()); } domainConfigurationMap.put(cfg.getDomainName(), cfg.getName()); // Add the seeds from the configuration to the Job seeds. // Take care of duplicates. for (Iterator<SeedList> itt = cfg.getSeedLists(); itt.hasNext();) { SeedList seed = itt.next(); List<String> seeds = seed.getSeeds(); for (String seedUrl : seeds) { seedListSet.add(seedUrl); // duplicates is silently ignored // TODO remove when heritrix implements this functionality // try to convert a seed into a Internationalized Domain Name try { String seedASCII = seedUrl; // It is rare to see these seeds, but they need to be // correctly idnaized if (seedUrl.contains(":") || seedUrl.contains("/")) { String normalizedUrl = seedUrl; if (!normalizedUrl.matches("^[a-zA-Z]+:.*")) { // If no protocol is given, assume http normalizedUrl = "http://" + normalizedUrl; } URL url = new URL(normalizedUrl); String domainName = url.getHost(); String domainNameASCII = IDNA.toASCII(domainName); if (!domainName.equals(domainNameASCII)) { // If the domain name changed, replace that in the // seed. seedASCII = seedUrl.replaceFirst(Pattern.quote(domainName), domainNameASCII); } } else { seedASCII = IDNA.toASCII(seedUrl); } if (!seedASCII.equals(seedUrl)) { log.trace("Converted {} to {}", seedUrl, seedASCII); // Note that duplicates is silently ignored seedListSet.add(seedASCII); } } catch (IDNAException e) { log.trace("Cannot convert seed {} to ASCII", seedUrl, e); } catch (MalformedURLException e) { log.trace("Cannot convert seed {} to ASCII", seedUrl, e); } } } orderXMLdoc.editOrderXMLAddPerDomainCrawlerTraps(cfg); // TODO update limits in settings files - see also bug 269 // Update estimates of job size long expectation = cfg.getExpectedNumberOfObjects(forceMaxObjectsPerDomain, forceMaxBytesPerDomain); maxCountObjects = Math.max(expectation, maxCountObjects); minCountObjects = Math.min(expectation, minCountObjects); totalCountObjects += expectation; configsChanged = true; assert (maxCountObjects >= minCountObjects) : "basic invariant"; }
From source file:com.adobe.acs.commons.mcp.impl.processes.PageRelocator.java
private String reversePathLookup(String path) { if (path.startsWith(destinationPath)) { return path.replaceAll(Pattern.quote(destinationPath), sourcePath); } else {//ww w .ja v a 2 s .c o m return path; } }