Example usage for java.util Scanner findWithinHorizon

List of usage examples for java.util Scanner findWithinHorizon

Introduction

In this page you can find the example usage for java.util Scanner findWithinHorizon.

Prototype

public String findWithinHorizon(Pattern pattern, int horizon) 

Source Link

Document

Attempts to find the next occurrence of the specified pattern.

Usage

From source file:net.jperf.logback.AppenderTest.java

public void testAppenders() throws Exception {
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(lc);/*from  ww  w .j ava  2 s. c o  m*/
    // the context was probably already configured by default configuration 
    // rules
    lc.reset();
    configurator.doConfigure(getClass().getResource("logback.xml"));

    AsyncCoalescingStatisticsAppender appender = (AsyncCoalescingStatisticsAppender) lc
            .getLogger(StopWatch.DEFAULT_LOGGER_NAME).getAppender("coalescingStatistics");

    //log from a bunch of threads
    TestLoggingThread[] testThreads = new TestLoggingThread[10];
    for (int i = 0; i < testThreads.length; i++) {
        testThreads[i] = new TestLoggingThread();
        testThreads[i].start();
    }

    for (TestLoggingThread testThread : testThreads) {
        testThread.join();
    }

    //close the output appender, which prevents us from returning until this method completes.
    appender.stop();

    //simple verification ensures that the total number of logged messages is correct.
    //tagName  avg           min     max     std dev       count, which is group 1
    String regex = "tag\\d\\s*\\d+\\.\\d\\s*\\d+\\s*\\d+\\s*\\d+\\.\\d\\s*(\\d+)";
    Pattern statLinePattern = Pattern.compile(regex);
    Scanner scanner = new Scanner(new File("target/statisticsLogback.log"));

    int totalCount = 0;
    while (scanner.findWithinHorizon(statLinePattern, 0) != null) {
        totalCount += Integer.parseInt(scanner.match().group(1));
    }
    assertEquals(testThreads.length * TestLoggingThread.STOP_WATCH_COUNT, totalCount);
}

From source file:net.jperf.log4j.AppenderTest.java

public void testAppendersTimesliceOver() throws Exception {
    // need to do immediateflush on the fileappender since close will not be called
    DOMConfigurator.configure(getClass().getResource("log4j-timeslicebug.xml"));

    AsyncCoalescingStatisticsAppender appender = (AsyncCoalescingStatisticsAppender) Logger
            .getLogger(StopWatch.DEFAULT_LOGGER_NAME).getAppender("coalescingStatistics");

    //log from a bunch of threads
    TestLoggingThread[] testThreads = new TestLoggingThread[10];
    for (int i = 0; i < testThreads.length; i++) {
        testThreads[i] = new TestLoggingThread();
        testThreads[i].start();// w ww  .  j a v a  2s .  c o  m
    }

    for (TestLoggingThread testThread : testThreads) {
        testThread.join();
    }

    // we should see all the logging after waiting this long
    Thread.sleep(2 * appender.getTimeSlice());

    //simple verification ensures that the total number of logged messages is correct.
    //tagName  avg           min     max     std dev       count, which is group 1
    String regex = "tag\\d+\\s*\\d+\\.\\d\\s*\\d+\\s*\\d+\\s*\\d+\\.\\d\\s*(\\d+)";
    Pattern statLinePattern = Pattern.compile(regex);
    Scanner scanner = new Scanner(new File("target/statisticsLog-timeslicebug.log"));

    int totalCount = 0;
    while (scanner.findWithinHorizon(statLinePattern, 0) != null) {
        totalCount += Integer.parseInt(scanner.match().group(1));
    }
    assertEquals(testThreads.length * TestLoggingThread.STOP_WATCH_COUNT, totalCount);
}

From source file:org.teleportr.plugin.BahnDePlugIn.java

