Example usage for org.apache.commons.lang3 StringEscapeUtils escapeCsv

List of usage examples for org.apache.commons.lang3 StringEscapeUtils escapeCsv

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringEscapeUtils escapeCsv.

Prototype

public static final String escapeCsv(final String input) 

Source Link

Document

<p>Returns a String value for a CSV column enclosed in double quotes, if required.</p> <p>If the value contains a comma, newline or double quote, then the String value is returned enclosed in double quotes.</p> <p>Any double quote characters in the value are escaped with another double quote.</p> <p>If the value does not contain a comma, newline or double quote, then the String value is returned unchanged.</p> see <a href="http://en.wikipedia.org/wiki/Comma-separated_values">Wikipedia</a> and <a href="http://tools.ietf.org/html/rfc4180">RFC 4180</a>.

Usage

From source file:fr.mcc.ginco.audit.csv.JournalLine.java

public String toString() {
    String line = "";
    line += StringEscapeUtils.escapeCsv(getEventType().toString()) + COMMA;
    line += StringEscapeUtils.escapeCsv(DateUtil.toString(getEventDate())) + COMMA;
    line += StringEscapeUtils.escapeCsv(authorId) + COMMA;
    if (conceptId != null) {
        line += StringEscapeUtils.escapeCsv(conceptId);
    }//www .  jav a2  s . co  m
    line += COMMA;
    if (termId != null) {
        line += StringEscapeUtils.escapeCsv(termId);
    }
    line += COMMA;
    if (termRole != null) {
        line += StringEscapeUtils.escapeCsv(termRole);
    }
    line += COMMA;
    if (status != null) {
        line += StringEscapeUtils.escapeCsv(LabelUtil.getResourceLabel("concept-status[" + status + "]"));
    }
    line += COMMA;
    if (oldLexicalValue != null) {
        line += StringEscapeUtils.escapeCsv(oldLexicalValue);
    }
    line += COMMA;
    if (newLexicalValue != null) {
        line += StringEscapeUtils.escapeCsv(newLexicalValue);
    }
    line += COMMA;
    if (oldGenericTerm != null) {
        Iterator<String> olGenericTermItr = oldGenericTerm.iterator();
        while (olGenericTermItr.hasNext()) {
            line += StringEscapeUtils.escapeCsv(olGenericTermItr.next());
            if (olGenericTermItr.hasNext()) {
                line += PIPE;
            }
        }
    }
    line += COMMA;
    if (newGenericTerm != null) {
        Iterator<String> newGenericTermItr = newGenericTerm.iterator();
        while (newGenericTermItr.hasNext()) {
            line += StringEscapeUtils.escapeCsv(newGenericTermItr.next());
            if (newGenericTermItr.hasNext()) {
                line += PIPE;
            }
        }
    }
    return line;
}

From source file:com.thejustdo.util.Utils.java

/**
 * Formats a string to avoid any injection exploit by escaping the special
 * characters.//  ww  w.  ja  v  a 2 s.c  om
 *
 * @param s String to be modified.
 * @return Modified string.
 */
public static String escapeString(String s) {
    String answer;
    answer = StringEscapeUtils.escapeCsv(s);
    answer = StringEscapeUtils.escapeEcmaScript(answer);
    answer = StringEscapeUtils.escapeHtml3(answer);
    answer = StringEscapeUtils.escapeHtml4(answer);
    answer = StringEscapeUtils.escapeJava(answer);
    answer = StringEscapeUtils.escapeXml(answer);
    return answer;
}

From source file:controllers.modules.CorpusModule.java

