Huge Map of <String,"Some Class"> in Java - javascript

In my application I need to show information about files as a friendly readable string, based on the file's MIME String. I have the information I need (FYI taken from /usr/share/mime/package/freedesktop.org.xml on Ubuntu 14.04), and I'd like to put everything as a static map<"String","MIMEInfoObject">.
protected class MIMEInfoObject {
//Getters ...
//Setters ...
...
private String mimeType; //Example: "application/pdf
private String defaultDescription; // "PDF document"
private String localDescription; // "Documento PDF"
private String acronym; // "PDF"
private String extendedAcronym; // "Portable Document Format"
private List<String> extensionList; // "pdf .."
private List<String> aliasList; // "application/x-pdf, application/acrobat, ... "
}
I made a shell script that outputs the linux file like this:
<mime-type type="image/vnd.adobe.photoshop">
<comment>Photoshop image</comment>
<comment xml:lang="pt_BR">Imagem do Photoshop</comment>
<glob pattern="*.psd"/>
<alias type="image/psd"/>
<alias type="image/x-psd"/>
<alias type="image/photoshop"/>
<alias type="image/x-photoshop"/>
<alias type="application/photoshop"/>
<alias type="application/x-photoshop"/>
++++END+++
and I used that output in another shell script that generates java code like this:
MIMEInfoObject obj;
obj.setMimeType("application/pdf");
obj.setDefaultDescription("PDF document");
obj.setLocalDescription("Documento PDF");
obj.setAcronym("PDF");
obj.setExtendedAcronym("Portable Document Format");
if (obj.getExtensionList() == null) {
obj.setExtensionList(new ArrayList<String>());
}
extList = obj.getExtensionList();
extList.add("*.pdf");
obj.setExtensionList(extList);
if (obj.getAliasList() == null) {
obj.setAliasList(new ArrayList<String>());
}
aliasList = obj.getAliasList();
aliasList.add("application/x-pdf");
obj.setAliasList(aliasList);
if (obj.getAliasList() == null) {
obj.setAliasList(new ArrayList<String>());
}
aliasList = obj.getAliasList();
aliasList.add("image/pdf");
obj.setAliasList(aliasList);
if (obj.getAliasList() == null) {
obj.setAliasList(new ArrayList<String>());
}
aliasList = obj.getAliasList();
aliasList.add("application/acrobat");
obj.setAliasList(aliasList);
mimeString2Obj.put(obj.getMimeType(), obj);
for (String alias : obj.getAliasList()) {
mimeString2Obj.put(alias, obj);
}
I know the code above is stupid, but it's how I can generate it, but the problem is that it generates about 17000 lines of code like that. Java is complaining about the method's bytes limit, which is 65535, and it's exceeded.
My concern is if anyone has a better idea of how to do this, taking in mind that I'm using GWTP (so I can use JavaScript although I'm not an expert) and my application will run both on Desktop/Mobile browsers and Mobile App (phonegap).
Thanks in advance.

The problem if I understand it correctly is that you're generating java code to explicitly load each object, as opposed to reusing java code to load objects from a data file. Don't do that. If you have more files, for instance, you would have to regenerate your code etc.
You need to create some kind of standardized data file, and create a method to read it. So if your data is CSV, or XML, then you can dump then in one/many files, and then it doesn't matter how much data you have, the java code will look the same. Just a simple loop which keeps reading and loading stuff in your map.
in pseudocode:
while (records.hasMoreRecords()) {
records.read()...
add record to map()
}

Related

How input Value from Scanner, and output the value to an txt file in Java?

I'm struggling to input value from Scanner option in Java to a txt file. while I can smoothly read the data using try{} catch{}, I cannot write the data from a scanner to the txt file. I can easily write data to txt file using PrintWriter, but that's not my goal... According to the scenario of the assignment, I have to create the system to input values and store the data text file, which I'm struggling to do.
Please help me with this problem, and provide me a solution...
This is my first Java project. Thanks
Scanner sc = new Scanner(System.in);
String data = sc.nextLine(); //taking input from user
// Use try with resource to release system resources
try ( FileWriter myWriter = new FileWriter("filename.txt"); ) {
myWriter.write(data); //writing into file
}
As you say you have successfully read (and maybe also manipulated) the data. Lets assume you have it ready to be written out as a String data and you also have a String filename of the file's intended name.
You can then do the following:
// generate the File object
File f = Paths.get("./" + filename).toFile();
f.delete(); // remove previous existing file -- equivalent to overwrite
try(BufferedWriter wr = new BufferedWriter(new FileWriter(f))){
wr.append(data); // adding the data into write buffer
wr.flush(); // writing the data out to the file
wr.close(); // closing the buffered writer
} catch (Exception e) {
e.printStackTrace();
}

