Applet on Browser - applet

How I can use some functions that were declared on the applet class? i.e.
this is my class
public class hi extends JApplet{
public void HiThere(){
System.out.println("Hi on Java Console");
}
}
and on my browser it's declared something like:
<applet.... name="HI" id="HI" ......>Ooops!!!</applet>"
but when I tried to use the function there was a mistake, so how a can use the functions declared on my applet class?? Thanks!!!

First you should do this change to your code:
public class HI extends JApplet {
public HI() {System.out.println("Hi on Java Console");}
}
When you have done that, and your browser still has an error, then post the exact error message here. Also you might want to look for a tutorial "programming Java applets getting started", since your code tells me, that you don't seem to know what you are doing.

In order to call your class methods from js you must declare the <object> in html specifying a .jar or .class with your compiled content, the package of the main class and some other parameters like in the follow example (object is for IE, and embed is for FF):
I suppose that you want to invoke the hi.HiThere() method as defined in your question.
<object
width="100" height="100" id="hi">
<param name = "code" value = "path.to.your.main.class.hi">
<param name = "archive" value = "jar location">
<param name = "mayscript" value = "true">
<param name = "scriptable" value = "true">
...
<comment>
<embed
code = "path.to.your.main.class.hi"
archive = "your jar location"
scriptable = "true"
width = "100" height = "100"
name = "hi"
...
</embed>
</comment>
</object>
Then from the js you can access you object through the document using the id attribute in <object> or name in <embed> in the sample case document.hi. With the follow code you can invoke the HiThere(); method:
try{
// ie, ff
document.hi.HiThere();
}catch(Exception){
// chrome, safari, opera
document.hi[1].HiThere();
}
In order to execute with last java versions remember to meet the new java security requirements (manifest attributes http://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html, jar signature... ).

You can call the applet methods in JavaScript:
To do this the applet should be launched from JavaScript, e.g.
<script src="https://www.java.com/js/deployJava.js"></script>
<script>
var attributes = { id: 'mainApplet', code:
'org.jazzteam.Example', archive: 'example.jar', width: 812, height:
635};
var parameters = {};
deployJava.runApplet(attributes, parameters, '1.7');
function actionInApplet(url) {
mainApplet.appletMethod(url);
}
</script>
In this case the applet is launched from JavaScript with id= 'mainApplet'. In the applet there is appletMethod() method, which we want to call. To do this you need to call the method related to JavaScript object with id name. You can also pass parameters to the called methods, as demonstrated in this example.
Also it is necessary to know that the applet method called from JavaScript should be privileged. To do this you need to wrap the method code in the following "wrapper":
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
//method code
return new Object();
}
});
This information is taken from the article:
Frequently Asked Questions during Java applet development

Related

Javascript module function in GWT with JsInterop

