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:com.klarna.checkout.stubs.HttpClientStub.java

/**
 * Uppercase data to simulate it having passed on to the server.
 *
 * @throws IOException in case of an IO error.
 *//*from  ww w  . j a v a 2  s  .c  om*/
private void fixData() throws IOException {
    if (this.httpUriReq.getMethod().equals("POST")) {
        HttpEntityEnclosingRequest h = (HttpEntityEnclosingRequest) this.httpUriReq;

        InputStream is = h.getEntity().getContent();
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");

        String str = "";
        while (s.hasNext()) {
            str = str.concat(s.next());
        }
        JSONParser jsonParser = new JSONParser();
        HashMap<String, String> obj = null;
        try {
            obj = (HashMap<String, String>) jsonParser.parse(str);
        } catch (ParseException ex) {
            Logger.getLogger(HttpClientStub.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (obj != null && obj.containsKey("test")) {
            str = obj.get("test").toUpperCase();
            this.data.put("test", str);
        }

        ByteArrayInputStream in = new ByteArrayInputStream(JSONObject.toJSONString(this.data).getBytes());

        this.lastResponse.setEntity(new InputStreamEntity(in, in.available()));
    }
}

From source file:eremeykin.pete.plotter.CartesianPlotterTopComponent.java

@Override
public void update() {
    // for first rpt file
    if (model == null) {
        clear();/*from  w w  w  .j a v  a2 s. c o m*/
        return;
    }
    File[] rptFiles = home.listFiles(filter());
    // catch if there is no such file
    if (rptFiles.length == 0) {
        clear();
        return;
    }
    File firstRPT = rptFiles[0];

    Scanner scanner;
    try {
        scanner = new Scanner(firstRPT);
        scanner.useDelimiter("\\s+|\n");
    } catch (FileNotFoundException ex) {
        clear();
        return;
    }
    List<Map.Entry<Double, Double>> tmpList = new ArrayList<>();
    for (int i = 0; scanner.hasNext(); i++) {
        String line = scanner.next();
        try {
            double x1 = Double.valueOf(line);
            line = scanner.next();
            double x2 = Double.valueOf(line);
            //                System.out.println("x1=" + x1 + "\nx2=" + x2);
            tmpList.add(new AbstractMap.SimpleEntry<>(x1, x2));
        } catch (NumberFormatException ex) {
            // only if it is the third or following line
            if (i > 1) {
                LOGGER.error("Error while parsing double from file: " + firstRPT.getAbsolutePath());
                JOptionPane.showMessageDialog(this, "Error while parsing result file.", "Parsing error",
                        JOptionPane.ERROR_MESSAGE);
            }
        }

    }
    if (tmpList.isEmpty()) {
        clear();
        return;
    }
    fillData(tmpList);

}

From source file:no.sintef.jarfter.Jarfter.java

private String streamToString(InputStream input) {
    String encoding = "UTF-8";
    java.util.Scanner scanner = new java.util.Scanner(input).useDelimiter("\\A");
    String inputAsString = scanner.hasNext() ? scanner.next() : "";
    return inputAsString.replaceAll("[\uFEFF-\uFFFF]", "");
}

From source file:org.c99.wear_imessage.RemoteInputService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent != null) {
        final String action = intent.getAction();
        if (ACTION_REPLY.equals(action)) {
            JSONObject conversations = null, conversation = null;
            try {
                conversations = new JSONObject(
                        getSharedPreferences("data", 0).getString("conversations", "{}"));
            } catch (JSONException e) {
                conversations = new JSONObject();
            }//  w  ww.  j a  v a  2s. c  om

            try {
                String key = intent.getStringExtra("service") + ":" + intent.getStringExtra("handle");
                if (conversations.has(key)) {
                    conversation = conversations.getJSONObject(key);
                } else {
                    conversation = new JSONObject();
                    conversations.put(key, conversation);

                    long time = new Date().getTime();
                    String tmpStr = String.valueOf(time);
                    String last4Str = tmpStr.substring(tmpStr.length() - 5);
                    conversation.put("notification_id", Integer.valueOf(last4Str));
                    conversation.put("msgs", new JSONArray());
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
            if (remoteInput != null || intent.hasExtra("reply")) {
                String reply = remoteInput != null ? remoteInput.getCharSequence("extra_reply").toString()
                        : intent.getStringExtra("reply");

                if (intent.hasExtra(Intent.EXTRA_STREAM)) {
                    NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
                            .setContentTitle("Uploading File").setProgress(0, 0, true).setLocalOnly(true)
                            .setOngoing(true).setSmallIcon(android.R.drawable.stat_sys_upload);
                    NotificationManagerCompat.from(this).notify(1337, notification.build());

                    InputStream fileIn = null;
                    InputStream responseIn = null;
                    HttpURLConnection http = null;
                    try {
                        String filename = "";
                        int total = 0;
                        String type = getContentResolver()
                                .getType((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM));
                        if (type == null || type.length() == 0)
                            type = "application/octet-stream";
                        fileIn = getContentResolver()
                                .openInputStream((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM));

                        Cursor c = getContentResolver().query(
                                (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM),
                                new String[] { OpenableColumns.SIZE, OpenableColumns.DISPLAY_NAME }, null, null,
                                null);
                        if (c != null && c.moveToFirst()) {
                            total = c.getInt(0);
                            filename = c.getString(1);
                            c.close();
                        } else {
                            total = fileIn.available();
                        }

                        String boundary = UUID.randomUUID().toString();
                        http = (HttpURLConnection) new URL(
                                "http://" + getSharedPreferences("prefs", 0).getString("host", "") + "/upload")
                                        .openConnection();
                        http.setReadTimeout(60000);
                        http.setConnectTimeout(60000);
                        http.setDoOutput(true);
                        http.setFixedLengthStreamingMode(total + (boundary.length() * 5) + filename.length()
                                + type.length() + intent.getStringExtra("handle").length()
                                + intent.getStringExtra("service").length() + reply.length() + 251);
                        http.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

                        OutputStream out = http.getOutputStream();
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"handle\"\r\n\r\n").getBytes());
                        out.write((intent.getStringExtra("handle") + "\r\n").getBytes());
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"service\"\r\n\r\n").getBytes());
                        out.write((intent.getStringExtra("service") + "\r\n").getBytes());
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"msg\"\r\n\r\n").getBytes());
                        out.write((reply + "\r\n").getBytes());
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + filename
                                + "\"\r\n").getBytes());
                        out.write(("Content-Type: " + type + "\r\n\r\n").getBytes());

                        byte[] buffer = new byte[8192];
                        int count = 0;
                        int n = 0;
                        while (-1 != (n = fileIn.read(buffer))) {
                            out.write(buffer, 0, n);
                            count += n;

                            float progress = (float) count / (float) total;
                            if (progress < 1.0f)
                                notification.setProgress(1000, (int) (progress * 1000), false);
                            else
                                notification.setProgress(0, 0, true);
                            NotificationManagerCompat.from(this).notify(1337, notification.build());
                        }

                        out.write(("\r\n--" + boundary + "--\r\n").getBytes());
                        out.flush();
                        out.close();
                        if (http.getResponseCode() == HttpURLConnection.HTTP_OK) {
                            responseIn = http.getInputStream();
                            StringBuilder sb = new StringBuilder();
                            Scanner scanner = new Scanner(responseIn).useDelimiter("\\A");
                            while (scanner.hasNext()) {
                                sb.append(scanner.next());
                            }
                            android.util.Log.i("iMessage", "Upload result: " + sb.toString());
                            try {
                                if (conversation != null) {
                                    JSONArray msgs = conversation.getJSONArray("msgs");
                                    JSONObject m = new JSONObject();
                                    m.put("msg", filename);
                                    m.put("service", intent.getStringExtra("service"));
                                    m.put("handle", intent.getStringExtra("handle"));
                                    m.put("type", "sent_file");
                                    msgs.put(m);

                                    while (msgs.length() > 10) {
                                        msgs.remove(0);
                                    }

                                    GCMIntentService.notify(getApplicationContext(),
                                            intent.getIntExtra("notification_id", 0), msgs, intent, true);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            responseIn = http.getErrorStream();
                            StringBuilder sb = new StringBuilder();
                            Scanner scanner = new Scanner(responseIn).useDelimiter("\\A");
                            while (scanner.hasNext()) {
                                sb.append(scanner.next());
                            }
                            android.util.Log.e("iMessage", "Upload failed: " + sb.toString());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (responseIn != null)
                                responseIn.close();
                        } catch (Exception ignore) {
                        }
                        try {
                            if (http != null)
                                http.disconnect();
                        } catch (Exception ignore) {
                        }
                        try {
                            fileIn.close();
                        } catch (Exception ignore) {
                        }
                    }
                    NotificationManagerCompat.from(this).cancel(1337);
                } else if (reply.length() > 0) {
                    URL url = null;
                    try {
                        url = new URL("http://" + getSharedPreferences("prefs", 0).getString("host", "")
                                + "/send?service=" + intent.getStringExtra("service") + "&handle="
                                + intent.getStringExtra("handle") + "&msg="
                                + URLEncoder.encode(reply, "UTF-8"));
                    } catch (Exception e) {
                        e.printStackTrace();
                        return;
                    }
                    HttpURLConnection conn;

                    try {
                        conn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
                    } catch (IOException e) {
                        e.printStackTrace();
                        return;
                    }
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);
                    conn.setUseCaches(false);

                    BufferedReader reader = null;

                    try {
                        if (conn.getInputStream() != null) {
                            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()), 512);
                        }
                    } catch (IOException e) {
                        if (conn.getErrorStream() != null) {
                            reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()), 512);
                        }
                    }

                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    conn.disconnect();
                    try {
                        if (conversation != null) {
                            JSONArray msgs = conversation.getJSONArray("msgs");
                            JSONObject m = new JSONObject();
                            m.put("msg", reply);
                            m.put("service", intent.getStringExtra("service"));
                            m.put("handle", intent.getStringExtra("handle"));
                            m.put("type", "sent");
                            msgs.put(m);

                            while (msgs.length() > 10) {
                                msgs.remove(0);
                            }

                            GCMIntentService.notify(getApplicationContext(),
                                    intent.getIntExtra("notification_id", 0), msgs, intent, true);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                SharedPreferences.Editor e = getSharedPreferences("data", 0).edit();
                e.putString("conversations", conversations.toString());
                e.apply();
            }
        }
    }
}

