Browser Java Plugin Detection - java

What is the preferred method to determine if the Sun Java Plugin is installed in the browser?

java deployment toolkit
script src="http://java.com/js/deployJava.js"
if (deployJava.versionCheck('1.6'))
{
alert("1.6 installed")
}

You may also consider PluginDetect script.

This isn't an answer for your exact question but is offered as a solution for determining the browser itself. Don't be too harsh, this is really old code that I wrote some time ago.
import java.applet.*;
public class BrowserDetector extends Applet {
public void init() {
if (isNetscape()) {
System.out.println("This browser is a Netscape Browser.");
}
if (isMicrosoft()) {
System.out.println("This browser is a Microsoft Browser.");
}
System.out.println("VM Type: " + getVMType());
}
public static boolean isNetscape() {
try {
Class.forName("netscape.applet.MozillaAppletContext");
} catch (ClassNotFoundException e) {
System.out.println("This browser is not a Netscape Browser.");
return false;
}
return true;
}
public static boolean isMicrosoft() {
try {
Class.forName("com.ms.applet.GenericAppletContext");
} catch (ClassNotFoundException e) {
System.out.println("This browser is not a Microsoft Browser.");
return false;
}
return true;
}
public String getVMType() {
String theBrowser = "No VM";
String appletContext = getAppletContext().toString();
if (appletContext.startsWith("sun.applet.AppletViewer"))
theBrowser = "APPLETVIEWER";
else if (appletContext.startsWith("netscape.applet."))
theBrowser = "NETSCAPE";
else if (appletContext.startsWith("com.ms.applet."))
theBrowser = "MICROSOFT";
else if (appletContext.startsWith("sunw.hotjava.tags.TagAppletPanel"))
theBrowser = "HOTJAVA";
else if (appletContext.startsWith( "sun.plugin.navig.win32.AppletPlugin"))
theBrowser = "NETSCAPEPLUGIN";
else if (appletContext.startsWith( "sun.plugin.ocx.ActiveXApplet"))
theBrowser = "MICROSOFTPLUGIN";
else if (appletContext.startsWith( "sun.plugin.viewer.context.IExplorerAppletContext"))
theBrowser = "MICROSOFTPLUGINJRE1.4";
return theBrowser;
}
}

Related

Custom wait for selenium for angular7 application

We are automating an Angular 7 application using Selenium Webdriver. I need the custom waits using Javascript or JQuery that will wait for the page to render and wait for the $http response to get completed.
I've tried explicit waits but they are not working since the elements get loaded on the page but still loads and tried ng Webdriver but that is also failing.
These may be helpful for you. Before accessing any element check whether Jquery/Angular is done or not.
public static boolean isJQueryDone() {
Object jsResponse = tryJavascript("return jQuery.active;");
if (jsResponse instanceof Long) {
return ((Long) jsResponse) == 0;
} else if (jsResponse instanceof String) {
String response = (String) jsResponse;
return (response.startsWith("{\"hCode\"") || response.isEmpty());
} else {
return true;
}
}
public static boolean isAngularDone() {
Object jsResponse = tryJavascript("return window.getAllAngularTestabilities().filter(x=>!x.isStable()).length;");
if (jsResponse instanceof Long) {
return ((Long) jsResponse) == 0;
} else if (jsResponse instanceof String) {
String response = (String) jsResponse;
return response.isEmpty();
} else {
return true;
}
}
public static synchronized Object tryJavascript(String script, Object... args) {
try {
return execJavascript(script, args);
} catch (Exception ignore) {
return "";
}
}

Exception in using Java API Oracle VirtualBox

