Example usage for java.io OutputStreamWriter OutputStreamWriter

List of usage examples for java.io OutputStreamWriter OutputStreamWriter

Introduction

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

Prototype

public OutputStreamWriter(OutputStream out, CharsetEncoder enc) 

Source Link

Document

Creates an OutputStreamWriter that uses the given charset encoder.

Usage

From source file:com.cloudera.csd.tools.MetricTools.java

/**
 * Writes usage message to 'stream'.//w ww.  j  a  v a 2  s.com
 *
 * @param stream output stream.
 * @throws UnsupportedEncodingException
 */
public static void printUsageMessage(OutputStream stream) throws UnsupportedEncodingException {
    PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream, "UTF-8")));
    try {
        String header = "Cloudera Manager Metric Tools";
        String footer = "";
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(writer, HelpFormatter.DEFAULT_WIDTH, "metric tools", header, OPTIONS,
                HelpFormatter.DEFAULT_LEFT_PAD, HelpFormatter.DEFAULT_DESC_PAD, footer, true); // auto-usage: whether to also show
                                                                                                                                                                                         // the command line args on the usage line.
    } finally {
        writer.close();
    }
}

From source file:com.fengduo.spark.commons.component.ComponentController.java

@ExceptionHandler(Throwable.class)
public ModelAndView handleIOException(Throwable e) throws Throwable {

    if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
        throw e;/*w  w  w .ja  v  a  2  s  .  co  m*/
    }

    if (request == null && response == null) {
        throw e;
    }

    if (request == null && response != null) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, "utf-8"));
        pw.println("{\"code\":1,\"msg\":\",?!\",\"data\":\"\"}");
        pw.flush();
        pw.close();
    }

    ModelAndView mav = new ModelAndView();
    // if (InvokeTypeTools.isAjax(request)) {
    // return createJsonMav("server exceptin or error", ResultCode.ERROR, e.getMessage());
    // }

    mav.addObject("exception", e.getCause() == null ? StringUtils.EMPTY : e.getCause().toString());
    mav.addObject("msg", StringUtils.isEmpty(e.getMessage()) ? e.toString() : e.getMessage());
    mav.addObject("stackTrace", e.getStackTrace().toString());
    if (request.getRequestURI() != null) {
        mav.addObject("url", request.getRequestURI().toString());
    }
    mav.setViewName("error");
    return mav;
}

From source file:com.bitsofproof.supernode.core.IRCDiscovery.java

@Override
public List<InetSocketAddress> discover() {
    List<InetSocketAddress> al = new ArrayList<InetSocketAddress>();

    try {// ww  w .j a v  a2  s  .co m
        log.trace("Connect to IRC server " + server);
        Socket socket = new Socket(server, port);
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));

        String[] answers = new String[] { "Found your hostname", "using your IP address instead",
                "Couldn't look up your hostname", "ignoring hostname" };
        String line;
        boolean stop = false;
        while (!stop && (line = reader.readLine()) != null) {
            log.trace("IRC receive " + line);
            for (int i = 0; i < answers.length; ++i) {
                if (line.contains(answers[i])) {
                    stop = true;
                    break;
                }
            }
        }

        String nick = "bop" + new SecureRandom().nextInt(Integer.MAX_VALUE);
        writer.println("NICK " + nick);
        writer.println("USER " + nick + " 8 * : " + nick);
        writer.flush();
        log.trace("IRC send: I am " + nick);

        while ((line = reader.readLine()) != null) {
            log.trace("IRC receive " + line);
            if (hasCode(line, new String[] { " 004 ", " 433 " })) {
                break;
            }
        }
        log.trace("IRC send: joining " + channel);
        writer.println("JOIN " + channel);
        writer.println("NAMES");
        writer.flush();
        while ((line = reader.readLine()) != null) {
            log.trace("IRC receive " + line);
            if (hasCode(line, new String[] { " 353 " })) {
                StringTokenizer tokenizer = new StringTokenizer(line, ":");
                String t = tokenizer.nextToken();
                if (tokenizer.hasMoreElements()) {
                    t = tokenizer.nextToken();
                }
                tokenizer = new StringTokenizer(t);
                tokenizer.nextToken();
                while (tokenizer.hasMoreTokens()) {
                    String w = tokenizer.nextToken().substring(1);
                    if (!tokenizer.hasMoreElements()) {
                        continue;
                    }
                    try {
                        byte[] m = ByteUtils.fromBase58WithChecksum(w);
                        byte[] addr = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0xff, (byte) 0xff, 0, 0,
                                0, 0 };
                        System.arraycopy(m, 0, addr, 12, 4);
                        al.add(new InetSocketAddress(InetAddress.getByAddress(addr), chain.getPort()));
                    } catch (ValidationException e) {
                        log.trace(e.toString());
                    }
                }
            }
            if (hasCode(line, new String[] { " 366 " })) {
                break;
            }
        }
        writer.println("PART " + channel);
        writer.println("QUIT");
        writer.flush();
        socket.close();
    } catch (UnknownHostException e) {
        log.error("Can not find IRC server " + server, e);
    } catch (IOException e) {
        log.error("Can not use IRC server " + server, e);
    }

    return al;
}

