List of usage examples for org.apache.commons.lang3 StringEscapeUtils unescapeJava
public static final String unescapeJava(final String input)
Unescapes any Java literals found in the String .
From source file:com.streamsets.pipeline.stage.origin.tcp.TCPServerSource.java
private DelimiterBasedFrameDecoder buildDelimiterBasedFrameDecoder(String recordSeparatorStr) { final byte[] delimiterBytes = StringEscapeUtils.unescapeJava(recordSeparatorStr).getBytes(); return new DelimiterBasedFrameDecoder(config.maxMessageSize, true, Unpooled.copiedBuffer(delimiterBytes)); }
From source file:io.github.swagger2markup.internal.component.PathOperationComponent.java
private void exampleMap(MarkupDocBuilder markupDocBuilder, Map<String, Object> exampleMap, String operationSectionTitle, String sectionTitle, boolean beforeBreak, boolean afterBreak) { if (exampleMap.size() > 0) { if (beforeBreak) markupDocBuilder.pageBreak(); buildSectionTitle(markupDocBuilder, operationSectionTitle); for (Map.Entry<String, Object> entry : exampleMap.entrySet()) { // Example title, like "Response 200" or "Request Body" buildExampleTitle(markupDocBuilder, sectionTitle + " " + entry.getKey()); if (NumberUtils.isNumber(entry.getKey())) { // Section header is an HTTP status code (numeric) JsonNode rootNode = parseExample(entry.getValue()); Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields(); if (!fieldsIterator.hasNext()) { // workaround for "array" example //TODO: print $ref'd examples correctly instead of just "array" String example = stripExampleQuotes(Json.pretty(entry.getValue())); example = Json.pretty(example); markupDocBuilder.listingBlock(example, "json"); }/* w w w.j av a 2 s . c om*/ while (fieldsIterator.hasNext()) { Map.Entry<String, JsonNode> field = fieldsIterator.next(); if (field.getKey().equals("application/json")) { String example = Json.pretty(field.getValue()); example = stripExampleQuotes(StringEscapeUtils.unescapeJson(example)); markupDocBuilder.listingBlock(example, "json"); } else if (field.getKey().equals("application/xml")) { String example = stripExampleQuotes(field.getValue().toString()); example = StringEscapeUtils.unescapeJava(example); //TODO: pretty print XML markupDocBuilder.listingBlock(example, "xml"); } else { String example = Json.pretty(entry.getValue()); markupDocBuilder.listingBlock(example, "json"); break; // No need to print the same example multiple times } } } else if (entry.getKey().equals("path")) { // Path shouldn't have quotes around it markupDocBuilder.listingBlock(entry.getValue().toString()); } else { markupDocBuilder.listingBlock(Json.pretty(entry.getValue()), "json"); } } if (afterBreak) markupDocBuilder.pageBreak(); } }
From source file:com.bidorbuy.graylog.alarmcallbacks.jira.JiraAlarmCallback.java
/** * Build the JIRA description/*from w w w . j ava 2 s. c o m*/ * @param stream * @param result * @return */ private String buildDescription(final Stream stream, final AlertCondition.CheckResult result) { String strMessage = CONST_JIRA_MESSAGE_TEMPLATE; if (configuration.stringIsSet(CK_JIRA_MESSAGE_TEMPLATE) && !configuration.getString(CK_JIRA_MESSAGE_TEMPLATE).equals("null") && !configuration.getString(CK_JIRA_MESSAGE_TEMPLATE).isEmpty()) { strMessage = configuration.getString(CK_JIRA_MESSAGE_TEMPLATE); } strMessage = StringEscapeUtils.unescapeJava(strMessage); // Get the last message if (!result.getMatchingMessages().isEmpty()) { // get fields from last message only MessageSummary lastMessage = result.getMatchingMessages().get(0); Map<String, Object> lastMessageFields = lastMessage.getFields(); strMessage = strMessage.replace("[LAST_MESSAGE.message]", lastMessage.getMessage()); strMessage = strMessage.replace("[LAST_MESSAGE.source]", lastMessage.getSource()); for (Map.Entry<String, Object> arg : lastMessageFields.entrySet()) { strMessage = strMessage.replace("[LAST_MESSAGE." + arg.getKey() + "]", arg.getValue().toString()); } // We regex template fields which have not been replaced strMessage = strMessage.replaceAll("\\[LAST_MESSAGE\\.[^\\]]*\\]", ""); } // replace placeholders strMessage = strMessage.replace("[CALLBACK_DATE]", Tools.iso8601().toString()); strMessage = strMessage.replace("[STREAM_ID]", stream.getId()); strMessage = strMessage.replace("[STREAM_TITLE]", stream.getTitle()); strMessage = strMessage.replace("[STREAM_URL]", buildStreamURL(configuration.getString(CK_GRAYLOG_URL), stream)); strMessage = strMessage.replace("[STREAM_RULES]", buildStreamRules(stream)); strMessage = strMessage.replace("[STREAM_RESULT]", result.getResultDescription()); strMessage = strMessage.replace("[ALERT_TRIGGERED_AT]", result.getTriggeredAt().toString()); strMessage = strMessage.replace("[ALERT_TRIGGERED_CONDITION]", result.getTriggeredCondition().toString()); // create final string StringBuilder sb = new StringBuilder(); sb.append("\n\n"); sb.append(strMessage).append("\n\n"); return sb.toString(); }
From source file:de.fraunhofer.sciencedataamanager.beans.SearchAnalyticsManagement.java
/** * Executes the generic export algorithmus. *///from ww w. ja v a 2 s . c o m public void export() { try { if (selectedExportInstance == null || "".equals(selectedExportInstance)) { return; } if (selectedSearchAnalytic == null || "".equals(selectedSearchAnalytic)) { return; } int selectedExportInstanceID = Integer.parseInt(selectedExportInstance); DataExportInstanceDataManager dataExportInstanceDataManager = new DataExportInstanceDataManager( applicationConfiguration); DataExportInstance dataExportInstance = dataExportInstanceDataManager .getDataExportInstanceByID(selectedExportInstanceID); FacesContext facesContext = FacesContext.getCurrentInstance(); ExternalContext externalContext = facesContext.getExternalContext(); String excelExportDefaultFilename = dataExportInstance.getExportFilePrefix() + new SimpleDateFormat("yyyyMMddhhmm").format(new Date()) + dataExportInstance.getExportFilePostfix(); externalContext.setResponseContentType(dataExportInstance.getResponseContentType()); externalContext.setResponseHeader("Content-Disposition", "attachment; filename=\"" + excelExportDefaultFilename + "\""); GroovyClassLoader gcl = new GroovyClassLoader(); Class parsedGroocyClass = gcl .parseClass(StringEscapeUtils.unescapeJava(dataExportInstance.getGroovyCode())); Object groovyClassInstance = parsedGroocyClass.newInstance(); SearchAnalyticDefinitionDataManager searchAnalyticDefinitionDataManager = new SearchAnalyticDefinitionDataManager( applicationConfiguration); Map<String, Map<String, List<Object>>> allConnectorsToExport = new HashMap<String, Map<String, List<Object>>>(); allConnectorsToExport.put(searchAnalyticDefinitionDataManager .getSearchAnalyticDefinitionByID(Integer.parseInt(this.selectedSearchAnalytic)).getName(), this.loadedSearchAnalyticsResultMap); IExportScientificPaperMetaInformation currentDataExportInstance = (IExportScientificPaperMetaInformation) groovyClassInstance; //ExcelDataExportIncChart excelDataExportIncChart = new ExcelDataExportIncChart(); //excelDataExportIncChart.export(allConnectorsToExport, externalContext.getResponseOutputStream()); currentDataExportInstance.export(allConnectorsToExport, externalContext.getResponseOutputStream()); facesContext.responseComplete(); } catch (Exception ex) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("The following error occured: " + ex.toString())); this.applicationConfiguration.getLoggingManager().logException(ex); Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex); } }
From source file:com.rockagen.commons.util.CommUtil.java
/** * unescape JAVA see StringEscapeUtils.unescapeJava(str) For example: * <p>/*from w ww . j a v a 2 s .co m*/ * <code>\u4E2D\u56FD</code> * </p> * becomes: * <p> * <code>""</code>. * </p> * @param str value * @return string */ public static String unescapeJava(String str) { if (isBlank(str)) { return str; } return StringEscapeUtils.unescapeJava(str); }
From source file:com.sri.ai.praise.model.imports.church.ChurchToModelVisitor.java
protected Expression newSymbol(String text) { // Remove quotes from around quoted strings if ((text.startsWith("'") && text.endsWith("'")) || (text.startsWith("\"") && text.endsWith("\""))) { text = text.substring(1, text.length() - 1); }/*from w ww . j a v a 2 s. com*/ // Ensure escapes are applied. text = StringEscapeUtils.unescapeJava(text); if (!text.contains(" ")) { text = text.replaceAll("-", "_"); text = ensureLegalRandomVariableName(new String(text)); } Expression result = Expressions.makeSymbol(text); return result; }
From source file:com.magestore.app.pos.api.m1.config.POSConfigDataAccessM1.java
@Override public List<Currency> getCurrencies() throws DataAccessException, ConnectionException, ParseException, IOException, ParseException { if (mConfig == null) mConfig = new PosConfigDefault(); List<LinkedTreeMap> currencyList = (ArrayList) mConfig.getValue("currencies"); List<Currency> listCurrency = new ArrayList<>(); for (LinkedTreeMap item : currencyList) { Currency currency = new PosCurrency(); String code = item.get("code").toString(); String currency_name = item.get("currency_name").toString(); String currency_symbol = ""; if (item.get("currency_symbol") != null) { String symbol = item.get("currency_symbol").toString(); if (symbol.length() > 0) { String sSymbol = symbol.substring(0, 1); if (sSymbol.equals("u")) { currency_symbol = StringEscapeUtils.unescapeJava("\\" + symbol); } else if (sSymbol.equals("\\")) { currency_symbol = StringEscapeUtils.unescapeJava(symbol); } else if (symbol.contains("\\u")) { currency_symbol = StringEscapeUtils.unescapeJava(symbol); } else { currency_symbol = StringEscapeUtils.unescapeJava(symbol); }// w ww.j av a 2s . com } } String is_default = item.get("is_default").toString(); String currency_rate = item.get("currency_rate").toString(); currency.setCode(code); currency.setCurrenyName(currency_name); currency.setCurrencySymbol(currency_symbol); currency.setIsDefault(is_default); try { currency.setCurrencyRate(Double.parseDouble(currency_rate)); } catch (Exception e) { } listCurrency.add(currency); } return listCurrency; }
From source file:dataviewer.DataViewer.java
private void read_data() { t[THREAD.read.ordinal()].stop();//from w w w .j ava2s. c o m t[THREAD.read.ordinal()] = new Thread(new Runnable() { @Override public void run() { //do stuff try { if (!selected_file.equals("")) { cb_table.setEnabled(false); btn_execute.setEnabled(false); tp_sql.setEnabled(false); ck_export.setEnabled(false); btn_remove.setEnabled(false); tb_data.setModel(new DefaultTableModel()); txt_count.setText("Please wait while profiling data ..."); table = selected_file.replaceAll(getExtension(selected_file), "") .replaceAll("[^a-zA-Z0-9]+", ""); DB db = new DB("./db/" + table + ".db"); db.initialize(); Timing timer = new Timing(); InputStream _in = new BufferedInputStream( new FileInputStream(cur_path + File.separator + selected_file)); byte[] c = new byte[1024]; int j = 0; int count = 0; while ((j = _in.read(c)) != -1) { for (int i = 0; i < j; ++i) { if (c[i] == '\n') { count++; } } } _in.close(); if (header) { count--; } CSVReader in = new CSVReader(new FileReader(cur_path + File.separator + selected_file), '\n'); String[] line = null; long _n_ = 0; boolean first = true; while ((line = in.readNext()) != null) { if (first) { first = false; List<String> cols = new ArrayList(); cols.add("_N_"); String[] s = line[0].split(delimiter); if (header) { for (String h : s) { cols.add(h); } } else { for (int i = 1; i <= s.length; ++i) { cols.add("field_" + i); } } db.createTable(table, cols.toArray(new String[cols.size()])); db.insertBegin(table); if (header) { continue; } } _n_++; StringBuilder s = new StringBuilder(); s.append(_n_).append(StringEscapeUtils.unescapeJava(delimiter)).append(line[0]); db.insertInto(s.toString().split(delimiter)); if (_n_ == N) { db.force_insert(); view("SELECT * FROM " + table + " WHERE _N_ <= " + N + ";"); } if (_n_ % 100000 == 0) { txt_count.setText("Reading " + selected_file + ": " + Math.floor(_n_ * 1.0 / count * 100) + "% completed."); } } in.close(); db.insertFinish(); db.create_index(table, "_N_", true, true); db.close(); if (_n_ < N) { view("SELECT * FROM " + table + ";"); } cb_table.setEnabled(true); btn_execute.setEnabled(true); tp_sql.setEnabled(true); ck_export.setEnabled(true); btn_remove.setEnabled(true); txt_count.setText("Read " + String.valueOf(_n_) + " many lines and showed top " + Math.min(N, _n_) + ". Took " + timer.getSec() + "s."); } tr_files.grabFocus(); } catch (Exception e) { txt_count.setText(e.getMessage()); } } }); t[THREAD.read.ordinal()].start(); }
From source file:dataviewer.DataViewer.java
private void view(String _sql) { final String sql = _sql; // check pivot t[THREAD.view.ordinal()].stop();/*from ww w .ja v a 2 s. co m*/ t[THREAD.view.ordinal()] = new Thread(new Runnable() { @Override public void run() { try { Timing timer = new Timing(); boolean alive = t[THREAD.read.ordinal()].isAlive(); if (!alive) { txt_count.setText("Running query ... "); } DB db = new DB("./db/" + table + ".db"); db.open(); ResultSet results = db.execute(sql); String csv = ""; CSVWriter out = null; boolean asked = false; if (export && ck_export.isEnabled()) { csv = JOptionPane.showInputDialog(new JFrame(""), "Please enter the name of the file without extension.", "Export File Name", JOptionPane.PLAIN_MESSAGE); if (csv == null) { csv = ""; } if (!csv.equals("")) { out = new CSVWriter(new FileWriter("./output/" + csv + ".txt"), '\n', CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER); } } String _delimiter = StringEscapeUtils.unescapeJava(delimiter); StringBuilder sb = new StringBuilder(); List<String> cols = new ArrayList(); for (int i = 0; i < results.getMetaData().getColumnCount(); ++i) { String name = results.getMetaData().getColumnName(i + 1); cols.add(name); sb.append(name).append(_delimiter); } sb.setLength(sb.length() - 1); DefaultTableModel model = new DefaultTableModel(); for (int i = 0; i < cols.size(); ++i) { model.addColumn(cols.get(i)); } if (!csv.equals("")) { out.writeNext(sb.toString()); } String[] vals; long count = 0; boolean is_model_render = false; while (results.next()) { count++; vals = new String[cols.size()]; sb = new StringBuilder(); for (int i = 0; i < cols.size(); ++i) { vals[i] = results.getString(cols.get(i)); sb.append(vals[i]).append(_delimiter); } sb.setLength(sb.length() - 1); if (!csv.equals("")) { out.writeNext(sb.toString()); } if (asked == false && is_model_render == false && count > N) { if (JOptionPane.showConfirmDialog(null, "Number of rows are more than " + N + ". Stop?", "", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { renderData(model); is_model_render = true; } asked = true; } if (is_model_render == false) { model.addRow(vals); } } db.close(); if (is_model_render == false) { if (transpose) { tb_data.setModel(model); transpose((DefaultTableModel) tb_data.getModel()); } else { renderData(model); } } if (!csv.equals("")) { out.close(); txt_count.setText(count + " records are queried from " + table + " and exported to /output/" + csv + ".txt. Took " + timer.getSec() + "s."); } else if (!alive) { if (is_model_render) { txt_count.setText(count + " records are queried from " + table + " but stopped at " + N + ". Took " + timer.getSec() + "s."); } else { txt_count.setText(count + " records are queried from " + table + ". Took " + timer.getSec() + "s."); } } } catch (Exception e) { txt_count.setText(e.getMessage()); } } }); t[THREAD.view.ordinal()].start(); }
From source file:com.kdmanalytics.toif.assimilator.Assimilator.java
/** * load the rdf file into repository.//from w ww .ja v a 2s.co m * * @param repository * the repository * @param is * the input stream from file * @throws IOException * @throws RepositoryException */ public void load(Repository repository, InputStream is) throws IOException, RepositoryException { int count = 0; final ValueFactory factory = repository.getValueFactory(); final RepositoryConnection con = repository.getConnection(); con.setAutoCommit(false); final BufferedReader in = new BufferedReader(new InputStreamReader(is)); String line = in.readLine(); URI lastSubject = null; while (line != null) { count++; if (line.length() <= 0) { line = in.readLine(); continue; } if (line.charAt(0) == '#') { line = in.readLine(); continue; } if (count == 1) { if (line.startsWith("KDM_Triple")) { line = in.readLine(); continue; } } URI subject = null; URI predicate = null; Value object = null; try { final char bytes[] = line.toCharArray(); // Skip the initial < int start = 1; int i = 1; // If the line starts with a space (indent) then reuse the last // subject, // otherwise parse the subject. if (bytes[0] == ' ') { subject = lastSubject; } else { // Parse the subject while ((i < bytes.length) && (bytes[i] != '>')) { ++i; } if (i >= bytes.length) { LOG.error("Invalid subject URI on ntriples line " + count); line = in.readLine(); continue; } subject = factory.createURI(MODEL_NS + new String(line.substring(start, i))); // Buffer the subject in case we need it next time lastSubject = subject; ++i; // Skip the > } while ((i < bytes.length) && (bytes[i] != '<')) { ++i; } if (i >= bytes.length) { LOG.error("Invalid subject URI on ntriples line " + count); line = in.readLine(); continue; } ++i; // Skip the > start = i; // Parse the predicate while ((i < bytes.length) && (bytes[i] != '>')) { ++i; } if (i >= bytes.length) { LOG.error("Invalid predicate URI on ntriples line " + count); line = in.readLine(); continue; } predicate = factory.createURI(KDM_NS_HOST + new String(line.substring(start, i))); ++i; // Skip the > while ((i < bytes.length) && (bytes[i] != '<') && (bytes[i] != '\"')) { ++i; } if (i >= bytes.length) { LOG.error("Invalid predicate URI on ntriples line " + count); line = in.readLine(); continue; } // Parse a URI if (bytes[i] == '<') { ++i; // Skip the > start = i; while ((i < bytes.length) && (bytes[i] != '>')) { ++i; } if (i >= bytes.length) { LOG.error("Invalid object URI on ntriples line " + count); line = in.readLine(); continue; } object = factory.createURI(MODEL_NS + new String(line.substring(start, i))); } // Parse a literal else { final int lastIndex = line.lastIndexOf('"'); if ((lastIndex < 0) || (lastIndex <= i)) { LOG.error("Invalid literal object on ntriples line " + count); line = in.readLine(); continue; } String string = new String(line.substring(++i, lastIndex)); string = string.replace("\\", "\\\\"); object = factory.createLiteral(StringEscapeUtils.unescapeJava(string)); } // In non-lowmem mode everything gets loaded into the // database // KdmXmlHandler.addOrWrite(con, subject, predicate, object); con.add(subject, predicate, object); } catch (final ArrayIndexOutOfBoundsException e) { LOG.error("Parse error on ntriples line " + count, e); // e.printStackTrace(); } line = in.readLine(); } con.commit(); con.close(); }