Hoping this is way easier than I'm making it - I'm a Java coder, some inner Javascript aspects are a tad unfamiliar to me.
Trying to embed the great CodeJar library inside a GWT panel. There's a pretty nice/simple example for CodeJar:
<script type="module">
import {CodeJar} from './codejar.js'
import {withLineNumbers} from './linenumbers.js';
const editor = document.querySelector('.editor')
const highlight = editor => {
// highlight.js does not trim old tags,
// let's do it by this hack.
editor.textContent = editor.textContent
hljs.highlightBlock(editor)
}
const jar = CodeJar(editor, withLineNumbers(highlight), {
indentOn: /[(\[{]$/
})
jar.updateCode(localStorage.getItem('code'))
jar.onUpdate(code => {
localStorage.setItem('code', code)
})
</script>
The module function itself looks like this:
export function CodeJar(editor, highlight, opt = {}) { ... }
'editor' is a Div reference, and 'highlight' is a callback library function for handling code highlighting.
What I'm battling with is the JsInterop markup and code to make Javascript modules work with GWT. The above has a few aspects which I'm battling with
replacing the "import" such that the javascript module code is available to GWT. Obvioulsy I can just import the js in my top level index.html, but as I understand it JS modules don't become part of the global namespace, they're only usable from the JS module that imports them. Which in my case, presumably needs to be the GWT code.
how to pass the callback function in when recoding the above in GWT
how to get my own 'jar' reference to do own text set/get (replacing the use of local storage)
To load the script and have it available for GWT consumption, you have (at least) 3 possibilities:
use a static import in a <script type=module>, and then assign the CodeJar function to a window property to make it available globally (that could be another global object than window actually)
use a dynamic import() from GWT, using JsInterop and possibly elemental2-promise
use Rollup/Webpack/whatever to turn the CodeJar module into a non-module script so you can use it differently
Next, you need to create JsInterop bindings so you can call it from GWT; something like that (assuming you made CodeJar available globally as window.CodeJar, and using elemental2-dom for HTMLElement, but com.google.gwt.dom.client.Element would work just as well):
#JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "?")
interface CodeJar {
#JsMethod(namespace = JsPackage.GLOBAL, name = "CodeJar")
static native CodeJar newInstance(HTMLElement element, HighlightFn highlight);
#JsMethod(namespace = JsPackage.GLOBAL, name = "CodeJar")
static native CodeJar newInstance(HTMLElement element, HighlightFn highlight, Options opts);
void updateOptions(Options options);
void updateCode(String code);
void onUpdate(UpdateFn cb);
void destroy();
}
#JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Object")
class Options {
public String tab;
public JsRegExp indentOn;
public boolean spellcheck;
public boolean addClosing;
}
#JsFunction
#FunctionalInterface
interface HighlightFn {
void highlight(HTMLElement e);
}
#JsFunction
#FunctionalInterface
interface UpdateFn {
void onUpdate(String code);
}
With the above code, you should be able to create an editor using something like:
CodeJar jar = CodeJar.newInstance(editor, MyHighlighter::highlight);
If you use a dynamic import(), replace the static methods with instance ones in a #JsType interface representing the module received from the promise.

Umbraco 7 generic node class

With the help of other Stackoverflow users, I have gone some way to my solution but have come to a halt.
I would like to build some generic classes in an app_code .cshtml file eg one would be to return property values from documents from a function eg
public static string docFieldValue(int docID,string strPropertyName){
var umbracoHelper = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);
var strValue = "";
try{
strValue = umbracoHelper.Content(docID).GetPropertyValue(strPropertyName).ToString();
}
catch(Exception ex){
strValue = "Error - invalid document field name (" + strPropertyName + ")";
}
var nContent = new HtmlString(strValue);
return nContent;
}
This works ok for returning one field (ie property) from a document. However, if I wanted to return 2 or more, ideally, I would store the returned node in a variable or class and then be able to fetch property values repeatedly without having to look up the document with each call
ie without calling
umbracoHelper.Content(docID).GetPropertyValue(strPropertyName).ToString();
with different strPropertyName parameters each time, as I assume that will mean multiple reads from the database).
I tried to build a class, with its properties to hold the returned node
using Umbraco.Web;
using Umbraco.Core.Models;
...
public static Umbraco.Web.UmbracoHelper umbracoHelper = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);
public static IPublishedContent docNode;
...
docNode = umbracoHelper.Content(docID);
but this crashed the code. Can I store the node in a property on a class, and if so, what type is it?
First of all, using a .cshtml file is unnecessary, use a .cs file instead :-) CSHTML files are for Razor code and HTML and stuff, CS files are for "pure" C#. That might also explain why your last idea crashes.
Second of all, UmbracoHelper uses Umbracos own cache, which means that the database is NOT touched with every request. I would at least define the umbracoHelper object outside of the method (so it gets reused every time the method is called instead of reinitialised).
Also, beware that property values can contain all kinds of other object types than strings.
EDIT
This is an example of the entire class file - my example namespace is Umbraco7 and my example class name is Helpers:
using Umbraco.Web;
namespace Umbraco7
{
public class Helpers
{
private static UmbracoHelper umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
private static dynamic docNode;
public static string docFieldValue(int docID, string strPropertyName)
{
docNode = umbracoHelper.Content(docID);
return docNode.GetPropertyValue(strPropertyName).ToString();
}
}
}
This is an example how the function is called inside a View (.cshtml file inside Views folder):
#Helpers.docFieldValue(1076, "introduction")
Helpers, again, is the class name I chose. It can be "anything" you want. I've just tested this and it works.
I suggest you read up on general ASP.NET MVC and Razor development, since this is not very Umbraco specific.

