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:com.centurylink.mdw.services.util.AuthUtils.java

private static boolean checkBearerAuthenticationHeader(String authHeader, Map<String, String> headers) {
    try {//from   w  ww. j  ava2s. co  m
        // Do NOT try to authenticate if it's not Bearer
        if (authHeader == null || !authHeader.startsWith("Bearer"))
            throw new Exception("Invalid MDW Auth Header"); // This should never happen

        authHeader = authHeader.replaceFirst("Bearer ", "");
        DecodedJWT jwt = JWT.decode(authHeader); // Validate it is a JWT and see which kind of JWT it is

        if (MDW_AUTH.equals(jwt.getIssuer())) // JWT was issued by MDW Central
            verifyMdwJWT(authHeader, headers);
        else if (verifierCustom.get(jwt.getIssuer()) != null
                || (PropertyManager.getInstance().getProperties(PropertyNames.MDW_JWT) != null
                        && PropertyManager.getInstance().getProperties(PropertyNames.MDW_JWT).values()
                                .contains(jwt.getIssuer()))) // Support for other issuers of JWTs
            verifyCustomJWT(authHeader, jwt.getAlgorithm(), jwt.getIssuer(), headers);
        else
            throw new Exception("Invalid JWT Issuer");
    } catch (Throwable ex) {
        if (!ApplicationContext.isDevelopment()) {
            headers.put(Listener.AUTHENTICATION_FAILED,
                    "Authentication failed for JWT '" + authHeader + "' " + ex.getMessage());
            logger.severeException("Authentication failed for JWT '" + authHeader + "' " + ex.getMessage(), ex);
        }
        return false;
    }
    if (logger.isDebugEnabled()) {
        logger.debug(
                "authentication successful for user '" + headers.get(Listener.AUTHENTICATED_USER_HEADER) + "'");
    }
    if (PropertyManager.getBooleanProperty(PropertyNames.MDW_JWT_PRESERVE, false))
        headers.put(Listener.AUTHENTICATED_JWT, authHeader);
    return true;
}

From source file:com.fujitsu.dc.test.jersey.cell.ErrorPageTest.java

/**
 * ????./*  w w w  .  ja v a 2 s. c om*/
 * @param res ?
 * @param expectedCode ?
 */
public static void checkResponseBody(DcResponse res, String expectedCode) {
    String body = null;
    String expectedMessage = null;
    if (expectedCode == null) {
        expectedMessage = DcCoreMessageUtils.getMessage("PS-ER-0003");
    } else {
        expectedMessage = DcCoreMessageUtils.getMessage(expectedCode);
    }
    try {
        body = res.bodyAsString();
        System.out.println(body);
        assertEquals(
                "<html><head><title>ERROR</title></head><body><h1>ERROR</h1></br><p>PCS ERROR</p><p>"
                        + expectedMessage + "</p></body></html>",
                body.replaceFirst("<!-- .*-->", ""));
    } catch (DaoException e) {
        fail(e.getMessage());
        e.printStackTrace();
    }
}

From source file:net.aepik.alasca.core.ldap.Schema.java

/**
 * Get sorted object identifiers keys, to loop on object identifiers
 * into a valid order./*from   w  ww  .j ava 2  s  .  c  o m*/
 * @param oids Object identifiers.
 * @return String[] Sorted keys
 */
public static String[] getSortedObjectsIdentifiersKeys(Properties oids) {
    Hashtable<String, String> ht = new Hashtable<String, String>();
    for (Enumeration keys = oids.propertyNames(); keys.hasMoreElements();) {
        String k = (String) keys.nextElement();
        Oid o = new Oid(oids.getProperty(k));
        String v = o.toString();
        String p = o.getPrefix();
        while (p != null) {
            v = v.replaceFirst(p + ":", oids.getProperty(p) + ".");
            p = (new Oid(oids.getProperty(p))).getPrefix();
        }
        ht.put(v, k);
    }
    String[] st = ht.keySet().toArray(new String[0]);
    Arrays.sort(st);
    String[] result = new String[st.length];
    int result_index = 0;
    for (String k : st) {
        result[result_index] = ht.get(k);
        result_index++;
    }
    return result;
}

From source file:com.varaneckas.hawkscope.util.PathUtils.java

/**
 * Interprets the location/*from ww w  .j a  v  a2 s .c  o m*/
 * 
 * It can either be a full path, a java property, 
 * like ${user.home} (default) or environmental variable like ${$JAVA_HOME}.
 * 
 * @param location
 * @return
 */
