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.mmj.app.common.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 . j  ava2s  .c  o  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,\"message\":\",?!\",\"data\":\"\"}");
        pw.flush();
        pw.close();
    }

    ModelAndView mav = new ModelAndView();
    if (InvokeTypeTools.isAjax(request)) {
        return createJsonMav(",?!", ResultCode.ERROR, e.getMessage());
    }

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

From source file:eu.h2020.symbiote.model.Registry.java

public void registerMapping(BigInteger mappingId, BigInteger modelId1, BigInteger modelId2, String mapping)
        throws UnsupportedEncodingException {
    // use library to parse mapping file to RDF, then read RDFXML into store
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try (PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out, "UTF-8")), true)) {
        AlignmentParser parser = new AlignmentParser(0);
        parser.initAlignment(null);/*from  ww w. j av a 2 s  . c om*/
        try {
            parser.parseString(mapping).render(new RDFRendererVisitor(writer));
        } catch (AlignmentException e) {
            log.error("Couldn't load the alignment:", e);
        }
        writer.flush();
    }
    String mappingRDF = out.toString();
    Model model = ModelFactory.createDefaultModel();
    model.read(new ByteArrayInputStream(out.toByteArray()), null, RDFFormat.RDFXML.toString());

    tripleStore.insertGraph(Ontology.getMappingGraphURI(mappingId), model, RDFFormat.RDFXML);
    tripleStore.insertGraph(Ontology.MAPPING_GRAPH, Ontology.getMappingMetadata(modelId1, modelId2, mappingId),
            RDFFormat.NTriples);
    log.debug(String.format("mapping registered: modelId1={}, modelId2={}, mapping={}", modelId1, modelId2,
            mappingRDF));
}

From source file:mtsar.api.csv.TaskCSV.java

public static void write(Collection<Task> tasks, OutputStream output) throws IOException {
    try (final Writer writer = new OutputStreamWriter(output, StandardCharsets.UTF_8)) {
        final Iterable<String[]> iterable = () -> tasks.stream().sorted(ORDER)
                .map(task -> new String[] { Integer.toString(task.getId()), // id
                        task.getStage(), // stage
                        Long.toString(task.getDateTime().toInstant().getEpochSecond()), // datetime
                        String.join("|", task.getTags()), // tags
                        task.getType(), // type
                        task.getDescription(), // description
                        String.join("|", task.getAnswers()), // answers
                }).iterator();//from  w ww .  j av  a2s . c om

        FORMAT.withHeader(HEADER).print(writer).printRecords(iterable);
    }
}

From source file:eu.delving.sip.files.ReportWriter.java

public ReportWriter(File reportFile, File reportIndexFile, LinkCheckExtractor linkCheckExtractor)
        throws FileNotFoundException, XPathExpressionException, UnsupportedEncodingException {
    this.reportFile = reportFile;
    this.reportIndexFile = reportIndexFile;
    this.linkCheckExtractor = linkCheckExtractor;
    this.indexOut = new DataOutputStream(new FileOutputStream(reportIndexFile));
    this.count = new CountingOutputStream(new FileOutputStream(reportFile));
    this.out = new OutputStreamWriter(count, "UTF-8");
}

From source file:DiskIO.java

public static void saveStringInFile(File toFile, String insertString) throws IOException {
    BufferedWriter out;/*from  w  w w .j a v  a2s .c  om*/

    out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(toFile), "ISO-8859-1"));
    out.write(insertString);
    out.flush();
    out.close();
}

From source file:Main.java

/**
 * Creates a {@link StreamResult} by wrapping the given outputEntry in an
 * {@link OutputStreamWriter} that transforms Windows line endings (\r\n) 
 * into Unix line endings (\n) on Windows for consistency with Roo's templates.  
 * @param outputEntry/*from w  w  w .j  a  v a  2s . c o  m*/
 * @return StreamResult 
 * @throws UnsupportedEncodingException 
 */