How can I get access to the current test method in NUnit

TestContext.CurrentContext.Test has several properties like FullName which can be parsed to get the current test method within NUnit. However, these don't help at all when the test's name is overridden using the TestName property on the TestCase attribute.
Is there a simple way to get the MethodInfo for the current test method from within an NUnit test? I can't simply use a stack trace, because I need this information in SetUp and TearDown when the test method is not on the stack.
I'm using NUnit 2.6.2
One thing that comes to my mind is writing a custom NUnit EventListener addin.
Then you could hook into the runcycle of the test runner and at least on the TestStarted overload you will have the TestName object. This won't have the MethodInfo available directly, but you may get it by playing around with the given properties there.
Good luck!
NUnit by default does not provide such information - but it can be queries via private fields and properties. Following code could be used for example (Tested with NUnit 3.13.2):
/// <summary>
/// Accesses private class type via reflection.
/// </summary>
/// <param name="_o">input object</param>
/// <param name="propertyPath">List of properties in one string, comma separated.</param>
/// <returns>output object</returns>
object getPrivate(object _o, string propertyPath)
{
object o = _o;
var flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
foreach (var name in propertyPath.Split('.'))
{
System.Type type = o.GetType();
if (char.IsUpper(name[0]))
o = type.GetProperty(name, flags).GetValue(o);
else
o = type.GetField(name, flags).GetValue(o);
}
return o;
}
[SetUp]
public void EachSpecSetup()
{
var mi = (MemberInfo)getPrivate(TestContext.CurrentContext.Test, "_test.Method.MethodInfo");
// Alternative method - using Exposed nuget package:
//dynamic test = Exposed.From(TestContext.CurrentContext.Test)._test;
//dynamic method = Exposed.From(test)._method;
FactAttribute attr = mi.GetCustomAttribute<FactAttribute>();
string path = attr.FilePath;
string funcName = attr.FunctionName;
}
Like mentioned in code above it's also possible to use Exposed.From - but main example should be theoretically faster.
Code will throw exception if any field / property is not valid - and this is intentional - use Visual studio watch window to identify type / field / properties.

how to change the themes in asp.net mvc 2

I would like to have an option wherein a user can choose his theme for the site from the dropdown list and the theme applies to that page [atleast].
I want this to be done in ASP.NET MVC 2 without using jquery like frameworks.
How can this be accomplished.
I am using the default webforms viewengine and donot want to go for a custom viewengine for this purpose.
It seems this is not supported out of the box, but here's what I did to implement theming:
First, I Added the App_Themes folder to my project, and set up a couple of themes
I then decided to try and mimic the Web-forms profile provider as close as possible, and added a profile-property to web.config:
<profile>
<properties>
<add name="ThemePreference" type="string" defaultValue="Blue" />
</properties>
</profile>
So, basically what I wanted to do was to be able to load the different css's from the appropriate theme-folder when the theme changed. I did this by implementing a helper method attached to the UrlHelper class so that I could write:
<link href="#Url.Theme("~/Content/Site.css")" rel="stylesheet" type="text/css" />
This should then load the appropriate themed Site.css, and fall back to ~/Content/Site.css if no file was found.
The helper is pretty simple:
public static class UrlHelpers
{
public static string Theme(this UrlHelper url, string u)
{
if (u.StartsWith("~")) u = u.TrimStart('~');
SettingsProperty settingsProperty = ProfileBase.Properties["ThemePreference"];
return url.Content("~/App_Themes/"+settingsProperty.DefaultValue + u);
}
}
Now, in this version of the code it simply gets the default-value, so you'll need to tweak the code slightly. But as you can see, this is not limited to css-files, but works with everything from .master files to images.
Update - Using Session instead of profile
public static class UrlHelpers
{
public static string Theme(this UrlHelper url, string u)
{
if (u.StartsWith("~")) u = u.TrimStart('~');
object currentThemeName = null;
if (url.RequestContext.HttpContext.Session != null)
{
currentThemeName = url.RequestContext.HttpContext.Session["ThemePreference"];
}
return currentThemeName != null ? url.Content(String.Format("~/App_Themes/{0}{1}", currentThemeName, u)) : url.Content("~"+u);
}
}
The return-line in this method checks if it found a ThemePreference session-value, and then returnes the appropriate URL for the content requested, otherwise it simply returns the content as it was requested with no App_Theme prefix.
In your controlleraction for the DropDown postmethod, you'd simply do:
Session.Add("ThemePreference", whateverValueYouGotFromDropdown);
Update ends
With some tweaking and fixing, this should do the trick.
Hope it helps some, even though it's not a complete walkthrough :)