public static String interpret(final String location) {
    if (!location.matches(".*" + INTERPRET_REGEX + ".*")) {
        return location;
    } else {
        String newLocation = location;
        try {
            final Pattern grep = Pattern.compile(INTERPRET_REGEX);
            final Matcher matcher = grep.matcher(location);
            while (matcher.find()) {
                log.debug("Parsing: " + matcher.group(1));
                String replacement;
                if (matcher.group(1).startsWith("$")) {
                    replacement = System.getenv(matcher.group(1).substring(1));
                } else {
                    replacement = System.getProperty(matcher.group(1));
                }
                newLocation = newLocation.replaceFirst(quote(matcher.group()),
                        replacement.replaceAll(Constants.REGEX_BACKSLASH, Constants.REGEX_SLASH));
            }
        } catch (final Exception e) {
            log.warn("Failed parsing location: " + location, e);
        }

        return newLocation;
    }
}

From source file:com.viettel.util.StringUtils.java

public static String removeNumbering(String str) {
     if (CommonUtil.isEmpty(str))
         return str;
     str = str.trim();// w ww .  ja  v  a2s.  co m
     if (str.startsWith("0") || str.startsWith("1") || str.startsWith("2") || str.startsWith("3")
             || str.startsWith("4") || str.startsWith("5") || str.startsWith("6") || str.startsWith("7")
             || str.startsWith("8") || str.startsWith("9"))
         return str.replaceFirst("(\\d\\.(\\d.)*)+", "").trim();
     else
         return str;
 }

From source file:com.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfigurationTest.java

/**
 * Return the classes inside the specified package and its sub-packages.
 * @param klass a class inside that package
 * @return a list of class names/*  w ww  .  j  a v  a  2 s  . c om*/
 */
public static List<String> getClassesForPackage(final Class<?> klass) {
    final List<String> list = new ArrayList<>();

    File directory = null;
    final String relPath = klass.getName().replace('.', '/') + ".class";

    final URL resource = JavaScriptConfiguration.class.getClassLoader().getResource(relPath);

    if (resource == null) {
        throw new RuntimeException("No resource for " + relPath);
    }
    final String fullPath = resource.getFile();

    try {
        directory = new File(resource.toURI()).getParentFile();
    } catch (final URISyntaxException e) {
        throw new RuntimeException(klass.getName() + " (" + resource + ") does not appear to be a valid URL",
                e);
    } catch (final IllegalArgumentException e) {
        directory = null;
    }

    if (directory != null && directory.exists()) {
        addClasses(directory, klass.getPackage().getName(), list);
    } else {
        try {
            String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
            if (System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win")) {
                jarPath = jarPath.replace("%20", " ");
            }
            final JarFile jarFile = new JarFile(jarPath);
            for (final Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
                final String entryName = entries.nextElement().getName();
                if (entryName.endsWith(".class")) {
                    list.add(entryName.replace('/', '.').replace('\\', '.').replace(".class", ""));
                }
            }
            jarFile.close();
        } catch (final IOException e) {
            throw new RuntimeException(klass.getPackage().getName() + " does not appear to be a valid package",
                    e);
        }
    }
    return list;
}

From source file:com.google.livingstories.server.dataservices.entities.BaseContentEntity.java

/**
 * Returns a form of input that's trimmed, including the removal of any leading or trailing <br/>s
 * @input /*from w  w w .j  a v a2  s  .  co  m*/
 * @return trimmed input
 */
private static String trimWithBrs(String input) {
    return input.replaceFirst("^(\\s|<br/?>|<br></br>)+", "").replaceFirst("(\\s|<br/?>|<br></br>)+$", "")
            .trim();
}

From source file:com.yahoo.semsearch.fastlinking.io.ExtractWikipediaAnchorText.java

public static String capitalizeFirstChar(String title) {
    String fc = title.substring(0, 1);
    if (fc.matches("[a-z]")) {
        title = title.replaceFirst(fc, fc.toUpperCase());
    }//w w w.  ja  v  a  2 s.  c om
    return title;
}

From source file:edu.harvard.mcz.imagecapture.data.UnitTrayLabel.java

/** Factory method, given a JSON encoded string, as encoded with toJSONString(), extract the values from that
 * string into a new instance of UnitTrayLabel so that they can be obtained by the appropriate returner
 * interface (taxonnameReturner, drawernumberReturner, collectionReturner).
 * //from  w ww.j  av  a  2  s  . c o  m
 * @param jsonEncodedLabel the JSON to decode.
 * @return a new UnitTrayLabel populated with the values found in the supplied jsonEncodedLabel text or null on a failure.
 * @see toJSONString
 */
