Java Code Examples for org.apache.commons.lang3.StringEscapeUtils

The following examples show how to use org.apache.commons.lang3.StringEscapeUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: AIDR   Source File: ClassifiedTweet.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 
 * @param isPrettyPrinting turn PrettyPrinting on/off
 * @return serialized JSON string
 */
public String toJsonString(boolean isPrettyPrinting) {
	Gson jsonObject = null;
	
	if (isPrettyPrinting) {
	jsonObject = new GsonBuilder().serializeNulls().disableHtmlEscaping()
			.serializeSpecialFloatingPointValues().setPrettyPrinting()
			.create();
	} else {
		jsonObject = new GsonBuilder().serializeNulls().disableHtmlEscaping()
				.serializeSpecialFloatingPointValues()
				.create();
	}
	
	try {
		String jsonString = jsonObject.toJson(this, ClassifiedTweet.class);
		jsonString = jsonString.replace("\\\\u", "\\u");
		return StringEscapeUtils.unescapeJava(jsonString);
	} catch (Exception e) {
		logger.error("Error while parsing jsonObject to json string", e);
		return null;
	}
}
 
Example 2
Source Project: gocd   Source File: ServerUnavailabilityResponse.java    License: Apache License 2.0 6 votes vote down vote up
private void generateAPIResponse() {

        try {
            HttpServletRequest httpRequest = request;

            if (requestIsOfType(JSON, httpRequest)) {
                response.setContentType("application/json");
                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("message", jsonMessage);
                response.getWriter().print(jsonObject);
            } else if (requestIsOfType(XML, httpRequest)) {
                response.setContentType("application/xml");
                String xml = String.format("<message>%s</message>", StringEscapeUtils.escapeXml11(jsonMessage));
                response.getWriter().print(xml);
            } else {
                generateHTMLResponse();
            }

        } catch (IOException e) {
            LOGGER.error("General IOException: {}", e.getMessage());
        }
    }
 
Example 3
Source Project: jinjava   Source File: PrettyPrintFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object filter(Object var, JinjavaInterpreter interpreter, String... args) {
  if (var == null) {
    return "null";
  }

  String varStr;

  if (
    var instanceof String ||
    var instanceof Number ||
    var instanceof PyishDate ||
    var instanceof Iterable ||
    var instanceof Map
  ) {
    varStr = Objects.toString(var);
  } else {
    varStr = objPropsToString(var);
  }

  return StringEscapeUtils.escapeHtml4(
    "{% raw %}(" + var.getClass().getSimpleName() + ": " + varStr + "){% endraw %}"
  );
}
 
Example 4
Source Project: spider   Source File: CommonsSpiderPanel.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 所有的抓取任务列表
 *
 * @return
 */
@RequestMapping(value = "tasks", method = RequestMethod.GET)
public ModelAndView tasks(@RequestParam(required = false, defaultValue = "false") boolean showRunning) {
    ModelAndView modelAndView = new ModelAndView("panel/commons/listTasks");
    ResultListBundle<Task> listBundle;
    if (!showRunning) {
        listBundle = commonsSpiderService.getTaskList(true);
    } else {
        listBundle = commonsSpiderService.getTasksFilterByState(State.RUNNING, true);
    }
    ResultBundle<Long> runningTaskCount = commonsSpiderService.countByState(State.RUNNING);
    modelAndView.addObject("resultBundle", listBundle)
            .addObject("runningTaskCount", runningTaskCount.getResult())
            .addObject("spiderInfoList", listBundle.getResultList().stream()
                    .map(task -> StringEscapeUtils.escapeHtml4(
                            gson.toJson(task.getExtraInfoByKey("spiderInfo")
                            ))
                    ).collect(Collectors.toList()));
    return modelAndView;
}
 
Example 5
Source Project: easyweb   Source File: StringUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 缩略字符串(不区分中英文字符)
 * @param str 目标字符串
 * @param length 截取长度
 * @return
 */
public static String abbr(String str, int length) {
	if (str == null) {
		return "";
	}
	try {
		StringBuilder sb = new StringBuilder();
		int currentLength = 0;
		for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) {
			currentLength += String.valueOf(c).getBytes("GBK").length;
			if (currentLength <= length - 3) {
				sb.append(c);
			} else {
				sb.append("...");
				break;
			}
		}
		return sb.toString();
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	}
	return "";
}
 
