Unable to load an html file (from local file system) using JxBrowser - javafx

Using JavaFX and Eclipse IDE, I have used the sample app from Teamdev for loading a sample file (notifications.html from my file system) but I keep getting the page not found/DNS error.
The file in question, notifications.html, is right there in the same package as the source file that invokes it as shown in the snippet below:
Scene scene = new Scene(new BorderPane(view), 700, 500);
primaryStage.setScene(scene);
primaryStage.show();
browser.loadURL("notifications.html");
I think my issue is composing the fully qualified path and since I'm using a Mac, it is not clear to me how to do this. I have tried:
browser.loadURL("Users/myusername/Documents/workspace/jxBrowser/src/application/notifications.html");
However it did not work.

You need to use loadHtml() instead loadUrl() suppose loadHtml goes to network and you try to download url from file on your pc. Read html from filesystem to String and pass it to loadHtml() method.
InputStream urlStream = getClass().getResourceAsStream("/notifications.html");
String html = null;
try (BufferedReader urlReader = new BufferedReader(new InputStreamReader (urlStream))) {
StringBuilder builder = new StringBuilder();
String row;
while ((row = urlReader.readLine()) != null) {
builder.append(row);
}
html = builder.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
browser.loadHTML(html);
for this code your html file must be in resources folder of your project

Related

Async await to save file causes "Process cannot access file because it is being used by another process" error

I have the following code to save an excel file on the server and then read its content:
if (file.Length > 0)
{
string path = _hostingEnvironment.ContentRootPath + "/CSV-import-students/";
FileStream fs = new FileStream(Path.Combine(path, file.FileName), FileMode.Create);
await file.CopyToAsync(fs);
FileInfo fileUploaded = new FileInfo(Path.Combine(path, file.FileName));
using (ExcelPackage package = new ExcelPackage(fileUploaded))
{
StringBuilder sb = new StringBuilder();
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
int rowCount = worksheet.Dimension.Rows;
int ColCount = worksheet.Dimension.Columns;
bool bHeaderRow = true;
}
The file is saved fine on the server. But, then when I try to access it, I receive "Process cannot access file because it is being used by another process" error. How can I prevent this error? Any ideas?
Almost invariably, when newing up a class that implements IDisposable (such as FileStream), you should do so with a using statement:
using (var fs = new FileStream(Path.Combine(path, file.FileName), FileMode.Create))
{
await file.CopyToAsync(fs);
}
This will automatically dispose of the resource when the using statement goes out of scope, and in the case of FileStream, will flush the write and close the file. That's the source of your issue, so this will solve your problem.
However, you might also need to contend with concurrency. It's possible for two requests to be processed simultaneously that both need to work with the same file. You should plan for concurrency, by catching file access violation exceptions and responding via a retry policy. The Polly exception handling library can help here.

JxBrowser not connecting

I am having troubles to make the jxbrowser work outside of the development environment. When I run it in eclipse it works fine, but when I compile it and run the screen doesn't seems to load. Here is the code that I'm using:
browser = new Browser();
com.teamdev.jxbrowser.chromium.swing.BrowserView view = new com.teamdev.jxbrowser.chromium.swing.BrowserView(browser);
javax.swing.JFrame frame = new javax.swing.JFrame();
frame.add(view, java.awt.BorderLayout.CENTER);
frame.setSize(800, 450);
frame.setVisible(true);
browser.loadURL(Main.class.getResource("/assets/engine.html").toExternalForm());
> When I run from eclipse <
> When I compile and run <
Am I missing something?
If your HTML resource "/assets/engine.html" is located inside the RPGItems.jar after build, the path to it will not be resolved properly by the Chromium engine by default. To be able to load resources located inside JAR archive you must register custom ProtocolHandler with the following implementation:
BrowserContext browserContext = browser.getContext();
ProtocolService protocolService = browserContext.getProtocolService();
protocolService.setProtocolHandler("jar", new ProtocolHandler() {
#Override
public URLResponse onRequest(URLRequest request) {
try {
URLResponse response = new URLResponse();
URL path = new URL(request.getURL());
InputStream inputStream = path.openStream();
DataInputStream stream = new DataInputStream(inputStream);
byte[] data = new byte[stream.available()];
stream.readFully(data);
response.setData(data);
String mimeType = getMimeType(path.toString());
response.getHeaders().setHeader("Content-Type", mimeType);
return response;
} catch (Exception ignored) {}
return null;
}
});
The getMimeTypemethod here returns appropriate mime type for the given resource extension:
private static String getMimeType(String path) {
if (path.endsWith(".html")) {
return "text/html";
}
if (path.endsWith(".css")) {
return "text/css";
}
if (path.endsWith(".js")) {
return "text/javascript";
}
return "text/html";
}
Once you register ProtocolHandler and define what mime types are supported, you can load resources from JAR archive using standard Java and JxBrowser API:
browser.loadURL(Main.class.getResource("/assets/engine.html").toString());

Modify dynamically a rdlc report (c#)

I have a font stored in a database, and I have to set all my fileds with that font.
I set bind my report like this :
FormBudgReelReport form = new FormBudgReelReport();
form.Viewer.LocalReport.ReportEmbeddedResource = _NomRessourceRpt;
form.Viewer.LocalReport.DataSources.Add(source);
form.ShowDialog();
If I could load my rdlc as an XmlDocument, I know how to do this, but is there a way to do this?
I can't use a formula like =Parameters!Police.Value because I have a lot of reports to change.
Ok !
I could load my rdlc as a xmlDocument by this code :
Stream st = this.GetType().Assembly.GetManifestResourceStream(_NomRessourceRpt);
// convert stream to string
StreamReader reader = new StreamReader(st);
string reportDef = reader.ReadToEnd();
XmlDocument document = new XmlDocument();
document.LoadXml(reportDef);
Thanks for the help :)
If I could load my rdlc as an XmlDocument, I know how to do this, but is there a way to do this?
In the Solution Explorer you can right-click the .rdlc file and select <Open With...> to choose the editor .
Update:
I am seeking for a way to load my rdlc in a xmlDocument object and then edit xml nodes in runtime.
The following code snippet helps you to load the .rdlc report file from the resources folder to an Xml document:
using System;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Resources;
private void LoadRDLCFromResources()
{
//Declare variables
XmlDocument objXmlDocument = new XmlDocument();
Byte[] byteArray;
Stream objStream = null;
ResourceManager resourceManager = null;
try
{
// Initialize ResourceManager object
resourceManager = new ResourceManager("your_namespace_name.Properties.Resources", GetType().Assembly);
if (resourceManager != null)
{
//Load the resource file "Sample.rdlc" into ByteArray
byteArray = (Byte[])resourceManager.GetObject("Sample");
if (byteArray != null)
{
//Load this bytearray into MemoryStream
objStream = new MemoryStream(byteArray);
if (byteArray.Length > 0)
{
//Load this stream object into XML document and
//thus you get the rdlc file loaded as an XML
//document.
objXmlDocument.Load(objStream);
// Code for using this xml document as per your use
}
}
}
}
//MissingManifestResourceException is an exception thrown when the resource manager fails to initialize appropriately. In such case, please check the namespace name.
catch (MissingManifestResourceException ex)
{
MessageBox.Show("Exception -> " + ex.Message,
"Sample Demo", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show("Exception -> " + ex.Message,
"Sample Demo", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
// Clear the objects in finally block. This is required for memory management issues.
// If xml document is not required further then clear it in the following manner
if (objXmlDocument != null)
{
objXmlDocument.DocumentElement.RemoveAllAttributes();
objXmlDocument.DocumentElement.RemoveAll();
objXmlDocument.RemoveAll();
}
//Clear the memory stream object
if (objStream != null)
{
objStream.Flush();
objStream.Close();
objStream.Dispose();
}
// Clear resource manager
resourceManager.ReleaseAllResources();
}
}
Source: How to load a rdlc file from resources folder into an XML document dynamically?

Spring MVC to open PDF as the view

Which is the appropriate View class to render existing PDF? AbstractView?
I am fetching PDF via a webservice ,so I'm not looking to subclass AbstractPdfView to render PDF.
I'd like to stay with the Spring controller classes which return a ModelAndView which means writing my own subclass of AbstractView to just write the PDF to a ServletOutputStream. Any other built in support available in Spring MVC?
Thanks
I agree with #Biju Kunjummen's answer but using iText would be also nice to generate the PDF.
here is the code snippet of the controller method.
#RequestMapping(value = "/common/reportgenerator/generatePDF")
public void generatePdf(HttpServletRequest req,HttpServletResponse res)
{
res.setContentType("text/html;charset=UTF-8");
ServletOutputStream outStream=null;
try
{
String calledFrom = req.getHeader("referer");
calledFrom=req.getRequestURL().substring(0,req.getRequestURL().lastIndexOf("/"))+"/ReportGenerator.egp";
calledFrom += "?isPdf=yes&"+req.getQueryString();
System.out.println(calledFrom+"?isPdf=yes&"+req.getQueryString());
InputStream input = new URL(calledFrom).openStream();
StringWriter writer = new StringWriter();
CopyUtils.copy(input, writer);
//System.out.println(writer.toString());
res.setContentType("application/pdf");
res.setHeader("Content-Disposition", "attachment;filename=report.pdf");
outStream = res.getOutputStream();
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(calledFrom);
renderer.layout();
renderer.createPDF(outStream);
}
catch (Exception e)
{
new AbcException(e,exceptionHandlerService);
}
finally
{
try
{
outStream.flush();
outStream.close();
}
catch(Exception ex)
{
new AbcException(ex,exceptionHandlerService);
}
}
}
Hope this helps you. Cheers.
I think the best way is to simply stream it out using HttpServletResponse:
OutputStream out = response.getOutputStream();
out.write(..); //buffer and write..
There is no such class.
You have to manually write that file.
Please see answer here:
Display the PDF file stored on the webserver on Browser new window using Spring MVC
I have changed that code to:
// get absolute path of the application
ServletContext context = request.getSession().getServletContext();
String appPath = context.getRealPath("/");
// construct the complete absolute path of the file
String fullPath = appPath + "WEB-INF/pdfs/201507.pdf";
Also, see the answer for not downloading the pdf
and putting the inputStream in the finally block.

ASP.NET- using System.IO.File.Delete() to delete file(s) from directory inside wwwroot?

I have a ASP.NET SOAP web service whose web method creates a PDF file, writes it to the "Download" directory of the applicaton, and returns the URL to the user. Code:
//Create the map images (MapPrinter) and insert them on the PDF (PagePrinter).
MemoryStream mstream = null;
FileStream fs = null;
try
{
//Create the memorystream storing the pdf created.
mstream = pgPrinter.GenerateMapImage();
//Convert the memorystream to an array of bytes.
byte[] byteArray = mstream.ToArray();
//return byteArray;
//Save PDF file to site's Download folder with a unique name.
System.Text.StringBuilder sb = new System.Text.StringBuilder(Global.PhysicalDownloadPath);
sb.Append("\\");
string fileName = Guid.NewGuid().ToString() + ".pdf";
sb.Append(fileName);
string filePath = sb.ToString();
fs = new FileStream(filePath, FileMode.CreateNew);
fs.Write(byteArray, 0, byteArray.Length);
string requestURI = this.Context.Request.Url.AbsoluteUri;
string virtPath = requestURI.Remove(requestURI.IndexOf("Service.asmx")) + "Download/" + fileName;
return virtPath;
}
catch (Exception ex)
{
throw new Exception("An error has occurred creating the map pdf.", ex);
}
finally
{
if (mstream != null) mstream.Close();
if (fs != null) fs.Close();
//Clean up resources
if (pgPrinter != null) pgPrinter.Dispose();
}
Then in the Global.asax file of the web service, I set up a Timer in the Application_Start event listener. In the Timer's ElapsedEvent listener I look for any files in the Download directory that are older than the Timer interval (for testing = 1 min., for deployment ~20 min.) and delete them. Code:
//Interval to check for old files (milliseconds), also set to delete files older than now minus this interval.
private static double deleteTimeInterval;
private static System.Timers.Timer timer;
//Physical path to Download folder. Everything in this folder will be checked for deletion.
public static string PhysicalDownloadPath;
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
deleteTimeInterval = Convert.ToDouble(System.Configuration.ConfigurationManager.AppSettings["FileDeleteInterval"]);
//Create timer with interval (milliseconds) whose elapse event will trigger the delete of old files
//in the Download directory.
timer = new System.Timers.Timer(deleteTimeInterval);
timer.Enabled = true;
timer.AutoReset = true;
timer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);
PhysicalDownloadPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "Download";
}
private static void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
{
//Delete the files older than the time interval in the Download folder.
var folder = new System.IO.DirectoryInfo(PhysicalDownloadPath);
System.IO.FileInfo[] files = folder.GetFiles();
foreach (var file in files)
{
if (file.CreationTime < DateTime.Now.AddMilliseconds(-deleteTimeInterval))
{
string path = PhysicalDownloadPath + "\\" + file.Name;
System.IO.File.Delete(path);
}
}
}
This works perfectly, with one exception. When I publish the web service application to inetpub\wwwroot (Windows 7, IIS7) it does not delete the old files in the Download directory. The app works perfect when I publish to IIS from a physical directory not in wwwroot. Obviously, it seems IIS places some sort of lock on files in the web root. I have tested impersonating an admin user to run the app and it still does not work. Any tips on how to circumvent the lock programmatically when in wwwroot? The client will probably want the app published to the root directory.
Your problem may be related to the fact that IIS reloads the Web Service Application if the directory or files contained in the main folder changes.
Try creating / deleting files in a temporary folder which is outside the root folder of your application (be aware of permissions on the folder to allow IIS to read/write files).
Instead of writing directly to the file system, why not use isolated storage?
http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstorage.aspx
This should solve any location or permission based issues that you are having
I forgot to come back and answer my question.
I had to give the IIS_IUSRS group Modify permissions to the directory where I was reading/writing files.
Thanks to all those who answered.

Resources