Velocity: Keep carriage returns and tabs - velocity

I'm using Velocity and JavaMail with spring to create mails for a Java app.
I save a Hibernate #Lob in database.
My clob is saved with carriage returns and tabulations in db:
but when I receive the mail my text is not formatted anymore:
My code is quite simple:
Map model = new HashMap();
model.put("monitoringError", baseMonitoringError);
model.put("businessCode", businessCode);
String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "velocity/crashMailTemplate.vm", "UTF-8", model);
from the template:
<p><strong>Stacktrace:</strong></p>
<p><em><span class="crayon-i ">${monitoringError.stacktrace}</span> </em></p>
...and the baseMonitoringError bean is a Hibernate Entity with
#Lob
#Column
private String stacktrace;
How should I do to keep the formatted original text?
Thanks

Try with:
${monitoringError.stacktrace.replace("\n","<br/>")}
or, depending on your platform:
${monitoringError.stacktrace.replace("\r\n","<br/>")}

Related

newtonsoft SerializeXmlNode trailing nulls

I am creating an XmlDoc in C# and using Newtonsoft to serialize to JSON. It works, but I am getting a bunch of what appear to be "NUL"'s at the end of the JSON. No idea why. Anyone seen this before?
CODE:
XmlDocument xmlDoc = BuildTranslationXML(allTrans, applicationName, language);
// Convert the xml doc to json
// the conversion inserts \" instead of using a single quote, so we need to replace it
string charToReplace = "\"";
string jsonText = JsonConvert.SerializeXmlNode(xmlDoc);
// json to a stream
MemoryStream memoryStream = new MemoryStream();
TextWriter tw = new StreamWriter(memoryStream);
tw.Write(jsonText);
tw.Flush();
tw.Close();
// output the stream as a file
string fileName = string.Format("{0}_{1}.json", applicationName, language);
return File(memoryStream.GetBuffer(), "text/json", fileName);
The file is served up to the calling web page and the browser prompts the user to save the file. When opening the file, it displays the correct JSON but also has all the trailing nulls. See image below (hopefully the stackoverflow link works):
file screenshot
The GetBuffer() method returns the internal representation of the MemoryStream. Use ToArray() instead to get just the part of that internal array that has data Newtonsoft has put in there.

Hybris DataHub INVALID_LOCALE Exception

I have localized raw data item baseName. I want to send localized raw data item to DataHub. I read many documents, it writes send localized raw attribute value but I couldn't find the format of the localized attribute value. In the composition, it throws INVALID_LOCALE exception.
I am sending value for baseName, but how can I localized "XYZ"?
RawFragmentData rawFragmentData = new RawFragmentData();
final Map<String, String> line = new HashMap<>();
........
line.put("baseName", "XYZ");
........
rawFragmentData.setValueMap(line);
rawFragmentData.setType(type);
rawFragmentData.setDataFeedName(feedName);
rawFragmentData.setExtensionSource(Constants.DATAHUB_EXTENSION_SOURCE);
return rawFragmentData;
e.g OOTB :
DefaultPartnerContributor.Java :-
row.put(PartnerCsvColumns.COUNTRY_ISO_CODE, address.getCountry());
Same way you might have languageColumn for it, so just pass language value to it.

Google diff-match-patch : How to unpatch to get Original String?

