"java:comp/env/jdbc/MY_SQL_DS" or "MY_SQL_DS" or what else to reference the DataSource from within Java? - jndi

"java:comp/env/jdbc/MY_SQL_DS" does not work. I get a Naming Exception: NameNotFoundException. neither works "MY_SQL_DS" alone.name exception again.
I created another JNDI for a Mail Session named "MY_MailSession" and reference it like (javax.mail.Session) ctx.lookup( "MY_MailSession" ) which works...
what is the convention to refer the JDBC DataSource then?

I solved it the following way:
hope this helps others having the same issue/problem afterwards...
protected Connection getConnection() {
try {
if (connection == null || connection.isClosed()) {
if (dataSource == null) {
// impliziter Initial Context von WebLogic ApplicationServer Environment
java.util.Hashtable environment = new java.util.Hashtable();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
Context wlsic = new InitialContext(environment);
showJndiContext( wlsic, "", "");
// logischer JNDI Rootcontext der Serverkomponente, kann mehrfach verwendet werden
Context ctx = (Context) wlsic.lookup("java:comp/env");
showJndiContext( ctx, "", "");
// weiter mit Resourcenpfad
dataSource = (DataSource) ctx.lookup("MY_SQL_DS");
}
connection = dataSource.getConnection();
}
}
catch (NamingException ne) {
ne.printStackTrace();
log.error(ne);
}
catch (SQLException sqlEx) {
sqlEx.printStackTrace();
log.error(sqlEx.getMessage());
}
return connection;
}
public static void showJndiContext(Context ctx, String name, String space) {
if (null == name)
name = "";
if (null == space)
space = "";
try {
NamingEnumeration en = ctx.list(name);
while (en.hasMoreElements()) {
String delim = (null != name && 0 < name.length()) ? "/" : "";
NameClassPair nc = (NameClassPair) en.next();
System.out.println(space + name + delim + nc);
if (40 > space.length())
showJndiContext(ctx, nc.getName(), " " + space);
}
}
catch (javax.naming.NamingException ex) {
//System.out.println( ex );
}
}

Related

Selenium grid error : Session [(null externalkey)] not available and is not among the last 1000 terminated sessions

