Example usage for java.util Scanner hasNextLine

List of usage examples for java.util Scanner hasNextLine

Introduction

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

Prototype

public boolean hasNextLine() 

Source Link

Document

Returns true if there is another line in the input of this scanner.

Usage

From source file:edu.emory.cci.aiw.cvrg.eureka.servlet.ProxyServlet.java

@Override
protected void doPut(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    LOGGER.debug("ProxyServlet - PUT");

    StringBuilder stringBuilder = new StringBuilder(1000);
    Scanner scanner = new Scanner(servletRequest.getInputStream());
    while (scanner.hasNextLine()) {
        stringBuilder.append(scanner.nextLine());
    }/*  w  ww.java 2 s  .co m*/
    LOGGER.debug("json: {}", stringBuilder.toString());
    StringBuilder uri = new StringBuilder(500);
    uri.append(getTargetUri());
    // Handle the path given to the servlet
    if (servletRequest.getPathInfo() != null) {//ex: /my/path.html
        uri.append(servletRequest.getPathInfo());
    }
    LOGGER.debug("uri: {}", uri.toString());
    try {
        servicesClient.proxyPut(uri.toString(), stringBuilder.toString());
    } catch (ClientException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.accumulo.shell.mock.MockShell.java

@Override
public int start() throws IOException {
    String input;/*from  w w w . j a  v  a2s  .co  m*/
    if (isVerbose())
        printInfo();

    if (execFile != null) {
        java.util.Scanner scanner = new java.util.Scanner(execFile, UTF_8.name());
        try {
            while (scanner.hasNextLine() && !hasExited()) {
                execCommand(scanner.nextLine(), true, isVerbose());
            }
        } finally {
            scanner.close();
        }
    } else if (execCommand != null) {
        for (String command : execCommand.split("\n")) {
            execCommand(command, true, isVerbose());
        }
        return exitCode;
    }

    while (true) {
        if (hasExited())
            return exitCode;

        reader.setPrompt(getDefaultPrompt());
        input = reader.readLine();
        if (input == null) {
            reader.println();
            return exitCode;
        } // user canceled

        execCommand(input, false, false);
    }
}

From source file:edu.emory.cci.aiw.cvrg.eureka.servlet.ProxyServlet.java

@Override
protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    LOGGER.debug("ProxyServlet - POST");

    StringBuilder stringBuilder = new StringBuilder(1000);
    Scanner scanner = new Scanner(servletRequest.getInputStream());
    while (scanner.hasNextLine()) {
        stringBuilder.append(scanner.nextLine());
    }/*  ww w  . j  a v  a  2s. com*/
    LOGGER.debug("json: {}", stringBuilder.toString());
    StringBuilder uri = new StringBuilder(500);
    uri.append(getTargetUri());
    // Handle the path given to the servlet
    if (servletRequest.getPathInfo() != null) {//ex: /my/path.html
        uri.append(servletRequest.getPathInfo());
    }
    LOGGER.debug("uri: {}", uri.toString());
    try {
        servicesClient.proxyPost(uri.toString(), stringBuilder.toString());
    } catch (ClientException e) {
        e.printStackTrace();
    }

}

From source file:edu.lafayette.metadb.web.controlledvocab.CreateVocab.java

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*///from  ww  w  .j  a v a  2  s  .  c o  m
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    PrintWriter out = response.getWriter();
    String vocabName = null;
    String name = "nothing";
    String status = "Upload failed ";

    try {

        if (ServletFileUpload.isMultipartContent(request)) {
            name = "isMultiPart";
            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
            List fileItemsList = servletFileUpload.parseRequest(request);
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */

            InputStream input = null;
            Iterator it = fileItemsList.iterator();
            String result = "";
            String vocabs = null;

            while (it.hasNext()) {
                FileItem fileItem = (FileItem) it.next();
                result += "CreateVocab: Form Field: " + fileItem.isFormField() + " Field name: "
                        + fileItem.getFieldName() + " Name: " + fileItem.getName() + " String: "
                        + fileItem.getString() + "\n";
                if (fileItem.isFormField()) {
                    /* The file item contains a simple name-value pair of a form field */
                    if (fileItem.getFieldName().equals("vocab-name"))
                        vocabName = fileItem.getString();
                    else if (fileItem.getFieldName().equals("vocab-terms"))
                        vocabs = fileItem.getString();
                } else {

                    @SuppressWarnings("unused")
                    String content = "nothing";
                    /* The file item contains an uploaded file */

                    /* Create new File object
                    File uploadedFile = new File("test.txt");
                    if(!uploadedFile.exists())
                       uploadedFile.createNewFile();
                    // Write the uploaded file to the system
                    fileItem.write(uploadedFile);
                    */
                    name = fileItem.getName();
                    content = fileItem.getContentType();
                    input = fileItem.getInputStream();
                }
            }
            //MetaDbHelper.note(result);
            if (vocabName != null) {
                Set<String> vocabList = new TreeSet<String>();
                if (input != null) {
                    Scanner fileSc = new Scanner(input);
                    while (fileSc.hasNextLine()) {
                        String vocabEntry = fileSc.nextLine();
                        vocabList.add(vocabEntry.trim());
                    }

                    HttpSession session = request.getSession(false);
                    if (session != null) {
                        String userName = (String) session.getAttribute("username");
                        SysLogDAO.log(userName, Global.SYSLOG_PROJECT,
                                "User " + userName + " created vocab " + vocabName);
                    }
                    status = "Vocab name: " + vocabName + ". File name: " + name + "\n";

                } else {
                    //               status = "Form is not multi-part";
                    //               vocabName = request.getParameter("vocab-name");
                    //               String vocabs = request.getParameter("vocab-terms");
                    MetaDbHelper.note(vocabs);
                    for (String vocab : vocabs.split("\n"))
                        vocabList.add(vocab);
                }
                if (!vocabList.isEmpty()) {
                    if (ControlledVocabDAO.addControlledVocab(vocabName, vocabList))
                        status = "Vocab " + vocabName + " created successfully";
                    else if (ControlledVocabDAO.updateControlledVocab(vocabName, vocabList))
                        status = "Vocab " + vocabName + " updated successfully ";
                    else
                        status = "Vocab " + vocabName + " cannot be updated/created";
                }
            }
        }
    } catch (Exception e) {
        MetaDbHelper.logEvent(e);
    }
    MetaDbHelper.note(status);
    out.print(status);
    out.flush();
}

