Example usage for java.util Scanner findInLine

List of usage examples for java.util Scanner findInLine

Introduction

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

Prototype

public String findInLine(Pattern pattern) 

Source Link

Document

Attempts to find the next occurrence of the specified pattern ignoring delimiters.

Usage

From source file:com.tesora.dve.tools.CLIBuilder.java

protected static String scanFilePath(Scanner scanner) {
    if (scanner.hasNext()) {
        final String token = scanner.next();
        if (token.startsWith("\"") || token.startsWith("'")) {
            final String quote = String.valueOf(token.charAt(0));
            if (!token.endsWith(quote)) {
                final String remainder = scanner.findInLine(".+?" + quote);
                return token.substring(1) + remainder.substring(0, remainder.length() - 1);
            }/* ww  w  .  jav a2 s  . c  om*/

            return token.substring(1, token.length() - 1);
        }

        return token;
    }

    return StringUtils.EMPTY;
}

From source file:edu.cmu.lti.oaqa.framework.eval.gs.PassageGoldStandardFilePersistenceProvider.java

@Override
public boolean initialize(ResourceSpecifier aSpecifier, Map<String, Object> aAdditionalParams)
        throws ResourceInitializationException {
    boolean ret = super.initialize(aSpecifier, aAdditionalParams);
    String dataset = (String) getParameterValue("DataSet");
    Pattern lineSyntaxPattern = Pattern.compile((String) getParameterValue("LineSyntax"));
    try {// w w w.  j  a  v a  2s. c o m
        Resource[] resources = resolver.getResources((String) getParameterValue("PathPattern"));
        for (Resource resource : resources) {
            Scanner scanner = new Scanner(resource.getInputStream());
            while (scanner.findInLine(lineSyntaxPattern) != null) {
                MatchResult result = scanner.match();
                DatasetSequenceId id = new DatasetSequenceId(dataset, result.group(1));
                List<GoldStandardSpan> list = id2gsSpans.get(id);
                if (list == null) {
                    list = new ArrayList<GoldStandardSpan>();
                    id2gsSpans.put(id, list);
                }
                GoldStandardSpan annotation = new GoldStandardSpan(result.group(2),
                        Integer.parseInt(result.group(3)), Integer.parseInt(result.group(4)), result.group(5));
                list.add(annotation);
                if (scanner.hasNextLine()) {
                    scanner.nextLine();
                } else {
                    break;
                }
            }
            scanner.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return ret;
}

From source file:org.apache.taverna.scufl2.api.io.structure.StructureReader.java

private String parseName(Scanner scanner) {
    String name = scanner.findInLine("'(.*[^\\\\])'");
    return name.substring(1, name.length() - 1);
}

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

/**
* Loads the reference data contained in separate data files
*/// w w w  . j  a va  2  s  . c  o  m
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:com.android.ddmuilib.log.event.DisplaySync.java

/**
 * Generates the tooltips text for an event.
 * This method decodes the cryptic details string.
 * @param auth The authority associated with the event
 * @param details The details string//from w w w.j  a  va 2 s . c  om
 * @param eventSource server, poll, etc.
 * @return The text to display in the tooltips
 */
private String getTextFromDetails(int auth, String details, int eventSource) {

    StringBuffer sb = new StringBuffer();
    sb.append(AUTH_NAMES[auth]).append(": \n");

    Scanner scanner = new Scanner(details);
    Pattern charPat = Pattern.compile("[a-zA-Z]");
    Pattern numPat = Pattern.compile("[0-9]+");
    while (scanner.hasNext()) {
        String key = scanner.findInLine(charPat);
        int val = Integer.parseInt(scanner.findInLine(numPat));
        if (auth == GMAIL && "M".equals(key)) {
            sb.append("messages from server: ").append(val).append("\n");
        } else if (auth == GMAIL && "L".equals(key)) {
            sb.append("labels from server: ").append(val).append("\n");
        } else if (auth == GMAIL && "C".equals(key)) {
            sb.append("check conversation requests from server: ").append(val).append("\n");
        } else if (auth == GMAIL && "A".equals(key)) {
            sb.append("attachments from server: ").append(val).append("\n");
        } else if (auth == GMAIL && "U".equals(key)) {
            sb.append("op updates from server: ").append(val).append("\n");
        } else if (auth == GMAIL && "u".equals(key)) {
            sb.append("op updates to server: ").append(val).append("\n");
        } else if (auth == GMAIL && "S".equals(key)) {
            sb.append("send/receive cycles: ").append(val).append("\n");
        } else if ("Q".equals(key)) {
            sb.append("queries to server: ").append(val).append("\n");
        } else if ("E".equals(key)) {
            sb.append("entries from server: ").append(val).append("\n");
        } else if ("u".equals(key)) {
            sb.append("updates from client: ").append(val).append("\n");
        } else if ("i".equals(key)) {
            sb.append("inserts from client: ").append(val).append("\n");
        } else if ("d".equals(key)) {
            sb.append("deletes from client: ").append(val).append("\n");
        } else if ("f".equals(key)) {
            sb.append("full sync requested\n");
        } else if ("r".equals(key)) {
            sb.append("partial sync unavailable\n");
        } else if ("X".equals(key)) {
            sb.append("hard error\n");
        } else if ("e".equals(key)) {
            sb.append("number of parse exceptions: ").append(val).append("\n");
        } else if ("c".equals(key)) {
            sb.append("number of conflicts: ").append(val).append("\n");
        } else if ("a".equals(key)) {
            sb.append("number of auth exceptions: ").append(val).append("\n");
        } else if ("D".equals(key)) {
            sb.append("too many deletions\n");
        } else if ("R".equals(key)) {
            sb.append("too many retries: ").append(val).append("\n");
        } else if ("b".equals(key)) {
            sb.append("database error\n");
        } else if ("x".equals(key)) {
            sb.append("soft error\n");
        } else if ("l".equals(key)) {
            sb.append("sync already in progress\n");
        } else if ("I".equals(key)) {
            sb.append("io exception\n");
        } else if (auth == CONTACTS && "g".equals(key)) {
            sb.append("aggregation query: ").append(val).append("\n");
        } else if (auth == CONTACTS && "G".equals(key)) {
            sb.append("aggregation merge: ").append(val).append("\n");
        } else if (auth == CONTACTS && "n".equals(key)) {
            sb.append("num entries: ").append(val).append("\n");
        } else if (auth == CONTACTS && "p".equals(key)) {
            sb.append("photos uploaded from server: ").append(val).append("\n");
        } else if (auth == CONTACTS && "P".equals(key)) {
            sb.append("photos downloaded from server: ").append(val).append("\n");
        } else if (auth == CALENDAR && "F".equals(key)) {
            sb.append("server refresh\n");
        } else if (auth == CALENDAR && "s".equals(key)) {
            sb.append("server diffs fetched\n");
        } else {
            sb.append(key).append("=").append(val);
        }
    }
    if (eventSource == 0) {
        sb.append("(server)");
    } else if (eventSource == 1) {
        sb.append("(local)");
    } else if (eventSource == 2) {
        sb.append("(poll)");
    } else if (eventSource == 3) {
        sb.append("(user)");
    }
    return sb.toString();
}

From source file:com.theoryinpractise.clojure.AbstractClojureCompilerMojo.java

protected void callClojureWith(ExecutionMode executionMode, File[] sourceDirectory, File outputDirectory,
        List<String> compileClasspathElements, String mainClass, String[] clojureArgs)
        throws MojoExecutionException {

    outputDirectory.mkdirs();//  w ww .j a  va2  s.  c o  m

    String classpath = manifestClasspath(sourceDirectory, outputDirectory, compileClasspathElements);

    final String javaExecutable = getJavaExecutable();
    getLog().debug("Java exectuable used:  " + javaExecutable);
    getLog().debug("Clojure manifest classpath: " + classpath);
    CommandLine cl = null;

    if (ExecutionMode.INTERACTIVE == executionMode && SystemUtils.IS_OS_WINDOWS
            && spawnInteractiveConsoleOnWindows) {
        Scanner sc = new Scanner(windowsConsole);
        Pattern pattern = Pattern.compile("\"[^\"]*\"|'[^']*'|[\\w'/]+");
        cl = new CommandLine(sc.findInLine(pattern));
        String param;
        while ((param = sc.findInLine(pattern)) != null) {
            cl.addArgument(param);
        }
        cl.addArgument(javaExecutable);
    } else {
        cl = new CommandLine(javaExecutable);
    }

    if (vmargs != null) {
        cl.addArguments(vmargs, false);
    }

    cl.addArgument("-Dclojure.compile.path=" + escapeFilePath(outputDirectory), false);

    if (warnOnReflection)
        cl.addArgument("-Dclojure.compile.warn-on-reflection=true");

    cl.addArguments(clojureOptions, false);

    cl.addArgument("-jar");
    File jar;
    if (prependClasses != null && prependClasses.size() > 0) {
        jar = createJar(classpath, prependClasses.get(0));
        cl.addArgument(jar.getAbsolutePath(), false);
        List<String> allButFirst = prependClasses.subList(1, prependClasses.size());
        cl.addArguments(allButFirst.toArray(new String[allButFirst.size()]));
        cl.addArgument(mainClass);
    } else {
        jar = createJar(classpath, mainClass);
        cl.addArgument(jar.getAbsolutePath(), false);
    }

    if (clojureArgs != null) {
        cl.addArguments(clojureArgs, false);
    }

    getLog().debug("Command line: " + cl.toString());

    Executor exec = new DefaultExecutor();
    Map<String, String> env = new HashMap<String, String>(System.getenv());
    //        env.put("path", ";");
    //        env.put("path", System.getProperty("java.home"));

    ExecuteStreamHandler handler = new PumpStreamHandler(System.out, System.err, System.in);
    exec.setStreamHandler(handler);
    exec.setWorkingDirectory(getWorkingDirectory());
    ShutdownHookProcessDestroyer destroyer = new ShutdownHookProcessDestroyer();
    exec.setProcessDestroyer(destroyer);

    int status;
    try {
        status = exec.execute(cl, env);
    } catch (ExecuteException e) {
        status = e.getExitValue();
    } catch (IOException e) {
        status = 1;
    }

    if (status != 0) {
        throw new MojoExecutionException("Clojure failed.");
    }

}

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

/**
 * @see {@link #testJspKeys()}/*from   ww w.j  a  va 2  s .  c  o  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:com.wikitude.phonegap.WikitudePlugin.java

/**
 * // www.  java2  s. co  m
 * @return true if device chip has neon-command support
 */
private boolean hasNeonSupport() {
    /* Read cpu info */

    FileInputStream fis;
    try {
        fis = new FileInputStream("/proc/cpuinfo");

    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return false;
    }

    Scanner scanner = new Scanner(fis);

    boolean neonSupport = false;

    try {

        while (scanner.hasNextLine()) {

            if (!neonSupport && (scanner.findInLine("neon") != null)) {

                neonSupport = true;

            }

            scanner.nextLine();

        }

    } catch (Exception e) {

        Log.i("Wikitudeplugin", "error while getting info about neon support" + e.getMessage());
        e.printStackTrace();

    } finally {

        scanner.close();

    }

    return neonSupport;
}