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:net.emotivecloud.scheduler.drp4one.DRP4OVF.java

private String VMDescriptionContext(EmotiveOVF ovf) {
    StringBuilder buf = new StringBuilder();
    // Context - requires again network attributes
    ///*w w w  .ja v a 2s  . c  o m*/
    // We list devices in order eth0, eth1, eth2... The context script will
    // get
    // them out and prepare the network configuration files.

    buf.append("CONTEXT = [\n");
    String separator = "";
    //        buf.append("hostname = \"optimis2.leeds\",");

    int ethNumber = 0;
    if (!ovf.getNetworks().isEmpty()) {
        for (OVFNetwork ovfNetwork : ovf.getNetworks().values()) {
            String nicName = ovfNetwork.getConnectionName();

            if (nicName == null || "".equals(nicName)) {
                String tmp = ovfNetwork.getIp();
                if (tmp != null) {
                    buf.append(separator);
                    buf.append("IP_");
                    buf.append(ethNumber);
                    buf.append(" = \"");
                    buf.append(tmp);
                    buf.append("\"\n");
                    separator = ",\n";
                }

                tmp = ovfNetwork.getMac();
                if (tmp != null) {
                    buf.append(separator);
                    buf.append("MAC_");
                    buf.append(ethNumber);
                    buf.append(" = \"");
                    buf.append(tmp);
                    buf.append("\"\n");
                    separator = ",\n";

                }

            } else {
                addNetworkConfigToContext(buf, separator, ethNumber, nicName);
            }
            ethNumber++;
        }

        log.debug("adding the networks configured in props..");
        log.debug("networks configured:" + netConnectNames);
        Scanner commaSperated = new Scanner(netConnectNames);
        commaSperated.useDelimiter(",");

        while (commaSperated.hasNext()) {
            String connectionName = commaSperated.next().trim();
            if (!nicNames.contains(connectionName)) {
                addNetworkConfigToContext(buf, separator, ethNumber, connectionName);
                log.debug("adding network config:" + connectionName);
                ethNumber++;
            }
        }
    } else {

        log.debug("no network configured in ovf input, hence checking the network config from properties file");
        log.debug("networks configured:" + netConnectNames);
        Scanner commaSperated = new Scanner(netConnectNames);
        commaSperated.useDelimiter(",");

        while (commaSperated.hasNext()) {
            String connectionName = commaSperated.next().trim();
            addNetworkConfigToContext(buf, separator, ethNumber, connectionName);
            ethNumber++;
            // buf.append("NIC = [\n");buf.append("NETWORK = \"");
            // buf.append(connectionName); buf.append("\"");
            // buf.append("]\n\n\n");
        }

    }

    Iterator<String> home_iter = arg1.iterator();
    Iterator<String> swap_iter = arg2.iterator();
    buf.append("HOME = \"");
    while (home_iter.hasNext()) {

        buf.append(home_iter.next());
        buf.append(" ");

    }

    buf.append("\",\n");
    buf.append("SWAP = \"");
    while (swap_iter.hasNext()) {

        buf.append(swap_iter.next());
        buf.append(" ");
    }
    buf.append("\"\n");
    //        buf.append("FILES=" + "\"" + scriptlocation + "/init.sh \"");
    buf.append("]\n");
    return buf.toString();
}

From source file:usbong.android.utils.UsbongUtils.java

