Example usage for java.util.regex Matcher lookingAt

List of usage examples for java.util.regex Matcher lookingAt

Introduction

In this page you can find the example usage for java.util.regex Matcher lookingAt.

Prototype

public boolean lookingAt() 

Source Link

Document

Attempts to match the input sequence, starting at the beginning of the region, against the pattern.

Usage

From source file:com.apigee.sdk.apm.http.impl.client.cache.WarningValue.java

protected void consumeWarnDate() {
    int curr = offs;
    Matcher m = WARN_DATE_PATTERN.matcher(src.substring(offs));
    if (!m.lookingAt())
        parseError();//from   w  w  w  .jav  a2 s  .com
    offs += m.end();
    try {
        warnDate = DateUtils.parseDate(src.substring(curr + 1, offs - 1));
    } catch (DateParseException e) {
        throw new IllegalStateException("couldn't parse a parseable date");
    }
}

From source file:com.redhat.rhn.frontend.action.kickstart.KickstartHelper.java

private String getClientIp() {
    String remoteAddr = request.getRemoteAddr();
    String proxyHeader = request.getHeader(XFORWARD);

    // check if we are going through a proxy, grab real IP if so
    if (proxyHeader != null) {
        log.debug("proxy header in: " + proxyHeader);
        Matcher matcher = Pattern.compile(XFORWARD_REGEX).matcher(proxyHeader);
        if (matcher.lookingAt()) {
            remoteAddr = matcher.group(1);
            log.debug("origination ip from pchain: " + remoteAddr);
        }//from   w  w w  . j a va2  s .c om
    }

    return remoteAddr;
}

From source file:org.apache.solr.servlet.SolrDispatchFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain, boolean retry)
        throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest))
        return;// w w w .  j a va 2s  .co  m
    try {

        if (cores == null || cores.isShutDown()) {
            log.error(
                    "Error processing the request. CoreContainer is either not initialized or shutting down.");
            throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE,
                    "Error processing the request. CoreContainer is either not initialized or shutting down.");
        }

        AtomicReference<ServletRequest> wrappedRequest = new AtomicReference<>();
        if (!authenticateRequest(request, response, wrappedRequest)) { // the response and status code have already been
                                                                       // sent
            return;
        }
        if (wrappedRequest.get() != null) {
            request = wrappedRequest.get();
        }

        request = closeShield(request, retry);
        response = closeShield(response, retry);

        if (cores.getAuthenticationPlugin() != null) {
            log.debug("User principal: {}", ((HttpServletRequest) request).getUserPrincipal());
        }

        // No need to even create the HttpSolrCall object if this path is excluded.
        if (excludePatterns != null) {
            String requestPath = ((HttpServletRequest) request).getServletPath();
            String extraPath = ((HttpServletRequest) request).getPathInfo();
            if (extraPath != null) { // In embedded mode, servlet path is empty - include all post-context path here for
                                     // testing
                requestPath += extraPath;
            }
            for (Pattern p : excludePatterns) {
                Matcher matcher = p.matcher(requestPath);
                if (matcher.lookingAt()) {
                    chain.doFilter(request, response);
                    return;
                }
            }
        }

        HttpSolrCall call = getHttpSolrCall((HttpServletRequest) request, (HttpServletResponse) response,
                retry);
        ExecutorUtil.setServerThreadFlag(Boolean.TRUE);
        try {
            Action result = call.call();
            switch (result) {
            case PASSTHROUGH:
                chain.doFilter(request, response);
                break;
            case RETRY:
                doFilter(request, response, chain, true);
                break;
            case FORWARD:
                request.getRequestDispatcher(call.getPath()).forward(request, response);
                break;
            }
        } finally {
            call.destroy();
            ExecutorUtil.setServerThreadFlag(null);
        }
    } finally {
        consumeInputFully((HttpServletRequest) request);
    }
}

From source file:com.zenkey.net.prowser.Response.java

