Example usage for java.util Scanner hasNext

List of usage examples for java.util Scanner hasNext

Introduction

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

Prototype

public boolean hasNext() 

Source Link

Document

Returns true if this scanner has another token in its input.

Usage

From source file:Balo.MainFrame.java

public void getDataFileToJTable() {
    String fileNameDefined = "src/Balo/Data_1.csv";
    File file = new File(fileNameDefined);
    int i = 0;/*from w  w w . j  av  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:calendarioSeries.vistas.MainViewController.java

public MainViewController() {
    mesActual = new Mes();
    Calendar cal = Calendar.getInstance();
    this.hoy = cal.get(Calendar.DAY_OF_MONTH);
    this.esteMes = mesActual.getNumMes();
    this.esteAno = mesActual.getNumAno();

    File file = new File("data.db");
    FileInputStream fis;/* ww w.j a v  a2 s .  c  o m*/
    ObjectInputStream ois;
    try {
        fis = new FileInputStream(file);
        ois = new ObjectInputStream(fis);
        this.series = (ArrayList<Serie>) ois.readObject();
        ois.close();
    } catch (IOException ex) {
        ex.printStackTrace();
        this.series = new ArrayList<>();
        try {
            File datos = new File("seriesUsuario.json");
            Scanner in = new Scanner(datos);
            String toJson = "";
            while (in.hasNext()) {
                toJson += in.nextLine();
            }
            JSONObject sesion = new JSONObject(toJson);
            Set<String> ids = sesion.keySet();
            for (String id : ids) {
                Serie aux = new Serie(id);
                if (series.contains(aux)) {
                    JSONArray lastVisto = sesion.getJSONArray(id).getJSONArray(1);
                    aux.setVistosHasta(lastVisto.getInt(0), lastVisto.getInt(1));
                    int i = 0;
                    for (Serie serie : series) {
                        if (serie.equals(aux)) {
                            this.series.set(i, aux);
                        }
                        i++;
                    }
                } else {
                    this.series.add(aux);
                }
            }

        } catch (FileNotFoundException e) {

        }
    } catch (ClassNotFoundException ex) {
        ex.printStackTrace();
    }

}

From source file:edu.american.student.stonewall.display.html.framework.HTMLElement.java

private List<Browser> getBrowsersToCheck() {
    List<Browser> toReturn = new ArrayList<Browser>();
    InputStream is = this.getClass().getClassLoader().getResourceAsStream("browsers.conf");
    if (is != null) {
        Scanner in = new Scanner(is);
        in.useDelimiter("\n");
        while (in.hasNext()) {
            String line = in.next();
            toReturn.add(Browser.getBrowser(line));
        }//from   www.j a va 2  s . c  o m
    } else {
        log.warn("Ignoring browser check. browsers.conf not found!");
    }
    return toReturn;
}

From source file:edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator.java

