Example usage for java.util Scanner useDelimiter

List of usage examples for java.util Scanner useDelimiter

Introduction

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

Prototype

public Scanner useDelimiter(String pattern) 

Source Link

Document

Sets this scanner's delimiting pattern to a pattern constructed from the specified String .

Usage

From source file:com.zero_x_baadf00d.partialize.Partialize.java

/**
 * Build a JSON object from data taken from the scanner and
 * the given class type and instance./*from  w w  w  .j av  a2 s.  co m*/
 *
 * @param depth         The current depth
 * @param fields        The field names to requests
 * @param clazz         The class of the object to render
 * @param instance      The instance of the object to render
 * @param partialObject The partial JSON document
 * @return A JSON Object
 * @since 16.01.18
 */
private ObjectNode buildPartialObject(final int depth, String fields, final Class<?> clazz,
        final Object instance, final ObjectNode partialObject) {
    if (depth <= this.maximumDepth) {
        if (clazz.isAnnotationPresent(com.zero_x_baadf00d.partialize.annotation.Partialize.class)) {
            final List<String> closedFields = new ArrayList<>();
            List<String> allowedFields = Arrays.asList(clazz
                    .getAnnotation(com.zero_x_baadf00d.partialize.annotation.Partialize.class).allowedFields());
            List<String> defaultFields = Arrays.asList(clazz
                    .getAnnotation(com.zero_x_baadf00d.partialize.annotation.Partialize.class).defaultFields());
            if (allowedFields.isEmpty()) {
                allowedFields = new ArrayList<>();
                for (final Method m : clazz.getDeclaredMethods()) {
                    final String methodName = m.getName();
                    if (methodName.startsWith("get") || methodName.startsWith("has")) {
                        final char[] c = methodName.substring(3).toCharArray();
                        c[0] = Character.toLowerCase(c[0]);
                        allowedFields.add(new String(c));
                    } else if (methodName.startsWith("is")) {
                        final char[] c = methodName.substring(2).toCharArray();
                        c[0] = Character.toLowerCase(c[0]);
                        allowedFields.add(new String(c));
                    }
                }
            }
            if (defaultFields.isEmpty()) {
                defaultFields = allowedFields.stream().map(f -> {
                    if (this.aliases != null && this.aliases.containsValue(f)) {
                        for (Map.Entry<String, String> e : this.aliases.entrySet()) {
                            if (e.getValue().compareToIgnoreCase(f) == 0) {
                                return e.getKey();
                            }
                        }
                    }
                    return f;
                }).collect(Collectors.toList());
            }
            if (fields == null || fields.length() == 0) {
                fields = defaultFields.stream().collect(Collectors.joining(","));
            }
            Scanner scanner = new Scanner(fields);
            scanner.useDelimiter(com.zero_x_baadf00d.partialize.Partialize.SCANNER_DELIMITER);
            while (scanner.hasNext()) {
                String word = scanner.next();
                String args = null;
                if (word.compareTo("*") == 0) {
                    final StringBuilder sb = new StringBuilder();
                    if (scanner.hasNext()) {
                        scanner.useDelimiter("\n");
                        sb.append(",");
                        sb.append(scanner.next());
                    }
                    final Scanner newScanner = new Scanner(
                            allowedFields.stream().filter(f -> !closedFields.contains(f)).map(f -> {
                                if (this.aliases != null && this.aliases.containsValue(f)) {
                                    for (Map.Entry<String, String> e : this.aliases.entrySet()) {
                                        if (e.getValue().compareToIgnoreCase(f) == 0) {
                                            return e.getKey();
                                        }
                                    }
                                }
                                return f;
                            }).collect(Collectors.joining(",")) + sb.toString());
                    newScanner.useDelimiter(com.zero_x_baadf00d.partialize.Partialize.SCANNER_DELIMITER);
                    scanner.close();
                    scanner = newScanner;
                }
                if (word.contains("(")) {
                    while (scanner.hasNext()
                            && (StringUtils.countMatches(word, "(") != StringUtils.countMatches(word, ")"))) {
                        word += "," + scanner.next();
                    }
                    final Matcher m = this.fieldArgsPattern.matcher(word);
                    if (m.find()) {
                        word = m.group(1);
                        args = m.group(2);
                    }
                }
                final String aliasField = word;
                final String field = this.aliases != null && this.aliases.containsKey(aliasField)
                        ? this.aliases.get(aliasField)
                        : aliasField;
                if (allowedFields.stream().anyMatch(
                        f -> f.toLowerCase(Locale.ENGLISH).compareTo(field.toLowerCase(Locale.ENGLISH)) == 0)) {
                    if (this.accessPolicyFunction != null
                            && !this.accessPolicyFunction.apply(new AccessPolicy(clazz, instance, field))) {
                        continue;
                    }
                    closedFields.add(aliasField);
                    try {
                        final Method method = clazz.getMethod("get" + WordUtils.capitalize(field));
                        final Object object = method.invoke(instance);
                        this.internalBuild(depth, aliasField, field, args, partialObject, clazz, object);
                    } catch (IllegalAccessException | InvocationTargetException
                            | NoSuchMethodException ignore) {
                        try {
                            final Method method = clazz.getMethod(field);
                            final Object object = method.invoke(instance);
                            this.internalBuild(depth, aliasField, field, args, partialObject, clazz, object);
                        } catch (IllegalAccessException | InvocationTargetException
                                | NoSuchMethodException ex) {
                            if (this.exceptionConsumer != null) {
                                this.exceptionConsumer.accept(ex);
                            }
                        }
                    }
                }
            }
            return partialObject;
        } else if (instance instanceof Map<?, ?>) {
            if (fields == null || fields.isEmpty() || fields.compareTo("*") == 0) {
                for (Map.Entry<?, ?> e : ((Map<?, ?>) instance).entrySet()) {
                    this.internalBuild(depth, String.valueOf(e.getKey()), String.valueOf(e.getKey()), null,
                            partialObject, e.getValue() == null ? Object.class : e.getValue().getClass(),
                            e.getValue());
                }
            } else {
                final Map<?, ?> tmpMap = (Map<?, ?>) instance;
                for (final String k : fields.split(",")) {
                    if (k.compareTo("*") != 0) {
                        final Object o = tmpMap.get(k);
                        this.internalBuild(depth, k, k, null, partialObject,
                                o == null ? Object.class : o.getClass(), o);
                    } else {
                        for (Map.Entry<?, ?> e : ((Map<?, ?>) instance).entrySet()) {
                            this.internalBuild(depth, String.valueOf(e.getKey()), String.valueOf(e.getKey()),
                                    null, partialObject,
                                    e.getValue() == null ? Object.class : e.getValue().getClass(),
                                    e.getValue());
                        }
                    }
                }
            }
        } else {
            throw new RuntimeException("Can't convert " + clazz.getCanonicalName());
        }
    }
    return partialObject;
}

