Example usage for java.lang CharSequence toString

List of usage examples for java.lang CharSequence toString

Introduction

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

Prototype

public String toString();

Source Link

Document

Returns a string containing the characters in this sequence in the same order as this sequence.

Usage

From source file:Grep.java

/**
 * Use the linePattern to break the given CharBuffer into lines, applying the
 * input pattern to each line to see if we have a match
 *///from   ww w.j  ava2s .  c om
private static List grep() {
    List matches = new ArrayList();
    Matcher lm = linePattern.matcher(indexFile); // Line matcher
    Matcher pm = null; // Pattern matcher
    int lines = 0;
    while (lm.find()) {
        lines++;
        CharSequence cs = lm.group(); // The current line
        if (pm == null)
            pm = pattern.matcher(cs);
        else
            pm.reset(cs);
        if (pm.find()) {
            matches.add(cs.toString());
        }
        if (lm.end() == indexFile.limit())
            break;
    }
    return matches;
}

From source file:com.aoyetech.fee.commons.utils.FileUtils.java

/**
 * ,?./*from  w w w  .j  a va  2  s  .c om*/
 * 
 * @param file
 * @param data
 * @param encoding
 * @param append
 * @throws IOException
 */
public static void write(final File file, final CharSequence data, final Charset encoding, final boolean append)
        throws IOException {
    final String str = data == null ? null : data.toString();
    writeStringToFile(file, str, encoding, append);
}

From source file:com.datamountaineer.streamreactor.connect.json.SimpleJsonConverter.java

/**
 * Convert this object, in the org.apache.kafka.connect.data format, into a JSON object, returning both the schema
 * and the converted object./* w  w w  .j a v a 2  s  . com*/
 */
private static JsonNode convertToJson(Schema schema, Object logicalValue) {
    if (logicalValue == null) {
        if (schema == null) // Any schema is valid and we don't have a default, so treat this as an optional schema
            return null;
        if (schema.defaultValue() != null)
            return convertToJson(schema, schema.defaultValue());
        if (schema.isOptional())
            return JsonNodeFactory.instance.nullNode();
        throw new DataException(
                "Conversion error: null value for field that is required and has no default value");
    }

    Object value = logicalValue;
    try {
        final Schema.Type schemaType;
        if (schema == null) {
            schemaType = ConnectSchema.schemaType(value.getClass());
            if (schemaType == null)
                throw new DataException(
                        "Java class " + value.getClass() + " does not have corresponding schema type.");
        } else {
            schemaType = schema.type();
        }
        switch (schemaType) {
        case INT8:
            return JsonNodeFactory.instance.numberNode((Byte) value);
        case INT16:
            return JsonNodeFactory.instance.numberNode((Short) value);
        case INT32:
            if (schema != null && Date.LOGICAL_NAME.equals(schema.name())) {
                return JsonNodeFactory.instance.textNode(ISO_DATE_FORMAT.format((java.util.Date) value));
            }
            if (schema != null && Time.LOGICAL_NAME.equals(schema.name())) {
                return JsonNodeFactory.instance.textNode(TIME_FORMAT.format((java.util.Date) value));
            }
            return JsonNodeFactory.instance.numberNode((Integer) value);
        case INT64:
            String schemaName = schema.name();
            if (Timestamp.LOGICAL_NAME.equals(schemaName)) {
                return JsonNodeFactory.instance
                        .numberNode(Timestamp.fromLogical(schema, (java.util.Date) value));
            }
            return JsonNodeFactory.instance.numberNode((Long) value);
        case FLOAT32:
            return JsonNodeFactory.instance.numberNode((Float) value);
        case FLOAT64:
            return JsonNodeFactory.instance.numberNode((Double) value);
        case BOOLEAN:
            return JsonNodeFactory.instance.booleanNode((Boolean) value);
        case STRING:
            CharSequence charSeq = (CharSequence) value;
            return JsonNodeFactory.instance.textNode(charSeq.toString());
        case BYTES:
            if (Decimal.LOGICAL_NAME.equals(schema.name())) {
                return JsonNodeFactory.instance.numberNode((BigDecimal) value);
            }

            byte[] valueArr = null;
            if (value instanceof byte[])
                valueArr = (byte[]) value;
            else if (value instanceof ByteBuffer)
                valueArr = ((ByteBuffer) value).array();

            if (valueArr == null)
                throw new DataException("Invalid type for bytes type: " + value.getClass());

            return JsonNodeFactory.instance.binaryNode(valueArr);

        case ARRAY: {
            Collection collection = (Collection) value;
            ArrayNode list = JsonNodeFactory.instance.arrayNode();
            for (Object elem : collection) {
                Schema valueSchema = schema == null ? null : schema.valueSchema();
                JsonNode fieldValue = convertToJson(valueSchema, elem);
                list.add(fieldValue);
            }
            return list;
        }
        case MAP: {
            Map<?, ?> map = (Map<?, ?>) value;
            // If true, using string keys and JSON object; if false, using non-string keys and Array-encoding
            boolean objectMode;
            if (schema == null) {
                objectMode = true;
                for (Map.Entry<?, ?> entry : map.entrySet()) {
                    if (!(entry.getKey() instanceof String)) {
                        objectMode = false;
                        break;
                    }
                }
            } else {
                objectMode = schema.keySchema().type() == Schema.Type.STRING;
            }
            ObjectNode obj = null;
            ArrayNode list = null;
            if (objectMode)
                obj = JsonNodeFactory.instance.objectNode();
            else
                list = JsonNodeFactory.instance.arrayNode();
            for (Map.Entry<?, ?> entry : map.entrySet()) {
                Schema keySchema = schema == null ? null : schema.keySchema();
                Schema valueSchema = schema == null ? null : schema.valueSchema();
                JsonNode mapKey = convertToJson(keySchema, entry.getKey());
                JsonNode mapValue = convertToJson(valueSchema, entry.getValue());

                if (objectMode)
                    obj.set(mapKey.asText(), mapValue);
                else
                    list.add(JsonNodeFactory.instance.arrayNode().add(mapKey).add(mapValue));
            }
            return objectMode ? obj : list;
        }
        case STRUCT: {
            Struct struct = (Struct) value;
            if (struct.schema() != schema)
                throw new DataException("Mismatching schema.");
            ObjectNode obj = JsonNodeFactory.instance.objectNode();
            for (Field field : schema.fields()) {
                obj.set(field.name(), convertToJson(field.schema(), struct.get(field)));
            }
            return obj;
        }
        }

        throw new DataException("Couldn't convert " + value + " to JSON.");
    } catch (ClassCastException e) {
        throw new DataException("Invalid type for " + schema.type() + ": " + value.getClass());
    }
}