public static String[] subsetStringVector(InputStream in, int column, int numCases) {
    String[] retVector = new String[numCases];
    Scanner scanner = new Scanner(in);
    scanner.useDelimiter("\\n");

    for (int caseIndex = 0; caseIndex < numCases; caseIndex++) {
        if (scanner.hasNext()) {
            String[] line = (scanner.next()).split("\t", -1);
            retVector[caseIndex] = line[column];

            if ("".equals(line[column])) {
                // An empty string is a string missing value!
                // An empty string in quotes is an empty string!
                retVector[caseIndex] = null;
            } else {
                // Strip the outer quotes:
                line[column] = line[column].replaceFirst("^\\\"", "");
                line[column] = line[column].replaceFirst("\\\"$", "");

                // We need to restore the special characters that 
                // are stored in tab files escaped - quotes, new lines 
                // and tabs. Before we do that however, we need to 
                // take care of any escaped backslashes stored in 
                // the tab file. I.e., "foo\t" should be transformed 
                // to "foo<TAB>"; but "foo\\t" should be transformed 
                // to "foo\t". This way new lines and tabs that were
                // already escaped in the original data are not 
                // going to be transformed to unescaped tab and 
                // new line characters!
                String[] splitTokens = line[column].split(Matcher.quoteReplacement("\\\\"), -2);

                // (note that it's important to use the 2-argument version 
                // of String.split(), and set the limit argument to a
                // negative value; otherwise any trailing backslashes 
                // are lost.)
                for (int i = 0; i < splitTokens.length; i++) {
                    splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\\""), "\"");
                    splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\t"), "\t");
                    splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\n"), "\n");
                    splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\r"), "\r");
                }/*from  ww  w . j a v  a 2s .c  o m*/
                // TODO: 
                // Make (some of?) the above optional; for ex., we 
                // do need to restore the newlines when calculating UNFs;
                // But if we are subsetting these vectors in order to 
                // create a new tab-delimited file, they will 
                // actually break things! -- L.A. Jul. 28 2014

                line[column] = StringUtils.join(splitTokens, '\\');

                retVector[caseIndex] = line[column];
            }

        } else {
            scanner.close();
            throw new RuntimeException("Tab file has fewer rows than the stored number of cases!");
        }
    }

    int tailIndex = numCases;
    while (scanner.hasNext()) {
        String nextLine = scanner.next();
        if (!"".equals(nextLine)) {
            scanner.close();
            throw new RuntimeException(
                    "Column " + column + ": tab file has more nonempty rows than the stored number of cases ("
                            + numCases + ")! current index: " + tailIndex + ", line: " + nextLine);
        }
        tailIndex++;
    }

    scanner.close();
    return retVector;

}

From source file:org.wso2.charon3.core.config.SCIMUserSchemaExtensionBuilder.java

private void readConfiguration(String configFilePath) throws CharonException {
    File provisioningConfig = new File(configFilePath);
    try {/* w w  w.java2s.c  om*/
        InputStream inputStream = new FileInputStream(provisioningConfig);
        //Scanner scanner = new Scanner(new FileInputStream(provisioningConfig));
        Scanner scanner = new Scanner(inputStream, "utf-8").useDelimiter("\\A");
        String jsonString = scanner.hasNext() ? scanner.next() : "";

        JSONArray attributeConfigArray = new JSONArray(jsonString);

        for (int index = 0; index < attributeConfigArray.length(); ++index) {
            JSONObject attributeConfig = attributeConfigArray.getJSONObject(index);
            ExtensionAttributeSchemaConfig attrubteConfig = new ExtensionAttributeSchemaConfig(attributeConfig);
            extensionConfig.put(attrubteConfig.getName(), attrubteConfig);

            /**
             * NOTE: Assume last config is the root config
             */
            if (index == attributeConfigArray.length() - 1) {
                extensionRootAttributeName = attrubteConfig.getName();
            }
        }
        inputStream.close();
    } catch (FileNotFoundException e) {
        throw new CharonException(SCIMConfigConstants.SCIM_SCHEMA_EXTENSION_CONFIG + " file not found!", e);
    } catch (JSONException e) {
        throw new CharonException(
                "Error while parsing " + SCIMConfigConstants.SCIM_SCHEMA_EXTENSION_CONFIG + " file!", e);
    } catch (IOException e) {
        throw new CharonException(
                "Error while closing " + SCIMConfigConstants.SCIM_SCHEMA_EXTENSION_CONFIG + " file!", e);
    }
}

From source file:com.photon.phresco.plugin.commons.PluginUtils.java