From source file:com.nextep.designer.beng.model.impl.FileUtils.java

/**
 * Writes the specified contents to a file at the given file location.
 * /*from  w  ww  .  ja  va 2  s  . c o m*/
 * @param fileName name of the file to create (will be replaced if exists)
 * @param contents contents to write to the file.
 */
public static void writeToFile(String fileName, String contents) {
    // Retrieves the encoding specified in the preferences
    String encoding = SQLGenUtil.getPreference(PreferenceConstants.SQL_SCRIPT_ENCODING);
    final boolean convert = SQLGenUtil.getPreferenceBool(PreferenceConstants.SQL_SCRIPT_NEWLINE_CONVERT);
    if (convert) {
        String newline = CorePlugin.getService(IGenerationService.class).getNewLine();
        // Converting everything to \n then \n to expected new line
        contents = contents.replace("\r\n", "\n");
        contents = contents.replace("\r", "\n");
        contents = contents.replace("\n", newline);
    }
    Writer w = null;
    try {
        w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileName)), encoding));
        w.write(contents);
    } catch (FileNotFoundException e) {
        throw new ErrorException(e);
    } catch (IOException e) {
        throw new ErrorException(e);
    } finally {
        if (w != null) {
            try {
                w.close();
            } catch (IOException e) {
                throw new ErrorException(e);
            }
        }
    }
}

From source file:com.lianggzone.freemarkerutils.utils.FreeMarkerFactory.java

/**
 * ?ftl?,???HTML/* ww w.j a va 2s.  co m*/
 * @param ftlPath   FTL?,["c:/liang/template.ftl"]
 * @param filePath  ?HMTL["d:/liang/lianggzone.html"]
 * @param data      Map?
 * @param isCreate4NoExists      ??
 * @return
 */
public static boolean createHTML(String ftlPath, String filePath, Map<String, Object> data,
        boolean isCreate4NoExists) throws IOException {
    String fileDir = StringUtils.substringBeforeLast(filePath, "/"); // ?HMTL
    //      String fileName = StringUtils.substringAfterLast(filePath, "/");  // ?HMTL??
    String ftlDir = StringUtils.substringBeforeLast(ftlPath, "/"); // ?FTL
    String ftlName = StringUtils.substringAfterLast(ftlPath, "/"); // ?FTL?? 

    //?
    if (isCreate4NoExists) {
        File realDirectory = new File(fileDir);
        if (!realDirectory.exists()) {
            realDirectory.mkdirs();
        }
    }

    // step1 ?freemarker?
    Configuration freemarkerCfg = new Configuration(Configuration.VERSION_2_3_23);
    // step2 freemarker??()
    freemarkerCfg.setDirectoryForTemplateLoading(new File(ftlDir));
    // step3 freemarker??
    freemarkerCfg.setEncoding(Locale.getDefault(), CharEncoding.UTF_8);
    // step4 freemarker?
    Template template = freemarkerCfg.getTemplate(ftlName, CharEncoding.UTF_8);
    // step5 ?IO?
    try (Writer writer = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(new File(filePath)), CharEncoding.UTF_8))) {
        writer.flush();
        // step6 ??
        template.process(data, writer);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:com.salsaberries.narchiver.Writer.java

/**
 * Writes all the pages to file.//ww w. j  a va 2  s.  com
 *
 * @param pages
 * @param location
 */
public static void storePages(LinkedList<Page> pages, String location) {

    logger.info("Dumping " + pages.size() + " pages to file at " + location + "/");

    File file = new File(location);
    // Make sure the directory exists
    if (!file.exists()) {
        try {
            file.mkdirs();
            logger.info("Directory " + file.getAbsolutePath() + " does not exist, creating.");
        } catch (SecurityException e) {
            logger.error(e.getMessage());
        }
    }
    // Write them to the file if they haven't been already written
    while (!pages.isEmpty()) {
        Page page = pages.removeFirst();

        String fileName = file.getAbsolutePath() + "/" + page.getDate() + "|"
                + URLEncoder.encode(page.getTagURL());

        try (BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(fileName), "utf-8"))) {
            writer.write(page.toString());
        } catch (IOException e) {
            logger.warn(e.getMessage());
        }
        // Temporarily try to reduce memory
        page.setHtml("");
    }
}

From source file:jt56.comm.code.util.CommonPageParser.java

public static void WriterPage(VelocityContext context, String templateName, String fileDirPath,
        String targetFile) {//  w w  w . j  a  v  a  2 s .  c  o  m
    try {
        File file = new File(fileDirPath + targetFile);
        if (!(file.exists())) {
            new File(file.getParent()).mkdirs();
        } else if (isReplace) {
            log.info("?:" + file.getAbsolutePath());
        }

        Template template = ve.getTemplate(templateName, "UTF-8");
        FileOutputStream fos = new FileOutputStream(file);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
        template.merge(context, writer);
        writer.flush();
        writer.close();
        fos.close();
        log.info("?" + file.getAbsolutePath());
    } catch (Exception e) {
        log.error(e);
    }
}