From source file:uk.bl.wa.annotation.AnnotationsFromAct.java

/**
 * Read data from ACT to include curator-specified metadata.
 * @param conf// w  w w . j  a  v a  2 s .  c  o  m
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
private String readAct(String url) throws IOException {
    URL act = new URL(url);
    HttpURLConnection connection = (HttpURLConnection) act.openConnection();
    if (this.cookie != null) {
        connection.setRequestProperty("Cookie", this.cookie);
        connection.setRequestProperty("X-CSRF-TOKEN", this.csrf);
    }

    Scanner scanner;
    if (connection.getResponseCode() != 200) {
        scanner = new Scanner(connection.getErrorStream());
        scanner.useDelimiter("\\Z");
        throw new IOException(scanner.next());
    } else {
        scanner = new Scanner(connection.getInputStream());
    }
    scanner.useDelimiter("\\Z");
    return scanner.next();
}

From source file:uk.bl.wa.annotation.AnnotationsFromAct.java

/**
 * Performs login operation to ACT, setting Cookie and CSRF.
 * @throws IOException/*from   w w  w .j a  va2  s  .  c  om*/
 */
private void actLogin() throws IOException {
    Config loginConf = ConfigFactory.parseFile(new File("credentials.conf"));
    URL login = new URL(loginConf.getString("act.login"));
    LOG.info("Logging in at " + login);

    HttpURLConnection connection = (HttpURLConnection) login.openConnection();
    StringBuilder credentials = new StringBuilder();
    credentials.append(loginConf.getString("act.username"));
    credentials.append(":");
    credentials.append(loginConf.getString("act.password"));
    connection.setRequestProperty("Authorization",
            "Basic " + Base64.byteArrayToBase64(credentials.toString().getBytes()));
    connection.setRequestProperty("Content-Type", "text/plain");

    Scanner scanner;
    if (connection.getResponseCode() != 200) {
        scanner = new Scanner(connection.getErrorStream());
        scanner.useDelimiter("\\Z");
        throw new IOException(scanner.next());
    } else {
        scanner = new Scanner(connection.getInputStream());
    }
    scanner.useDelimiter("\\Z");
    this.csrf = scanner.next();
    this.cookie = connection.getHeaderField("set-cookie");
}