Example 6
Source Project: zest-writer   Source File: MenuController.java    License: GNU General Public License v3.0 6 votes vote down vote up
@FXML private void handleGunningButtonAction(ActionEvent event){
    Function<Textual, Double> calGuning = (Textual ch) -> {
        String htmlText = StringEscapeUtils.unescapeHtml4(markdownToHtml(mainApp.getIndex(), ch.readMarkdown()));
        String plainText = Corrector.htmlToTextWithoutCode(htmlText);
        if("".equals(plainText.trim())){
            return 100.0;
        }else{
            Readability rd = new Readability(plainText);
            return rd.getGunningFog();
        }
    };
    ComputeIndexService computeIndexService = new ComputeIndexService(calGuning, (Container) mainApp.getIndex().getSummary().getRoot().getValue());
    hBottomBox.getChildren().clear();
    hBottomBox.getChildren().addAll(labelField);
    labelField.textProperty().bind(computeIndexService.messageProperty());
    computeIndexService.setOnSucceeded(t -> {
        displayIndex(((ComputeIndexService) t.getSource()).getValue(),
                Configuration.getBundle().getString("ui.menu.edit.readable.gunning_index"),
                Configuration.getBundle().getString("ui.menu.edit.readable.gunning_index.header"));
        hBottomBox.getChildren().clear();
    });
    computeIndexService.start();
}
 
Example 7
Source Project: paas   Source File: HttpClientUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 缩略字符串(不区分中英文字符)
 *
 * @param str    目标字符串
 * @param length 截取长度
 * @return
 */
public static String abbr(String str, int length) {
    if (str == null) {
        return "";
    }
    try {
        StringBuilder sb = new StringBuilder();
        int currentLength = 0;

        for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) {
            currentLength += String.valueOf(c).getBytes("GBK").length;
            if (currentLength <= length - 3) {
                sb.append(c);
            } else {
                sb.append("...");
                break;
            }
        }
        return sb.toString();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return "";
}
 
Example 8
@SuppressWarnings("static-method")
public String escapeText(String input) {
    if (input == null) {
        return input;
    }

    // remove \t, \n, \r
    // replace \ with \\
    // replace " with \"
    // outter unescape to retain the original multi-byte characters
    // finally escalate characters avoiding code injection
    return escapeUnsafeCharacters(
            StringEscapeUtils.unescapeJava(
                    StringEscapeUtils.escapeJava(input)
                            .replace("\\/", "/"))
                    .replaceAll("[\\t\\n\\r]", " ")
                    .replace("\\", "\\\\")
                    .replace("\"", "\\\""));
}
 
Example 9
Source Project: atlas   Source File: TPatchTool.java    License: Apache License 2.0 6 votes vote down vote up
protected File getLastPatchFile(String baseApkVersion,
                                String productName,
                                File outPatchDir) throws IOException {
    try {
        String httpUrl = ((TpatchInput)input).LAST_PATCH_URL +
                "baseVersion=" +
                baseApkVersion +
                "&productIdentifier=" +
                productName;
        String response = HttpClientUtils.getUrl(httpUrl);
        if (StringUtils.isBlank(response) ||
                response.equals("\"\"")) {
            return null;
        }
        File downLoadFolder = new File(outPatchDir, "LastPatch");
        downLoadFolder.mkdirs();
        File downLoadFile = new File(downLoadFolder, "lastpatch.tpatch");
        String downLoadUrl = StringEscapeUtils.unescapeJava(response);
        downloadTPath(downLoadUrl.substring(1, downLoadUrl.length() - 1), downLoadFile);

        return downLoadFile;
    } catch (Exception e) {
        return null;
    }
}
 
Example 10
Source Project: uyuni   Source File: RhnHiddenTag.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public int doStartTag() throws JspException {
    JspWriter out = null;
    try {
        StringBuffer buf = new StringBuffer();
        out = pageContext.getOut();

        HtmlTag baseTag = new HiddenInputTag();
        if (!StringUtils.isBlank(getId())) {
            baseTag.setAttribute("id", getId());
        }
        baseTag.setAttribute("name", getName());
        baseTag.setAttribute("value", StringEscapeUtils.escapeHtml4(getValue()));
        buf.append(baseTag.render());
        out.print(buf.toString());
        return SKIP_BODY;
    }
    catch (Exception e) {
        throw new JspException("Error writing to JSP file:", e);
    }
}
 
