Example usage for java.io Writer append

List of usage examples for java.io Writer append

Introduction

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

Prototype

public Writer append(char c) throws IOException 

Source Link

Document

Appends the specified character to this writer.

Usage

From source file:com.joliciel.csvLearner.CSVLearner.java

private void generateEventFile(File eventFile, GenericEvents events) throws IOException {
    eventFile.delete();/*from  w  w  w  .  ja v a2s. c  om*/
    eventFile.createNewFile();
    Writer eventFileWriter = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(eventFile, false), "UTF8"));
    try {
        for (GenericEvent event : events) {
            eventFileWriter.append(event.getIdentifier() + "\t");
            for (int i = 0; i < event.getFeatures().size(); i++) {
                eventFileWriter.append(event.getFeatures().get(i) + "="
                        + CSVFormatter.format(event.getWeights().get(i)) + "\t");
            }
            eventFileWriter.append(event.getOutcome());
            eventFileWriter.append("\n");
        }
    } finally {
        eventFileWriter.close();
    }
}

From source file:gov.utah.dts.det.ccl.service.impl.FacilityServiceImpl.java

private void addCsvField(Writer writer, String field) throws IOException {
    writer.append(",\"");
    if (!StringUtils.isBlank(field)) {
        writer.append(field.replaceAll("\"", "\"\"")); // escape quotes with double quotes.
    }/*from ww  w  .  j a  v a2  s .  c  o m*/
    writer.append("\"");
}

From source file:com.dm.material.dashboard.candybar.fragments.SettingsFragment.java

public void rebuildPremiumRequest() {
    new AsyncTask<Void, Void, Boolean>() {

        MaterialDialog dialog;/*from  w ww. j  ava  2 s.co m*/
        StringBuilder sb;
        List<Request> requests;
        String zipFile;

        String log = "";

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            sb = new StringBuilder();

            MaterialDialog.Builder builder = new MaterialDialog.Builder(getActivity());
            builder.content(R.string.premium_request_rebuilding);
            builder.cancelable(false);
            builder.canceledOnTouchOutside(false);
            builder.progress(true, 0);
            builder.progressIndeterminateStyle(true);
            dialog = builder.build();
            dialog.show();
        }

        @Override
        protected Boolean doInBackground(Void... voids) {
            while (!isCancelled()) {
                try {
                    Thread.sleep(1);
                    Database database = new Database(getActivity());
                    File directory = getActivity().getCacheDir();
                    File appFilter = new File(directory.toString() + "/" + "appfilter.xml");

                    requests = database.getPremiumRequest(null);

                    if (requests.size() == 0)
                        return true;

                    sb.append(DeviceHelper.getDeviceInfo(getActivity()));

                    List<String> files = new ArrayList<>();
                    Writer out = new BufferedWriter(
                            new OutputStreamWriter(new FileOutputStream(appFilter), "UTF8"));

                    for (int i = 0; i < requests.size(); i++) {
                        String activity = requests.get(i).getActivity();
                        String packageName = activity.substring(0, activity.lastIndexOf("/"));
                        Request request = new Request(requests.get(i).getName(), packageName, activity, true);

                        String string = RequestHelper.writeRequest(request);
                        sb.append(string);
                        sb.append("\n").append("Order Id : ").append(requests.get(i).getOrderId());
                        sb.append("\n").append("Product Id : ").append(requests.get(i).getProductId());

                        String string1 = RequestHelper.writeAppFilter(request);
                        out.append(string1);

                        Bitmap bitmap = DrawableHelper.getHighQualityIcon(getActivity(),
                                request.getPackageName());

                        String icon = FileHelper.saveIcon(directory, bitmap, request.getName());
                        if (icon != null)
                            files.add(icon);
                    }

                    out.flush();
                    out.close();
                    files.add(appFilter.toString());

                    zipFile = directory.toString() + "/" + "icon_request.zip";
                    FileHelper.createZip(files, zipFile);
                    return true;
                } catch (Exception e) {
                    log = e.toString();
                    LogUtil.e(Log.getStackTraceString(e));
                    return false;
                }
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            dialog.dismiss();
            if (aBoolean) {
                if (requests.size() == 0) {
                    Toast.makeText(getActivity(), R.string.premium_request_rebuilding_empty, Toast.LENGTH_LONG)
                            .show();
                    return;
                }

                String subject = "Rebuild Premium Icon Request "
                        + getActivity().getResources().getString(R.string.app_name);

                Request request = new Request(subject, sb.toString(), zipFile);
                IntentChooserFragment.showIntentChooserDialog(getActivity().getSupportFragmentManager(),
                        request);
            } else {
                Toast.makeText(getActivity(), "Failed " + log, Toast.LENGTH_LONG).show();
            }
            dialog = null;
            sb.setLength(0);
        }

    }.execute();
}