From source file:ch.kostceco.tools.siardexcerpt.excerption.moduleexcerpt.impl.ExcerptCGrepModuleImpl.java

@Override
public boolean validate(File siardDatei, File outFile, String excerptString) throws ExcerptCGrepException {
    // Ausgabe -> Ersichtlich das SIARDexcerpt arbeitet
    int onWork = 41;

    boolean isValid = true;

    File fGrepExe = new File("resources" + File.separator + "grep" + File.separator + "grep.exe");
    String pathToGrepExe = fGrepExe.getAbsolutePath();
    if (!fGrepExe.exists()) {
        // grep.exe existiert nicht --> Abbruch
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                + getTextResourceService().getText(ERROR_XML_C_MISSINGFILE, fGrepExe.getAbsolutePath()));
        return false;
    } else {/*w ww  . j a v  a 2s  .  c o  m*/
        File fMsys10dll = new File("resources" + File.separator + "grep" + File.separator + "msys-1.0.dll");
        if (!fMsys10dll.exists()) {
            // msys-1.0.dll existiert nicht --> Abbruch
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                    + getTextResourceService().getText(ERROR_XML_C_MISSINGFILE, fMsys10dll.getAbsolutePath()));
            return false;
        }
    }

    File tempOutFile = new File(outFile.getAbsolutePath() + ".tmp");
    String content = "";

    // Record aus Maintable herausholen
    try {
        if (tempOutFile.exists()) {
            Util.deleteDir(tempOutFile);
        }

        /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim
         * entsprechenden Modul die property anzugeben: <property name="configurationService"
         * ref="configurationService" /> */

        String name = getConfigurationService().getMaintableName();
        String folder = getConfigurationService().getMaintableFolder();
        String cell = getConfigurationService().getMaintablePrimarykeyCell();

        File fMaintable = new File(siardDatei.getAbsolutePath() + File.separator + "content" + File.separator
                + "schema0" + File.separator + folder + File.separator + folder + ".xml");

        try {
            // grep "<c11>7561234567890</c11>" table13.xml >> output.txt
            String command = "cmd /c \"" + pathToGrepExe + " \"<" + cell + ">" + excerptString + "</" + cell
                    + ">\" " + fMaintable.getAbsolutePath() + " >> " + tempOutFile.getAbsolutePath() + "\"";
            /* Das redirect Zeichen verunmglicht eine direkte eingabe. mit dem geschachtellten Befehl
             * gehts: cmd /c\"urspruenlicher Befehl\" */

            // System.out.println( command );

            Process proc = null;
            Runtime rt = null;

            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_OPEN, name));

            try {
                Util.switchOffConsole();
                rt = Runtime.getRuntime();
                proc = rt.exec(command.toString().split(" "));
                // .split(" ") ist notwendig wenn in einem Pfad ein Doppelleerschlag vorhanden ist!

                // Fehleroutput holen
                StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");

                // Output holen
                StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");

                // Threads starten
                errorGobbler.start();
                outputGobbler.start();

                // Warte, bis wget fertig ist
                proc.waitFor();

                Util.switchOnConsole();

            } catch (Exception e) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                        + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
                return false;
            } finally {
                if (proc != null) {
                    closeQuietly(proc.getOutputStream());
                    closeQuietly(proc.getInputStream());
                    closeQuietly(proc.getErrorStream());
                }
            }

            Scanner scanner = new Scanner(tempOutFile);
            content = "";
            try {
                content = scanner.useDelimiter("\\Z").next();
            } catch (Exception e) {
                // Grep ergab kein treffer Content Null
                content = "";
            }
            scanner.close();

            getMessageService()
                    .logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CONTENT, content));
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CLOSE, name));

            if (tempOutFile.exists()) {
                Util.deleteDir(tempOutFile);
            }
            content = "";

            // Ende Grep

        } catch (Exception e) {
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                    + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
            return false;
        }

    } catch (Exception e) {
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
        return false;
    }

    // Ende MainTable

    // grep der SubTables
    try {
        String name = null;
        String folder = null;
        String cell = null;

        InputStream fin = new FileInputStream(
                new File("configuration" + File.separator + "SIARDexcerpt.conf.xml"));
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(fin);
        fin.close();

        /* read the document and for each subTable */
        Namespace ns = Namespace.getNamespace("");

        // select schema elements and loop
        List<Element> subtables = document.getRootElement().getChild("subtables", ns).getChildren("subtable",
                ns);
        for (Element subtable : subtables) {
            name = subtable.getChild("name", ns).getText();
            folder = subtable.getChild("folder", ns).getText();
            cell = subtable.getChild("foreignkeycell", ns).getText();

            // System.out.println( name + " - " + folder + " - " + cell );
            File fSubtable = new File(siardDatei.getAbsolutePath() + File.separator + "content" + File.separator
                    + "schema0" + File.separator + folder + File.separator + folder + ".xml");

            try {
                // grep "<c11>7561234567890</c11>" table13.xml >> output.txt
                String command = "cmd /c \"" + pathToGrepExe + " \"<" + cell + ">" + excerptString + "</" + cell
                        + ">\" " + fSubtable.getAbsolutePath() + " >> " + tempOutFile.getAbsolutePath() + "\"";
                /* Das redirect Zeichen verunmglicht eine direkte eingabe. mit dem geschachtellten Befehl
                 * gehts: cmd /c\"urspruenlicher Befehl\" */

                // System.out.println( command );

                Process proc = null;
                Runtime rt = null;

                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_OPEN, name));

                try {
                    Util.switchOffConsole();
                    rt = Runtime.getRuntime();
                    proc = rt.exec(command.toString().split(" "));
                    // .split(" ") ist notwendig wenn in einem Pfad ein Doppelleerschlag vorhanden ist!

                    // Fehleroutput holen
                    StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");

                    // Output holen
                    StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");

                    // Threads starten
                    errorGobbler.start();
                    outputGobbler.start();

                    // Warte, bis wget fertig ist
                    proc.waitFor();

                    Util.switchOnConsole();

                } catch (Exception e) {
                    getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                            + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
                    return false;
                } finally {
                    if (proc != null) {
                        closeQuietly(proc.getOutputStream());
                        closeQuietly(proc.getInputStream());
                        closeQuietly(proc.getErrorStream());
                    }
                }

                Scanner scanner = new Scanner(tempOutFile);
                content = "";
                try {
                    content = scanner.useDelimiter("\\Z").next();
                } catch (Exception e) {
                    // Grep ergab kein treffer Content Null
                    content = "";
                }
                scanner.close();

                getMessageService()
                        .logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CONTENT, content));
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CLOSE, name));

                if (tempOutFile.exists()) {
                    Util.deleteDir(tempOutFile);
                }
                content = "";

                // Ende Grep

            } catch (Exception e) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                        + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
                return false;
            }

            // Ende SubTables
            if (onWork == 41) {
                onWork = 2;
                System.out.print("-   ");
                System.out.print("\r");
            } else if (onWork == 11) {
                onWork = 12;
                System.out.print("\\   ");
                System.out.print("\r");
            } else if (onWork == 21) {
                onWork = 22;
                System.out.print("|   ");
                System.out.print("\r");
            } else if (onWork == 31) {
                onWork = 32;
                System.out.print("/   ");
                System.out.print("\r");
            } else {
                onWork = onWork + 1;
            }
        }
        System.out.print("   ");
        System.out.print("\r");
    } catch (Exception e) {
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
        return false;
    }

    return isValid;
}