From source file:jp.go.nict.langrid.wrapper.ws_1_2.translation.AbstractTranslationService.java

/**
 * //from www  . j av  a2 s.  c o  m
 * 
 */
public final String multistatementTranslate(String sourceLang, String targetLang, String source,
        String delimiterRegx)
        throws AccessLimitExceededException, InvalidParameterException, LanguagePairNotUniquelyDecidedException,
        NoAccessPermissionException, NoValidEndpointsException, ProcessFailedException, ServerBusyException,
        ServiceNotActiveException, ServiceNotFoundException, UnsupportedLanguagePairException {
    checkStartupException();
    if (StringUtils.isBlank(delimiterRegx)) {
        throw new InvalidParameterException("delimiterRegx", "is Blank.");
    }
    StringBuilder sb = new StringBuilder();
    Scanner s = new Scanner(source).useDelimiter(delimiterRegx);
    int i = 0;
    while (s.hasNext()) {
        String text = s.next();
        MatchResult m = s.match();
        if (i != m.start()) {
            String tag = source.substring(i, m.start());
            sb.append(tag);
        }
        i = m.end();
        sb.append(invokeDoTranslation(sourceLang, targetLang, text));
    }
    if (source.length() != i) {
        String tag = source.substring(i);
        sb.append(tag);
    }

    return sb.toString();
}