Example 11
Source Project: aws-mock   Source File: MockEC2QueryHandler.java    License: MIT License 6 votes vote down vote up
/**
 * Generate error response body in xml and write it with writer.
 *
 * @param errorCode
 *            the error code wrapped in the xml response
 * @param errorMessage
 *            the error message wrapped in the xml response
 * @return xml body for an error message which can be recognized by AWS clients
 */
private String getXmlError(final String errorCode, final String errorMessage) {
    Map<String, Object> data = new HashMap<String, Object>();
    data.put("errorCode", StringEscapeUtils.escapeXml(errorCode));
    data.put("errorMessage", StringEscapeUtils.escapeXml(errorMessage));
    // fake a random UUID as request ID
    data.put("requestID", UUID.randomUUID().toString());

    String ret = null;

    try {
        ret = TemplateUtils.get(ERROR_RESPONSE_TEMPLATE, data);
    } catch (AwsMockException e) {
        log.error("fatal exception caught: {}", e.getMessage());
        e.printStackTrace();
    }
    return ret;
}
 
Example 12
/**
 * Retrieves the destination of this transfer by evaluating the
 * <code>dest</code> and the <code>destexpr</code> attributes.
 * 
 * @return destination of this transfer.
 * @throws SemanticError
 *             Error evaluating the <code>destexpr</code> attribute.
 * @throws BadFetchError
 *             No destination specified.
 * @since 0.7 TODO evaluate the telephone URI after RFC2806
 */
public String getDest() throws SemanticError, BadFetchError {
    final Transfer transfer = getTransfer();
    if (transfer == null) {
        return null;
    }
    String dest = transfer.getDest();
    if (dest != null) {
        return dest;
    }
    dest = transfer.getDestexpr();
    if (dest == null) {
        throw new BadFetchError("Either one of \"dest\" or \"destexpr\""
                + " must be specified!");
    }
    final String unescapedDestexpr = StringEscapeUtils.unescapeXml(dest);
    final VoiceXmlInterpreterContext context = getContext();
    final DataModel model = context.getDataModel();
    return model.evaluateExpression(unescapedDestexpr, String.class);
}
 
Example 13
Source Project: MLib   Source File: Functions.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static void unescapeDescription(DatenFilm film) {
    // Beschreibung
    film.arr[DatenFilm.FILM_BESCHREIBUNG] = StringEscapeUtils.unescapeXml(film.arr[DatenFilm.FILM_BESCHREIBUNG]);
    film.arr[DatenFilm.FILM_BESCHREIBUNG] = StringEscapeUtils.unescapeHtml4(film.arr[DatenFilm.FILM_BESCHREIBUNG]);
    film.arr[DatenFilm.FILM_BESCHREIBUNG] = StringEscapeUtils.unescapeJava(film.arr[DatenFilm.FILM_BESCHREIBUNG]);
    film.arr[DatenFilm.FILM_BESCHREIBUNG] = removeHtml(film.arr[DatenFilm.FILM_BESCHREIBUNG]);
}
 
Example 14
static void appendGetParametersShowOnly(Element form, final Map<String, String> getParameterMap) {
    Document doc = form.getOwnerDocument();

    Element fieldset = doc.createElement("fieldset");
    form.appendChild(fieldset);

    Element legend = doc.createElement("legend");
    legend.setTextContent("GET Parameters:");
    fieldset.appendChild(legend);

    Element table = doc.createElement("table");

    for (Map.Entry<String, String> parameter : getParameterMap.entrySet()) {
        Element tr = doc.createElement("tr");
        table.appendChild(tr);

        Element tdLeft = doc.createElement("td");
        tr.appendChild(tdLeft);
        tdLeft.setTextContent(parameter.getKey());

        Element tdRight = doc.createElement("td");
        tr.appendChild(tdRight);
        String value = StringEscapeUtils.escapeHtml4(parameter.getValue());
        tdRight.setTextContent(value);
    }
    if (!getParameterMap.isEmpty()) {
        fieldset.appendChild(table);
    }
}
 
Example 15
Source Project: Shop-for-JavaWeb   Source File: GenTemplateService.java    License: MIT License 5 votes vote down vote up
@Transactional(readOnly = false)
public void save(GenTemplate genTemplate) {
	if (genTemplate.getContent()!=null){
		genTemplate.setContent(StringEscapeUtils.unescapeHtml4(genTemplate.getContent()));
	}
	if (StringUtils.isBlank(genTemplate.getId())){
		genTemplate.preInsert();
		genTemplateDao.insert(genTemplate);
	}else{
		genTemplate.preUpdate();
		genTemplateDao.update(genTemplate);
	}
}
 
