Example usage for java.lang String replaceFirst

List of usage examples for java.lang String replaceFirst

Introduction

In this page you can find the example usage for java.lang String replaceFirst.

Prototype

public String replaceFirst(String regex, String replacement) 

Source Link

Document

Replaces the first substring of this string that matches the given regular expression with the given replacement.

Usage

From source file:Main.java

/**
 * @brief      Converting the url to lower case.
 * //w  w w  .jav  a2  s .  c  o m
 * @param      strUrl   [IN]  url path
 * 
 * @return     Return modificated url string
 */
public static String fixUrl(String inUrl) {
    if (inUrl == null) {
        return null;
    }

    int colon = inUrl.indexOf(':');
    boolean allLower = true;

    if (colon == -1) {
        inUrl = "http://" + inUrl;
    }
    for (int index = 0; index < colon; index++) {
        char ch = inUrl.charAt(index);
        if (!Character.isLetter(ch)) {
            break;
        }
        allLower &= Character.isLowerCase(ch);
        if (index == colon - 1 && !allLower) {
            inUrl = inUrl.substring(0, colon).toLowerCase() + inUrl.substring(colon);
        }
    }
    if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
        return inUrl;
    if (inUrl.startsWith("http:") || inUrl.startsWith("https:")) {
        if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
            inUrl = inUrl.replaceFirst("/", "//");
        } else
            inUrl = inUrl.replaceFirst(":", "://");
    }
    return inUrl;
}

From source file:com.centurylink.mdw.services.util.AuthUtils.java

/**
 * @return true if no authentication at all or authentication is successful
 *///  w  w  w  . j  a va  2 s .c o m
private static boolean checkBasicAuthenticationHeader(String authorizationHeader, Map<String, String> headers) {
    String user = "Unknown";
    try {
        // Do NOT try to authenticate if it's not Basic auth
        if (authorizationHeader == null || !authorizationHeader.startsWith("Basic"))
            throw new Exception("Invalid Basic Auth Header"); // This should never happen

        authorizationHeader = authorizationHeader.replaceFirst("Basic ", "");

        byte[] valueDecoded = Base64.decodeBase64(authorizationHeader.getBytes());
        authorizationHeader = new String(valueDecoded);

        String[] creds = authorizationHeader.split(":");

        if (creds.length < 2)
            throw new Exception("Invalid Basic Auth Header");

        user = creds[0];
        String pass = creds[1];

        if (ApplicationContext.isMdwAuth()) {
            if (PackageCache.getPackage(CTLJWTPKG) == null)
                throw new Exception("Basic Auth is not allowed when authMethod is mdw");

            String token = null;
            CacheService jwtTokenCacheInstance = CacheRegistration.getInstance().getCache(JWTTOKENCACHE);
            try {
                Method compiledAssetGetter = jwtTokenCacheInstance.getClass().getMethod("getToken",
                        String.class, String.class);
                token = (String) compiledAssetGetter.invoke(jwtTokenCacheInstance, user, pass);
            } catch (Exception ex) {
                logger.severeException("Exception trying to retreieve App token from cache", ex);
            }
            boolean validated = false;
            if (!StringHelper.isEmpty(token)) { // Use token if this user was already validated
                try {
                    // Use cached token
                    verifyMdwJWT(token, headers);
                    validated = true;
                } catch (Exception e) {
                } // Token might be expired or some other issue with it - re-authenticate
            }
            if (!validated) {
                // Authenticate using com/centurylink/mdw/central/auth service hosted in MDW Central
                com.centurylink.mdw.model.workflow.Package pkg = PackageCache.getPackage(CTLJWTPKG);
                Authenticator jwtAuth = (Authenticator) CompiledJavaCache.getInstance(CTLJWTAUTH,
                        pkg.getCloudClassLoader(), pkg);
                jwtAuth.authenticate(user, pass); // This will populate JwtTokenCache with token for next time
            }
        } else {
            ldapAuthenticate(user, pass);
        }

        headers.put(Listener.AUTHENTICATED_USER_HEADER, user);
        if (logger.isDebugEnabled()) {
            logger.debug("authentication successful for user '" + user + "'");
        }
    } catch (Exception ex) {
        if (!ApplicationContext.isDevelopment()) {
            headers.put(Listener.AUTHENTICATION_FAILED,
                    "Authentication failed for '" + user + "'. " + ex.getMessage());
            logger.severeException("Authentication failed for user '" + user + "'. " + ex.getMessage(), ex);
        }
        return false;
    }
    return true;
}

