Example usage for java.lang String toString

List of usage examples for java.lang String toString

Introduction

In this page you can find the example usage for java.lang String toString.

Prototype

public String toString() 

Source Link

Document

This object (which is already a string!) is itself returned.

Usage

From source file:io.undertow.server.security.DigestAuthenticationAuthTestCase.java

static void _testDigestSuccess() throws Exception {
    TestHttpClient client = new TestHttpClient();
    HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL());
    HttpResponse result = client.execute(get);
    assertEquals(StatusCodes.UNAUTHORIZED, result.getStatusLine().getStatusCode());
    Header[] values = result.getHeaders(WWW_AUTHENTICATE.toString());
    String value = getAuthHeader(DIGEST, values);

    Map<DigestWWWAuthenticateToken, String> parsedHeader = DigestWWWAuthenticateToken
            .parseHeader(value.substring(7));
    assertEquals(REALM_NAME, parsedHeader.get(DigestWWWAuthenticateToken.REALM));
    assertEquals(DigestAlgorithm.MD5.getToken(), parsedHeader.get(DigestWWWAuthenticateToken.ALGORITHM));
    assertEquals(DigestQop.AUTH.getToken(), parsedHeader.get(DigestWWWAuthenticateToken.MESSAGE_QOP));

    String clientNonce = createNonce();
    int nonceCount = 1;
    String nonce = parsedHeader.get(DigestWWWAuthenticateToken.NONCE);
    String opaque = parsedHeader.get(DigestWWWAuthenticateToken.OPAQUE);
    assertNotNull(opaque);/*from w  w  w  . j a v  a2 s  .  c  o  m*/
    // Send 5 requests with an incrementing nonce count on each call.
    for (int i = 0; i < 5; i++) {
        client = new TestHttpClient();
        get = new HttpGet(DefaultServer.getDefaultServerURL());

        int thisNonceCount = nonceCount++;
        String authorization = createAuthorizationLine("userOne", "passwordOne", "GET", "/", nonce,
                thisNonceCount, clientNonce, opaque);

        get.addHeader(AUTHORIZATION.toString(), authorization);
        result = client.execute(get);
        assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());

        values = result.getHeaders("ProcessedBy");
        assertEquals(1, values.length);
        assertEquals("ResponseHandler", values[0].getValue());
        assertSingleNotificationType(EventType.AUTHENTICATED);

        values = result.getHeaders("Authentication-Info");
        assertEquals(1, values.length);
        Map<AuthenticationInfoToken, String> parsedAuthInfo = AuthenticationInfoToken
                .parseHeader(values[0].getValue());

        assertEquals("Didn't expect a new nonce.", nonce,
                parsedAuthInfo.get(AuthenticationInfoToken.NEXT_NONCE));
        assertEquals(DigestQop.AUTH.getToken(), parsedAuthInfo.get(AuthenticationInfoToken.MESSAGE_QOP));
        String nonceCountString = toHex(thisNonceCount);
        assertEquals(
                createRspAuth("userOne", REALM_NAME, "passwordOne", "/", nonce, nonceCountString, clientNonce),
                parsedAuthInfo.get(AuthenticationInfoToken.RESPONSE_AUTH));
        assertEquals(clientNonce, parsedAuthInfo.get(AuthenticationInfoToken.CNONCE));
        assertEquals(nonceCountString, parsedAuthInfo.get(AuthenticationInfoToken.NONCE_COUNT));
    }
}

From source file:com.ppshein.PlanetMyanmarDictionary.common.java

public static String checkBookmark(String notedword, Context context) {
    String returnString = "nofade";
    try {//w  w w . j a  v  a  2  s .co m

        DatabaseUtil dbUtil = new DatabaseUtil(context);

        dbUtil.open();
        Cursor cursor = dbUtil.fetchBookmark(notedword);
        String getBookmark = cursor.getString(1);
        cursor.close();
        dbUtil.close();
        if (getBookmark.toString() != "") {
            returnString = "fade";
        }
    } catch (Exception e) {
        returnString = "nofade";
    }

    return returnString;
}

From source file:io.undertow.server.security.DigestAuthenticationAuthTestCase.java