My goal is running some process in VirtualMachine using Java. First of all, I have a part of code for create and connect to VB, but i have exception(NullPointer in main Thread) in 21 and 89 lines. I searching some answer to fix this problem, and read that problem look as I haven't Oracle VB. But in my computer i have it , version equals to imported.
So if you have an experience in using this API, or can help me, please, describe in detail how i can fix it. So, my code:
import org.virtualbox_5_1.*;
import org.virtualbox_5_1.ISession;
import org.virtualbox_5_1.IProgress;
import java.util.List;
import java.util.Arrays;
public class Events_5_1 {
static VirtualBoxManager mgr;
static Thread listener;
public static void main(String[] args) {
String vmName = Long.toString(System.currentTimeMillis()); // Берем рандомное значение имени VirtualMachine
System.out.println("Creating VirtualBox instance");
mgr = VirtualBoxManager.createInstance(null);
try {
listener = new EventWorker();
listener.start();
try {
//Создаем пустую машину и сохраняем на диск
IMachine vm = mgr.getVBox().createMachine(null, vmName, null, "Other", null);//тестить , разобраться с параметрами
vm.saveSettings();
mgr.getVBox().registerMachine(vm);
vm = mgr.getVBox().findMachine(vmName);
ISession session = mgr.getSessionObject();
IProgress p = vm.launchVMProcess(session, "headless", null); // Вместо headless - ставим процесс ??
p.waitForCompletion(-1);
try {
if (p.getResultCode() != 0) {
throw new RuntimeException(p.getErrorInfo().getText());
} else {
p = session.getConsole().powerDown();
p.waitForCompletion(-1);
if (p.getResultCode() != 0) {
throw new RuntimeException(p.getErrorInfo().getText());
} else {
}
}
} finally {
session.unlockMachine();
while (!SessionState.Unlocked.equals(vm.getSessionState())) {
try {
System.out.println("Waiting for session unlocked");
Thread.sleep(1000L);
} catch (InterruptedException e) {
System.err.println("Interrupted while vaiting for session unlocked");
}
}
System.out.println("Deleting machine");
vm.deleteConfig(vm.unregister(CleanupMode.DetachAllReturnHardDisksOnly));
}
} finally {
listener.interrupt();
try {
listener.join(5000);
} catch (InterruptedException e) {
System.err.println("Inerrupted while vaiting for EventWorker stop");
}
if (listener.isAlive()) {
System.err.println("Event worked did not stop in a timely fashion");
} else {
System.out.println("event worker stoped");
}
}
} finally {
mgr.disconnect();
mgr.cleanup();
System.out.println("Disconecting from VirtualBox");
}
}
static class EventWorker extends Thread {
IEventListener el;
#Override
public void run() {
System.out.println("EventWorker started");
el = mgr.getVBox().getEventSource().createListener();
//TODO: connect gradle, mvnrepository.com idea connect datasource postgre
List<VBoxEventType> types = Arrays.asList(VBoxEventType.OnSessionStateChanged, VBoxEventType.OnMachineStateChanged,
VBoxEventType.OnMachineRegistered);
mgr.getVBox().getEventSource().registerListener(el, types, false);
try{
while(!isInterrupted()){
mgr.waitForEvents(0);
IEvent rawEvent = mgr.getVBox().getEventSource().getEvent(el , 1000);
if(rawEvent==null) continue;
try{
System.out.println("Got event type "+rawEvent.getType());
if(VBoxEventType.OnSessionStateChanged.equals(rawEvent.getType())){
ISessionStateChangedEvent event = ISessionStateChangedEvent.queryInterface(rawEvent);
System.out.println("Machine "+event.getState()+" for machine "+event.getMachineId());
}
if(VBoxEventType.OnMachineRegistered.equals((rawEvent.getType()))){
IMachineRegisteredEvent event = IMachineRegisteredEvent.queryInterface(rawEvent);
System.out.println("Machine "+event.getMachineId()+" has been "+(event.getRegistered() ? "registered":"unregistered"));
}
if(VBoxEventType.OnMachineStateChanged.equals(rawEvent.getType())){
IMachineStateChangedEvent event = IMachineStateChangedEvent.queryInterface(rawEvent);
System.out.println("Machine "+event.getMachineId()+" state changed to "+event.getState());
}
}finally {
mgr.getVBox().getEventSource().eventProcessed(el,rawEvent);
}
}
}catch(Throwable t){
t.printStackTrace();
}finally {
mgr.getVBox().getEventSource().unregisterListener(el);
System.out.println("EventWorker finished");
}
}
}
}
If you are to plain copy/paste adapt my code, you should at least stick to the code structure and flow.
You've moved code around for some reasons and variables are not initialized timely, which is why you get NPEs.
Here is the working version for VirtualBox 5.1.x