From source file:com.github.mjdetullio.jenkins.plugins.multibranch.TemplateDrivenMultiBranchProject.java

/**
 * Migrates {@code SyncBranchesTrigger} to {@link hudson.triggers.TimerTrigger} and copies the
 * template's {@code hudson.security.AuthorizationMatrixProperty} to the parent as a
 * {@code com.cloudbees.hudson.plugins.folder.properties.AuthorizationMatrixProperty}.
 *
 * @throws IOException if errors reading/modifying files during migration
 *///  w  w  w  . j ava2  s  .c o  m
@SuppressWarnings(UNUSED)
@Initializer(before = InitMilestone.PLUGINS_STARTED)
public static void migrate() throws IOException {
    final String projectAmpStartTag = "<hudson.security.AuthorizationMatrixProperty>";

    final File projectsDir = new File(Jenkins.getActiveInstance().getRootDir(), "jobs");

    if (!projectsDir.getCanonicalFile().isDirectory()) {
        return;
    }

    List<File> configFiles = getConfigFiles(projectsDir);

    for (final File configFile : configFiles) {
        String xml = FileUtils.readFileToString(configFile);

        // Rename and wrap trigger open tag
        xml = xml.replaceFirst("(?m)^  <syncBranchesTrigger>(\r?\n)    <spec>",
                "  <triggers>\n    <hudson.triggers.TimerTrigger>\n      <spec>");

        // Rename and wrap trigger close tag
        xml = xml.replaceFirst("(?m)^  </syncBranchesTrigger>",
                "    </hudson.triggers.TimerTrigger>\n  </triggers>");

        // Copy AMP from template if parent does not have a properties tag
        if (!xml.matches("(?ms).+(\r?\n)  <properties.+")
                // Long line is long
                && xml.matches(
                        "(?ms).*<((freestyle|maven)-multi-branch-project|com\\.github\\.mjdetullio\\.jenkins\\.plugins\\.multibranch\\.(FreeStyle|Maven)MultiBranchProject)( plugin=\".*?\")?.+")) {

            File templateConfigFile = new File(new File(configFile.getParentFile(), TEMPLATE), "config.xml");

            if (templateConfigFile.isFile()) {
                String templateXml = FileUtils.readFileToString(templateConfigFile);

                int start = templateXml.indexOf(projectAmpStartTag);
                int end = templateXml.indexOf("</hudson.security.AuthorizationMatrixProperty>");

                if (start != -1 && end != -1) {
                    String ampSettings = templateXml.substring(start + projectAmpStartTag.length(), end);

                    xml = xml.replaceFirst("(?m)^  ", "  <properties>\n    "
                            + "<com.cloudbees.hudson.plugins.folder.properties.AuthorizationMatrixProperty>"
                            + ampSettings
                            + "</com.cloudbees.hudson.plugins.folder.properties.AuthorizationMatrixProperty>"
                            + "\n  </properties>\n  ");
                }
            }
        }

        FileUtils.writeStringToFile(configFile, xml);
    }
}

From source file:io.personium.test.jersey.cell.ErrorPageTest.java

/**
 * ????.//w  w w.j a  v  a2 s.c  om
 * @param res ?
 * @param expectedCode ?
 */
