How to Use WikiToXhtmlMigrator to Convert using Confluence SDK - confluence

I am trying to convert WikiMarkup data to Confluence's XHTML based format. I saw there are 2 different ways to do the same.
1) Use the rest/XML Rpc based API convertWikiToStorageFormat(String token, String markup) to do the same.
2) Other way is to use WikiToXhtmlMigrator to do the same Task. Since I am using Confluence SDK, I choose 2nd way to do the same.
public String getXHTMLConvertedTextFromWiki(String markupData){
String content = null;
try {
RenderContext renderContext = new RenderContext();
DefaultConversionContext defaultConversionContext = new DefaultConversionContext(renderContext);
ExceptionTolerantMigrator wikiToXhtmlMigrator = (ExceptionTolerantMigrator) ContainerManager.getComponent("wikiToXhtmlMigrator");
content = wikiToXhtmlMigrator.migrate(markupData, defaultConversionContext).getContent();
}catch(Exception e){
e.printStackTrace();
}
return content;
}
But Always, I am getting the exception:
[INFO] [talledLocalContainer] java.lang.NullPointerException
[INFO] [talledLocalContainer] at com.atlassian.confluence.content.render.xhtml.migration.WikiToXhtmlMigrator.migrate(WikiToXhtmlMigrator.java:57)
[INFO] [talledLocalContainer] at com.atlassian.confluence.content.render.xhtml.migration.WikiToXhtmlMigrator.migrate(WikiToXhtmlMigrator.java:69)
I tried to push the render mode by setting All in render Context but got the same exception.
renderContext.pushRenderMode(RenderMode.ALL);
Please let me know the what is the problem in this example and show the correct way to do it.

Able to convert markup to Xhtml through below code.
public String getXHTMLConvertedTextFromWiki(String wikiText){
String content = null;
try {
List<RuntimeException> exceptions = newArrayList();
XhtmlContent xhtmlContent = (XhtmlContent)ContainerManager.getComponent("xhtmlContent");
content = xhtmlContent.convertWikiToStorage(wikiText, new DefaultConversionContext(new PageContext()),exceptions);
for(RuntimeException e : exceptions){
log.error(e.getMessage());
}
}catch(Exception e){
e.printStackTrace();
}
return content;
}
Please make sure that, your newline characters should not be lost while reading Page Markup Data if reading from external source.

Related

GitHub Readme.md markdown file data-canonical-src issue with image src

I have an azure function that returns an image of my top blog from my feed. Now I have just added that function URL as the image src as below in the Readme.md file.
<img src="https://getlatestposts.azurewebsites.net/api/GetLatestPosts?code=VS4fy5DNxpj8/SUS0Chp0aGBux36c9OyOg5KhmSjh5dPVBvCaVaEuA==">
But the image is not loading at all, and when I check the HTML generated, I could see that the src is been updated with some weird URL from "https://camo.githubusercontent.com". There is also an additional a tag introduced.
Anyone else faced this issue?
Finally, I was able to fix this issue. What I did is that, I returned a File Stream from my Azure Function, instead of returning a base64 string. Below is my Azure function.
[FunctionName("GetLatestPosts")]
public static FileStreamResult Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest request, ILogger log) {
try {
var baseString = WriteOnImage(GetLatestFeeds());
// Had to do this, as it was throwing error "The input is not a valid Base-64 string as it contains a non-base 64 character"
string convert = baseString.Replace("data:image/png;base64,", String.Empty);
var bytes = Convert.FromBase64String(convert);
var result = new FileStreamResult(new MemoryStream(bytes), Configuration.ContentType);
log.LogInformation("Returning stream now!");
request.HttpContext.Response.Headers.Add("Cache-Control", "s-maxage=1, stale-while-revalidate");
return result;;
} catch (System.Exception ex) {
log.LogError($ "Something went wrong: {ex}");
throw ex;
}
}
I did write an article about this entire application, you can read it here. It contains the GitHub repositories too, just in case, if you are interested.

Plug-In that Converted Note entity pre-existing attachment XML file into new .MMP file