public static Result update(UUID corpus) {
    OpinionCorpus corpusObj = null;/*  ww  w.  jav a  2s .  c  om*/
    if (corpus != null) {
        corpusObj = fetchResource(corpus, OpinionCorpus.class);
    }
    OpinionCorpusFactory corpusFactory = null;

    MultipartFormData formData = request().body().asMultipartFormData();
    if (formData != null) {
        // if we have a multi-part form with a file.
        if (formData.getFiles() != null) {
            // get either the file named "file" or the first one.
            FilePart filePart = ObjectUtils.defaultIfNull(formData.getFile("file"),
                    Iterables.getFirst(formData.getFiles(), null));
            if (filePart != null) {
                corpusFactory = (OpinionCorpusFactory) new OpinionCorpusFactory().setFile(filePart.getFile())
                        .setFormat(FilenameUtils.getExtension(filePart.getFilename()));
            }
        }
    } else {
        // otherwise try as a json body.
        JsonNode json = request().body().asJson();
        if (json != null) {
            OpinionCorpusFactoryModel optionsVM = Json.fromJson(json, OpinionCorpusFactoryModel.class);
            if (optionsVM != null) {
                corpusFactory = optionsVM.toFactory();
            } else {
                throw new IllegalArgumentException();
            }

            if (optionsVM.grabbers != null) {
                if (optionsVM.grabbers.twitter != null) {
                    if (StringUtils.isNotBlank(optionsVM.grabbers.twitter.query)) {
                        TwitterFactory tFactory = new TwitterFactory();
                        Twitter twitter = tFactory.getInstance();
                        twitter.setOAuthConsumer(
                                Play.application().configuration().getString("twitter4j.oauth.consumerKey"),
                                Play.application().configuration().getString("twitter4j.oauth.consumerSecret"));
                        twitter.setOAuthAccessToken(new AccessToken(
                                Play.application().configuration().getString("twitter4j.oauth.accessToken"),
                                Play.application().configuration()
                                        .getString("twitter4j.oauth.accessTokenSecret")));

                        Query query = new Query(optionsVM.grabbers.twitter.query);
                        query.count(ObjectUtils.defaultIfNull(optionsVM.grabbers.twitter.limit, 10));
                        query.resultType(Query.RECENT);
                        if (StringUtils.isNotEmpty(corpusFactory.getLanguage())) {
                            query.lang(corpusFactory.getLanguage());
                        } else if (corpusObj != null) {
                            query.lang(corpusObj.getLanguage());
                        }

                        QueryResult qr;
                        try {
                            qr = twitter.search(query);
                        } catch (TwitterException e) {
                            throw new IllegalArgumentException();
                        }

                        StringBuilder tweets = new StringBuilder();
                        for (twitter4j.Status status : qr.getTweets()) {
                            // quote for csv, normalize space, and remove higher unicode characters. 
                            String text = StringEscapeUtils.escapeCsv(StringUtils
                                    .normalizeSpace(status.getText().replaceAll("[^\\u0000-\uFFFF]", "")));
                            tweets.append(text + System.lineSeparator());
                        }

                        corpusFactory.setContent(tweets.toString());
                        corpusFactory.setFormat("txt");
                    }
                }
            }
        } else {
            // if not json, then just create empty.
            corpusFactory = new OpinionCorpusFactory();
        }
    }

    if (corpusFactory == null) {
        throw new IllegalArgumentException();
    }

    if (corpus == null && StringUtils.isEmpty(corpusFactory.getTitle())) {
        corpusFactory.setTitle("Untitled corpus");
    }

    corpusFactory.setOwnerId(SessionedAction.getUsername(ctx())).setExistingId(corpus).setEm(em());

    DocumentCorpusModel corpusVM = null;
    corpusObj = corpusFactory.create();
    if (!em().contains(corpusObj)) {
        em().persist(corpusObj);

        corpusVM = (DocumentCorpusModel) createViewModel(corpusObj);
        corpusVM.populateSize(em(), corpusObj);
        return created(corpusVM.asJson());
    }

    for (PersistentObject obj : corpusObj.getDocuments()) {
        if (em().contains(obj)) {
            em().merge(obj);
        } else {
            em().persist(obj);
        }
    }
    em().merge(corpusObj);

    corpusVM = (DocumentCorpusModel) createViewModel(corpusObj);
    corpusVM.populateSize(em(), corpusObj);
    return ok(corpusVM.asJson());
}

From source file:com.matthewmitchell.peercoin_android_wallet.ui.WalletActivity.java