private static StreamResult createUnixStreamResultForEntry(OutputStream outputEntry)
        throws UnsupportedEncodingException {
    final Writer writer;
    if (System.getProperty("line.separator").equals("\r\n")) {
        writer = new OutputStreamWriter(outputEntry, "ISO-8859-1") {
            public void write(char[] cbuf, int off, int len) throws IOException {
                for (int i = off; i < off + len; i++) {
                    if (cbuf[i] != '\r' || (i < cbuf.length - 1 && cbuf[i + 1] != '\n')) {
                        super.write(cbuf[i]);
                    }
                }
            }

            public void write(int c) throws IOException {
                if (c != '\r')
                    super.write(c);
            }

            public void write(String str, int off, int len) throws IOException {
                String orig = str.substring(off, off + len);
                String filtered = orig.replace("\r\n", "\n");
                int lengthDiff = orig.length() - filtered.length();
                if (filtered.endsWith("\r")) {
                    super.write(filtered.substring(0, filtered.length() - 1), 0, len - lengthDiff - 1);
                } else {
                    super.write(filtered, 0, len - lengthDiff);
                }
            }
        };
    } else {
        writer = new OutputStreamWriter(outputEntry, "ISO-8859-1");
    }
    return new StreamResult(writer);
}

From source file:edu.lafayette.metadb.web.dataman.ViewMetadata.java

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*///  ww  w.  j  a v a 2 s. c  o  m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
    String projname = (String) request.getSession(false).getAttribute(Global.SESSION_PROJECT);
    String username = (String) request.getSession(false).getAttribute(Global.SESSION_USERNAME);

    JSONObject output = new JSONObject();
    JSONArray headers = new JSONArray();
    JSONArray items = new JSONArray();

    if (projname == null || projname.equals(""))
        return;

    int itemCount = ItemsDAO.nextItemNumber(projname) - 1;

    try {
        JSONObject itemNumberHeader = new JSONObject();
        itemNumberHeader.put("name", "Filename");
        itemNumberHeader.put("editable", false);
        headers.put(itemNumberHeader);

        for (int i = 0; i < itemCount; i++) {
            items.put(new JSONArray());

            int itemNumber = i + 1;
            String[] filePath = ItemsDAO.getMasterPath(projname, itemNumber).split("/");
            //String[] itemFilename = filePath[filePath.length - 1].split("-");
            String itemName = filePath[filePath.length - 1];
            items.getJSONArray(i).put(itemName);

        }

        String[] techList = request.getParameterValues(Global.MD_TYPE_TECH);
        if (techList != null)
            for (String attr : techList) {

                String element = attr.split("-")[0];
                String[] labelArray = attr.split("-");
                String label = labelArray.length > 1 ? labelArray[1] : "";

                JSONObject techHeader = new JSONObject();
                techHeader.put("name", element + (label.equals("") ? "" : "." + label));
                techHeader.put("editable", false);
                headers.put(techHeader);

                List<String> techData = TechnicalDataDAO.getMultipleTechnicalData(projname, element, label);
                for (int i = 0; i < itemCount; i++) {
                    String data = "";
                    if (i < techData.size())
                        data = techData.get(i);
                    items.getJSONArray(i).put(data);
                }
            }

        Permission metadataPermission = PermissionManDAO.getUserPermission(username, projname);
        boolean editAdmin = metadataPermission.getAdmin_md().equals("read_write");
        boolean editDesc = metadataPermission.getDesc_md().equals("read_write");
        String[] adminList = request.getParameterValues(Global.MD_TYPE_ADMIN);
        if (adminList != null)
            for (String attr : adminList) {
                String[] labelArray = attr.split("-");

                String element = labelArray[0];
                String label = labelArray.length > 1 ? labelArray[1] : "";
                List<String> adminDescData = AdminDescDataDAO.getMultipleAdminDescData(projname, element, label,
                        Global.MD_TYPE_ADMIN);

                //MetaDbHelper.note("Select size "+adminDescData.size());

                JSONObject adminHeader = new JSONObject();
                adminHeader.put("name", element + (label.equals("") ? "" : "." + label));
                adminHeader.put("editable", editAdmin);
                headers.put(adminHeader);

                for (int i = 0; i < itemCount; i++) {
                    String data = "";
                    if (i < adminDescData.size())
                        data = StringEscapeUtils.escapeHtml(adminDescData.get(i));
                    items.getJSONArray(i).put(data);

                }
            }

        String[] descList = request.getParameterValues(Global.MD_TYPE_DESC);

        if (descList != null)
            for (String attr : descList) {
                String[] labelArray = attr.split("-");

                String element = labelArray[0];
                String label = labelArray.length > 1 ? labelArray[1] : "";
                List<String> adminDescData = AdminDescDataDAO.getMultipleAdminDescData(projname, element, label,
                        Global.MD_TYPE_DESC);

                //MetaDbHelper.note("Select size "+adminDescData.size());

                JSONObject descHeader = new JSONObject();
                descHeader.put("name", element + (label.equals("") ? "" : "." + label));
                descHeader.put("editable", editDesc);
                headers.put(descHeader);

                for (int i = 0; i < itemCount; i++) {
                    String data = "";
                    if (i < adminDescData.size())
                        if (AdminDescAttributesDAO.getAttributeByName(projname, element, label).isSorted())
                            data = StringEscapeUtils.escapeHtml(MetaDbHelper.sortVocab(adminDescData.get(i)));
                        else
                            data = StringEscapeUtils.escapeHtml(adminDescData.get(i));
                    items.getJSONArray(i).put(data);
                }
            }

        output.put("headers", headers);
        output.put("items", items);
    } catch (Exception e) {
        MetaDbHelper.logEvent(e);
    }

    out.print(output);
    out.flush();
}