Example 16
Source Project: portals-pluto   Source File: HelloWorldRender.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Bean portlet render method for "BeanHelloWorld" portlet.
 */
@RenderMethod(portletNames = {"BeanPortlet"})
public String methodName() {
   
   // In it's simplest form, the render method just returns text.
   // The content type is set through the annotation.
   
   StringBuilder txt = new StringBuilder(128);
   
   txt.append("<h3>Hello \n");
   // Get the name from the bean. If it hasn't been set, just greet the world.
   if (nameBean.getName() != null) {
      txt.append(StringEscapeUtils.escapeHtml4(nameBean.getName()));
   } else {
      txt.append("World\n");
   }
   txt.append("!!</h3>\n");
   
   txt.append("<p><table id=\"").append(res.getNamespace());
   txt.append("_scope_info\" cellspacing='2' cellpadding='0'><tr><td align='left'>\n");
   txt.append("Application Scoped number:</td><td>").append(apprn.getRandomNumber());
   txt.append("</td></tr><tr><td>\n");
   txt.append("Session scoped number:</td><td>").append(sessrn.getRandomNumber());
   txt.append("</td></tr><tr><td>\n");
   txt.append("Portlet session scoped (Application) number:</td><td>").append(appsessrn.getRandomNumber());
   txt.append("</td></tr><tr><td>\n");
   txt.append("Portlet session scoped (Portlet) number:</td><td>").append(pltsessrn.getRandomNumber());
   txt.append("</td></tr><tr><td>\n");
   txt.append("Portlet Request number:</td><td>").append(pltreqrn.getRandomNumber());
   txt.append("</td></tr><tr><td>\n");
   txt.append("Request number:</td><td>").append(reqrn.getRandomNumber());
   txt.append("</td></tr></table></p>\n");
   
   txt.append("<p>User agent: ").append(req.getUserAgent()).append("</p>");
   
   return txt.toString();
}
 
Example 17
/** Gets the template used to initialise the code area. */
private static LiveTemplateBuilder<ObservableXPathRuleBuilder> liveTemplateBuilder() {
    return LiveTemplate.<ObservableXPathRuleBuilder>newBuilder()
        .withDefaultIndent("      ")
        .withDefaultEscape(StringEscapeUtils::escapeXml10)
        .append("<rule name=\"").bind(ObservableRuleBuilder::nameProperty).appendLine("\"")
        .appendIndent(1).append("language=\"").bind(ObservableRuleBuilder::languageProperty, Language::getTerseName).appendLine("\"")
        .bind(ObservableRuleBuilder::minimumVersionProperty, indented(2, surrounded("minimumLanguageVersion=\"", "\"\n", asString(LanguageVersion::getVersion))))
        .bind(ObservableRuleBuilder::maximumVersionProperty, indented(2, surrounded("maximumLanguageVersion=\"", "\"\n", asString(LanguageVersion::getVersion))))
        .withDefaultEscape(s -> s) // special escape for message
        .appendIndent(1).append("message=\"").bind(b -> b.messageProperty().map(ExportXPathWizardController::escapeMessageFormatter)).appendLine("\"")
        .withDefaultEscape(StringEscapeUtils::escapeXml10) // restore escaper
        .appendIndent(1).append("class=\"").bind(ObservableRuleBuilder::clazzProperty, Class::getCanonicalName).appendLine("\">")
        .withDefaultIndent("   ")
        .appendIndent(1).appendLine("<description>")
        .bind(ObservableRuleBuilder::descriptionProperty, wrapped(55, 2, true, asString())).endLine()
        .appendIndent(1).appendLine("</description>")
        .appendIndent(1).append("<priority>").bind(ObservableRuleBuilder::priorityProperty, p -> "" + p.getPriority()).appendLine("</priority>")
        .appendIndent(1).appendLine("<properties>")
        .bindTemplatedSeq(
            ObservableRuleBuilder::getRuleProperties,
            prop -> prop.appendIndent(2)
                        .append("<property name=\"").bind(PropertyDescriptorSpec::nameProperty)
                        .append("\" type=\"").bind(PropertyDescriptorSpec::typeIdProperty, PropertyTypeId::getStringId)
                        .append("\" value=\"").bind(PropertyDescriptorSpec::valueProperty)
                        .append("\" description=\"").bind(PropertyDescriptorSpec::descriptionProperty)
                        .appendLine("\"/>")
        )
        .appendIndent(2).append("<property name=\"version\" value=\"").bind(ObservableXPathRuleBuilder::xpathVersionProperty).appendLine("\"/>")
        .appendIndent(2).appendLine("<property name=\"xpath\">")
        .appendIndent(3).appendLine("<value>")
        .appendLine("<![CDATA[")
        .withDefaultEscape(s -> s) // stop escaping
        .bind(ObservableXPathRuleBuilder::xpathExpressionProperty).endLine()
        .appendLine("]]>")
        .appendIndent(3).appendLine("</value>")
        .appendIndent(2).appendLine("</property>")
        .appendIndent(1).appendLine("</properties>")
        .appendLine("</rule>");
}
 
