org.apache.commons.lang3.StringEscapeUtils Java Examples

The following examples show how to use org.apache.commons.lang3.StringEscapeUtils. 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 File: ClassifiedTweet.java    From AIDR with 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 File: TPatchTool.java    From atlas with 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 #3
Source File: ServerUnavailabilityResponse.java    From gocd with 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 #4
Source File: StringUtils.java    From easyweb with 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 #5
Source File: TransferFormItem.java    From JVoiceXML with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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 #6
Source File: HaskellHttpClientCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@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 #7
Source File: CommonsSpiderPanel.java    From spider with 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 #8
Source File: RhnHiddenTag.java    From uyuni with 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 #9
Source File: PrettyPrintFilter.java    From jinjava with 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 #10
Source File: MenuController.java    From zest-writer with 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 #11
Source File: HttpClientUtils.java    From paas with 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 #12
Source File: MockEC2QueryHandler.java    From aws-mock with 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 #13
Source File: RequestResponeLoggingFilterTest.java    From parsec-libraries with Apache License 2.0 5 votes vote down vote up
private String createLogStringPatternForError(String requestMethod, String url, String queryString,
                                              Map<String, Collection<String>> reqHeaders, String reqBodyJson,
                                              Object error) throws JsonProcessingException {

    Map<String, String> headers = reqHeaders.entrySet().stream().collect(
            Collectors.toMap(Map.Entry::getKey,
                    e -> String.join(",", e.getValue())));


    String reqHeaderString = _OBJECT_MAPPER.writeValueAsString(headers);
    String pattern = String.format("{" +
                    "\"time\":\"${json-unit.any-number}\","+
                    "\"request\": {" +
                        "\"method\": \"%s\"," +
                        "\"uri\": \"%s\"," +
                        "\"query\": \"%s\"," +
                        "\"headers\": %s," +
                        "\"payload\": \"%s\"" +
                        "}," +
                    "\"response\": {}," +
                    "\"response-error\": \"${json-unit.ignore}\", " +
                    "\"progress\": {" +
                        "\"namelookup_time\": \"${json-unit.any-number}\"," +
                        "\"connect_time\": \"${json-unit.any-number}\"," +
                        "\"pretransfer_time\": \"${json-unit.any-number}\"," +
                        "\"starttransfer_time\": \"${json-unit.any-number}\"," +
                        "\"total_time\":\"${json-unit.any-number}\"" +
                        "}" +
                    "}", requestMethod, url, queryString, reqHeaderString, StringEscapeUtils.escapeJson(reqBodyJson));

    return pattern;

}
 
Example #14
Source File: XmlMessages.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method to format a string from the resource bundle.  This
 * method allows the user of this class to directly specify the
 * bundle package name to be used.  Allows us to have
 * resource bundles in packages without classes.  Eliminates
 * the need for "Dummy" classes.
 *
 * @param clazz the class to which the string belongs
 * @param locale the locale used to find the resource bundle
 * @param key the key for the string to be obtained from the resource bundle
 * @param args the arguments that should be applied to the string obtained
 * from the resource bundle. Can be null, to represent no arguments
 * @return the formatted message for the given key and arguments
 */
public String format(final Class clazz,
                            final Locale locale,
                            final String key,
                            final Object... args) {

    // Fetch the bundle
    ResourceBundle bundle = getBundle(getBundleName(clazz), locale);
    String pattern = StringEscapeUtils.unescapeHtml4(bundle.getString(key));

    pattern = pattern.replaceAll(PRODUCT_NAME_MACRO,
            Config.get().getString("product_name"));

    pattern = pattern.replaceAll(VENDOR_NAME_MACRO,
            Config.get().getString("java.vendor_name"));

    pattern = pattern.replaceAll(ENTERPRISE_LINUX_NAME_MACRO,
            Config.get().getString("java.enterprise_linux_name"));

    pattern = pattern.replaceAll(VENDOR_SERVICE_NAME_MACRO,
            Config.get().getString("java.vendor_service_name"));

    if (args == null || args.length == 0) {
        return pattern;
    }

    //MessageFormat uses single quotes to escape text. Therefore, we have to
    //escape the single quote so that MessageFormat keeps the single quote and
    //does replace all arguments after it.
    String escapedPattern = pattern.replaceAll("'", "''");
    MessageFormat mf = new MessageFormat(escapedPattern, locale);
    return mf.format(args);
}
 
Example #15
Source File: CompareDeployedSubmitAction.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
private void makeMessage(Action action, HttpServletRequest request) {
    if (action != null) {
        //get how many servers this action was created for.
        int successes = action.getServerActions().size();
        String number = LocalizationService.getInstance()
                .formatNumber(successes);

        //build the url for the action we have created.
        String url = "/rhn/schedule/ActionDetails.do?aid=" + action.getId();

        //create the success message
        ActionMessages msg = new ActionMessages();
        String key;
        if (successes == 1) {
            key = "configdiff.schedule.success.singular";
        }
        else {
            key = "configdiff.schedule.success";
        }

        Object[] args = new Object[2];
        args[0] = StringEscapeUtils.escapeHtml4(url);
        args[1] = StringEscapeUtils.escapeHtml4(number);

        //add in the success message
        msg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(key, args));
        getStrutsDelegate().saveMessages(request, msg);
    }
    else {
        //Something went wrong, tell user!
        ActionErrors errors = new ActionErrors();
        getStrutsDelegate().addError("configdiff.schedule.selection_error",
                errors);
        getStrutsDelegate().saveMessages(request, errors);
    }
}
 