We are executing multiple test cases in selenium grid where hub is connected to 2 machines, but every time I am running the grid, I get an error.
Error creating a webdriver. Exception message:
Session [(null externalkey)] not available and is not among the last 1000 terminated sessions.
Active sessions are[]
Command duration or timeout: 0 milliseconds
Code:
private static List<WebDriver> m_listOfWebDrivers = Collections.synchronizedList(new ArrayList<WebDriver>());
private static ThreadLocal<WebDriver> m_driverForThread = new ThreadLocal<WebDriver>() {
#Override
protected WebDriver initialValue() {
WebDriver driver = null;
try {
driver = loadDesktopDriver();
} catch (Exception e) {
e.printStackTrace();
}
Log.info("Initializing Webdriver");
m_listOfWebDrivers.add(driver);
return driver;
}
};
protected static WebDriver loadDesktopDriver() throws Exception {
WebDriver driver = null;
Log.debug("Get Driver for Browser : " + m_browser);
try {
if (!m_runOnBrowserStack && null == m_browser) {
throw new IllegalArgumentException("Browser value should be provided for test");
}
driver = getNewDriver(m_browser, "", "", m_context);
**driver.manage().timeouts().implicitlyWait(50000, TimeUnit.MILLISECONDS);** /* this was added later, still didnt work*/
} catch (Exception e) {
Log.fatal("Error creating a webdriver. Exception message : " + e.getMessage());
throw e;
}
return driver;
}
public static WebDriver getNewDriver(String browserName, String browserVersion, String platform,
ITestContext context)
throws IOException, ComboBoxElementException, TextBoxElementException, ElementException, PageException {
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.ALL);
/**
* These capabilities will need to be re assigned according to the
* browser we are going to be launched. This is required in case of
* running on Grid only but keeping it same normal execution to avoid
* code redundancy.
*/
DesiredCapabilities desiredCapabilities = null;
if (m_runOnBrowserStack) {
desiredCapabilities = new DesiredCapabilities();
JSONObject envs = (JSONObject) m_bsConfig.get("environment");
String bsEnvironment = context.getCurrentXmlTest().getParameter("bsEnvironment");
String testName = context.getCurrentXmlTest().getName();
Log.info("Environmnet details for Test [" + testName + "] is : " + bsEnvironment);
if (null == bsEnvironment)
throw new PageException(
"Environment name does not present in XML or not passed from CLI : " + bsEnvironment);
Map<String, String> envCapabilities = (Map<String, String>) envs.get(bsEnvironment);
if (null == envCapabilities)
throw new PageException("Environment name does not present in Config file : " + bsEnvironment);
Iterator<Entry<String, String>> it = envCapabilities.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, ?> pair = (Map.Entry<String, ?>) it.next();
desiredCapabilities.setCapability(pair.getKey().toString(), pair.getValue().toString());
}
Map<String, String> commonCapabilities = (Map<String, String>) m_bsConfig.get("capabilities");
it = commonCapabilities.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, ?> pair = (Map.Entry<String, ?>) it.next();
if (desiredCapabilities.getCapability(pair.getKey().toString()) == null) {
desiredCapabilities.setCapability(pair.getKey().toString(), pair.getValue().toString());
}
}
browserName = (String) desiredCapabilities.getCapability("browser");
}
DriverSupportedBrowsers driverType = DriverSupportedBrowsers.valueOf(browserName.toUpperCase());
if (null != m_gridUrl && !m_gridUrl.isEmpty()) {
m_gridUrl += "/wd/hub";
}
switch (driverType) {
case CHROME:
String chromeDriverPath = driverHome + File.separator + FrameworkConstants.chromeDriverExeName;
if (m_runOnBrowserStack || CommonHelper.isFileExists(chromeDriverPath)) {
if (!m_runOnBrowserStack)
desiredCapabilities = DesiredCapabilities.chrome();
desiredCapabilities.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
options.addArguments("--disable-extensions");
// To start browser in private mode
// options.addArguments("incognito");
desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, options);
System.setProperty("webdriver.chrome.driver", chromeDriverPath);
if (null != m_gridUrl && !m_gridUrl.isEmpty()) {// for runs on
// grid
return new RemoteWebDriver(new URL(m_gridUrl), desiredCapabilities);
} else
return new RemoteWebDriver(service.getUrl(), desiredCapabilities); /* The code fails here generally with the failure*/
} else {
throw new FileNotFoundException(
"Chrome Driver path : " + chromeDriverPath + "\n\"" + FrameworkConstants.chromeDriverExeName
+ "\" not found in driver home path declared in System Environment Variable \""
+ driverHome + "\"");
}
#Parameters({ "bsEnvironment" })
#BeforeMethod(alwaysRun = true)
public void initialize(ITestContext context, Method method, #Optional String bsEnvironment)
throws IOException {
String customer = context.getCurrentXmlTest().getParameter("customer");
String testName = context.getCurrentXmlTest().getName();
setTestName(testName);
String methodName = "";
m_testMethod = method.getName();
methodName = testName + "_" + method.getName() + "_" + customer;
CommonHelper.renameRetryLog(m_logDir, methodName);
Log.setLog(m_logDir, methodName);
m_context = context;
if (m_runOnBrowserStack) {
if (null == context.getCurrentXmlTest().getParameter("bsEnvironment")
|| context.getCurrentXmlTest().getParameter("bsEnvironment").isEmpty()) {
Log.info("Adding bsEnvironment parameter for run on BrowserStack");
context.getCurrentXmlTest().addParameter("bsEnvironment", bsEnvironment);
}
}
try {
WebDriver driver = getDriverInstanceForThread();
if (null == driver)
throw new PageException("Driver is null. Initialization problem!!");
// Logging browser name and version parameters, driver and thread
// instances
String browserName = null;
String browserVersion = null;
try {
Capabilities webDriverCapablities = ((RemoteWebDriver) driver).getCapabilities();
browserName = webDriverCapablities.getBrowserName();
browserVersion = webDriverCapablities.getVersion();
} catch (ClassCastException e) {
Log.error("Unable to cast driver to RemoteWebdriver");
browserName = m_browser;
browserVersion = "NA";
}
Log.info("\n ****************** START OF TEST CASE " + method.getName() + " " + customer + ":"
+ browserName + ":" + browserVersion + "\t THREAD:" + Thread.currentThread().getId()
+ "\t WEBDRIVER:" + driver + " ****************** \n");
// driver.manage().timeouts().pageLoadTimeout(CommonConstants.PAGE_LOAD_WAIT_SEC,
// TimeUnit.SECONDS);
if (null != m_gridUrl) {
// Log the remote node ip address where the test is running
Log.info("Remote Node IP: " + CommonHelper.getIPOfRemoteNode(driver));
}
} catch (Exception e) {
e.printStackTrace();
Log.warn(e.getMessage());
}
The CMD is triggered for Node giving timeout and browser timeout:
java -Dwebdriver.chrome.driver=D:/imp/iTAF_Driver_Home/chromedriver.exe -jar selenium-server-standalone-3.3.1.jar -port 5554 -role node -hub http://10.18.15.168:5550/grid/register -timeout 86400 -browserTimeout 86000
This issue is a recurring error.

BlackBerry java.io.IOException: null

I am using following code for getting contents of a web page
String url = "http://abc.com/qrticket.asp?qrcode="
+ "2554";
try {
url += ";deviceside=true;interface=wifi;ConnectionTimeout=" + 50000;
HttpConnection connection = (HttpConnection) Connector.open(url,
Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.GET);
// connection.openDataOutputStream();
InputStream is = connection.openDataInputStream();
String res = "";
int chr;
while ((chr = is.read()) != -1) {
res += (char) chr;
}
is.close();
connection.close();
showDialog(parseData(res));
} catch (IOException ex) {
ex.printStackTrace();
showDialog("http: " + ex.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
showDialog("unknown: " + ex.getMessage());
}
public void showDialog(final String text) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(text);
}
});
}
public String parseData(String str) {
String[] data = split(str, "//");
StringBuffer builder = new StringBuffer();
for (int i = 0; i < data.length; i++) {
System.out.println("data:" + data[i]);
String[] vals = split(data[i], ">>");
if (vals.length > 1) {
System.out.println(vals[0]);
builder.append(vals[0].trim()).append(": ")
.append(vals[1].trim()).append("\n");
} else {
builder.delete(0, builder.toString().length()).append(
vals[0].trim());
break;
}
}
return builder.toString();
}
public String[] split(String splitStr, String delimiter) {
// some input validation
if (delimiter == null || delimiter.length() == 0) {
return new String[] { splitStr };
} else if (splitStr == null) {
return new String[0];
}
StringBuffer token = new StringBuffer();
Vector tokens = new Vector();
int delimLength = delimiter.length();
int index = 0;
for (int i = 0; i < splitStr.length();) {
String temp = "";
if (splitStr.length() > index + delimLength) {
temp = splitStr.substring(index, index + delimLength);
} else {
temp = splitStr.substring(index);
}
if (temp.equals(delimiter)) {
index += delimLength;
i += delimLength;
if (token.length() > 0) {
tokens.addElement(token.toString());
}
token.setLength(0);
continue;
} else {
token.append(splitStr.charAt(i));
}
i++;
index++;
}
// don't forget the "tail"...
if (token.length() > 0) {
tokens.addElement(token.toString());
}
// convert the vector into an array
String[] splitArray = new String[tokens.size()];
for (int i = 0; i > splitArray.length; i++) {
splitArray[i] = (String) tokens.elementAt(i);
}
return splitArray;
}
This is working absolutely fine in simulator but giving 'http:null' (IOException) on device, I dont know why??
How to solve this problem?
Thanks in advance
I think the problem might be the extra connection suffixes you're trying to add to your URL.
http://abc.com/qrticket.asp?qrcode=2554;deviceside=true;interface=wifi;ConnectionTimeout=50000
According to this BlackBerry document, the ConnectionTimeout parameter isn't available for Wifi connections.
Also, I think that if you're using Wifi, your suffix should simply be ";interface=wifi".
Take a look at this blog post on making connections on BlackBerry Java, pre OS 5.0. If you only have to support OS 5.0+, I would recommend using the ConnectionFactory class.
So, I would try this with the url:
http://abc.com/qrticket.asp?qrcode=2554;interface=wifi
Note: it's not clear to me whether your extra connection parameters are just ignored, or are actually a problem. But, since you did get an IOException on that line, I would try removing them.
The problem was that no activation of blackberry internet service. After subscription problem is solved.
Thanks alto all of you especially #Nate