public static UnitTrayLabel createFromJSONString(String jsonEncodedLabel) {
    UnitTrayLabel result = null;
    if (jsonEncodedLabel.matches("\\{.*\\}")) {
        String originalJsonEncodedLabel = new String(jsonEncodedLabel.toString());
        jsonEncodedLabel = jsonEncodedLabel.replaceFirst("^\\{", ""); // Strip off leading  { 
        jsonEncodedLabel = jsonEncodedLabel.replaceFirst("\\}$", ""); // Strip off trailing } 
        if (jsonEncodedLabel.contains("}")) {
            // nested json, not expected.
            log.error("JSON for UnitTrayLabel contains unexpected nesting { { } }.  JSON is: "
                    + originalJsonEncodedLabel);
        } else {
            log.debug(jsonEncodedLabel);
            result = new UnitTrayLabel();
            // Beginning and end are special case for split on '", "'
            // remove leading quotes and spaces (e.g. either trailing '" ' or trailing '"').
            jsonEncodedLabel = jsonEncodedLabel.replaceFirst("^ ", ""); // Strip off leading space 
            jsonEncodedLabel = jsonEncodedLabel.replaceFirst(" $", ""); // Strip off trailing space
            jsonEncodedLabel = jsonEncodedLabel.replaceFirst("^\"", ""); // Strip off leading quote
            jsonEncodedLabel = jsonEncodedLabel.replaceFirst("\"$", ""); // Strip off trailing quote
            // Convert any ", " into "," then split on ","
            jsonEncodedLabel = jsonEncodedLabel.replaceAll("\",\\s\"", "\",\"");
            log.debug(jsonEncodedLabel);
            // split into key value parts by '","'
            String[] pairs = jsonEncodedLabel.split("\",\"");
            for (int x = 0; x < pairs.length; x++) {
                // split each key value pair
                String[] keyValuePair = pairs[x].split("\":\"");
                if (keyValuePair.length == 2) {
                    String key = keyValuePair[0];
                    String value = keyValuePair[1];
                    log.debug("key=[" + key + "], value=[" + value + "]");

                    if (key.equals("m1p")) {
                        log.debug("Configured for Project: " + value);
                        if (!value.equals("MCZ Lepidoptera") && !value.equals("ETHZ Entomology")
                                && !value.equals("[ETHZ Entomology]")) {
                            log.error("Project specified in JSON is not recognized: " + value);
                            log.error("Warning: Keys in JSON may not be correctly interpreted.");
                        }
                    }

                    // Note: Adding values here isn't sufficient to populate specimen records,
                    // you still need to invoke the relevant returner interface on the parser.
                    if (key.equals("f")) {
                        result.setFamily(value);
                    }
                    if (key.equals("b")) {
                        result.setSubfamily(value);
                    }
                    if (key.equals("t")) {
                        result.setTribe(value);
                    }
                    if (key.equals("g")) {
                        result.setGenus(value);
                    }
                    if (key.equals("s")) {
                        result.setSpecificEpithet(value);
                    }
                    if (key.equals("u")) {
                        result.setSubspecificEpithet(value);
                    }
                    if (key.equals("i")) {
                        result.setInfraspecificEpithet(value);
                    }
                    if (key.equals("r")) {
                        result.setInfraspecificRank(value);
                    }
                    if (key.equals("a")) {
                        result.setAuthorship(value);
                    }
                    if (key.equals("d")) {
                        result.setDrawerNumber(value);
                    }
                    if (key.equals("c")) {
                        result.setCollection(value);
                        log.debug(result.getCollection());
                    }
                    if (key.equals("id")) {
                        result.setIdentifiedBy(value);
                    }
                }
            }
            log.debug(result.toJSONString());
        }
    } else {
        log.debug("JSON not matched to { }");
    }
    return result;
}

From source file:com.sabdroidex.controllers.couchpotato.CouchPotatoController.java

/**
 * This function handle the API calls to Couchpotato to define the URL and
 * parameters//from   ww w.  j a v a  2s.  c  om
 * 
 * @param command The type of command that will be sent to Sabnzbd
 * @param extraParams Any parameter that will have to be part of the URL
 * @return The result of the API call
 * @throws RuntimeException
 *             Thrown if there is any unexpected problem during the
 *             communication with the server
 */
public static String makeApiCall(String command, String... extraParams) throws Exception {

    /**
     * Correcting the command names to be understood by CouchPotato
     */
    command = command.replaceFirst("_", ".");
    String url = getFormattedUrl();
    url = url.replace("[COMMAND]", command);
    url = url.replace("[API]", Preferences.get(Preferences.COUCHPOTATO_API_KEY));

    for (final String xTraParam : extraParams) {
        if (xTraParam != null && !xTraParam.trim().equals("")) {
            url = url.endsWith("/") ? url + "?" + xTraParam : url + "&" + xTraParam;
        }
    }

    url = url.replace(" ", "%20");
    Log.d(TAG, url);

    return new String(
            HttpUtil.getInstance().getDataAsCharArray(url, ApacheCredentialProvider.getCredentialsProvider()));
}