public static View applyHintsInView(Activity a, View myView, int type) {
    Log.d(">>>>>>", "1");
    String filePath = UsbongUtils.USBONG_TREES_FILE_PATH + myTreeFileName + ".utree/hints/hints.xml";
    File file = new File(filePath);
    if (!file.exists()) {
        Log.d(">>>>>>", "2.1");
        file = new File(
                UsbongUtils.USBONG_TREES_FILE_PATH + "temp/" + myTreeFileName + ".utree/hints/hints.xml");

        if (!file.exists()) {
            Log.d(">>>>>>", "2.2");
            //            return myView; //just send the original view
            switch (type) {
            case IS_RADIOBUTTON:
                ((RadioButton) myView).setText(Html.fromHtml((((RadioButton) myView).getText().toString())));
                return myView;
            case IS_CHECKBOX:
                ((CheckBox) myView).setText(Html.fromHtml((((CheckBox) myView).getText().toString())));
                return myView;
            default: //case IS_TEXTVIEW:
                ((TextView) myView).setText(Html.fromHtml(((TextView) myView).getText().toString()));
                return myView;
            }/* www. j a v  a 2s  .  co  m*/
        }
    }
    //if this point is reached, this means that hint file exists

    Log.d(">>>>>>", "2");

    if (tokenizedStringList == null) {
        tokenizedStringList = new ArrayList<String>();
    } else {
        tokenizedStringList.clear();
    }
    Scanner sc;
    StringBuffer output = new StringBuffer();

    //added by Mike, Oct. 3, 2014
    //       myView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

    switch (type) {
    case IS_RADIOBUTTON:
        sc = new Scanner(((RadioButton) myView).getText().toString());
        ((RadioButton) myView).setText("");
        break;
    case IS_CHECKBOX:
        sc = new Scanner(((CheckBox) myView).getText().toString());
        ((CheckBox) myView).setText("");
        break;
    default: //case IS_TEXTVIEW:
        sc = new Scanner(((TextView) myView).getText().toString());
        /*
                     Spannable myScannable = ((Spannable)((TextView)myView).getText());
        //            sc = new Scanner(Html.toHtml(myScannable));             
                    sc = new Scanner(myScannable.toString());             
        */
        ((TextView) myView).setText("");
        break;
    }

    //Japanese sentences do not have clear delimiters, such as spaces. 
    //They do have particles, but how does a computer know if it's a particle 
    //or part of a phrase?
    if (getSetLanguage() == getLanguageBasedOnID(LANGUAGE_JAPANESE)) {
        //          if (sc.hasNext()) {
        while (sc.hasNext()) {
            ArrayList<String> temp = tokenizeJapaneseString(sc.next());

            for (int i = 0; i < temp.size(); i++) {
                tokenizedStringList.add(temp.get(i)); //= tokenizeJapaneseString(sc.next());
            }
        }
    } else {
        //edited by Mike, Oct. 19, 2014
        /*
                  while (sc.hasNext()) {
                     tokenizedStringList.add(sc.next()+" ");
                  }          
        */
        StringBuffer temp = new StringBuffer();
        while (sc.hasNext()) {
            temp.append(sc.next() + " ");

            Log.d(">>>temp: ", temp.toString());

            if (temp.toString().startsWith("<a")) {
                while (sc.hasNext() && !temp.toString().trim().endsWith("</a>")) {
                    temp.append(sc.next() + " ");
                }
            } else if (temp.toString().startsWith("<small>")) {
                while (sc.hasNext() && !temp.toString().trim().endsWith("</small>")) {
                    temp.append(sc.next() + " ");
                }
            } else if (temp.toString().startsWith("<big>")) {
                while (sc.hasNext() && !temp.toString().trim().endsWith("</big>")) {
                    temp.append(sc.next() + " ");
                }
            } else if (temp.toString().startsWith("<font>")) {
                while (sc.hasNext() && !temp.toString().trim().endsWith("</font>")) {
                    temp.append(sc.next() + " ");
                }
            } else if (temp.toString().startsWith("<b>")) {
                //                Log.d(">>nasa loob","<b>");
                while (sc.hasNext() && !temp.toString().trim().endsWith("</b>")) {
                    //                while (sc.hasNext()&&!temp.toString().trim().contains("</b>")) {
                    temp.append(sc.next() + " ");
                }
            } else if (temp.toString().startsWith("<i>")) {
                while (sc.hasNext() && !temp.toString().trim().endsWith("</i>")) {
                    //                while (sc.hasNext()&&!temp.toString().trim().contains("</i>")) {
                    temp.append(sc.next() + " ");
                }
            } else if (temp.toString().startsWith("<u>")) {
                while (sc.hasNext() && !temp.toString().trim().endsWith("</u>")) {
                    temp.append(sc.next() + " ");
                }
            }

            tokenizedStringList.add(temp.toString() + " ");
            temp.delete(0, temp.length());//reset
        }
    }

    for (int i = 0; i < tokenizedStringList.size(); i++) {
        Log.d(">>", "" + tokenizedStringList.get(i));
    }

    Log.d(">>>>>>", "3");

    try {
        boolean foundMatch = false;

        for (int i = 0; i < tokenizedStringList.size(); i++) {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XmlPullParser parser = factory.newPullParser();

            InputStream in = null;
            InputStreamReader reader;
            try {
                in = new BufferedInputStream(new FileInputStream(file));
            } catch (Exception e) {
                e.printStackTrace();
            }
            reader = new InputStreamReader(in, "UTF-8");

            parser.setInput(reader);

            foundMatch = false;

            //Reference: http://developer.android.com/training/basics/network-ops/xml.html;
            //last accessed: 24 Oct. 2012
            while (parser.next() != XmlPullParser.END_DOCUMENT) {
                if (parser.getEventType() != XmlPullParser.START_TAG) {
                    continue;
                }

                if (parser.getName().equals("string")) {

                    Log.d(">>>>>parser.getAttributeValue(null, 'name'): ",
                            parser.getAttributeValue(null, "name"));
                    Log.d(">>>>>tokenizedStringList.get(" + i + "): ", tokenizedStringList.get(i));

                    if (parser.getAttributeValue(null, "name").equals(tokenizedStringList.get(i).trim())) {
                        if (parser.next() == XmlPullParser.TEXT) {
                            //                          Log.d(">>>>>parser.getText();: ",parser.getText());
                            //                          return parser.getText();

                            final String hintText = parser.getText();
                            final UsbongDecisionTreeEngineActivity finalUdtea = (UsbongDecisionTreeEngineActivity) a;

                            SpannableString link = makeLinkSpan(tokenizedStringList.get(i),
                                    new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            new AlertDialog.Builder(finalUdtea).setTitle("Phrase Hint!")
                                                    .setMessage(hintText).setPositiveButton("OK",
                                                            new DialogInterface.OnClickListener() {
                                                                @Override
                                                                public void onClick(DialogInterface dialog,
                                                                        int which) {
                                                                }
                                                            })
                                                    .show();
                                        }
                                    });
                            Log.d(">>>", "has match: " + tokenizedStringList.get(i));
                            foundMatch = true;

                            switch (type) {
                            case IS_RADIOBUTTON:
                                ((RadioButton) myView).append(link);
                                makeLinksFocusable(((RadioButton) myView), IS_RADIOBUTTON);
                                continue;
                            case IS_CHECKBOX:
                                ((CheckBox) myView).append(link);
                                makeLinksFocusable(((CheckBox) myView), IS_CHECKBOX);
                                continue;
                            default://case IS_TEXTVIEW:
                                ((TextView) myView).append(link);
                                makeLinksFocusable(((TextView) myView), IS_TEXTVIEW);
                                continue;
                            }
                        }
                    }
                }
            }
            if (!foundMatch) {
                Log.d(">>>", "i: " + i + " " + tokenizedStringList.get(i));
                output.append(tokenizedStringList.get(i));
                Log.d(">>> type", "" + type);

                switch (type) {
                case IS_RADIOBUTTON:
                    ((RadioButton) myView).append(Html.fromHtml(tokenizedStringList.get(i)));
                    //makeLinksFocusable(((RadioButton)myView), IS_RADIOBUTTON);
                    continue;
                case IS_CHECKBOX:
                    ((CheckBox) myView).append(Html.fromHtml(tokenizedStringList.get(i)));
                    //                         makeLinksFocusable(((CheckBox)myView), IS_CHECKBOX); 
                    continue;
                default://case IS_TEXTVIEW:
                    //                        Log.d(">>>>>myView before Html.fromHtml...",((TextView)myView).getText().toString());
                    ((TextView) myView).append(Html.fromHtml(tokenizedStringList.get(i)));

                    //                        ((TextView)myView).setText(Html.fromHtml(((TextView)myView).getText().toString()+tokenizedStringList.get(i)));

                    Log.d(">>>>>myView", ((TextView) myView).getText().toString());
                    //                        ((CheckBox)myView).setText(mySpanned, TextView.BufferType.SPANNABLE);
                    //                        ((TextView)myView).setMovementMethod(LinkMovementMethod.getInstance());
                    //                         makeLinksFocusable(((TextView)myView), IS_TEXTVIEW); 
                    continue;
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return myView;
}

From source file:io.minio.MinioClient.java

/**
 * Executes complete multipart upload of given bucket name, object name, upload ID and parts.
 *//*from w w w.  j a  v  a2  s . c  o  m*/
private void completeMultipart(String bucketName, String objectName, String uploadId, Part[] parts)
        throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException,
        InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
        InternalException {
    Map<String, String> queryParamMap = new HashMap<>();
    queryParamMap.put(UPLOAD_ID, uploadId);

    CompleteMultipartUpload completeManifest = new CompleteMultipartUpload(parts);

    HttpResponse response = executePost(bucketName, objectName, null, queryParamMap, completeManifest);

    // Fixing issue https://github.com/minio/minio-java/issues/391
    String bodyContent = "";
    try {
        // read enitre body stream to string.
        Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A");
        if (scanner.hasNext()) {
            bodyContent = scanner.next();
        }
    } catch (EOFException e) {
        // Getting EOF exception is not an error.
        // Just log it.
        LOGGER.log(Level.WARNING, "EOF exception occured: " + e);
    } finally {
        response.body().close();
    }

    bodyContent = bodyContent.trim();
    if (!bodyContent.isEmpty()) {
        ErrorResponse errorResponse = new ErrorResponse(new StringReader(bodyContent));
        if (errorResponse.code() != null) {
            throw new ErrorResponseException(errorResponse, response.response());
        }
    }
}

From source file:org.de.jmg.learn.MainActivity.java

private void processPreferences(boolean blnReStarted) {
    libLearn.gStatus = "getting preferences";
    try {/*from  w ww .ja  va2s  .  c o  m*/
        libLearn.gStatus = "onCreate getPrefs";
        prefs = this.getPreferences(Context.MODE_PRIVATE);
        String Installer = this.getPackageManager().getInstallerPackageName(this.getPackageName());
        if (!blnReStarted) {
            if (prefs.getBoolean("play", true)
                    && (Installer == null || (!Installer.equalsIgnoreCase("com.android.vending")
                            && !Installer.contains("com.google.android")))) {
                lib.YesNoCheckResult res = lib.ShowMessageYesNoWithCheckbox(this,
                        Installer != null ? Installer : "", this.getString(R.string.msgNotGooglePlay),
                        this.getString(R.string.msgDontShowThisMessageAgain), false);
                if (res != null) {
                    prefs.edit().putBoolean("play", !res.checked).commit();
                    if (res.res == yesnoundefined.yes) {
                        String url = "https://play.google.com/store/apps/details?id=org.de.jmg.learn";//"https://play.google.com/apps/testing/org.de.jmg.learn";
                        Intent i = new Intent(Intent.ACTION_VIEW);
                        i.setData(Uri.parse(url));
                        startActivity(i);
                        finish();
                    }
                }
            } else {
                //lib.ShowMessageOKCancel(this,this.getString(R.string.msgAppStarted),"",true);
            }
        }
        vok = new Vokabel(this, (TextView) this.findViewById(R.id.txtStatus));
        if (fPA.fragMain != null)
            fPA.fragMain._vok = vok;
        vok.setSchrittweite((short) prefs.getInt("Schrittweite", 6));
        CharsetASCII = prefs.getString("CharsetASCII", "Windows-1252");
        vok.CharsetASCII = CharsetASCII;
        vok.setAbfragebereich((short) prefs.getInt("Abfragebereich", -1));
        DisplayDurationWord = prefs.getFloat("DisplayDurationWord", 1.5f);
        DisplayDurationBed = prefs.getFloat("DisplayDurationBed", 2.5f);
        PaukRepetitions = prefs.getInt("PaukRepetitions", 3);
        vok.ProbabilityFactor = prefs.getFloat("ProbabilityFactor", -1f);
        vok.setAbfrageZufaellig(prefs.getBoolean("Random", vok.getAbfrageZufaellig()));
        vok.setAskAll(prefs.getBoolean("AskAll", vok.getAskAll()));
        vok.RestartInterval = prefs.getInt("RestartInterval", 10);
        lib.sndEnabled = prefs.getBoolean("Sound", lib.sndEnabled);
        SoundDir = prefs.getString("SoundDir", Environment.getExternalStorageDirectory().getPath());
        Colors = getColorsFromPrefs();
        colSounds = getSoundsFromPrefs();
        blnTextToSpeech = prefs.getBoolean("TextToSpeech", true);
        StartTextToSpeech();

        boolean blnLicenseAccepted = prefs.getBoolean("LicenseAccepted", false);
        if (!blnLicenseAccepted) {
            InputStream is = this.getAssets().open("LICENSE");
            java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
            String strLicense = s.hasNext() ? s.next() : "";
            s.close();
            is.close();
            lib.yesnoundefined res = (lib.ShowMessageYesNo(this, strLicense, getString(R.string.license),
                    true));
            /*
            java.lang.CharSequence[] cbxs = {getString(R.string.gpl),getString(R.string.gplno)};
            boolean[] blns = {false,false};
            lib.yesnoundefined res = (lib.ShowMessageYesNoWithCheckboxes
             (this,
                   strLicense,
                   cbxs,
                   blns,
                   new DialogInterface.OnMultiChoiceClickListener() {
                    
                      @Override
                      public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                    
                      }
                   })
            );
            */
            if (res == lib.yesnoundefined.yes) {
                prefs.edit().putBoolean("LicenseAccepted", true).commit();
            } else {
                finish();
            }

        }
    } catch (Exception e) {

        lib.ShowException(this, e);
    }
}

From source file:org.de.jmg.learn.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.

    try {//w  w  w .j a v a2s . co m
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            mPager.setCurrentItem(SettingsActivity.fragID);
        } else if (id == R.id.mnuCredits) {
            InputStream is = this.getAssets().open("CREDITS");
            java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
            String strCredits = s.hasNext() ? s.next() : "";
            s.close();
            is.close();
            String versionName = context.getPackageManager().getPackageInfo(context.getPackageName(),
                    0).versionName;
            Spannable spn = lib.getSpanableString(strCredits + "\nV" + versionName);
            lib.ShowMessage(this, spn, "Credits");
        } else if (id == R.id.mnuContact) {
            Intent intent = new Intent(Intent.ACTION_SEND,
                    Uri.fromParts("mailto", "jhmgbl2@t-online.de", null));
            intent.setType("message/rfc822");
            intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "jhmgbl2@t-online.de" });
            String versionName = context.getPackageManager().getPackageInfo(context.getPackageName(),
                    0).versionName;
            intent.putExtra(Intent.EXTRA_SUBJECT, "learnforandroid " + versionName);
            intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.ConvertVok));
            this.startActivity(Intent.createChooser(intent, getString(R.string.SendMail)));
        } else if (id == R.id.mnuFileOpen) {
            mPager.setCurrentItem(fragFileChooser.fragID);
            //LoadFile(true);
        } else if (id == R.id.mnuHome) {
            mPager.setCurrentItem(_MainActivity.fragID);
        } else if (id == R.id.mnuOpenQuizlet) {
            //LoginQuizlet();
            if (mPager.getCurrentItem() != fragFileChooserQuizlet.fragID) {
                mPager.setCurrentItem(fragFileChooserQuizlet.fragID);
            } else {
                if (fPA != null && fPA.fragQuizlet != null) {
                    searchQuizlet();
                }
            }
        } else if (id == R.id.mnuUploadToQuizlet) {
            uploadtoQuizlet();

        } else if (id == R.id.mnuAskReverse) {
            item.setChecked(!item.isChecked());
            vok.reverse = item.isChecked();
            setMnuReverse();
        } else if (id == R.id.mnuOpenUri) {
            if (saveVok(false)) {
                String defaultURI = prefs.getString("defaultURI", "");
                Uri def;
                if (libString.IsNullOrEmpty(defaultURI)) {
                    File F = new File(JMGDataDirectory);
                    def = Uri.fromFile(F);
                } else {
                    def = Uri.parse(defaultURI);
                }
                lib.SelectFile(this, def);
            }
        } else if (id == R.id.mnuNew) {
            newVok();

        } else if (id == R.id.mnuAddWord) {
            mPager.setCurrentItem(_MainActivity.fragID);
            if (fPA.fragMain != null && fPA.fragMain.mainView != null) {
                if (fPA.fragMain.EndEdit(false)) {
                    vok.AddVokabel();
                    fPA.fragMain.getVokabel(true, false, true);
                    fPA.fragMain.StartEdit();
                }
            }

        } else if (id == R.id.mnuFileOpenASCII) {
            LoadFile(false);
        } else if (id == R.id.mnuConvMulti) {
            if (fPA.fragMain != null && fPA.fragMain.mainView != null) {
                vok.ConvertMulti();
                fPA.fragMain.getVokabel(false, false);
            }
        } else if (id == R.id.mnuFileSave) {
            saveVok(false);
        } else if (id == R.id.mnuSaveAs) {
            SaveVokAs(true, false);
        } else if (id == R.id.mnuRestart) {
            vok.restart();
        } else if (id == R.id.mnuDelete) {
            if (fPA.fragMain != null && fPA.fragMain.mainView != null) {
                vok.DeleteVokabel();
                fPA.fragMain.EndEdit2();
            }
        } else if (id == R.id.mnuReverse) {
            if (fPA.fragMain != null && fPA.fragMain.mainView != null) {
                vok.revert();
                fPA.fragMain.getVokabel(false, false);
            }
        } else if (id == R.id.mnuReset) {
            if (lib.ShowMessageYesNo(this, this.getString(R.string.ResetVocabulary),
                    "") == yesnoundefined.yes) {
                vok.reset();
            }

        } else if (id == R.id.mnuStatistics) {
            if (vok.getGesamtzahl() > 5) {
                try {
                    /*
                    IDemoChart chart = new org.de.jmg.learn.chart.LearnBarChart();
                    int UIMode = lib.getUIMode(this);
                            
                    switch (UIMode)
                    {
                    case Configuration.UI_MODE_TYPE_TELEVISION:
                    isTV = true;
                    break;
                    case Configuration.UI_MODE_TYPE_WATCH:
                    isWatch = true;
                    break;
                    }
                    Intent intent = chart.execute(this);
                    this.startActivity(intent);
                    */
                    mPager.setCurrentItem(fragStatistics.fragID);
                } catch (Exception ex) {
                    lib.ShowException(this, ex);
                }

            }
        } else if (id == R.id.mnuEdit) {
            if (fPA.fragMain != null && fPA.fragMain.mainView != null) {
                fPA.fragMain.edit();
            }
        } else if (id == R.id.mnuLoginQuizlet) {
            LoginQuizlet(false);
        }

    } catch (Throwable ex) {
        lib.ShowException(this, ex);
    }

    return super.onOptionsItemSelected(item);
}