From source file:no.sintef.jarfter.Jarfter.java

private boolean fileContains(String filename, String searchString) {
    File file = new File(filename);
    try {/*from  w w  w .  j  a  v a 2  s . c  o m*/
        FileInputStream fileStream = new FileInputStream(file);
        java.util.Scanner scanner = new java.util.Scanner(fileStream).useDelimiter("\\A");
        String fileAsString = scanner.hasNext() ? scanner.next() : "";
        return fileAsString.contains(searchString);
    } catch (FileNotFoundException fnfe) {
        throw new JarfterException(JarfterException.Error.IO_NO_TEMP_FILE);
    }
}

From source file:org.springframework.data.gemfire.samples.helloworld.CommandProcessor.java

String process(final String line) {
    final Scanner sc = new Scanner(line);

    return template.execute(new GemfireCallback<String>() {

        public String doInGemfire(Region reg) throws GemFireCheckedException, GemFireException {
            Region<String, String> region = reg;

            if (!sc.hasNext(COM)) {
                return "Invalid command - type 'help' for supported operations";
            }// w  ww.jav  a  2  s .  co m
            String command = sc.next();
            String arg1 = (sc.hasNext() ? sc.next() : null);
            String arg2 = (sc.hasNext() ? sc.next() : null);

            // query shortcut
            if ("query".equalsIgnoreCase(command)) {
                String query = line.trim().substring(command.length());
                return region.query(query).toString();
            }

            // parse commands w/o arguments
            if ("exit".equalsIgnoreCase(command)) {
                threadActive = false;
                return "Node exiting...";
            }
            if ("help".equalsIgnoreCase(command)) {
                return help;
            }
            if ("size".equalsIgnoreCase(command)) {
                return EMPTY + region.size();
            }
            if ("clear".equalsIgnoreCase(command)) {
                region.clear();
                return "Clearing grid..";
            }
            if ("keys".equalsIgnoreCase(command)) {
                return region.keySet().toString();
            }
            if ("values".equalsIgnoreCase(command)) {
                return region.values().toString();
            }

            if ("map".equalsIgnoreCase(command)) {
                Set<Entry<String, String>> entrySet = region.entrySet();
                if (entrySet.size() == 0)
                    return "[]";

                StringBuilder sb = new StringBuilder();
                for (Entry<String, String> entry : entrySet) {
                    sb.append("[");
                    sb.append(entry.getKey());
                    sb.append("=");
                    sb.append(entry.getValue());
                    sb.append("] ");
                }
                return sb.toString();
            }

            // commands w/ 1 arg
            if ("containsKey".equalsIgnoreCase(command)) {
                return EMPTY + region.containsKey(arg1);
            }
            if ("containsValue".equalsIgnoreCase(command)) {
                return EMPTY + region.containsValue(arg1);
            }
            if ("get".equalsIgnoreCase(command)) {
                return region.get(arg1);
            }
            if ("remove".equalsIgnoreCase(command)) {
                return region.remove(arg1);
            }

            // commands w/ 2 args

            if ("put".equalsIgnoreCase(command)) {
                return region.put(arg1, arg2);
            }

            sc.close();
            return "unknown command - run 'help' for available commands";
        }
    });
}