/**************************************************************************
 * Returns the title of the web page associated with this
 * <code>Response</code>, as specified in the <code>&lt;title&gt;</code>
 * tag of the page's HTML source code. If the page is not HTML source
 * (i.e., it's a binary file), then the filename is returned instead.
 * <p>//from www. j  ava  2 s.c o  m
 * Note that all leading and trailing whitespace is trimmed from the title
 * string before it is returned.
 * 
 * @return The title of the web page associated with this
 *         <code>Response</code>, or the filename of the retrieved page
 *         if it is not in the form of HTML source code.
 */
public String getTitle() {

    // If page title hasn't been determined yet, do it
    if (pageTitle == null) {

        // If Content-type is not some form of HTML, use filename as title
        if (responseContentType == null || !responseContentType.matches("(?i).*HTML.*")) {
            pageTitle = getFilename();
        }

        // Else get title from page source (use filename if title not found)
        else {
            getPageSource();
            Pattern pattern = Pattern.compile("(?s)(?i).*<TITLE(?:\\s+.*)?>(.*)</TITLE>");
            Matcher matcher = pattern.matcher(pageSource);
            if (matcher.lookingAt())
                pageTitle = matcher.group(1).trim();
            else
                pageTitle = getFilename();
        }
    }

    // Return the page title
    return pageTitle;
}

From source file:com.application.utils.FastDateParser.java

@Override
public Date parse(final String source, final ParsePosition pos) {
    final int offset = pos.getIndex();
    final Matcher matcher = parsePattern.matcher(source.substring(offset));
    if (!matcher.lookingAt()) {
        return null;
    }/*from   w w w .j a v a  2  s.c  o m*/
    // timing tests indicate getting new instance is 19% faster than cloning
    final Calendar cal = Calendar.getInstance(timeZone, locale);
    cal.clear();

    for (int i = 0; i < strategies.length;) {
        final Strategy strategy = strategies[i++];
        strategy.setCalendar(this, cal, matcher.group(i));
    }
    pos.setIndex(offset + matcher.end());
    return cal.getTime();
}

From source file:com.application.utils.FastDateParser.java

/**
 * Initialize derived fields from defining fields.
 * This is called from constructor and from readObject (de-serialization)
 *
 * @param definingCalendar the {@link java.util.Calendar} instance used to initialize this FastDateParser
 *//*from  w w w. j  av  a 2s. c o  m*/
private void init(Calendar definingCalendar) {

    final StringBuilder regex = new StringBuilder();
    final List<Strategy> collector = new ArrayList<Strategy>();

    final Matcher patternMatcher = formatPattern.matcher(pattern);
    if (!patternMatcher.lookingAt()) {
        throw new IllegalArgumentException(
                "Illegal pattern character '" + pattern.charAt(patternMatcher.regionStart()) + "'");
    }

    currentFormatField = patternMatcher.group();
    Strategy currentStrategy = getStrategy(currentFormatField, definingCalendar);
    for (;;) {
        patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd());
        if (!patternMatcher.lookingAt()) {
            nextStrategy = null;
            break;
        }
        final String nextFormatField = patternMatcher.group();
        nextStrategy = getStrategy(nextFormatField, definingCalendar);
        if (currentStrategy.addRegex(this, regex)) {
            collector.add(currentStrategy);
        }
        currentFormatField = nextFormatField;
        currentStrategy = nextStrategy;
    }
    if (patternMatcher.regionStart() != patternMatcher.regionEnd()) {
        throw new IllegalArgumentException(
                "Failed to parse \"" + pattern + "\" ; gave up at index " + patternMatcher.regionStart());
    }
    if (currentStrategy.addRegex(this, regex)) {
        collector.add(currentStrategy);
    }
    currentFormatField = null;
    strategies = collector.toArray(new Strategy[collector.size()]);
    parsePattern = Pattern.compile(regex.toString());
}

From source file:terse.a1.TerseActivity.java