Example 18
/**
 * {@inheritDoc}
 */
@Override
public final Object evaluateExpression(final DataModel model)
        throws SemanticError {
    final String expr = node.getAttribute("expr");
    if (expr == null) {
        return null;
    }
    final String unescapedExpr = StringEscapeUtils.unescapeXml(expr);
    return model.evaluateExpression(unescapedExpr, Object.class);
}
 
Example 19
public ResultStyleExpression(String result, String bundleName, Locale locale) {
    if (bundleName != null) {
        ResourceBundle resourceBundle = ResourceBundle.getBundle(bundleName, locale);
        this.result = StringEscapeUtils.unescapeHtml4(resourceBundle.getString(result));
    } else {
        this.result = result;
    }
}
 
Example 20
Source Project: jtwig-core   Source File: StringExpressionParser.java    License: Apache License 2.0 5 votes vote down vote up
Rule Escape() {
    return Sequence(Sequence(
                    '\\',
                    ANY
            ),
            run(peek().append(StringEscapeUtils.unescapeJava(match())))
    );
}
 
Example 21
Source Project: tools   Source File: License.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return the standardLicenseHeader
 */
public String getStandardLicenseHeader() {
	if (this.resource != null && this.refreshOnGet) {
		this.standardLicenseHeader = findSinglePropertyValue(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_STD_LICENSE_NOTICE);
		if (this.standardLicenseHeader == null) {
			this.standardLicenseHeader = findSinglePropertyValue(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_STD_LICENSE_HEADER_VERSION_1);
		}
		if (this.standardLicenseHeader != null) {
			this.standardLicenseHeader = StringEscapeUtils.unescapeHtml4(this.standardLicenseHeader);
		}
	}
	return standardLicenseHeader;
}
 
Example 22
Source Project: symphony-java-client   Source File: MlMessageParser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Experimental - will attempt to escape all text within xml elements
 * @param xml full xml
 * @return escaped xml string
 */
public static String escapeAllXml(String xml)
{
    // Match the pattern <something>text</something>
    Pattern xmlCleanerPattern = Pattern.compile("(<[^/<>]*>)([^<>]*)(</[^<>]*>)");

    StringBuilder xmlStringBuilder = new StringBuilder();

    Matcher matcher = xmlCleanerPattern.matcher(xml);
    int lastEnd = 0;
    while (matcher.find())
    {
        // Include any non-matching text between this result and the previous result
        if (matcher.start() > lastEnd) {
            xmlStringBuilder.append(xml.substring(lastEnd, matcher.start()));
        }
        lastEnd = matcher.end();

        // Sanitise the characters inside the tags and append the sanitised version
        String cleanText = StringEscapeUtils.escapeXml(matcher.group(2));
        xmlStringBuilder.append(matcher.group(1)).append(cleanText).append(matcher.group(3));
    }
    // Include any leftover text after the last result
    xmlStringBuilder.append(xml.substring(lastEnd));

    return xmlStringBuilder.toString();
}
 
Example 23
Source Project: windup   Source File: TagService.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private void escapeOrNull(final String string, Writer writer) throws IOException
{
    if (string == null)
        writer.append("null");
    else
        writer.append('"').append(StringEscapeUtils.escapeEcmaScript(string)).append('"');
}
 
Example 24
Source Project: discord.jar   Source File: WebhookImpl.java    License: The Unlicense 5 votes vote down vote up
@Override
public void changeAvatar(String avatar) {
    PacketBuilder pb = new PacketBuilder(api);
    pb.setType(RequestType.PATCH);
    pb.setData(new JSONObject().put("avatar", StringEscapeUtils.escapeJson(avatar)).toString());
    pb.setUrl("https://discordapp.com/api/webhooks/" + id);
    System.out.println(pb.makeRequest());
}
 
