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:org.alfresco.selenium.FetchCSS.java

/**
 * Extract additional content found in css.
 * @param source css /*from  www .j  ava2  s .co m*/
 * @return collection of files to get 
 * @throws IOException if error
 */
public static void getCSSFiles(File file, WebDriver driver) throws IOException {
    if (file == null) {
        throw new IllegalArgumentException("CSS source is required");
    }
    String source = FileUtils.readFileToString(file);
    source = source.replaceAll("}", "}\n");
    String domain = getHost(driver);
    CloseableHttpClient client = FetchHttpClient.getHttpClient(driver);
    StringBuffer sb = new StringBuffer();
    try {
        //Extract all source files
        Matcher matchSrc = CSS_BACKGOUND_IMG_PATTERN.matcher(source);
        while (matchSrc.find()) {
            //Change extracted source file to absolute urls 
            String fileSourceOri = matchSrc.group(0);
            String fileSource = fileSourceOri.replaceAll("\"", "");
            if (!fileSource.startsWith("data:image")) {
                if (fileSource.startsWith("//")) {
                    fileSource = fileSource.replace("//", "http://");
                } else if (fileSource.startsWith("/")) {
                    fileSource = fileSource.replaceFirst("/", domain + "/");
                }
                //Add to collection of paths for downloading
                getCssFile(fileSource, fileSourceOri, client);
            }
            //Amend path to point to file in the same directory
            if (!fileSourceOri.startsWith("//") || fileSourceOri.startsWith("\"/")) {
                String t = fileSourceOri.replaceFirst("\"/", "\"");
                matchSrc.appendReplacement(sb, t);
            } else {

                matchSrc.appendReplacement(sb, fileSourceOri);
            }
        }
        if (sb.length() < 1) {
            FileUtils.writeStringToFile(file, source);
        } else {
            FileUtils.writeStringToFile(file, sb.toString());
        }

    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:org.alfresco.selenium.FetchUtil.java

/**
 * Gets the external file using http client.
 * @param source file name/*w  ww. java 2 s.  co  m*/
 * @param client {@link CloseableHttpClient}
 * @return {@link File} output.
 * @throws IOException if error
 */
private static File getFile(final String source, final CloseableHttpClient client) throws IOException {
    String name = getName(source);
    //Strip ? as it causes regex problems when its a prefix. 
    if (name.startsWith("?")) {
        name = name.replaceFirst("\\?", "");
    }
    File target = new File(ASSET_DIR);
    if (!target.exists()) {
        target.mkdirs();
    }
    File destination = new File(ASSET_DIR + URL_PATH_SEPARATOR + name);
    return retrieveFile(source, client, destination);
}

From source file:pt.webdetails.cns.notifications.sparkl.kettle.baserver.web.utils.HttpConnectionHelper.java

public static Response callHttp(String url, String user, String password)
        throws IOException, KettleStepException {

    // used for calculating the responseTime
    long startTime = System.currentTimeMillis();

    HttpClient httpclient = SlaveConnectionManager.getInstance().createHttpClient();
    HttpMethod method = new GetMethod(url);
    httpclient.getParams().setAuthenticationPreemptive(true);
    Credentials credentials = new UsernamePasswordCredentials(user, password);
    httpclient.getState().setCredentials(AuthScope.ANY, credentials);
    HostConfiguration hostConfiguration = new HostConfiguration();

    int status;//from   ww  w .j a  v a  2  s. co  m
    try {
        status = httpclient.executeMethod(hostConfiguration, method);
    } catch (IllegalArgumentException ex) {
        status = -1;
    }

    Response response = new Response();
    if (status != -1) {
        String body = null;
        String encoding = "";
        Header contentTypeHeader = method.getResponseHeader("Content-Type");
        if (contentTypeHeader != null) {
            String contentType = contentTypeHeader.getValue();
            if (contentType != null && contentType.contains("charset")) {
                encoding = contentType.replaceFirst("^.*;\\s*charset\\s*=\\s*", "").replace("\"", "").trim();
            }
        }

        // get the response
        InputStreamReader inputStreamReader = null;
        if (!Const.isEmpty(encoding)) {
            inputStreamReader = new InputStreamReader(method.getResponseBodyAsStream(), encoding);
        } else {
            inputStreamReader = new InputStreamReader(method.getResponseBodyAsStream());
        }
        StringBuilder bodyBuffer = new StringBuilder();
        int c;
        while ((c = inputStreamReader.read()) != -1) {
            bodyBuffer.append((char) c);
        }
        inputStreamReader.close();
        body = bodyBuffer.toString();

        // Get response time
        long responseTime = System.currentTimeMillis() - startTime;

        response.setStatusCode(status);
        response.setResult(body);
        response.setResponseTime(responseTime);
    }
    return response;
}

From source file:com.vaadin.integration.maven.wscdn.CvalChecker.java

static final int computeMajorVersion(String productVersion) {
    return productVersion == null || productVersion.isEmpty() ? 0
            : parseInt(productVersion.replaceFirst("[^\\d]+.*$", ""));
}

From source file:ambroafb.general.AnnotiationUtils.java

private static boolean checkValidationForContentRateAnnotation(Field field, Object currSceneController) {
    boolean contentIsCorrect = false;
    Annotations.ContentRate annotation = field.getAnnotation(Annotations.ContentRate.class);
    Object[] typeAndContent = getNodesTypeAndContent(field, currSceneController);

    if (!Pattern.matches(annotation.valueForIntegerPart(), (String) typeAndContent[1])) {
        String explainFromBundle = GeneralConfig.getInstance().getTitleFor(annotation.explainForIntegerPart());
        String integerPartExp = explainFromBundle.replaceFirst("#",
                "" + Annotations.ContentRate.integerPartLen);
        changeNodeTitleLabelVisual((Node) typeAndContent[0], integerPartExp);
    } else if (!Pattern.matches(annotation.valueForFractionalPart(), (String) typeAndContent[1])) {
        String explainFromBundle = GeneralConfig.getInstance()
                .getTitleFor(annotation.explainForFractionalPart());
        String fractionalPartExp = explainFromBundle.replaceFirst("#",
                "" + Annotations.ContentRate.fractionalPartLen);
        changeNodeTitleLabelVisual((Node) typeAndContent[0], fractionalPartExp);
    } else if (!Pattern.matches(annotation.valueForWhole(), (String) typeAndContent[1])) {
        changeNodeTitleLabelVisual((Node) typeAndContent[0], annotation.explainForWhole());
    } else {//  w ww.j  a  va2 s  .co m
        changeNodeTitleLabelVisual((Node) typeAndContent[0], "");
        contentIsCorrect = true;
    }
    return contentIsCorrect;
}

From source file:com.jaspersoft.studio.server.protocol.restv2.CASUtil.java

public static String doGetTocken(ServerProfile sp, SSOServer srv, IProgressMonitor monitor) throws Exception {
    SSLContext sslContext = SSLContext.getInstance("SSL");

    // set up a TrustManager that trusts everything
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            // System.out.println("getAcceptedIssuers =============");
            return null;
        }/*from  w w  w .ja  v  a2  s. com*/

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
            // System.out.println("checkClientTrusted =============");
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            // System.out.println("checkServerTrusted =============");
        }
    } }, new SecureRandom());

    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf)
            .setRedirectStrategy(new DefaultRedirectStrategy() {
                @Override
                protected boolean isRedirectable(String arg0) {
                    // TODO Auto-generated method stub
                    return super.isRedirectable(arg0);
                }

                @Override
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                        throws ProtocolException {
                    // TODO Auto-generated method stub
                    return super.isRedirected(request, response, context);
                }
            }).setDefaultCookieStore(new BasicCookieStore())
            .setUserAgent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0")
            .build();

    Executor exec = Executor.newInstance(httpclient);

    URIBuilder ub = new URIBuilder(sp.getUrl() + "index.html");

    String fullURL = ub.build().toASCIIString();
    Request req = HttpUtils.get(fullURL, sp);
    HttpHost proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL));
    if (proxy != null)
        req.viaProxy(proxy);
    String tgtID = readData(exec, req, monitor);
    String action = getFormAction(tgtID);
    if (action != null) {
        action = action.replaceFirst("/", "");
        int indx = action.indexOf(";jsession");
        if (indx >= 0)
            action = action.substring(0, indx);
    } else
        action = "cas/login";
    String url = srv.getUrl();
    if (!url.endsWith("/"))
        url += "/";
    ub = new URIBuilder(url + action);
    //
    fullURL = ub.build().toASCIIString();
    req = HttpUtils.get(fullURL, sp);
    proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL));
    if (proxy != null)
        req.viaProxy(proxy);
    tgtID = readData(exec, req, monitor);
    action = getFormAction(tgtID);
    action = action.replaceFirst("/", "");

    ub = new URIBuilder(url + action);
    Map<String, String> map = getInputs(tgtID);
    Form form = Form.form();
    for (String key : map.keySet()) {
        if (key.equals("btn-reset"))
            continue;
        else if (key.equals("username")) {
            form.add(key, srv.getUser());
            continue;
        } else if (key.equals("password")) {
            form.add(key, Pass.getPass(srv.getPassword()));
            continue;
        }
        form.add(key, map.get(key));
    }
    //
    req = HttpUtils.post(ub.build().toASCIIString(), form, sp);
    if (proxy != null)
        req.viaProxy(proxy);
    // Header header = null;
    readData(exec, req, monitor);
    // for (Header h : headers) {
    // for (HeaderElement he : h.getElements()) {
    // if (he.getName().equals("CASTGC")) {
    // header = new BasicHeader("Cookie", h.getValue());
    // break;
    // }
    // }
    // }
    ub = new URIBuilder(url + action);
    url = sp.getUrl();
    if (!url.endsWith("/"))
        url += "/";
    ub.addParameter("service", url + "j_spring_security_check");

    req = HttpUtils.get(ub.build().toASCIIString(), sp);
    if (proxy != null)
        req.viaProxy(proxy);
    // req.addHeader("Accept",
    // "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8, value");
    req.addHeader("Referrer", sp.getUrl());
    // req.addHeader(header);
    String html = readData(exec, req, monitor);
    Matcher matcher = ahrefPattern.matcher(html);
    while (matcher.find()) {
        Map<String, String> attributes = parseAttributes(matcher.group(1));
        String v = attributes.get("href");
        int ind = v.indexOf("ticket=");
        if (ind > 0) {
            return v.substring(ind + "ticket=".length());
        }
    }
    return null;
}

