Example usage for java.io OutputStreamWriter flush

List of usage examples for java.io OutputStreamWriter flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:org.apache.olingo.fit.utils.AbstractXMLUtilities.java

@Override
public InputStream setChanges(final InputStream toBeChanged, final Map<String, InputStream> properties)
        throws Exception {
    XMLEventReader reader = getEventReader(toBeChanged);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    XMLEventWriter writer = getEventWriter(bos);

    // ---------------------------------
    // add property changes
    // ---------------------------------
    Map.Entry<Integer, XmlElement> propertyElement = extractElement(reader, writer,
            Collections.<String>singletonList(PROPERTIES), 0, 2, 3);

    writer.flush();/*from   ww  w.  j  a  v  a  2 s  . co m*/

    ByteArrayOutputStream pbos = new ByteArrayOutputStream();
    OutputStreamWriter pwriter = new OutputStreamWriter(pbos);

    final XMLEventReader propertyReader = propertyElement.getValue().getContentReader();

    try {
        while (true) {
            final XmlElement property = extractElement(propertyReader, null, null, 0, -1, -1).getValue();
            final String name = property.getStart().getName().getLocalPart();

            if (properties.containsKey(name)) {
                // replace
                final InputStream replacement = properties.get(name);
                properties.remove(property.getStart().getName().getLocalPart());
                pwriter.append(IOUtils.toString(replacement));
                IOUtils.closeQuietly(replacement);
            } else {
                pwriter.append(IOUtils.toString(property.toStream()));
            }
        }
    } catch (Exception ignore) {
        // end
    }

    for (Map.Entry<String, InputStream> remains : properties.entrySet()) {
        if (!remains.getKey().startsWith("[LINK]")) {
            pwriter.append(IOUtils.toString(remains.getValue()));
            IOUtils.closeQuietly(remains.getValue());
        }
    }

    pwriter.flush();
    pwriter.close();

    writer.add(propertyElement.getValue().getStart());
    writer.add(new XMLEventReaderWrapper(new ByteArrayInputStream(pbos.toByteArray())));
    writer.add(propertyElement.getValue().getEnd());

    IOUtils.closeQuietly(pbos);

    writer.add(reader);
    reader.close();
    writer.flush();
    writer.close();
    // ---------------------------------

    // ---------------------------------
    // add navigationm changes
    // ---------------------------------

    // remove existent links
    for (Map.Entry<String, InputStream> remains : properties.entrySet()) {

        if (remains.getKey().startsWith("[LINK]")) {
            reader = getEventReader(new ByteArrayInputStream(bos.toByteArray()));

            bos.reset();
            writer = getEventWriter(bos);

            try {
                final String linkName = remains.getKey().substring(remains.getKey().indexOf("]") + 1);

                extractElement(reader, writer, Collections.<String>singletonList(LINK),
                        Collections.<Map.Entry<String, String>>singleton(
                                new SimpleEntry<String, String>("title", linkName)),
                        false, 0, 2, 2);

                writer.add(reader);

            } catch (Exception ignore) {
                // ignore
            }

            writer.flush();
            writer.close();
        }
    }

    reader = getEventReader(new ByteArrayInputStream(bos.toByteArray()));

    bos.reset();
    writer = getEventWriter(bos);

    propertyElement = extractElement(reader, writer, Collections.<String>singletonList(CONTENT), 0, 2, 2);
    writer.flush();

    pbos.reset();
    pwriter = new OutputStreamWriter(pbos);

    for (Map.Entry<String, InputStream> remains : properties.entrySet()) {
        if (remains.getKey().startsWith("[LINK]")) {
            pwriter.append(IOUtils.toString(remains.getValue()));
            IOUtils.closeQuietly(remains.getValue());
        }
    }

    pwriter.flush();
    pwriter.close();

    writer.add(new XMLEventReaderWrapper(new ByteArrayInputStream(pbos.toByteArray())));
    IOUtils.closeQuietly(pbos);

    writer.add(propertyElement.getValue().getStart());
    writer.add(propertyElement.getValue().getContentReader());
    writer.add(propertyElement.getValue().getEnd());

    writer.add(reader);
    reader.close();
    writer.flush();
    writer.close();
    // ---------------------------------

    return new ByteArrayInputStream(bos.toByteArray());
}