static void _testNonceCountReUse() throws Exception {
    TestHttpClient client = new TestHttpClient();
    HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL());
    HttpResponse result = client.execute(get);
    assertEquals(StatusCodes.UNAUTHORIZED, result.getStatusLine().getStatusCode());
    Header[] values = result.getHeaders(WWW_AUTHENTICATE.toString());

    String value = getAuthHeader(DIGEST, values);

    Map<DigestWWWAuthenticateToken, String> parsedHeader = DigestWWWAuthenticateToken
            .parseHeader(value.substring(7));
    assertEquals(REALM_NAME, parsedHeader.get(DigestWWWAuthenticateToken.REALM));
    assertEquals(DigestAlgorithm.MD5.getToken(), parsedHeader.get(DigestWWWAuthenticateToken.ALGORITHM));
    assertEquals(DigestQop.AUTH.getToken(), parsedHeader.get(DigestWWWAuthenticateToken.MESSAGE_QOP));

    String clientNonce = createNonce();
    int nonceCount = 1;
    String nonce = parsedHeader.get(DigestWWWAuthenticateToken.NONCE);
    String opaque = parsedHeader.get(DigestWWWAuthenticateToken.OPAQUE);
    assertNotNull(opaque);//from  w w w  . ja  va 2 s . co  m
    // Send 5 requests with an incrementing nonce count on each call.
    for (int i = 0; i < 2; i++) {
        client = new TestHttpClient();
        get = new HttpGet(DefaultServer.getDefaultServerURL());

        int thisNonceCount = nonceCount; // Note - No increment
        String authorization = createAuthorizationLine("userOne", "passwordOne", "GET", "/", nonce,
                thisNonceCount, clientNonce, opaque);

        get.addHeader(AUTHORIZATION.toString(), authorization);
        result = client.execute(get);

        if (i == 0) {
            assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
            assertSingleNotificationType(EventType.AUTHENTICATED);

            values = result.getHeaders("ProcessedBy");
            assertEquals(1, values.length);
            assertEquals("ResponseHandler", values[0].getValue());

            values = result.getHeaders("Authentication-Info");
            assertEquals(1, values.length);
            Map<AuthenticationInfoToken, String> parsedAuthInfo = AuthenticationInfoToken
                    .parseHeader(values[0].getValue());

            assertEquals("Didn't expect a new nonce.", nonce,
                    parsedAuthInfo.get(AuthenticationInfoToken.NEXT_NONCE));
            assertEquals(DigestQop.AUTH.getToken(), parsedAuthInfo.get(AuthenticationInfoToken.MESSAGE_QOP));
            String nonceCountString = toHex(thisNonceCount);
            assertEquals(createRspAuth("userOne", REALM_NAME, "passwordOne", "/", nonce, nonceCountString,
                    clientNonce), parsedAuthInfo.get(AuthenticationInfoToken.RESPONSE_AUTH));
            assertEquals(clientNonce, parsedAuthInfo.get(AuthenticationInfoToken.CNONCE));
            assertEquals(nonceCountString, parsedAuthInfo.get(AuthenticationInfoToken.NONCE_COUNT));
        } else {
            assertEquals(StatusCodes.UNAUTHORIZED, result.getStatusLine().getStatusCode());
        }
    }
}

From source file:com.ppshein.PlanetMyanmarDictionary.common.java

public static String ProcessBookmark(String notedword, Context context) {
    String returnString = "nofade";
    try {/*from w w w .j  a  v a2 s  .  c o  m*/

        DatabaseUtil dbUtil = new DatabaseUtil(context);

        dbUtil.open();
        Cursor cursor = dbUtil.fetchBookmark(notedword);
        String getBookmark = cursor.getString(1);
        cursor.close();
        dbUtil.close();
        if (getBookmark.toString() != "") {
            dbUtil.open();
            boolean IsDeleted = dbUtil.deleteBookmark(notedword);
            Log.v("Bookmarks", "Bookmark is deleted " + IsDeleted);
            dbUtil.close();
            returnString = "nofade";
        }
    } catch (Exception e) {
        addBookmark(notedword, context);
        returnString = "fade";
    }
    return returnString;
}