public void handleExportTransactions() {

    // Create CSV file from transactions

    final File file = new File(Constants.Files.EXTERNAL_WALLET_BACKUP_DIR,
            Constants.Files.TX_EXPORT_NAME + "-" + getFileDate() + ".csv");

    try {// w  w w .ja va 2  s . c  om

        final BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        writer.append("Date,Label,Amount (" + MonetaryFormat.CODE_PPC + "),Fee (" + MonetaryFormat.CODE_PPC
                + "),Address,Transaction Hash,Confirmations\n");

        if (txListAdapter == null || txListAdapter.transactions.isEmpty()) {
            longToast(R.string.export_transactions_mail_intent_failed);
            log.error("exporting transactions failed");
            return;
        }

        final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm z");
        dateFormat.setTimeZone(TimeZone.getDefault());

        for (Transaction tx : txListAdapter.transactions) {

            TransactionsListAdapter.TransactionCacheEntry txCache = txListAdapter.getTxCache(tx);
            String memo = tx.getMemo() == null ? "" : StringEscapeUtils.escapeCsv(tx.getMemo());
            String fee = tx.getFee() == null ? "" : tx.getFee().toPlainString();
            String address = txCache.address == null ? getString(R.string.export_transactions_unknown)
                    : txCache.address.toString();

            writer.append(dateFormat.format(tx.getUpdateTime()) + ",");
            writer.append(memo + ",");
            writer.append(txCache.value.toPlainString() + ",");
            writer.append(fee + ",");
            writer.append(address + ",");
            writer.append(tx.getHash().toString() + ",");
            writer.append(tx.getConfidence().getDepthInBlocks() + "\n");

        }

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

    } catch (IOException x) {
        longToast(R.string.export_transactions_mail_intent_failed);
        log.error("exporting transactions failed", x);
        return;
    }

    final DialogBuilder dialog = new DialogBuilder(this);
    dialog.setMessage(Html.fromHtml(getString(R.string.export_transactions_dialog_success, file)));

    dialog.setPositiveButton(WholeStringBuilder.bold(getString(R.string.export_keys_dialog_button_archive)),
            new OnClickListener() {

                @Override
                public void onClick(final DialogInterface dialog, final int which) {

                    final Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.export_transactions_mail_subject));
                    intent.putExtra(Intent.EXTRA_TEXT,
                            makeEmailText(getString(R.string.export_transactions_mail_text)));
                    intent.setType(Constants.MIMETYPE_TX_EXPORT);
                    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));

                    try {
                        startActivity(Intent.createChooser(intent,
                                getString(R.string.export_transactions_mail_intent_chooser)));
                        log.info("invoked chooser for exporting transactions");
                    } catch (final Exception x) {
                        longToast(R.string.export_transactions_mail_intent_failed);
                        log.error("exporting transactions failed", x);
                    }

                }

            });

    dialog.setNegativeButton(R.string.button_dismiss, null);
    dialog.show();

}

From source file:edu.utsa.sifter.IndexResource.java

void writeRecord(final Result doc, final Bookmark mark, final OutputStreamWriter writer) throws IOException {
    writer.write(nullCheck(doc.ID));/*from   ww  w .  j  a v a  2s  .  c  o m*/
    writer.write(",");
    writer.write(Double.toString(doc.Score));
    writer.write(",\"");
    writer.write(StringEscapeUtils.escapeCsv(nullCheck(doc.Name)));
    writer.write("\",\"");
    writer.write(StringEscapeUtils.escapeCsv(nullCheck(doc.Path)));
    writer.write("\",\"");
    writer.write(StringEscapeUtils.escapeCsv(nullCheck(doc.Extension)));
    writer.write("\",");
    writer.write(Long.toString(doc.Size));
    writer.write(",");
    writer.write(Long.toString(doc.Modified));
    writer.write(",");
    writer.write(Long.toString(doc.Accessed));
    writer.write(",");
    writer.write(Long.toString(doc.Created));
    writer.write(",");
    writer.write(nullCheck(doc.Cell));
    writer.write(",");
    writer.write(Double.toString(doc.CellDistance));
    writer.write(",");
    writer.write(mark == null ? "0" : Long.toString(mark.Created));
    writer.write(",");
    writer.write(mark == null ? "" : StringEscapeUtils.escapeCsv(nullCheck(mark.Comment)));
    writer.write("\n");
}

From source file:com.rockagen.commons.util.CommUtil.java

/**
 * escape CSV see StringEscapeUtils.escapeCsv(str)
 *
 * @param str value/* w  w  w . ja  va2  s .c o m*/
 * @return string
 */
public static String escapeCsv(String str) {
    if (isBlank(str)) {
        return str;
    }
    return StringEscapeUtils.escapeCsv(str);
}

From source file:edu.utsa.sifter.IndexResource.java

void writeHitRecord(final SearchHit hit, final Bookmark mark, final OutputStreamWriter writer)
        throws IOException, InterruptedException {
    writer.write(nullCheck(hit.ID()));//w ww . j a  v a2 s .c o  m
    writer.write(",");
    writer.write(Double.toString(hit.Score));
    writer.write(",\"");
    writer.write(StringEscapeUtils.escapeCsv(nullCheck(hit.Name())));
    writer.write("\",\"");
    writer.write(StringEscapeUtils.escapeCsv(nullCheck(hit.Path())));
    writer.write("\",\"");
    writer.write(nullCheck(StringEscapeUtils.escapeCsv(hit.Extension())));
    writer.write("\",");
    writer.write(Long.toString(hit.Size()));
    writer.write(",");
    writer.write(Long.toString(hit.Modified()));
    writer.write(",");
    writer.write(Long.toString(hit.Accessed()));
    writer.write(",");
    writer.write(Long.toString(hit.Created()));
    writer.write(",");
    writer.write(nullCheck(hit.Cell()));
    writer.write(",");
    writer.write(Double.toString(hit.CellDistance()));
    writer.write(",");
    writer.write(Long.toString(hit.Start));
    writer.write(",");
    writer.write(Long.toString(hit.End));
    writer.write(",");
    writer.write(nullCheck(StringEscapeUtils.escapeCsv(hit.Passage.replace('\n', ' ').replace('\r', ' '))));
    writer.write(",");
    writer.write(mark == null ? "0" : Long.toString(mark.Created));
    writer.write(",");
    writer.write(mark == null ? "" : StringEscapeUtils.escapeCsv(nullCheck(mark.Comment)));
    writer.write("\n");
}

