Example usage for java.util Scanner next

List of usage examples for java.util Scanner next

Introduction

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

Prototype

public String next() 

Source Link

Document

Finds and returns the next complete token from this scanner.

Usage

From source file:it.acubelab.batframework.systemPlugins.TagmeAnnotator.java

@Override
public HashSet<ScoredAnnotation> solveSa2W(String text) throws AnnotationException {
    // System.out.println(text.length()+ " "+text.substring(0,
    // Math.min(text.length(), 15)));
    // TODO: workaround for a bug in tagme. should be deleted afterwards.
    String newText = "";
    for (int i = 0; i < text.length(); i++)
        newText += (text.charAt(i) > 127 ? ' ' : text.charAt(i));
    text = newText;/*from  w w w .j a  v  a2  s.c  o  m*/

    // avoid crashes for empty documents
    int j = 0;
    while (j < text.length() && text.charAt(j) == ' ')
        j++;
    if (j == text.length())
        return new HashSet<ScoredAnnotation>();

    HashSet<ScoredAnnotation> res;
    String params = null;
    try {
        res = new HashSet<ScoredAnnotation>();

        params = "key=" + this.key;
        params += "&lang=en";
        if (epsilon >= 0)
            params += "&epsilon=" + epsilon;
        if (minComm >= 0)
            params += "&min_comm=" + minComm;
        if (minLink >= 0)
            params += "&min_link=" + minLink;
        params += "&text=" + URLEncoder.encode(text, "UTF-8");
        URL wikiApi = new URL(url);

        HttpURLConnection slConnection = (HttpURLConnection) wikiApi.openConnection();
        slConnection.setRequestProperty("accept", "text/xml");
        slConnection.setDoOutput(true);
        slConnection.setDoInput(true);
        slConnection.setRequestMethod("POST");
        slConnection.setRequestProperty("charset", "utf-8");
        slConnection.setRequestProperty("Content-Length", Integer.toString(params.getBytes().length));
        slConnection.setUseCaches(false);
        slConnection.setReadTimeout(0);

        DataOutputStream wr = new DataOutputStream(slConnection.getOutputStream());
        wr.writeBytes(params);
        wr.flush();
        wr.close();

        Scanner s = new Scanner(slConnection.getInputStream());
        Scanner s2 = s.useDelimiter("\\A");
        String resultStr = s2.hasNext() ? s2.next() : "";
        s.close();

        JSONObject obj = (JSONObject) JSONValue.parse(resultStr);
        lastTime = (Long) obj.get("time");

        JSONArray jsAnnotations = (JSONArray) obj.get("annotations");
        for (Object js_ann_obj : jsAnnotations) {
            JSONObject js_ann = (JSONObject) js_ann_obj;
            System.out.println(js_ann);
            int start = ((Long) js_ann.get("start")).intValue();
            int end = ((Long) js_ann.get("end")).intValue();
            int id = ((Long) js_ann.get("id")).intValue();
            float rho = Float.parseFloat((String) js_ann.get("rho"));
            System.out.println(text.substring(start, end) + "->" + id + " (" + rho + ")");
            res.add(new ScoredAnnotation(start, end - start, id, (float) rho));
        }

    } catch (Exception e) {
        e.printStackTrace();
        throw new AnnotationException("An error occurred while querying TagMe API. Message: " + e.getMessage()
                + " Parameters:" + params);
    }
    return res;

}

From source file:org.catnut.service.UpgradeService.java