Example 25
Source Project: localization_nifi   Source File: JsonRowSerializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String serialize(byte[] rowKey, ResultCell[] cells) {
    final StringBuilder jsonBuilder = new StringBuilder();
    jsonBuilder.append("{");

    final String row = new String(rowKey, charset);
    jsonBuilder.append("\"row\":")
            .append("\"")
            .append(StringEscapeUtils.escapeJson(row))
            .append("\"");

    jsonBuilder.append(", \"cells\": {");
    int i = 0;
    for (final ResultCell cell : cells) {
        final String cellFamily = new String(cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength(), charset);
        final String cellQualifier = new String(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength(), charset);

        if (i > 0) {
            jsonBuilder.append(", ");
        }
        jsonBuilder.append("\"")
                .append(StringEscapeUtils.escapeJson(cellFamily))
                .append(":")
                .append(StringEscapeUtils.escapeJson(cellQualifier))
                .append("\":\"")
                .append(StringEscapeUtils.escapeJson(new String(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength(), charset)))
                .append("\"");
        i++;
    }

    jsonBuilder.append("}}");
    return jsonBuilder.toString();
}
 
Example 26
Source Project: winter   Source File: WebTablesStringNormalizer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param columnName
 * @return the normalised string
 */
public static String normaliseHeader(String columnName) {
	if(columnName==null)
	{
		return "";
	} else {
		columnName = StringEscapeUtils.unescapeJava(columnName);
		columnName = columnName.replace("\"", "");
		columnName = columnName.replace("|", " ");
		columnName = columnName.replace(",", "");
		columnName = columnName.replace("{", "");
		columnName = columnName.replace("}", "");
		columnName = columnName.replaceAll("\n", "");

		columnName = columnName.replace("&nbsp;", " ");
		columnName = columnName.replace("&nbsp", " ");
		columnName = columnName.replace("nbsp", " ");
		columnName = columnName.replaceAll("<.*>", "");

		columnName = columnName.toLowerCase();
		columnName = columnName.trim();

		columnName = columnName.replaceAll("\\.", "");
		columnName = columnName.replaceAll("\\$", "");
		// clean the values from additional strings
		// if (columnName.contains("/")) {
		// 	columnName = columnName.substring(0, columnName.indexOf("/"));
		// }

		// if (columnName.contains("\\")) {
		// 	columnName = columnName.substring(0, columnName.indexOf("\\"));
		// }
		if (possibleNullValues.contains(columnName)) {
			columnName = nullValue;
		}
		
		return columnName;
	}
}
 
Example 27
Source Project: tcases   Source File: XmlWriter.java    License: MIT License 5 votes vote down vote up
/**
 * Writes an attribute definition.
 */
protected void writeAttribute( String name, String value)
  {
  print( " ");
  print( name);
  print( "=\"");
  // StringEscapeUtils escapes symbols ', < >, &, ", and some control characters
  // NumericEntityEscaper translates additional control characters \n, \t, ...
  print( NumericEntityEscaper.below(0x20).translate(StringEscapeUtils.escapeXml11(value)));
  print( "\"");
  }
 
Example 28
Source Project: EchoQuery   Source File: VisualizationUtil.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void updateResultData(JSONObject data, Session session) {
  try {
    makeSureSessionExistsInDB(session.getUser().getUserId());
    Statement statement = conn.createStatement();
    statement.executeUpdate("update sessions set result='" +
        StringEscapeUtils.escapeJava(data.toString()) + "'where id='" +
        cleanId(session.getUser().getUserId()) + "';");
  } catch (SQLException e) {
    log.error(e.getMessage());
  }
}
 
Example 29
Source Project: datacollector   Source File: StringEL.java    License: Apache License 2.0 5 votes vote down vote up
@ElFunction(
    prefix = "str",
    name = "escapeXML11",
    description = "Returns a string safe to embed in an XML 1.1 document."
)
public static String escapeXml11(@ElParam("string") String string) {
  return StringEscapeUtils.escapeXml11(string);
}
 
Example 30
private String genericInfoContent(Map.Entry<String, String> pair) {
    return String.format(FOUR_SPACES_INDENT + TAG_WITH_TWO_ATTRIBUTES,
                         XMLTags.COMMON_INFO,
                         XMLAttributes.COMMON_NAME,
                         pair.getKey(),
                         XMLAttributes.COMMON_VALUE,
                         StringEscapeUtils.escapeXml11(pair.getValue()));
}