From source file:com.norconex.collector.http.pipeline.importer.HttpImporterPipelineUtil.java

public static void enhanceHTTPHeaders(HttpMetadata metadata) {
    if (StringUtils.isNotBlank(metadata.getString(HttpMetadata.COLLECTOR_CONTENT_TYPE))) {
        return;//from w  w w  .  j  a v a  2s .  co  m
    }

    String contentType = metadata.getString(HttpMetadata.HTTP_CONTENT_TYPE);
    if (StringUtils.isBlank(contentType)) {
        for (String key : metadata.keySet()) {
            if (StringUtils.endsWith(key, HttpMetadata.HTTP_CONTENT_TYPE)) {
                contentType = metadata.getString(key);
            }
        }
    }
    if (StringUtils.isNotBlank(contentType)) {
        String mimeType = contentType.replaceFirst("(.*?)(;.*)", "$1");
        String charset = contentType.replaceFirst("(.*?)(; )(.*)", "$3");
        charset = charset.replaceFirst("(charset=)(.*)", "$2");
        metadata.addString(HttpMetadata.COLLECTOR_CONTENT_TYPE, mimeType);
        metadata.addString(HttpMetadata.COLLECTOR_CONTENT_ENCODING, charset);
    }
}

From source file:ambroafb.general.AnnotiationUtils.java