From source file:jp.classmethod.aws.petrucci.Tasks.java

@Scheduled(cron = "0 */2 * * * *")
public void reportS3AndEC2() {
    logger.info("report start");
    DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    StringBuilder sb = new StringBuilder();

    logger.info("check S3 buckets");
    sb.append("== S3 Buckets ==\n");
    try {//from  ww w  .ja  va2  s. c om
        for (Bucket bucket : s3.listBuckets()) {
            sb.append(
                    String.format("%s (created:%s)%n", bucket.getName(), df.format(bucket.getCreationDate())));
        }
    } catch (AmazonClientException e) {
        logger.error("unexpected exception", e);
    }

    sb.append("\n");

    logger.info("check EC2 instances");
    sb.append("== EC2 Instances ==").append("\n");
    try {
        DescribeInstancesResult result = ec2.describeInstances();
        for (Reservation reservation : result.getReservations()) {
            for (Instance instance : reservation.getInstances()) {
                sb.append(String.format("%s %s %s%n", instance.getInstanceId(), instance.getImageId(),
                        instance.getInstanceType(), instance.getInstanceLifecycle()));
            }
        }
    } catch (AmazonClientException e) {
        logger.error("unexpected exception", e);
    }

    if (logger.isInfoEnabled()) {
        Scanner scanner = null;
        try {
            scanner = new Scanner(sb.toString());
            while (scanner.hasNextLine()) {
                logger.info("{}", scanner.nextLine());
            }
        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }
    }

    logger.info("send report mail");
    ses.sendEmail(new SendEmailRequest(mailaddress, new Destination(Collections.singletonList(mailaddress)),
            new Message(new Content("S3 & EC2 Report"), new Body(new Content(sb.toString())))));

    logger.info("report end");
}

From source file:org.dbpedia.spotlight.lucene.index.CandidateIndexer.java

/**
 * Index surrogates mapping from a tab separated file.
 */// w  w  w .  j  a  v  a2 s  .  c  o  m
public void addFromTSVfile(File surfaceFormsDataSet) throws IOException, IndexException {
    LOG.info("Indexing candidate map from " + surfaceFormsDataSet.getName() + " to " + mLucene.directory()
            + "...");

    String separator = "\t";
    Scanner tsvScanner = new Scanner(new FileInputStream(surfaceFormsDataSet), "UTF-8");

    while (tsvScanner.hasNextLine()) {
        String[] line = tsvScanner.nextLine().split(separator);
        String surfaceFormString = line[0];
        String resourceString = line[1];
        //TODO read counts and set DBpediaResource.support
        // int countSfRes = new Integer(line[2])
        DBpediaResource res = new DBpediaResource(resourceString);
        // DBpediaResource res = new DBpediaResource(resourceString,countSfRes)
        List<SurfaceForm> surfaceForms = AddSurfaceFormsToIndex
                .fromTitlesToAlternativesJ(new SurfaceForm(surfaceFormString));
        add(surfaceForms, res);
    }

    LOG.info("Done.");
}