From source file:argendata.web.controller.DatasetController.java

@RequestMapping(method = RequestMethod.GET)
public ModelAndView view(@RequestParam String qName, HttpSession session) {
    ModelAndView mav = new ModelAndView();
    mav.addObject("mainURL", properties.getMainURL());

    Dataset retrievedDataset = this.datasetService.getApprovedDatasetByQName(qName);

    if (retrievedDataset == null) {
        logger.info("El dataset no existe");
        mav.setViewName("redirect:/bin/dataset/error");
        return mav;
    }// w  ww. j a  va  2s .c  o  m

    String format = null;
    if (retrievedDataset.getDistribution() != null && retrievedDataset.getDistribution().getFormat() != null) {
        format = retrievedDataset.getDistribution().getFormat().toLowerCase();
    }

    DatasetViewDTO dview;
    /*
     * Microsoft Office: doc, docx, xls, xlsx, ppt, pptx, pps; OpenDocument:
     * odt, ods, odp; OpenOffice:sxw, sxc, sxi; Other Formats: wpd, pdf,
     * rtf, txt, html, csv, tsv
     */
    if (format != null && (format.endsWith("doc") || format.endsWith("docx") || format.endsWith("xls")
            || format.endsWith("xlsx") || format.endsWith("ppt") || format.endsWith("pptx")
            || format.endsWith("pps") || format.endsWith("odt") || format.endsWith("ods")
            || format.endsWith("odp") || format.endsWith("swx") || format.endsWith("sxi")
            || format.endsWith("wpd") || format.endsWith("pdf") || format.endsWith("rtf")
            || format.endsWith("txt") || format.endsWith("csv") || format.endsWith("tsv"))) {
        dview = new DatasetViewDTO(retrievedDataset, true);
    } else {
        dview = new DatasetViewDTO(retrievedDataset, false);
    }

    mav.addObject("dto", dview);
    String theDate = "";
    /* Se pasa la fecha a un formato entendible por el usuario final */
    String correctDate = dview.getDataset().getModified();
    Scanner scanner = new Scanner(correctDate);
    scanner.useDelimiter("T");
    if (scanner.hasNext()) {
        theDate = scanner.next();
        Scanner scannerDate = new Scanner(theDate);
        scannerDate.useDelimiter("-");
        String year = scannerDate.next();
        String month = scannerDate.next();
        String day = scannerDate.next();
        theDate = year + "-" + month + "-" + day;
    } else {
        logger.error("No se pudo obtener la fecha de la ltima modificacin.");
    }
    mav.addObject("datasetDate", theDate);

    ArgendataUser user = (ArgendataUser) session.getAttribute("user");
    if (user != null && user.isAdmin()) {
        mav.addObject("admin", true);
    } else {
        mav.addObject("admin", false);
    }

    if (user != null) {
        mav.addObject("logged", true);
    } else {
        mav.addObject("logged", false);
    }

    return mav;
}

