Example usage for java.io BufferedWriter append

List of usage examples for java.io BufferedWriter append

Introduction

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

Prototype

public Writer append(CharSequence csq) throws IOException 

Source Link

Document

Appends the specified character sequence to this writer.

Usage

From source file:de.dfki.km.perspecting.obie.connection.RDFTripleParser.java

/**
 * /*from www. jav a  2 s .  c  om*/
 * @param input
 * @param mimetype
 * @param sessionPath
 * @param absoluteBaseURI
 * @return
 * @throws Exception
 */
public TripleStats parseTriples(final InputStream[] input, final MediaType rdf_mimetype, final File sessionPath,
        final String absoluteBaseURI, final MediaType file_mimetype) throws Exception {

    final TripleStats stats = new TripleStats();
    //      int count = 0;

    new File(sessionPath.getAbsolutePath() + "/dump/").mkdirs();

    stats.datatypeProps = new File(sessionPath.getAbsolutePath() + "/dump/datatypeProperties.lst");
    stats.objectProps = new File(sessionPath.getAbsolutePath() + "/dump/objectProperties.lst");

    stats.datatypeProps.deleteOnExit();
    stats.objectProps.deleteOnExit();

    stats.datatypeProps.setReadable(true, false);
    stats.objectProps.setReadable(true, false);

    if (stats.datatypeProps.exists() && stats.objectProps.exists()) {
        return stats;
    }

    // stats.literalLanguageList = new File(sessionPath +
    // "/dump/literals_language.lst");

    // final BufferedWriter literalLanguageWriter = new BufferedWriter(new
    // FileWriter(
    // stats.literalLanguageList, true));

    final BufferedWriter datatypePropertiesWriter = new BufferedWriter(
            new FileWriter(stats.datatypeProps, false));

    final BufferedWriter objectPropertiesWriter = new BufferedWriter(new FileWriter(stats.objectProps, false));

    final ArrayList<Callable<Boolean>> threads = new ArrayList<Callable<Boolean>>();

    int sourceCount = 0;

    for (final InputStream stream : input) {

        final String source = (++sourceCount) + "";
        log.info("Parsing: " + source + " from ( " + input.length + " )");

        final RDFParser parser = getParser(rdf_mimetype);
        parser.setRDFHandler(new RDFHandler() {

            long tripleCount = 0;

            @Override
            public void startRDF() throws RDFHandlerException {
                log.info("Start parsing RDF triples");
            }

            @Override
            public void handleStatement(Statement stmt) throws RDFHandlerException {
                try {

                    tripleCount++;

                    if (tripleCount % 10000 == 0) {
                        log.info(source + ": Parsed " + tripleCount + " RDF triples");
                    }
                    // get triple components
                    String p = stmt.getPredicate().toString();
                    String s = stmt.getSubject().toString();
                    String o = stmt.getObject().toString();

                    // test URIs
                    if (s.length() > URISIZE) {
                        log.warning("Skipping too long subject " + s);
                        return;
                    }

                    if (p.length() > URISIZE) {
                        log.warning("Skipping too long predicate " + p);
                        return;
                    }

                    if (stmt.getSubject() instanceof URI)
                        s = fixJavaURI(s);

                    p = fixJavaURI(p);

                    // check object properties URIs
                    if (stmt.getObject() instanceof URI) {
                        if (o.length() > URISIZE) {
                            return;
                        } else {
                            o = fixJavaURI(o);
                            appendObjectTriple(s, p, o);
                        }
                    } else if (stmt.getObject() instanceof Literal) {
                        o = stmt.getObject().stringValue().replaceAll("[\n\t\\\\\"]", "").trim();

                        if (o.length() < 2 || o.length() > 100) {
                            return;
                        }

                        appendLiteralTriple(s, p, o, ((Literal) stmt.getObject()).getLanguage());
                    } else {
                        log.warning("Skipping bad triple " + stmt);
                    }

                } catch (Exception e) {
                    log.log(Level.SEVERE, "Error in parsing: " + source, e);
                }

            }

            /**
             * Encodes characters invalid (e.g. "|") in the uri and returns
             * the encoded string.
             * 
             * @param uri
             *            uri to enctode
             * @return encoded uri
             */
            private String fixJavaURI(String uri) {

                try {
                    new java.net.URI(uri);
                } catch (URISyntaxException e) {
                    String badChar = Character.toString(uri.charAt(e.getIndex()));
                    try {
                        log.fine("Fixing bad uri: " + uri);
                        return fixJavaURI(uri.replace(badChar, URLEncoder.encode(badChar, "utf-8")));
                    } catch (UnsupportedEncodingException e1) {
                        throw new RuntimeException(e1);
                    }
                }

                return uri;
            }

            private void appendLiteralTriple(String subject, String predicate, String literal, String language)
                    throws IOException {

                if (language == null) {
                    language = ALL;
                }

                synchronized (SEMAPHOR) {
                    stats.datatypePropsSize++;
                    datatypePropertiesWriter.write(RDFTripleParser.encloseCharacterString(subject));
                    datatypePropertiesWriter.append(',');
                    datatypePropertiesWriter.write(RDFTripleParser.encloseCharacterString(predicate));
                    datatypePropertiesWriter.append(',');
                    datatypePropertiesWriter.write(RDFTripleParser.encloseCharacterString(literal));

                    datatypePropertiesWriter.append(',');
                    datatypePropertiesWriter
                            .write(Integer.toString(hashing.hash(literal.toLowerCase(Locale.US))));

                    datatypePropertiesWriter.newLine();
                }

            }

            private void appendObjectTriple(String subject, String predicate, String object)
                    throws IOException {

                synchronized (SEMAPHOR) {

                    stats.objectPropsSize++;

                    objectPropertiesWriter.write(RDFTripleParser.encloseCharacterString(subject));
                    objectPropertiesWriter.append(',');
                    objectPropertiesWriter.write(RDFTripleParser.encloseCharacterString(predicate));
                    objectPropertiesWriter.append(',');
                    objectPropertiesWriter.write(RDFTripleParser.encloseCharacterString(object));
                    objectPropertiesWriter.newLine();
                }

            }

            @Override
            public void handleNamespace(String arg0, String arg1) throws RDFHandlerException {
            }

            @Override
            public void handleComment(String arg0) throws RDFHandlerException {
            }

            @Override
            public void endRDF() throws RDFHandlerException {
                log.info("Finished parsing RDF triples " + tripleCount + " RDF triples");

            }
        });

        threads.add(new Callable<Boolean>() {
            /*
             * (non-Javadoc)
             * 
             * @see java.util.concurrent.Callable#call()
             */
            @Override
            public Boolean call() throws Exception {

                InputStream unpackedStream = getStream(stream, file_mimetype);
                try {
                    if (absoluteBaseURI != null)
                        parser.parse(unpackedStream, absoluteBaseURI);
                    else
                        parser.parse(unpackedStream, BASEURI);
                } catch (Exception e) {
                    new Exception("Error during parsing " + source + " with mimetype " + file_mimetype, e)
                            .printStackTrace();
                    unpackedStream.close();
                    return false;
                }
                unpackedStream.close();

                return true;
            }
        });

    }

    for (Future<Boolean> future : pool.invokeAll(threads)) {
        if (!future.get()) {
            throw new Exception("error occured during parsing");
        }
    }

    // literalLanguageWriter.close();
    objectPropertiesWriter.close();
    datatypePropertiesWriter.close();

    return stats;
}

