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:org.ednovo.gooru.service.ResourceCassandraServiceImpl.java

public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {

    String jsonKey = "http://gdata.youtube.com/feeds/api/videos?q=" + url.substring(31, 42)
            + "&max-results=1&v=2&alt=jsonc";

    InputStream inputStream = (InputStream) new URL(jsonKey).openStream();
    try {//from  www .  j a va2s  . co  m
        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
        String jsonText = readAll(rd);
        JSONObject json = null;
        json = new JSONObject(jsonText.toString());
        return json;
    } finally {
        inputStream.close();
    }
}

From source file:edu.indiana.d2i.htrc.io.SparseVectorsToMemcached.java

private static Vector transform2Vector(String text, String field, Analyzer analyzer, HTRCFilter filter,
        Dictionary dictionary) throws IOException {
    Vector result = new RandomAccessSparseVector(dictionary.size());

    TokenStream stream = analyzer.reusableTokenStream(field, new StringReader(text.toString()));
    CharTermAttribute termAtt = stream.addAttribute(CharTermAttribute.class);
    stream.reset();/*from   w ww .j a  v  a  2s  . c  o  m*/
    while (stream.incrementToken()) {
        // String term = new String(termAtt.buffer(), 0,
        // termAtt.length());
        String term = new String(termAtt.buffer(), 0, termAtt.length()).toLowerCase();
        if (filter.accept(term, 0)) {
            int index = dictionary.get(term);
            result.setQuick(index, result.get(index) + 1);
        }
    }

    return result;
}

From source file:org.web4thejob.util.CoreUtil.java

public static String getCommandImage(CommandEnum id, String defaultImage) {
    String sb = "img/CMD_" + id.name() + ".png";
    return ContextUtil.resourceExists(sb.toString()) ? sb.toString() : defaultImage;
}

From source file:org.web4thejob.util.CoreUtil.java

public static String getCommandImage(CommandEnum id, String defaultImage, boolean dirty) {
    if (!dirty)//from  www .  j a  v a 2  s.  c  o m
        return getCommandImage(id, defaultImage);

    String sb = "img/CMD_" + id.name() + "_Dirty.png";
    return ContextUtil.resourceExists(sb.toString()) ? sb.toString() : defaultImage;
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.agent.KubernetesCacheDataConverter.java

static Map<String, Collection<String>> namespaceRelationship(String account, String namespace) {
    Map<String, Collection<String>> relationships = new HashMap<>();
    relationships.put(NAMESPACE.toString(),
            Collections.singletonList(Keys.infrastructure(NAMESPACE, account, namespace, namespace)));

    return relationships;
}

From source file:org.jboss.as.test.integration.web.sso.SSOTestBase.java

public static void executeFormLogin(HttpClient httpConn, URL warURL) throws IOException {
    // Submit the login form
    HttpPost formPost = new HttpPost(warURL + "j_security_check");
    formPost.addHeader("Referer", warURL + "login.html");

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("j_username", "user1"));
    formparams.add(new BasicNameValuePair("j_password", "password1"));
    formPost.setEntity(new UrlEncodedFormEntity(formparams, "UTF-8"));

    HttpResponse postResponse = httpConn.execute(formPost);

    int statusCode = postResponse.getStatusLine().getStatusCode();
    Header[] errorHeaders = postResponse.getHeaders("X-NoJException");
    assertTrue("Should see HTTP_MOVED_TEMP. Got " + statusCode,
            statusCode == HttpURLConnection.HTTP_MOVED_TEMP);
    assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);
    EntityUtils.consume(postResponse.getEntity());

    // Follow the redirect to the index.html page
    String indexURL = postResponse.getFirstHeader("Location").getValue();
    HttpGet rediretGet = new HttpGet(indexURL.toString());
    HttpResponse redirectResponse = httpConn.execute(rediretGet);

    statusCode = redirectResponse.getStatusLine().getStatusCode();
    errorHeaders = redirectResponse.getHeaders("X-NoJException");
    assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
    assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);

    String body = EntityUtils.toString(redirectResponse.getEntity());
    assertTrue("Get of " + indexURL + " redirected to login page", body.indexOf("j_security_check") < 0);
}

From source file:com.netsteadfast.greenstep.base.model.SqlGenerateUtil.java

public static Map<String, Object> getDeleteByPK(Object entityObject) throws Exception {
    String tableName = getTableName(entityObject);
    String pk = getPKname(entityObject);
    Object value = getPKvalue(entityObject);
    if ("".equals(tableName.trim()) || null == pk || "".equals(pk) || null == value) {
        throw new java.lang.IllegalArgumentException(NOT_ENTITY_BEAN);
    }//from  w  ww .j a  va  2 s.  c  om
    String sql = " delete from " + tableName + " where " + pk + "=?";
    Map<String, Object> queryMap = new HashMap<String, Object>();
    queryMap.put(RETURN_SQL, sql.toString());
    queryMap.put(RETURN_PARAMS, new Object[] { value });
    return queryMap;
}

From source file:com.oplay.nohelper.volley.toolbox.HttpHeaderParser.java