From source file:org.xwiki.commons.internal.DefaultMailSender.java

@Override
public int sendMailFromTemplate(String templateDocFullName, String from, String to, String cc, String bcc,
        String language, VelocityContext vContext) {
    if (!documentAccessBridge.hasProgrammingRights()) // Forbids the use of a template created by a user having no
                                                      // programming rights
    {/*w ww . j a  v a  2 s.com*/
        logger.error(
                "No mail has been sent : The author of the document needs programming rights to be able to use the sendMailFromTemplate method");
        return 0;
    }
    try {
        ExecutionContext context = this.execution.getContext();
        XWikiContext xwikiContext = (XWikiContext) context.getProperty("xwikicontext");
        if (vContext == null)
            vContext = velocityManager.getVelocityContext();
        vContext.put("from.name", from);
        vContext.put("from.address", from);
        vContext.put("to.name", to);
        vContext.put("to.address", to);
        vContext.put("to.cc", cc);
        vContext.put("to.bcc", bcc);
        vContext.put("bounce", from);

        String wiki = documentAccessBridge.getCurrentDocumentReference().getWikiReference().getName();
        String templateSpace = "";
        String templatePage = "";
        Scanner scan = new Scanner(templateDocFullName);
        scan.useDelimiter("\\.");
        if (scan.hasNext())
            templateSpace = scan.next();
        if (scan.hasNext())
            templatePage = scan.next();
        else {
            logger.error("Template reference is invalid");
            return 0;
        }
        DocumentReference template = new DocumentReference(wiki, templateSpace, templatePage);
        boolean hasRight = checkAccess(template, xwikiContext);
        if (!hasRight) // If the current user is not allowed to view the page of the template, he can't use it to
                       // send mails
        {
            logger.error("You haven't the right to use this mail template !");
            return 0;
        }
        DocumentReference mailClass = new DocumentReference(wiki, "XWiki", "Mail");
        int n = -1;

        n = documentAccessBridge.getObjectNumber(template, mailClass, "language", language);

        if (n == -1) {
            n = documentAccessBridge.getObjectNumber(template, mailClass, "language", "en");
            logger.warn("No mail object found with language = " + language);
        }
        if (n == -1) {
            logger.error("No mail object found in the document " + templateDocFullName);
            return 0;
        }

        String subject = documentAccessBridge.getProperty(template, mailClass, n, "subject").toString();
        subject = XWikiVelocityRenderer.evaluate(subject, templateDocFullName, vContext, xwikiContext);
        String text = documentAccessBridge.getProperty(template, mailClass, n, "text").toString();
        text = XWikiVelocityRenderer.evaluate(text, templateDocFullName, vContext, xwikiContext);
        String html = documentAccessBridge.getProperty(template, mailClass, n, "html").toString();
        html = XWikiVelocityRenderer.evaluate(html, templateDocFullName, vContext, xwikiContext);

        Mail mail = new Mail();
        mail.setFrom(from);
        mail.setTo(to);
        mail.setCc(cc);
        mail.setBcc(bcc);
        mail.setSubject(subject);
        mail.addContent("text/plain", text);
        if (!StringUtils.isEmpty(html))
            mail.addContent("text/html", html);
        return this.send(mail);
    } catch (Exception e) {
        return 0;
    }

}