From source file:jp.zippyzip.impl.GeneratorServiceImpl.java

public void storeX0401Zip() {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    ZipOutputStream out = new ZipOutputStream(baos);
    Collection<Pref> prefs = getPrefs();
    ZipEntry tsv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_utf8.txt");
    ZipEntry csv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_sjis.csv");
    ZipEntry json = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_utf8.json");
    ZipEntry xml = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_utf8.xml");

    tsv.setTime(timestamp);/*from   w ww  . jav a2 s .c o  m*/
    csv.setTime(timestamp);
    json.setTime(timestamp);
    xml.setTime(timestamp);

    try {

        out.putNextEntry(tsv);

        for (Pref pref : prefs) {

            out.write(new String(pref.getCode() + "\t" + pref.getName() + "\t" + pref.getYomi() + CRLF)
                    .getBytes("UTF-8"));
        }

        out.closeEntry();
        out.putNextEntry(csv);

        for (Pref pref : prefs) {

            out.write(new String(pref.getCode() + "," + pref.getName() + "," + pref.getYomi() + CRLF)
                    .getBytes("MS932"));
        }

        out.closeEntry();
        out.putNextEntry(json);

        OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
        JSONWriter jwriter = new JSONWriter(writer);

        jwriter.array();

        for (Pref pref : prefs) {

            jwriter.object().key("code").value(pref.getCode()).key("name").value(pref.getName()).key("yomi")
                    .value(pref.getYomi()).endObject();
        }

        jwriter.endArray();
        writer.flush();
        out.closeEntry();
        out.putNextEntry(xml);

        XMLStreamWriter xwriter = XMLOutputFactory.newInstance()
                .createXMLStreamWriter(new OutputStreamWriter(out, "UTF-8"));

        xwriter.writeStartDocument("UTF-8", "1.0");
        xwriter.writeStartElement("x0401s");

        for (Pref pref : prefs) {

            xwriter.writeStartElement("x0401");
            xwriter.writeAttribute("code", pref.getCode());
            xwriter.writeAttribute("name", pref.getName());
            xwriter.writeAttribute("yomi", pref.getYomi());
            xwriter.writeEndElement();
        }

        xwriter.writeEndElement();
        xwriter.writeEndDocument();
        xwriter.flush();
        out.closeEntry();
        out.finish();
        baos.flush();
        getRawDao().store(baos.toByteArray(), "x0401.zip");
        log.info("prefs: " + prefs.size());

    } catch (JSONException e) {
        log.log(Level.WARNING, "", e);
    } catch (XMLStreamException e) {
        log.log(Level.WARNING, "", e);
    } catch (FactoryConfigurationError e) {
        log.log(Level.WARNING, "", e);
    } catch (IOException e) {
        log.log(Level.WARNING, "", e);
    }
}

From source file:davmail.exchange.ews.EWSMethod.java

