org.apache.catalina.ServerFactory.getServer() equivalent in Tomcat 7 - tomcat7

What is the equivalent of org.apache.catalina.ServerFactory.getServer() in Tomcat 7 or what would be the best way to retrieve org.apache.catalina.Session instances ?
Here is a sample code that used to work on Tomcat 6.0:
public List<org.apache.catalina.Session> findActiveSessions() throws ServiceException {
StandardEngine engine = (StandardEngine) ServerFactory.getServer().findService("Catalina").getContainer();
StandardContext context = (StandardContext) engine.findChild(engine.getDefaultHost())
.findChild(ServletActionContext.getServletContext().getContextPath());
List<org.apache.catalina.Session> list = new ArrayList<org.apache.catalina.Session>();
for (org.apache.catalina.Session session : context.getManager().findSessions()) {
list.add(session);
}
return list;
}

You can look it up via its management registration..
import javax.management.*;
import org.apache.catalina.Server;
MBeanServer mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0);
ObjectName name = new ObjectName("Catalina", "type", "Server");
Server server = (Server) mBeanServer.getAttribute(name, "managedResource");
Obviously that code is devoid of error checking but is functional.

Related

Error Login failed for user ''.' when i try to connect through azure active directory interceptor in my solution

I am implementing the Azure active directory interceptor to connect my solution through active directory. My username is already added in the azure database and I am using below class as interceptor with like below.
public class AadAuthenticationDbConnectionInterceptor : DbConnectionInterceptor
{
public override InterceptionResult ConnectionOpening();
public override async Task<InterceptionResult> ConnectionOpeningAsync();
}
Its connecting fine through SSMS with the account but when I connect through my solution in visual studio it gives me below error:
Microsoft.Data.SqlClient.SqlException: 'Login failed for user ''.'
Help will be appreciated.
You need to use Azure Identity:
var resourceScope = "https://database.windows.net/.default";
var tokenCredential = new DefaultAzureCredential();
var accessToken = tokenCredential.GetToken(
new TokenRequestContext(scopes: new string[] { resourceScope }) { }
);
using (var connection = new SqlConnection($"Server={dbserver};Initial Catalog={db};Encrypt=True;TrustServerCertificate=True"))
{
connection.AccessToken = accessToken.Token;
connection.Open();
}

Windows Application Driver, error "Could not find any recognizable digits." when connecting to session (driver)

I know how to launch a windows application using the filepath to launch it and that works (working example below). I am writing tests and they work too but my question is this: If the application is running already, how do I create my "session" (often called "driver") for the currently running application?
I have read this article that explains how you would connect a new session to Cortana which is already running. It's a great example but my app is an exe that has been launched and is not part of windows and I'm getting the error "Could not find any recognizable digits.".
What am I doing wrong?
WORKING CODE THAT LAUNCHES THE APP AND CREATES THE "session":
private const string WindowsApplicationDriverUrl = "http://127.0.0.1:4723";
protected static WindowsDriver<RemoteWebElement> session;
public static void Setup(TestContext context)
{
// Launch app and populate session
if (session == null)
{
// Create a new sessio
DesiredCapabilities appCapabilities = new DesiredCapabilities();
appCapabilities.SetCapability("app", filepath /*The exeecutable's filepath on c drive*/);
//LaunchWPF app and wpf session
session = new WindowsDriver<RemoteWebElement>(new Uri(WindowsApplicationDriverUrl), appCapabilities);
session.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
}
}
PROBLEM CODE :
[TestMethod()]
public void Common_CreateSession_ForAlreadyRunningmyApp()
{
string WindowsApplicationDriverUrl = "http://127.0.0.1:4723";
IntPtr myAppTopLevelWindowHandle = new IntPtr();
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.Contains("MyApp.Client.Shell"))
{
myAppTopLevelWindowHandle = clsProcess.Handle;
}
}
DesiredCapabilities appCapabilities = new DesiredCapabilities();
appCapabilities.SetCapability("appTopLevelWindow", myAppTopLevelWindowHandle);
//Create session for app that's already running (THIS LINE FAILS, ERROR: : 'Could not find any recognizable digits.')
session = new WindowsDriver<RemoteWebElement>(new Uri(WindowsApplicationDriverUrl), appCapabilities);
session.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
}
}
There's now an answer on github here. You can see on github I have made 3 tweaks to the answer given by moonkey124, 2 of them were obvious (my aplication name and a little sleep command), 1 of them was to adapt the answer to a WPF application under test...

Jmeter does not see the variables when trying to connect to the database

