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());
Related
I got an error like this when trying to add google drive service to my project. Although there is "System.Web" in the "Library" section, it cannot be used actively. Could you help?
public static string DownloadGoogleFile(string fileId)
{
DriveService service = GetService();
string FolderPath = System.Web.HttpContext.Current.Server.MapPath("/GoogleDriveFiles/");
FilesResource.GetRequest request = service.Files.Get(fileId);
string FileName = request.Execute().Name;
string FilePath = System.IO.Path.Combine(FolderPath, FileName);
MemoryStream stream1 = new MemoryStream();
// Add a handler which will be notified on progress changes.
// It will notify on each chunk download and when the
// download is completed or failed.
request.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) =>
{
switch (progress.Status)
{
case DownloadStatus.Downloading:
{
Console.WriteLine(progress.BytesDownloaded);
break;
}
case DownloadStatus.Completed:
{
Console.WriteLine("Download complete.");
SaveStream(stream1, FilePath);
break;
}
case DownloadStatus.Failed:
{
Console.WriteLine("Download failed.");
break;
}
}
};
request.Download(stream1);
return FilePath;
}
Trying to pass the current HttpContext to a static method gets tricky depending on the project framework. It's also not clear the type of project or framework you are using.
Here's a similar question that might help you clarify the difference between HttpContext when it pertains to .net and .net-core.
HttpContext in .net standard library
I am using CameraX API to take pictures in my android app, save them and then display them from their path. With the previous version alpha-09 I was able to do so with onImageSaved(File file). However with the alpha-10 I have to use onImageSaved(OutputFileResults outputFileResults) and then get the path from the uri retrieved by the outputFileResults. But the Uri I get is always wrong. For instance when my image is saved at: "/external/images/media/1581680878237.jpg" I get the uri's path: "/external/images/media/113758".
Here is my code:
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, "NEW_IMAGE");
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
ImageCapture.OutputFileOptions outputFileOptions = new ImageCapture.OutputFileOptions.Builder(
activity.getContentResolver(),
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
contentValues).build();
imageCapture.takePicture(outputFileOptions, Runnable::run, new ImageCapture.OnImageSavedCallback() {
#Override
public void onImageSaved(#NonNull ImageCapture.OutputFileResults outputFileResults) {
Uri uri = outputFileResults.getSavedUri();
if(uri != null){
System.out.println("URI PATH" + uri.getPath());
System.out.println("URI PATH" + uri.toString());
activity.runOnUiThread(cameraProvider::unbindAll);
galleryAddPic(uri);
Bundle params = new Bundle();
params.putString("FILE_PATH", uri.getPath());
Navigation.findNavController(root).navigate(R.id.navigation_edit_image, params);
}
}
#Override
public void onError(#NonNull ImageCaptureException exception) {
exception.printStackTrace();
}
});
So I finally managed to save the image taken by ImageCapture by using an other method (especially an other ImageCapture.OutputFileOptions.Builde). I didn't use an Uri object to save the image but a File object.
File mImageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "YOUR_DIRECTORY");
boolean isDirectoryCreated = mImageDir.exists() || mImageDir.mkdirs();
if(isDirectoryCreated){
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/YOUR_DIRECTORY", "YOUR_IMAGE.jpg");
ImageCapture.OutputFileOptions.Builder outputFileOptionsBuilder =
new ImageCapture.OutputFileOptions.Builder(file);
imageCapture.takePicture(outputFileOptionsBuilder.build(), Runnable::run, new ImageCapture.OnImageSavedCallback() {
#Override
public void onImageSaved(#NonNull ImageCapture.OutputFileResults outputFileResults) {
Bundle params = new Bundle();
params.putString("FILE_PATH", file.getPath());
Navigation.findNavController(root).navigate(R.id.navigation_edit_image, params);
}
#Override
public void onError(#NonNull ImageCaptureException exception) {
exception.printStackTrace();
}
});
}
Be aware that if you use outputFileResults.getSavedUri() with this method you will always have a null uri.
As of CameraX alpha 10, ImageCapture supports 3 types of save location: File, MediaStore URI and OutputStream, depending on which OutputFileOptions.Builder() is used.
The Uri field in OutputFileResults is only populated if the OutputFileOptions is MediaStore URI type. For File type, the caller should have the save location already, there is no need to return the info; for OutputStream type, the save location is unknown to CameraX. See the JavaDoc:
public Uri getSavedUri ()
Returns the Uri of the saved file.
This field is only returned if the ImageCapture.OutputFileOptions is
backed by MediaStore constructed with #Builder(ContentResolver, Uri,
ContentValues).
For more info, please checkout the developer doc.
I have a Cefsharp application which has Html pages with Javascript. Js makes API calls which happens fine if I open cef application in windows but most of API calls are not happening when I am opening same cef application through testcompelete.
On debugging application I am getting CORS warning.
I am using CefCustomScheme which has root folder path, schemeName and host name specified. And provided same shemeName and host name in Address in wpf: chromiumwebrowse tag. If I hard-code root folder path in Address Source binding, its working fine even in testcomplete.
private static CefCustomScheme GetAlmanacScheme(IAppSettings appSettings)
{
try
{
var almanacFolder = appSettings.Settings["ALMANAC_WIDGET_PATH"];
if (string.IsNullOrWhiteSpace(almanacFolder))
{
almanacFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Thermo", "InstConnectAgent", "AlmanacWidget");
}
var factory = new FolderSchemeHandlerFactory(almanacFolder, "thermo", "almanac");
return new CefCustomScheme() { SchemeName = "thermo", SchemeHandlerFactory = factory, IsCorsEnabled = true };
}
catch
{
return null;
}
}
and Source is
private const string WidgetUrl = "thermo://almanac";
public string Source
{
get
{
return WidgetUrl;
}
}
I have this controller which create an empty sheet and I want to return the excel file to the navigator. The problem is, the excel file is corrupted.
If I create the file on my computer the file isn't corrupted, so my HSSFWorkbook is valid. Seems a problem of encodage/encapsulation added by the spring context ?
#Controller
public class ExportController {
#RequestMapping(value = "/export/test/excel", method = RequestMethod.POST)
public void downloadExcelTestFile(
HttpServletRequest request,
HttpServletResponse response) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
wb.createSheet("Sheet1");
//response.reset();
//response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=test.xls");
OutputStream out = response.getOutputStream();
wb.write(out);
out.flush();
out.close();
wb.close();
}
The download start well, I receive the file test.xls, but I can't open it. Is there a Spring way to achiev a proper download inside a #Controller ?
I use Spring 4.2.4
UPDATE 1
I tried a Spring way but it's not working better
HSSFWorkbook wb = new HSSFWorkbook();
wb.createSheet("Sheet1");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
wb.write(bos);
} finally {
bos.close();
}
byte[] bytes = bos.toByteArray();
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/vnd.ms-excel;");
headers.set("content-length",Integer.toString(bytes.length));
headers.set("Content-Disposition", "attachment; filename=test.xls");
return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.CREATED);
UPDATE 3
I found a reason but I don't understand why.
If I build my war file and deploy it manually in the very same tomcat 7.0.70 it works. My Excel is not corrupted.
If I download from the dev environnement in eclipse, it doesn't work. Seems a tomcat + eclipse issue.
Ok that wasn't a Spring issue, not even a tomcat issue.
The problem was from my grunt-connect-proxy, when I run my front throught localhost:9000 : files that I downloaded were corrupted. If I build the project in a war file or run the front from localhost:8080 ( same port than the server ) without "grunt serve" and so without the proxy it works.
I have not fix the problem with grunt ... I just ignore it, but this answer can save your time.
Sample Spring Backed Code to create an excel and return it using Spring REST. The input parameters may change as per your requirement
#RequestMapping(value = "/convertFlatFileToExcel.do", method = RequestMethod.POST)
public HttpEntity<byte[]> convertFlatFileToExcel(#RequestParam(value="file") MultipartFile file,#RequestParam(value="jobid") String jobid) {
ByteArrayOutputStream archivo = new ByteArrayOutputStream();
XSSFWorkbook workbook = new XSSFWorkbook();
workbook.write(archivo);
if(null!=workbook && null!=archivo) {
workbook.close();
archivo.close();
}
byte[] documentContent = archivo.toByteArray();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"myexcelfile.xls\"");
headers.setContentLength(documentContent.length);
response = new ResponseEntity<byte[]>(documentContent, headers, HttpStatus.OK);
}
**Sample UI Code:
Below is the sample code to call to Rest Service using Angular JS. Import the FileSaver js file using https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.min.js
This will have the method saveAs() to save the given excel blob data with a given name.
**
$http.post(urlBase+'/convertFlatFileToExcel.do', formData,{
transformRequest : angular.identity,
responseType: 'arraybuffer',
headers : {
'Content-Type' : undefined,
'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}})
.then(
function (response) {
$window.sessionStorage.showProgress = "";
var file = new Blob([response.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
saveAs(file, jobid.toUpperCase()+'.xlsx');
},
function (errResponse) {
$window.sessionStorage.showProgress = "";
$mdDialog.show($mdDialog.alert({title: 'Invalid Job ID!',textContent: 'Please enter a valid Job ID. For any issues, please contact the admin!',ok: 'GOT IT!'}));
deferred.reject(errResponse);
});
How do I use AWS SDK for ASP.NET to upload a file to a specific folder? - I was able to upload files by specifying the bucket name (request.WithBucketName), but I want to be able to upload a file to a specific folder within the bucket itself.
This is the code that I use to upload a file to a single bucket:
public bool UploadFileToS3(string uploadAsFileName, Stream ImageStream, S3CannedACL filePermission, S3StorageClass storageType, string toWhichBucketName)
{
try
{
client = Amazon.AWSClientFactory.CreateAmazonS3Client(MY_AWS_ACCESS_KEY_ID, MY_AWS_SECRET_KEY);
PutObjectRequest request = new PutObjectRequest();
request.WithKey(uploadAsFileName);
request.WithInputStream(ImageStream);
request.WithBucketName(toWhichBucketName);
request.CannedACL = filePermission;
request.StorageClass = storageType;
client.PutObject(request);
client.Dispose();
}
catch
{
return false;
}
return true;
}
Hope that this code will help you out.
To add a file to a folder in a bucket, you need to update the Key of the PutObjectRequest to include the folder before the file name.
public bool UploadFileToS3(string uploadAsFileName, Stream ImageStream, S3CannedACL filePermission, S3StorageClass storageType, string toWhichBucketName)
{
try
{
using(client = Amazon.AWSClientFactory.CreateAmazonS3Client(MY_AWS_ACCESS_KEY_ID, MY_AWS_SECRET_KEY))
{
PutObjectRequest request = new PutObjectRequest();
request.WithKey( "folder" + "/" + uploadAsFileName );
request.WithInputStream(ImageStream);
request.WithBucketName(toWhichBucketName);
request.CannedACL = filePermission;
request.StorageClass = storageType;
client.PutObject(request);
}
}
catch
{
return false;
}
return true;
}
This post that talks about uploading files to folder. They are using a TransferUtilityUploadRequest though, but it should work with the PutObjectRequest. Scroll to the bottom for the relevant example.
This post shows how to create a folder without uploading a file to it.
Hope this is helpful
Edit:
Updated the code to use a using block instead of calling Dispose per best practices.
Look Like Following functionlity
1.Create an AmazonS3 object
2.Create a bucket
3.Add a new file to Amazon S3
4.Get a file from Amazon S3
5.Delete a file from Amazon S3
Amazon
super easy way:
using System;
using System.Web;
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using System.Configuration;
/// <summary>
/// Summary description for AWShandler
/// </summary>
public static class AWSHandler
{
public static void sendFileToS3(string fileName, string storeLocation)
{
try
{
AmazonS3Client client = new AmazonS3Client(RegionEndpoint.EUWest1);
PutObjectRequest request = new PutObjectRequest();
request.BucketName = ConfigurationManager.AppSettings["AWSBucket"].ToString();
request.FilePath = fileName;
request.Key = storeLocation + fileName;
request.ContentType = MimeMapping.GetMimeMapping(fileName);
PutObjectResponse response = client.PutObject(request);
}
catch (Exception ex)
{
// use a logger and handle it
}
}
}
you just need to put your keys in the web/app.config file:
<add key="AWSAccessKey" Value="yourKey" />
<add key="AWSSecretKey" Value="yourSecret" />
These can be obtained from you account page in the AWS console. They must use the names quoted here too, as they are pre-defined by the AWS library.