From source file:dylemator.DylematorUI.java

private void writeReport() {

    SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy");
    String date = sdf.format(new Date());
    String[] questionsFile = this.file.getName().split("\\.");
    boolean newDate = false;
    File resultsFile = new File("Odpowiedzi_" + questionsFile[0] + "_" + date + ".csv");
    if (resultsFile.exists() == false) {
        newDate = true;//from   ww w.  j  av a2  s.  c  o  m
    }

    displayCenteredText("KONIEC BADANIA.\r\nDZIKUJEMY ZA UDZIA?.");

    try {

        BufferedWriter bufferedWriter = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(resultsFile, true)));
        StringBuffer sb = new StringBuffer();
        if (newDate) {
            String[] fields = new String[] { "Kod osoby", "Data badania", "Imi", "Nazwisko", "Wiek", "Pe",
                    "Miejsce zamieszkania", "Praworczno", "Lata edukacji", "Urazy gowy",
                    "Leczenie neur.", "Leczenie psych.", "Zaywa leki psych.", "Kopoty z pam.",
                    "Uzalenienia", "Lek zamienny", "Brownie", "Malownicza trasa", "Prysznic", "Ankieta",
                    "Pocig czy autobus", "Kadka", "Typ decyzji", "?d podwodna", "Typ decyzji",
                    "Paczce dziecko", "Typ decyzji", "Wybr Zofii", "Typ decyzji", "Test szczepionki",
                    "Typ decyzji", "Zapobieganie zaraeniu", "Typ decyzji", "Wagonik (wersja standardowa)",
                    "Typ decyzji", "Trujcy dym (wersja standardowa)", "Typ decyzji", "Polityka szczepie",
                    "Typ decyzji", "Oczy", "Typ decyzji", "Podatki", "Typ decyzji",
                    "Wskazwka dotyczca inwestowania", "Typ decyzji" };
            String fieldStr = StringUtils.join(fields, ";");
            sb.append(fieldStr).append("\r\n");
        }
        String[] userData = new String[] { ud.getCode(), date, ud.getName(), ud.getSurname(),
                new Integer(ud.getAge()).toString(), new Integer(ud.getGender()).toString(),
                new Integer(ud.getPlace()).toString(), new Integer(ud.getHandedness()).toString(),
                new Integer(ud.getEducationYears()).toString(),
                // Interview
                new Integer(ud.getHeadInjuries()).toString(), new Integer(ud.getNeurotreatment()).toString(),
                new Integer(ud.getPsychotreatment()).toString(), new Integer(ud.getOnDrugs()).toString(),
                new Integer(ud.getMemoryPb()).toString(), new Integer(ud.getAddictions()).toString(),

                new Long(this.getResults("nonmoral", 0).getSeconds()).toString(),
                new Long(this.getResults("nonmoral", 1).getSeconds()).toString(),
                new Long(this.getResults("nonmoral", 2).getSeconds()).toString(),
                new Long(this.getResults("nonmoral", 3).getSeconds()).toString(),
                new Long(this.getResults("nonmoral", 4).getSeconds()).toString(),
                new Long(this.getResults("nonmoral", 5).getSeconds()).toString(),

                new Long(this.getResults("personal", 0).getSeconds()).toString(),
                this.getResults("personal", 0).getAnswerType(),
                new Long(this.getResults("personal", 1).getSeconds()).toString(),
                this.getResults("personal", 1).getAnswerType(),
                new Long(this.getResults("personal", 2).getSeconds()).toString(),
                this.getResults("personal", 2).getAnswerType(),
                new Long(this.getResults("personal", 3).getSeconds()).toString(),
                this.getResults("personal", 3).getAnswerType(),
                new Long(this.getResults("personal", 4).getSeconds()).toString(),
                this.getResults("personal", 4).getAnswerType(),
                new Long(this.getResults("personal", 5).getSeconds()).toString(),
                this.getResults("personal", 5).getAnswerType(),

                new Long(this.getResults("nonpersonal", 0).getSeconds()).toString(),
                this.getResults("nonpersonal", 0).getAnswerType(),
                new Long(this.getResults("nonpersonal", 1).getSeconds()).toString(),
                this.getResults("nonpersonal", 1).getAnswerType(),
                new Long(this.getResults("nonpersonal", 2).getSeconds()).toString(),
                this.getResults("nonpersonal", 2).getAnswerType(),
                new Long(this.getResults("nonpersonal", 3).getSeconds()).toString(),
                this.getResults("personal", 3).getAnswerType(),
                new Long(this.getResults("nonpersonal", 4).getSeconds()).toString(),
                this.getResults("nonpersonal", 4).getAnswerType(),
                new Long(this.getResults("nonpersonal", 5).getSeconds()).toString(),
                this.getResults("nonpersonal", 5).getAnswerType()

        };

        String userDataStr = StringUtils.join(userData, ";");
        sb.append(userDataStr);
        sb.append("\r\n");
        bufferedWriter.append(sb);
        bufferedWriter.flush();
        bufferedWriter.close();
        sb.delete(0, sb.length());
    } catch (IOException ex) {
        Logger.getLogger(DylematorUI.class.getName()).log(Level.SEVERE, null, ex);
    }

    //this.textArea.append("\nCakowity czas: " + totalTimeStr + " sek.\n");
}