private void viewPath9display(String path, LayoutParams widgetParams) {
    String explain;/*from   w w w  .ja  va 2s  . c o m*/
    if (terp_error != null) {
        explain = "terp_error = " + terp_error;
    } else {
        try {
            terp.say("Sending to terp: %s", path);
            final Dict d = terp.handleUrl(path, taQuery);
            explain = "DEFAULT EXPLANATION:\n\n" + d.toString();

            Str TYPE = d.cls.terp.newStr("type");
            Str VALUE = d.cls.terp.newStr("value");
            Str TITLE = d.cls.terp.newStr("title");
            Str type = (Str) d.dict.get(TYPE);
            Ur value = d.dict.get(VALUE);
            Ur title = d.dict.get(TITLE);

            // {
            // double ticks = Static.floatAt(d, "ticks", -1);
            // double nanos = Static.floatAt(d, "nanos", -1);
            // Toast.makeText(
            // getApplicationContext(),
            // Static.fmt("%d ticks, %.3f secs", (long) ticks,
            // (double) nanos / 1e9), Toast.LENGTH_SHORT)
            // .show();
            // }

            if (type.str.equals("list") && value instanceof Vec) {
                final ArrayList<Ur> v = ((Vec) value).vec;
                final ArrayList<String> labels = new ArrayList<String>();
                final ArrayList<String> links = new ArrayList<String>();
                for (int i = 0; i < v.size(); i++) {
                    Ur item = v.get(i);
                    String label = item instanceof Str ? ((Str) item).str : item.toString();
                    if (item instanceof Vec && ((Vec) item).vec.size() == 2) {
                        // OLD STYLE
                        label = ((Vec) item).vec.get(0).toString();
                        Matcher m = LINK_P.matcher(label);
                        if (m.lookingAt()) {
                            label = m.group(2) + " " + m.group(3);
                        }
                        label += "    [" + ((Vec) item).vec.get(1).toString().length() + "]";
                        links.add(null); // Use old style, not links.
                    } else {
                        // NEW STYLE
                        label = item.toString();
                        if (label.charAt(0) == '/') {
                            String link = Terp.WHITE_PLUS.split(label, 2)[0];
                            links.add(link);
                        } else {
                            links.add("");
                        }
                    }
                    labels.add(label);
                }
                if (labels.size() != links.size())
                    terp.toss("lables#%d links#%d", labels.size(), links.size());

                ListView listv = new ListView(this);
                listv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, labels));
                listv.setLayoutParams(widgetParams);
                listv.setTextFilterEnabled(true);

                listv.setOnItemClickListener(new OnItemClickListener() {
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        // When clicked, show a toast with the TextView text
                        // Toast.makeText(getApplicationContext(),
                        // ((TextView) view).getText(),
                        // Toast.LENGTH_SHORT).show();
                        String toast_text = ((TextView) view).getText().toString();
                        // if (v.get(position) instanceof Vec) {
                        if (links.get(position) == null) {
                            // OLD STYLE
                            Vec pair = (Vec) v.get(position);
                            if (pair.vec.size() == 2) {
                                if (pair.vec.get(0) instanceof Str) {
                                    String[] words = ((Str) pair.vec.get(0)).str.split("\\|");
                                    Log.i("TT-WORDS", terp.arrayToString(words));
                                    toast_text += "\n\n" + Static.arrayToString(words);
                                    if (words[1].equals("link")) {
                                        Uri uri = new Uri.Builder().scheme("terse").path(words[2]).build();
                                        Intent intent = new Intent("android.intent.action.MAIN", uri);
                                        intent.setClass(getApplicationContext(), TerseActivity.class);

                                        startActivity(intent);
                                    }
                                }
                            }
                        } else {
                            // NEW STYLE
                            terp.say("NEW STYLE LIST SELECT #%d link=<%s> label=<%s>", position,
                                    links.get(position), labels.get(position));
                            if (links.get(position).length() > 0) {
                                Uri uri = new Uri.Builder().scheme("terse").path(links.get(position)).build();
                                Intent intent = new Intent("android.intent.action.MAIN", uri);
                                intent.setClass(getApplicationContext(), TerseActivity.class);

                                startActivity(intent);
                            }
                        }
                        // }
                        // Toast.makeText(getApplicationContext(),
                        // ((TextView) view).getText(),
                        // Toast.LENGTH_SHORT).show();
                    }
                });
                setContentView(listv);
                return;
            } else if (type.str.equals("edit") && value instanceof Str) {
                final EditText ed = new EditText(this);

                ed.setText(taSaveMe == null ? value.toString() : taSaveMe);

                ed.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE
                        | InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
                ed.setLayoutParams(widgetParams);
                // ed.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
                ed.setTextAppearance(this, R.style.teletype);
                ed.setBackgroundColor(Color.BLACK);
                ed.setGravity(Gravity.TOP);
                ed.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET);
                ed.setVerticalFadingEdgeEnabled(true);
                ed.setVerticalScrollBarEnabled(true);
                ed.setOnKeyListener(new OnKeyListener() {
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        // If the event is a key-down event on the "enter"
                        // button
                        // if ((event.getAction() == KeyEvent.ACTION_DOWN)
                        // &&
                        // (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        // // Perform action on key press
                        // Toast.makeText(TerseActivity.this, ed.getText(),
                        // Toast.LENGTH_SHORT).show();
                        // return true;
                        // }
                        return false;
                    }
                });

                Button btn = new Button(this);
                btn.setText("Save");
                btn.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        // Perform action on clicks
                        String text = ed.getText().toString();
                        text = Parser.charSubsts(text);
                        Toast.makeText(TerseActivity.this, text, Toast.LENGTH_SHORT).show();
                        String action = stringAt(d, "action");
                        String query = "";

                        String f1 = stringAt(d, "field1");
                        String v1 = stringAt(d, "value1");
                        String f2 = stringAt(d, "field2");
                        String v2 = stringAt(d, "value2");
                        f1 = (f1 == null) ? "f1null" : f1;
                        v1 = (v1 == null) ? "v1null" : v1;
                        f2 = (f2 == null) ? "f2null" : f2;
                        v2 = (v2 == null) ? "v2null" : v2;

                        startTerseActivity(action, query, stringAt(d, "field1"), stringAt(d, "value1"),
                                stringAt(d, "field2"), stringAt(d, "value2"), "text", text);
                    }
                });

                LinearLayout linear = new LinearLayout(this);
                linear.setOrientation(LinearLayout.VERTICAL);
                linear.addView(btn);
                linear.addView(ed);
                setContentView(linear);
                return;

            } else if (type.str.equals("draw") && value instanceof Vec) {
                Vec v = ((Vec) value);
                DrawView dv = new DrawView(this, v.vec, d);
                dv.setLayoutParams(widgetParams);
                setContentView(dv);
                return;
            } else if (type.str.equals("live")) {
                Blk blk = value.mustBlk();
                Blk event = Static.urAt(d, "event").asBlk();
                TerseSurfView tsv = new TerseSurfView(this, blk, event);
                setContentView(tsv);
                return;
            } else if (type.str.equals("fnord")) {
                Blk blk = value.mustBlk();
                Blk event = Static.urAt(d, "event").asBlk();
                FnordView fnord = new FnordView(this, blk, event);
                setContentView(fnord);
                return;
            } else if (type.str.equals("world") && value instanceof Str) {
                String newWorld = value.toString();
                if (Terp.WORLD_P.matcher(newWorld).matches()) {
                    world = newWorld;
                    resetTerp();
                    explain = Static.fmt("Switching to world <%s>\nUse menu to go Home.", world);
                    Toast.makeText(getApplicationContext(), explain, Toast.LENGTH_LONG).show();
                } else {
                    terp.toss("Bad world syntax (must be 3 letters then 0 to 3 digits: <%s>", newWorld);
                }
                // Fall thru for explainv.setText(explain).
            } else if (type.str.equals("text")) {
                explain = "<<< " + title + " >>>\n\n" + value.toString();
                // Fall thru for explainv.setText(explain).
            } else if (type.str.equals("html")) {
                final WebView webview = new WebView(this);
                // webview.loadData(value.toString(), "text/html", null);
                webview.loadDataWithBaseURL("terse://terse", value.toString(), "text/html", "UTF-8", null);
                webview.setWebViewClient(new WebViewClient() {
                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, String url) {
                        // terp.say("WebView UrlLoading: url=%s", url);
                        URI uri = URI.create("" + url);
                        // terp.say("WebView UrlLoading: URI=%s", uri);
                        terp.say("WebView UrlLoading: getPath=%s", uri.getPath());
                        terp.say("WebView UrlLoading: getQuery=%s", uri.getQuery());

                        // Toast.makeText(getApplicationContext(),
                        // uri.toASCIIString(), Toast.LENGTH_SHORT)
                        // .show();
                        // webview.invalidate();
                        //
                        // TextView quick = new
                        // TextView(TerseActivity.this);
                        // quick.setText(uri.toASCIIString());
                        // quick.setBackgroundColor(Color.BLACK);
                        // quick.setTextColor(Color.WHITE);
                        // setContentView(quick);

                        startTerseActivity(uri.getPath(), uri.getQuery());

                        return true;
                    }
                });

                // webview.setWebChromeClient(new WebChromeClient());
                webview.getSettings().setBuiltInZoomControls(true);
                // webview.getSettings().setJavaScriptEnabled(true);
                webview.getSettings().setDefaultFontSize(18);
                webview.getSettings().setNeedInitialFocus(true);
                webview.getSettings().setSupportZoom(true);
                webview.getSettings().setSaveFormData(true);
                setContentView(webview);

                // ScrollView scrollv = new ScrollView(this);
                // scrollv.addView(webview);
                // setContentView(scrollv);
                return;
            } else {
                explain = "Unknown page type: " + type.str + " with vaule type: " + value.cls
                        + "\n\n##############\n\n";
                explain += value.toString();
                // Fall thru for explainv.setText(explain).
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            explain = Static.describe(ex);
        }
    }

    TextView explainv = new TextView(this);
    explainv.setText(explain);
    explainv.setBackgroundColor(Color.BLACK);
    explainv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
    explainv.setTextColor(Color.YELLOW);

    SetContentViewWithHomeButtonAndScroll(explainv);
}

