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:us.colloquy.util.ElasticLoader.java

public static void uploadLettersToElasticServer(Properties properties, List<Letter> letterList) {
    if (letterList.size() > 0) {
        try (RestHighLevelClient client = new RestHighLevelClient(RestClient
                .builder(new HttpHost("localhost", 9200, "http"), new HttpHost("localhost", 9201, "http")))) {

            BulkRequest request = new BulkRequest();

            ObjectMapper ow = new ObjectMapper(); // create once, reuse

            ow.enable(SerializationFeature.INDENT_OUTPUT);

            for (Letter letter : letterList) {
                try {
                    String json = ow.writerWithDefaultPrettyPrinter().writeValueAsString(letter);

                    String name = "unk";

                    if (letter.getTo().size() > 0) {
                        name = letter.getTo().get(0).getLastName();

                    }/*from  w  ww .  j a  va2 s . c  om*/

                    String id = letter.getId() + "-" + letter.getDate() + "-" + letter.getSource();

                    if (StringUtils.isNotEmpty(json)) {
                        IndexRequest indexRequest = new IndexRequest("lntolstoy-letters", "letters", id)
                                .source(json, XContentType.JSON);

                        request.add(new UpdateRequest("lntolstoy-letters", "letters", id)
                                .doc(json, XContentType.JSON).upsert(indexRequest));
                    } else {
                        System.out.println("empty doc: " + id.toString());
                    }

                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            }

            BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);

            if (bulkResponse.hasFailures())
            // process failures by iterating through each bulk response item
            {
                System.err.println(bulkResponse.buildFailureMessage());

                for (BulkItemResponse b : bulkResponse) {
                    System.out.println("Error inserting id: " + b.getId());
                    System.out.println("Failure message: " + b.getFailureMessage());
                }
            } else {
                System.out.println("Bulk indexing succeeded.");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        System.out.println("The list for bulk import is empty!");
    }
}

From source file:org.kie.smoke.wb.util.RestUtil.java

public static <T> T post(URL deploymentUrl, String relativeUrl, String mediaType, int status, String user,
        String password, double timeoutInSecs, Class<T>... responseTypes) {

    String uriStr = createBaseUriString(deploymentUrl, relativeUrl);

    ResponseHandler<T> rh = createResponseHandler(mediaType, status, responseTypes);

    // @formatter:off
    Request request = Request.Post(uriStr).addHeader(HttpHeaders.CONTENT_TYPE, mediaType.toString())
            .addHeader(HttpHeaders.ACCEPT, mediaType.toString())
            .addHeader(HttpHeaders.AUTHORIZATION, basicAuthenticationHeader(user, password));
    // @formatter:on

    Response resp = null;// ww w.  jav a  2s .  c o m
    long before = 0, after = 0;
    try {
        logOp("POST", uriStr);
        before = System.currentTimeMillis();
        resp = request.execute();
        after = System.currentTimeMillis();
    } catch (Exception e) {
        logAndFail("[GET] " + uriStr, e);
    }

    long duration = after - before;
    assertTrue("Timeout exceeded " + timeoutInSecs + " secs: " + ((double) duration / 1000d) + " secs",
            duration < timeoutInSecs * 1000);

    try {
        return resp.handleResponse(rh);
    } catch (Exception e) {
        logAndFail("Failed retrieving response from [GET] " + uriStr, e);
    }

    // never happens
    return null;
}

From source file:com.mirth.connect.client.ui.components.MirthTree.java

/**
 * Construct a variable for a specfic node.
 * //  w w w. j  a  v  a2  s .c  o  m
 * @param parent
 * @return
 */
public static String constructVariable(TreeNode parent) {
    String variable = "";

    MirthTreeNode node = (MirthTreeNode) parent;
    SerializationType serializationType = node.getSerializationType();

    // Get the parent if the leaf was actually passed in instead of the parent.
    if (node.isLeaf()) {
        node = (MirthTreeNode) node.getParent();
    }

    boolean wasArrayElement = false;

    // Stop the loop as soon as the parent or grandparent is null,
    // because we don't want to include the root node.
    while (node != null && node.getParent() != null) {
        String parentName = node.getValue();
        Pattern pattern = Pattern.compile(" (\\(.*\\))");
        Matcher matcher = pattern.matcher(parentName.toString());

        if (serializationType.equals(SerializationType.JSON) && node.isArrayElement()) {
            if (variable.length() != 0) {
                variable = "_" + variable;
            }
            variable = (node.getParent().getIndex(node) - 1) + variable; // JSON array
            wasArrayElement = true;
        } else {
            String parentIndex = "";
            if (serializationType.equals(SerializationType.XML)) {
                // Get the index of the parent about to be added.
                int parentIndexValue = MirthTree.getIndexOfNode(node);
                if (parentIndexValue != -1) {
                    parentIndex += parentIndexValue;
                }
            }

            // If something has already been added and last node processed wasn't an array element, then prepend it with an "_"
            if (variable.length() != 0 && !wasArrayElement) {
                variable = "_" + variable;
            }

            // Add either the vocab (if there is one) or the name.
            if (matcher.find()) {
                variable = removeInvalidVariableCharacters(matcher.group(1)) + parentIndex + variable;
            } else {
                variable = removeInvalidVariableCharacters(node.getValue().replaceAll(" \\(.*\\)", ""))
                        + parentIndex + variable;
            }

            wasArrayElement = false;
        }

        node = (MirthTreeNode) node.getParent();
    }

    return variable;
}

From source file:com.mirth.connect.client.ui.components.MirthTree.java

public static String constructNodeDescription(TreeNode parent) {
    String description = "";

    MirthTreeNode node = (MirthTreeNode) parent;
    SerializationType serializationType = node.getSerializationType();

    // Get the parent if the leaf was actually passed in instead of the parent.
    if (node.isLeaf()) {
        node = (MirthTreeNode) node.getParent();
    }//from  w w  w  .  j ava  2  s  .c om

    boolean wasArrayElement = false;
    // Stop the loop as soon as the parent or grandparent is null,
    // because we don't want to include the root node.
    while (node != null && node.getParent() != null) {
        String parentName = node.getValue();
        Pattern pattern = Pattern.compile(" (\\(.*\\))");
        Matcher matcher = pattern.matcher(parentName.toString());

        // Get the index of the parent about to be added.
        String parentIndex = "";
        if (serializationType.equals(SerializationType.JSON) && node.isArrayElement()) {
            // Prepend " - " to description if last node processed was not an array element.
            if (!wasArrayElement) {
                description = " - " + description;
            }
            description = " [" + (node.getParent().getIndex(node) - 1) + "]" + description; // JSON array
            wasArrayElement = true;
        } else {
            if (serializationType.equals(SerializationType.XML)) {
                int parentIndexValue = MirthTree.getIndexOfNode(node);
                if (parentIndexValue != -1) {
                    parentIndex = " [" + parentIndexValue + "]";
                }
            }

            // Add either the vocab (if there is one) or the name.
            if (matcher.find()) {
                String matchDescription = matcher.group(1);
                matchDescription = matchDescription.substring(1, matchDescription.length() - 1);
                // Also add the segment name for the last node if vocab was used.
                description = matchDescription + parentIndex
                        + (description.length() == 0 ? " (" + node.getValue().replaceAll(" \\(.*\\)", "") + ")"
                                : " - ")
                        + description;
            } else {
                description = node.getValue() + parentIndex
                        + (description.length() != 0 && !wasArrayElement ? " - " : "") + description;
            }

            wasArrayElement = false;
        }

        node = (MirthTreeNode) node.getParent();
    }

    return description;
}

From source file:org.kie.remote.tests.base.RestUtil.java

public static <T> T post(URL deploymentUrl, String relativeUrl, String mediaType, int status, String user,
        String password, double timeoutInSecs, Class<T>... responseTypes) {

    String uriStr = createBaseUriString(deploymentUrl, relativeUrl);

    ResponseHandler<T> rh = createResponseHandler(mediaType, status, responseTypes);

    // @formatter:off
    Request request = Request.Post(uriStr).addHeader(HttpHeaders.CONTENT_TYPE, mediaType.toString())
            .addHeader(HttpHeaders.ACCEPT, mediaType.toString())
            .addHeader(HttpHeaders.AUTHORIZATION, basicAuthenticationHeader(user, password));
    // @formatter:on

    Response resp = null;/*from  w w w  . ja  v  a2 s .  c om*/
    long before = 0, after = 0;
    try {
        logOp("POST", uriStr);
        before = System.currentTimeMillis();
        resp = request.execute();
        after = System.currentTimeMillis();
    } catch (Exception e) {
        failAndLog("[GET] " + uriStr, e);
    }

    long duration = after - before;
    assertTrue("Timeout exceeded " + timeoutInSecs + " secs: " + ((double) duration / 1000d) + " secs",
            duration < timeoutInSecs * 1000);

    try {
        return resp.handleResponse(rh);
    } catch (Exception e) {
        failAndLog("Failed retrieving response from [GET] " + uriStr, e);
    }

    // never happens
    return null;
}

From source file:com.example.heya.couchdb.ConnectionHandler.java

/**
 * Http POST//  ww  w.ja va2  s . c  o  m
 * 
 * @param create
 * @return
 * @throws IOException 
 * @throws ClientProtocolException 
 * @throws JSONException 
 * @throws SpikaException 
 * @throws IllegalStateException 
 * @throws SpikaForbiddenException 
 */
public static String postJsonObjectForString(String apiName, JSONObject create, String userId, String token)
        throws ClientProtocolException, IOException, JSONException, IllegalStateException, SpikaException,
        SpikaForbiddenException {

    InputStream is = httpPostRequest(CouchDB.getUrl() + apiName, create, userId);
    String result = getString(is);

    is.close();

    Logger.debug("Response: ", result.toString());
    return result;
}

From source file:edu.harvard.mcz.imagecapture.data.UnitTrayLabel.java

/** Factory method, given a JSON encoded string, as encoded with toJSONString(), extract the values from that
 * string into a new instance of UnitTrayLabel so that they can be obtained by the appropriate returner
 * interface (taxonnameReturner, drawernumberReturner, collectionReturner).
 * //w  w  w  . j  a va 2  s.c o m
 * @param jsonEncodedLabel the JSON to decode.
 * @return a new UnitTrayLabel populated with the values found in the supplied jsonEncodedLabel text or null on a failure.
 * @see toJSONString
 */
public static UnitTrayLabel createFromJSONString(String jsonEncodedLabel) {
    UnitTrayLabel result = null;
    if (jsonEncodedLabel.matches("\\{.*\\}")) {
        String originalJsonEncodedLabel = new String(jsonEncodedLabel.toString());
        jsonEncodedLabel = jsonEncodedLabel.replaceFirst("^\\{", ""); // Strip off leading  { 
        jsonEncodedLabel = jsonEncodedLabel.replaceFirst("\\}$", ""); // Strip off trailing } 
        if (jsonEncodedLabel.contains("}")) {
            // nested json, not expected.
            log.error("JSON for UnitTrayLabel contains unexpected nesting { { } }.  JSON is: "
                    + originalJsonEncodedLabel);
        } else {
            log.debug(jsonEncodedLabel);
            result = new UnitTrayLabel();
            // Beginning and end are special case for split on '", "'
            // remove leading quotes and spaces (e.g. either trailing '" ' or trailing '"').
            jsonEncodedLabel = jsonEncodedLabel.replaceFirst("^ ", ""); // Strip off leading space 
            jsonEncodedLabel = jsonEncodedLabel.replaceFirst(" $", ""); // Strip off trailing space
            jsonEncodedLabel = jsonEncodedLabel.replaceFirst("^\"", ""); // Strip off leading quote
            jsonEncodedLabel = jsonEncodedLabel.replaceFirst("\"$", ""); // Strip off trailing quote
            // Convert any ", " into "," then split on ","
            jsonEncodedLabel = jsonEncodedLabel.replaceAll("\",\\s\"", "\",\"");
            log.debug(jsonEncodedLabel);
            // split into key value parts by '","'
            String[] pairs = jsonEncodedLabel.split("\",\"");
            for (int x = 0; x < pairs.length; x++) {
                // split each key value pair
                String[] keyValuePair = pairs[x].split("\":\"");
                if (keyValuePair.length == 2) {
                    String key = keyValuePair[0];
                    String value = keyValuePair[1];
                    log.debug("key=[" + key + "], value=[" + value + "]");

                    if (key.equals("m1p")) {
                        log.debug("Configured for Project: " + value);
                        if (!value.equals("MCZ Lepidoptera") && !value.equals("ETHZ Entomology")
                                && !value.equals("[ETHZ Entomology]")) {
                            log.error("Project specified in JSON is not recognized: " + value);
                            log.error("Warning: Keys in JSON may not be correctly interpreted.");
                        }
                    }

                    // Note: Adding values here isn't sufficient to populate specimen records,
                    // you still need to invoke the relevant returner interface on the parser.
                    if (key.equals("f")) {
                        result.setFamily(value);
                    }
                    if (key.equals("b")) {
                        result.setSubfamily(value);
                    }
                    if (key.equals("t")) {
                        result.setTribe(value);
                    }
                    if (key.equals("g")) {
                        result.setGenus(value);
                    }
                    if (key.equals("s")) {
                        result.setSpecificEpithet(value);
                    }
                    if (key.equals("u")) {
                        result.setSubspecificEpithet(value);
                    }
                    if (key.equals("i")) {
                        result.setInfraspecificEpithet(value);
                    }
                    if (key.equals("r")) {
                        result.setInfraspecificRank(value);
                    }
                    if (key.equals("a")) {
                        result.setAuthorship(value);
                    }
                    if (key.equals("d")) {
                        result.setDrawerNumber(value);
                    }
                    if (key.equals("c")) {
                        result.setCollection(value);
                        log.debug(result.getCollection());
                    }
                    if (key.equals("id")) {
                        result.setIdentifiedBy(value);
                    }
                }
            }
            log.debug(result.toJSONString());
        }
    } else {
        log.debug("JSON not matched to { }");
    }
    return result;
}

From source file:com.me.edu.Servlet.ElasticSearch_Backup.java

public static String cleanStopWords(String inputText) {
    String[] stopwords = { "the", "-RRB-", "-LRB-", "a", "as", "able", "about", "WHEREAS", "above", "according",
            "accordingly", "across", "actually", "after", "afterwards", "again", "against", "aint", "all",
            "allow", "allows", "almost", "alone", "along", "already", "also", "although", "always", "am",
            "among", "amongst", "an", "and", "another", "any", "anybody", "anyhow", "anyone", "anything",
            "anyway", "anyways", "anywhere", "apart", "appear", "appreciate", "appropriate", "are", "arent",
            "around", "as", "aside", "ask", "asking", "associated", "at", "available", "away", "awfully", "be",
            "became", "because", "become", "becomes", "becoming", "been", "before", "beforehand", "behind",
            "being", "believe", "below", "beside", "besides", "best", "better", "between", "beyond", "both",
            "brief", "but", "by", "cmon", "cs", "came", "can", "cant", "cannot", "cant", "cause", "causes",
            "certain", "certainly", "changes", "clearly", "co", "com", "come", "comes", "concerning",
            "consequently", "consider", "considering", "contain", "containing", "contains", "corresponding",
            "could", "couldnt", "course", "currently", "definitely", "described", "despite", "did", "didnt",
            "different", "do", "does", "doesnt", "doing", "dont", "done", "down", "downwards", "during", "each",
            "edu", "eg", "eight", "either", "else", "elsewhere", "enough", "entirely", "especially", "et",
            "etc", "even", "ever", "every", "everybody", "everyone", "everything", "everywhere", "ex",
            "exactly", "example", "except", "far", "few", "ff", "fifth", "first", "five", "followed",
            "following", "follows", "for", "former", "formerly", "forth", "four", "from", "further",
            "furthermore", "get", "gets", "getting", "given", "gives", "go", "goes", "going", "gone", "got",
            "gotten", "greetings", "had", "hadnt", "happens", "hardly", "has", "hasnt", "have", "havent",
            "having", "he", "hes", "hello", "help", "hence", "her", "here", "heres", "hereafter", "hereby",
            "herein", "hereupon", "hers", "herself", "hi", "him", "himself", "his", "hither", "hopefully",
            "how", "howbeit", "however", "i", "id", "ill", "im", "ive", "ie", "if", "ignored", "immediate",
            "in", "inasmuch", "inc", "indeed", "indicate", "indicated", "indicates", "inner", "insofar",
            "instead", "into", "inward", "is", "isnt", "it", "itd", "itll", "its", "its", "itself", "just",
            "keep", "keeps", "kept", "know", "knows", "known", "last", "lately", "later", "latter", "latterly",
            "least", "less", "lest", "let", "lets", "like", "liked", "likely", "little", "look", "looking",
            "looks", "ltd", "mainly", "many", "may", "maybe", "me", "mean", "meanwhile", "merely", "might",
            "more", "moreover", "most", "mostly", "much", "must", "my", "myself", "name", "namely", "nd",
            "near", "nearly", "necessary", "need", "needs", "neither", "never", "nevertheless", "new", "next",
            "nine", "no", "nobody", "non", "none", "noone", "nor", "normally", "not", "nothing", "novel", "now",
            "nowhere", "obviously", "of", "off", "often", "oh", "ok", "okay", "old", "on", "once", "one",
            "ones", "only", "onto", "or", "other", "others", "otherwise", "ought", "our", "ours", "ourselves",
            "out", "outside", "over", "overall", "own", "particular", "particularly", "per", "perhaps",
            "placed", "please", "plus", "possible", "presumably", "probably", "provides", "que", "quite", "qv",
            "rather", "rd", "re", "really", "reasonably", "regarding", "regardless", "regards", "relatively",
            "respectively", "right", "said", "same", "saw", "say", "saying", "says", "second", "secondly",
            "see", "seeing", "seem", "seemed", "seeming", "seems", "seen", "self", "selves", "sensible", "sent",
            "serious", "seriously", "seven", "several", "shall", "she", "should", "shouldnt", "since", "six",
            "so", "some", "somebody", "somehow", "someone", "something", "sometime", "sometimes", "somewhat",
            "somewhere", "soon", "sorry", "specified", "specify", "specifying", "still", "sub", "such", "sup",
            "sure", "ts", "take", "taken", "tell", "tends", "th", "than", "thank", "thanks", "thanx", "that",
            "thats", "thats", "the", "their", "theirs", "them", "themselves", "then", "thence", "there",
            "theres", "thereafter", "thereby", "therefore", "therein", "theres", "thereupon", "these", "they",
            "theyd", "theyll", "theyre", "theyve", "think", "third", "this", "thorough", "thoroughly", "those",
            "though", "three", "through", "throughout", "thru", "thus", "to", "together", "too", "took",
            "toward", "towards", "tried", "tries", "truly", "try", "trying", "twice", "two", "un", "under",
            "unfortunately", "unless", "unlikely", "until", "unto", "up", "upon", "us", "use", "used", "useful",
            "uses", "using", "usually", "value", "various", "very", "via", "viz", "vs", "want", "wants", "was",
            "wasnt", "way", "we", "wed", "well", "were", "weve", "welcome", "well", "went", "were", "werent",
            "what", "whats", "whatever", "when", "whence", "whenever", "where", "wheres", "whereafter",
            "whereas", "whereby", "wherein", "whereupon", "wherever", "whether", "which", "while", "whither",
            "who", "whos", "whoever", "whole", "whom", "whose", "why", "will", "willing", "wish", "with",
            "within", "without", "wont", "wonder", "would", "would", "wouldnt", "yes", "yet", "you", "youd",
            "youll", "youre", "youve", "your", "yours", "yourself", "yourselves", "zero" };
    List<String> wordsList = new ArrayList<String>();
    //String tweet = "Feeling miserable with the cold? Here's WHAT you can do.";
    inputText = inputText.trim().replaceAll("\\s+", " ");
    System.out.println("After trim:  " + inputText);
    //Get all the words Tokenize rather than spliting
    String[] words = inputText.split(" ");
    for (String word : words) {
        wordsList.add(word);/*www .j  ava 2s .  c o  m*/
    }
    System.out.println("After for loop:  " + wordsList);
    //remove stop words here from the temp list
    for (int i = 0; i < wordsList.size(); i++) {
        // get the item as string
        for (int j = 0; j < stopwords.length; j++) {
            if (stopwords[j].contains(wordsList.get(i))
                    || stopwords[j].toUpperCase().contains(wordsList.get(i))) {
                wordsList.remove(i);
            }
        }
    }
    String cleanString = "";
    for (String str : wordsList) {
        System.out.print(str + " ");
        cleanString = cleanString.replaceAll(",", "");
        cleanString = cleanString + " " + str;
    }
    try {
        FileWriter file = new FileWriter("cleanDoc.txt");
        file.write(cleanString.toString());
        file.flush();
        file.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return cleanString;
}

From source file:com.appbackr.android.tracker.Tracker.java

/**
  * Generates a unique ID for the device.
  * /*from  ww w . ja v a2  s. c  o  m*/
  * This function obtain the Unique ID from the phone. The Unique ID consist of
  *    Build.BOARD + Build.BRAND + Build.CPU_ABI
  *    + Build.DEVICE + Build.DISPLAY + Build.FINGERPRINT + Build.HOST
  *    + Build.ID + Build.MANUFACTURER + Build.MODEL + Build.PRODUCT
  *    + Build.TAGS + Build.TYPE + Build.USER;
  *    + IMEI (GSM) or MEID/ESN (CDMA)
  *    + Android-assigned id
  * 
  * The Android ID may be changed everytime the user perform Factory Reset
  * I heard that IMEI values might not be unique because phone factory
  * might reuse IMEI values to cut cost.
  * 
  * While the ID might be different from the same device, but resetting of the
  * Android phone should not occur that often. The values should be close 
  * enough.
  *
  * @param c android application contact 
  * @return unique ID as md5 hash generated of available parameters from device and cell phone service provider
  */
 private static String getUDID(Context c) {

     // Get some of the hardware information
     String buildParams = Build.BOARD + Build.BRAND + Build.CPU_ABI + Build.DEVICE + Build.DISPLAY
             + Build.FINGERPRINT + Build.HOST + Build.ID + Build.MANUFACTURER + Build.MODEL + Build.PRODUCT
             + Build.TAGS + Build.TYPE + Build.USER;

     // Requires READ_PHONE_STATE
     TelephonyManager tm = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);

     // gets the imei (GSM) or MEID/ESN (CDMA)
     String imei = tm.getDeviceId();

     // gets the android-assigned id
     String androidId = Secure.getString(c.getContentResolver(), Secure.ANDROID_ID);

     // concatenate the string
     String fullHash = buildParams.toString() + imei + androidId;

     return md5(fullHash);
 }

From source file:com.wso2.mobile.mdm.utils.ServerUtilities.java

public static Map<String, String> sendWithTimeWait(String epPostFix, Map<String, String> params, String option,
        Context context) {//  ww  w .  j a v a2s.  com
    Map<String, String> response = null;
    Map<String, String> responseFinal = null;
    long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
    for (int i = 1; i <= MAX_ATTEMPTS; i++) {
        Log.d(TAG, "Attempt #" + i + " to register");
        try {
            //response = sendToServer(epPostFix, params, option, context);

            response = postData(context, epPostFix, params);
            if (response != null && !response.equals(null)) {
                responseFinal = response;
            }
            GCMRegistrar.setRegisteredOnServer(context, true);
            String message = context.getString(R.string.server_registered);
            Log.v("Check Reg Success", message.toString());

            return responseFinal;
        } catch (Exception e) {
            Log.e(TAG, "Failed to register on attempt " + i, e);
            if (i == MAX_ATTEMPTS) {
                break;
            }

            return responseFinal;
        }
    }
    String message = context.getString(R.string.server_register_error, MAX_ATTEMPTS);

    return responseFinal;
}