From source file:org.ofbiz.magento.CatalogServices.java

public static Map<String, Object> getMagentoProducts(DispatchContext dctx, Map<String, ?> context) {
    Map<String, Object> result = ServiceUtil.returnSuccess();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    File file = new File(System.getProperty("ofbiz.home") + "/runtime/tmp/MagentoProductInfo.csv");

    try {/*  w  ww  .ja  v a2s .c om*/
        BufferedWriter output = new BufferedWriter(new FileWriter(file));
        MagentoClient magentoClient = new MagentoClient(dispatcher, delegator);

        List<CatalogProductEntity> catalogProductEntityList = magentoClient.getMagentoProducts();
        List<String> csvFields = new ArrayList<String>();
        csvFields.add("Product Id");
        csvFields.add("SKU");
        csvFields.add("Product Type Id");
        csvFields.add("Product Name");
        csvFields.add("Bundle Parent Id");
        csvFields.add("Configurable Parent Id");
        csvFields.add("Grouped Parent Id");
        csvFields.add("Description");
        csvFields.add("Long Description");
        csvFields.add("Price");
        csvFields.add("Tax Class Id");
        csvFields.add("Category Ids");
        csvFields.add("Web Site Ids");
        csvFields.add("Thumbnail Image Url");
        csvFields.add("Small Image Url");
        csvFields.add("Original Image Url");
        csvFields.add("Url Key");
        csvFields.add("Url Path");
        csvFields.add("Meta Description");
        csvFields.add("Meta Keyword");
        csvFields.add("Meta Title");
        csvFields.add("Status");
        csvFields.add("Special From Date");
        csvFields.add("Special Price");
        csvFields.add("Created At");
        csvFields.add("Updated At");

        String header = StringUtil.join(csvFields, ",");
        output.write(header);
        String fieldValue = "";

        for (CatalogProductEntity catalogProductEntity : catalogProductEntityList) {
            CatalogProductReturnEntity productInfo = magentoClient
                    .getProductInfo(catalogProductEntity.getProductId());
            String productId = catalogProductEntity.getProductId();
            String productTypeId = productInfo.getTypeId();
            Map<String, String> record = new HashMap<String, String>();
            CatalogProductImageEntityArray productImageInfoList = magentoClient
                    .getProductImageInfoList(productId);
            List<CatalogProductImageEntity> catalogProductImageEntityList = productImageInfoList
                    .getComplexObjectArray();
            for (CatalogProductImageEntity catalogProductImageEntity : catalogProductImageEntityList) {
                for (String imageType : catalogProductImageEntity.getTypes().getComplexObjectArray()) {
                    if ("thumbnail".equalsIgnoreCase(imageType)) {
                        record.put("Thumbnail Image Url", catalogProductImageEntity.getUrl());
                    }
                    if ("small_image".equalsIgnoreCase(imageType)) {
                        record.put("Small Image Url", catalogProductImageEntity.getUrl());
                    }
                    if ("image".equalsIgnoreCase(imageType)) {
                        record.put("Original Image Url", catalogProductImageEntity.getUrl());
                    }
                }
            }
            if ("simple".equalsIgnoreCase(productTypeId) || "virtual".equalsIgnoreCase(productTypeId)) {
                List<CatalogProductRelationEntity> catalogProductRelationEntityList = magentoClient
                        .getParentProduct(productId);
                for (CatalogProductRelationEntity catalogProductRelationEntity : catalogProductRelationEntityList) {
                    if ("bundle".equalsIgnoreCase(catalogProductRelationEntity.getParentType())) {
                        record.put("Bundle Parent Id", catalogProductRelationEntity.getParentId());
                    }
                    if ("configurable".equalsIgnoreCase(catalogProductRelationEntity.getParentType())) {
                        record.put("Configurable Parent Id", catalogProductRelationEntity.getParentId());
                    }
                    if ("grouped".equalsIgnoreCase(catalogProductRelationEntity.getParentType())) {
                        record.put("Grouped Parent Id", catalogProductRelationEntity.getParentId());
                    }
                }
            }

            record.put("Product Id", productId);
            record.put("SKU", productInfo.getSku());
            record.put("Product Type Id", productTypeId);
            record.put("Product Name", productInfo.getName());
            record.put("Description", productInfo.getShortDescription());
            record.put("Long Description", productInfo.getDescription());
            record.put("Price", productInfo.getPrice());
            record.put("Tax Class Id", productInfo.getTaxClassId());
            record.put("Category Ids",
                    catalogProductEntity.getCategoryIds().getComplexObjectArray().toString());
            record.put("Web Site Ids", catalogProductEntity.getWebsiteIds().getComplexObjectArray().toString());
            record.put("Url Key", productInfo.getUrlKey());
            record.put("Url Path", productInfo.getUrlPath());
            record.put("Meta Description", productInfo.getMetaDescription());
            record.put("Meta Keyword", productInfo.getMetaKeyword());
            record.put("Meta Title", productInfo.getMetaTitle());
            record.put("Status", productInfo.getStatus());
            record.put("Special From Date", productInfo.getSpecialFromDate());
            record.put("Special Price", productInfo.getSpecialPrice());
            record.put("Created At", productInfo.getCreatedAt());
            record.put("Updated At", productInfo.getUpdatedAt());

            StringBuffer row = new StringBuffer();
            for (String fieldName : csvFields) {
                fieldValue = record.get(fieldName);
                if (UtilValidate.isNotEmpty(fieldValue)) {
                    fieldValue = fieldValue.replace("\"", "&quot;");
                } else {
                    fieldValue = "NA";
                }
                row = row.append("\"" + fieldValue + "\"");
                row = row.append(",");
            }
            output.append("\n");
            output.append(row);
        }
        output.close();
    } catch (IOException e) {
        Debug.logInfo(e.getMessage(), module);
    } catch (Exception e) {
        Debug.logInfo(e.getMessage(), module);
    }
    return result;
}