001/*
002 * (C) Copyright 2017 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     bdelbosc
018 */
019package org.nuxeo.lib.stream.tools.renderer;
020
021import static java.lang.Math.min;
022
023import java.io.UnsupportedEncodingException;
024import java.text.SimpleDateFormat;
025import java.util.Date;
026import java.util.function.Consumer;
027
028import org.nuxeo.lib.stream.computation.Record;
029import org.nuxeo.lib.stream.computation.Watermark;
030import org.nuxeo.lib.stream.log.LogRecord;
031
032/**
033 * @since 9.3
034 */
035public abstract class Renderer implements Consumer<LogRecord<Record>> {
036
037    public abstract void header();
038
039    public abstract void footer();
040
041    protected String watermarkString(long watermark) {
042        if (watermark == 0) {
043            return "0";
044        }
045        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
046        Watermark wm = Watermark.ofValue(watermark);
047        return String.format("%s:%d%s", dateFormat.format(new Date(wm.getTimestamp())), wm.getSequence(),
048                wm.isCompleted() ? " completed" : "");
049    }
050
051    protected String binaryString(byte[] data) {
052        String overview = "";
053        if (data != null) {
054            try {
055                overview += new String(data, "UTF-8").substring(0, min(data.length, 512));
056            } catch (UnsupportedEncodingException e) {
057                overview = "unsupported encoding";
058            }
059            overview = overview.replaceAll("[^\\x20-\\x7e]", ".");
060        }
061        return overview;
062    }
063}