Example usage for java.io OutputStreamWriter write

List of usage examples for java.io OutputStreamWriter write

Introduction

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

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:be.fedict.eidviewer.lib.file.imports.Version35CSVFile.java

public static void toCSV(Version35CSVFile v35File, OutputStream outputStream) throws Exception {
    /* version;type;name;surname;gender;date_of_birth;location_of_birth;nobility;nationality;
    national_nr;special_organization;member_of_family;special_status;logical_nr;chip_nr;
    date_begin;date_end;issuing_municipality;version;street;zip;municipality;country;
    file_id;file_id_sign;file_address;file_address_sign; */

    /* picturedata;picturehash */

    /*//from ww w.  ja  va  2 s.c o  m
    serial_nr;component_code;os_nr;os_version;softmask_nr;softmask_version;applet_version;
    global_os_version;applet_interface_version;PKCS1_support;key_exchange_version;
    application_lifecycle;graph_perso;elec_perso;elec_perso_interface;
    */

    /* challenge, response */

    /*
     * RRN Cert
     */

    /*
    certificatescount;certificate1;certificate2;...
    */

    /*
     * PIN codes
     */

    DateFormat dottyDate = new SimpleDateFormat("dd.MM.yyyy");

    OutputStreamWriter writer = new OutputStreamWriter(outputStream);

    logger.finest(TextFormatHelper.dateToRRNDate(v35File.identity.dateOfBirth.getTime()).toUpperCase());

    // write all fixed pos data
    writer.write(String.format(
            "1;eid;;%02d;%s;%s;%c;%s;%s;%s;%s;%s;%s;%s;%s;%1d;%s;%s;%s;%s;%s;;%s;%s;%s;be;;;;;%s;;;;;;;;;;;;;;;;;;;;;RRN;1;%s;;",
            v35File.identity.documentType.getKey(), v35File.identity.firstName, v35File.identity.name,
            (v35File.identity.gender == Gender.FEMALE ? 'F' : 'M'),
            TextFormatHelper.dateToRRNDate(v35File.identity.dateOfBirth.getTime()).toUpperCase(),
            v35File.identity.placeOfBirth,
            (v35File.identity.nobleCondition != null ? v35File.identity.nobleCondition : ""),
            v35File.identity.nationality, v35File.identity.nationalNumber,
            (v35File.identity.duplicate != null ? v35File.identity.duplicate : ""),
            (v35File.identity.specialOrganisation != null ? v35File.identity.specialOrganisation : ""),
            (v35File.identity.memberOfFamily ? "1" : ""),
            (v35File.identity.specialStatus != null ? v35File.identity.specialStatus.ordinal() : 0),
            // logicalNumber
            v35File.identity.cardNumber, v35File.identity.chipNumber,
            dottyDate.format(v35File.identity.cardValidityDateBegin.getTime()),
            dottyDate.format(v35File.identity.cardValidityDateEnd.getTime()),
            v35File.identity.cardDeliveryMunicipality,
            // version
            v35File.address.streetAndNumber, v35File.address.zip, v35File.address.municipality,
            // file_id
            // file_id_sign
            // file_address
            // file_address_sign
            X509Utilities.eidBase64Encode(v35File.photo),
            // picturehash
            // serial_nr
            // component_code
            // os_nr
            // os_version
            // softmask_nr
            // softmask_version
            // applet_version
            // global_os_version
            // applet_interface_version
            // PKCS1_support
            // key_exchange_version
            // application_lifecycle
            // graph_perso
            // elec_perso
            // elec_perso_interface
            // challenge
            // response
            X509Utilities.eidBase64Encode(v35File.rrnCert.getEncoded())));

    // write variable number of certificates
    int ncerts = 0;
    if (v35File.authenticationCert != null)
        ncerts++;
    if (v35File.signingCert != null)
        ncerts++;
    if (v35File.citizenCert != null)
        ncerts++;
    if (v35File.rootCert != null)
        ncerts++;
    writer.write(String.format("%d;", ncerts));
    if (v35File.authenticationCert != null)
        X509CertToCSV(v35File.authenticationCert, "Authentication", writer);
    if (v35File.signingCert != null)
        X509CertToCSV(v35File.signingCert, "Signature", writer);
    if (v35File.citizenCert != null)
        X509CertToCSV(v35File.citizenCert, "CA", writer);
    if (v35File.rootCert != null)
        X509CertToCSV(v35File.rootCert, "Root", writer);

    // write variable number of pin codes..
    writer.write("0"); // zero PIN codes in this file
    writer.flush();
    writer.close();

}

From source file:gate.util.Files.java

/**
 * This method updates an XML element in an XML file
 * with a new set of attributes. If the element is not found the XML
 * file is unchanged. The attributes keys and values must all be Strings.
 * We first try to read the file using UTF-8 encoding.  If an error occurs we
 * fall back to the platform default encoding (for backwards-compatibility
 * reasons) and try again.  The file is written back in UTF-8, with an
 * updated encoding declaration./*from   w  w w.j av  a2  s.  c o  m*/
 *
 * @param xmlFile An XML file.
 * @param elementName The name of the element to update.
 * @param newAttrs The new attributes to place on the element.
 * @return A string of the whole XML file, with the element updated (the
 *   file is also overwritten).
 */