private void checkout() throws Exception {
    URL url = new URL(METADATA_URL);
    InputStream inputStream = url.openStream();
    Scanner in = new Scanner(inputStream).useDelimiter("\\A");
    if (in.hasNext()) {
        JSONObject metadata = new JSONObject(in.next());
        PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
        if (info.versionCode < metadata.optInt(FIELD_VERSION_CODE)) {
            Notification.InboxStyle style = new Notification.InboxStyle(mBuilder);
            String size = metadata.optString("size");
            style.setBigContentTitle(getString(R.string.find_new_version, size));
            JSONArray messages = metadata.optJSONArray("messages");
            for (int i = 0; i < messages.length(); i++) {
                style.addLine(messages.optString(i));
            }//  w ww  . j  a  v  a 2 s . c  o  m
            // download&upgrade intent
            Intent download = new Intent(this, UpgradeService.class);
            download.setAction(ACTION_DOWNLOAD);
            download.putExtra(DOWNLOAD_LINK, metadata.optString(DOWNLOAD_LINK));
            PendingIntent piDownload = PendingIntent.getService(this, 0, download, 0);
            mBuilder.addAction(R.drawable.ic_stat_download_dark, getString(R.string.down_load_and_upgrade),
                    piDownload);
            // dismiss notification
            Intent dismiss = new Intent(this, UpgradeService.class);
            dismiss.setAction(ACTION_DISMISS);
            PendingIntent piDismiss = PendingIntent.getService(this, 0, dismiss, 0);
            mBuilder.addAction(R.drawable.ic_stat_content_remove_dark, getString(R.string.not_upgrade_now),
                    piDismiss);
            // show it.
            mBuilder.setTicker(getString(R.string.find_new_version));
            mNotificationManager.notify(ID, mBuilder.setDefaults(Notification.DEFAULT_ALL).build());
        } else {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(UpgradeService.this, getString(R.string.already_updated), Toast.LENGTH_SHORT)
                            .show();
                }
            });
        }
    }
    in.close();
}

From source file:me.emmy.db.MySQLLayer.java

private DataLayerVersion detectVersion() {
    try {/*w w  w  .j a v a2  s . c o m*/
        Scanner scanner = new Scanner(new File(plugin.getDataFolder(), "mysql.dl.version"));
        return DataLayerVersion.valueOf(scanner.next());
    } catch (FileNotFoundException e) {
        return DataLayerVersion.v0;
    }
}

From source file:org.apache.uima.ruta.resource.CSVTable.java

private void buildTable(InputStream stream) {
    Scanner sc = new Scanner(stream, Charset.forName("UTF-8").name());
    sc.useDelimiter("\\n");
    tableData = new ArrayList<List<String>>();
    while (sc.hasNext()) {
        String line = sc.next().trim();
        line = line.replaceAll(";;", "; ;");
        String[] lineElements = line.split(";");
        List<String> row = Arrays.asList(lineElements);
        tableData.add(row);/*from  w w w.  j  av  a  2s  . c o  m*/
    }
    sc.close();
}

From source file:com.afis.jx.ckfinder.connector.utils.FileUtils.java

/**
 * check if dirname matches configuration hidden folder regex.
 *
 * @param dirName dir name/*from  ww w.j  a va2s.co  m*/
 * @param conf connector configuration
 * @return true if matches.
 */
public static boolean checkIfDirIsHidden(final String dirName, final IConfiguration conf) {
    if (dirName == null || dirName.equals("")) {
        return false;
    }
    String dir = PathUtils.removeSlashFromEnd(PathUtils.escape(dirName));
    Scanner sc = new Scanner(dir).useDelimiter("/");
    while (sc.hasNext()) {
        boolean check = Pattern.compile(getHiddenFileOrFolderRegex(conf.getHiddenFolders())).matcher(sc.next())
                .matches();
        if (check) {
            return true;
        }
    }
    return false;
}

From source file:org.apache.nutch.indexer.html.HtmlIndexingFilter.java

private NutchDocument addRawContent(NutchDocument doc, WebPage page, String url) {
    ByteBuffer raw = page.getContent();
    if (raw != null) {
        if (LOG.isInfoEnabled()) {
            LOG.info("Html indexing for: " + url.toString());
        }/*from ww w. j a va  2 s  . c  o m*/
        ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(raw.array(),
                raw.arrayOffset() + raw.position(), raw.remaining());
        Scanner scanner = new Scanner(arrayInputStream);
        scanner.useDelimiter("\\Z");//To read all scanner content in one String
        String data = "";
        if (scanner.hasNext()) {
            data = scanner.next();
        }
        doc.add("rawcontent", StringUtil.cleanField(data));
    }
    return doc;
}

From source file:eu.cassandra.server.api.UploadFileService.java