From source file:com.cloudera.sqoop.orm.ClassWriter.java

/**
 * Generate the ORM code for the class.// w w w .ja  v a2 s  .c o m
 */
public void generate() throws IOException {
    Map<String, Integer> columnTypes;

    if (null != tableName) {
        // We're generating a class based on a table import.
        columnTypes = connManager.getColumnTypes(tableName);
    } else {
        // This is based on an arbitrary query.
        String query = this.options.getSqlQuery();
        if (query.indexOf(SqlManager.SUBSTITUTE_TOKEN) == -1) {
            throw new IOException("Query [" + query + "] must contain '" + SqlManager.SUBSTITUTE_TOKEN
                    + "' in WHERE clause.");
        }

        columnTypes = connManager.getColumnTypesForQuery(query);
    }

    String[] colNames = options.getColumns();
    if (null == colNames) {
        if (null != tableName) {
            // Table-based import. Read column names from table.
            colNames = connManager.getColumnNames(tableName);
        } else {
            // Infer/assign column names for arbitrary query.
            colNames = connManager.getColumnNamesForQuery(this.options.getSqlQuery());
        }
    } else {
        // These column names were provided by the user. They may not be in
        // the same case as the keys in the columnTypes map. So make sure
        // we add the appropriate aliases in that map.
        for (String userColName : colNames) {
            for (Map.Entry<String, Integer> typeEntry : columnTypes.entrySet()) {
                String typeColName = typeEntry.getKey();
                if (typeColName.equalsIgnoreCase(userColName) && !typeColName.equals(userColName)) {
                    // We found the correct-case equivalent.
                    columnTypes.put(userColName, typeEntry.getValue());
                    // No need to continue iteration; only one could match.
                    // Also, the use of put() just invalidated the iterator.
                    break;
                }
            }
        }
    }

    // Translate all the column names into names that are safe to
    // use as identifiers.
    String[] cleanedColNames = cleanColNames(colNames);

    for (int i = 0; i < colNames.length; i++) {
        // Make sure the col->type mapping holds for the
        // new identifier name, too.
        String identifier = cleanedColNames[i];
        String col = colNames[i];
        columnTypes.put(identifier, columnTypes.get(col));
    }

    // The db write() method may use column names in a different
    // order. If this is set in the options, pull it out here and
    // make sure we format the column names to identifiers in the same way
    // as we do for the ordinary column list.
    String[] dbWriteColNames = options.getDbOutputColumns();
    String[] cleanedDbWriteColNames = null;
    if (null == dbWriteColNames) {
        cleanedDbWriteColNames = cleanedColNames;
    } else {
        cleanedDbWriteColNames = cleanColNames(dbWriteColNames);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("selected columns:");
        for (String col : cleanedColNames) {
            LOG.debug("  " + col);
        }

        if (cleanedDbWriteColNames != cleanedColNames) {
            // dbWrite() has a different set of columns than the rest of the
            // generators.
            LOG.debug("db write column order:");
            for (String dbCol : cleanedDbWriteColNames) {
                LOG.debug("  " + dbCol);
            }
        }
    }

    // Generate the Java code.
    StringBuilder sb = generateClassForColumns(columnTypes, cleanedColNames, cleanedDbWriteColNames);

    // Write this out to a file in the jar output directory.
    // We'll move it to the user-visible CodeOutputDir after compiling.
    String codeOutDir = options.getJarOutputDir();

    // Get the class name to generate, which includes package components.
    String className = new TableClassName(options).getClassForTable(tableName);
    // Convert the '.' characters to '/' characters.
    String sourceFilename = className.replace('.', File.separatorChar) + ".java";
    String filename = codeOutDir + sourceFilename;

    if (LOG.isDebugEnabled()) {
        LOG.debug("Writing source file: " + filename);
        LOG.debug("Table name: " + tableName);
        StringBuilder sbColTypes = new StringBuilder();
        for (String col : colNames) {
            Integer colType = columnTypes.get(col);
            sbColTypes.append(col + ":" + colType + ", ");
        }
        String colTypeStr = sbColTypes.toString();
        LOG.debug("Columns: " + colTypeStr);
        LOG.debug("sourceFilename is " + sourceFilename);
    }

    compileManager.addSourceFile(sourceFilename);

    // Create any missing parent directories.
    File file = new File(filename);
    File dir = file.getParentFile();
    if (null != dir && !dir.exists()) {
        boolean mkdirSuccess = dir.mkdirs();
        if (!mkdirSuccess) {
            LOG.debug("Could not create directory tree for " + dir);
        }
    }

    OutputStream ostream = null;
    Writer writer = null;
    try {
        ostream = new FileOutputStream(filename);
        writer = new OutputStreamWriter(ostream);
        writer.append(sb.toString());
    } finally {
        if (null != writer) {
            try {
                writer.close();
            } catch (IOException ioe) {
                // ignored because we're closing.
            }
        }

        if (null != ostream) {
            try {
                ostream.close();
            } catch (IOException ioe) {
                // ignored because we're closing.
            }
        }
    }
}