From source file:org.apache.jmeter.protocol.http.util.ConversionUtils.java

/**
 * Generate an absolute URL from a possibly relative location,
 * allowing for extraneous leading "../" segments.
 * The Java {@link URL#URL(URL, String)} constructor does not remove these.
 *
 * @param baseURL the base URL which is used to resolve missing protocol/host in the location
 * @param location the location, possibly with extraneous leading "../"
 * @return URL with extraneous ../ removed
 * @throws MalformedURLException when the given <code>URL</code> is malformed
 * @see <a href="https://bz.apache.org/bugzilla/show_bug.cgi?id=46690">Bug 46690 - handling of 302 redirects with invalid relative paths</a>
 *///w  ww . j  a va 2s  .  co m
public static URL makeRelativeURL(URL baseURL, String location) throws MalformedURLException {
    URL initial = new URL(baseURL, location);

    // skip expensive processing if it cannot apply
    if (!location.startsWith("../")) {// $NON-NLS-1$
        return initial;
    }
    String path = initial.getPath();
    // Match /../[../] etc.
    Pattern p = Pattern.compile("^/((?:\\.\\./)+)"); // $NON-NLS-1$
    Matcher m = p.matcher(path);
    if (m.lookingAt()) {
        String prefix = m.group(1); // get ../ or ../../ etc.
        if (location.startsWith(prefix)) {
            return new URL(baseURL, location.substring(prefix.length()));
        }
    }
    return initial;
}

From source file:org.exoplatform.wiki.rendering.internal.parser.confluence.ConfluenceLinkReferenceParser.java

public ConfluenceLink parseAsLink(String rawReference) {
    ConfluenceLink link = new ConfluenceLink();
    StringBuffer buf = new StringBuffer(rawReference);
    link.setRawReference(rawReference);//from  w w  w. ja v a2 s  .  co m
    if (!rawReference.startsWith("~")) {
        StringBuffer shortcutBuf = new StringBuffer(rawReference);
        link.setShortcutName(trimIfPossible(divideAfterLast(shortcutBuf, '@')));
        if (!StringUtils.isEmpty(link.getShortcutName())) {
            link.setShortcutValue(shortcutBuf.toString());
        }
    }
    link.setAttachmentName(trimIfPossible(divideAfter(buf, '^')));
    link.setAnchor(trimIfPossible(divideAfter(buf, '#')));
    Matcher matcher = URL_SCHEME_PATTERN.matcher(buf.toString().trim());
    if (matcher.lookingAt()) {
        link.setUriPrefix(trimIfPossible(divideOn(buf, ':')));
    } else {
        link.setDestinationReference(buf.toString().trim());
    }
    return link;
}