Example #16
Source File: ChannelOverviewTasks.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
private void makeMessage(int successes, HttpServletRequest request) {
    if (successes > 0) {
        String number = LocalizationService.getInstance()
                .formatNumber(successes);

        //create the success message
        ActionMessages msg = new ActionMessages();
        String key;
        if (successes == 1) {
            key = "configdiff.schedule.success.singular";
        }
        else {
            key = "configdiff.schedule.success";
        }

        Object[] args = new Object[1];
        args[0] = StringEscapeUtils.escapeHtml4(number);

        //add in the success message
        msg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(key, args));
        getStrutsDelegate().saveMessages(request, msg);
    }
    else {
        //Something went wrong, tell user!
        ActionErrors errors = new ActionErrors();
        getStrutsDelegate().addError("configdiff.schedule.error", errors);
        getStrutsDelegate().saveMessages(request, errors);
    }
}
 
Example #17
Source File: CypherQueryGraphHelper.java    From streams with Apache License 2.0 5 votes vote down vote up
/**
 * getPropertyCreater.
 * @param map paramMap
 * @return PropertyCreater string
 */
public static String getPropertyCreater(Map<String, Object> map) {
  StringBuilder builder = new StringBuilder();
  builder.append("{ ");
  List<String> parts = new ArrayList<>();
  for( Map.Entry<String, Object> entry : map.entrySet()) {
    if( entry.getValue() instanceof String ) {
      String propVal = (String) (entry.getValue());
      parts.add("`"+entry.getKey() + "`:'" + StringEscapeUtils.escapeJava(propVal) + "'");
    }
  }
  builder.append(String.join(" ", parts));
  builder.append(" }");
  return builder.toString();
}
 
Example #18
Source File: ActivateUserEmailTransformer.java    From website with GNU Affero General Public License v3.0 5 votes vote down vote up
private Map<String, Object> buildModel(final User user) {
	Map<String, Object> model = new HashMap<String, Object>();
	model.put("appUrl", getApplicationUrl());
	String userActivationHash = userService.buildUserActivationHash(user);
	String activateUrl = getApplicationUrl() + "/activate?email=" + StringEscapeUtils.escapeHtml4(user.getEmail()) + "&hash=" + userActivationHash;
	model.put("activateUrl", activateUrl);
	model.put("user", user);
	return model;
}
 
Example #19
Source File: PhoenixRuntime.java    From phoenix with Apache License 2.0 5 votes vote down vote up
private static char getCharacter(String s) {
    String unescaped = StringEscapeUtils.unescapeJava(s);
    if (unescaped.length() > 1) {
        throw new IllegalArgumentException("Invalid single character: '" + unescaped + "'");
    }
    return unescaped.charAt(0);
}
 
Example #20
Source File: CypherQueryGraphHelper.java    From streams with Apache License 2.0 5 votes vote down vote up
/**
 * getPropertyParamSetter.
 * @param map paramMap
 * @return PropertyParamSetter string
 */
public static String getPropertyParamSetter(Map<String, Object> map, String symbol) {
  StringBuilder builder = new StringBuilder();
  for( Map.Entry<String, Object> entry : map.entrySet()) {
    if( entry.getValue() instanceof String ) {
      String propVal = (String)(entry.getValue());
      builder.append("," + symbol + ".`" + entry.getKey() + "` = '" + StringEscapeUtils.escapeJava(propVal) + "'");
    }
  }
  return builder.toString();
}
 
Example #21
Source File: WebhookImpl.java    From discord.jar with 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 #22
Source File: CustomHttpServletRequestWrapper.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
@Override  
public String[] getParameterValues(String name) {  
     String[] values = super.getParameterValues(name);  
     if(values != null && values.length > 0){  
         for(int i =0; i< values.length ;i++){  
             values[i] = StringEscapeUtils.escapeEcmaScript(values[i]);  
         }  
     }  
    return values;  
 }
 
Example #23
Source File: ConfigActionFormatter.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String getRelatedObjectDescription() {
    Set<ConfigRevisionAction> revisionActions = ((ConfigAction) getAction())
        .getConfigRevisionActions();
    List<String> result = new LinkedList<String>();
    if (revisionActions != null) {
        for (ConfigRevisionAction revisionAction : revisionActions) {
            ConfigRevision revision = revisionAction.getConfigRevision();
            if (revision != null) {
                ConfigFile configFile = revision.getConfigFile();
                if (configFile != null) {
                    ConfigFileName configFileName = configFile.getConfigFileName();
                    if (configFileName != null) {
                        result.add(
                            "<a href=\"/rhn/configuration/file/FileDetails.do?crid=" +
                            revision.getId().toString() +
                            "\">" +
                            StringEscapeUtils.escapeHtml4(configFileName.getPath()) +
                            "</a>"
                        );
                    }
                }
            }
        }
    }
    return StringUtil.join(", ", result);
}
 
Example #24
Source File: GetJobContentGenerator.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
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()));
}
 
Example #25
Source File: StringEL.java    From datacollector with 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 #26
Source File: Functions.java    From MLib with 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 #27
Source File: XmlWriter.java    From tcases with 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 File: WebTablesStringNormalizer.java    From winter with 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 #29
Source File: JsonRowSerializer.java    From localization_nifi with 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 #30
Source File: VisualizationUtil.java    From EchoQuery with 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());
  }
}