From source file:io.minio.MinioClient.java

/**
 * Executes given request parameters./* w  w w  .ja va  2  s  .  c o  m*/
 *
 * @param method         HTTP method.
 * @param region         Amazon S3 region of the bucket.
 * @param bucketName     Bucket name.
 * @param objectName     Object name in the bucket.
 * @param headerMap      Map of HTTP headers for the request.
 * @param queryParamMap  Map of HTTP query parameters of the request.
 * @param contentType    Content type of the request body.
 * @param body           HTTP request body.
 * @param length         Length of HTTP request body.
 */
private HttpResponse execute(Method method, String region, String bucketName, String objectName,
        Map<String, String> headerMap, Map<String, String> queryParamMap, String contentType, Object body,
        int length) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException,
        IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
        InternalException {
    Request request = createRequest(method, bucketName, objectName, region, headerMap, queryParamMap,
            contentType, body, length);

    if (this.accessKey != null && this.secretKey != null) {
        request = Signer.signV4(request, region, accessKey, secretKey);
    }

    if (this.traceStream != null) {
        this.traceStream.println("---------START-HTTP---------");
        String encodedPath = request.httpUrl().encodedPath();
        String encodedQuery = request.httpUrl().encodedQuery();
        if (encodedQuery != null) {
            encodedPath += "?" + encodedQuery;
        }
        this.traceStream.println(request.method() + " " + encodedPath + " HTTP/1.1");
        String headers = request.headers().toString().replaceAll("Signature=([0-9a-f]+)",
                "Signature=*REDACTED*");
        this.traceStream.println(headers);
    }

    Response response = this.httpClient.newCall(request).execute();
    if (response == null) {
        if (this.traceStream != null) {
            this.traceStream.println("<NO RESPONSE>");
            this.traceStream.println(END_HTTP);
        }
        throw new NoResponseException();
    }

    if (this.traceStream != null) {
        this.traceStream.println(response.protocol().toString().toUpperCase() + " " + response.code());
        this.traceStream.println(response.headers());
    }

    ResponseHeader header = new ResponseHeader();
    HeaderParser.set(response.headers(), header);

    if (response.isSuccessful()) {
        if (this.traceStream != null) {
            this.traceStream.println(END_HTTP);
        }
        return new HttpResponse(header, response);
    }

    ErrorResponse errorResponse = null;

    // HEAD returns no body, and fails on parseXml
    if (!method.equals(Method.HEAD)) {
        try {
            String errorXml = "";

            // read entire body stream to string.
            Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A");
            if (scanner.hasNext()) {
                errorXml = scanner.next();
            }

            errorResponse = new ErrorResponse(new StringReader(errorXml));

            if (this.traceStream != null) {
                this.traceStream.println(errorXml);
            }
        } finally {
            response.body().close();
        }
    }

    if (this.traceStream != null) {
        this.traceStream.println(END_HTTP);
    }

    if (errorResponse == null) {
        ErrorCode ec;
        switch (response.code()) {
        case 400:
            ec = ErrorCode.INVALID_URI;
            break;
        case 404:
            if (objectName != null) {
                ec = ErrorCode.NO_SUCH_KEY;
            } else if (bucketName != null) {
                ec = ErrorCode.NO_SUCH_BUCKET;
            } else {
                ec = ErrorCode.RESOURCE_NOT_FOUND;
            }
            break;
        case 501:
        case 405:
            ec = ErrorCode.METHOD_NOT_ALLOWED;
            break;
        case 409:
            if (bucketName != null) {
                ec = ErrorCode.NO_SUCH_BUCKET;
            } else {
                ec = ErrorCode.RESOURCE_CONFLICT;
            }
            break;
        case 403:
            ec = ErrorCode.ACCESS_DENIED;
            break;
        default:
            throw new InternalException("unhandled HTTP code " + response.code()
                    + ".  Please report this issue at " + "https://github.com/minio/minio-java/issues");
        }

        errorResponse = new ErrorResponse(ec, bucketName, objectName, request.httpUrl().encodedPath(),
                header.xamzRequestId(), header.xamzId2());
    }

    // invalidate region cache if needed
    if (errorResponse.errorCode() == ErrorCode.NO_SUCH_BUCKET) {
        BucketRegionCache.INSTANCE.remove(bucketName);
        // TODO: handle for other cases as well
        // observation: on HEAD of a bucket with wrong region gives 400 without body
    }

    throw new ErrorResponseException(errorResponse, response);
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.dta.DTA117FileReader.java

private void readSTRLs(DataReader reader) throws IOException {
    logger.fine("STRLs section; at offset " + reader.getByteOffset() + "; dta map offset: "
            + dtaMap.getOffset_strls());
    // TODO: /*  w  w w.j  av a2  s  .  c  o m*/
    // check that we are at the right byte offset!
    //reader.readOpeningTag(TAG_STRLS);

    if (hasSTRLs) {
        reader.readOpeningTag(TAG_STRLS);

        File intermediateTabFile = ingesteddata.getTabDelimitedFile();
        FileInputStream fileInTab = new FileInputStream(intermediateTabFile);

        Scanner scanner = new Scanner(fileInTab);
        scanner.useDelimiter("\\n");

        File finalTabFile = File.createTempFile("finalTabfile.", ".tab");
        FileOutputStream fileOutTab = new FileOutputStream(finalTabFile);
        PrintWriter pwout = new PrintWriter(new OutputStreamWriter(fileOutTab, "utf8"), true);

        logger.fine("Setting the tab-delimited file to " + finalTabFile.getName());
        ingesteddata.setTabDelimitedFile(finalTabFile);

        int nvar = dataTable.getVarQuantity().intValue();
        int nobs = dataTable.getCaseQuantity().intValue();

        String[] line;

        for (int obsindex = 0; obsindex < nobs; obsindex++) {
            if (scanner.hasNext()) {
                line = (scanner.next()).split("\t", -1);

                for (int varindex = 0; varindex < nvar; varindex++) {
                    if ("STRL".equals(variableTypes[varindex])) {
                        // this is a STRL; needs to be re-processed:

                        String voPair = line[varindex];
                        long v;
                        long o;
                        if (voPair == null) {
                            throw new IOException("Failed to read an intermediate v,o Pair for variable "
                                    + varindex + ", observation " + obsindex);
                        }

                        if ("0,0".equals(voPair)) {
                            // This is a code for an empty string - "";
                            // doesn't need to be defined or looked up.

                            line[varindex] = "\"\"";
                        } else {
                            String[] voTokens = voPair.split(",", 2);

                            try {
                                v = new Long(voTokens[0]).longValue();
                                o = new Long(voTokens[1]).longValue();
                            } catch (NumberFormatException nfex) {
                                throw new IOException("Illegal v,o value: " + voPair + " for variable "
                                        + varindex + ", observation " + obsindex);
                            }

                            if (v == varindex + 1 && o == obsindex + 1) {
                                // This v,o must be defined in the STRLs section:
                                line[varindex] = readGSO(reader, v, o);
                                if (line[varindex] == null) {
                                    throw new IOException("Failed to read GSO value for " + voPair);
                                }

                            } else {
                                // This one must have been cached already:
                                if (cachedGSOs.get(voPair) != null && !cachedGSOs.get(voPair).equals("")) {
                                    line[varindex] = cachedGSOs.get(voPair);
                                } else {
                                    throw new IOException("GSO string unavailable for v,o value " + voPair);
                                }
                            }
                        }
                    }
                }
                // Dump the row of data to the tab-delimited file:
                pwout.println(StringUtils.join(line, "\t"));
            }
        }

        scanner.close();
        pwout.close();

        reader.readClosingTag(TAG_STRLS);
    } else {
        // If this data file doesn't use STRLs, we can just skip 
        // this section, and assume that we are done with the 
        // tabular data file.
        reader.readPrimitiveSection(TAG_STRLS);
    }

    //reader.readClosingTag(TAG_STRLS);
}

From source file:Model.MultiPlatformLDA.java

public void readData() {
    Scanner sc = null;
    BufferedReader br = null;//  ww  w. j  a  v a 2  s  . c  o m
    String line = null;
    HashMap<String, Integer> userId2Index = null;
    HashMap<Integer, String> userIndex2Id = null;

    try {
        String folderName = dataPath + "/users";
        File postFolder = new File(folderName);

        // Read number of users
        int nUser = postFolder.listFiles().length;
        users = new User[nUser];
        userId2Index = new HashMap<String, Integer>(nUser);
        userIndex2Id = new HashMap<Integer, String>(nUser);
        int u = -1;

        // Read the posts from each user file
        for (File postFile : postFolder.listFiles()) {
            u++;
            users[u] = new User();

            // Read index of the user
            String userId = FilenameUtils.removeExtension(postFile.getName());
            userId2Index.put(userId, u);
            userIndex2Id.put(u, userId);
            users[u].userID = userId;

            // Read the number of posts from user
            int nPost = 0;
            br = new BufferedReader(new FileReader(postFile.getAbsolutePath()));
            while (br.readLine() != null) {
                nPost++;
            }
            br.close();

            // Declare the number of posts from user
            users[u].posts = new Post[nPost];

            // Read each of the post
            br = new BufferedReader(new FileReader(postFile.getAbsolutePath()));
            int j = -1;
            while ((line = br.readLine()) != null) {
                j++;
                users[u].posts[j] = new Post();

                sc = new Scanner(line.toString());
                sc.useDelimiter(",");
                while (sc.hasNext()) {
                    users[u].posts[j].postID = sc.next();
                    users[u].posts[j].platform = sc.nextInt();
                    users[u].posts[j].batch = sc.nextInt();

                    // Read the words in each post
                    String[] tokens = sc.next().toString().split(" ");
                    users[u].posts[j].words = new int[tokens.length];
                    for (int i = 0; i < tokens.length; i++) {
                        users[u].posts[j].words[i] = Integer.parseInt(tokens[i]);
                    }
                }
            }
            br.close();
        }

        // Read post vocabulary
        String vocabularyFileName = dataPath + "/vocabulary.csv";

        br = new BufferedReader(new FileReader(vocabularyFileName));
        int nPostWord = 0;
        while (br.readLine() != null) {
            nPostWord++;
        }
        br.close();
        vocabulary = new String[nPostWord];

        br = new BufferedReader(new FileReader(vocabularyFileName));
        while ((line = br.readLine()) != null) {
            String[] tokens = line.split(",");
            int index = Integer.parseInt(tokens[0]);
            vocabulary[index] = tokens[1];
        }
        br.close();

    } catch (Exception e) {
        System.out.println("Error in reading post from file!");
        e.printStackTrace();
        System.exit(0);
    }
}

From source file:net.siveo.virtualization.vmware.Main.java

public String processLine(String aLine) {
    Scanner scanner = new Scanner(aLine);
    scanner.useDelimiter("=");

    String parameter = null;/*w  ww .j a  va  2 s . c o  m*/
    String value = null;
    String txt = "";

    if (scanner.hasNext()) {
        parameter = scanner.next().trim();
        value = scanner.next().trim();

        if (parameter.equalsIgnoreCase("numvcpus") || parameter.equalsIgnoreCase("sched.cpu.min")
                || parameter.equalsIgnoreCase("sched.cpu.max") || parameter.equalsIgnoreCase("memSize")
                || parameter.equalsIgnoreCase("sched.mem.min") || parameter.equalsIgnoreCase("sched.mem.max")) {
            txt = txt + parameter + "=" + value + "\n";
        }

    }

    return txt;

}