I have the following problem.
When you try to create a connection can not find variables.
The test has the following set of actions
Download the local settings file (put in props)
Create a database connection (This happens all in different groups, i tried in the same)
Use next code for upload local property file(Bean Shell, Thread Group 1)
FileInputStream is = new FileInputStream(new File("d:/somefolder/somefile.properties"));
props.load(is);
is.close();
Before creating the connection I checked the availability of variables(Bean Shell, Thread Group 2)
System.out.println(props.get("db.url"));
System.out.println(${__P("db.url")});
${__setProperty("db.url", props.get("db.url"))};
System.out.println(${__P("db.url")});
OutPut
correct connection url
1(Because function __P return default value if variable undefined,
default value = 1)
correct connection url
Create Jdbc Connection with next parametrs(Thread Group 2)
url: ${__P("db.url")}
Test Failure because ${__P("db.url")} return 1
If i use ${__BeanShell(props.get(db.url))}
Test Failure because props.get(db.url) return nothing
If i use ${__javaScript(props.get(db.url))}
Test Failure because props.get(db.url) return nothing
"Component jdbc connection configuration" initialized before started first Thread Group, so component don't see variables because he don't initialize.
Create Script for connecting to db
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSetMetaData;
ResultSet clientConfigs = null;
ResultSet gameIds = null;
Connection connect = null;
Statement statement = null;
try {
Class.forName(props.get("configdb.driverClassName"));
String connectionUrl = props.get("configdb.url") + "?user=" + props.get("configdb.username") + "&password=" + props.get("configdb.password");
connect = DriverManager.getConnection(connectionUrl);
statement = connect.createStatement();
clientConfigs = statement.executeQuery("Select keyname,valuestr from client_config WHERE valuestr Like '%/_ah/api/%'");
ResultSetMetaData ccMetaData = clientConfigs.getMetaData();
int clientConfigsColumns = ccMetaData.getColumnCount();
ArrayList clientConfigsList = new ArrayList(20);
while (clientConfigs.next()){
HashMap clientConfigsRow = new HashMap(clientConfigsColumns);
for(int i=1; i<=clientConfigsColumns; ++i){
clientConfigsRow.put(ccMetaData.getColumnName(i), clientConfigs.getObject(i));
}
clientConfigsList.add(clientConfigsRow);
}
vars.putObject("clientConfigs", clientConfigsList);
gameIds = statement.executeQuery("Select gameId from game_config");
ResultSetMetaData giMetaData = gameIds.getMetaData();
int gameIdsColumns = giMetaData.getColumnCount();
ArrayList gameIdsList = new ArrayList(50);
while (gameIds.next()){
HashMap gameIdsRow = new HashMap(gameIdsColumns);
for(int i=1; i<=gameIdsColumns; ++i){
gameIdsRow.put(giMetaData.getColumnName(i), gameIds.getObject(i));
}
gameIdsList.add(gameIdsRow);
}
vars.putObject("gameIds", gameIdsList);
}
catch (Exception e) {
throw e;
} finally {
try {
if (clientConfigs != null) {
clientConfigs.close();
}
if (gameIds != null) {
gameIds.close();
}
if (statement != null) {
statement.close();
}
if (connect != null) {
connect.close();
}
} catch (Exception e) {
}
}
Apparently JMeter loads JDBC configuration parameters at really early, likely at UI load. See discussion here
The JDBC Config element is only processed at test startup, so it is
not possible to change the values once a test has started - i.e. you
could not change the values for different loops of the test plan. The
test plan has to know the JDBC settings near the start.
Which means, if you change value of property in threadGroup-1 at runtime, the changes will not take effect in JDBC config.
One possible way around this is to set the property from the command line while starting JMeter.
Alternatively drop JDBC sampler entirely and use one of the custom samplers to interact with your JDBC data source.

Unable to connect to HP Quality Center using Com4j