public void executeSql(SettingsInfo info, File basedir, String filePath, String fileName)
        throws PhrescoException {
    initDriverMap();/*  w w w  . j  av  a2s.co m*/
    String host = info.getPropertyInfo(Constants.DB_HOST).getValue();
    String port = info.getPropertyInfo(Constants.DB_PORT).getValue();
    String userName = info.getPropertyInfo(Constants.DB_USERNAME).getValue();
    String password = info.getPropertyInfo(Constants.DB_PASSWORD).getValue();
    String databaseName = info.getPropertyInfo(Constants.DB_NAME).getValue();
    String databaseType = info.getPropertyInfo(Constants.DB_TYPE).getValue();
    String version = info.getPropertyInfo(Constants.DB_VERSION).getValue();
    String connectionProtocol = findConnectionProtocol(databaseType, host, port, databaseName);
    Connection con = null;
    FileInputStream file = null;
    Statement st = null;
    try {
        Class.forName(getDbDriver(databaseType)).newInstance();
        file = new FileInputStream(basedir.getPath() + filePath + databaseType.toLowerCase() + File.separator
                + version + fileName);
        Scanner s = new Scanner(file);
        s.useDelimiter("(;(\r)?\n)|(--\n)");
        con = DriverManager.getConnection(connectionProtocol, userName, password);
        con.setAutoCommit(false);
        st = con.createStatement();
        while (s.hasNext()) {
            String line = s.next().trim();
            if (databaseType.equals("oracle")) {
                if (line.startsWith("--")) {
                    String comment = line.substring(line.indexOf("--"), line.lastIndexOf("--"));
                    line = line.replace(comment, "");
                    line = line.replace("--", "");
                }
                if (line.startsWith(Constants.REM_DELIMETER)) {
                    String comment = line.substring(0, line.lastIndexOf("\n"));
                    line = line.replace(comment, "");
                }
            }
            if (line.startsWith("/*!") && line.endsWith("*/")) {
                line = line.substring(line.indexOf("/*"), line.indexOf("*/") + 2);
            }
            if (line.trim().length() > 0) {
                st.execute(line);
            }
        }
    } catch (SQLException e) {
        throw new PhrescoException(e);
    } catch (FileNotFoundException e) {
        throw new PhrescoException(e);
    } catch (Exception e) {
        throw new PhrescoException(e);
    } finally {
        try {
            if (con != null) {
                con.commit();
                con.close();
            }
            if (file != null) {
                file.close();
            }
        } catch (Exception e) {
            throw new PhrescoException(e);
        }
    }
}

From source file:cz.cuni.mff.ksi.jinfer.autoeditor.automatonvisualizer.layouts.graphviz.GraphvizLayoutFactory.java