private static boolean checkValidationForContentAmountAnnotation(Field field, Object currSceneController) {
    boolean contentIsCorrect = false;
    Annotations.ContentAmount annotation = field.getAnnotation(Annotations.ContentAmount.class);
    Object[] typeAndContent = getNodesTypeAndContent(field, currSceneController);

    String integerPartPattern = annotation.valueForIntegerPart();
    int outerIntegerPartMaxLen = annotation.integerPartMaxLen();
    if (outerIntegerPartMaxLen > 0) {
        integerPartPattern = annotation.valueForIntegerPart().replaceFirst(
                "" + (Annotations.ContentAmount.integerPartMaxLen - 1), "" + annotation.integerPartMaxLen());
    }//from ww  w.  ja  v  a 2  s .  co  m

    if (!Pattern.matches(integerPartPattern, (String) typeAndContent[1])) {
        String integerPartExplain = (outerIntegerPartMaxLen > 0) ? "" + outerIntegerPartMaxLen
                : "" + Annotations.ContentAmount.integerPartMaxLen;
        String explainFromBundle = GeneralConfig.getInstance().getTitleFor(annotation.explainForIntegerPart());
        String integerPartExp = explainFromBundle.replaceFirst("#", integerPartExplain);
        changeNodeTitleLabelVisual((Node) typeAndContent[0], integerPartExp);
    } else if (!Pattern.matches(annotation.valueForFractionalPart(), (String) typeAndContent[1])) {
        String explainFromBundle = GeneralConfig.getInstance()
                .getTitleFor(annotation.explainForFractionalPart());
        String fractionalPartExp = explainFromBundle.replaceFirst("#",
                "" + Annotations.ContentAmount.fractionalPartMaxLen);
        changeNodeTitleLabelVisual((Node) typeAndContent[0], fractionalPartExp);
    } else if (!Pattern.matches(annotation.valueForWhole(), (String) typeAndContent[1])) {
        changeNodeTitleLabelVisual((Node) typeAndContent[0], annotation.explainForWhole());
    } else {
        changeNodeTitleLabelVisual((Node) typeAndContent[0], "");
        contentIsCorrect = true;
    }
    return contentIsCorrect;
}

From source file:com.diyshirt.util.RegexUtil.java

public static String encodeEmail(String str) {
    // obfuscate mailto's: turns them into hex encoded,
    // so that browsers can still understand the mailto link
    Matcher mailtoMatch = mailtoPattern.matcher(str);
    while (mailtoMatch.find()) {
        String email = mailtoMatch.group(1);
        //System.out.println("email=" + email);
        String hexed = encode(email);
        str = str.replaceFirst("mailto:" + email, "mailto:" + hexed);
    }//from   w  w  w  . j  a v  a2s . c o  m

    return obfuscateEmail(str);
}

From source file:com.reizes.shiva.utils.CommonUtil.java

/**
 * API ?  path ? /*w w  w .j  a  va2 s. com*/
 * path  null ? null 
 * @param path  
 * @return "||" -> ">", ?  "^>" -> ""  replace
 */
public static String getDirPathForApi(String path) {
    if (path == null) {
        return null;
    }
    String dispPath = path.replace("||", ">");
    dispPath = dispPath.replaceFirst("^>", "");
    return dispPath;
}