public static String updateXmlElement(File xmlFile, String elementName, Map<String, String> newAttrs)
        throws IOException {
    String newXml = null;
    BufferedReader utfFileReader = null;
    BufferedReader platformFileReader = null;
    Charset utfCharset = Charset.forName("UTF-8");
    try {
        FileInputStream fis = new FileInputStream(xmlFile);
        // try reading with UTF-8, make sure any errors throw an exception
        CharsetDecoder decoder = utfCharset.newDecoder().onUnmappableCharacter(CodingErrorAction.REPORT)
                .onMalformedInput(CodingErrorAction.REPORT);
        utfFileReader = new BomStrippingInputStreamReader(fis, decoder);
        newXml = updateXmlElement(utfFileReader, elementName, newAttrs);
    } catch (CharacterCodingException cce) {
        // File not readable as UTF-8, so try the platform default encoding
        if (utfFileReader != null) {
            utfFileReader.close();
            utfFileReader = null;
        }
        if (DEBUG) {
            Err.prln("updateXmlElement: could not read " + xmlFile + " as UTF-8, " + "trying platform default");
        }
        platformFileReader = new BufferedReader(new FileReader(xmlFile));
        newXml = updateXmlElement(platformFileReader, elementName, newAttrs);
    } finally {
        if (utfFileReader != null) {
            utfFileReader.close();
        }
        if (platformFileReader != null) {
            platformFileReader.close();
        }
    }

    // write the updated file in UTF-8, fixing the encoding declaration
    newXml = newXml.replaceFirst("\\A<\\?xml (.*)encoding=(?:\"[^\"]*\"|'[^']*')",
            "<?xml $1encoding=\"UTF-8\"");
    FileOutputStream fos = new FileOutputStream(xmlFile);
    OutputStreamWriter fileWriter = new OutputStreamWriter(fos, utfCharset);
    fileWriter.write(newXml);
    fileWriter.close();

    return newXml;
}

From source file:org.hl7.fhir.client.ClientUtils.java

private static byte[] encodeFormSubmission(Map<String, String> parameters, String resourceName,
        Resource resource, String boundary) throws Exception {
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    OutputStreamWriter w = new OutputStreamWriter(b, "UTF-8");
    for (String name : parameters.keySet()) {
        w.write("--");
        w.write(boundary);/*from  w  ww.jav  a2  s. co m*/
        w.write("\r\nContent-Disposition: form-data; name=\"" + name + "\"\r\n\r\n");
        w.write(parameters.get(name) + "\r\n");
    }
    w.write("--");
    w.write(boundary);
    w.write("\r\nContent-Disposition: form-data; name=\"" + resourceName + "\"\r\n\r\n");
    w.close();
    new JsonComposer().compose(b, resource, false);
    w = new OutputStreamWriter(b, "UTF-8");
    w.write("\r\n--");
    w.write(boundary);
    w.write("--");
    w.close();
    return b.toByteArray();
}

From source file:com.denimgroup.threadfix.service.defects.RestUtils.java

public static InputStream postUrl(String urlString, String data, String username, String password) {
    URL url = null;//from   w ww. jav a2s. co  m
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        log.warn("URL used for POST was bad: '" + urlString + "'");
        return null;
    }

    HttpURLConnection httpConnection = null;
    OutputStreamWriter outputWriter = null;
    try {
        httpConnection = (HttpURLConnection) url.openConnection();

        setupAuthorization(httpConnection, username, password);

        httpConnection.addRequestProperty("Content-Type", "application/json");
        httpConnection.addRequestProperty("Accept", "application/json");

        httpConnection.setDoOutput(true);
        outputWriter = new OutputStreamWriter(httpConnection.getOutputStream());
        outputWriter.write(data);
        outputWriter.flush();

        InputStream is = httpConnection.getInputStream();

        return is;
    } catch (IOException e) {
        log.warn("IOException encountered trying to post to URL with message: " + e.getMessage());
        if (httpConnection == null) {
            log.warn(
                    "HTTP connection was null so we cannot do further debugging of why the HTTP request failed");
        } else {
            try {
                InputStream errorStream = httpConnection.getErrorStream();
                if (errorStream == null) {
                    log.warn("Error stream from HTTP connection was null");
                } else {
                    log.warn(
                            "Error stream from HTTP connection was not null. Attempting to get response text.");
                    String postErrorResponse = IOUtils.toString(errorStream);
                    log.warn("Error text in response was '" + postErrorResponse + "'");
                }
            } catch (IOException e2) {
                log.warn("IOException encountered trying to read the reason for the previous IOException: "
                        + e2.getMessage(), e2);
            }
        }
    } finally {
        if (outputWriter != null) {
            try {
                outputWriter.close();
            } catch (IOException e) {
                log.warn("Failed to close output stream in postUrl.", e);
            }
        }
    }

    return null;
}