strong text [Plugin error at Note entity][1]
[1]: http://i.stack.imgur.com/hRIi9.png
Hi,Anyone resolved my issue i got a Plug-in error which i worked at Update of "Note" entity.Basically i want a Plugin which converted pre-exiting Note attachment XML file into new .MMP extension file with the same name.
I have done following procedure firstly i created a "Converter_Code.cs" dll which contains Convert() method that converted XML file to .MMP file here is the constructor of the class.
public Converter(string xml, string defaultMapFileName, bool isForWeb)
{
Xml = xml;
DefaultMapFileName = defaultMapFileName;
Result = Environment.NewLine;
IsForWeb = isForWeb;
IsMapConverted = false;
ResultFolder = CreateResultFolder(MmcGlobal.ResultFolder);
}
In ConvertPlugin.cs Plug-in class firstly i retrieved Note entity attachment XML file in a string using following method in
IPluginExecutionContext context =(IPluginExecutionContext)serviceProvider.
GetService (typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory= (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService
(context.UserId);
if (context.InputParameters.Contains("Target")
&& context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parameters.
Entity entity = (Entity)context.InputParameters["Target"];
var annotationid = entity.GetAttributeValue<Guid>("annotationid");
if (entity.LogicalName != "annotation")
{
return;
}
else
{
try
{
//retrieve annotation file
QueryExpression Notes = new QueryExpression { EntityName ="annotation"
,ColumnSet = new ColumnSet("filename", "subject", "annotationid",
"documentbody") };
Notes.Criteria.AddCondition("annotationid", ConditionOperator.Equal,
annotationid);
EntityCollection NotesRetrieve = service.RetrieveMultiple(Notes);
if (NotesRetrieve != null && NotesRetrieve.Entities.Count > 0)
{
{
//converting document body content to bytes
byte[] fill = Convert.FromBase64String(NotesRetrieve.Entities[0]
.Attributes["documentbody"].ToString());
//Converting to String
string content = System.Text.Encoding.UTF8.GetString(fill);
Converter objConverter = new Converter(content, "TestMap", true);
objConverter.Convert();
}
}
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("something is going wrong");
}
}
}
}
and than A string is passed to "Converter" constructor as a parameter.
finally i merged all dll using ILMerge following method:
ilmerge /out:NewConvertPlugin.dll ConvertPlugin.dll Converter_Code.dll
and NewConvertPlugin is registered successfully but while its working its generate following error:
Unexpected exception from plug-in (Execute): ConverterPlugin.Class1: System.Security.SecurityException: That assembly does not allow partially trusted callers.
i also debug the plugin using Error-log but its not worked so i could not get a reason whats going wrong.
The error is caused by the library you merged inside your plugin.
First of all you are using CRM Online (from your screenshot) and with CRM Online you can use only register plugins inside sandbox.
Sandbox means that your plugins are limited and they run in a partial-trust environment.
You merged an external library that requires full-trust permissions, so your plugin can't work and this is the reason of your error.
Because you are in CRM Online, or you find another library (the Converter) that requires only partial-trust, hoping that the merge process will work, or you include (if you have it) the source code of the converter library directly inside your plugin.

java api to get a file content for enterprise github

I tried so hard for a simple line of code that read a file content from enterprise github with oauth token, but could not find a example of such.
I tried https://github.com/jcabi/jcabi-github, but it does not support enterprise github?(maybe I am wrong)
Now i am trying egit:
GitHubClient client = new GitHubClient("enterprise url");
GitHubRequest request = new GitHubRequest();
request.setUri("/readme");
GitHubResponse response = client.get(request);
Then what? I only saw a getBody, maybe I need to parse it with some kinda json library? It has to be simpler..I am expecting something like: repo.get(url).getContent()
Finally figure out by reading source code..
GitHubClient client = new GitHubClient(YOURENTERPRICEURL);
client.setOAuth2Token(token);
// first use token service
RepositoryService repoService = new RepositoryService(client);
try {
Repository repo = repoService.getRepository(USER, REPONAME);
// now contents service
ContentsService contentService = new ContentsService(client);
List<RepositoryContents> test = contentService.getContents(repo, YOURFILENAME);
List<RepositoryContents> contentList = contentService.getContents(repo);
for(RepositoryContents content : test){
String fileConent = content.getContent();
String valueDecoded= new String(Base64.decodeBase64(fileConent.getBytes() ));
System.out.println(valueDecoded);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

GWT Upload/Download best practices

So I am new to GWT and am not sure what the best programming practices are for what I am trying to do. In my web application the user will be able to upload a data file, my application needs to be able to access this file, do some stuff to it, and then let the user download the manipulated file.
So far I have been able to successfully upload a file with an upload servlet with this doPost method:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory);
fileUpload.setSizeMax(FILE_SIZE_LIMIT);
List<FileItem> items = fileUpload.parseRequest(req);
for (FileItem item : items) {
if (item.isFormField()) {
logger.log(Level.INFO, "Received form field:");
logger.log(Level.INFO, "Name: " + item.getFieldName());
logger.log(Level.INFO, "Value: " + item.getString());
} else {
logger.log(Level.INFO, "Received file:");
logger.log(Level.INFO, "Name: " + item.getName());
logger.log(Level.INFO, "Size: " + item.getSize());
}
if (!item.isFormField()) {
if (item.getSize() > FILE_SIZE_LIMIT) {
resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, "File size exceeds limit");
return;
}
String fileName = item.getName();
if (fileName != null) {
fileName = FilenameUtils.getName(fileName);
}
fileName = getServletContext().getRealPath("/uploadedFiles/" + fileName);
byte[] data = item.get();
FileOutputStream fileOutSt = new FileOutputStream(fileName);
fileOutSt.write(data);
fileOutSt.close();
if (!item.isInMemory())
item.delete();
}
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e);
throw new ServletException(e);
}
}
When I look in my war folder, the uploadedFiles folder is created successfully and files are put there.
At this point I am a bit stuck, I have been researching but cannot seem to find a clear concise answer on what is the best way for me to access the uploaded files on the client side in order to manipulate them and then allow the user to download them. Maybe I am approaching this wrong, I am not sure. If someone could point me in the right direction or show me some good examples of the right way to do things that would be great, thanks.
To access the file in client side you need a new servlet or the same you are using with a doGet method.
The client should ask for the file via an Anchor or an Image depending on the file type but adding a parameter so as the server is able to identify the file. Normally you can use the name of the FileInput you used for uploading or maybe you could return a tag from the server.
I would recommend to you to take a try to gwt-upload, it would save a lot of time to you.
I solved my problem. When the file was successfully uploaded, I stored the file name. Later I used a RPC to access the file on the server. I passed the file name to the RPC so that it knows what file I am working on, then it looks for that file in the upload folder. So I can create the java file like this,
File file = new File((this.getServletContext().getRealPath("uploadedFiles") + File.separator + fileName));
and manipulate it how I see fit.

