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:com.adguard.compiler.FileUtil.java

private static void processHtmlFile(File file, Browser browser) throws Exception {

    Configuration templateConfiguration = new Configuration();

    FileTemplateLoader fileTemplateLoader = new FileTemplateLoader(file.getParentFile());
    templateConfiguration.setTemplateLoader(fileTemplateLoader);

    String result;/*  w ww .  j a v  a  2s.  com*/
    Writer out = null;
    try {

        out = new StringWriter();

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("browser", browser);

        Template template = templateConfiguration.getTemplate(file.getName(), "utf-8");
        template.process(params, out);

        result = out.toString();
    } finally {
        IOUtils.closeQuietly(out);
    }

    FileUtils.writeStringToFile(file, result);
}

From source file:com.qpark.eip.core.failure.BaseFailureHandler.java

private static String getStackTrace(final Throwable t) {
    if (t != null) {
        Writer w = new StringWriter();
        PrintWriter pw = new PrintWriter(w);
        t.printStackTrace(pw);// ww w .  j  av  a 2 s  . c  o m
        return w.toString();
    } else {
        return "";
    }
}

From source file:Main.java

private static String convertStreamToString(InputStream is) {
    Writer writer = new StringWriter();
    char[] buffer = new char[2048];
    try {/*from w w w. j av a 2s . co m*/
        Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        int len;
        while ((len = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return writer.toString();
}

From source file:com.varaneckas.hawkscope.Version.java

/**
 * Formats bug report from exception/* w  w  w .j a  va2 s.com*/
 * 
 * @param e cause of possible bug
 * @return formatted report
 */
public static String getBugReport(final Throwable e) {
    final StringBuilder sb = new StringBuilder(300);
    final Writer stringWriter = new StringWriter();
    final PrintWriter w = new PrintWriter(stringWriter);
    e.printStackTrace(w);
    sb.append("Hawkscope Bug Report").append('\n').append(SEPARATOR)
            .append(e.getMessage().replaceAll(": ", ":\n")).append('\n').append(SEPARATOR)
            .append(stringWriter.toString()).append('\n').append(SEPARATOR).append(getEnvironmentReport());
    return sb.toString();
}

From source file:com.grouptuity.venmo.VenmoUtility.java

public static String convertStreamToString(InputStream inputStream) throws IOException {
    if (inputStream != null) {
        Writer writer = new StringWriter();
        char[] buffer = new char[1024];
        try {//w  w w.  j av a  2  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.apache.ofbiz.common.JsLanguageFileMappingCreator.java

public static Map<String, Object> createJsLanguageFileMapping(DispatchContext ctx, Map<String, ?> context) {
    Map<String, Object> result = ServiceUtil.returnSuccess();
    String encoding = (String) context.get("encoding"); // default value: UTF-8

    List<Locale> localeList = UtilMisc.availableLocales();
    Map<String, Object> jQueryLocaleFile = new LinkedHashMap<String, Object>();
    Map<String, String> dateJsLocaleFile = new LinkedHashMap<String, String>();
    Map<String, String> validationLocaleFile = new LinkedHashMap<String, String>();
    Map<String, String> dateTimePickerLocaleFile = new LinkedHashMap<String, String>();

    // setup some variables to locate the js files
    String componentRoot = "component://images/webapp";
    String jqueryUiLocaleRelPath = "/images/jquery/ui/i18n/";
    String dateJsLocaleRelPath = "/images/jquery/plugins/datejs/";
    String validateRelPath = "/images/jquery/plugins/validate/localization/";
    String dateTimePickerJsLocaleRelPath = "/images/jquery/plugins/datetimepicker/localization/";
    String jsFilePostFix = ".js";
    String dateJsLocalePrefix = "date-";
    String validateLocalePrefix = "messages_";
    String jqueryUiLocalePrefix = "jquery.ui.datepicker-";
    String dateTimePickerPrefix = "jquery-ui-timepicker-";
    String defaultLocaleDateJs = "en-US";
    String defaultLocaleJquery = "en"; // Beware to keep the OFBiz specific jquery.ui.datepicker-en.js file when upgrading...

    for (Locale locale : localeList) {
        String displayCountry = locale.toString();
        String modifiedDisplayCountry = null;
        String modifiedDisplayCountryForValidation = null;
        if (displayCountry.contains("_")) {
            modifiedDisplayCountry = displayCountry.replace("_", "-");
            modifiedDisplayCountryForValidation = displayCountry; // messages*.js use "_" not "-" as others
        } else {//from w w w.j ava 2  s  . c  o  m
            modifiedDisplayCountry = displayCountry;
        }

        String strippedLocale = locale.getLanguage();

        File file = null;
        String fileUrl = null;

        /*
         * Try to open the date-js language file
         */
        String fileName = componentRoot + dateJsLocaleRelPath + dateJsLocalePrefix + modifiedDisplayCountry
                + jsFilePostFix;
        file = FileUtil.getFile(fileName);

        if (file.exists()) {
            fileUrl = dateJsLocaleRelPath + dateJsLocalePrefix + modifiedDisplayCountry + jsFilePostFix;
        } else {
            // Try to guess a language
            String tmpLocale = strippedLocale + "-" + strippedLocale.toUpperCase();
            fileName = componentRoot + dateJsLocaleRelPath + dateJsLocalePrefix + tmpLocale + jsFilePostFix;
            file = FileUtil.getFile(fileName);
            if (file.exists()) {
                fileUrl = dateJsLocaleRelPath + dateJsLocalePrefix + tmpLocale + jsFilePostFix;
            } else {
                // use language en-US as fallback
                fileUrl = dateJsLocaleRelPath + dateJsLocalePrefix + defaultLocaleDateJs + jsFilePostFix;
            }
        }
        dateJsLocaleFile.put(displayCountry, fileUrl);

        /*
         * Try to open the jquery validation language file
         */
        if (modifiedDisplayCountryForValidation != null) { // Try 1st lang_country
            fileName = componentRoot + validateRelPath + validateLocalePrefix
                    + modifiedDisplayCountryForValidation + jsFilePostFix;
            file = FileUtil.getFile(fileName);
            if (file.exists()) {
                fileUrl = validateRelPath + validateLocalePrefix + modifiedDisplayCountryForValidation
                        + jsFilePostFix;
            } else { // lang only
                fileName = componentRoot + validateRelPath + validateLocalePrefix + strippedLocale
                        + jsFilePostFix;
                file = FileUtil.getFile(fileName);
                if (file.exists()) {
                    fileUrl = validateRelPath + validateLocalePrefix + strippedLocale + jsFilePostFix;
                } else {
                    // use default language en as fallback
                    fileUrl = validateRelPath + validateLocalePrefix + defaultLocaleJquery + jsFilePostFix;
                }
            }
        } else { // Then try lang only
            fileName = componentRoot + validateRelPath + validateLocalePrefix + strippedLocale + jsFilePostFix;
            file = FileUtil.getFile(fileName);
            if (file.exists()) {
                fileUrl = validateRelPath + validateLocalePrefix + strippedLocale + jsFilePostFix;
            } else {
                // use default language en as fallback
                fileUrl = validateRelPath + validateLocalePrefix + defaultLocaleJquery + jsFilePostFix;
            }
        }
        validationLocaleFile.put(displayCountry, fileUrl);

        /*
         * Try to open the jquery timepicker language file
         */
        fileName = componentRoot + jqueryUiLocaleRelPath + jqueryUiLocalePrefix + strippedLocale
                + jsFilePostFix;
        file = FileUtil.getFile(fileName);

        if (file.exists()) {
            fileUrl = jqueryUiLocaleRelPath + jqueryUiLocalePrefix + strippedLocale + jsFilePostFix;
        } else {
            // Try to guess a language
            fileName = componentRoot + jqueryUiLocaleRelPath + jqueryUiLocalePrefix + modifiedDisplayCountry
                    + jsFilePostFix;
            file = FileUtil.getFile(fileName);
            if (file.exists()) {
                fileUrl = jqueryUiLocaleRelPath + jqueryUiLocalePrefix + modifiedDisplayCountry + jsFilePostFix;
            } else {
                // use default language en as fallback
                fileUrl = jqueryUiLocaleRelPath + jqueryUiLocalePrefix + defaultLocaleJquery + jsFilePostFix;
            }
        }
        jQueryLocaleFile.put(displayCountry, fileUrl);

        /*
         * Try to open the datetimepicker language file
         */
        fileName = componentRoot + dateTimePickerJsLocaleRelPath + dateTimePickerPrefix + strippedLocale
                + jsFilePostFix;
        file = FileUtil.getFile(fileName);

        if (file.exists()) {
            fileUrl = dateTimePickerJsLocaleRelPath + dateTimePickerPrefix + strippedLocale + jsFilePostFix;
        } else {
            // Try to guess a language
            fileName = componentRoot + dateTimePickerJsLocaleRelPath + dateTimePickerPrefix
                    + modifiedDisplayCountry + jsFilePostFix;
            file = FileUtil.getFile(fileName);
            if (file.exists()) {
                fileUrl = dateTimePickerJsLocaleRelPath + dateTimePickerPrefix + modifiedDisplayCountry
                        + jsFilePostFix;
            } else {
                // use default language en as fallback
                fileUrl = dateTimePickerJsLocaleRelPath + dateTimePickerPrefix + defaultLocaleJquery
                        + jsFilePostFix;
            }
        }
        dateTimePickerLocaleFile.put(displayCountry, fileUrl);
    }

    // check the template file
    String template = "framework/common/template/JsLanguageFilesMapping.ftl";
    String output = "framework/common/src/org/apache/ofbiz/common/JsLanguageFilesMapping.java";
    Map<String, Object> mapWrapper = new HashMap<String, Object>();
    mapWrapper.put("datejs", dateJsLocaleFile);
    mapWrapper.put("jquery", jQueryLocaleFile);
    mapWrapper.put("validation", validationLocaleFile);
    mapWrapper.put("dateTime", dateTimePickerLocaleFile);

    // some magic to create a new java file: render it as FTL
    Writer writer = new StringWriter();
    try {
        FreeMarkerWorker.renderTemplate(template, mapWrapper, writer);
        // write it as a Java file
        File file = new File(output);
        FileUtils.writeStringToFile(file, writer.toString(), encoding);
    } catch (Exception e) {
        Debug.logError(e, module);
        return ServiceUtil
                .returnError(UtilProperties.getMessage("CommonUiLabels", "CommonOutputFileCouldNotBeCreated",
                        UtilMisc.toMap("errorString", e.getMessage()), (Locale) context.get("locale")));
    }

    return result;
}

From source file:net.duckling.ddl.util.FileUtil.java

/**
 *  Returns the full contents of the Reader as a String.
 *
 *  @since 1.5.8//from w  w w .  ja  va  2  s.  co  m
 *  @param in The reader from which the contents shall be read.
 *  @return String read from the Reader
 *  @throws IOException If reading fails.
 */
public static String readContents(Reader in) throws IOException {
    Writer out = null;

    try {
        out = new StringWriter();

        copyContents(in, out);

        return out.toString();
    } finally {
        try {
            out.close();
        } catch (Exception e) {
            LOG.error("Not able to close the stream while reading contents.");
        }
    }
}

From source file:com.teotigraphix.caustk.utils.RuntimeUtils.java

/**
 * Converts and {@link InputStream} to a String.
 * //from   w w  w . ja v a  2  s.  c  o  m
 * @param is The {@link InputStream} to read into a String.
 * @return THe String read from the stream.
 * @throws IOException
 */
public static final String convertStreamToString(InputStream is) throws IOException {
    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:org.apache.manifoldcf.authorities.authorities.jira.JiraSession.java

private static String convertToString(HttpResponse httpResponse) throws IOException {
    HttpEntity entity = httpResponse.getEntity();
    if (entity != null) {
        InputStream is = entity.getContent();
        try {//  w w  w.ja va  2 s.c o  m
            char[] buffer = new char[65536];
            Reader r = new InputStreamReader(is, getCharSet(entity));
            Writer w = new StringWriter();
            try {
                while (true) {
                    int amt = r.read(buffer);
                    if (amt == -1)
                        break;
                    w.write(buffer, 0, amt);
                }
            } finally {
                w.flush();
            }
            return w.toString();
        } finally {
            is.close();
        }
    }
    return "";
}

From source file:com.cisco.ca.cstg.pdi.utils.Util.java

/**
 * This method converts the entries in the Map to json string and adds it to
 * jsonList/*from   www  .j a  v a 2  s . c  om*/
 * 
 * @author padmkris
 * 
 * @param myMap
 *            contains the entry of key value pair for json object
 * @param jsonList
 *            List of json string, added from myMap
 */
public static void convertMapToJson(Map<String, Object> myMap, List<Object> jsonList) {
    Writer strWriter = new StringWriter();
    ObjectMapper mapper = new ObjectMapper();
    try {
        mapper.writeValue(strWriter, myMap);
        String pmDataJSON = strWriter.toString();
        jsonList.add(pmDataJSON);

    } catch (JsonGenerationException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (JsonMappingException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }
}