public static void checkResponseBody(PersoniumResponse res, String expectedCode) {
    String body = null;
    String expectedMessage = null;
    String expectedTitle = PersoniumCoreMessageUtils.getMessage("PS-ER-0001");
    if (expectedCode == null) {
        expectedMessage = PersoniumCoreMessageUtils.getMessage("PS-ER-0002");
    } else {
        expectedMessage = PersoniumCoreMessageUtils.getMessage(expectedCode);
    }
    try {
        body = res.bodyAsString();
        System.out.println(body);
        assertEquals(
                "<html><head><title>" + expectedTitle + "</title></head><body><h1>" + expectedTitle + "</h1><p>"
                        + expectedMessage + "</p></body></html>",
                body.replaceFirst("<!-- .*-->", ""));
    } catch (DaoException e) {
        fail(e.getMessage());
        e.printStackTrace();
    }
}

From source file:eu.eubrazilcc.lvl.core.conf.ConfigurationManager.java

private static String subsEnvVars(final String path, final boolean ensureWriting) {
    String substituted = path;
    if (path != null && path.trim().length() > 0) {
        substituted = path.trim();//w  ww. ja  v  a2s .c om
        if (substituted.startsWith("$HOME")) {
            final String userDir = getUserDirectoryPath();
            substituted = (ensureWriting && !new File(userDir).canWrite()
                    ? substituted.replaceFirst("\\$HOME", getTempDirectoryPath())
                    : substituted.replaceFirst("\\$HOME", userDir));
        } else if (substituted.startsWith("$TMP")) {
            substituted = substituted.replaceFirst("\\$TMP", getTempDirectoryPath());
        }
    }
    return substituted;
}

From source file:net.intelliant.util.UtilCommon.java

private static String generateCompressedImageForInputFile(String locationInFileSystem, String srcFileName)
        throws NoSuchAlgorithmException, IOException {
    String outputFileName = srcFileName;
    File srcFile = new File(locationInFileSystem, srcFileName);
    File compressedFile = null;//w w w . ja v  a2  s.com
    FileImageOutputStream outputStream = null;
    try {
        if (srcFile.exists()) {
            String md5sum = getMD5SumForFile(srcFile.getAbsolutePath());
            int extentionIndex = srcFileName.lastIndexOf("."); // find index of extension.
            if (extentionIndex != -1) {
                outputFileName = outputFileName.replaceFirst("\\.", "_" + md5sum + ".");
            }
            compressedFile = new File(locationInFileSystem, outputFileName);
            if (Debug.infoOn()) {
                Debug.logInfo("[generateCompressedImageFor] sourceFile >> " + srcFile.getAbsolutePath(),
                        module);
                Debug.logInfo("[generateCompressedImageFor] md5sum >> " + md5sum, module);
                Debug.logInfo(
                        "[generateCompressedImageFor] compressedFile >> " + compressedFile.getAbsolutePath(),
                        module);
            }
            if (!compressedFile.exists()) {
                if (Debug.infoOn()) {
                    Debug.logInfo("[generateCompressedImageFor] compressed file does NOT exist..", module);
                }
                Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
                ImageWriter imageWriter = (ImageWriter) iter.next();
                ImageWriteParam iwp = imageWriter.getDefaultWriteParam();
                iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                iwp.setCompressionQuality(Float.parseFloat(imageCompressionQuality)); // an integer between 0 and 1, 1 specifies minimum compression and maximum quality
                BufferedImage bufferedImage = ImageIO.read(srcFile);
                outputStream = new FileImageOutputStream(compressedFile);
                imageWriter.setOutput(outputStream);
                IIOImage image = new IIOImage(bufferedImage, null, null);
                imageWriter.write(null, image, iwp);
            } else {
                if (Debug.infoOn()) {
                    Debug.logInfo(
                            "[generateCompressedImageFor] compressed file exists, not compressing again..",
                            module);
                }
            }
        } else {
            Debug.logWarning(String.format("Source image file does NOT exist..", srcFile), module);
        }
    } finally {
        if (outputStream != null) {
            outputStream.close();
            outputStream = null;
        }
    }
    return outputFileName;
}

From source file:com.ibm.research.rdf.store.runtime.service.sql.StoreHelper.java

/**
 * Creates the named RDFStore Config table in a schema
 * //from   ww w .  jav a  2s  .  c o m
 * @param conn
 * @param systemPredicates
 * @return
 */