Unity WebGL External Assets

I'm developing some webGL project in Unity that has to load some external images from a directory, it runs all fine in the editor, however when I build it, it throws a Directory Not Found exception in web console. I am putting the images in Assets/StreamingAssets folder, that will become StreamingAssets folder in the built project (at root, same as index.html). Images are located there, yet browser still complains about not being able to find that directory. (I'm opening it on my own computer, no running web server)
I guess I'm missing something very obvious, but it seems like I could use some help, I've just started learning unity a week ago, and I'm not that great with C# or JavaScript (I'm trying to get better...) Is this somehow related to some javascript security issues?
Could someone please point me in the right direction, how I should be reading images(no writing need to be done) in Unity WebGL?
string appPath = Application.dataPath;
string[] filePaths = Directory.GetFiles(appPath, "*.jpg");
According to unity3d.com in webGL builds everything except threading and reflection is supported, so IO should be working - or so I thought:S
I was working around a bit and now I'm trying to load a text file containing the paths of the images (separated by ';'):
TextAsset ta = Resources.Load<TextAsset>("texManifest");
string[] lines = ta.text.Split(';');
Then I convert all lines to proper path, and add them to a list:
string temp = Application.streamingAssetsPath + "/textures/" + s;
filePaths.Add(temp);
Debug.Log tells me it looks like this:
file://////Downloads/FurnitureDresser/build/StreamingAssets/textures/79.jpg
So that seems to be allright except for all those slashes (That looks a bit odd to me)
And finally create the texture:
WWW www = new WWW("file://" + filePaths[i]);
yield return www;
Texture2D new_texture = new Texture2D(120, 80);
www.LoadImageIntoTexture(new_texture);
And around this last part (unsure: webgl projects does not seem easily debuggable) it tells me: NS_ERROR_DOM_BAD_URI: Access to restricted URI denied
Can someone please enlighten me what is happening? And most of all, what would be proper to solution to create a directory from where I can load images during runtime?
I realise this question is now a couple of years old, but, since this still appears to be commonly asked question, here is one solution (sorry, the code is C# but I am guessing the javascript implementation is similar). Basically you need to use UnityWebRequest and Coroutines to access a file from the StreamingAssets folder.
1) Create a new Loading scene (which does nothing but query the files; you could have it display some status text or a progress bar to let the user knows what is happening).
2) Add a script called Loader to the Main Camera in the Loading scene.
3) In the Loader script, add a variable to indicate whether the asset has been read successfully:
private bool isAssetRead;
4) In the Start() method of the Loading script:
void Start ()
{
// if webGL, this will be something like "http://..."
string assetPath = Application.streamingAssetsPath;
bool isWebGl = assetPath.Contains("://") ||
assetPath.Contains(":///");
try
{
if (isWebGl)
{
StartCoroutine(
SendRequest(
Path.Combine(
assetPath, "myAsset")));
}
else // desktop app
{
// do whatever you need is app is not WebGL
}
}
catch
{
// handle failure
}
}
5) In the Update() method of the Loading script:
void Update ()
{
// check to see if asset has been successfully read yet
if (isAssetRead)
{
// once asset is successfully read,
// load the next screen (e.g. main menu or gameplay)
SceneManager.LoadScene("NextScene");
}
// need to consider what happens if
// asset fails to be read for some reason
}
6) In the SendRequest() method of the Loading script:
private IEnumerator SendRequest(string url)
{
using (UnityWebRequest request = UnityWebRequest.Get(url))
{
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
// handle failure
}
else
{
try
{
// entire file is returned via downloadHandler
//string fileContents = request.downloadHandler.text;
// or
//byte[] fileContents = request.downloadHandler.data;
// do whatever you need to do with the file contents
if (loadAsset(fileContents))
isAssetRead = true;
}
catch (Exception x)
{
// handle failure
}
}
}
}
Put your image in the Resources folder and use Resources.Load to open the file and use it.
For example:
Texture2D texture = Resources.Load("images/Texture") as Texture2D;
if (texture != null)
{
GetComponent<Renderer>().material.mainTexture = texture;
}
The directory listing and file APIs are not available in webgl builds.
Basically no low level IO operations are supported.

