Example usage for java.io Writer toString

List of usage examples for java.io Writer toString

Introduction

In this page you can find the example usage for java.io Writer toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.datavec.api.transform.ui.HtmlSequencePlotting.java

/**
 * Create a HTML file with plots for the given sequence.
 *
 * @param title    Title of the page//from w ww . j  a v a  2  s  . c o  m
 * @param schema   Schema for the data
 * @param sequence Sequence to plot
 * @return HTML file as a string
 */
public static String createHtmlSequencePlots(String title, Schema schema, List<List<Writable>> sequence)
        throws Exception {
    Configuration cfg = new Configuration(new Version(2, 3, 23));

    // Where do we load the templates from:
    cfg.setClassForTemplateLoading(HtmlSequencePlotting.class, "/templates/");

    // Some other recommended settings:
    cfg.setIncompatibleImprovements(new Version(2, 3, 23));
    cfg.setDefaultEncoding("UTF-8");
    cfg.setLocale(Locale.US);
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

    Map<String, Object> input = new HashMap<>();
    input.put("pagetitle", title);

    ObjectMapper ret = new ObjectMapper();
    ret.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    ret.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    ret.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
    ret.enable(SerializationFeature.INDENT_OUTPUT);

    List<DivObject> divs = new ArrayList<>();
    List<String> divNames = new ArrayList<>();

    //First: create table for schema
    int n = schema.numColumns();
    String[][] table = new String[n / 2 + n % 2][6]; //Number, name, type; 2 columns

    List<ColumnMetaData> meta = schema.getColumnMetaData();
    for (int i = 0; i < meta.size(); i++) {
        int o = i % 2;
        table[i / 2][o * 3] = String.valueOf(i);
        table[i / 2][o * 3 + 1] = meta.get(i).getName();
        table[i / 2][o * 3 + 2] = meta.get(i).getColumnType().toString();
    }

    for (int i = 0; i < table.length; i++) {
        for (int j = 0; j < table[i].length; j++) {
            if (table[i][j] == null) {
                table[i][j] = "";
            }
        }
    }

    RenderableComponentTable rct = new RenderableComponentTable.Builder().table(table)
            .header("#", "Name", "Type", "#", "Name", "Type").backgroundColor("#FFFFFF").headerColor("#CCCCCC")
            .colWidthsPercent(8, 30, 12, 8, 30, 12).border(1).padLeftPx(4).padRightPx(4).build();
    divs.add(new DivObject("tablesource", ret.writeValueAsString(rct)));

    //Create the plots
    double[] x = new double[sequence.size()];
    for (int i = 0; i < x.length; i++) {
        x[i] = i;
    }

    for (int i = 0; i < n; i++) {
        double[] lineData;
        switch (meta.get(i).getColumnType()) {
        case Integer:
        case Long:
        case Double:
        case Float:
        case Time:
            lineData = new double[sequence.size()];
            for (int j = 0; j < lineData.length; j++) {
                lineData[j] = sequence.get(j).get(i).toDouble();
            }
            break;
        case Categorical:
            //This is a quick-and-dirty way to plot categorical variables as a line chart
            List<String> stateNames = ((CategoricalMetaData) meta.get(i)).getStateNames();
            lineData = new double[sequence.size()];
            for (int j = 0; j < lineData.length; j++) {
                String state = sequence.get(j).get(i).toString();
                int idx = stateNames.indexOf(state);
                lineData[j] = idx;
            }
            break;
        case Bytes:
        case String:
        case Boolean:
        default:
            //Skip
            continue;
        }

        String name = meta.get(i).getName();

        String chartTitle = "Column: \"" + name + "\" - Column Type: " + meta.get(i).getColumnType();
        if (meta.get(i).getColumnType() == ColumnType.Categorical) {
            List<String> stateNames = ((CategoricalMetaData) meta.get(i)).getStateNames();
            StringBuilder sb = new StringBuilder(chartTitle);
            sb.append(" - (");
            for (int j = 0; j < stateNames.size(); j++) {
                if (j > 0) {
                    sb.append(", ");
                }
                sb.append(j).append("=").append(stateNames.get(j));
            }
            sb.append(")");
            chartTitle = sb.toString();
        }

        RenderableComponentLineChart lc = new RenderableComponentLineChart.Builder().title(chartTitle)
                .addSeries(name, x, lineData).build();

        String divname = "plot_" + i;

        divs.add(new DivObject(divname, ret.writeValueAsString(lc)));
        divNames.add(divname);
    }

    input.put("divs", divs);
    input.put("divnames", divNames);

    //Current date/time, UTC
    DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss zzz")
            .withZone(DateTimeZone.UTC);
    long currTime = System.currentTimeMillis();
    String dateTime = formatter.print(currTime);
    input.put("datetime", dateTime);

    Template template = cfg.getTemplate("sequenceplot.ftl");

    //Process template to String
    Writer stringWriter = new StringWriter();
    template.process(input, stringWriter);

    return stringWriter.toString();
}