Display HTTP Request Information - BlackBerry

How can I get the all HTTP request headers, method, the suffix of the connection, and all parameters that I added to the request?
Try something like this (I ran this code on a background thread, which I why I use UiApplication.invokeLater() to display results):
try {
ConnectionFactory factory = new ConnectionFactory(); // for OS 5.0+
factory.setPreferredTransportTypes(new int[] {
TransportInfo.TRANSPORT_TCP_WIFI,
TransportInfo.TRANSPORT_TCP_CELLULAR
});
// For OS < 5.0
//HttpConnection conn = (HttpConnection) Connector.open("http://www.google.com;interface=wifi");
HttpConnection conn = (HttpConnection) factory.getConnection("http://www.google.com").getConnection();
conn.setRequestProperty("sessionId", "ABCDEF0123456789");
final StringBuffer results = new StringBuffer();
String key = "";
int index = 0;
// loop over all the header fields, and record their values
while (key != null) {
key = conn.getHeaderFieldKey(index);
if (key != null) {
String value = conn.getHeaderField(key);
results.append(key + " = " + value + "\n\n");
}
index++;
}
results.append("method = " + conn.getRequestMethod() + "\n\n");
// we (should) know which request properties we've set, so we ask
// for them by name here
String sessionId = conn.getRequestProperty("sessionId");
results.append("sessionId = " + sessionId + "\n\n");
String url = conn.getURL();
results.append("URL = " + url);
// show the result on screen (UI thread)
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
textField.setText(results.toString());
}
});
} catch (IOException e) {
e.printStackTrace();
}