How to have functionality of Compiler in my jsp pages

I have a textarea through which user will write his code and when he press submit button then text should get compiled and result should be displayed.
Can anyone provide any API's available which I can use.?
More Details:
I have a form consisting of textarea where user can write code and submit.
On submit I want to compile this code through jsp page and return output message of compiler.
One more thing I do not Have file of submitted code, I have only string.
string code = request.getparameter("textareaCode");
So, is there any way to compile this code for any one languages ex. C, C++ or Java?
Is there any API's available which I can use to work it?
How to give system call through jsp pages so that I can compile the submitted code?
You can make use of run-time java compilation feature provided in JavaCompiler interface which accepts input/output stream.
Step 1. Convert contents submitted by text-area into input stream.
Step 2. JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
Step 3. Call compiler.run method by providing inputstream(you have created in step 1) as one argument. You can capture the output of compilation thru output stream as another argument.
You can execute command line commands using Runtime.getRuntime().exec("command");
For example if you want to compile a java file then try the following :
import java.io.*;
public class JavaRunCommand {
public static void main(String args[]) {
String s = null;
try {
// Logic to save textarea code into java file.
// then compile a java file "javac fileName.java" command
// using the Runtime exec method
Process p = Runtime.getRuntime().exec("javac fileName.java");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
System.exit(0);
}catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
System.exit(-1);
}
}
}

PDF hostContainer callback