From source file:io.syndesis.rest.v1.state.ClientSideState.java

static byte[] mac(final String authenticationAlgorithm, final CharSequence base,
        final SecretKey authenticationKey) {
    try {//from  w ww.j a  va2  s . co  m
        final String baseString = base.toString();

        final Mac mac = Mac.getInstance(authenticationAlgorithm);
        mac.init(authenticationKey);

        // base contains only BASE64 characters and '|', so we use ASCII
        final byte[] raw = baseString.getBytes(StandardCharsets.US_ASCII);

        return mac.doFinal(raw);
    } catch (final GeneralSecurityException e) {
        throw new IllegalStateException("Unable to compute MAC of the given value", e);
    }
}

From source file:eu.edisonproject.training.execute.Main.java

private static void saveTerms2Avro(List<Term> terms, String out) {
    TermAvroSerializer ts = new TermAvroSerializer(out, Term.getClassSchema());
    List<CharSequence> empty = new ArrayList<>();
    empty.add("");
    //        Stemming stemer = new Stemming();
    String stopWordsPath = System.getProperty("stop.words.file");

    if (stopWordsPath == null) {
        stopWordsPath = prop.getProperty("stop.words.file",
                ".." + File.separator + "etc" + File.separator + "stopwords.csv");
    }//from  www  .  ja v  a 2  s. c  o m

    CharArraySet stopwordsCharArray = new CharArraySet(ConfigHelper.loadStopWords(stopWordsPath), true);
    StopWord tokenizer = new StopWord(stopwordsCharArray);
    StanfordLemmatizer lematizer = new StanfordLemmatizer();

    for (Term t : terms) {
        List<CharSequence> nuid = t.getNuids();
        if (nuid == null || nuid.isEmpty() || nuid.contains(null)) {
            t.setNuids(empty);
        }

        List<CharSequence> buids = t.getBuids();
        if (buids == null || buids.isEmpty() || buids.contains(null)) {
            t.setBuids(empty);
        }
        List<CharSequence> alt = t.getAltLables();
        if (alt == null || alt.isEmpty() || alt.contains(null)) {
            t.setAltLables(empty);
        }
        List<CharSequence> gl = t.getGlosses();
        if (gl == null || gl.isEmpty() || gl.contains(null)) {
            ArrayList<CharSequence> lem = new ArrayList<>();
            lem.add(t.lemma);
            t.setGlosses(lem);
        } else {
            StringBuilder glosses = new StringBuilder();
            for (CharSequence n : gl) {
                glosses.append(n).append(" ");
            }
            glosses.append(t.lemma.toString().replaceAll("_", " "));
            if (alt != null && !alt.isEmpty() && !alt.contains(null)) {
                for (CharSequence c : alt) {
                    glosses.append(c.toString().replaceAll("_", " ")).append(" ");
                }
            }
            gl = new ArrayList<>();
            tokenizer.setDescription(glosses.toString());
            String cleanText = tokenizer.execute();
            lematizer.setDescription(cleanText);
            String lematizedText = lematizer.execute();

            gl.add(lematizedText);
            t.setGlosses(gl);

        }
        List<CharSequence> cat = t.getCategories();
        if (cat == null || cat.contains(null)) {
            t.setCategories(empty);
        }
        ts.serialize(t);
    }
    ts.close();

}

