Example usage for java.util Scanner nextLine

List of usage examples for java.util Scanner nextLine

Introduction

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

Prototype

public String nextLine() 

Source Link

Document

Advances this scanner past the current line and returns the input that was skipped.

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());
    }//from   ww w  .  j a  va 2  s  . c  o  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: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());
    }/*from 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:jmap2gml.ScriptGui.java

private void loadConfig() {
    try {//w w  w.  j a  v  a2 s .  c  o m
        Scanner scan = new Scanner(new File("config"));

        JSONObject config = new JSONObject(scan.nextLine());
        this.setLocation(config.getInt("WindowX"), config.getInt("WindowY"));
        prevDirectory = config.getString("PrevFile");
        jta.setText(config.getString("PrevScript"));
        jta.setCaretPosition(0);

    } catch (FileNotFoundException | JSONException ex) {
    }
}

From source file:org.sasabus.export2Freegis.network.SubscriptionManager.java

public void unsubscribe() throws IOException {
    Scanner sc = new Scanner(new File(UNSUBSCRIPTIONFILE));
    String subscriptionstring = "";
    while (sc.hasNextLine()) {
        subscriptionstring += sc.nextLine();
    }//from  w  w  w .j av  a  2 s.c o  m
    sc.close();
    SimpleDateFormat date_date = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat date_time = new SimpleDateFormat("HH:mm:ssZ");

    Date d = new Date();
    String timestamp = date_date.format(d) + "T" + date_time.format(d);
    timestamp = timestamp.substring(0, timestamp.length() - 2) + ":"
            + timestamp.substring(timestamp.length() - 2);

    subscriptionstring = subscriptionstring.replaceAll(":timestamp", timestamp);

    String requestString = "http://" + this.address + ":" + this.portnumber_sender
            + "/TmEvNotificationService/gms/subscription.xml";

    HttpPost subrequest = new HttpPost(requestString);

    StringEntity requestEntity = new StringEntity(subscriptionstring,
            ContentType.create("text/xml", "ISO-8859-1"));

    CloseableHttpClient httpClient = HttpClients.createDefault();

    subrequest.setEntity(requestEntity);

    CloseableHttpResponse response = httpClient.execute(subrequest);

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        try {
            System.out.println("Stauts Response: " + response.getStatusLine().getStatusCode());
            System.out.println("Status Phrase: " + response.getStatusLine().getReasonPhrase());
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                String responsebody = EntityUtils.toString(responseEntity);
                System.out.println(responsebody);
            }
        } finally {
            response.close();
            httpClient.close();
        }
    }
}

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 {// ww  w .  j  a  va 2s . c o m
        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:com.addthis.hydra.data.util.JSONFetcher.java

/**
 * loads a json-formatted array from an url and adds enclosing
 * square brackets if missing//from   w w w .  j a va  2  s  .c  om
 *
 * @param mapURL
 * @return string set
 */
public HashSet<String> loadCSVSet(String mapURL, HashSet<String> set) {
    try {
        byte[] raw = retrieveBytes(mapURL);
        String list = LessBytes.toString(raw);

        if (set == null) {
            set = new HashSet<>();
        }

        Scanner in = new Scanner(list);

        while (in.hasNext()) {
            set.add(in.nextLine().replaceAll("^\"|\"$", ""));
        }

        return set;
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

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  w  ww  .  j  a  v a  2s  .c  om*/
        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:com.joliciel.csvLearner.EventCombinationGenerator.java

public void readDesiredCounts(File file) {
    try {//from  w ww .j av  a2  s.c  o m
        this.desiredCountPerOutcome = new LinkedHashMap<String, Integer>();
        Scanner scanner = new Scanner(new FileInputStream(file), "UTF-8");
        try {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                List<String> cells = CSVFormatter.getCSVCells(line);
                String outcome = cells.get(0);
                int count = Integer.parseInt(cells.get(1));
                this.desiredCountPerOutcome.put(outcome, count);
            }
        } finally {
            scanner.close();
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:com.bealearts.template.SimpleTemplate.java

/**
 * Load a template file/*from   w w  w . j a  v  a 2  s . c  o m*/
 * @throws FileNotFoundException 
 */
public void loadTemplate(File template) throws FileNotFoundException {
    this.blockMap = new HashMap<String, BlockContent>();
    this.blockData = null;

    StringBuilder text = new StringBuilder();
    String NL = System.getProperty("line.separator");
    Scanner scanner = new Scanner(new FileInputStream(template), "UTF-8");
    try {
        while (scanner.hasNextLine()) {
            text.append(scanner.nextLine() + NL);
        }
    } finally {
        scanner.close();
    }

    this.parseTemplate(text.toString());
}

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

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/// w ww .  j av  a2s.c om
@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();
}