protected byte[] generateSoapEnvelope() {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {// w  w w.j  a va 2s  .co  m
        OutputStreamWriter writer = new OutputStreamWriter(baos, "UTF-8");
        writer.write("<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" "
                + "xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\" "
                + "xmlns:m=\"http://schemas.microsoft.com/exchange/services/2006/messages\">" + "");
        writer.write("<soap:Header>");
        if (serverVersion != null) {
            writer.write("<t:RequestServerVersion Version=\"");
            writer.write(serverVersion);
            writer.write("\"/>");
        }
        if (timezoneContext != null) {
            writer.write("<t:TimeZoneContext><t:TimeZoneDefinition Id=\"");
            writer.write(timezoneContext);
            writer.write("\"/></t:TimeZoneContext>");
        }
        writer.write("</soap:Header>");

        writer.write("<soap:Body>");
        writer.write("<m:");
        writer.write(methodName);
        if (traversal != null) {
            traversal.write(writer);
        }
        if (deleteType != null) {
            deleteType.write(writer);
        }
        if (methodOptions != null) {
            for (AttributeOption attributeOption : methodOptions) {
                attributeOption.write(writer);
            }
        }
        writer.write(">");
        writeSoapBody(writer);
        writer.write("</m:");
        writer.write(methodName);
        writer.write(">");
        writer.write("</soap:Body>" + "</soap:Envelope>");
        writer.flush();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return baos.toByteArray();
}

From source file:jp.zippyzip.impl.GeneratorServiceImpl.java

public void storeX0402Zip() {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    ZipOutputStream out = new ZipOutputStream(baos);
    Collection<City> cities = getCities();
    ZipEntry tsv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.txt");
    ZipEntry csv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_sjis.csv");
    ZipEntry json = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.json");
    ZipEntry xml = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.xml");

    tsv.setTime(timestamp);//w  ww  .j ava  2s.c  o  m
    csv.setTime(timestamp);
    json.setTime(timestamp);
    xml.setTime(timestamp);

    try {

        out.putNextEntry(tsv);

        for (City city : cities) {

            out.write(new String(city.getCode() + "\t" + city.getName() + "\t" + city.getYomi() + "\t"
                    + ((city.getExpiration().getTime() < new Date().getTime()) ? "" : "") + CRLF)
                            .getBytes("UTF-8"));
        }

        out.closeEntry();
        out.putNextEntry(csv);

        for (City city : cities) {

            out.write(new String(city.getCode() + "," + city.getName() + "," + city.getYomi() + ","
                    + ((city.getExpiration().getTime() < new Date().getTime()) ? "" : "") + CRLF)
                            .getBytes("MS932"));
        }

        out.closeEntry();
        out.putNextEntry(json);

        OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
        JSONWriter jwriter = new JSONWriter(writer);

        jwriter.array();

        for (City city : cities) {

            jwriter.object().key("code").value(city.getCode()).key("name").value(city.getName()).key("yomi")
                    .value(city.getYomi()).key("expired")
                    .value((city.getExpiration().getTime() < new Date().getTime()) ? "true" : "false")
                    .endObject();
        }

        jwriter.endArray();
        writer.flush();
        out.closeEntry();
        out.putNextEntry(xml);

        XMLStreamWriter xwriter = XMLOutputFactory.newInstance()
                .createXMLStreamWriter(new OutputStreamWriter(out, "UTF-8"));

        xwriter.writeStartDocument("UTF-8", "1.0");
        xwriter.writeStartElement("x0402s");

        for (City city : cities) {

            xwriter.writeStartElement("x0402");
            xwriter.writeAttribute("code", city.getCode());
            xwriter.writeAttribute("name", city.getName());
            xwriter.writeAttribute("yomi", city.getYomi());
            xwriter.writeAttribute("expired",
                    (city.getExpiration().getTime() < new Date().getTime()) ? "true" : "false");
            xwriter.writeEndElement();
        }

        xwriter.writeEndElement();
        xwriter.writeEndDocument();
        xwriter.flush();
        out.closeEntry();
        out.finish();
        baos.flush();
        getRawDao().store(baos.toByteArray(), "x0402.zip");
        log.info("cities: " + cities.size());

    } catch (JSONException e) {
        log.log(Level.WARNING, "", e);
    } catch (XMLStreamException e) {
        log.log(Level.WARNING, "", e);
    } catch (FactoryConfigurationError e) {
        log.log(Level.WARNING, "", e);
    } catch (IOException e) {
        log.log(Level.WARNING, "", e);
    }
}

From source file:com.wentam.defcol.connect_to_computer.HomeCommandHandler.java

@Override
public void handle(final HttpRequest request, final HttpResponse response, HttpContext httpContext)
        throws HttpException, IOException {
    HttpEntity entity = new EntityTemplate(new ContentProducer() {
        public void writeTo(final OutputStream outstream) throws IOException {
            OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
            String req = request.getRequestLine().getUri();

            req = req.replaceAll("/\\?", "");

            String[] pairs = req.split("&");

            HashMap data = new HashMap();

            for (int i = 0; i < pairs.length; i++) {
                if (pairs[i].contains("=")) {
                    String[] pair = pairs[i].split("=");
                    data.put(pair[0], pair[1]);
                }// w  w w  .ja  v a 2s  .c o  m
            }

            String action = "none";
            if (data.containsKey("action")) {
                action = (String) data.get("action");
            }

            String resp = "404 on " + action;
            if (action.equals("none") || action.equals("home")) {
                response.setHeader("Content-Type", "text/html");

                resp = getHtml();

            } else if (action.equals("getPalettes")) {
                response.setHeader("Content-Type", "application/json");

                JSONArray json = new JSONArray();

                int tmp[] = { 0 };
                ArrayList<String> palettes = pFile.getRows(tmp);
                Iterator i = palettes.iterator();
                while (i.hasNext()) {
                    JSONObject item = new JSONObject();
                    try {
                        item.put("name", i.next());
                    } catch (JSONException e) {
                    }
                    json.put(item);
                }

                resp = json.toString();

            } else if (action.equals("getJquery")) {
                response.setHeader("Content-Type", "application/javascript");
                resp = jquery;
            } else if (action.equals("getJs")) {
                response.setHeader("Content-Type", "application/javascript");
                resp = getJs();
            } else if (action.equals("getPaletteColors")) {
                response.setHeader("Content-Type", "application/javascript");
                int id = Integer.parseInt((String) data.get("id"));

                int tmp[] = { 1 };
                String row = pFile.getRow(id, tmp);

                String colors[] = row.split("\\.");

                JSONArray json = new JSONArray();

                for (int i = 0; i < colors.length; i++) {
                    json.put(colors[i]);
                }

                resp = json.toString();
            }

            writer.write(resp);
            writer.flush();
        }
    });

    response.setEntity(entity);
}

From source file:org.apache.catalina.servlets.DefaultServlet.java

/**
 * Return an InputStream to an HTML representation of the contents
 * of this directory.//from w  w w  .j ava2  s  . c  o  m
 *
 * @param contextPath     Context path to which our internal paths are
 *                        relative
 * @param resourceInfo    Description of the Parameter
 * @param xsltInputStream Description of the Parameter
 * @return Description of the Return Value
 */
protected InputStream renderXml(String contextPath, ResourceInfo resourceInfo, InputStream xsltInputStream) {

    StringBuffer sb = new StringBuffer();

    sb.append("<?xml version=\"1.0\"?>");
    sb.append("<listing ");
    sb.append(" contextPath='");
    sb.append(contextPath);
    sb.append("'");
    sb.append(" directory='");
    sb.append(resourceInfo.path);
    sb.append("' ");
    sb.append(" hasParent='").append(!resourceInfo.path.equals("/"));
    sb.append("'>");

    sb.append("<entries>");

    try {

        // Render the directory entries within this directory
        DirContext directory = resourceInfo.directory;
        NamingEnumeration enum1 = resourceInfo.resources.list(resourceInfo.path);
        while (enum1.hasMoreElements()) {

            NameClassPair ncPair = (NameClassPair) enum1.nextElement();
            String resourceName = ncPair.getName();
            ResourceInfo childResourceInfo = new ResourceInfo(resourceName, directory);

            String trimmed = resourceName;
            if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF")
                    || trimmed.equalsIgnoreCase(localXsltFile)) {
                continue;
            }

            sb.append("<entry");
            sb.append(" type='").append(childResourceInfo.collection ? "dir" : "file").append("'");
            sb.append(" urlPath='").append(rewriteUrl(contextPath))
                    .append(rewriteUrl(resourceInfo.path + resourceName))
                    .append(childResourceInfo.collection ? "/" : "").append("'");
            if (!childResourceInfo.collection) {
                sb.append(" size='").append(renderSize(childResourceInfo.length)).append("'");
            }
            sb.append(" date='").append(childResourceInfo.httpDate).append("'");

            sb.append(">");
            sb.append(trimmed);
            if (childResourceInfo.collection) {
                sb.append("/");
            }
            sb.append("</entry>");

        }

    } catch (NamingException e) {
        // Something went wrong
        e.printStackTrace();
    }

    sb.append("</entries>");

    String readme = getReadme(resourceInfo.directory);

    if (readme != null) {
        sb.append("<readme><![CDATA[");
        sb.append(readme);
        sb.append("]]></readme>");
    }

    sb.append("</listing>");

    try {
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Source xmlSource = new StreamSource(new StringReader(sb.toString()));
        Source xslSource = new StreamSource(xsltInputStream);
        Transformer transformer = tFactory.newTransformer(xslSource);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8");
        StreamResult out = new StreamResult(osWriter);
        transformer.transform(xmlSource, out);
        osWriter.flush();
        return (new ByteArrayInputStream(stream.toByteArray()));
    } catch (Exception e) {
        log("directory transform failure: " + e.getMessage());
        return renderHtml(contextPath, resourceInfo);
    }
}