Error in creating new workspace in Eclipse RCP application

Problem in creating a new workspace in an Eclipse RCP application.
When the RCP application is launched, a dialog is prompted to ask the workspace location.
When the location is given, then there is error saying "Could not launch the product because the specified workspace cannot be created.
The specified workspace directory is either invalid or read-only".
I have followed the code from IDEApplication.java from eclipse, but still I am facing same issue.
Application code:
#SuppressWarnings("restriction")
public class MyRcpApplication implements IApplication
{
private static final String METADATA_PROJECTS_PATH = "/.plugins/org.eclipse.core.resources/.projects";
private static final String METADATA_ROOT = ".metadata";
private static final String COMMAND_ARG = "--container";
private static final String SYSTEM_PROPERTY_EXIT_CODE = "eclipse.exitcode";
private static final String WORKSPACE_VERSION_KEY = "org.eclipse.core.runtime";
private static final String VERSION_FILENAME = "version.ini";
private static final String WORKSPACE_VERSION_VALUE = "1"; //$NON-NLS-1$
public static final String METADATA_FOLDER = ".metadata"; //$NON-NLS-1$
private Shell shell;
/*
* (non-Javadoc)
*
* #see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext)
*/
#Override
public Object start(final IApplicationContext context)
{
Display display = PlatformUI.createDisplay();
Shell shell = display.getActiveShell();
try
{
// for backward compatibility we need to clear the workspace before start also
cleanUpTheWorkSpace();
boolean instanceLocationCheck = checkInstanceLocation(shell, context.getArguments());
if (!instanceLocationCheck)
{
MessageDialog.openError(shell, IDEWorkbenchMessages.IDEApplication_workspaceInUseTitle,
"Could not launch the product because the associated workspace is currently in use by another My Application.");
return IApplication.EXIT_OK;
}
int returnCode = PlatformUI.createAndRunWorkbench(display, new MyApplicationWorkbenchAdvisor());
if (returnCode == PlatformUI.RETURN_RESTART)
{
// eclipse.exitcode system property may be set to re-launch
if (IApplication.EXIT_RELAUNCH.equals(Integer.getInteger(SYSTEM_PROPERTY_EXIT_CODE)))
{
return IApplication.EXIT_RELAUNCH;
}
return IApplication.EXIT_RESTART;
}
// if application return code is exit clean up the workspace
// cleanUpTheWorkSpace();
return IApplication.EXIT_OK;
}
finally
{
if (display != null)
{
display.dispose();
}
Location instanceLoc = Platform.getInstanceLocation();
if (instanceLoc != null)
{
instanceLoc.release();
}
}
}
#SuppressWarnings("rawtypes")
private boolean checkInstanceLocation(final Shell shell, final Map arguments)
{
Location instanceLoc = Platform.getInstanceLocation();
if (instanceLoc == null)
{
MessageDialog.openError(shell, "Workspace is Mandatory", "IDEs need a valid workspace.");
return false;
}
// -data "/valid/path", workspace already set
if (instanceLoc.isSet())
{
// make sure the meta data version is compatible (or the user has
// chosen to overwrite it).
try
{
// Used to check whether are we launching My application from development environment or not
if (isDevLaunchMode(arguments))
{
return true;
}
// Used to check instance location is locked or not
if (instanceLoc.isLocked())
{
return false;
}
// we failed to create the directory.
// Two possibilities:
// 1. directory is already in use
// 2. directory could not be created
File workspaceDirectory = new File(instanceLoc.getURL().getFile());
if (workspaceDirectory.exists())
{
if (isDevLaunchMode(arguments))
{
return true;
}
MessageDialog.openError(
shell,
"Workspace Cannot Be Locked",
"Could not launch the product because the associated workspace at '" + workspaceDirectory.getAbsolutePath()
+ "' is currently in use by another Eclipse application");
}
else
{
MessageDialog
.openError(
shell,
"Workspace Cannot Be Created",
"Could not launch the product because the specified workspace cannot be created. The specified workspace directory is either invalid or read-only.");
}
}
catch (IOException e)
{
MessageDialog.openError(shell, "Internal Error", e.getMessage());
}
}
else
{
try
{
// -data #noDefault or -data not specified, prompt and set
ChooseWorkspaceData launchData = new ChooseWorkspaceData(instanceLoc.getDefault());
boolean force = false;
while (true)
{
URL workspaceUrl = promptForWorkspace(shell, launchData, force);
if (workspaceUrl == null)
{
return false;
}
// if there is an error with the first selection, then force the
// dialog to open to give the user a chance to correct
force = true;
try
{
// the operation will fail if the url is not a valid
// instance data area, so other checking is unneeded
if (instanceLoc.set(workspaceUrl, false))
{
launchData.writePersistedData();
writeWorkspaceVersion(workspaceUrl);
return true;
}
}
catch (IllegalStateException e)
{
MessageDialog
.openError(
shell,
IDEWorkbenchMessages
.IDEApplication_workspaceCannotBeSetTitle,
IDEWorkbenchMessages
.IDEApplication_workspaceCannotBeSetMessage);
return false;
}
// by this point it has been determined that the workspace is
// already in use -- force the user to choose again
MessageDialog.openError(shell, IDEWorkbenchMessages
.IDEApplication_workspaceInUseTitle,
IDEWorkbenchMessages.
IDEApplication_workspaceInUseMessage);
}
}
catch (IllegalStateException | IOException e)
{
}
}
return true;
}
private static void writeWorkspaceVersion(final URL defaultValue)
{
Location instanceLoc = Platform.getInstanceLocation();
if (instanceLoc.isReadOnly())
{
// MessageDialog.openError(shell,"Read-Only Dialog", "Location was read-only");
System.out.println("Instance Got Locked......");
}
if ((instanceLoc == null) || instanceLoc.isReadOnly())
{
return;
}
File versionFile = getVersionFile(instanceLoc.getURL(), true);
if (versionFile == null)
{
return;
}
OutputStream output = null;
try
{
String versionLine = WORKSPACE_VERSION_KEY + '=' + WORKSPACE_VERSION_VALUE;
output = new FileOutputStream(versionFile);
output.write(versionLine.getBytes("UTF-8")); //$NON-NLS-1$
}
catch (IOException e)
{
IDEWorkbenchPlugin.log("Could not write version file", //$NON-NLS-1$
StatusUtil.newStatus(IStatus.ERROR, e.getMessage(), e));
}
finally
{
try
{
if (output != null)
{
output.close();
}
}
catch (IOException e)
{
// do nothing
}
}
}
/*
* (non-Javadoc)
*
* #see org.eclipse.equinox.app.IApplication#stop()
*/
#Override
public void stop()
{
if (!PlatformUI.isWorkbenchRunning())
{
return;
}
final IWorkbench workbench = PlatformUI.getWorkbench();
final Display display = workbench.getDisplay();
display.syncExec(new Runnable()
{
#Override
public void run()
{
if (!display.isDisposed())
{
workbench.close();
}
}
});
}
private URL promptForWorkspace(final Shell shell, final ChooseWorkspaceData launchData, boolean force)
{
URL url = null;
do
{
new ChooseWorkspaceDialog(shell, launchData, false, force).prompt(force);
String instancePath = launchData.getSelection();
if (instancePath == null)
{
return null;
}
// the dialog is not forced on the first iteration, but is on every
// subsequent one -- if there was an error then the user needs to be
// allowed to
force = true;
// create the workspace if it does not already exist
File workspace = new File(instancePath);
if (!workspace.exists())
{
workspace.mkdir();
}
try
{
// Don't use File.toURL() since it adds a leading slash that Platform does not
// handle properly. See bug 54081 for more details.
String path = workspace.getAbsolutePath().replace(File.separatorChar, '/');
url = new URL("file", null, path); //$NON-NLS-1$
}
catch (MalformedURLException e)
{
MessageDialog
.openError(
shell,
IDEWorkbenchMessages
.IDEApplication_workspaceInvalidTitle,
IDEWorkbenchMessages
.IDEApplication_workspaceInvalidMessage);
continue;
}
}
while (!checkValidWorkspace(shell, url));
return url;
}
private boolean checkValidWorkspace(final Shell shell, final URL url)
{
String version = readWorkspaceVersion(url);
// if the version could not be read, then there is not any existing
// workspace data to trample, e.g., perhaps its a new directory that
// is just starting to be used as a workspace
if (version == null)
{
return true;
}
final int ide_version = Integer.parseInt(WORKSPACE_VERSION_VALUE);
int workspace_version = Integer.parseInt(version);
// equality test is required since any version difference (newer
// or older) may result in data being trampled
if (workspace_version == ide_version)
{
return true;
}
// At this point workspace has been detected to be from a version
// other than the current ide version -- find out if the user wants
// to use it anyhow.
String title = "My App Titile"; //$NON-NLS-1$
String message = "My App Message";
MessageBox mbox = new MessageBox(shell, SWT.OK | SWT.CANCEL
| SWT.ICON_WARNING | SWT.APPLICATION_MODAL);
mbox.setText(title);
mbox.setMessage(message);
return mbox.open() == SWT.OK;
}
private static String readWorkspaceVersion(final URL workspace)
{
File versionFile = getVersionFile(workspace, false);
if ((versionFile == null) || !versionFile.exists())
{
return null;
}
try
{
// Although the version file is not spec'ed to be a Java properties
// file, it happens to follow the same format currently, so using
// Properties to read it is convenient.
Properties props = new Properties();
FileInputStream is = new FileInputStream(versionFile);
try
{
props.load(is);
}
finally
{
is.close();
}
return props.getProperty(WORKSPACE_VERSION_KEY);
}
catch (IOException e)
{
IDEWorkbenchPlugin.log("Could not read version file", new Status( //$NON-NLS-1$
IStatus.ERROR, IDEWorkbenchPlugin.IDE_WORKBENCH,
IStatus.ERROR,
e.getMessage() == null ? "" : e.getMessage(), //$NON-NLS-1$,
e));
return null;
}
}
private static File getVersionFile(final URL workspaceUrl, final boolean create)
{
if (workspaceUrl == null)
{
return null;
}
try
{
// make sure the directory exists
File metaDir = new File(workspaceUrl.getPath(), METADATA_FOLDER);
if (!metaDir.exists() && (!create || !metaDir.mkdir()))
{
return null;
}
// make sure the file exists
File versionFile = new File(metaDir, VERSION_FILENAME);
if (!versionFile.exists()
&& (!create || !versionFile.createNewFile()))
{
return null;
}
return versionFile;
}
catch (IOException e)
{
// cannot log because instance area has not been set
return null;
}
}
#SuppressWarnings("rawtypes")
private static boolean isDevLaunchMode(final Map args)
{
// see org.eclipse.pde.internal.core.PluginPathFinder.isDevLaunchMode()
if (Boolean.getBoolean("eclipse.pde.launch"))
{
return true;
}
return args.containsKey("-pdelaunch"); //$NON-NLS-1$
}
/**
* Deletes all the available projects in the workspace
*/
private void cleanUpTheWorkSpace()
{
// this will be the
String[] commands = Platform.getCommandLineArgs();
if (commands != null)
{
List<String> args = Arrays.asList(commands);
if (args.contains(COMMAND_ARG))
{
// if project is in the root delete it.. it will delete associated metadata
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
if (projects != null)
{
for (IProject project : projects)
{
try
{
project.delete(true, new NullProgressMonitor());
}
catch (CoreException e)
{
// msgHandler.post(MsgSeverity.ERROR, "Unable to clear the workspace");
}
}
}
// if project is not in the root but if its in the workspace delete the metadata too
File[] workSpaceFiles = Platform.getLocation().toFile().listFiles();
for (File file : workSpaceFiles)
{
if (METADATA_ROOT.equals(file.getName()))
{
File projectMeta = new File(file.getPath() + METADATA_PROJECTS_PATH);
if ((projectMeta != null) && projectMeta.exists())
{
File[] children = projectMeta.listFiles();
for (File child : children)
{
FileUtils.deleteQuietly(child);
}
}
}
/*
* else { FileUtils.deleteQuietly(file); }
*/
}
}
}
}
}
Try run Eclipse as administrator.
Your code is just calling
if (instanceLoc.isLocked())
{
return false;
}
to check if the workspace is locked, but is doing nothing to make the workspace locked so this will always fall through to the error code.
IDEApplication does this:
if (instanceLoc.lock()) {
writeWorkspaceVersion();
return null;
}
you need to do something similar.