How to get the URL to a Wicket shared resource?

The web designer has given me HTML which looks like:
<div .... style="background: transparent url(xxx.png) 170px center no-repeat">
Unfortunately the contents of the image xxx.png is generated by the software, so I have made it a WebResource and use the following strategy to generate the URL for the resource which I then embed in the style= attribute using a Wicket AttributeModifier.
// App initialization code
String resourceName = ....;
getSharedResources().add(resourceName, myWebResource);
// Creating the widget
String url = getServletContext().getContextPath()
+ "/resources/org.apache.wicket.Application/" + resourceName ;
String style = "background: transparent url(" + url + ") 170px center no-repeat";
div.add(new AttributeModifier("style", new Model<String>(style)));
This works fine when I test it locally using Eclipse, but :
When I install this in production, I want to have Apache as a proxy to Jetty such that the context root isn't visible, i.e. Apache forwards a request of /foo onto Jetty as /context-root/foo.
In general, I don't think this is very elegant. I'm sure I am duplicating Wicket code here?
I understand Wicket solves this problem of context-roots and Apache proxying by only using relative URLs. That would be the most elegant solution I suspect. But if I have e.g. a IndexedParamUrlCodingStrategy then the URL could be of arbitrary length and I don't know how many .. to include to get back to /resources.
Edit: The current solution is to use absolute URLs as in my code example above, and in Apache (a) rewrite /context-root/* into /* (b) as before then ADD the context root to all requests (c) forward to Jetty. That way most URLs can be without the context root but some URLs (to my resources) can have the context root and it's OK. But I don't like this solution!
If the code is called from inside a component (or page):
urlFor(new ResourceReference("sharedResourceName"));
or
RequestCycle.get().urlFor(new ResourceReference("sharedResourceName"));
Sample application below. I used a ByteArrayResource for simplicity, but any Resource subclass will do:
WicketApplication.java
package app1;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.request.target.coding.IndexedParamUrlCodingStrategy;
import org.apache.wicket.resource.ByteArrayResource;
public class WicketApplication extends WebApplication {
#Override
protected void init() {
super.init();
getSharedResources().add("testResource", new ByteArrayResource("text/plain", "This is a test".getBytes()));
mount(new IndexedParamUrlCodingStrategy("home/very/deep/folder", getHomePage()));
}
public Class<HomePage> getHomePage() {
return HomePage.class;
}
}
HomePage.java
package app1;
import org.apache.wicket.PageParameters;
import org.apache.wicket.ResourceReference;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.WebPage;
public class HomePage extends WebPage {
public HomePage(final PageParameters parameters) {
CharSequence resourceHref = urlFor(new ResourceReference("testResource"));
add(new Label("link", "Click me!")
.add(new SimpleAttributeModifier("href", resourceHref)));
}
}
HomePage.html
<html xmlns:wicket="http://wicket.apache.org/dtds.data/wicket-xhtml1.4-strict.dtd" >
<body>
<a wicket:id="link"></a>
</body>
</html>
I think the tactic used in this answer for creating dynamic image urls will apply here.