OTAClient.dll version 10.0.0.2532
The following is the code I have used to connect to qc, apply filter and fetch qcpath and a field data. It is working fine with java 32 bit version 1.7.
import com.oracle.qcTasks.ClassFactory;
import com.oracle.qcTasks.IList;
import com.oracle.qcTasks.ISubjectNode;
import com.oracle.qcTasks.ITDConnection;
import com.oracle.qcTasks.ITDFilter;
import com.oracle.qcTasks.ITest;
import com.oracle.qcTasks.ITestFactory;
import com4j.Com4jObject;
public class qcClient {
public static void main(String[] args) {
ITest qcTestCase;
ISubjectNode qcTestCasePath;
Com4jObject SubjectField;
//QC url
String url = "http://fusionqc.us.oracle.com/";
//username for login
String username = "username";
//password for login
String password = "";
//domain
String domain = "domain";
//project
String project = "project";
ITDConnection itdc = ClassFactory.createTDConnection();
itdc.initConnectionEx(url);
itdc.connectProjectEx(domain, project, username, password);
boolean flag = itdc.connected();
System.out.println(itdc.projectName());
ITestFactory qcTestFactory = itdc.testFactory().queryInterface(ITestFactory.class);
ITDFilter qcFilter=qcTestFactory.filter().queryInterface(ITDFilter.class);
String query="^Subject\\path^";
qcFilter.clear();
qcFilter.filter("TS_SUBJECT", query);
IList qcTestList = qcFilter.newList();
for (Com4jObject com4jObject : qcTestList) {
qcTestCase = com4jObject.queryInterface(ITest.class);
System.out.println(qcTestCase.name());
System.out.println(qcTestCase.field("TS_USER_09"));
SubjectField = (Com4jObject)qcTestCase.field("TS_SUBJECT");
qcTestCasePath = SubjectField.queryInterface(ISubjectNode.class);
System.out.println(qcTestCasePath.path());
break;
}
System.out.println("command output :: "+flag);
System.out.println("OUT");
itdc.disconnectProject();
}
}
To the project requirement, I've downgraded the version of java to 64 bit version of 1.6. Post the downgrade, I'm receiving the following error.
Exception in thread "main" com4j.ExecutionException: com4j.ComException: 80040154 CoCreateInstance failed : Class not registered : .\com4j.cpp:153
at com4j.ComThread.execute(ComThread.java:203)
at com4j.Task.execute(Task.java:25)
at com4j.COM4J.createInstance(COM4J.java:97)
at com4j.COM4J.createInstance(COM4J.java:72)
at com.oracle.qcTasks.ClassFactory.createTDConnection(ClassFactory.java:16)
at com.oracle.qcCode.qcClient.main(qcClient.java:32)
Caused by: com4j.ComException: 80040154 CoCreateInstance failed : Class not registered : .\com4j.cpp:153
at com4j.Native.createInstance(Native Method)
at com4j.COM4J$CreateInstanceTask.call(COM4J.java:117)
at com4j.COM4J$CreateInstanceTask.call(COM4J.java:104)
at com4j.Task.invoke(Task.java:51)
at com4j.ComThread.run0(ComThread.java:153)
at com4j.ComThread.run(ComThread.java:134)
I've found similar threads but didn't found any particular solution for the same. Please help. Is there any impact wrt java versions
What version of com4j do you use? See this post for using com4j on a 64 bit Windows machine. Are there any COM objects you can use from your 64 bit environment?
According to this blog entry you will get a Class not Registered Exception when you try to access a 32 bit COM object in a 64 bit environment. It even contains a workaround using some registry hacks. Maybe it works?

"A registration already exists for URI" when using HttpSelfHostServer

We are having an issue unit test failing because previous tests haven't closed session of HttpSelfHostServer.
So the second time we try to open a connection to a sever we get this message:
System.InvalidOperationException : A registration already exists for URI 'http://localhost:1337/'.
This test forces the issue (as an example):
[TestFixture]
public class DuplicatHostIssue
{
public HttpSelfHostServer _server;
[Test]
public void please_work()
{
var config = new HttpSelfHostConfiguration("http://localhost:1337/");
_server = new HttpSelfHostServer(config);
_server.OpenAsync().Wait();
config = new HttpSelfHostConfiguration("http://localhost:1337/");
_server = new HttpSelfHostServer(config);
_server.OpenAsync().Wait();
}
}
So newing up a new instance of the server dosent seem to kill the previous session. Any idea how to force the desposal of the previous session?
Full exception if it helps?
System.AggregateException : One or more errors occurred. ----> System.InvalidOperationException : A registration already exists for URI 'http://localhost:1337/'.
at
System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken) at System.Threading.Tasks.Task.Wait()
at ANW.API.Tests.Acceptance.DuplicatHostIssue.please_work() in DuplicatHostIssue.cs: line 32
--InvalidOperationException
at System.Runtime.AsyncResult.End(IAsyncResult result)
at System.ServiceModel.Channels.CommunicationObject.EndOpen(IAsyncResult result)
at System.Web.Http.SelfHost.HttpSelfHostServer.OpenListenerComplete(IAsyncResult result)
You might want to write a Dispose method like below and call it appropriately to avoid this issue
private static void HttpSelfHostServerDispose()
{
if (server != null)
{
_server.CloseAsync().Wait();
_server.Dispose();
_server = null;
}
}
This will clear the URI register.

Resources