From source file:org.apache.olingo.fit.AbstractServices.java

/**
 * Retrieve entity set or function execution sample.
 *
 * @param accept Accept header.//w w w. jav a2s .c om
 * @param name entity set or function name.
 * @param format format query option.
 * @param count inlinecount query option.
 * @param filter filter query option.
 * @param orderby orderby query option.
 * @param skiptoken skiptoken query option.
 * @return entity set or function result.
 */
@GET
@Path("/{name}")
public Response getEntitySet(@Context final UriInfo uriInfo,
        @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept,
        @PathParam("name") final String name,
        @QueryParam("$top") @DefaultValue(StringUtils.EMPTY) final String top,
        @QueryParam("$skip") @DefaultValue(StringUtils.EMPTY) final String skip,
        @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format,
        @QueryParam("$inlinecount") @DefaultValue(StringUtils.EMPTY) final String count,
        @QueryParam("$filter") @DefaultValue(StringUtils.EMPTY) final String filter,
        @QueryParam("$orderby") @DefaultValue(StringUtils.EMPTY) final String orderby,
        @QueryParam("$skiptoken") @DefaultValue(StringUtils.EMPTY) final String skiptoken) {

    try {
        final Accept acceptType;
        if (StringUtils.isNotBlank(format)) {
            acceptType = Accept.valueOf(format.toUpperCase());
        } else {
            acceptType = Accept.parse(accept, version);
        }

        final String location = uriInfo.getRequestUri().toASCIIString();
        try {
            // search for function ...
            final InputStream func = FSManager.instance(version).readFile(name, acceptType);
            return xml.createResponse(location, func, null, acceptType);
        } catch (NotFoundException e) {
            if (acceptType == Accept.XML || acceptType == Accept.TEXT) {
                throw new UnsupportedMediaTypeException("Unsupported media type");
            }

            // search for entitySet ...
            final String basePath = name + File.separatorChar;

            final StringBuilder builder = new StringBuilder();
            builder.append(basePath);

            if (StringUtils.isNotBlank(orderby)) {
                builder.append(Constants.get(version, ConstantKey.ORDERBY)).append(File.separatorChar)
                        .append(orderby).append(File.separatorChar);
            }

            if (StringUtils.isNotBlank(filter)) {
                builder.append(Constants.get(version, ConstantKey.FILTER)).append(File.separatorChar)
                        .append(filter.replaceAll("/", "."));
            } else if (StringUtils.isNotBlank(skiptoken)) {
                builder.append(Constants.get(version, ConstantKey.SKIP_TOKEN)).append(File.separatorChar)
                        .append(skiptoken);
            } else {
                builder.append(
                        metadata.getEntitySet(name).isSingleton() ? Constants.get(version, ConstantKey.ENTITY)
                                : Constants.get(version, ConstantKey.FEED));
            }

            final InputStream feed = FSManager.instance(version).readFile(builder.toString(), Accept.ATOM);

            final ResWrap<EntitySet> container = atomDeserializer.toEntitySet(feed);

            setInlineCount(container.getPayload(), count);

            final ByteArrayOutputStream content = new ByteArrayOutputStream();
            final OutputStreamWriter writer = new OutputStreamWriter(content, Constants.ENCODING);

            // -----------------------------------------------
            // Evaluate $skip and $top
            // -----------------------------------------------
            List<Entity> entries = new ArrayList<Entity>(container.getPayload().getEntities());

            if (StringUtils.isNotBlank(skip)) {
                entries = entries.subList(Integer.valueOf(skip), entries.size());
            }

            if (StringUtils.isNotBlank(top)) {
                entries = entries.subList(0, Integer.valueOf(top));
            }

            container.getPayload().getEntities().clear();
            container.getPayload().getEntities().addAll(entries);
            // -----------------------------------------------

            if (acceptType == Accept.ATOM) {
                atomSerializer.write(writer, container);
            } else {
                jsonSerializer.write(writer, container);
            }
            writer.flush();
            writer.close();

            return xml.createResponse(location, new ByteArrayInputStream(content.toByteArray()),
                    Commons.getETag(basePath, version), acceptType);
        }
    } catch (Exception e) {
        return xml.createFaultResponse(accept, e);
    }
}

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  w  w w  . jav  a 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:org.apache.olingo.fit.utils.XMLUtilities.java