From source file:ca.ualberta.cs.expenseclaim.dao.ExpenseClaimDao.java

private ExpenseClaimDao(Context context) {
    claimList = new ArrayList<ExpenseClaim>();
    File file = new File(context.getFilesDir(), FILENAME);
    Scanner scanner = null;
    try {//w  w  w  .ja  v  a2  s .  c  o m
        scanner = new Scanner(file);
        while (scanner.hasNextLine()) {
            JSONObject jo = new JSONObject(scanner.nextLine());
            ExpenseClaim claim = new ExpenseClaim();
            claim.setId(jo.getInt("id"));
            claim.setName(jo.getString("name"));
            claim.setDescription(jo.getString("description"));
            claim.setStartDate(new Date(jo.getLong("startDate")));
            claim.setEndDate(new Date(jo.getLong("endDate")));
            claim.setStatus(jo.getString("status"));
            if (maxId < claim.getId()) {
                maxId = claim.getId();
            }
            claimList.add(claim);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
    maxId++;
}

From source file:com.ibm.bluemix.samples.UploadServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("Upload Servlet");

    try {/*from   www  .j a  v a 2  s .com*/
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : items) {
            if (!item.isFormField()) {
                // item is the file (and not a field), read it in and add to List
                Scanner scanner = new Scanner(new InputStreamReader(item.getInputStream(), "UTF-8"));
                List<String> lines = new ArrayList<String>();
                while (scanner.hasNextLine()) {
                    String line = scanner.nextLine().trim();
                    if (line.length() > 0) {
                        lines.add(line);
                    }
                }
                scanner.close();

                // add lines to database
                int rows = db.addPosts(lines);
                String msg = "Added " + rows + " rows.";
                request.setAttribute("msg", msg);
                break;
            }
        }

        request.setAttribute("posts", db.getResults());
    } catch (Exception e) {
        request.setAttribute("msg", e.getMessage());
        e.printStackTrace(System.err);
    }

    response.setContentType("text/html");
    response.setStatus(200);
    request.getRequestDispatcher("/home.jsp").forward(request, response);
}

From source file:org.dbpedia.spotlight.lucene.index.CandidateIndexer.java

/**
 * Index surrogates mapping from a tab separated file.
 *///www.  j ava2s  .  c o  m
public void addFromCounts(File surfaceFormsDataSet, int minCount) throws IOException, IndexException {
    LOG.info("Indexing candidate map from " + surfaceFormsDataSet.getName() + " to " + mLucene.directory()
            + "...");

    String separator = "\t";
    Scanner tsvScanner = new Scanner(new FileInputStream(surfaceFormsDataSet), "UTF-8");

    while (tsvScanner.hasNextLine()) {
        String[] line = tsvScanner.nextLine().split(separator);
        try {
            String countAndSf = line[0];
            int count = Integer.valueOf(countAndSf.substring(0, 7).trim());
            String resourceString = countAndSf.substring(8);
            String surfaceFormString = line[1];
            if (count > minCount)
                add(new SurfaceForm(surfaceFormString), new DBpediaResource(resourceString), count);
            List<SurfaceForm> surfaceForms = AddSurfaceFormsToIndex
                    .fromTitlesToAlternativesJ(new SurfaceForm(surfaceFormString));
            add(surfaceForms, new DBpediaResource(resourceString));
        } catch (ArrayIndexOutOfBoundsException e) {
            LOG.error("Error parsing line: " + line);
            e.printStackTrace();
        }
    }

    LOG.info("Done.");
}

From source file:ca.ualberta.cs.expenseclaim.dao.ExpenseItemDao.java

private ExpenseItemDao(Context context) {
    itemList = new ArrayList<ExpenseItem>();
    File file = new File(context.getFilesDir(), FILENAME);
    Scanner scanner = null;
    try {/*from   w w  w.  j  a v  a2 s. com*/
        scanner = new Scanner(file);
        while (scanner.hasNextLine()) {
            JSONObject jo = new JSONObject(scanner.nextLine());
            ExpenseItem item = new ExpenseItem();
            item.setId(jo.getInt("id"));
            item.setClaimId(jo.getInt("claimId"));
            item.setCategory(jo.getString("category"));
            item.setDescription(jo.getString("description"));
            item.setDate(new Date(jo.getLong("date")));
            item.setAmount(jo.getDouble("amount"));
            item.setUnit(jo.getString("unit"));
            if (maxId < item.getId()) {
                maxId = item.getId();
            }
            itemList.add(item);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
    maxId++;
}