How do you use an enum with another enum?

I'm making a selenium webdriver and I have an enum for the environments I am testing my app in and an enum for the app itself. My problem is I can't figure out how to use the environment enum inside the app enum in order to open it. I have a comment at the two spots I think my problem is. I get an error at the first comment so whatever would go there would be helpful.
public enum ENV
{
QA, STAGE,
PROD, DEV;
public String toString()
{
switch(this)
{
case QA: return "http://****/qa_was8.html";
case STAGE: return "http://****/stage.html";
case PROD: return "http://****/prod.html";
case DEV: return "http://****/index.html";
default: return "http://****/qa_was8.html";
}
}
}
public enum Application
{
ACCOUNTINVENTORY , AUDITACTIONITEMS;
public static Application chooseApp(String args)
{
File file = new File("H:\\InternStuff\\Selenium\\IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath() );
WebDriver driver = new InternetExplorerDriver();
for(Application app : Application.values())
{
switch(app)
{
case ACCOUNTINVENTORY:
driver.get(ENV.valueOf(args[1]));//What would go here
driver.findElement(By.linkText("Account Inventory")).click();
driver.findElement(By.name("j_username")).sendKeys("****");
driver.findElement(By.name("j_password")).sendKeys("****");
driver.findElement(By.cssSelector("input[type='submit']")).click();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
driver.findElement(By.className("inputText")).sendKeys("smith");
driver.findElement(By.className("commandExButton")).click();
break;
case AUDITACTIONITEMS:
driver.findElement(By.linkText("AuditAction Items")).click();
driver.findElement(By.name("j_username")).sendKeys("****");
driver.findElement(By.name("j_password")).sendKeys("****");
driver.findElement(By.cssSelector("input[type='submit']")).click();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
driver.findElement(By.className("commandExButton")).click();
default:
System.out.println("...");
}
}
return null;
}
}
public static void main(String[] args)
{
if(args.length != 0)
{
Application app = Application.chooseApp(args[1]);
ENV env = ENV.valueOf(args[0]);
if(app != null)
{
app.toString();
}
else if(env != null)
{
env.toString();// Or maybe is my problem here?
}
}
}
}
If I understand your question, you have a compile time error because you are attempting to treat String args as a String[] in chooseApp. The easiest solution I see is to pass the entire args array to chooseApp,
public static Application chooseApp(String[] args)
// ...
driver.get(ENV.valueOf(args[1]));// <-- now you can access args[1]
then
Application app = Application.chooseApp(args);