public ArrayList<Ride> find(Place orig, Place dest, Date time, Teleporter tlp) {

    StringBuilder url = new StringBuilder();
    url.append("http://mobile.bahn.de/bin/mobil/query.exe/dox?");
    url.append("n=1");

    //        if (orig.city!=null)
    //           Log.d(TAG, "city: "+orig.city);
    if (orig.address != null)
        url.append("&f=2&s=")
                .append(URLEncoder.encode(orig.address + (orig.city != null ? (", " + orig.city) : "") + "!"));
    else/*from  w ww . j a  va  2  s .  co  m*/
        url.append("&f=1&s=")
                .append(URLEncoder.encode(orig.name + (orig.city != null ? (", " + orig.city) : "") + "!"));

    if (dest.address != null)
        url.append("&o=2&z=")
                .append(URLEncoder.encode(dest.address + (dest.city != null ? (", " + dest.city) : "") + "!"));
    else
        url.append("&o=1&z=")
                .append(URLEncoder.encode(dest.name + (dest.city != null ? (", " + dest.city) : "") + "!"));

    url.append("&d="); // date
    url.append((new SimpleDateFormat("ddMMyy")).format(time));
    url.append("&t="); // time
    url.append((new SimpleDateFormat("HHmm")).format(time));
    url.append("&start=Suchen");
    //        Log.d(TAG, "url: "+url.toString());

    // fetch
    try {
        Ride r;
        MatchResult m;
        rides.clear();
        Scanner scanner = new Scanner(client.execute(new HttpGet(url.toString())).getEntity().getContent(),
                "iso-8859-1");
        Log.d(TAG, " url: " + url.toString());
        while (scanner.findWithinHorizon("<a href=\"([^\"]*)\">(\\d\\d):(\\d\\d)<br />(\\d\\d):(\\d\\d)",
                10000) != null) {
            m = scanner.match();
            Date dep = parseDate(m.group(2), m.group(3));
            if (dep.getTime() - time.getTime() > 100000) {
                r = new Ride();
                r.orig = orig;
                r.dest = dest;
                r.mode = Ride.MODE_TRANSIT;
                r.dep = dep;
                r.arr = parseDate(m.group(4), m.group(5));
                r.price = -1;
                r.fun = 3;
                r.eco = 3;
                r.fast = 1;
                r.social = 2;
                r.green = 4;
                r.uri = m.group(1).replace("&amp;", "&");

                rides.add(r);
                Log.d(TAG, " + found " + r.uri);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "Mist!");
        e.printStackTrace();
    }
    return rides;
}

From source file:co.pugo.convert.ConvertServlet.java

/**
 * extract a set of image links/*from ww  w .jav a  2 s.c  o m*/
 * @param content document content as String
 * @return Set of http links to images
 */
private Set<String> extractImageLinks(String content) {
    final Set<String> imageLinks = new HashSet<>();
    final Scanner scanner = new Scanner(content);
    final Pattern imgPattern = Pattern.compile("<img(.*?)>", Pattern.DOTALL);
    final Pattern srcPattern = Pattern.compile("src=\"(.*?)\"");

    Matcher matchSrc;
    String imgMatch;

    while (scanner.findWithinHorizon(imgPattern, 0) != null) {
        imgMatch = scanner.match().group(1);
        matchSrc = srcPattern.matcher(imgMatch);
        if (matchSrc.find())
            imageLinks.add(matchSrc.group(1));
    }

    scanner.close();
    return imageLinks;
}

From source file:com.googlecode.esms.provider.Tim.java

/**
 * Search for a pattern inside a stream.
 * @param source The stream to search into.
 * @param pattern The pattern to match.//from  ww  w.j a  v a2  s  .c  om
 * @return List of matches found.
 */
private List<String> findPattern(InputStream source, Pattern pattern) {
    List<String> results = new ArrayList<String>();
    Scanner scanner = new Scanner(source, "UTF-8");

    String match = "";
    while (match != null) {
        match = scanner.findWithinHorizon(pattern, 0);
        if (match != null)
            results.add(match);
    }

    scanner.close();
    return results;
}

From source file:busradar.madison.StopDialog.java

@Override
public void show() {
    new Thread() {
        @Override/*from  w  w w.  j a  v  a  2 s  .c  o  m*/
        public void run() {

            for (final RouteURL r : routes) {
                G.activity.runOnUiThread(new Runnable() {
                    public void run() {
                        cur_loading_text
                                .setText(String.format("Loading route %s...", G.route_points[r.route].name));
                    }
                });

                final ArrayList<RouteTime> curtimes = new ArrayList<RouteTime>();
                try {
                    System.err.printf("BusRadar URL %s\n", TRANSITTRACKER_URL + r.url);
                    URL url = new URL(TRANSITTRACKER_URL + r.url);
                    URLConnection url_conn = url.openConnection();
                    if (url_conn instanceof HttpsURLConnection) {
                        ((HttpsURLConnection) url_conn).setHostnameVerifier(new HostnameVerifier() {

                            public boolean verify(String hostname, SSLSession session) {
                                return true;
                            }
                        });
                    }
                    InputStream is = url_conn.getInputStream();
                    Scanner scan = new Scanner(is, "UTF-8");

                    //String outstr_cur = "Route " + r.route + "\n";

                    if (scan.findWithinHorizon(num_vehicles_re, 0) != null) {

                        while (scan.findWithinHorizon(time_re, 0) != null) {
                            RouteTime time = new RouteTime();
                            time.route = r.route;
                            time.time = scan.match().group(1).replace(".", "");
                            time.dir = scan.match().group(2);
                            //time.date = DateFormat.getTimeInstance(DateFormat.SHORT).parse(time.time);

                            SimpleDateFormat f = new SimpleDateFormat("h:mm aa", Locale.US);
                            time.date = f.parse(time.time);
                            r.status = RouteURL.DONE;

                            //outstr_cur += String.format("%s to %s\n", time.time, time.dir);
                            curtimes.add(time);
                        }

                        while (scan.findWithinHorizon(time_re_backup, 0) != null) {
                            RouteTime time = new RouteTime();
                            time.route = r.route;
                            time.time = scan.match().group(1).replace(".", "");
                            //time.dir = scan.match().group(2);
                            //time.date = DateFormat.getTimeInstance(DateFormat.SHORT).parse(time.time);

                            SimpleDateFormat f = new SimpleDateFormat("h:mm aa", Locale.US);
                            time.date = f.parse(time.time);
                            r.status = RouteURL.DONE;

                            //outstr_cur += String.format("%s to %s\n", time.time, time.dir);
                            curtimes.add(time);
                        }

                    }

                    //                  else if (scan.findWithinHorizon(no_busses_re, 0) != null) {
                    //                     r.status = RouteURL.NO_MORE_TODAY; 
                    //                  } 
                    //                  else if (scan.findWithinHorizon(no_timepoints_re, 0) != null) {
                    //                     r.status = RouteURL.NO_TIMEPOINTS;
                    //                  }
                    //                  else {
                    //                     r.status = RouteURL.ERROR;
                    //                     System.out.printf("BusRadar: Could not get stop info for %s\n", r.url);
                    //                     
                    //                     throw new Exception("Error parsing TransitTracker webpage.");
                    //                  }
                    else {
                        r.status = RouteURL.NO_STOPS_UNKONWN;
                    }

                    //r.text = outstr_cur;

                    G.activity.runOnUiThread(new Runnable() {
                        public void run() {
                            times.addAll(curtimes);
                            StopDialog.this.update_times();
                        }
                    });

                }
                //               catch  (final IOException ioe) {
                //                  log_problem(ioe);
                //                  G.activity.runOnUiThread(new Runnable() {
                //                     public void run() {
                //                        final Context ctx = StopDialog.this.getContext();
                //                        
                //                        StopDialog.this.setContentView(new RelativeLayout(ctx) {{
                //                           addView(new TextView(ctx) {{
                //                              setText(Html.fromHtml("Error downloading data. Is the data connection enabled?"+
                //                                                  "<p>Report problems to <a href='mailto:support@busradarapp.com'>support@busradarapp.com</a><p>"+ioe));
                //                              setPadding(5, 5, 5, 5);
                //                              this.setMovementMethod(LinkMovementMethod.getInstance());
                //                           }}, new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
                //                        }});
                //                     }
                //                  });                  
                //                  return;
                //               }
                catch (Exception e) {
                    log_problem(e);

                    String custom_msg = "";
                    final String turl = TRANSITTRACKER_URL + r.url;
                    if ((e instanceof SocketException) || (e instanceof UnknownHostException)) {
                        // data connection doesn't work
                        custom_msg = "Error downloading data. Is the data connection enabled?"
                                + "<p>Report problems to <a href='mailto:support@busradarapp.com'>support@busradarapp.com</a><p>"
                                + TextUtils.htmlEncode(e.toString());
                    } else {

                        String rurl = String.format(
                                "http://www.cityofmadison.com/metro/BusStopDepartures/StopID/%04d.pdf", stopid);
                        custom_msg = "Trouble retrieving real-time arrival estimates from <a href='" + turl
                                + "'>this</a> TransitTracker webpage, which is displayed below. "
                                + "Meanwhile, try PDF timetable <a href='" + rurl + "'>here</a>. "
                                + "Contact us at <a href='mailto:support@busradarapp.com'>support@busradarapp.com</a> to report the problem.<p>"
                                + TextUtils.htmlEncode(e.toString());
                    }

                    final String msg = custom_msg;

                    G.activity.runOnUiThread(new Runnable() {
                        public void run() {
                            final Context ctx = StopDialog.this.getContext();

                            StopDialog.this.setContentView(new RelativeLayout(ctx) {
                                {
                                    addView(new TextView(ctx) {
                                        {
                                            setId(1);
                                            setText(Html.fromHtml(msg));
                                            setPadding(5, 5, 5, 5);
                                            this.setMovementMethod(LinkMovementMethod.getInstance());
                                        }
                                    }, new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));

                                    addView(new WebView(ctx) {
                                        {
                                            setWebViewClient(new WebViewClient());
                                            loadUrl(turl);
                                        }
                                    }, new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
                                            LayoutParams.FILL_PARENT) {
                                        {
                                            addRule(RelativeLayout.BELOW, 1);
                                        }
                                    });
                                }
                            });
                        }
                    });
                    return;
                }

            }

            G.activity.runOnUiThread(new Runnable() {
                public void run() {
                    cur_loading_text.setText("");
                }
            });
        }
    }.start();

    super.show();

}

