CachedRowSet always returns empty - try-with-resources

public CachedRowSet execute(String asql) throws ServiceUnavailableException {
try (Connection connection = getDatabaseConnection();
Statement statement = connection.createStatement();) {
try (ResultSet resultSet = statement.executeQuery(asql);
CachedRowSet rowset = CachedRowSetFactory.getCachedRowSet()) {
rowset.populate(resultSet);
return rowset;
}
} catch (SQLException se) {
throw new ServiceUnavailableException("Database broken " + se);
} catch (Exception ne) {
throw new ServiceUnavailableException("JNDI Lookup broken ");
}
return null;
}
Hi everyone. I have a sample code as above. The problem is that returned rowset is always empty, even though there are lots of data in database.
Any suggestions? Thank you.

Related

(log) File watching with citrus-framework

Is there a way and/or what are best practices to watch log files from the System Under Test?
My requirement is to validate presence/absence of log entries according known patterns produced by the SUT.
Thank you very much!
Well, I don't think there is a Citrus tool specifically designed for that. But I think that is a really good idea. You could open an issue and ask for this feature.
Meanwhile, here is a solution that we have used in one of our projects to check if the applicaiton log contained specific strings that were generated by our test.
sleep(2000),
echo("Searching the log..."),
new AbstractTestAction() {
#Override
public void doExecute(TestContext context) {
try {
String logfile = FileUtils.getFileContentAsString(Paths.get("target", "my-super-service.log").toAbsolutePath().normalize());
if (!logfile.contains("ExpectedException: ... | Details: BOOM!.")) {
throw new RuntimeException("Missing exceptions in log");
}
} catch (IOException e) {
throw new RuntimeException("Unable to get log");
}
}
}
OR you can replace that simple contains with a more elegant solution:
String grepResult = grepForLine(LOGFILE_PATH, ".*: SupermanMissingException.*");
if (grepResult == null) {
throw new RuntimeException("Expected error log entry not found");
}
The function goes over each line searching for a match to the regex supplied.
public String grepForLine(Path path, String regex) {
Pattern regexp = Pattern.compile(regex);
Matcher matcher = regexp.matcher("");
String msg = null;
try (
BufferedReader reader = Files.newBufferedReader(path, Charset.defaultCharset());
LineNumberReader lineReader = new LineNumberReader(reader)
) {
String line;
while ((line = lineReader.readLine()) != null) {
matcher.reset(line); //reset the input
if (matcher.find()) {
msg = "Line " + lineReader.getLineNumber() + " contains the error log: " + line;
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return msg;
}

Junit testing for database conection

Is there a way to test below code.Here I am connecting to database with JNDI.I am new to mockito and not getting a way to test the same.
#SuppressWarnings("unused")
public Connection getJNDIConnection() {
Connection result = null;
try {
InitialContext initialContext = new InitialContext();
if (initialContext == null) {
LOGGER.info("JNDI problem. Cannot get InitialContext.");
}
DataSource datasource = (DataSource) initialContext.lookup(jndiName);
if (datasource != null) {
result = datasource.getConnection();
} else {
LOGGER.info("Failed to lookup datasource.");
}
} catch (NamingException ex) {
LOGGER.error("Cannot get connection: " + ex);
} catch (SQLException ex) {
LOGGER.error("Cannot get connection: " + ex);
}
return result;
}
Of course, you can to do it, but I think you should read the documentation yourself. The main points here is:
InitialContext initialContext = mock(InitialContext.class);
DataSource dataSource = mock(DataSource.class);
Connection expected = mock(Connection.class);
whenNew(InitialContext.class).withNoArguments().thenReturn(initialContext);
when(initialContext.lookup(jndiName)).thenReturn(dataSource);
when(initialContext.getConnection()).thenReturn(connection);
Connection result = intatnceOfCalss.getJNDIConnection();
assertSame("Should be equals", expected, result);
Also you should use PowerMock to mock constructors and static methods. To have deal with Logger, just add this code:
#BeforeClass
public static void setUpClass() {
mockStatic(LoggerFactory.class);
Logger logger = mock(Logger.class);
when(LoggerFactory.getLogger(ApplySqlFileIfExistsChange.class)).thenReturn(logger);
}
Don't forget about annotations:
#RunWith(PowerMockRunner.class)
#PrepareForTest({LoggerFactory.class})
Try to read this doc http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html

Returning empty IQueryable<>

I have this method that tries to get a list of things:
private static IQueryable<Thing> GetThings(int thingsType)
{
try
{
return from thing in entities.thing.Include("thingStuff")
select thing;
}
catch (Exception exception)
{
return new EnumerableQuery<Thing>(?????);
}
}
}
I want to return an empty IQueryable if I can't for whatever reason get the query to run. I don't want to return NULL because that could break the calling code. Is it possible or am I going totally wrong about this?
These answers are good and do work, however I have always felt using Empty and not creating a new List is cleaner:
Enumerable.Empty<Thing>().AsQueryable();
Try the following:
private static IQueryable<Thing> GetThings(int thingsType)
{
IQueryable<Thing> things = new List<Thing>().AsQueryable();
try
{
things = from thing in entities.thing.Include("thingStuff")
select thing;
return things;
}
catch (Exception exception)
{
return things;
}
}
I would add block finally {} and put my return type in that code.
This will take care of the issue by returning the type that your application expects.
private static IQueryable<T> GetThings(int thingsType)
{
IQueryable<T> list = new List<Thing>().AsQueryable();
try
{
list = from thing in entities.thing.Include("thingStuff")
select t;
}
catch (Exception exception)
{
// handle exception here;
}
finally {
return list;
}
}
}
Returning empty IQueryable<>
DbSet.Take(0)
I think this would be tidier:
private static IQueryable<T> GetThings(int thingsType)
{
try
{
return from thing in entities.thing.Include("thingStuff")
select t;
}
catch (Exception exception)
{
// Exception handling code goes here
return new List<Thing>().AsQueryable();
}
}

A network related error or instance-specific error occured while establishing a connection to sql server

This is the error which arises when I tried to debug an application under Visual C# 2010
I write that code to retrieve some rows from a database table, I already attached the two well known databases Pubs and Northwind to the db explorer, but the error remains
class Author
{
SqlConnection _pubConnection;
string _connString;
public Author()
{
_connString = "Data Source=./INSTANCE2;Initial Catalog=pubs;Integrated Security=True";
_pubConnection = new SqlConnection();
_pubConnection.ConnectionString = _connString;
}
public int CountAuthors()
{
try
{
SqlCommand pubCommand = new SqlCommand();
pubCommand.Connection = _pubConnection;
pubCommand.CommandText = "Select Count(au_id) from authors";
_pubConnection.Open();
return (int)pubCommand.ExecuteScalar();
}
catch (SqlException ex)
{
throw ex;
}
finally
{
if (_pubConnection != null)
{
_pubConnection.Close();
}
}
}
}
static void Main(string[] args)
{
try
{
Author author = new Author();
Console.WriteLine(author.CountAuthors());
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
the Connection string isn't ok , i correct it and it works fine

Problem in getting attributes from webservice to servlet when the return type of operation in webservice is STRING []

I made a Webservice Operation whose return type is STRING []
Following is the code
#WebMethod(operationName = "authorize")
public String [] authorize(#WebParam(name = "Username")
String Username) {
CAuthorization CA = new CAuthorization();
String [] Result= null;
try {
Result = CA.CheckAuthorization(Username);
} catch (SQLException ex) {
Logger.getLogger(WS_Authentication.class.getName()).log(Level.SEVERE, null, ex);
}
**return Result;**
}
And then i made a Servlet
The code of the servlet thing is :
try { // Call Web Service Operation
java.lang.String result = null;
result = port.authorize(Username);
out.println("Result = "+result);
} catch (Exception ex) {
// TODO handle custom exceptions here
}
Problem is in my WEbservice Code in RETURN STATEMENT i have attributes of any table
and i want to take these attributes to servlet so that i can see them on my front end
but what im getting here is the only the LAST ATTRIBUTE
Thanks!
This is the way u can handle Webservice Operation of String Return type
#WebMethod(operationName = "authorize")
public String authorize(#WebParam(name = "Username")
String Username) {
CAuthorization CA = new CAuthorization();
StringBuffer result = new StringBuffer();
try {
if (CA.CheckAuthorization(Username).length > 0) {
result.append(CA.CheckAuthorization(Username)[0]);
for (int i = 1; i < CA.CheckAuthorization(Username).length; i++) {
result.append(",");
result.append(CA.CheckAuthorization(Username)[i]);
}
}
} catch (SQLException ex) {
Logger.getLogger(WS_Authentication.class.getName()).log(Level.SEVERE, null, ex);
}
//TODO write your implementation code here:
return result.toString();
}
}