public static boolean createRdfStoreTable(Connection conn, Backend backend, String schemaName, String storeName,
        String tablespaceName, String predicateMappings) {

    //
    // create the master table
    //

    //
    // For PostgreSQL, a sequence must be defined for the master table
    //
    if (backend == Store.Backend.postgresql) {
        String newSeq = Sqls.getSqls(backend).getSql("entry_id_seq");
        newSeq = newSeq.replaceFirst("%s", storeName);
        doSql(conn, backend, newSeq);
    }

    long length = new File(predicateMappings).length();
    String t = Sqls.getSqls(backend).getSql("storeCfgTable");
    t = t.replaceFirst("%s", storeName);
    if (Backend.shark == backend) {
        t = t.replaceFirst("%s", storeName); // needed for shark in "CACHE TABLE %s"
    }

    //
    // In both DB2 and PostgreSQL, there is a second %s, but for different reasons in each one.
    //

    //
    // In DB2, there is a CLOB object to hold the predicate mappings. We need to replace the %s with the size of the predicate_mappings file.
    // In PostgreSQL, the same attribute has type TEXT. So, no need to set it's size
    //
    if (backend == Backend.db2) {
        t = t.replaceFirst("%s", predicateMappings == null ? "2M" : String.valueOf(Math.round(length * 1.2)));
    }

    //
    // In PostgreSQL, entry_ID is a sequence, so we need to properly set it. This is where the second %s appears in PostgreSQL
    //
    if (backend == Backend.postgresql) {
        t = t.replace("%s", storeName);
    }

    if (tablespaceName != null) {
        t = t + " IN " + tablespaceName;
    }
    doSql(conn, backend, t);

    return true;

}

From source file:com.ibm.research.rdf.store.runtime.service.sql.StoreHelper.java

public static Store connectStore(Connection conn, Backend backend, String schemaName, String datasetName,
        Context context) {//from   w  ww  . j a  v a 2  s  . com

    StoreImpl store = null;
    String getter = Sqls.getSqls(backend).getSql("getDataset");

    store = new SQLExecutor().getStore(conn, context, getter.replaceFirst("%s", schemaName + "." + datasetName),
            datasetName.toUpperCase());

    if (store != null) {
        store.setStoreBackend(backend);
        store.setSchemaName(getSchema(conn, schemaName));
        ensureExistenceOfUserTablespaceAndBuiltInRecursiveStoreProcedure(conn, store);
    }

    return store;
}

From source file:com.perl5.lang.perl.util.PerlPackageUtil.java

/**
 * Translates package relative name to the package name Foo/Bar.pm => Foo::Bar
 *
 * @param packagePath package relative path
 * @return canonical package name/*  www . j a  v a2 s  .c o m*/
 */
public static String getPackageNameByPath(final String packagePath) {
    String result = myFilePathsToPackageNameMap.get(packagePath);

    if (result == null) {
        String path = packagePath.replaceAll("\\\\", "/");
        result = getCanonicalPackageName(
                StringUtils.join(path.replaceFirst("\\.[^.]+$", "").split("/"), PACKAGE_SEPARATOR));
        myFilePathsToPackageNameMap.put(packagePath, result);
    }
    return result;
}

From source file:com.t3.persistence.PersistenceUtil.java

/**
 * Determines whether the incoming map name is unique. If it is, it's
 * returned as-is. If it's not unique, a newly generated name is returned.
 * //from  w  w w.  ja  va 2s .c  o  m
 * @param n
 *            name from imported map
 * @return new name to use for the map
 */
private static String fixupZoneName(String n) {
    List<Zone> zones = TabletopTool.getCampaign().getZones();
    for (Zone zone : zones) {
        if (zone.getName().equals(n)) {
            String count = n.replaceFirst("Import (\\d+) of.*", "$1"); //$NON-NLS-1$
            Integer next = 1;
            try {
                next = StringUtil.parseInteger(count) + 1;
                n = n.replaceFirst("Import \\d+ of", "Import " + next + " of"); //$NON-NLS-1$
            } catch (ParseException e) {
                n = "Import " + next + " of " + n; //$NON-NLS-1$
            }
        }
    }
    return n;
}