Using the content handler API (JSR 211) to open applications - java

I want to be able to launch native and J2ME applications through my application using the content handler API (JSR 211) on a Nokia 6212.
At the moment, I am unable to do so, as it always states that there is "No Content Handler Found" and throws a javax.microedition.content.ContentHandlerException.
At the moment, I am trying to get the phone to launch its browser and go to a certain website, just to test that I can use the framework. I have tried many different Invocation objects:
//throw exceptions
new Invocation("http://www.somesite.com/index.html",
"application/internet-shortcut");
new Invocation("http://www.google.co.uk","text/html");
// a long shot, I know
new Invocation("http://www.somesite.com/text.txt","text/plain");
// massive long shot
new Invocation("http://www.google.co.uk","application/browser");
//appears to download the link and content (and definitely does in the Nokia
// emulator) and then throws an exception
new Invocation("http://www.google.co.uk");
new Invocation("http://www.somesite.com/index.html");
Below is the code that I have been using, please bear in mind the parameters often changed to generate the different Invocation objects.
/*
* Invokes an application using the Content Handler API
*/
public void doInvoke(String url, String mime, String payload){
Registry register = Registry.getRegistry(this.getClass().getName());
Invocation invoke = new Invocation(url, mime, null, false,
ContentHandler.ACTION_OPEN);
boolean mustQuit = false;
try {
mustQuit = register.invoke(invoke);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (ContentHandlerException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(mustQuit){
this.quit();
}
}

Try this:
Registry register = Registry.getRegistry(this.getClass().getName());
You must call Registry.getRegistry for the MIDlet inheritor. Just use your MIDlet for getting the class name.

Related

Jsoup not connecting to webpage in Android Studio

I am working on a project right now where I use jsoup in a class with the function retrieveMedia in order to return an ArrayList filled with data from the webpage. I run it in a thread since you shouldn't be connecting to URLs from the main thread. I run it and join it. However, it doesn't work (I tested the same code in Eclipse separate from Android Studio and it worked fine). It seems that no matter what I do I can't get jsoup to connect to the webpage. Below is my class MediaRetriever.
public class MediaRetreiever {
public ArrayList<Media> retrieveMedia() {
ArrayList<Media> mediaOutput = new ArrayList<Media>(); //Store each scraped post
Thread downloadThread = new Thread(new Runnable() {
public void run() {
Document doc = null;
try {
doc = Jsoup.connect(<Website Im connecting to>).timeout(20000).get();
} catch (IOException e) {
System.out.println("Failed to connect to webpage.");
mediaOutput.add(new Media("Failed to connect", "oops", "", "oh well"));
return;
}
Elements mediaFeed = doc.getElementById("main").getElementsByClass("node");
for (Element e : mediaFeed) {
String title, author, imageUrl, content;
title=e.getElementsByClass("title").text().trim();
author=e.getElementsByClass("content").tagName("p").select("em").text().trim();
content=e.getElementsByClass("content").text().replace(author,"").trim();
Media media = new Media(title, author, "", content);
mediaOutput.add(media);
}
}
});
downloadThread.start();
try {
downloadThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return mediaOutput;
}
}
Running this class's method from another class and it doesn't ever connect. Any ideas?
Since you say that the problem persists only in Android, it looks like that you should add the user agent string to your request - first get the user agent string of a browser that displays correctly the site, and then add it to the request:
doc = Jsoup.connect(<Website Im connecting to>)
.userAgent("your-user-agent-string")
.timeout(20000).get();
And as a sidenote - if you are catching exception, don't print your own error message - print the original message, it may be very useful.

Theming support in Play Framework 2.0

How can i implement theming support in Play Framework 2?
I want to create directory structure like:
views/default <- default template directory
views/site1 <- template for site 1
views/site2 <- template for site 2
If template doesn`t exist (ie. views/site1/home) it should render template from default directory.
I have tried cls = Class.forName("views.html.home); But I get class not found exception.
SOLUTION:
Maybe someone will find this useful:
protected static String renderTemplate(final String template, final String action,final ViewData templateParams) {
Class<?> cls = null;
String ret = "Template not found";
try {
cls = Class.forName(template);
} catch (ClassNotFoundException e) {
ret = e.toString();
}
if (cls == null) {
try {
cls = Class.forName("views.html.default."+action);
} catch (ClassNotFoundException e) {
ret = e.toString();
}
}
if (cls != null) {
Method htmlRender;
try {
htmlRender = cls.getMethod("render", ViewData.class);
ret = htmlRender.invoke("",templateParams).toString();
} catch (NoSuchMethodException e) {
ret = "Method not found"+e.toString();
} catch (IllegalAccessException e) {
ret = "illegal access exception";
} catch (InvocationTargetException e) {
ret = "InvocationTargetException";
}
}
return ret;
}
ViewData vd=new ViewData();
renderTemplate("views.html.custom."+viewname, actionname, vd)
You have to implement it yourself, as a reference, check the Play Authenticate usage sample, it allows to send ie. validation emails basing on Play's template and depending on the client's language, so for an instance, if your main language is Polish it will render the verify_email_pl.scala.html otherwise if your browser uses language not supported by PA, it will silently fallback to: verify_email_en.scala.html.
Check the usage and declaration of the method.
For your case it will be good solution, of course just criteria of the choice will be different.
This process is called "Branding". What you have to do is following.
Create a table in db by name "BRANDING" and add theme names in it against each instance of website.
Now you will make folders hierarchy as you mentioned and in jsp pages where load css files you will do that like this <link rel="stylesheet" type="text/css" href="/views/${themeName}.css">
where themeName would be a server side variable that you will program in your controller to be fetched from db or first time you will fetch it and then cache it.

Sending XML from Java to MSMQ - bodyType from VT_EMPTY to VT_BSTR

We work on a Java (Java EE) application, and we generate XML files in order to send them to a remote .NET application with MSMQ reading on their side.
The XML file is generated by JDom, like so :
// add elements...
Document doc = new Document(root);
String XmlData = new XMLOutputter(Format.getPrettyFormat().setOmitEncoding(true)).outputString(doc);
try {
SendFile( XmlData, "title" , "path");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MessageQueueException e) {
e.printStackTrace();
}
Then we use this function, using the MsmqJava library to send the file :
private void SendFile(String data, String title, String outputPath) throws UnsupportedEncodingException, MessageQueueException{
String qname="name_of_the_queue";
String fullname= "server_path" + qname;
String body = data;
String label = title;
String correlationId= "L:none";
try {
Queue queue= new Queue(fullname);
Message msg= new Message(body, label, correlationId);
queue.send(msg);
} catch (MessageQueueException ex1) {
System.out.println("Put failure: " + ex1.toString());
}
}
They correctly receive the file, but they told us that the bodyType was set to "VT_EMPTY" while they wanted "VT_BSTR", and we haven't find a clue about how to fix this. If you know another lib who does the job, or a workaround to this one, we can change with no problem.
Thanks !
Looking at the documentation for the library you use, it is not possible using that library.
Jmsmqqueue also doesn't provide the functionality you need.
It seems sun also had an adapter: https://wikis.oracle.com/display/JavaCAPS/Sun+Adapter+for+MSMQ

Stop a JADE system (Java agents)

I run JADE embedded in a Java program, i.e. not with java jade.Boot ....
Now I wanted to stop the JADE system, but I have found no nice way to do that.
I can exit the whole program using System.exit(), but that's not what I want to do.
I tried several different things, and I succeeded stopping my agent behaviours,
but a couple of Threads continue running: the AMS, the DF, a web server, the JADE Timer dispatcher, several Deliverer threads, etc.
This is how my current shutdown method looks like:
#Override
public void shutdown() {
// TODO This does not work yet..
try {
for (WeakReference<AgentController> acr : agents) {
AgentController ac = acr.get(); // jade.wrapper.AgentController
if ( ac != null ) ac.kill();
}
container.kill(); // jade.wrapper.AgentContainer
Runtime.instance().shutDown(); // jade.core.Runtime
} catch ( StaleProxyException e ) {
e.printStackTrace();
}
}
The reason I want to do that is that I have some JUnit tests for my
agent system.
Any ideas how to accomplish that?
You can request AMS to stop the platform in such way:
Codec codec = new SLCodec();
Ontology jmo = JADEManagementOntology.getInstance();
getContentManager().registerLanguage(codec);
getContentManager().registerOntology(jmo);
ACLMessage msg = new ACLMessage(ACLMessage.REQUEST);
msg.addReceiver(getAMS());
msg.setLanguage(codec.getName());
msg.setOntology(jmo.getName());
try {
getContentManager().fillContent(msg, new Action(getAID(), new ShutdownPlatform()));
send(msg);
}
catch (Exception e) {}
You can shutdown the whole JADE platform with:
try {
this.getContainerController().getPlatformController().kill();
}
catch (final ControllerException e) {
System.out.println("Failed to end simulation.");
}
"this" refers to an Agent class object.

How to Change Screen Resolution Programmatically?

Let me tell you my problem. I want to change my screen resolution.
I can change it in an application but it changes only application's
screen. I wanna set system's resolution so it won't be important which
application is running on front. My device's resolution is set as 1280
* 720 p. Can I make it 1260 * 680? If it requires to make changes in
Android source code, I can. Just tell me where to change. Waiting for
your help.
This thread on xda-developers should set you on the right track.
Searching too a valid answer to this, but I have a lead to the solution :
WARNING Experimental buggy stuff :
/*
Requires android.permission.WRITE_SETTINGS
and android.permission.WRITE_SECURE_SETTINGS, thus it requires the app to be a system app.
*/
public void changeResolution(int x, int y){
try { Class c = Class.forName("android.os.ServiceManager");
try { Method method = c.getDeclaredMethod("checkService", String.class);
try {
IWindowManager mWindowManager = IWindowManager.Stub.asInterface((IBinder) method.invoke(null,Context.WINDOW_SERVICE));
try { mWindowManager.setForcedDisplaySize(Display.DEFAULT_DISPLAY,x,y);
} catch (RemoteException e) {e.printStackTrace();}
} catch (IllegalAccessException e) {e.printStackTrace();}
catch (InvocationTargetException e) {e.printStackTrace();}
} catch (NoSuchMethodException e) {e.printStackTrace();}
} catch (ClassNotFoundException e) {e.printStackTrace();}
}
Add a reduced AIDL version of IWindowManager to your project :
/app/src/main/aidl/android/view/IWindowManager.aidl
package android.view;
interface IWindowManager
{
boolean startViewServer(int port); // Transaction #1
boolean stopViewServer(); // Transaction #2
boolean isViewServerRunning(); // Transaction #3
void setForcedDisplaySize(int displayId, int width, int height);
void clearForcedDisplaySize(int displayId);
void setForcedDisplayDensity(int displayId, int density);
void clearForcedDisplayDensity(int displayId);
}
The app will require to be in the system apps folder.
It does something for sure, but right now it also lead to severe bugs.
Rebooting seems to cancel changes.
Waiting for feedback on this.
If you are using Windows and know how to use JNI, Microsoft provides C++ Win32 function calls to do this: ChangeDisplaySettingsEx() and EnumDisplaySettings().

Categories