I am using Google diff-match-patch JAVA plugin to create patch between two JSON strings and storing the patch to database.
diff_match_patch dmp = new diff_match_patch();
LinkedList<Patch> diffs = dmp.patch_make(latestString, originalString);
String patch = dmp.patch_toText(diffs); // Store patch to DB
Now is there any way to use this patch to re-create the originalString by passing the latestString?
I google about this and found this very old comment # Google diff-match-patch Wiki saying,
Unpatching can be done by just looping through the diff, swapping
DIFF_INSERT with DIFF_DELETE, then applying the patch.
But i did not find any useful code that demonstrates this. How could i achieve this with my existing code ? Any pointers or code reference would be appreciated.
Edit:
The problem i am facing is, in the front-end i am showing a revisions module that shows all the transactions of a particular fragment (take for example an employee details), like which user has updated what details etc. Now i am recreating the fragment JSON by reverse applying each patch to get the current transaction data and show it as a table (using http://marianoguerra.github.io/json.human.js/). But some JSON data are not valid JSON and I am getting JSON.parse error.
I was looking to do something similar (in C#) and what is working for me with a relatively simple object is the patch_apply method. This use case seems somewhat missing from the documentation, so I'm answering here. Code is C# but the API is cross language:
static void Main(string[] args)
{
var dmp = new diff_match_patch();
string v1 = "My Json Object;
string v2 = "My Mutated Json Object"
var v2ToV1Patch = dmp.patch_make(v2, v1);
var v2ToV1PatchText = dmp.patch_toText(v2ToV1Patch); // Persist text to db
string v3 = "Latest version of JSON object;
var v3ToV2Patch = dmp.patch_make(v3, v2);
var v3ToV2PatchTxt = dmp.patch_toText(v3ToV2Patch); // Persist text to db
// Time to re-hydrate the objects
var altV3ToV2Patch = dmp.patch_fromText(v3ToV2PatchTxt);
var altV2 = dmp.patch_apply(altV3ToV2Patch, v3)[0].ToString(); // .get(0) in Java I think
var altV2ToV1Patch = dmp.patch_fromText(v2ToV1PatchText);
var altV1 = dmp.patch_apply(altV2ToV1Patch, altV2)[0].ToString();
}
I am attempting to retrofit this as an audit log, where previously the entire JSON object was saved. As the audited objects have become more complex the storage requirements have increased dramatically. I haven't yet applied this to the complex large objects, but it is possible to check if the patch was successful by checking the second object in the array returned by the patch_apply method. This is an array of boolean values, all of which should be true if the patch worked correctly. You could write some code to check this, which would help check if the object can be successfully re-hydrated from the JSON rather than just getting a parsing error. My prototype C# method looks like this:
private static bool ValidatePatch(object[] patchResult, out string patchedString)
{
patchedString = patchResult[0] as string;
var successArray = patchResult[1] as bool[];
foreach (var b in successArray)
{
if (!b)
return false;
}
return true;
}

Linqpad - Outputting into anchor to use title

I have a db that stores exception messages.
I would like to create a query that gets these exceptions but instead of dumping huge amounts of text i would prefer it to be "on demand".
I figured putting the exception into an anchor tag like so and then reading the message when needed by mousing over it would work... apparently not.
var logsForErrors = (from error in Logs
select new {
error = LINQPad.Util.RawHtml("<a title='"+ error.Exception+"'></a>"),
errorDate = error.Date,
errorMessage = error.Message
}).Take(10);
logsForErrors.Dump();
This is throwing an exception (lol) - "Cannot parse custom HTML: "
Encoding the exception message
...RawHtml("<a title='"+ Uri.EscapeDataString(error.Exception)+"'></a>")
Message Could not translate expression 'RawHtml((("h__TransparentIdentifier0.error.Exception)) +
"'>"))' into SQL and could not treat it as a local expression.
will generate a new error
Any ideas? - I am open to alternative solutions to this also.
I just want a container for the message instead of it just dumping right into the output as it it so huge!.
Thanks,
Kohan
Have you tried using the "Results to DataGrids" mode in the recent betas? It might do just what you need without having to write anything else.
Edit: your error was probably due to emitting HTML without escaping the text. The easiest solution is to call Util.RawHtml with an XElement instead of a string. You could write an extension method that does what you want like this:
public static class Extensions
{
public static object Tooltipize (this string data)
{
if (string.IsNullOrEmpty (data) || data.Length < 20) return data;
return Util.RawHtml (new XElement ("span", new XAttribute ("title", data), data.Substring (0, 20)));
}
}
Put this into My Extensions and you can use it from any query.

convert vb.net data to json string and send it to a specific URL

this is the JSON string the data is required in to be sent using a given URL.
$jsonstr = '{"data":
[{
"id":"5",
"owner_id":"0",
"status":"unassigned",
"first_name":"Test",
"last_name":"IS",
"tobacco_user":"",
"date_of_birth":"",
"age":"",
"gender":"",
"email":"lb#you.com",
"zip":"",
"phone":"(210)629-2560",
"phone_type":"cell",
"phone_alt":"",
"phone_alt_type":"",
"product_msip":"",
"product_pdp":"",
"product_sdhv":""
},
I am using VB.net and i need to create this string using VB.net. I tried using namevaluecollection and doing a POST. I also tried making a string and send data using GET. Both failed. how can i do this?
Create an object with property names that are identical to those in your example, use the DataContract and DataMember attributes to mark serialization.
Then use the JavaScriptSerializer to serialize the object into JSON.
you can use the class when you want to work with JavaScript Object Notation (JSON) in managed code.
If you don't want to build an actual class as #Oded recommended you can just hack it together as a string. I usually use a NameValueCollection as you said you tried.
''//Setup some values
Dim NVC As New NameValueCollection()
NVC.Add("id", "5")
NVC.Add("owner_id", "0")
NVC.Add("status", "unassigned")
''//Convert to string
Dim Pairs As New List(Of String)
For Each N As String In NVC.Keys
Pairs.Add(String.Format("""{0}"":""{1}""", N.Replace("""", "\"""), NVC(N).Replace("""", "\""")))
Next
Dim S = Join(Pairs.ToArray(), ",")
S now holds "id":"5","owner_id":"0","status":"unassigned" which you should be able to concat into your bigger JSON string.