Example usage for java.util Scanner match

List of usage examples for java.util Scanner match

Introduction

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

Prototype

public MatchResult match() 

Source Link

Document

Returns the match result of the last scanning operation performed by this scanner.

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 w w w. ja va 2  s  . com*/
    // 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  w w .j  a  v a  2  s.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 v a  2 s  .  c  o  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  w  w  w . j  a  va  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:jp.go.nict.langrid.wrapper.ws_1_2.translation.AbstractTranslationService.java

/**
 * /*from  w  w w. jav a2  s . c  o m*/
 * 
 */
public final String multistatementTranslate(String sourceLang, String targetLang, String source,
        String delimiterRegx)
        throws AccessLimitExceededException, InvalidParameterException, LanguagePairNotUniquelyDecidedException,
        NoAccessPermissionException, NoValidEndpointsException, ProcessFailedException, ServerBusyException,
        ServiceNotActiveException, ServiceNotFoundException, UnsupportedLanguagePairException {
    checkStartupException();
    if (StringUtils.isBlank(delimiterRegx)) {
        throw new InvalidParameterException("delimiterRegx", "is Blank.");
    }
    StringBuilder sb = new StringBuilder();
    Scanner s = new Scanner(source).useDelimiter(delimiterRegx);
    int i = 0;
    while (s.hasNext()) {
        String text = s.next();
        MatchResult m = s.match();
        if (i != m.start()) {
            String tag = source.substring(i, m.start());
            sb.append(tag);
        }
        i = m.end();
        sb.append(invokeDoTranslation(sourceLang, targetLang, text));
    }
    if (source.length() != i) {
        String tag = source.substring(i);
        sb.append(tag);
    }

    return sb.toString();
}

From source file:com.medigy.persist.model.data.EntitySeedDataPopulator.java

/**
* Loads the reference data contained in separate data files
*//*from w w  w.j a  v  a 2 s  . com*/
protected void loadExternalReferenceData() {
    try {
        InputStream propertyFileStream = Environment.class.getResourceAsStream(EXTERNAL_DATA_PROPERTY_FILE);
        if (propertyFileStream == null)
            propertyFileStream = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream(EXTERNAL_DATA_PROPERTY_FILE);
        if (propertyFileStream == null) {
            log.warn("'" + EXTERNAL_DATA_PROPERTY_FILE
                    + "' property file not found for loading reference data contained " + "in external files.");
            return;
        }
        Properties props = new java.util.Properties();
        props.load(propertyFileStream);

        final Enumeration keys = props.keys();
        while (keys.hasMoreElements()) {
            final String className = (String) keys.nextElement();
            final String dataFileName = props.getProperty(className);
            InputStream stream = Environment.class.getResourceAsStream(dataFileName);
            if (stream == null)
                stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(dataFileName);
            Scanner sc = new Scanner(stream);
            int rowsAdded = 0;
            if (sc.hasNextLine()) {
                sc.findInLine(
                        "\\\"([ \\.0-9a-zA-Z]*)\\\"\\s*\\\"([ \\.0-9a-zA-Z]*)\\\"\\s*\\\"([ \\.0-9a-zA-Z]*)\\\"\\s*\\\"([ \\.0-9a-zA-Z]*)\\\"");
                try {
                    MatchResult result = sc.match();
                    final Class refClass = Class.forName(className);
                    final Object refObject = refClass.newInstance();
                    if (refObject instanceof AbstractReferenceEntity) {
                        final AbstractReferenceEntity refEntity = (AbstractReferenceEntity) refObject;
                        refEntity.setCode(result.group(0));
                        refEntity.setLabel(result.group(1));
                        refEntity.setDescription(result.group(2));
                        HibernateUtil.getSession().save(refEntity);
                        rowsAdded++;
                    }
                } catch (Exception e) {
                    log.error(className + ": Error at data row count = " + rowsAdded + " \n"
                            + ExceptionUtils.getStackTrace(e));
                }
            }
            sc.close();
            log.info(className + ", Rows Added = " + rowsAdded);
        }
        //InputStream stream = new FileInputStream("e:\\netspective\\medigy\\persistence\\database\\refdata\\icd9-codes.txt");
    } catch (Exception e) {
        log.error(ExceptionUtils.getStackTrace(e));
    }
}

From source file:de.iteratec.iteraplan.general.PropertiesTest.java

/**
 * @see {@link #testJspKeys()}/*from w  w  w  . ja va2 s  .  co m*/
 * @param collectedBundleKeys
 *          Bundle keys collected so far. Acts as in-out parameter.
 * @param p
 *          The pattern to find.
 * @param fileToProcess
 *          The file to be looked at.
 * @return true if a bundle key was missing.
 * @throws FileNotFoundException
 */
private boolean parseJspForBundleKeys(Set<String> collectedBundleKeys, Pattern p, File fileToProcess)
        throws FileNotFoundException {
    boolean wasSuccessful = true;

    if (fileToProcess.isDirectory()) {
        for (File f : fileToProcess.listFiles()) {
            boolean containedSuccess = parseJspForBundleKeys(collectedBundleKeys, p, f);
            if (!containedSuccess) {
                wasSuccessful = false;
            }
        }
    } else if (fileToProcess.getName().toLowerCase().endsWith("jsp")) {
        Scanner sc = new Scanner(fileToProcess);
        StringBuffer jspAsStringBuffer = new StringBuffer();
        while (sc.hasNextLine()) {
            jspAsStringBuffer.append(sc.nextLine());
        }
        String jspAsString = jspAsStringBuffer.toString();
        MatchResult result = null;
        sc = new Scanner(jspAsString);
        while (true) {
            if (sc.findInLine(p) == null) {
                break;
            }
            result = sc.match();
            String bundleKey = result.group(POSITION_OF_PROPERTY_IN_JSP_TAG); // refers to regexp which is passed into this method
            collectedBundleKeys.add(bundleKey);

            // omit registered keys and keys which contain variables
            if (!ACCEPTABLE_MISSES_LIST.contains(bundleKey) && !(bundleKey.contains("$"))) {
                for (LanguageFile l : languageFiles) {
                    if (!l.keySet().contains(bundleKey)) {
                        wasSuccessful = false;
                        LOGGER.info(
                                "Bundle key {0} defined in JSP {1} was not found in {2} ApplicationResources.properties!",
                                bundleKey, fileToProcess, l.language);
                    }
                }
            }
        }
    }

    return wasSuccessful;
}

From source file:busradar.madison.StopDialog.java

@Override
public void show() {
    new Thread() {
        @Override// w  ww .  ja v  a 2  s.co 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:org.perf4j.log4j.AppenderTest.java

public void testAppenders() throws Exception {
    DOMConfigurator.configure(getClass().getResource("log4j.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();/*from w  ww.j  a  v  a2 s. co  m*/
    }

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

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

    //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.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);
}