From source file:com.ieasy.basic.util.file.FileUtils.java

public static void WriteJSON(String outPath, String perfix, Object obj) {
    try {//from   w w  w  . j av  a 2s.  com
        String json = JSON.toJSONStringWithDateFormat(obj, "yyyy-MM-dd HH:mm:ss");
        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(outPath), "UTF-8");
        out.write((null != perfix ? perfix : "") + json);
        out.flush();
        out.close();
    } catch (IOException e) {
        logger.error("?JSON" + e.getMessage());
    }
    logger.debug("?JSON-->" + outPath);
}

From source file:at.lame.hellonzb.parser.NzbParser.java

/**
 * This method writes out the content (segments) of a DownloadFile object
 * to the given OutputStreamWriter object.
 * //from www .j  ava 2  s. c  o m
 * @param writer The stream writer object to use
 * @param dlFile The download file to use
 * @throws IOException
 */
private static void writeDlFileToXml(OutputStreamWriter writer, DownloadFile dlFile) throws IOException {
    String newline = System.getProperty("line.separator");
    String poster = StringEscapeUtils.escapeHtml(dlFile.getPoster());
    String date = StringEscapeUtils.escapeHtml(dlFile.getCreationDate());
    String subject = StringEscapeUtils.escapeHtml(dlFile.getSubject());

    // <file ...> element
    writer.write("<file poster=\"" + poster + "\" ");
    writer.write("date=\"" + date + "\" ");
    writer.write("subject=\"" + subject + "\">");
    writer.write(newline);

    // <group> elements
    writer.write("<groups>");
    writer.write(newline);
    for (String group : dlFile.getGroups()) {
        writer.write("<group>" + group + "</group>");
        writer.write(newline);
    }
    writer.write("</groups>");
    writer.write(newline);

    // <segment> elements
    writer.write("<segments>");
    writer.write(newline);
    for (DownloadFileSegment seg : dlFile.getAllOriginalSegments()) {
        if (seg == null)
            continue;

        String aID = StringEscapeUtils.escapeXml(seg.getArticleId());

        writer.write("<segment bytes=\"" + seg.getSize() + "\" " + "number=\"" + seg.getIndex() + "\">" + aID
                + "</segment>");
        writer.write(newline);
    }
    writer.write("</segments>");
    writer.write(newline);

    // end <file> element
    writer.write("</file>");
    writer.write(newline);
}

From source file:de.codesourcery.jasm16.utils.Misc.java

public static void writeResource(IResource resource, String s) throws IOException {
    final OutputStreamWriter writer = new OutputStreamWriter(resource.createOutputStream(false));
    try {/*from w  w w .  j a v  a  2 s. com*/
        writer.write(s);
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

From source file:at.tugraz.sss.serv.SSFileU.java

public static void writeStr(final String str, final String filePath) throws Exception {

    OutputStreamWriter out = null;

    try {//from w w w . j  a  va  2  s.  c  om

        out = new OutputStreamWriter(openOrCreateFileWithPathForWrite(filePath), SSEncodingU.utf8.toString());

        out.write(str);

    } finally {

        if (out != null) {
            out.close();
        }
    }
}

From source file:com.ms.commons.test.treedb.Objects2XmlFileUtil.java

public static void write(String testMethodName, BuiltInCacheKey prePareOrResult, List<?>... prepareData) {

    OutputStreamWriter writer = null;
    File file = getFile(testMethodName, prePareOrResult);
    try {//www.  j av  a 2  s  .  c  o  m
        writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        XStream xStream = new XStream();
        StringBuilder root = new StringBuilder();

        root.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        root.append("<").append(ROOT).append(">");

        for (List<?> objectList : prepareData) {
            if (objectList == null || objectList.size() <= 0)
                continue;

            StringBuilder objectStr = objectList2XmlString(xStream, objectList);

            root.append(objectStr);
        }

        root.append("</").append(ROOT).append(">");

        writer.write(prettyPrint(root.toString()));
        writer.close();
    } catch (FileNotFoundException e) {
        throw new RuntimeException("write " + file.getAbsolutePath() + " failed", e);
    } catch (IOException e) {
        throw new RuntimeException("write " + file.getAbsolutePath() + " failed", e);
    } finally {
        close(writer);
    }
}

From source file:at.tugraz.sss.serv.SSFileU.java

public static void writeFileText(final File file, final String text) throws Exception {

    if (SSObjU.isNull(file, text)) {
        throw new Exception("pars not okay");
    }//from   w  w w .  j a v  a  2 s .  c o  m

    //    final byte[]        bytes      = text.getBytes();
    OutputStreamWriter fileOut = null;

    try {

        fileOut = new OutputStreamWriter(openOrCreateFileWithPathForWrite(file.getAbsolutePath()),
                Charset.forName(SSEncodingU.utf8.toString()));

        fileOut.write(text);
        //      fileOut.write (bytes, 0, bytes.length);

    } catch (Exception error) {
        throw error;
    } finally {

        if (fileOut != null) {
            fileOut.close();
        }
    }
}