Following this SO solution here to notify clients of a click event in a PDF document, how is it possible to notify the client when the PDF gets submitted by the client using this.myPDF.submitForm("localhost/Handler.ashx?r=2) function?
The PDF File is created inside a user control then rendered into a HTML object:
string container = ("<object data='/myfile.pdf' type='application/pdf'></object>");
The JS file attached to the PDF is done like this:
var webClient = new WebClient();
string htmlContent = webClient.DownloadString(fileurl + "pdf_script.js");
PdfAction action = PdfAction.JavaScript(htmlContnent, pdfstamper.Writer);
pdfstamper.Writer.SetOpenAction(action);
And the content of the js file:
this.disclosed = true;
if (this.external && this.hostContainer) {
function onMessageFunc(stringArray) {
try {
this.myPDF.submitForm("http://localhost/Handler.ashx?EmpNo=12345" + "#FDF", false);
}
catch (e) {
}
}
function onErrorFunc(e) {
console.show();
console.println(e.toString());
}
try {
if (!this.hostContainer.messageHandler);
this.hostContainer.messageHandler = new Object();
this.hostContainer.messageHandler.myPDF = this;
this.hostContainer.messageHandler.onMessage = onMessageFunc;
this.hostContainer.messageHandler.onError = onErrorFunc;
this.hostContainer.messageHandler.onDisclose = function () { return true; };
}
catch (e) {
onErrorFunc(e);
}
}
When the submitForm call is made the PDF contents (form fields) get saved successfully and an alert is displayed in the PDF by doing this:
message = "%FDF-1.2
1 0 obj
<<
/FDF
<<
/Status("Success!")
>>
>>
endobj
trailer
<</Root 1 0 R>>
%%EOF");
return message;
What I'm trying to do is to get the PDF to callback the client after the form submit call sent from this client, a way to acknowledge the client that the form has been submitted, not in a form of an alert, but rather, a way to trigger a function in the host (the container, an iframe, object...etc).
The FDF response you used was unknown to me, so I've learned something new from your question. I've studied the AcroJS Reference and the FDF specification in the PDF Reference, and now I have a better understanding of what your code does. Thank you for that.
I assume that you already know how to trigger a JavaScript message in an HTML file using a JavaScript call from a PDF. See the createMessageHandler() in the JavaScript Communication between HTML and PDF article.
I interpret your question as: "How to I invoke this method after a successful submission of the data?"
If there's a solution to this question, it will involve JavaScript. I see that one can add JavaScript in an FDF file, but I'm not sure if that JavaScript can 'talk to' HTML. I'm not sure if you can call a JavaScript function in your initial PDF from the FDF response. If it's possible, you should add a JavaScript entry to your PDF similar to the /Status entry.
The value of this entry is a dictionary, something like:
<<
/Before (app.alert\("before!"\))
/After (app.alert\("after"\))
/Doc [/MyDocScript1, (myFunc1\(\)),
/MyDocScript2, (myFunc2\(\))
>>
In your case, I would remove the /Before and /Doc keys. I don't think you need them, I'd reduce the dictionary to:
<<
/After (talkToHtml\(\))
>>
Where talkToHtml() is a method already present in the PDF:
function talkToHtml() {
var names = new Array();
names[0] = "Success!";
try{
this.hostContainer.postMessage(names);
}
catch(e){
app.alert(e.message);
}
}
I don't know if this will work. I've never tried it myself. I'm basing my answer on the specs.
I don't know if you really need to use FDF. Have you tried adding JavaScript to your submitForm() method? Something like:
this.myPDF.submitForm({
cURL: "http://localhost/Handler.ashx?EmpNo=12345",
cSubmitAs: "FDF",
oJavaScript: {
Before: 'app.alert("before!")',
After: 'app.alert("after")',
Doc: ["MyDocScript1", "myFunc1()",
"MyDocScript2", "myFunc2()" ]
}
});
This will only work if you submit as FDF. I don't think there's a solution if you submit an HTML query string.
In case you're wondering what MyDocScript1 and MyDocScript2 are:
Doc defines an array defining additional JavaScript scripts to be
added to those defined in the JavaScript entry of the document’s name
dictionary. The array contains an even number of elements, organized
in pairs. The first element of each pair is a name and the second
is a text string or text stream defining the script corresponding
to that name. Each of the defined scripts is added to those already
defined in the name dictionary and then executed before the script
defined in the Before entry is executed. (ISO-32000-1 Table 245)
I'm not sure if all of this will work in practice. Please let me know either way.

Load file after page is complete without redirecting

I am trying to do pretty much the same, as is for example on Sourceforge. After a user creates some data, I generate a file and I want it to be offered to him after a page load. However, I know almost nothing about javascript and simple copy-paste of
<script type="text/javascript">
var download_url = "http://downloads.sourceforge.net/sourceforge/itextsharp/itextsharp-4.1.2-dll.zip?use_mirror=dfn";
function downloadURL() {
if (download_url.length != 0 && !jQuery.browser.msie) {
window.location.href = download_url;
}
}
jQuery(window).load(downloadURL);
</script>
is not enough. It is important for the user to download the file, so how to do that?
A question related to the previous is - where to store the file i created? Once while using the asp.net development server and then on the real IIS server? And how should this address look? When I tried
setTimeout("window.location.href='file://localhost/C:/Downloads/file.pdf'", 2000);
I was getting nothing, with HTTP an error of unknown address.
See Haack's DownloadResult example. It explains (I think) exactly what you're truing to do. Except you would provide the timeout call with your download action url.
you're asking the user's browser to look for a file on their own computer... that you're trying to save there.
you could use something like:
window.location.href='http://www.yourServer.com/generatePDF.asp?whatever=whatever'
where http://www.yourServer.com/generatePDF.asp?whatever=whatever is what is generating the pdf file for the user
On the server, you have to set the content disposition in the response header to "Attachment" as described in these answers.
If you do that, the download will not affect the page that is currently displayed in the browser. So, if you initiate a request in Javascript that gets an attachment, the browser will leave the page alone, and the user will see a message box with the Open/Save/Cancel question.
You can create your own PdfResult which extends ActionResult like this:
public class PdfResult : ActionResult
{
public byte[] Content { get; set; }
public string FileName { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.Response;
response.AddHeader("content-disposition", "attachment; filename=" + this.FileName);
response.AddHeader("content-length", this.Content.Length.ToString());
response.ContentType = "application/pdf";
using (MemoryStream memoryStream = new MemoryStream(this.Content))
{
memoryStream.WriteTo(response.OutputStream);
}
response.End();
}
Then in your action you can simply return the file as follows:
public ActionResult Pdf(string param1...)
{
var content = GeneratePdf(); //etc
var fileName = AssignFileName();
return new PdfResult { Content = content, FileName = fileName + ".pdf" };
}
A couple of different things. First, since you are using MVC, create an action that actually generates the file and returns it as a FileResult. The file can be an actual file on the server, but it can also be generated dynamically -- say in a MemoryStream -- and the FileResult created from that. Set the content to application/octet-stream or the actual file type if it's not one that will render in the browser via a plugin. Second, don't generate the file in the action that renders the page, but rather call the action that generates the FileResult from that page using the technique you've referenced (though it looks like they are doing something different for IE). If the MIME type is not one that can be rendered it will be downloaded.
public ActionResult GenerateFile( string value, int other )
{
MemoryStream file = new MemoryStream();
...
return File( file, "application/octet-stream" );
}

Categories

Resources