@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(@FormDataParam("file") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("prj_id") String prj_id) {

    String filename = fileDetail.getFileName();
    String uploadedFileLocation = context.getRealPath("/resources") + "/" + filename;

    System.out.println(uploadedFileLocation);

    try {/*from  w  w  w.  ja  v a  2s.  co m*/
        // Save it
        writeToFile(uploadedInputStream, uploadedFileLocation);
        // TODO: Create a Run and return the id in the response
        ObjectId objid = ObjectId.get();
        DBObject run = new BasicDBObject();
        String dbname = objid.toString();
        Mongo m = new Mongo("localhost");
        DB db = m.getDB(dbname);
        MongoResults mr = new MongoResults(dbname);
        mr.createIndexes();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmm");
        String runName = "Run for " + filename + " on " + sdf.format(calendar.getTime());
        run.put("_id", objid);
        run.put("name", runName);
        run.put("started", System.currentTimeMillis());
        run.put("ended", System.currentTimeMillis());
        run.put("type", "file");
        run.put("prj_id", prj_id);
        run.put("percentage", 100);
        DBConn.getConn().getCollection(MongoRuns.COL_RUNS).insert(run);

        // Find the project
        DBObject query = new BasicDBObject();
        query.put("_id", new ObjectId(prj_id));
        DBObject project = DBConn.getConn().getCollection(MongoProjects.COL_PROJECTS).findOne(query);
        db.getCollection(MongoProjects.COL_PROJECTS).insert(project);
        // Make a scenario
        DBObject scenario = new BasicDBObject();
        scenario.put("name", filename);
        scenario.put("project_id", prj_id);
        db.getCollection(MongoScenarios.COL_SCENARIOS).insert(scenario);
        // Get the scenario id
        query = new BasicDBObject();
        query.put("project_id", prj_id);
        DBObject insertedScenario = db.getCollection(MongoScenarios.COL_SCENARIOS).findOne(query);
        ObjectId scnIdObj = (ObjectId) insertedScenario.get("_id");
        String scnId = scnIdObj.toString();
        // TODO: Parse and calculate KPIs
        File f = new File(uploadedFileLocation);
        Scanner sc = new Scanner(f);
        String header = sc.next();
        String[] headerTokens = header.split(",");
        int numOfInstallations = headerTokens.length - 1;
        double maxPower = 0;
        double[] maxPowerInst = new double[numOfInstallations];
        double avgPower = 0;
        double[] avgPowerInst = new double[numOfInstallations];
        double energy = 0;
        double[] energyInst = new double[numOfInstallations];
        int tick = 0;
        while (sc.hasNext()) {
            tick++;
            String line = sc.next();
            String[] tokens = line.split(",");
            double powerSum = 0;
            for (int i = 1; i < tokens.length; i++) {
                double power = Double.parseDouble(tokens[i]);
                energyInst[i - 1] += (power / 1000.0) * Constants.MINUTE_HOUR_RATIO;
                avgPowerInst[i - 1] += power;
                if (maxPowerInst[i - 1] < power) {
                    maxPowerInst[i - 1] = power;
                }
                powerSum += power;
                mr.addTickResultForInstallation(tick, headerTokens[i], power, 0, MongoResults.COL_INSTRESULTS);
            }
            mr.addAggregatedTickResult(tick, powerSum, 0, MongoResults.COL_AGGRRESULTS);
            energy += (powerSum / 1000.0) * Constants.MINUTE_HOUR_RATIO;
            avgPower += powerSum;
            if (maxPower < powerSum) {
                maxPower = powerSum;
            }
        }

        // TODO: Add ticks and KPIs in the db
        for (int i = 0; i < numOfInstallations; i++) {
            mr.addKPIs(headerTokens[i + 1], maxPowerInst[i], avgPowerInst[i] / tick, energyInst[i], 0, 0);
        }
        mr.addKPIs(MongoResults.AGGR, maxPower, avgPower / tick, energy, 0, 0);

        String output = "File uploaded to : " + uploadedFileLocation;
        // Make sim params
        DBObject sim_params = new BasicDBObject();
        sim_params.put("name", filename);
        sim_params.put("scn_id", scnId);
        sim_params.put("numberOfDays", (tick / 1440));
        sim_params.put("mcruns", 1);
        db.getCollection(MongoSimParam.COL_SIMPARAM).insert(sim_params);
        return Response.status(200).entity(output).build();
    } catch (Exception exp) {
        JSONtoReturn jsonMsg = new JSONtoReturn();
        String json = PrettyJSONPrinter.prettyPrint(jsonMsg.createJSONError("Error", exp));
        Response r = Response.status(Response.Status.BAD_REQUEST).entity(json).build();
        return r;
    }

}