From source file:com.flaptor.indextank.util.FlaptorHtmlEntities.java

/**
 * <p>//from  ww  w .  j a  va2 s  .  c om
 * Escapes the characters in the <code>String</code> passed and writes the result to the <code>Writer</code>
 * passed.
 * </p>
 * 
 * @param writer
 *            The <code>Writer</code> to write the results of the escaping to. Assumed to be a non-null value.
 * @param str
 *            The <code>String</code> to escape. Assumed to be a non-null value.
 * @throws IOException
 *             when <code>Writer</code> passed throws the exception from calls to the {@link Writer#write(int)}
 *             methods.
 * 
 * @see #escape(String)
 * @see Writer
 */
public void escape(Writer dest, String str, int start, int offset) throws IOException {
    for (int i = start; i < offset; i++) {
        char c = str.charAt(i);
        String entityName = this.entityName(c);
        if (entityName == null) {
            if (c > 0x7F) {
                dest.append("&#");
                dest.append(Integer.toString(c, 10));
                dest.append(';');
            } else {
                dest.append(c);
            }
        } else {
            dest.append('&');
            dest.append(entityName);
            dest.append(';');
        }
    }
}

From source file:org.tolven.app.bean.DataExtractBean.java

private void createTableStatement(Writer out, String table, DataQueryResults dq,
        SQLDialectHandler sqlDialectHandler) throws IOException {
    out.write("CREATE TABLE");
    out.write(" ");
    out.write(table);/*from  w  w w.ja v  a  2 s. c  om*/
    out.write("(");
    boolean firstTime = true;
    for (DataField field : dq.getSelectedFields()) {
        if (firstTime) {
            firstTime = false;
        } else {
            out.append(",\n");
        }
        out.write(sqlDialectHandler.encodeIdentifier(field.getExternal()));
        out.write(' ');
        String columnType = sqlDialectHandler.getColumnType(field.getInternalField());
        out.write(columnType);
        if ("id".equals(field.getInternal())) {
            out.append(" PRIMARY KEY");
        } else if (field.getInternal().endsWith(".id")) {
            out.append(" REFERENCES ");
            out.append(sqlDialectHandler
                    .encodeIdentifier(field.getExternalSegments()[field.getExternalSegments().length - 2]));
            out.append(" (id)");
        }
    }
    out.write(");");
}