From source file:Main.java

static public String convertStreamToString(InputStream is) throws IOException {
    if (is != null) {
        Writer writer = new StringWriter();
        char[] buffer = new char[1024];
        try {/*from w w w.  j  av  a  2 s.  c  o  m*/
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {
        return "";
    }
}

From source file:Main.java

public static String streamToString(InputStream is) throws IOException {
    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {//from   ww  w .  j  av a 2 s. c  o m
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {
        return "";
    }
}

From source file:ca.mudar.parkcatcher.io.LocalExecutor.java

/**
 * Loads the JSON text resource with the given ID and returns the JSON
 * content.//from w w  w .  j av  a 2  s.  c  o m
 */
public static String loadResourceJson(Context context, int resource) throws IOException {
    InputStream is = context.getResources().openRawResource(resource);
    Writer writer = new StringWriter();
    char[] buffer = new char[1024];
    try {
        Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } finally {
        is.close();
    }

    return writer.toString();
}

From source file:com.sinet.gage.dlap.utils.XMLUtils.java

/**
 * @param String/*from www  . j a  v  a 2 s. com*/
 * @param String
 * @return String
 */
public static String parseXML(String xml, String rootElementName) {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(false);
        DocumentBuilder db;
        db = dbf.newDocumentBuilder();
        Document newDoc = db.parse(new ByteArrayInputStream(xml.getBytes()));

        Element element = (Element) newDoc.getElementsByTagName(rootElementName).item(0);
        // Imports a node from another document to this document,
        // without altering
        Document newDoc2 = db.newDocument();
        // or removing the source node from the original document
        Node copiedNode = newDoc2.importNode(element, true);
        // Adds the node to the end of the list of children of this node
        newDoc2.appendChild(copiedNode);

        Transformer tf = TransformerFactory.newInstance().newTransformer();
        tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        tf.setOutputProperty(OutputKeys.INDENT, "yes");

        Writer out = new StringWriter();

        tf.transform(new DOMSource(newDoc2), new StreamResult(out));

        return out.toString();
    } catch (TransformerException | ParserConfigurationException | SAXException | IOException e) {
        LOGGER.error("Exception in parsing xml from response: ", e);
    }
    return "";
}

From source file:org.carewebframework.ui.test.CommonTest.java

/**
 * Reads text from the specified resource on the classpath.
 * //from w  w w.  j  a  v a2 s.com
 * @param resourceName Name of the resource.
 * @return Text read from the resource.
 * @throws IOException IO exception.
 */
public static String getTextFromResource(String resourceName) throws IOException {
    Resource resource = desktopContext.getResource("classpath:" + resourceName);
    InputStream is = resource.getInputStream();
    Writer writer = new StringWriter();
    char[] buffer = new char[1024];

    try {
        Reader reader = new BufferedReader(new InputStreamReader(is, StrUtil.CHARSET));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } finally {
        is.close();
    }
    return writer.toString();
}

From source file:Main.java

public static String convertStreamToString(InputStream inputStream) throws IOException {
    if (inputStream != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {//from ww w. j a  v  a2 s .  c  o m
            Reader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 1024);
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            inputStream.close();
        }
        return writer.toString();
    } else {
        return "";
    }
}

From source file:org.noerp.webtools.print.FoPrintServerEvents.java

public static byte[] getXslFo(DispatchContext dctx, String screen, Map<String, Object> parameters)
        throws GeneralException {
    // run as the system user
    GenericValue system = null;//from   www  .j a  va2 s.  co m
    try {
        system = dctx.getDelegator().findOne("UserLogin", false, "userLoginId", "system");
    } catch (GenericEntityException e) {
        throw new GeneralException(e.getMessage(), e);
    }
    parameters.put("userLogin", system);
    if (!parameters.containsKey("locale")) {
        parameters.put("locale", Locale.getDefault());
    }

    // render and obtain the XSL-FO
    Writer writer = new StringWriter();
    try {
        ScreenRenderer screens = new ScreenRenderer(writer, null, htmlScreenRenderer);
        screens.populateContextForService(dctx, parameters);
        screens.render(screen);
    } catch (Throwable t) {
        throw new GeneralException("Problems rendering FOP XSL-FO", t);
    }
    return writer.toString().getBytes();
}

From source file:com.swordlord.gozer.file.GozerFileLoader.java

public static String convertInputStreamToString(InputStream is) {
    String strReturn = "";

    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {/*from  w  w  w. ja v  a  2  s  .  co m*/
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }

            reader.close();
            strReturn = writer.toString();
            writer.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
    }

    return strReturn;
}

From source file:gov.nih.nci.cacisweb.util.CaCISUtil.java

/**
 * Return the string equivalent of the stack trace
 * //from ww  w.  j  a  v a 2s. c o m
 * @param arg0
 * @return
 */
public static String getStackTrace(Throwable arg0) {
    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    arg0.printStackTrace(printWriter);
    return result.toString();
}