From source file:com.fufang.httprequest.HttpPostBuild.java

public static String postBuildJson(String url, String params)
        throws UnsupportedEncodingException, ClientProtocolException, IOException {

    CloseableHttpClient httpClient = HttpClients.createDefault();
    String postResult = null;/*  w  ww  .java  2 s . c  om*/

    HttpPost httpPost = new HttpPost(url);
    System.out.println(" request " + httpPost.getRequestLine());

    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000)
            .build();
    httpPost.setConfig(requestConfig);
    StringEntity entity = new StringEntity(params.toString(), "UTF-8");
    entity.setContentType("application/json");
    httpPost.setEntity(entity);

    try {
        HttpResponse response = httpClient.execute(httpPost);
        int status = response.getStatusLine().getStatusCode();
        if (status >= 200 && status < 300) {
            HttpEntity responseEntity = response.getEntity();
            postResult = EntityUtils.toString(responseEntity);
        } else {
            System.out.println("unexpected response status - " + status);
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return postResult;
}

From source file:com.github.DroidPHP.ServerUtils.java

/**
 * This Method is not in use any more because its causing bug after end of
 * iteration//from w w  w. j a  va  2s. c  o  m
 * 
 * @see mySQLShell().ShellAsync()
 * @return
 * @throws IOException
 */

public static String readExecutedSQLShellCMD() throws IOException {
    /*
     * Returns an input stream that is connected to the standard output
     * stream (stdout) of the native process represented by this object
     */
    java.io.BufferedReader buffr = new java.io.BufferedReader(new java.io.InputStreamReader(stdout));
    String sb = new String();
    try {
        while (true) {
            String READ = buffr.readLine();

            if (READ == null) {
                break;
            }
            sb += READ + "\n";

        }

        Log.e(TAG, "Result = " + sb.toString());
    } catch (IOException e) {

        stdout.close();
        Log.e(TAG, "Unable to read mysql stream", e);

    }

    return sb.toString();

}

From source file:info.staticfree.android.units.UnitUsageDBHelper.java

/**
 * @param otherEntry/*ww  w .  j a  va  2  s.c o m*/
 * @return
 */
private synchronized static String[] getConformingSelectionArgs(TextView otherEntry) {
    final String otherEntryText = otherEntry.getText().toString();
    if (otherEntryText.length() > 0) {
        if (otherEntryText.toString().equals(cachedEntryText)) {
            return cachedEntryFprintArgs;
        }
        try {
            final String[] conformingSelectionArgs = {
                    ValueGui.getFingerprint(ValueGui.fromUnicodeString(ValueGui.closeParens(otherEntryText))) };
            cachedEntryText = otherEntryText;
            cachedEntryFprintArgs = conformingSelectionArgs;
            return conformingSelectionArgs;
        } catch (final EvalError e) {
            return null;
        }
    }
    return null;
}

From source file:org.dkpro.similarity.experiments.rte.util.Evaluator.java

public static void runClassifierCV(WekaClassifier wekaClassifier, Dataset dataset) throws Exception {
    // Set parameters
    int folds = 10;
    Classifier baseClassifier = ClassifierSimilarityMeasure.getClassifier(wekaClassifier);

    // Set up the random number generator
    long seed = new Date().getTime();
    Random random = new Random(seed);

    // Add IDs to the instances
    AddID.main(new String[] { "-i", MODELS_DIR + "/" + dataset.toString() + ".arff", "-o",
            MODELS_DIR + "/" + dataset.toString() + "-plusIDs.arff" });
    Instances data = DataSource.read(MODELS_DIR + "/" + dataset.toString() + "-plusIDs.arff");
    data.setClassIndex(data.numAttributes() - 1);

    // Instantiate the Remove filter
    Remove removeIDFilter = new Remove();
    removeIDFilter.setAttributeIndices("first");

    // Randomize the data
    data.randomize(random);//from w w w .  j  a v a 2 s .com

    // Perform cross-validation
    Instances predictedData = null;
    Evaluation eval = new Evaluation(data);

    for (int n = 0; n < folds; n++) {
        Instances train = data.trainCV(folds, n, random);
        Instances test = data.testCV(folds, n);

        // Apply log filter
        //          Filter logFilter = new LogFilter();
        //           logFilter.setInputFormat(train);
        //           train = Filter.useFilter(train, logFilter);        
        //           logFilter.setInputFormat(test);
        //           test = Filter.useFilter(test, logFilter);

        // Copy the classifier
        Classifier classifier = AbstractClassifier.makeCopy(baseClassifier);

        // Instantiate the FilteredClassifier
        FilteredClassifier filteredClassifier = new FilteredClassifier();
        filteredClassifier.setFilter(removeIDFilter);
        filteredClassifier.setClassifier(classifier);

        // Build the classifier
        filteredClassifier.buildClassifier(train);

        // Evaluate
        eval.evaluateModel(filteredClassifier, test);

        // Add predictions
        AddClassification filter = new AddClassification();
        filter.setClassifier(classifier);
        filter.setOutputClassification(true);
        filter.setOutputDistribution(false);
        filter.setOutputErrorFlag(true);
        filter.setInputFormat(train);
        Filter.useFilter(train, filter); // trains the classifier

        Instances pred = Filter.useFilter(test, filter); // performs predictions on test set
        if (predictedData == null)
            predictedData = new Instances(pred, 0);
        for (int j = 0; j < pred.numInstances(); j++)
            predictedData.add(pred.instance(j));
    }

    System.out.println(eval.toSummaryString());
    System.out.println(eval.toMatrixString());

    // Prepare output scores
    String[] scores = new String[predictedData.numInstances()];

    for (Instance predInst : predictedData) {
        int id = new Double(predInst.value(predInst.attribute(0))).intValue() - 1;

        int valueIdx = predictedData.numAttributes() - 2;

        String value = predInst.stringValue(predInst.attribute(valueIdx));

        scores[id] = value;
    }

    // Output classifications
    StringBuilder sb = new StringBuilder();
    for (String score : scores)
        sb.append(score.toString() + LF);

    FileUtils.writeStringToFile(new File(OUTPUT_DIR + "/" + dataset.toString() + "/" + wekaClassifier.toString()
            + "/" + dataset.toString() + ".csv"), sb.toString());

    // Output prediction arff
    DataSink.write(OUTPUT_DIR + "/" + dataset.toString() + "/" + wekaClassifier.toString() + "/"
            + dataset.toString() + ".predicted.arff", predictedData);

    // Output meta information
    sb = new StringBuilder();
    sb.append(baseClassifier.toString() + LF);
    sb.append(eval.toSummaryString() + LF);
    sb.append(eval.toMatrixString() + LF);

    FileUtils.writeStringToFile(new File(OUTPUT_DIR + "/" + dataset.toString() + "/" + wekaClassifier.toString()
            + "/" + dataset.toString() + ".meta.txt"), sb.toString());
}

From source file:com.zimbra.cs.servlet.ZimbraServlet.java

public static void proxyServletRequest(HttpServletRequest req, HttpServletResponse resp, Server server,
        String uri, AuthToken authToken) throws IOException, ServiceException {
    if (server == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "cannot find remote server");
        return;// ww  w  . j  a v a  2 s .  c om
    }
    HttpMethod method;
    String url = getProxyUrl(req, server, uri);
    mLog.debug("Proxy URL = %s", url);
    if (req.getMethod().equalsIgnoreCase("GET")) {
        method = new GetMethod(url.toString());
    } else if (req.getMethod().equalsIgnoreCase("POST") || req.getMethod().equalsIgnoreCase("PUT")) {
        PostMethod post = new PostMethod(url.toString());
        post.setRequestEntity(new InputStreamRequestEntity(req.getInputStream()));
        method = post;
    } else {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "cannot proxy method: " + req.getMethod());
        return;
    }
    HttpState state = new HttpState();
    String hostname = method.getURI().getHost();
    if (authToken != null) {
        authToken.encode(state, false, hostname);
    }
    try {
        proxyServletRequest(req, resp, method, state);
    } finally {
        method.releaseConnection();
    }
}