From source file:com.jayway.maven.plugins.android.AbstractAndroidMojo.java

/**
 * Extracts the package name from an XmlTree dump of AndroidManifest.xml by the <code>aapt</code> tool.
 *
 * @param aaptDumpXmlTree output from <code>aapt dump xmltree &lt;apkFile&gt; AndroidManifest.xml
 * @return the package name from inside the apkFile.
 *///from w  w  w.ja v a  2  s  . c o m
protected String extractPackageNameFromAndroidManifestXmlTree(String aaptDumpXmlTree) {
    final Scanner scanner = new Scanner(aaptDumpXmlTree);
    // Finds the root element named "manifest".
    scanner.findWithinHorizon("^E: manifest", 0);
    // Finds the manifest element's attribute named "package".
    scanner.findWithinHorizon("  A: package=\"", 0);
    // Extracts the package value including the trailing double quote.
    String packageName = scanner.next(".*?\"");
    // Removes the double quote.
    packageName = packageName.substring(0, packageName.length() - 1);
    return packageName;
}

From source file:com.jsmartframework.web.manager.BeanHandler.java

private void readJspPageResource(ServletContext context, String path, JspPageBean jspPageBean) {
    InputStream is = context.getResourceAsStream(getForwardPath(path));

    if (is != null) {
        Scanner fileScanner = new Scanner(is);
        Set<String> includes = new LinkedHashSet<>();

        try {/*  w ww. ja v a2s .c o  m*/
            String lineScan;
            while ((lineScan = fileScanner.findWithinHorizon(HANDLER_EL_PATTERN, 0)) != null) {

                boolean hasInclude = false;
                Matcher matcher = INCLUDE_PATTERN.matcher(lineScan);

                while (matcher.find()) {
                    hasInclude = true;
                    includes.add(matcher.group(1));
                }

                if (hasInclude) {
                    continue;
                }

                matcher = ExpressionHandler.EL_PATTERN.matcher(lineScan);
                while (matcher.find()) {
                    for (String name : matcher.group(1).split(Constants.SEPARATOR_REGEX)) {
                        if (webBeans.containsKey(name.trim())) {
                            jspPageBean.addBeanName(name.trim());
                        }
                    }
                }

                matcher = ExpressionHandler.JSP_PATTERN.matcher(lineScan);
                while (matcher.find()) {
                    for (String name : matcher.group(1).split(Constants.SEPARATOR_REGEX)) {
                        if (webBeans.containsKey(name.trim())) {
                            jspPageBean.addBeanName(name.trim());
                        }
                    }
                }

                matcher = ExpressionHandler.ID_PATTERN.matcher(lineScan);
                while (matcher.find()) {
                    AnnotatedAction annotatedAction = getAnnotatedAction(matcher.group(1));
                    if (annotatedAction != null) {
                        jspPageBean.addBeanName(annotatedAction.getClassName());
                    }
                }
            }
        } finally {
            fileScanner.close();
        }

        // Read include page resources
        for (String include : includes) {
            String includeOwner = getForwardPath(path);
            includeOwner = includeOwner.substring(0, includeOwner.lastIndexOf(Constants.PATH_SEPARATOR) + 1);

            include = getRelativeIncludePath(includeOwner, include);
            readJspPageResource(context, include, jspPageBean);
        }
    }
}