From source file:it.doqui.index.ecmengine.business.personalization.multirepository.bootstrap.SchemaBootstrap.java

/**
 * Builds the schema from scratch or applies the necessary patches to the schema.
 *//* ww  w.  j  a v  a 2 s. c  om*/
private void updateSchema(Configuration cfg, Session session, Connection connection) throws Exception {
    boolean create = false;
    try {
        countAppliedPatches(connection);
    } catch (NoSchemaException e) {
        create = true;
    }
    // Get the dialect
    final Dialect dialect = Dialect.getDialect(cfg.getProperties());
    String dialectStr = dialect.getClass().getName();

    if (create) {
        // the applied patch table is missing - we assume that all other tables are missing
        // perform a full update using Hibernate-generated statements
        File tempFile = TempFileProvider.createTempFile("AlfrescoSchemaCreate-" + dialectStr + "-", ".sql");
        SchemaBootstrap.dumpSchemaCreate(cfg, tempFile);
        executeScriptFile(cfg, connection, tempFile, null);
        // execute post-create scripts (not patches)
        for (String scriptUrl : this.postCreateScriptUrls) {
            executeScriptUrl(cfg, connection, scriptUrl);
        }
    } else {
        // Check for scripts that must have been run
        checkSchemaPatchScripts(cfg, session, connection, validateUpdateScriptPatches, false);
        // Execute any pre-auto-update scripts
        checkSchemaPatchScripts(cfg, session, connection, preUpdateScriptPatches, true);

        // Build and execute changes generated by Hibernate
        File tempFile = null;
        Writer writer = null;
        try {
            DatabaseMetadata metadata = new DatabaseMetadata(connection, dialect);
            String[] sqls = cfg.generateSchemaUpdateScript(dialect, metadata);
            if (sqls.length > 0) {
                tempFile = TempFileProvider.createTempFile("AlfrescoSchemaUpdate-" + dialectStr + "-", ".sql");
                writer = new BufferedWriter(new FileWriter(tempFile));
                for (String sql : sqls) {
                    writer.append(sql);
                    writer.append(";\n");
                }
            }
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (Throwable e) {
                }
            }
        }
        // execute if there were changes raised by Hibernate
        if (tempFile != null) {
            executeScriptFile(cfg, connection, tempFile, null);
        }

        // Execute any post-auto-update scripts
        checkSchemaPatchScripts(cfg, session, connection, postUpdateScriptPatches, true);
    }
}

From source file:org.openhab.binding.samsungtv.internal.protocol.RemoteControllerLegacy.java

private void writeInitialInfo(Writer writer, Socket socket) throws RemoteControllerException {
    try {/*  w w  w  .  java2s  .  co m*/
        /* @formatter:off
        *
        * offset value and description
        * ------ ---------------------
        * 0x00   0x00 - datagram type?
        * 0x01   0x0013 - string length (little endian)
        * 0x03   "iphone.iapp.samsung" - string content
        * 0x16   0x0038 - payload size (little endian)
        * 0x18   payload
        *
        * Payload starts with 2 bytes: 0x64 and 0x00, then comes 3 strings
        * encoded with base64 algorithm. Every string is preceded by
        * 2-bytes field containing encoded string length.
        *
        * These three strings are as follow:
        *
        * remote control device IP, unique ID  value to distinguish
        * controllers, name  it will be displayed as controller name.
        *
        * @formatter:on
        */

        writer.append((char) 0x00);
        writeString(writer, APP_STRING);
        writeString(writer, createRegistrationPayload(socket.getLocalAddress().getHostAddress()));
        writer.flush();
    } catch (IOException e) {
        throw new RemoteControllerException(e);
    }
}