From source file:de.cebitec.readXplorer.plotting.ChartExporter.java

@Override
public void run() {
    notifyObservers(ChartExportStatus.RUNNING);
    Rectangle bounds = new Rectangle(1920, 1080);
    DOMImplementation dom = GenericDOMImplementation.getDOMImplementation();
    Document document = dom.createDocument(null, "svg", null);
    SVGGraphics2D generator = new SVGGraphics2D(document);
    chart.draw(generator, bounds);/*from   ww  w  .j  a  v a 2s . co m*/
    try (OutputStream outputStream = Files.newOutputStream(file, StandardOpenOption.CREATE)) {
        Writer out = new OutputStreamWriter(outputStream, "UTF-8");
        generator.stream(out, true);
        outputStream.flush();
        notifyObservers(ChartExportStatus.FINISHED);
    } catch (IOException ex) {
        notifyObservers(ChartExportStatus.FAILED);
    }
}

From source file:gr.uoc.nlp.opinion.ilsptagger.POSTagDocuments.java

private void crateTxtFiles(ResultSet rs) {

    System.out.println("Creating .txt files..");
    try {/*from  w w w  .  ja  v a2 s.co m*/
        while (rs.next()) {
            try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(this.dir + rs.getString("comment_id") + ".txt"), "utf-8"))) {
                bw.write(rs.getString("comment"));

                bw.close();
            }
        }

        System.out.println("Done creating .txt files!");

    } catch (FileNotFoundException | UnsupportedEncodingException ex) {
        System.err.println("Abort!");
        Logger.getLogger(POSTagDocuments.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException | IOException ex) {
        Logger.getLogger(POSTagDocuments.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.benasmussen.maven.plugin.i18n.io.JsonResourceWriter.java

@Override
protected void after(ResourceEntry resourceEntry) {
    super.after(resourceEntry);

    Set<String> keySet = output.keySet();
    for (String locale : keySet) {
        String filename = getFilename(resourceEntry, locale);

        Writer writer = null;// ww w.  ja  v  a2 s.  co m
        try {
            File outputFile = new File(outputFolder, filename);
            writer = new OutputStreamWriter(new FileOutputStream(outputFile), getOutputEnconding());

            LinkedHashMap<String, String> jsonMap = output.get(locale);

            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(jsonMap);
            writer.write(json);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(writer);
        }
    }

}