From source file:org.alfresco.bm.api.v1.RestAPITest.java

/**
 * Point the test at a missing MongoDB//from  w ww  .j a va 2s . c om
 */
@Test
public synchronized void testScenario06() throws Exception {
    createTestRun("T06", "A test for scenario 06.", "01", "Scenario 06 - Run 01");

    // Set an incorrect MongoDB host
    PropSetBean propSetBean = new PropSetBean();
    propSetBean.setValue("localhostFAIL");
    propSetBean.setVersion(0);
    api.setTestRunProperty("T06", "01", PROP_MONGO_TEST_HOST, propSetBean);

    // Direct monitor
    org.alfresco.bm.test.Test test = ctx.getBean(org.alfresco.bm.test.Test.class);

    // Now schedule it
    TestRunSchedule schedule = new TestRunSchedule();
    schedule.setScheduled(System.currentTimeMillis());
    schedule.setVersion(0);
    api.scheduleTestRun("T06", "01", schedule);

    // Poke the test and check that the test run's new state brings it into
    // view
    test.forcePing();
    // The test run should not have started as the mongo host is invalid
    // from server 2.1 on the test would be STOPPED if incorrect server
    // connection - because otherwise it will restart over and over again.
    // depending on the test check speed the status would be scheduled or
    // stopped - but must never be started!
    checkTestRunState("T06", "01", TestRunState.STARTED, false);

    // Now check that the logs reflect the situation
    LogWatcher logWatcher = ctx.getBean(LogWatcher.class);
    boolean found = false;
    for (String logFilename : logWatcher.getLogFilenames()) {
        File logFile = new File(logFilename);
        Scanner scanner = new Scanner(logFile);
        try {
            String scanned = scanner.findWithinHorizon("localhostFAIL", 0);
            if (scanned != null) {
                found = true;
                break;
            }
        } finally {
            scanner.close();
        }
    }
    assertTrue("Failed to find error message for MongoDB host.", found);

    test.stop();
}