List of usage examples for java.util.regex Matcher replaceFirst
public String replaceFirst(Function<MatchResult, String> replacer)
From source file:net.paissad.waqtsalat.utils.UncompressUtils.java
/** * Implements different methods used to uncompress a file. * /* w ww . ja v a 2s. co m*/ * @param method * Method to use for uncompressing the file. Available methods * are GUNZIP_METHOD, BUNZIP_METHOD. * @return File that has been created after the decompression process. * @throws IOException * @see #gunzip * @see #bunzip2 */ private File uncompress(final String method) throws IOException { try { logger.info("Uncompressing file '{}' ...", source.getAbsolutePath()); // We must set the destination filename, if not set before ! if (this.dest == null) { logger.trace("'dest' file is null ..."); Pattern pattern; String outputFileName; if (method.equals(BUNZIP_METHOD)) { pattern = Pattern.compile(REGEX_DEFAULT_EXTENSION_BZIP, Pattern.CASE_INSENSITIVE); } else if (method.equals(GUNZIP_METHOD)) { pattern = Pattern.compile(REGEX_DEFAULT_EXTENSION_GZIP, Pattern.CASE_INSENSITIVE); } else if (method.equals(TAR_METHOD)) { pattern = Pattern.compile(REGEX_DEFAULT_EXTENSION_TAR); } else { throw new RuntimeException("Unsupported method '" + method + "'."); } // Set output filename. Matcher matcher = pattern.matcher(source.getAbsolutePath()); if (source.toString().toLowerCase().endsWith(".tgz")) { outputFileName = matcher.replaceFirst(".tar"); } else { outputFileName = matcher.replaceFirst(""); } dest = new File(outputFileName); } // GZIP and BZIP2 (decompression) if (method.equals(BUNZIP_METHOD) || method.equals(GUNZIP_METHOD)) { dest = inputstreamToFile(uncompressStream(method), dest, CLOSE_STREAM); } // TAR (decompression) else if (method.equals(TAR_METHOD)) { TarInputStream tis = (TarInputStream) uncompressStream(TAR_METHOD); try { TarEntry tarEntry = tis.getNextEntry(); while (tarEntry != null) { File destPath = new File(dest.getParent() + File.separatorChar + tarEntry.getName()); if (tarEntry.isDirectory()) { destPath.mkdir(); } else { if (!destPath.getParentFile().exists()) { destPath.getParentFile().mkdirs(); } logger.trace("untar: '{}'", destPath); FileOutputStream fos = new FileOutputStream(destPath); try { tis.copyEntryContents(fos); } finally { fos.flush(); fos.close(); } } tarEntry = tis.getNextEntry(); } } catch (IOException ioe) { ioe.printStackTrace(); throw new IOException("Untar failed."); } finally { if (tis != null) tis.close(); } } // End of tar method. } catch (IOException ioe) { ioe.printStackTrace(); throw new IOException("Uncompressing file '" + source.getAbsolutePath() + "' failed."); } logger.info("Uncompressing file '{}' finished successfully.", source.getAbsolutePath()); return dest; }
From source file:org.openmrs.module.patientflags.evaluator.SQLFlagEvaluator.java
/** * @see org.openmrs.module.patientflags.evaluator.FlagEvaluator#eval(Flag, Patient) *//*from w w w . jav a 2 s . c o m*/ public Boolean eval(Flag flag, Patient patient) { if (patient.isVoided()) throw new APIException("Unable to evaluate SQL flag " + flag.getName() + " against voided patient"); String criteria = flag.getCriteria(); // pull out the "*.patient_id" clause // is this robust enough? Matcher matcher = Pattern.compile("(\\w+\\.patient_id)").matcher(criteria); matcher.find(); // just check for the first occurrence of the pattern... is this enough? String patientIdColumn = matcher.group(); // since we are going to append a where/and to the end of this sql statement, we need to trim off trailing ";" and any trailing whitespace matcher = Pattern.compile(";?\\s*$").matcher(criteria); criteria = matcher.replaceFirst(""); // replace first, because there should only be one occurrence // create the criteria for a single patient by appending a "where" or "and" clause String toEval = criteria + (criteria.matches("(?i)(?s).*where.*") ? " and " : " where ") + patientIdColumn + " = " + patient.getPatientId(); try { Context.addProxyPrivilege("SQL Level Access"); List<List<Object>> resultSet = Context.getAdministrationService().executeSQL(toEval, true); // if the list is empty, return false, otherwise, return true return !resultSet.isEmpty(); } catch (Exception e) { throw new APIException("Unable to evaluate SQL Flag " + flag.getName() + ", " + e.getLocalizedMessage(), e); } finally { Context.removeProxyPrivilege("SQL Level Access"); } }
From source file:com.adgear.data.plugin.IDLSchemaMojo.java
/** * Factory method for generating instances of IDLObject * * @param name File name//from www. j a v a 2 s .c o m * @param source IDL source code */ protected IDLObject generateIdlObject(String name, String source) { getLog().debug("Preprocessing file " + name); String namespaceAnnotationRegex = "(?<!\\w)@namespace\\(\"[a-zA-Z0-9$_\\.]+\"\\)"; Matcher m = Pattern.compile(namespaceAnnotationRegex, Pattern.MULTILINE).matcher(source); while (m.find()) { getLog().warn("Ignoring @namespace annotation '" + m.group(1) + "'"); source = m.replaceFirst(" "); } String namespace = name.replaceFirst("\\.[^\\.]+$", ""); return new IDLObject(name, "@namespace(\"" + namespace + "\")\n" + source.trim(), collectDependencies(source)); }
From source file:org.openmrs.module.patientflags.evaluator.SQLFlagEvaluator.java
@Override public String evalMessage(Flag flag, int patientId) { String literal = "\\$\\{\\d{1,2}\\}"; String message = flag.getMessage(); if (!message.matches(".*(" + literal + ")+.*")) { return message; }/* www .ja va 2 s .c om*/ log.info("Replacing values in " + message); Patient p = Context.getPatientService().getPatient(patientId); if (p.isVoided()) throw new APIException("VOIDED PATIENT"); String criteria = flag.getCriteria(); // pull out the "*.patient_id" clause // is this robust enough? Matcher matcher = Pattern.compile("(\\w+\\.patient_id)").matcher(criteria); matcher.find(); // just check for the first occurrence of the pattern... is this enough? String patientIdColumn = matcher.group(); // since we are going to append a where/and to the end of this sql statement, we need to trim off trailing ";" and any trailing whitespace matcher = Pattern.compile(";?\\s*$").matcher(criteria); criteria = matcher.replaceFirst(""); // replace first, because there should only be one occurrence // create the criteria for a single patient by appending a "where" or "and" clause String toEval = criteria + (criteria.matches("(?i)(?s).*where.*") ? " and " : " where ") + patientIdColumn + " = " + p.getPatientId(); try { Context.addProxyPrivilege("SQL Level Access"); List<List<Object>> resultSet = Context.getAdministrationService().executeSQL(toEval, true); // list would for sure contain one only one patient if (!resultSet.isEmpty()) {// empty resultset means no one matched the criteria Matcher m = Pattern.compile(literal).matcher(message); while (!m.hitEnd() && m.find()) {// replace each instance until end String replaceString = m.group(); try { //get index between the brackets ${indexNumber} int index = Integer.parseInt(replaceString.replace("${", "").replace("}", "")); if (index < resultSet.get(0).size()) {// do nothing if index is invalid message = message.replace(replaceString, resultSet.get(0).get(index).toString()); log.info("Replaced " + replaceString + " ON " + index); } } catch (Exception e) { //do nothing. text would remain unreplaced } } } else { log.info("result set empty"); } } catch (Exception e) { throw new APIException( "Unable to evaluate SQL Flag Message" + flag.getName() + ", " + e.getLocalizedMessage(), e); } finally { Context.removeProxyPrivilege("SQL Level Access"); } return message; }
From source file:org.jenkinsci.plugins.androidsigning.SignApksBuilder.java
@Override public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException { if (isIntermediateFailure(run)) { listener.getLogger()/*from ww w .ja v a 2 s . c o m*/ .println("[SignApksBuilder] skipping Sign APKs step because a previous step failed"); return; } if (getEntries() != null && !getEntries().isEmpty()) { List<SignApksBuilder> newModelBuilders = singleEntryBuildersFromEntriesOfBuilder(this); for (SignApksBuilder builder : newModelBuilders) { builder.perform(run, workspace, launcher, listener); } return; } EnvVars env; if (run instanceof AbstractBuild) { env = run.getEnvironment(listener); env.overrideAll(((AbstractBuild<?, ?>) run).getBuildVariables()); } else { env = new EnvVars(); } FilePath builderDir = workspace.child(BUILDER_DIR); String excludeBuilderDir = builderDir.getName() + "/**"; ZipalignTool zipalign = new ZipalignTool(env, workspace, listener.getLogger(), androidHome, zipalignPath); Map<String, String> apksToArchive = new LinkedHashMap<>(); StandardCertificateCredentials keyStoreCredential = getKeystore(getKeyStoreId(), run.getParent()); char[] storePassword = keyStoreCredential.getPassword().getPlainText().toCharArray(); // TODO: add key password support char[] keyPassword = storePassword; KeyStore keyStore = keyStoreCredential.getKeyStore(); String alias = getKeyAlias(); PrivateKey key; Certificate[] certChain; try { if (getKeyAlias() == null) { // TODO: search all entries to find key, throw error if multiple keys } key = (PrivateKey) keyStore.getKey(alias, keyPassword); certChain = keyStore.getCertificateChain(alias); } catch (GeneralSecurityException e) { PrintWriter details = listener.fatalError("Error reading keystore " + getKeyStoreId()); e.printStackTrace(details); throw new AbortException("Error reading keystore " + getKeyStoreId()); } if (key == null || certChain == null) { throw new AbortException("Alias " + alias + " does not exist or does not point to a key and certificate in certificate credentials " + getKeyStoreId()); } String v1SigName = alias; if (v1SigName == null) { v1SigName = keyStoreCredential.getId(); } Set<FilePath> matchedApks = new TreeSet<>(Comparator.comparing(FilePath::getRemote)); String[] globs = getSelectionGlobs(); for (String glob : globs) { FilePath[] globMatch = workspace.list(glob, excludeBuilderDir); if (globMatch.length == 0) { throw new AbortException("No APKs in workspace matching " + glob); } matchedApks.addAll(Arrays.asList(globMatch)); } for (FilePath unsignedApk : matchedApks) { unsignedApk = unsignedApk.absolutize(); FilePath archiveDir = builderDir.child(unsignedApk.getName()); if (archiveDir.isDirectory()) { archiveDir.deleteContents(); } else { archiveDir.mkdirs(); } String archiveDirRelName = relativeToWorkspace(workspace, archiveDir); String unsignedPathName = unsignedApk.getRemote(); Pattern stripUnsignedPattern = Pattern.compile("(-?unsigned)?.apk$", Pattern.CASE_INSENSITIVE); Matcher stripUnsigned = stripUnsignedPattern.matcher(unsignedApk.getName()); String strippedApkName = stripUnsigned.replaceFirst(""); String alignedRelName = archiveDirRelName + "/" + strippedApkName + "-aligned.apk"; String signedRelName = archiveDirRelName + "/" + strippedApkName + "-signed.apk"; ArgumentListBuilder zipalignCommand = zipalign.commandFor(unsignedPathName, alignedRelName); listener.getLogger().printf("[SignApksBuilder] %s%n", zipalignCommand); int zipalignResult = launcher.launch().cmds(zipalignCommand).pwd(workspace).stdout(listener) .stderr(listener.getLogger()).join(); if (zipalignResult != 0) { listener.fatalError("[SignApksBuilder] zipalign failed: exit code %d", zipalignResult); throw new AbortException( String.format("zipalign failed on APK %s: exit code %d", unsignedPathName, zipalignResult)); } FilePath alignedPath = workspace.child(alignedRelName); if (!alignedPath.exists()) { throw new AbortException(String.format("aligned APK does not exist: %s", alignedRelName)); } listener.getLogger().printf("[SignApksBuilder] signing APK %s%n", alignedRelName); FilePath signedPath = workspace.child(signedRelName); final SignApkCallable signApk = new SignApkCallable(key, certChain, v1SigName, signedPath.getRemote(), listener); alignedPath.act(signApk); listener.getLogger().printf("[SignApksBuilder] signed APK %s%n", signedRelName); if (getArchiveUnsignedApks()) { listener.getLogger().printf("[SignApksBuilder] archiving unsigned APK %s%n", unsignedPathName); apksToArchive.put(archiveDirRelName + "/" + unsignedApk.getName(), relativeToWorkspace(workspace, unsignedApk)); } if (getArchiveSignedApks()) { listener.getLogger().printf("[SignApksBuilder] archiving signed APK %s%n", signedRelName); apksToArchive.put(signedRelName, signedRelName); } } listener.getLogger().println("[SignApksBuilder] finished signing APKs"); if (apksToArchive.size() > 0) { run.pickArtifactManager().archive(workspace, launcher, BuildListenerAdapter.wrap(listener), apksToArchive); } }
From source file:org.rhq.enterprise.server.plugins.alertOperations.AlertTokenReplacer.java
/** * Replace all tokens on the input line. If no tokens are found the input is returned. * Tokens have the form '<i><% class.sub %></i>' * @param input a line of text//from ww w. java 2 s. c om * @return input with tokens replaced. * @see org.rhq.enterprise.server.plugins.alertOperations.Token * @see org.rhq.enterprise.server.plugins.alertOperations.TokenClass */ public String replaceTokens(String input) { String work = input; Matcher matcher = pattern.matcher(work); if (!matcher.find()) { if (log.isDebugEnabled()) { log.debug("No tokens found in " + input); } return input; } matcher.reset(); do { matcher = pattern.matcher(work); if (!matcher.find()) { break; } String replacement = replaceToken(matcher.group(1)); String s = matcher.replaceFirst(replacement); work = s; } while (true); return work; }
From source file:com.cloudera.impala.planner.PlannerTestBase.java
/** * Normalize components of the given file path, removing any environment- or test-run * dependent components. For example, substitutes the unique id portion of Impala * generated file names with a fixed literal. Subclasses should override to do * filesystem specific cleansing./*from w w w. ja v a2s . c om*/ */ protected Path cleanseFilePath(Path path) { String fileName = path.getName(); Pattern pattern = Pattern.compile("\\w{16}-\\w{16}_\\d+_data"); Matcher matcher = pattern.matcher(fileName); fileName = matcher.replaceFirst("<UID>_data"); return new Path(path.getParent(), fileName); }
From source file:jenkins.model.RunIdMigrator.java
/** Inverse of {@link #doMigrate}. */ private void unmigrateBuildsDir(File builds) throws Exception { File mapFile = new File(builds, MAP_FILE); if (!mapFile.isFile()) { System.err.println(builds + " does not look to have been migrated yet; skipping"); return;// w w w .java2s . c om } for (File build : builds.listFiles()) { int number; try { number = Integer.parseInt(build.getName()); } catch (NumberFormatException x) { continue; } File buildXml = new File(build, "build.xml"); if (!buildXml.isFile()) { System.err.println(buildXml + " did not exist"); continue; } String xml = FileUtils.readFileToString(buildXml, Charsets.UTF_8); Matcher m = TIMESTAMP_ELT.matcher(xml); if (!m.find()) { System.err.println(buildXml + " did not contain <timestamp> as expected"); continue; } long timestamp = Long.parseLong(m.group(1)); String nl = m.group(2); xml = m.replaceFirst(" <number>" + number + "</number>" + nl); m = ID_ELT.matcher(xml); String id; if (m.find()) { id = m.group(1); xml = m.replaceFirst(""); } else { // Post-migration build. We give it a new ID based on its timestamp. id = legacyIdFormatter.format(new Date(timestamp)); } FileUtils.write(buildXml, xml, Charsets.UTF_8); if (!build.renameTo(new File(builds, id))) { System.err.println(build + " could not be renamed"); } Util.createSymlink(builds, id, Integer.toString(number), StreamTaskListener.fromStderr()); } Util.deleteFile(mapFile); System.err.println(builds + " has been restored to its original format"); }
From source file:org.cloudfoundry.identity.uaa.scim.JdbcScimUserProvisioning.java
private String makeBooleans(String where, Pattern pattern, String template, Map<String, Object> values) { String output = where;/*from w w w .j a v a 2 s . c o m*/ Matcher matcher = pattern.matcher(output); int count = values.size(); while (matcher.matches()) { values.put("value" + count, Boolean.valueOf(matcher.group(3).toLowerCase())); String query = template.replace("?", "value" + count); output = matcher .replaceFirst(String.format(query, matcher.group(1), matcher.group(2), matcher.group(4))); matcher = pattern.matcher(output); count++; } return output; }
From source file:password.pwm.http.servlet.resource.ResourceFileServlet.java
private String stripNonceFromURI(final ResourceServletConfiguration resourceServletConfiguration, final String uriString) { if (!resourceServletConfiguration.isEnablePathNonce()) { return uriString; }/*w w w .j av a2 s . c o m*/ final Matcher theMatcher = resourceServletConfiguration.getNoncePattern().matcher(uriString); if (theMatcher.find()) { return theMatcher.replaceFirst(""); } return uriString; }