From source file:no.dusken.momus.service.drive.GoogleDriveService.java

/**
 * Fetches the new content from Google Drive as HTML, and sends
 * it to the googleDocsTextConverter//  w  w w. j  a  v  a  2 s  . co  m
 */
private void updateContentFromDrive(Article article) {
    String downloadUrl = "https://docs.google.com/feeds/download/documents/export/Export?id="
            + article.getGoogleDriveId() + "&exportFormat=html";

    try {
        // Read data, small hack to convert the stream to a string
        InputStream inputStream = drive.getRequestFactory().buildGetRequest(new GenericUrl(downloadUrl))
                .execute().getContent();
        Scanner s = new java.util.Scanner(inputStream).useDelimiter("\\A");
        String content = s.hasNext() ? s.next() : "";
        logger.debug("Got new content:\n{}", content);

        String convertedContent = googleDocsTextConverter.convert(content);
        article.setContent(convertedContent);
    } catch (IOException e) {
        logger.error("Couldn't get content for article", e);
        // Let the content remain as it was
    }
}

From source file:br.com.poc.navigation.NavigationLoader.java

private void startNavigation() {

    Scanner scanner = new Scanner(System.in);

    this.printLogo();

    boolean continueExecution = true;

    do {//from  w  w w . j  ava 2 s. c o  m

        this.printMenu();

        final String option = scanner.next();

        switch (option) {

        case "1":

            try {

                this.printCommandList();

                String commands = scanner.next();

                System.out.println("\n > Aguarde o processamento....");

                System.out.println("\n > Comandos inputados: " + commands);

                final String distinateCoordinate = navigationComponent.traceRoute(commands).toString();

                System.out.println("\n > A rota final ser: " + distinateCoordinate);

            } catch (ParseInputCommandException | InvalidCommandException exception) {

                System.out.println("\n > Ocorreram alguns erros ao processar a sequncia de comandos:\n");

                final List<String> messages = ExceptionMessageCollector.getStackMessages(exception);

                messages.stream().forEach((message) -> {
                    System.out.println(message);
                });

            }

            break;

        case "2":

            System.out.println("\n > Obrigado por navegar conosco! \n");

            scanner.close();

            continueExecution = false;

            break;

        default:

            System.out.println("\n > Opo de menu invlida.");

            break;

        }

    } while (continueExecution);

}

From source file:coral.reef.web.ReefController.java

@RequestMapping("/admin/edit")
public String edit(@RequestParam(value = "name") String name,
        @RequestParam(value = "properties", required = false) String properties,
        @RequestParam(value = "basepath", required = false) String basepath, Map<String, Object> model) {

    CoralBean cb = coralBeanRepository.findOne(name);

    if (cb == null) {
        cb = new CoralBean();
        String content;//from   w w  w .  j  a va2 s  . co  m
        try {
            Scanner scan = new Scanner(new ClassPathResource("reef.default.properties").getInputStream());
            scan.useDelimiter("\\Z");
            content = scan.next();
            cb.setProperties(content);
        } catch (IOException e) {
            content = e.getMessage();
        }
        cb.setName(name);
    }

    if (properties != null) {
        cb.setProperties(properties);
    }

    if (basepath != null) {
        String prop = cb.getProperties();
        prop = prop.replaceFirst("[#]?(\\s*?)exp.basepath = (.*?)\n", "# exp.basepath = " + basepath + "\n");
        cb.setProperties(prop);
    }

    coralBeanRepository.save(cb);

    model.put("coral", cb);

    return "edit";
}