multiple pages with C# Web browser control

I am trying to download HTML content from any URL through webbrowser control in C#.net.
I choose webrowser to handle Javascript issues. I am using webbrowser control without placing
it on the form. It works great for one url, but when I call it for multiple urls I am unable
to download the page.
Here is the code
GetWebpage()
{
System.Windows.Forms.WebBrowser wb = new System.Windows.Forms.WebBrowser();
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
wb.Navigate(sURI, false);
bDocumentLoaded = false;
while (!bDocumentLoaded)
{
Application.DoEvents();
Thread.Sleep(100);
}
sHTML = wb.DocumentText;
bDocumentLoaded = false;
}
Event:
private void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
System.Windows.Forms.WebBrowser webBrowser1;
webBrowser1 = sender as WebBrowser;
string strTit = webBrowser1.DocumentTitle;
string str = webBrowser1.DocumentText;
bDocumentLoaded = true;
}
Cheers,
Karthik
You can use webclient object to fetch data from some url.
Try using Downloading String
public static void DownloadString (string address)
{
WebClient client = new WebClient ();
string reply = client.DownloadString (address);
Console.WriteLine (reply);
}
You can also use ASYC method of same downloading string.
I think your problem is that some sites are detecting specific browsertype and then they are returning HTML
Try setting the HeaderProperty of WebClient Object this is a list of HttpWebRequest Object
For Example
myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");
Modify the useragent of HTTPWEBRequest then add to headers.
HTTPWEBRequest.UserAgent=".NET Framework Test Client";
You can check more information about this in MSDN Link
I might recommend using the mshtml and SHDocVW libraries and using approach found in the answer here:
Unable to to locate and click a submit button using mshtml.HTMLInputElement