@SuppressWarnings("PMD")
private <T> Map<State<T>, Point2D> getGraphvizPositions(final byte[] graphInDotFormat,
        final Set<State<T>> automatonStates) throws GraphvizException, IOException {
    final Map<State<T>, Point2D> result = new HashMap<State<T>, Point2D>();

    // creates new dot process.
    final ProcessBuilder processBuilder = new ProcessBuilder(Arrays.asList(GraphvizUtils.getPath(), "-Tplain"));
    final Process process = processBuilder.start();

    // write our graph into dot binary standart input
    process.getOutputStream().write(graphInDotFormat);
    process.getOutputStream().flush();//from   ww w.ja  v a 2 s. c o m

    // read from dot binary standard output
    final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    process.getOutputStream().close();

    final Scanner scanner = new Scanner(reader);
    // jumps some unnecessary information from output
    scanner.next();
    scanner.next();

    // get width and height of graph
    windowWidth = 100 + (int) Double.parseDouble(scanner.next());
    windowHeight = 100 + (int) Double.parseDouble(scanner.next());

    // parse output for graph vertex positions
    while (scanner.hasNext()) {
        final String n = scanner.next();
        if (n.equals("node")) {
            final int nodeName = Integer.parseInt(scanner.next());
            final double x = Double.parseDouble(scanner.next());
            final double y = Double.parseDouble(scanner.next());
            boolean found = false;
            for (State<T> state : automatonStates) {
                if (state.getName() == nodeName) {
                    result.put(state, new Point(50 + (int) (x), 50 + (int) (y)));
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new GraphvizException("Node with name " + nodeName + " was not found in automaton.");
            }
        }
    }

    return result;
}

From source file:jvm.ncatz.netbour.ActivityAbout.java

@NonNull
@Override//from  w w  w.j  av a 2s . co m
protected MaterialAboutList getMaterialAboutList(@NonNull Context context) {
    count = 0;

    MaterialAboutCard.Builder builderCardApp = new MaterialAboutCard.Builder();
    builderCardApp.title(R.string.aboutApp);
    MaterialAboutCard.Builder builderCardAuthor = new MaterialAboutCard.Builder();
    builderCardAuthor.title(R.string.aboutAuthor);
    MaterialAboutCard.Builder builderCardSocial = new MaterialAboutCard.Builder();
    builderCardSocial.title(R.string.aboutSocial);
    MaterialAboutCard.Builder builderCardOther = new MaterialAboutCard.Builder();
    builderCardOther.title(R.string.aboutOther);

    IconicsDrawable iconAppVersion = new IconicsDrawable(this).icon(MaterialDesignIconic.Icon.gmi_info_outline)
            .color(ContextCompat.getColor(this, R.color.grey_800)).sizeDp(20);
    IconicsDrawable iconAppRepository = new IconicsDrawable(this).icon(MaterialDesignIconic.Icon.gmi_github_box)
            .color(ContextCompat.getColor(this, R.color.grey_800)).sizeDp(20);
    IconicsDrawable iconAppLicenses = new IconicsDrawable(this).icon(MaterialDesignIconic.Icon.gmi_file)
            .color(ContextCompat.getColor(this, R.color.grey_800)).sizeDp(20);
    IconicsDrawable iconAuthorEmail = new IconicsDrawable(this).icon(MaterialDesignIconic.Icon.gmi_email)
            .color(ContextCompat.getColor(this, R.color.grey_800)).sizeDp(20);
    IconicsDrawable iconAuthorWeb = new IconicsDrawable(this).icon(MaterialDesignIconic.Icon.gmi_view_web)
            .color(ContextCompat.getColor(this, R.color.grey_800)).sizeDp(20);
    IconicsDrawable iconSocialGithub = new IconicsDrawable(this).icon(MaterialDesignIconic.Icon.gmi_github_alt)
            .color(ContextCompat.getColor(this, R.color.grey_800)).sizeDp(20);
    IconicsDrawable iconSocialLinkedin = new IconicsDrawable(this).icon(MaterialDesignIconic.Icon.gmi_linkedin)
            .color(ContextCompat.getColor(this, R.color.grey_800)).sizeDp(20);
    IconicsDrawable iconSocialStack = new IconicsDrawable(this)
            .icon(MaterialDesignIconic.Icon.gmi_stackoverflow)
            .color(ContextCompat.getColor(this, R.color.grey_800)).sizeDp(20);
    IconicsDrawable iconSocialTwitter = new IconicsDrawable(this).icon(MaterialDesignIconic.Icon.gmi_twitter)
            .color(ContextCompat.getColor(this, R.color.grey_800)).sizeDp(20);
    IconicsDrawable iconOtherBugs = new IconicsDrawable(this).icon(MaterialDesignIconic.Icon.gmi_bug)
            .color(ContextCompat.getColor(this, R.color.grey_800)).sizeDp(20);

    MaterialAboutTitleItem itemAppName = new MaterialAboutTitleItem(getString(R.string.app_name),
            ContextCompat.getDrawable(this, R.drawable.logo160));
    MaterialAboutActionItem itemAppVersion = new MaterialAboutActionItem(getString(R.string.app_version_title),
            getString(R.string.app_version_sub), iconAppVersion, new MaterialAboutItemOnClickListener() {
                @Override
                public void onClick(boolean b) {
                    count++;
                    if (count == 7) {
                        try {
                            stopPlaying();
                            player = MediaPlayer.create(ActivityAbout.this, R.raw.easteregg);
                            player.start();
                            count = 0;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
    MaterialAboutActionItem itemAppRepository = new MaterialAboutActionItem(
            getString(R.string.app_repository_title), getString(R.string.app_repository_sub), iconAppRepository,
            new MaterialAboutItemOnClickListener() {
                @Override
                public void onClick(boolean b) {
                    String url = "https://github.com/JMedinilla/Netbour";
                    openUrl(url);
                }
            });
    MaterialAboutActionItem itemAppLicenses = new MaterialAboutActionItem(
            getString(R.string.app_licenses_title), getString(R.string.app_licenses_sub), iconAppLicenses,
            new MaterialAboutItemOnClickListener() {
                @Override
                public void onClick(boolean b) {
                    DialogPlus dialogPlus = DialogPlus.newDialog(ActivityAbout.this).setGravity(Gravity.BOTTOM)
                            .setContentHolder(new ViewHolder(R.layout.licenses_dialog)).setCancelable(true)
                            .setExpanded(true, 600).create();

                    View view = dialogPlus.getHolderView();
                    FButton apacheButton = (FButton) view.findViewById(R.id.apacheButton);
                    FButton mitButton = (FButton) view.findViewById(R.id.mitButton);
                    WebView webView = (WebView) view.findViewById(R.id.licensesWeb);
                    apacheButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            try {
                                AssetManager am = getAssets();
                                InputStream is = am.open("apache");

                                Scanner s = new Scanner(is).useDelimiter("\\A");
                                String apache = s.hasNext() ? s.next() : "";

                                AlertDialog.Builder builder = new AlertDialog.Builder(ActivityAbout.this);
                                builder.setTitle(R.string.apache_title);
                                builder.setMessage(apache);
                                builder.create().show();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    mitButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            try {
                                AssetManager am = getAssets();
                                InputStream is = am.open("mit");

                                Scanner s = new Scanner(is).useDelimiter("\\A");
                                String mit = s.hasNext() ? s.next() : "";

                                AlertDialog.Builder builder = new AlertDialog.Builder(ActivityAbout.this);
                                builder.setTitle(R.string.mit_title);
                                builder.setMessage(mit);
                                builder.create().show();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    try {
                        AssetManager am = getAssets();
                        InputStream is = am.open("licenses.html");

                        webView.loadData(inputStreamToString(is), "text/html", "UTF-8");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    dialogPlus.show();
                }
            });
    MaterialAboutTitleItem itemAuthorName = new MaterialAboutTitleItem(getString(R.string.author_name),
            ContextCompat.getDrawable(this, R.drawable.favicon));
    MaterialAboutActionItem itemAuthorEmail = new MaterialAboutActionItem(
            getString(R.string.author_email_title), getString(R.string.author_email_sub), iconAuthorEmail,
            new MaterialAboutItemOnClickListener() {
                @Override
                public void onClick(boolean b) {
                    sendEmail(getString(R.string.author_email_subject));
                }
            });
    MaterialAboutActionItem itemAuthorWeb = new MaterialAboutActionItem(getString(R.string.author_web_title),
            getString(R.string.author_web_sub), iconAuthorWeb, new MaterialAboutItemOnClickListener() {
                @Override
                public void onClick(boolean b) {
                    String url = "https://jvmedinilla.ncatz.com/";
                    openUrl(url);
                }
            });
    MaterialAboutActionItem itemSocialGithub = new MaterialAboutActionItem(
            getString(R.string.social_github_title), getString(R.string.social_github_sub), iconSocialGithub,
            new MaterialAboutItemOnClickListener() {
                @Override
                public void onClick(boolean b) {
                    String url = "https://github.com/JMedinilla";
                    openUrl(url);
                }
            });
    MaterialAboutActionItem itemSocialLinkedin = new MaterialAboutActionItem(
            getString(R.string.social_linkedin_title), getString(R.string.social_linkedin_sub),
            iconSocialLinkedin, new MaterialAboutItemOnClickListener() {
                @Override
                public void onClick(boolean b) {
                    String url = "https://www.linkedin.com/in/javier-medinilla-ag%C3%BCera-951749121/";
                    openUrl(url);
                }
            });
    MaterialAboutActionItem itemSocialStackoverflow = new MaterialAboutActionItem(
            getString(R.string.social_stack_title), getString(R.string.social_stack_sub), iconSocialStack,
            new MaterialAboutItemOnClickListener() {
                @Override
                public void onClick(boolean b) {
                    String url = "http://stackoverflow.com/users/7426526/jmedinilla?tab=profile";
                    openUrl(url);
                }
            });
    MaterialAboutActionItem itemSocialTwitter = new MaterialAboutActionItem(
            getString(R.string.social_twitter_title), getString(R.string.social_twitter_sub), iconSocialTwitter,
            new MaterialAboutItemOnClickListener() {
                @Override
                public void onClick(boolean b) {
                    String url = "https://twitter.com/JMedinillaDev";
                    openUrl(url);
                }
            });
    MaterialAboutActionItem itemOtherBugs = new MaterialAboutActionItem(getString(R.string.other_bug_title),
            getString(R.string.other_bug_sub), iconOtherBugs, new MaterialAboutItemOnClickListener() {
                @Override
                public void onClick(boolean b) {
                    sendEmail(getString(R.string.other_bug_subject));
                }
            });

    builderCardApp.addItem(itemAppName);
    builderCardApp.addItem(itemAppVersion);
    builderCardApp.addItem(itemAppRepository);
    builderCardApp.addItem(itemAppLicenses);
    builderCardAuthor.addItem(itemAuthorName);
    builderCardAuthor.addItem(itemAuthorEmail);
    builderCardAuthor.addItem(itemAuthorWeb);
    builderCardSocial.addItem(itemSocialGithub);
    builderCardSocial.addItem(itemSocialLinkedin);
    builderCardSocial.addItem(itemSocialStackoverflow);
    builderCardSocial.addItem(itemSocialTwitter);
    builderCardOther.addItem(itemOtherBugs);

    MaterialAboutList.Builder builderList = new MaterialAboutList.Builder();
    builderList.addCard(builderCardApp.build());
    builderList.addCard(builderCardAuthor.build());
    builderList.addCard(builderCardSocial.build());
    builderList.addCard(builderCardOther.build());

    return builderList.build();
}

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();
            }/*from  w ww  .j  a  v a 2 s.c  o  m*/

            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:com.jayway.restassured.internal.http.URIBuilder.java

/**
 * Adds all parameters within the Scanner to the list of
 * <code>parameters</code>, as encoded by <code>encoding</code>. For
 * example, a scanner containing the string <code>a=1&b=2&c=3</code> would
 * add the {@link NameValuePair NameValuePairs} a=1, b=2, and c=3 to the
 * list of parameters./*from   w  w  w  . java 2  s. c o m*/
 * <p>
 * Note that this method has been copied from {@link URLEncodedUtils#parse(java.util.List, java.util.Scanner, String)} but it doesn't do URL decoding.
 * </p>
 */
private List<NameValuePair> parse(URI uri) {
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    final String query = uri.getRawQuery();
    if (query != null && query.length() > 0) {
        final Scanner scanner = new Scanner(query);
        scanner.useDelimiter(PARAMETER_SEPARATOR);
        while (scanner.hasNext()) {
            String name;
            String value = null;
            String token = scanner.next();
            int i = token.indexOf(NAME_VALUE_SEPARATOR);
            if (i != -1) {
                name = token.substring(0, i).trim();
                value = token.substring(i + 1).trim();
            } else {
                name = token.trim();
            }
            parameters.add(new BasicNameValuePair(name, value));
        }
    }
    return parameters;
}