@Override
public InputStream readEntities(final List<String> links, final String linkName, final String next,
        final boolean forceFeed) throws Exception {

    if (links.isEmpty()) {
        throw new NotFoundException();
    }/*from  w w w  . ja v a2  s.  co m*/

    final Charset encoding = Charset.forName("UTF-8");

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final OutputStreamWriter writer = new OutputStreamWriter(bos, encoding);

    writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>".toCharArray());

    if (forceFeed || links.size() > 1) {
        // build a feed

        writer.write(("<feed xml:base=\"" + Constants.get(ConstantKey.DEFAULT_SERVICE_URL) + "\" "
                + "xmlns=\"http://www.w3.org/2005/Atom\" "
                + "xmlns:d=\"http://schemas.microsoft.com/ado/2007/08/dataservices\" "
                + "xmlns:m=\"http://schemas.microsoft.com/ado/2007/08/dataservices/metadata\">").toCharArray());

        writer.write(("<id>" + Constants.get(ConstantKey.DEFAULT_SERVICE_URL) + "entityset(entityid)/"
                + linkName + "</id>").toCharArray());

        writer.write(("<title type=\"text\">" + linkName + "</title>").toCharArray());
        writer.write("<updated>2014-03-03T13:40:49Z</updated>".toCharArray());
        writer.write(
                ("<link rel=\"self\" title=\"" + linkName + "\" href=\"" + linkName + "\" />").toCharArray());
    }

    for (String link : links) {
        try {
            final Map.Entry<String, String> uri = Commons.parseEntityURI(link);

            final XMLElement entry = extractElement(
                    getEventReader(readEntity(uri.getKey(), uri.getValue(), Accept.ATOM).getValue()), null,
                    Collections.<String>singletonList("entry"), 0, 1, 1).getValue();

            IOUtils.copy(entry.toStream(), writer, encoding);
        } catch (Exception e) {
            // log and ignore link
            LOG.warn("Error parsing uri {}", link, e);
        }
    }

    if (forceFeed || links.size() > 1) {

        if (StringUtils.isNotBlank(next)) {
            writer.write(String.format("<link rel=\"next\" href=\"%s\" />", next).toCharArray());
        }

        writer.write("</feed>".toCharArray());
    }

    writer.flush();
    writer.close();

    return new ByteArrayInputStream(bos.toByteArray());
}