From source file:ddf.catalog.transformer.csv.common.CsvTransformerTest.java

@Test
public void writeSearchResultsToCsvWithAliasMap() throws CatalogTransformerException {
    List<AttributeDescriptor> requestedAttributes = new ArrayList<>();
    requestedAttributes.add(buildAttributeDescriptor("attribute1", BasicTypes.STRING_TYPE));

    Map<String, String> aliasMap = ImmutableMap.of("attribute1", "column1");

    Appendable csvText = CsvTransformer.writeMetacardsToCsv(metacardList, requestedAttributes, aliasMap);

    Scanner scanner = new Scanner(csvText.toString());
    scanner.useDelimiter(CSV_ITEM_SEPARATOR_REGEX);

    String[] expectedHeaders = { "column1" };
    validate(scanner, expectedHeaders);/*from  ww  w  . j  av a2  s .  co m*/

    String[] expectedValues = { "", "value1" };

    for (int i = 0; i < METACARD_COUNT; i++) {
        validate(scanner, expectedValues);
    }

    // final new line causes an extra "" value at end of file
    assertThat(scanner.hasNext(), is(true));
    assertThat(scanner.next(), is(""));
    assertThat(scanner.hasNext(), is(false));
}

From source file:org.talend.dataprep.schema.csv.CSVFastHeaderAndTypeAnalyzer.java

/**
 * Performs type analysis for fields of the record at the specified index.
 * /*from   w w  w.j av a 2s  .  co m*/
 * @param i the index of the record to be analyzed.
 * @return the list of types of the record
 */
private List<Integer> setFieldType(int i) {
    List<Integer> result = new ArrayList<>();
    String line = i < sampleLines.size() ? sampleLines.get(i) : null;
    if (StringUtils.isEmpty(line)) {
        return result;
    }
    List<String> fields = readLine(line);
    for (String field : fields) {
        Scanner scanner = new Scanner(field);
        scanner.useDelimiter(Character.toString(separator.getSeparator()));
        // called integer but we are looking for long in Java parlance
        if (scanner.hasNextLong()) {
            result.add(INTEGER);
            scanner.next();
        } else if (scanner.hasNextDouble()) {
            result.add(DECIMAL);
            scanner.next();
        } else if (scanner.hasNextBoolean()) {
            result.add(BOOLEAN);
            scanner.next();
        } else {
            String text = scanner.hasNext() ? scanner.next() : StringUtils.EMPTY;
            switch (text) {
            case "":
                result.add(EMPTY);
                break;
            default: // used to detect a stable length of a field (may be it is a date or a pattern)
                result.add(text.length());
            }
        }
        scanner.close();
    }
    return result;
}

From source file:ddf.catalog.transformer.csv.common.CsvTransformerTest.java

@Test
public void writeSearchResultsToCsv() throws CatalogTransformerException {
    List<AttributeDescriptor> requestedAttributes = new ArrayList<>();
    requestedAttributes.add(buildAttributeDescriptor("attribute1", BasicTypes.STRING_TYPE));

    Appendable csvText = CsvTransformer.writeMetacardsToCsv(metacardList, requestedAttributes,
            Collections.emptyMap());

    Scanner scanner = new Scanner(csvText.toString());
    scanner.useDelimiter(CSV_ITEM_SEPARATOR_REGEX);

    String[] expectedHeaders = { "attribute1" };
    validate(scanner, expectedHeaders);//  w  ww.ja  va  2s .com

    String[] expectedValues = { "", "value1" };

    for (int i = 0; i < METACARD_COUNT; i++) {
        validate(scanner, expectedValues);
    }

    // final new line causes an extra "" value at end of file
    assertThat(scanner.hasNext(), is(true));
    assertThat(scanner.next(), is(""));
    assertThat(scanner.hasNext(), is(false));
}