From source file:com.java2s.intents4.IntentsDemo4Activity.java

private IntentFilter createFilterFromEditTextFields() {
    IntentFilter filter = new IntentFilter();

    if (filterActionsLayout != null) {
        int count = filterActionsLayout.getChildCount();
        for (int i = 0; i < count; i++) {
            String action = ((EditText) ((ViewGroup) filterActionsLayout.getChildAt(i)).getChildAt(1)).getText()
                    .toString().trim();/*  w ww.  ja va 2  s  .  c  o  m*/
            if (action.length() != 0) {
                filter.addAction(action);
            }
        }
    }

    if (filterSchemeLayout != null) {
        int count = filterSchemeLayout.getChildCount();
        for (int i = 0; i < count; i++) {
            String scheme = ((EditText) ((ViewGroup) filterSchemeLayout.getChildAt(i)).getChildAt(1)).getText()
                    .toString().trim();
            if (scheme.length() != 0) {
                filter.addDataScheme(scheme);
            }
        }
    }

    if (filterAuthLayout != null) {
        int count = filterAuthLayout.getChildCount();
        for (int i = 0; i < count; i++) {
            String auth = ((EditText) ((ViewGroup) filterAuthLayout.getChildAt(i)).getChildAt(1)).getText()
                    .toString().trim();
            if (auth.length() != 0) {
                Scanner scanner = new Scanner(auth);
                scanner.useDelimiter(":");
                String host = null;
                String port = null;
                if (scanner.hasNext()) {
                    host = scanner.next();
                }
                if (scanner.hasNext()) {
                    port = scanner.next();
                }
                filter.addDataAuthority(host, port);
            }
        }
    }

    if (filterPathLayout != null) {
        int count = filterPathLayout.getChildCount();
        for (int i = 0; i < count; i++) {

            ViewGroup group = (ViewGroup) filterPathLayout.getChildAt(i);
            String path = ((EditText) group.getChildAt(1)).getText().toString().trim();
            String pattern = ((TextView) ((ViewGroup) group.getChildAt(2)).getChildAt(0)).getText().toString()
                    .trim(); // ((TextView)

            int patternInt = 0;
            if (pattern.equals(pathPatterns[0])) {
                patternInt = PatternMatcher.PATTERN_LITERAL;
            }
            if (pattern.equals(pathPatterns[1])) {
                patternInt = PatternMatcher.PATTERN_PREFIX;
            }
            if (pattern.equals(pathPatterns[2])) {
                patternInt = PatternMatcher.PATTERN_SIMPLE_GLOB;
            }
            if (path.length() != 0) {
                filter.addDataPath(path, patternInt);
            }
        }
    }

    if (filterTypeLayout != null) {
        int count = filterTypeLayout.getChildCount();
        for (int i = 0; i < count; i++) {
            String aType = ((EditText) ((ViewGroup) filterTypeLayout.getChildAt(i)).getChildAt(1)).getText()
                    .toString().trim();
            if (aType.length() != 0) {
                try {
                    filter.addDataType(aType);
                } catch (MalformedMimeTypeException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    if (filterCategoriesLayout != null) {
        int count = filterCategoriesLayout.getChildCount();
        for (int i = 0; i < count; i++) {
            String cat = ((EditText) ((ViewGroup) filterCategoriesLayout.getChildAt(i)).getChildAt(1)).getText()
                    .toString().trim();
            if (cat.length() != 0) {
                filter.addCategory(cat);
            }
        }
    }
    return filter;
}

From source file:files.populate.java

void populate_business(Connection connection, String filename) {
    String fileName = "/Users/yash/Documents/workspace/HW 3/data/yelp_business.json";
    Path path = Paths.get(fileName);
    Scanner scanner = null;
    try {/*from  www . j  a  v  a  2 s  . c o  m*/
        scanner = new Scanner(path);

    } catch (IOException e) {
        e.printStackTrace();
    }

    //read file line by line
    scanner.useDelimiter("\n");
    int i = 0;
    while (scanner.hasNext()) {
        if (i < 500) {
            JSONParser parser = new JSONParser();
            String s = (String) scanner.next();
            s = s.replace("'", "''");

            JSONObject obj;

            try {
                obj = (JSONObject) parser.parse(s);
                String add = (String) obj.get("full_address");
                add = add.replace("\n", "");
                //insertion into business table
                String query = "insert into yelp_business values ('" + obj.get("business_id") + "','" + add
                        + "','" + obj.get("open") + "','" + obj.get("city") + "','" + obj.get("state") + "','"
                        + obj.get("latitude") + "','" + obj.get("longitude") + "','" + obj.get("review_count")
                        + "','" + obj.get("name") + "','" + obj.get("stars") + "','" + obj.get("type") + "')";
                Statement statement = connection.createStatement();

                System.out.println(query);
                statement.executeUpdate(query);
                //end

                //inserting into hours table
                Map hours = (Map) obj.get("hours");
                Set keys = hours.keySet();
                Object[] days = keys.toArray();
                for (int j = 0; j < days.length; ++j) {
                    //                        
                    String thiskey = days[j].toString();
                    Map timings = (Map) hours.get(thiskey);
                    //                       
                    String q3 = "insert into business_hours values ('" + obj.get("business_id") + "','"
                            + thiskey + "','" + timings.get("close") + "','" + timings.get("open") + "')";
                    //                        
                    statement.executeUpdate(q3);

                }
                //end

                //insertion into cat table
                //                      System.out.println(s);
                String[] mainCategories = { "Active Life", "Arts & Entertainment", "Automotive", "Car Rental",
                        "Cafes", "Beauty & Spas", "Convenience Stores", "Dentists", "Doctors", "Drugstores",
                        "Department Stores", "Education", "Event Planning & Services", "Flowers & Gifts",
                        "Food", "Health & Medical", "Home Services", "Home & Garden", "Hospitals",
                        "Hotels & Travel", "Hardware Stores", "Grocery", "Medical Centers",
                        "Nurseries & Gardening", "Nightlife", "Restaurants", "Shopping", "Transportation" };

                List<String> mainCategories1 = Arrays.asList(mainCategories);
                ArrayList<String> categories = (ArrayList<String>) obj.get("categories");
                for (int j = 0; j < categories.size(); ++j) {
                    String q;
                    if (mainCategories1.contains(categories.get(j))) {
                        q = "insert into business_cat values ('" + obj.get("business_id") + "','"
                                + categories.get(j) + "','main')";
                    } else {
                        q = "insert into business_cat values ('" + obj.get("business_id") + "','"
                                + categories.get(j) + "','sub')";
                    }
                    //                         System.out.println(q);
                    statement.executeUpdate(q);
                }
                //end

                //insertion into neighborhood table
                ArrayList<String> hood = (ArrayList<String>) obj.get("neighborhoods");
                for (int j = 0; j < hood.size(); ++j) {
                    String q = "insert into business_hood values ('" + obj.get("business_id") + "','"
                            + hood.get(j) + "')";
                    //                         System.out.println(q);
                    statement.executeUpdate(q);
                }
                //end

                //insertion into attributes and ambience table

                Map<String, ?> att = (Map<String, ?>) obj.get("attributes");
                System.out.println(att + "\n\n");
                Set keys1 = att.keySet();
                Object[] attname = keys1.toArray();
                for (int j = 0; j < attname.length; ++j) {

                    //                            
                    String thiskey = attname[j].toString();
                    String att_query = new String();
                    if (att.get(thiskey) instanceof JSONObject) {

                        Map<String, ?> subatt = (Map<String, ?>) att.get(thiskey);

                        Set keys2 = subatt.keySet();

                        Object[] attname2 = keys2.toArray();
                        for (int k = 0; k < attname2.length; ++k) {
                            String thiskey2 = attname2[k].toString();
                            String subcat_value = (String) String.valueOf(subatt.get(thiskey2));
                            att_query = "insert into business_attributes values ('" + obj.get("business_id")
                                    + "','" + thiskey + "','" + thiskey2 + "','" + subcat_value + "')";
                            //                                     System.out.println("subkey="+thiskey2 + "value = "+subcat_value);
                            //                                              System.out.println(att_query);
                            statement.executeUpdate(att_query);
                        }

                    }

                    else {
                        String attvalues = (String) String.valueOf(att.get(thiskey));
                        att_query = "insert into business_attributes values ('" + obj.get("business_id")
                                + "','n/a','" + thiskey + "','" + attvalues + "')";
                        //                               System.out.println("key="+thiskey + "value = "+attvalues);
                        statement.executeUpdate(att_query);
                    }

                    //                           String q3 = "insert into business_hours values ('"+obj.get("business_id")+"','"+thiskey+"','"+timings.get("close")+"','"+timings.get("open")+"')";
                    //                           System.out.println(q3);
                    //                            statement.executeUpdate(q3);

                }
                statement.close();
                //                   
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            i++;

        } else {
            break;
        }
    }
}

From source file:Balo.MainFram.java

public void getDataFileToJTable() {
    String fileNameDefined = "src/Balo/Data_3.csv";
    File file = new File(fileNameDefined);
    int i = 0;/*from  w  ww  .jav  a  2  s.  co  m*/

    dvDynamic[0] = new Dovat();
    //Get value from csv file
    try {
        Scanner inputStream = new Scanner(file);
        inputStream.useDelimiter(",");
        while (inputStream.hasNext()) {
            dvDynamic[i + 1] = dvGreedy[i] = new Dovat();
            dvDynamic[i + 1].ten = dvGreedy[i].ten = inputStream.next().trim();
            dvDynamic[i + 1].soluong = dvGreedy[i].soluong = Integer.valueOf(inputStream.next().trim());
            dvDynamic[i + 1].giatri = dvGreedy[i].giatri = Integer.valueOf(inputStream.next().trim());
            dvDynamic[i + 1].trongluong = dvGreedy[i].trongluong = Integer.valueOf(inputStream.next().trim());
            i++;
        }
        //Set number of Items
        numOfItem = i;
        //Get weight bag
        weightBag = Integer.parseInt(TextW.getText());
        inputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    //Set value for JTable
    for (int item = 0; item < numOfItem; item++) {
        Object[] row = new Object[4];
        row[0] = dvGreedy[item].ten;
        row[1] = dvGreedy[item].soluong;
        row[2] = dvGreedy[item].giatri;
        row[3] = dvGreedy[item].trongluong;
        model.addRow(row);
    }
}

From source file:org.opencastproject.composer.gstreamer.AbstractGSEncoderEngine.java

/**
 * Parses image extraction configuration in the following format: #{image_time_1}:#{image_width}x#{image_height}.
 * Multiple extraction configurations can be separated by comma.
 * //from w  w w. j  av  a2s .  com
 * @param configuration
 *          Configuration for image extraction
 * @param outputTemplate
 *          output path template. Should be in the form /some_file_name_#{time}.jpg so that each image will have it's
 *          unique path.
 * @return parsed List for image extraction
 */
protected List<ImageExtractionProperties> parseImageExtractionConfiguration(String configuration,
        String outputTemplate) {

    LinkedList<ImageExtractionProperties> propertiesList = new LinkedList<AbstractGSEncoderEngine.ImageExtractionProperties>();
    Scanner scanner = new Scanner(configuration);
    scanner.useDelimiter(",");
    int counter = 0;

    while (scanner.hasNext()) {
        String nextToken = scanner.next().trim();
        if (!nextToken.matches("[0-9]+:[0-9]+[x|X][0-9]+")) {
            throw new IllegalArgumentException("Invalid token found: " + nextToken);
        }

        String[] properties = nextToken.split("[:|x|X]");
        String output = outputTemplate.replaceAll("#\\{time\\}", properties[0]);
        if (output.equals(outputTemplate)) {
            logger.warn("Output filename does not contain #{time} template: multiple images will overwrite");
        }

        if (new File(output).exists()) {
            String outputFile = FilenameUtils.removeExtension(output);
            String extension = FilenameUtils.getExtension(output);
            output = outputFile + "_reencode." + extension;
        }

        ImageExtractionProperties imageProperties = new ImageExtractionProperties(counter++,
                Long.parseLong(properties[0]), Integer.parseInt(properties[1]), Integer.parseInt(properties[2]),
                output);

        propertiesList.add(imageProperties);
    }

    Collections.sort(propertiesList, new Comparator<ImageExtractionProperties>() {
        @Override
        public int compare(ImageExtractionProperties o1, ImageExtractionProperties o2) {
            return (int) (o2.timeInSeconds - o1.timeInSeconds);
        }
    });

    return propertiesList;
}