blackberry app not running on gprs connection in device

Hi am trying to run my app on blackberry device using Edge gprs connection but its not rendering the pages.i have tried lot to get the connection,also i tried the various links to solve, one of the simple code i have attached here, kindly guide me to solve this
public static String getConnectionString() {
String value="" ;
if(WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
value=";interface=wifi";
}else{
value=";deviceside=true";
}
return value;
}
Append the connection string to your url. Then try
public static String getConnectionString() {
// This code is based on the connection code developed by Mike Nelson of
// AccelGolf.
// http://blog.accelgolf.com/2009/05/22/blackberry-cross-carrier-and-cross-network-http-connection
String connectionString = null;
// Simulator behavior is controlled by the USE_MDS_IN_SIMULATOR
// variable.
if (DeviceInfo.isSimulator()) {
connectionString = ";deviceSide=true";
}
// Wifi is the preferred transmission method
else if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
// System.out.println("Device is connected via Wifi.");
connectionString = ";interface=wifi";
}
// Is the carrier network the only way to connect?
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// System.out.println("Carrier coverage.---->>" + CoverageInfo.getCoverageStatus());
String carrierUid = getCarrierBIBSUid();
// DebugScreen.Log(" carrierUid is: " + carrierUid);
if (carrierUid == null) {
// Has carrier coverage, but not BIBS. So use the carrier's TCP
// network
// System.out.println("No Uid");
String wapString = getAvailableConnectionsString();
// DebugScreen.Log("from wap2 connection--->" + wapString);
if(wapString == null){
connectionString = ";deviceside=true";
}else{
connectionString = wapString;
}
} else {
// otherwise, use the Uid to construct a valid carrier BIBS
// request
connectionString = ";deviceside=true;connectionUID=" + carrierUid + ";ConnectionType=mds-public";
}
}
// Check for an MDS connection instead (BlackBerry Enterprise Server)
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
// System.out.println("MDS coverage found");
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid bugging the user
// unnecssarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
// System.out.println("There is no available connection.");
}
// In theory, all bases are covered so this shouldn't be reachable.
else {
// System.out.println("no other options found, assuming device.");
connectionString = ";deviceside=true";
}
return connectionString;
}
Add this method and append connection String to url.
private static String getCarrierBIBSUid() {
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
// DebugScreen.Log("Util.getCarrierBIBSUid() for ippp--------->>" + records[currentRecord].getCid().toLowerCase());
if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
// DebugScreen.Log("Util.getCarrierBIBSUid() for bibs..........'''''" + records[currentRecord].getName().toLowerCase().indexOf("bibs") );
if (records[currentRecord].getName().toLowerCase().indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
return null;
}
public static String getAvailableConnectionsString() {
String conns = null;
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.getRecords();
String cid;
String uid;
for (int i = 0; i < records.length; i++) {
ServiceRecord myRecord = records[i];
// System.out.println("record name:"+myRecord.getName()+" cid:"+myRecord.getCid().toLowerCase()+" "+myRecord.getUid().toLowerCase());
if (myRecord.isValid() && !myRecord.isDisabled()) {
cid = myRecord.getCid().toLowerCase();
uid = myRecord.getUid().toLowerCase();
//Wap2.0
if (cid.indexOf("wptcp") != -1 && uid.indexOf("wifi") == -1 && uid.indexOf("mms") == -1 ) {
conns = ";deviceside=true" + ";ConnectionUID="+ myRecord.getUid();
if(myRecord.getUid().equalsIgnoreCase("GTCP BIBS")){
return conns;
}
}
}
}
return conns;
}
This code is work for me..

What is correct way to implement the HTTPConnection in Blackberry

I tired to connect my app with the remote server and pass few credentials to it, but i am always getting a same response from the server. I tried changing all the parameter value and other request header values that i am passing, but still i can't reach the exact solution. I need to you, whether am i using the correct way to ping with the server and to pass the values.
Below is the code that i am using , Please let me know if i have gone wrong somewhere.
// HttpServiceConnection.java
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.HttpsConnection;
import net.rim.device.api.system.DeviceInfo;
import com.beacon.bb.app.util.WSMConfig;
/**
* #author N********
*
*/
public class HttpServiceCommunication {
public HttpServiceCommunication() {
System.out.println("Http Service Communication Called");
}
public String sendHttpPost(String uri, String email, String uid,
String pass) throws Exception { // Hashtable header
String response = null;
// create the connection...
System.out.println("Url    " + uri);
HttpConnection _connection = null;
String params = null;
if (DeviceInfo.isSimulator()) {
params = ";deviceside=false";
} else {
params = ";deviceside=true;interface=wifi";
}
String URL = uri + params;
System.out.println("Connecting to Http Connection ");
try {
_connection = (HttpConnection) Connector.open(URL);
} catch(Exception e){
e.printStackTrace();
}
if (_connection != null) {
_connection.setRequestMethod(HttpConnection.POST);
System.out.println("After Request Method ");
_connection.setRequestProperty("User-Agent",
"Profile/MIDP-2.0 Configuration/CLDC-1.1");
_connection.setRequestProperty("Content-Language", "en-US");
_connection.setRequestProperty("Content-type", "application/json");
// setting header if any
// if (header != null) {
// for (Enumeration en = header.keys(); en.hasMoreElements();) {
// String key = (String) en.nextElement();
// String value = (String) header.get(key);
// _connection.setRequestProperty(key, value);
_connection.setRequestProperty("email", email);
//_connection.setRequestProperty("method","login");
_connection.setRequestProperty("uid", uid);
_connection.setRequestProperty("password", pass);
//_connection.setRequestProperty("uid", uid);
// }
// }
System.out.println("Open Output Stream  ");
// System.out.println("Data is     "+data);
OutputStream _outputStream = _connection.openOutputStream();
//System.out.println("Writing data  ");
//_outputStream.write(data);
// _outputStream.flush(); // Optional, getResponseCode will flush
// Getting the response code will open the connection, send the
// request, and read the HTTP response headers.
// The headers are stored until requested.
try {
System.out.println("Response Code :" + _connection.getResponseCode());
int rc = _connection.getResponseCode();
System.out.println("Response Code :" + rc);
System.out.println("Response Code   :" + rc + " if HTTP OK    :"
+ (rc == HttpConnection.HTTP_OK));
if (rc == HttpConnection.HTTP_FORBIDDEN) {
System.out.println("FORBIDDEN");
response = WSMConfig.NOT_AUTH;
} else if (rc != HttpConnection.HTTP_OK) {
response = WSMConfig.NOT_OK;
} else if (rc == HttpConnection.HTTP_OK) {
InputStream _inputStream = _connection.openInputStream();
final int MAX_LENGTH = 128;
byte[] buf = new byte[MAX_LENGTH];
int total = 0;
while (total < MAX_LENGTH) {
int count = _inputStream.read(buf, total, MAX_LENGTH
- total);
if (count < 0) {
break;
}
total += count;
}
response = new String(buf, 0, total);
//ByteBuffer bb = new ByteBuffer(_inputStream);
//response = bb.getString();
System.out.println("Response from Server   :" + response);
// close everything out
{
if (_inputStream != null)
try {
_inputStream.close();
} catch (Exception e) {
}
if (_outputStream != null)
try {
_outputStream.close();
} catch (Exception e) {
}
if (_connection != null)
try {
_connection.close();
} catch (Exception e) {
}
}
}
else {
response = WSMConfig.SERVER_ERROR;
}
}catch(Exception e){
e.printStackTrace();
}
}
//System.out.println("Response :" + response);
return response;
}
}
I am getting a response like {"code":0,"err":"Missing 'method'."}
Any Help is Appreciable....
Thanks
Try this out when you're wanting to pass data to the server:
//encode your data to send
URLEncodedPostData encoder = new URLEncodedPostData(null, false);
encoder.encode("email", email);
encoder.encode("method", "login");
encoder.encode("uid", uid);
encoder.encode("password", pass);
//Now you open up an output stream to write to the connection
OutputStream os = _connection.openOutputStream();
os.write(encoder.getBytes();
os.flush();
And then continue with the rest of your logic

Resources