/**
 * Extracts a {@link Cache.Entry} from a {@link NetworkResponse}.
 *
 * @param response The network response to parse headers from
 * @return a cache entry for the given response, or null if the response is not cacheable.
 *//*from   w ww . ja va  2s  .co m*/
public static Cache.Entry parseCacheHeaders(NetworkResponse response) {
    long now = System.currentTimeMillis();

    Map<String, String> headers = response.headers;

    long serverDate = 0;

    String serverEtag = null;
    String headerValue;

    if (headers.containsKey("Data")) {
        headerValue = headers.get("Date");
        if (headerValue != null) {
            serverDate = parseDateAsEpoch(headerValue);
        }
    }

    if (headers.containsKey("ETag")) {
        serverEtag = headers.get("ETag");
        VolleyLog.d("Cache-Control", serverEtag.toString());
    }

    Cache.Entry entry = new Cache.Entry();
    entry.setKey(key);
    entry.data = response.data;
    entry.mEtag = serverEtag;
    entry.mServerDate = serverDate;
    entry.responseHeaders = headers;
    return entry;
}

From source file:com.example.dlp.RiskAnalysis.java

private static void calculateNumericalStats(String projectId, String datasetId, String tableId,
        String columnName) throws Exception {
    // [START dlp_numerical_stats_analysis]

    /**/*  w  ww  .  j  av a2s  . c om*/
     * Calculate numerical statistics for a column in a BigQuery table using the DLP API.
     * @param projectId The Google Cloud Platform project ID to run the API call under.
     * @param datasetId The BigQuery dataset to analyze.
     * @param tableId The BigQuery table to analyze.
     * @param columnName The name of the column to analyze, which must contain only numerical data.
     */

    // instantiate a client
    try (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {

        // projectId = process.env.GCLOUD_PROJECT;
        // datasetId = "my_dataset";
        // tableId = "my_table";
        // columnName = "firstName";

        FieldId fieldId = FieldId.newBuilder().setColumnName(columnName).build();

        NumericalStatsConfig numericalStatsConfig = NumericalStatsConfig.newBuilder().setField(fieldId).build();

        BigQueryTable bigQueryTable = BigQueryTable.newBuilder().setProjectId(projectId).setDatasetId(datasetId)
                .setTableId(tableId).build();

        PrivacyMetric privacyMetric = PrivacyMetric.newBuilder().setNumericalStatsConfig(numericalStatsConfig)
                .build();

        AnalyzeDataSourceRiskRequest request = AnalyzeDataSourceRiskRequest.newBuilder()
                .setPrivacyMetric(privacyMetric).setSourceTable(bigQueryTable).build();

        // asynchronously submit a risk analysis operation
        OperationFuture<RiskAnalysisOperationResult, RiskAnalysisOperationMetadata, Operation> responseFuture = dlpServiceClient
                .analyzeDataSourceRiskAsync(request);

        // ...
        // block on response
        RiskAnalysisOperationResult response = responseFuture.get();
        NumericalStatsResult results = response.getNumericalStatsResult();

        System.out.println("Value range: [" + results.getMaxValue() + ", " + results.getMinValue() + "]");

        // Print out unique quantiles
        String previousValue = "";
        for (int i = 0; i < results.getQuantileValuesCount(); i++) {
            Value valueObj = results.getQuantileValues(i);
            String value = valueObj.toString();

            if (!previousValue.equals(value)) {
                System.out.println("Value at " + i + "% quantile: " + value.toString());
                previousValue = value;
            }
        }
    } catch (Exception e) {
        System.out.println("Error in numericalStatsAnalysis: " + e.getMessage());
    }
    // [END dlp_numerical_stats_analysis]
}

From source file:com.ikanow.aleph2.data_model.utils.ProcessUtils.java

/**
 * Finds all a processes children, kills the process then recursively calls this on the children.
 * //  www  .j a  va2s.c  om
 * @param pid
 * @param kill_signal
 * @return
 * @throws IOException 
 */
private static boolean killProcessAndChildren(final String pid, final Optional<Integer> kill_signal)
        throws IOException {
    //first find any children via pgrep -P pid
    final ProcessBuilder pb_children = new ProcessBuilder("pgrep", "-P", pid.toString());
    final BufferedReader br = new BufferedReader(new InputStreamReader(pb_children.start().getInputStream()));
    final Set<String> child_pids = new HashSet<String>();
    String line;
    while ((line = br.readLine()) != null) {
        child_pids.add(line);
    }
    logger.debug("children of pid: " + pid + " are: " + child_pids.toString());
    //kill pid w/ signal
    killProcess(pid, kill_signal);

    //if still alive kill with -9, give it 5s to try and die the old way
    for (int i = 0; i < 5; i++) {
        try {
            Thread.sleep(1000L);
        } catch (Exception e) {
        }
        if (!isProcessRunning(pid)) {
            break;
        }
    }
    if (isProcessRunning(pid)) {
        killProcess(pid, Optional.of(9));
    }

    //call this on all children
    return !child_pids.stream().filter(child_pid -> {
        try {
            return killProcessAndChildren(child_pid, kill_signal);
        } catch (Exception ex) {
            return false;
        }
    }).anyMatch(result -> false);
}