From source file:org.archive.crawler.util.BdbUriUniqFilter.java

/**
 * Create fingerprint.//from   w ww .j  a  v  a 2s  .com
 * Pubic access so test code can access createKey.
 * @param uri URI to fingerprint.
 * @return Fingerprint of passed <code>url</code>.
 */
public static long createKey(CharSequence uri) {
    String url = uri.toString();
    long schemeAuthorityKeyPart = calcSchemeAuthorityKeyBytes(url);
    return schemeAuthorityKeyPart | (FPGenerator.std40.fp(url) >>> 24);
}

From source file:fr.landel.utils.assertor.helper.HelperMessage.java

/**
 * Gets the message (the locale can be change through <code>setLocale</code>
 * ). Supports injecting parameters in message by using %s* or %1$s*
 * //from   w  ww .j  av a  2 s .co m
 * @param defaultString
 *            The default message provided by each method
 * @param locale
 *            The message locale
 * @param message
 *            The user message
 * @param parameters
 *            The method parameters
 * @param arguments
 *            The user arguments
 * @return The formatted message
 */
public static String getMessage(final CharSequence defaultString, final Locale locale,
        final CharSequence message, final List<ParameterAssertor<?>> parameters, final Object[] arguments) {

    String msg;

    if (StringUtils.isNotEmpty(message)) {
        if (message.toString().indexOf(PREFIX) > -1) {
            Object[] params = HelperMessage.convertParams(parameters);
            Object[] args = ObjectUtils.defaultIfNull(arguments, EMPTY_ARRAY);

            msg = StringUtils.prepareFormat(message, params.length, 1, args.length, 1).toString();

            if (msg.indexOf(PERCENT) > -1) {
                msg = String.format(Assertor.getLocale(locale), msg, ArrayUtils.addAll(params, args));
            }
        } else {
            msg = message.toString();
        }
    } else {
        msg = defaultString.toString();
    }
    return msg;
}

From source file:org.envirocar.app.util.Util.java

public static JSONObject readJsonContents(File f) throws IOException, JSONException {
    BufferedReader bufferedReader = new BufferedReader(new FileReader(f));

    CharSequence content = consumeBufferedReader(bufferedReader);

    JSONObject tou = new JSONObject(content.toString());
    return tou;//  w  w w .j  av  a  2s .  c o m
}

From source file:Main.java

public static boolean writeToFileAppend(@NonNull File file, @NonNull CharSequence text) {
    try {//w  w w  .  j  a v a2 s  .  co  m
        //noinspection ResultOfMethodCallIgnored
        file.createNewFile();
    } catch (IOException e) {
        Log.w(TAG, "Failed to create the file: file=" + file.getName());
        return false;
    }

    OutputStream os = null;
    InputStream is = null;
    try {
        os = new FileOutputStream(file, true);
        is = new ByteArrayInputStream(text.toString().getBytes("UTF-8"));

        int read;
        final byte[] buffer = new byte[1024];
        do {
            read = is.read(buffer, 0, buffer.length);
            if (read > 0)
                os.write(buffer, 0, read);
        } while (read > 0);
        return true;
    } catch (Exception e) {
        Log.w(TAG, "Failed to append to a file: file=" + file.getName());
        e.printStackTrace();
    } finally {
        // Try to close the stream.
        if (os != null)
            try {
                os.close();
            } catch (IOException e) {
                Log.e(TAG, "Failed to close the stream!");
                e.printStackTrace();
            }

        // Try to close the stream.
        if (is != null)
            try {
                is.close();
            } catch (IOException e) {
                Log.e(TAG, "Failed to close the stream!");
                e.printStackTrace();
            }
    }
    return false;
}

From source file:com.serendio.lingo3g.ProcessingResult.java

/**
 * Deserialize from an input stream of characters.
 *//*from   ww w.j  a v a  2s. c  om*/
public static ProcessingResult deserialize(CharSequence input) throws Exception {
    return new Persister().read(ProcessingResult.class, input.toString());
}