From source file:io.mapzone.arena.share.ShareInfoServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {/*from   w ww  . j  av a 2s.c o  m*/
        // log.info( "QueryString: " + req.getQueryString() );
        // Enumeration<String> headerNames = req.getHeaderNames();
        // while (headerNames.hasMoreElements()) {
        // String header = headerNames.nextElement();
        // log.info( "HEADER '" + header + "': '" + req.getHeader( header ) + "'"
        // );
        // }

        if (req.getParameterMap().isEmpty() || StringUtils.isBlank(req.getParameter(PARAMETER_LAYERS))
                || StringUtils.isBlank(req.getParameter(PARAMETER_BBOX))) {
            resp.sendError(400, "No parameters found! Please specify at least '" + PARAMETER_LAYERS + "' and '"
                    + PARAMETER_BBOX + "'.");
            return;
        }

        final String layers = req.getParameter(PARAMETER_LAYERS);
        final String bbox = req.getParameter(PARAMETER_BBOX);
        final String authToken = req.getParameter(PARAMETER_AUTHTOKEN);

        resp.setStatus(HttpStatus.SC_OK);
        resp.setContentType("text/html;charset=utf-8");

        final String projectName = ArenaConfig.getAppTitle();
        // FIXME add the project description here
        final String description = ArenaConfig.getAppTitle();
        final String arenaUrl = ArenaPlugin.instance().config().getProxyUrl() + ArenaPlugin.ALIAS;
        final StringBuilder imageUrl = new StringBuilder(ArenaPlugin.instance().config().getProxyUrl());
        imageUrl.append(GeoServerStarter.ALIAS);
        imageUrl.append(
                "?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&FORMAT=image%2Fpng&CRS=EPSG%3A3857&STYLES=&WIDTH=1200&HEIGHT=630");
        imageUrl.append("&LAYERS=").append(URLEncoder.encode(layers, "utf-8"));
        imageUrl.append("&BBOX=").append(URLEncoder.encode(bbox, "utf-8"));
        if (!StringUtils.isBlank(authToken)) {
            imageUrl.append("&authToken=").append(URLEncoder.encode(authToken, "utf-8"));
        }

        //            log.info( "IMGURL" + imageUrl.toString() );
        // convert addresses to result json
        OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream());
        writer.write("<html>\n");
        writer.write(" <head>\n");
        writer.write("  <title>mapzone - " + projectName + "</title>\n");
        writer.write("  <meta name='author' content='mapzone' />\n");
        writer.write("  <meta name='description' content='" + description + "' />\n");
        writer.write(
                "  <meta name='keywords' content='location, geo, web, osm, map, maps, styling, wms, csv, xls, georeference, geofence, geocode' />\n");
        writer.write("  <meta name='robots' content='index,follow' />\n");
        writer.write("  <meta name='audience' content='all' />\n");
        // writer.write( " <meta name='revisit-after' content='5 days' />\n");
        // facebook/opengraph
        writer.write("  <meta property='og:locality' content='Leipzig'/>\n");
        writer.write("  <meta property='og:country-name' content='Germany'/>\n");
        writer.write("  <meta property='og:latitude' content='51.32794'/>\n");
        writer.write("  <meta property='og:longitude' content='12.33126'/>\n");
        writer.write("  <meta property='og:image:url' content='" + imageUrl.toString() + "' />\n");
        writer.write("  <meta property='og:image:type' content='image/png' />\n");
        writer.write("  <meta property='og:image:width' content='1200' />\n");
        writer.write("  <meta property='og:image:height' content='630' />\n");
        writer.write("  <meta property='og:type' content='article' />\n");
        writer.write("  <meta property='og:site_name' content='mapzone - " + projectName + "' />\n");
        // wird grad nicht von Facebook untersttzt
        // writer.write( " <meta property='fb:app_id' content='1754931524765083'
        // />\n");
        // writer.write( " <meta property='fb:admins' content='739545402735248'
        // />\n");
        writer.write(
                "  <meta property='article:publisher' content='https://www.facebook.com/mapzoneio-1401853630109662' />\n");
        writer.write("  <meta property='article:author' content='https://www.facebook.com/stundzig' />\n");

        // writer.write( " <meta property='og:url' content='" + arenaUrl + "'
        // />\n");

        // perform a redirect after 10ms
        writer.write("  <script type='text/javascript'>window.setTimeout(function(){window.location.href = '"
                + arenaUrl + "'; },10);</script>\n");
        writer.write(" </head>\n");
        writer.write(" <body>\n");
        // writer.write( " <iframe src='" + arenaUrl
        // + "' width='100%' height='520' frameborder='0'
        // allowfullscreen='allowfullscreen'></iframe>\n");
        writer.write(" </body>\n");
        writer.write("<head>\n");
        writer.flush();
        writer.close();

        EventManager.instance().publish(new ServletRequestEvent(getServletContext(), req));
    } catch (Exception e) {
        e.printStackTrace();
        resp.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}