From source file:nz.net.catalyst.MaharaDroid.upload.http.RestClient.java

public static JSONObject CallFunction(String url, String[] paramNames, String[] paramVals, Context context) {
    JSONObject json = new JSONObject();

    SchemeRegistry supportedSchemes = new SchemeRegistry();

    SSLSocketFactory sf = getSocketFactory(DEBUG);

    // TODO we make assumptions about ports.
    supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    supportedSchemes.register(new Scheme("https", sf, 443));

    HttpParams http_params = new BasicHttpParams();
    ClientConnectionManager ccm = new ThreadSafeClientConnManager(http_params, supportedSchemes);

    // HttpParams http_params = httpclient.getParams();
    http_params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpConnectionParams.setConnectionTimeout(http_params, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(http_params, CONNECTION_TIMEOUT);

    DefaultHttpClient httpclient = new DefaultHttpClient(ccm, http_params);

    if (paramNames == null) {
        paramNames = new String[0];
    }/*from w w w.ja  va2 s  .  c o  m*/
    if (paramVals == null) {
        paramVals = new String[0];
    }

    if (paramNames.length != paramVals.length) {
        Log.w(TAG, "Incompatible number of param names and values, bailing on upload!");
        return null;
    }

    SortedMap<String, String> sig_params = new TreeMap<String, String>();

    HttpResponse response = null;
    HttpPost httppost = null;
    Log.d(TAG, "HTTP POST URL: " + url);
    try {
        httppost = new HttpPost(url);
    } catch (IllegalArgumentException e) {
        try {
            json.put("fail", e.getMessage());
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return json;
    }

    try {
        File file = null;
        // If this is a POST call, then it is a file upload. Check to see if
        // a
        // filename is given, and if so, open that file.
        // Get the title of the photo being uploaded so we can pass it into
        // the
        // MultipartEntityMonitored class to be broadcast for progress
        // updates.
        String title = "";
        for (int i = 0; i < paramNames.length; ++i) {
            if (paramNames[i].equals("title")) {
                title = paramVals[i];
            } else if (paramNames[i].equals("filename")) {
                file = new File(paramVals[i]);
                continue;
            }
            sig_params.put(paramNames[i], paramVals[i]);
        }

        MultipartEntityMonitored mp_entity = new MultipartEntityMonitored(context, title);
        if (file != null) {
            mp_entity.addPart("userfile", new FileBody(file));
        }
        for (Map.Entry<String, String> entry : sig_params.entrySet()) {
            mp_entity.addPart(entry.getKey(), new StringBody(entry.getValue()));
        }
        httppost.setEntity(mp_entity);

        response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {
            String content = convertStreamToString(resEntity.getContent());
            if (response.getStatusLine().getStatusCode() == 200) {
                try {
                    json = new JSONObject(content.toString());
                } catch (JSONException e1) {
                    Log.w(TAG, "Response 200 received but invalid JSON.");
                    json.put("fail", e1.getMessage());
                    if (DEBUG)
                        Log.d(TAG, "HTTP POST returned status code: " + response.getStatusLine());
                }
            } else {
                Log.w(TAG, "File upload failed with response code:" + response.getStatusLine().getStatusCode());
                json.put("fail", response.getStatusLine().getReasonPhrase());
                if (DEBUG)
                    Log.d(TAG, "HTTP POST returned status code: " + response.getStatusLine());
            }
        } else {
            Log.w(TAG, "Response does not contain a valid HTTP entity.");
            if (DEBUG)
                Log.d(TAG, "HTTP POST returned status code: " + response.getStatusLine());
        }

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        try {
            json.put("fail", e.getMessage());
        } catch (JSONException e1) {
        }
        e.printStackTrace();
    } catch (IllegalStateException e) {
        try {
            json.put("fail", e.getMessage());
        } catch (JSONException e1) {
        }
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        try {
            json.put("fail", e.getMessage());
        } catch (JSONException e1) {
        }
        e.printStackTrace();
    } catch (JSONException e) {
    }

    httpclient.getConnectionManager().shutdown();

    return json;

}