CaptureDeviceManager.getDeviceList() returns null - java

I coded in java on ubuntu 11.10
Laptop webcam is running correctly and locate it /dev/v4l/.
Skype application can use webcam and run.
I installed JMF but i couldn't add environment variables.`
Vector deviceList = CaptureDeviceManager.getDeviceList(new RGBFormat());
System.out.println(deviceList.toString());
if(!deviceList.isEmpty()){
System.out.println("1");
device = (CaptureDeviceInfo) deviceList.firstElement();
}
device = (CaptureDeviceInfo) deviceList.firstElement();
ml = device.getLocator();
I want to just a capture a image in java.
What should i do solving the problem or use instead of JMF?

Before calling CaptureDeviceManager.getDeviceList(), the available devices must be loaded into the memory first.
You can do it manually by running JMFRegistry after installing JMF.
or do it programmatically with the help of the extension library FMJ (Free Media in Java). Here is the code:
import java.lang.reflect.Field;
import java.util.Vector;
import javax.media.*;
import javax.media.format.RGBFormat;
import net.sf.fmj.media.cdp.GlobalCaptureDevicePlugger;
public class FMJSandbox {
static {
System.setProperty("java.library.path", "D:/fmj-sf/native/win32-x86/");
try {
final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
sysPathsField.setAccessible(true);
sysPathsField.set(null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
GlobalCaptureDevicePlugger.addCaptureDevices();
Vector deviceInfo = CaptureDeviceManager.getDeviceList(new RGBFormat());
System.out.println(deviceInfo.size());
for (Object obj : deviceInfo ) {
System.out.println(obj);
}
}
}

Related

Setup for Bluecove

This is my first project with bluecove and I am having problems before I even start!
Here is my code:
import java.io.IOException;
import java.util.ArrayList;
import bluecove;
/**
* Class that discovers all bluetooth devices in the neighbourhood and
displays their name and bluetooth address.
*/
public class BluetoothDeviceDiscovery implements DiscoveryListener {
// object used for waiting
private static Object lock = new Object();
// vector containing the devices discovered
public static ArrayList<RemoteDevice> devices;
public BluetoothDeviceDiscovery() {
devices = new ArrayList<RemoteDevice>();
}
// main method of the application
public static void main(String[] args) throws IOException {
//create an instance of this class
BluetoothDeviceDiscovery bluetoothDeviceDiscovery=new
BluetoothDeviceDiscovery();
//display local device address and name
LocalDevice localDevice = LocalDevice.getLocalDevice();
System.out.println("Address: " + localDevice.getBluetoothAddress());
System.out.println("Name: " + localDevice.getFriendlyName());
//find devices
DiscoveryAgent agent = localDevice.getDiscoveryAgent();
System.out.println("Starting device inquiry…");
agent.startInquiry(DiscoveryAgent.GIAC, bluetoothDeviceDiscovery);
try {
synchronized(lock) {
lock.wait();
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Device Inquiry Completed. ");
//print all devices in devices
int deviceCount=devices.size();
System.out.println(deviceCount);
if(deviceCount <= 0) {
System.out.println("No Devices Found .");
} else {
//print bluetooth device addresses and names in the format [ No. address (name) ]
System.out.println("Bluetooth Devices:" );
for (int i = 0; i < deviceCount; i++) {
RemoteDevice remoteDevice=(RemoteDevice)devices.get(i);
System.out.println(i +". "+remoteDevice.getBluetoothAddress() );
//("+remoteDevice.getFriendlyName(true)+")");
}
}
}
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod)
{
System.out.println("Device discovered: "+btDevice.getBluetoothAddress());
//add the device to the vector
if(!devices.contains(btDevice))
{
devices.add(btDevice);
}
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
}
public void serviceSearchCompleted(int transID, int respCode) {
}
public void inquiryCompleted(int discType)
{
synchronized(lock){
lock.notify();
}
switch (discType)
{
case DiscoveryListener.INQUIRY_COMPLETED :
System.out.println("INQUIRY_COMPLETED");
break;
case DiscoveryListener.INQUIRY_TERMINATED :
System.out.println("INQUIRY_TERMINATED");
break;
case DiscoveryListener.INQUIRY_ERROR :
System.out.println("INQUIRY_ERROR");
break;
default :
System.out.println("Unknown Response Code");
break;
}
}
}
I am getting an error on line 3 (surprise, surprise) telling me that a ';' was expected.
I know the real reason I am getting an error is that I did not import bluecove correctly.
I downloaded the bluecove jar, renamed it and added the file to my classpath thinking that I could now import and use bluecove in my java projects.
Did I setup/import bluecove the wrong way? How do I actually import bluecove so I can use bluetooth in my project?
The first two import statements inform Java about the full package paths for the IOException and ArrayList classes that you are referencing in your code.
Once you start using bluecove classes in your code, you will need to add one or more import statements telling Java about the full package paths of those classes.
Just in case some impatient people come here for a quick copy&paste, here is my list of imports:
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.UUID;

how to obtain the Wireless AP's SSIDs of the network through java?

iam new to java programming and my final year project is based on a Rogue Access point detection tool, and i need to how can i obtain SSID from a java code of the exisiting wifi networks?
for eg: say iam in my laptop i need the program to show how many SSIDs are there broadcasting the SSIDS and the names! (through the built in wifi adapter in the laptop).
Thank you.
Java is a High-Level, Platform-Independent programming language. Network settings, and how you control them will depend on your Operating System, and to my knowledge there is no simple way or an API to expose this,but i tried write a code maybe is helpful for you.
Code :
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package network;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Electron-Eddine
*/
public class Network {
ArrayList<String> localNetworks = new ArrayList<>();
public static void main(String[] args) throws IOException {
new network.Network().display(new Network().getNetwokrs());
new Network().searchSystemNetwork(new Network().getNetwokrs());
}
public ArrayList<String> getNetwokrs() throws IOException {
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", "netsh wlan show networks mode=Bssid");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String lineCommand;
String network ;
while (true) {
lineCommand = r.readLine();
if (lineCommand == null) {
break;
} else if (lineCommand.contains("SSID")&&!lineCommand.contains("BSSID")) {
String[] networks = lineCommand.split(":", 2);
network = networks[1];
if (!network.equals(" ")) {
String pureNetworkName = network.trim();
localNetworks.add(pureNetworkName);
} else {
return null;
}
}
}
return localNetworks;
}
private void display(ArrayList<String> networks) {
networks.forEach(network -> {
System.out.println(network);
});
}
private void searchSystemNetwork(ArrayList<String> networks) {
String REQUIRED_NETWORK = "PEER2PEER";
networks.forEach(network -> {
if (network.equals(REQUIRED_NETWORK)) {
System.out.println("Network is availabale");
} else {
}
});
}
void create()
{
// Netsh WLAN export profile key=clear folder="Folder_Path"
}
}
Output :
run:
PEER2PEER
condor PGN522
Ammar_A
Network is availabale
BUILD SUCCESSFUL (total time: 1 second)

How to get text of a toaster message in mobile app using Appium

I am trying to verify a toaster message in Android Mobile app but not able to get text of toaster message as it doesn't show in uiautomatorviewer.
Got some information that by the help of OCR it can be done taking screenshots and fetching the text from that screenshots
Can anyone help me out how to do this step by step using java in Appium project?
You can follow the information on the below links to install the Tesseract on your machine:
For Mac: http://emop.tamu.edu/Installing-Tesseract-Mac
For Windows: http://emop.tamu.edu/Installing-Tesseract-Windows8
After installing the TessEract on your machine you need to add the dependency of TessEract Java library in your project. If you are using Maven for it, adding below dependency will work:
<dependency>
<groupId>org.bytedeco.javacpp-presets</groupId>
<artifactId>tesseract</artifactId>
<version>3.04-1.1</version>
</dependency>
Also the 'Step 3' which is mentioned by Ivan need not to be followed.
If you are using 'TestNG' the TessEract API needs to be initialised only once so instead of initialising it every time, as per your framework you can initialise it either in the 'BeforeTest' or 'BeforeSuite' or 'BeforeClass' method and accordingly close the API either in 'AfterTest' or 'AfterSuite' or 'AfterClass' method.
Below is the code that I have written to achieve it.
import static org.bytedeco.javacpp.lept.pixDestroy;
import static org.bytedeco.javacpp.lept.pixRead;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.bytedeco.javacpp.lept.PIX;
import org.bytedeco.javacpp.tesseract.TessBaseAPI;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
public class BaseTest {
static TessBaseAPI api = new TessBaseAPI();
#BeforeSuite
public void beforeSuit() throws IOException {
File screenshotsDirec = new File("target/screenshots");
if (screenshotsDirec.exists())
FileUtils.forceDelete(screenshotsDirec);
FileUtils.forceMkdir(screenshotsDirec);
System.out.println("Initializing TessEract library");
if (api.Init("/opt/local/share", "eng") != 0) {
System.err.println("Could not initialize tesseract.");
}
}
public synchronized boolean verifyToastMessage(String msg)
throws IOException {
TakesScreenshot takeScreenshot = ((TakesScreenshot) driver);
File[] screenshots = new File[5];
for (int i = 0; i < screenshots.length; i++) {
screenshots[i] = takeScreenshot.getScreenshotAs(OutputType.FILE);
}
String outText;
Boolean isMsgContains = false;
for (int i = 0; i < screenshots.length; i++) {
PIX image = pixRead(screenshots[i].getAbsolutePath());
api.SetImage(image);
outText = api.GetUTF8Text().getString().replaceAll("\\s", "");
System.out.println(outText);
isMsgContains = outText.contains(msg);
pixDestroy(image);
if (isMsgContains) {
break;
}
}
return isMsgContains;
}
#AfterSuite()
public void afterTest() {
try {
api.close();
} catch (Exception e) {
api.End();
e.printStackTrace();
}
}
}
I would also like to add that writing tests to read and verify the Toast messages in this way is not very much reliable as in one of my tests this code successfully captures the Toast message while in another test it fails to capture the toast message because the capturing of the screenshots starts when the toast message disappears. That was the reason I tried to write this code very much efficiently. However that also does not serve the purpose.
Follow this discussion on Appium forum: https://discuss.appium.io/t/verifying-toast/3676.
Basic steps to verify a Toaster are:
Perform action to trigger the toast message to appear on screen
Take x number of screenshots
Increase resolutions of all screenshots
Use tessearct OCR to detect the toast message.
Refer this repo to use Java OCR library (see at the bottom):
import org.bytedeco.javacpp.*;
import static org.bytedeco.javacpp.lept.*;
import static org.bytedeco.javacpp.tesseract.*;
public class BasicExample {
public static void main(String[] args) {
BytePointer outText;
TessBaseAPI api = new TessBaseAPI();
// Initialize tesseract-ocr with English, without specifying tessdata path
if (api.Init(null, "eng") != 0) {
System.err.println("Could not initialize tesseract.");
System.exit(1);
}
// Open input image with leptonica library
PIX image = pixRead(args.length > 0 ? args[0] : "/usr/src/tesseract/testing/phototest.tif");
api.SetImage(image);
// Get OCR result
outText = api.GetUTF8Text();
System.out.println("OCR output:\n" + outText.getString());
// Destroy used object and release memory
api.End();
outText.deallocate();
pixDestroy(image);
}
}

Freetts is not working with external speakers

I have used Freetts.jar file in my java application that announces the token number. My application is working perfectly in my laptop but is not working in my desktop that has an external speaker. I get a null pointer exception. NOTE: I use Windows 7 in both my computers.
The Below Code is the Sample Format I used.
package tsapp;
import java.util.Locale;
import javax.speech.Central;
import javax.speech.synthesis.Synthesizer;
import javax.speech.synthesis.SynthesizerModeDesc;
import javax.swing.JOptionPane;
public class TextSpeech {
public static void main(String[] args){
try
{
System.setProperty("freetts.voices",
"com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory");
Central.registerEngineCentral
("com.sun.speech.freetts.jsapi.FreeTTSEngineCentral");
Synthesizer synthesizer =
Central.createSynthesizer(new SynthesizerModeDesc(Locale.US));
synthesizer.allocate();
synthesizer.resume();
String str;
str=JOptionPane.showInputDialog(null,"Voice Check");
if(str==null)
return;
synthesizer.speakPlainText(str, null);
synthesizer.waitEngineState(Synthesizer.QUEUE_EMPTY);
synthesizer.deallocate();
}
catch(Exception e)
{
System.out.println(e.getClass());
e.printStackTrace();
}
}
}
Can we do one simple thing:
Download binary https://netix.dl.sourceforge.net/project/freetts/FreeTTS/FreeTTS%201.2.2/freetts-1.2.2-bin.zip
Add to your project
Write simple code.
Like this
import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;
public class TestVoice {
public static void main(String[] args) {
String text = "Voice check!";
Voice voice;
VoiceManager voiceManager = VoiceManager.getInstance();
voice = voiceManager.getVoice("kevin");
voice.allocate();
voice.speak(text);
}
}
Just be sure that all these libs are on your desktop too.

How to remove java apis from Nashorn-engine?

Is it possible to hide or remove java api's from nashorn-engine?
So that it could only see or use "default" ECMAScript 262 Edition 5.1 with some especially exposed functions / variables?
I would like to let my endusers create some specific logic for their own without worrying they could hack the whole system. Of course there might be some security holes in the nashorn engine etc. but that is the different topic.
Edit: Sorry I forgot to mention that I am running nashorn inside my java application, so no commandline parameters can be used.
Programmatically, you can also directly use the NashornScriptEngineFactory class which has an appropriate getScriptEngine() method:
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
...
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
...
ScriptEngine engine = factory.getScriptEngine("-strict", "--no-java", "--no-syntax-extensions");
OK, here is sample class with some limiting arguments:
package com.pasuna;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
public class ScriptTest {
public static class Logger {
public void log(String message) {
System.out.println(message);
}
}
public static class Dice {
private Random random = new Random();
public int D6() {
return random.nextInt(6) + 1;
}
}
public static void main(String[] args) {
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine(new String[]{"-strict", "--no-java", "--no-syntax-extensions"});
//note final, does not work.
final Dice dice = new Dice();
final Logger logger = new Logger();
engine.put("dice", dice);
engine.put("log", logger);
engine.put("hello", "world");
try {
engine.eval("log.log(hello);");
engine.eval("log.log(Object.keys(this));");
engine.eval("log.log(dice.D6());"
+ "log.log(dice.D6());"
+ "log.log(dice.D6());");
engine.eval("log.log(Object.keys(this));");
engine.eval("Coffee"); //boom as should
engine.eval("Java"); //erm? shoud boom?
engine.eval("log = 1;"); //override final, boom, nope
engine.eval("log.log(hello);"); //boom
} catch (final ScriptException ex) {
ex.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = "";
do {
try {
input = br.readLine();
engine.eval(input);
} catch (final ScriptException | IOException se) {
se.printStackTrace();
}
} while (!input.trim().equals("quit"));
try {
engine.eval("var add = function(first, second){return first + second;};");
Invocable invocable = (Invocable) engine;
Object result = invocable.invokeFunction("add", 1, 2);
System.out.println(result);
} catch (final NoSuchMethodException | ScriptException se) {
se.printStackTrace();
}
Object l = engine.get("log");
System.out.println(l == logger);
}
}
more info about flags can be found from here: http://hg.openjdk.java.net/jdk8/jdk8/nashorn/rev/eb7b8340ce3a
(imho atm the nashorn documentation is poor)
You can specify any jjs option for script engines via -Dnashorn.args option when you launch your java program. For example:
java -Dnashorn.args=--no-java Main
where Main uses javax.script API with nashorn engine.
You can run "jjs" tool with --no-java option to prevent any explicit Java package/class access from scripts. That said Nashorn platform is secure and uses Java standard URL codebase based security model ('eval'-ed script without known URL origin is treated like untrusted, unsigned code and so gets only sandbox permissions.
--no-java is the main flag to turn off java extensions. --no-syntax-extensions turns off non-standard extensions.

Categories

Resources