getSnapshot not supported on Blackberry

I'm having problem when taking a picture using VideoControl.getSnapshot() method. It always throw the exception: getSnapshot not Supported. I'm using JRE 5.0.0 with Eclipse and BlackBerry® Java® SDK 5.0 Plugin.
What I do first is to list the encoding supported by Blackberry SmartPhone selected (bold 9700) with the command System.getProperty("video.snapshot.encodings") and select one encoding from the list and pass it as the getSnapshot argument.
I've tested on several Blackberry and the same exception is thrown.
Part of the code:
mPlayer = Manager.createPlayer("capture://video?encoding=video/3gpp");
mPlayer.realize();
mPlayer = Manager.createPlayer("capture://video?encoding=video/3gpp");
mPlayer.start();
videoControl = (VideoControl)mPlayer.getControl("VideoControl");
Field cameraView = (Field) videoControl.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
Thread.sleep(1000);
UiApplication.getUiApplication().pushScreen(new TempScreen(cameraView));
byte[] snapShot = videoControl.getSnapshot("encoding=jpeg&width=480&height=360&quality=superfine");
Bitmap image = Bitmap.createBitmapFromBytes(snapShot, 0, snapShot.length, 1);
UiApplication.getUiApplication().pushScreen(new TempScreen(image));
}catch (MediaException e){
UiApplication.getUiApplication().pushScreen(new TempScreen("Exception: " + e.getMessage())); }
catch (IOException e){
UiApplication.getUiApplication().pushScreen(new TempScreen("IO Exception: " + e.getMessage()));
}
catch (InterruptedException e){UiApplication.getUiApplication().pushScreen(new TempScreen("Interrupted Exception: "+ e.getMessage()));}
Not sure is my answer is actual after more than a half of year, but may be it will be useful.
You may try to use Thread.sleep(1000); before getSnapshot() call.
The problem may be related with that fact: "viewfinder must actually be visible on the screen prior to calling getSnapShot()."
So if you call getSnapshot immediately after UiApplication.getUiApplication().pushScreen(new TempScreen(cameraView));
the camera isn't prepared for the next shot.
Also are you really sure that getSnapshot() API is supported exactly on your device? Some manufacturers may not support it, despite the API defines this method. Did you run System.getProperty("video.snapshot.encodings") exactly on the same device where you test getSnapshot()?
Player _p;
VideoControl _vc ;
RecordControl _rc ;
String PATH;
FileConnection fileconn;
Object canvas= new Object();
public static boolean SdcardAvailabulity() {
String root = null;
Enumeration e = FileSystemRegistry.listRoots();
while (e.hasMoreElements()) {
root = (String) e.nextElement();
if( root.equalsIgnoreCase("sdcard/") ) {
return true;
}else if( root.equalsIgnoreCase("store/") ) {
return false;
}
}
class MySDListener implements FileSystemListener {
public void rootChanged(int state, String rootName) {
if( state == ROOT_ADDED ) {
if( rootName.equalsIgnoreCase("sdcard/") ) {
}
} else if( state == ROOT_REMOVED ) {
}
}
}
return true;
}
protected boolean invokeAction(int action){
boolean handled = super.invokeAction(action);
if(SdcardAvailabulity()){
PATH = System.getProperty("fileconn.dir.memorycard.videos")+"Video_"+System.currentTimeMillis()+".3gpp";//here "str" having the current Date and Time;
} else {
PATH = System.getProperty("fileconn.dir.videos")+"Video_"+System.currentTimeMillis()+".3gpp";
}
if(!handled){
if(action == ACTION_INVOKE){
try{
if(_p!=null)
_p.close();
}catch(Exception e){
}
}
}
return handled;
}
public MyScreen(){
setTitle("Video recording demo");
ButtonField AddPhoto = new ButtonField("push",ButtonField.FOCUSABLE | ButtonField.FIELD_HCENTER | ButtonField.FIELD_VCENTER | DrawStyle.HCENTER | ButtonField.NEVER_DIRTY | Field.USE_ALL_WIDTH);
FieldChangeListener PhotoListener = new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
ButtonField Button = (ButtonField) field;
if (Button.getLabel().equals("push")){
}
}
};
AddPhoto.setChangeListener(PhotoListener);
add(AddPhoto);
}
}

Categories