From source file:com.clican.pluto.cms.ui.servlet.VelocityResourceServlet.java

@SuppressWarnings("unchecked")
@Override/*ww  w. j  av  a  2  s.c  o m*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String prefix = request.getContextPath() + request.getServletPath();
    if (request.getRequestURI().startsWith(prefix)) {
        String path = request.getRequestURI().replaceFirst(prefix, "");
        if (path.startsWith("/")) {
            path = path.substring(1, path.indexOf(";"));
        }
        // request.getSession().setAttribute("propertyDescriptionList", new
        // ArrayList<PropertyDescription>());
        Writer w = new OutputStreamWriter(response.getOutputStream(), "utf-8");
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        InputStream is = null;
        try {
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
            byte[] data = new byte[is.available()];
            is.read(data);
            String content = new String(data, "utf-8");
            Template t = null;
            VelocityContext velocityContext = new VelocityContext();
            HttpSession session = request.getSession();
            Enumeration<String> en = session.getAttributeNames();
            while (en.hasMoreElements()) {
                String name = en.nextElement();
                velocityContext.put(name, session.getAttribute(name));
            }
            SimpleNode node = RuntimeSingleton.getRuntimeServices().parse(content, path);
            t = new Template();
            t.setName(path);
            t.setRuntimeServices(RuntimeSingleton.getRuntimeServices());
            t.setData(node);
            t.initDocument();
            Writer wr = new OutputStreamWriter(os);
            t.merge(velocityContext, wr);
            wr.flush();
            byte[] datas = os.toByteArray();
            String s = new String(datas);
            log.info(s);
        } catch (Exception e) {
            log.error("", e);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } finally {
            if (w != null) {
                w.close();
            }
            if (is != null) {
                is.close();
            }
        }
    } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }

}

From source file:com.yoncabt.ebr.logger.fs.FileSystemReportLogger.java

@Override
public void logReport(ReportRequest request, ReportOutputFormat outputFormat, InputStream reportData)
        throws IOException {
    String uuid = request.getUuid();
    Map<String, Object> reportParams = request.getReportParams();
    File saveDir = new File(EBRConf.INSTANCE.getValue(EBRParams.REPORT_LOGGER_FSLOGGER_PATH, "/tmp"));
    saveDir.mkdirs();/*from ww  w. j av a2 s. c  o m*/
    boolean compress = EBRConf.INSTANCE.getValue(EBRParams.REPORT_LOGGER_FSLOGGER_COMPRESS, true);
    OutputStream osReport;
    OutputStream osParams;
    if (compress) {
        osReport = new GZIPOutputStream(new FileOutputStream(new File(saveDir, uuid + ".gz")));
        osParams = new GZIPOutputStream(new FileOutputStream(new File(saveDir, uuid + ".json.gz")));
    } else {
        osReport = new FileOutputStream(new File(saveDir, uuid));
        osParams = new FileOutputStream(new File(saveDir, uuid + ".json"));
    }
    IOUtils.copy(reportData, osReport);
    JSONObject jo = new JSONObject(reportParams);
    try (OutputStreamWriter osw = new OutputStreamWriter(osParams, "utf-8")) {
        jo.write(osw);
    }
    osReport.close();
    osParams.close();
}

From source file:com.ksc.auth.profile.ProfilesConfigFileWriter.java

/**
 * Write all the credential profiles to a file. Note that this method will
 * clobber the existing content in the destination file if it's in the
 * overwrite mode. Use {@link #modifyOrInsertProfiles(File, Profile...)}
 * instead, if you want to perform in-place modification on your existing
 * credentials file.//from w  w w.j  a v a  2s.c  o  m
 *
 * @param destination
 *            The destination file where the credentials will be written to.
 * @param overwrite
 *            If true, this method If false, this method will throw
 *            exception if the file already exists.
 * @param profiles
 *            All the credential profiles to be written.
 */
public static void dumpToFile(File destination, boolean overwrite, Profile... profiles) {
    if (destination.exists() && !overwrite) {
        throw new KscClientException("The destination file already exists. "
                + "Set overwrite=true if you want to clobber the existing "
                + "content and completely re-write the file.");
    }

    OutputStreamWriter writer;
    try {
        writer = new OutputStreamWriter(new FileOutputStream(destination, false), StringUtils.UTF8);

    } catch (IOException ioe) {
        throw new KscClientException("Unable to open the destination file.", ioe);
    }

    try {
        final Map<String, Profile> modifications = new LinkedHashMap<String, Profile>();
        for (Profile profile : profiles) {
            modifications.put(profile.getProfileName(), profile);
        }
        ProfilesConfigFileWriterHelper writerHelper = new ProfilesConfigFileWriterHelper(writer, modifications);

        writerHelper.writeWithoutExistingContent();
    } finally {
        try {
            writer.close();
        } catch (IOException ioe) {
        }
    }

}