From source file:jdiff.API.java

private void dumpClassInCsvFormat(ClassAPI classAPI, PrintWriter writer) {
    if (classAPI.isInterface_)
        writer.print(classAPI.name_);/*from w w w . j a v a2s  .  c  o  m*/
    else
        writer.print(classAPI.name_);
    if (classAPI.doc_ != null) {
        writer.println(", " + StringEscapeUtils.escapeCsv(removeNewLine(classAPI.doc_)));
    } else {
        writer.println();
    }
}

From source file:loggerplusplus.LogEntry.java

public String toCSVString(boolean includeRequests, boolean includeResponses) {
    StringBuilder result = new StringBuilder();
    //         for (int i=1; i<loggerTableDetails.length; i++) {
    ///*from   ww  w  .j  ava2  s. c om*/
    //            result.append(StringEscapeUtils.escapeCsv(String.valueOf(getValueByName((String) loggerTableDetails[i][0]))));
    //
    //            if(i<tableHelper.getLogTableModel().getColumnCount()-1)
    //               result.append(",");
    //         }

    LogTableColumnModel columnModel = LoggerPlusPlus.getInstance().getLogTable().getColumnModel();
    ArrayList<LogTableColumn> columns = columnModel.getAllColumns();
    Collections.sort(columns);
    boolean firstDone = false;
    for (LogTableColumn logTableColumn : columns) {
        if (logTableColumn.isVisible() && logTableColumn.isEnabled()) {
            if (firstDone) {
                result.append(",");
            } else {
                firstDone = true;
            }
            result.append(StringEscapeUtils.escapeCsv(getValue(logTableColumn.getIdentifier()).toString()));
        }
    }

    if (includeRequests) {
        result.append(",");
        if (requestResponse != null && requestResponse.getRequest() != null)
            result.append(StringEscapeUtils.escapeCsv(new String(requestResponse.getRequest())));
    }
    if (includeResponses) {
        result.append(",");
        if (requestResponse != null && requestResponse.getResponse() != null)
            result.append(StringEscapeUtils.escapeCsv(new String(requestResponse.getResponse())));
    }
    return result.toString();
}

From source file:com.denimgroup.threadfix.service.report.ReportsServiceImpl.java

@SuppressWarnings("unchecked")
private StringBuffer getDataVulnListReport(List<List<String>> rowParamsList, List<Integer> applicationIdList) {
    StringBuffer data = new StringBuffer();
    data.append("Vulnerability List \n\n");

    if (applicationIdList != null) {

        List<String> teamNames = applicationDao.getTeamNames(applicationIdList);
        String teamName = (teamNames != null && teamNames.size() == 1) ? teamNames.get(0) : "All";
        data.append("Team: ").append(teamName).append(" \n");
        String appName = "";
        if (applicationIdList.size() == 1) {
            Application app = applicationDao.retrieveById(applicationIdList.get(0));
            if (app != null) {
                appName = app.getName();
            }// w ww  . j  a  v  a2 s  .  c  o  m
        } else {
            appName = "All";
        }
        data.append("Application: ").append(appName).append(" \n \n");
    }

    DefaultConfiguration configuration = defaultConfigService.loadCurrentConfiguration();
    List<CSVExportField> exportFields = configuration.getCsvExportFields();

    if (exportFields.size() > 0) {
        String exportFieldsStr = join(", ", defaultConfigService.getDisplayNamesFromExportFields(exportFields))
                + "\n";
        data.append(exportFieldsStr);
    } else {
        data.append(getCSVExportHeaderString());
    }

    for (List<String> row : rowParamsList) {
        for (int i = 0; i < row.size(); i++) {
            String str = "";
            if (row.get(i) != null) {
                str = row.get(i);
            }

            if (str.length() > 31800) {
                str = StringUtils.abbreviate(str, 31800) + "\n...data exceeds space allotted for cell.";
            }
            str = StringEscapeUtils.escapeCsv(str);

            if (i < row.size() - 1) {
                data.append(str).append(",");
            } else {
                data.append(str).append(" \n");
            }
        }
    }

    return data;
}