From source file:org.jahia.tools.maven.plugins.LegalArtifactAggregator.java

private void outputPackageLicenses() {
    SortedSet<PackageMetadata> packageLicenses = new TreeSet<>();
    for (JarMetadata jarMetadata : jarDatabase.values()) {
        for (String packageName : jarMetadata.getPackages()) {
            PackageMetadata packageMetadata = new PackageMetadata();
            packageMetadata.setPackageName(packageName);
            packageMetadata.setJarName(jarMetadata.getName());
            if (jarMetadata.getProject() != null && packageName.contains(jarMetadata.getProject())) {
                for (LicenseFile licenseFile : jarMetadata.getLicenseFiles().values()) {
                    for (KnownLicense knownLicense : licenseFile.getKnownLicenses()) {
                        packageMetadata.getLicenseKeys().add(knownLicense.getId());
                    }//  ww  w  . j  av  a2 s.  co  m
                }
                StringBuilder copyrightBuilder = new StringBuilder();
                copyrightBuilder.append("Copyright (c) ");
                if (jarMetadata.getInceptionYear() != null) {
                    copyrightBuilder.append(jarMetadata.getInceptionYear());
                    copyrightBuilder.append("-");
                }
                Calendar calendar = Calendar.getInstance();
                int currentYear = calendar.get(Calendar.YEAR);
                copyrightBuilder.append(Integer.toString(currentYear));
                if (jarMetadata.getOrganizationName() != null) {
                    copyrightBuilder.append(" ");
                    copyrightBuilder.append(jarMetadata.getOrganizationName());
                }
                packageMetadata.setCopyright(copyrightBuilder.toString());
                if (jarMetadata.getProjectUrl() != null) {
                    packageMetadata.setProjectUrl(jarMetadata.getProjectUrl());
                }
            }
            packageLicenses.add(packageMetadata);
        }
    }
    File packageLicensesFile = new File(outputDirectory, "package-licenses.json");
    try {
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.writeValue(packageLicensesFile, packageLicenses);
    } catch (IOException e) {
        e.printStackTrace();
    }

    Writer flatPackageListWriter = null;
    try {
        flatPackageListWriter = new PrintWriter(
                new FileWriter(new File(outputDirectory, "flat-package-list.csv")));
        flatPackageListWriter.append("Package name,JAR name,License keys,Copyright,Project URL\n");
        for (PackageMetadata packageMetadata : packageLicenses) {
            flatPackageListWriter.append(packageMetadata.getPackageName()).append(",")
                    .append(emptyIfNull(packageMetadata.getJarName())).append(",")
                    .append(setToString(packageMetadata.getLicenseKeys())).append(",")
                    .append(emptyIfNull(packageMetadata.getCopyright())).append(",")
                    .append(emptyIfNull(packageMetadata.getProjectUrl())).append("\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
        IOUtils.closeQuietly(flatPackageListWriter);
    }
}

From source file:com.emc.ecs.sync.CasMigrationTest.java

protected List<String> createTestClips(FPPool pool, int maxBlobSize, int thisMany, Writer summaryWriter)
        throws Exception {
    ExecutorService service = Executors.newFixedThreadPool(CAS_THREADS);

    System.out.print("Creating clips");

    List<String> clipIds = Collections.synchronizedList(new ArrayList<String>());
    List<String> summaries = Collections.synchronizedList(new ArrayList<String>());
    for (int clipIdx = 0; clipIdx < thisMany; clipIdx++) {
        service.submit(new ClipWriter(pool, clipIds, maxBlobSize, summaries));
    }/*from  w ww  .j av a  2s . c  o m*/

    service.shutdown();
    service.awaitTermination(CAS_SETUP_WAIT_MINUTES, TimeUnit.MINUTES);
    service.shutdownNow();

    Collections.sort(summaries);
    for (String summary : summaries) {
        summaryWriter.append(summary);
    }

    System.out.println();

    return clipIds;
}