Start test body after jar file loading (from JAVA) is finished - multithreading

I want to write UNIT test with SOAP webservices. Webservices work in other jar file, which I try to load Runtime.getRuntime().exec(// java - jar ...). Loading jar file takes 2 min. When loading is in new Thread the test ends before loading jar file will be finished. If loading is in main thread, test is not finished. I try to listen HTTP response with while cycle, but when cycle is working, the jar file is not loading.
#Before
public void setUp() throws Exception {
// Get path of jar file
thread = new Thread() {
public void run() {
try {
Process process = Runtime.getRuntime().exec(path-to-java.exe -jar webservices.jar);
process.waitFor();
process.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
int responseCode;
do {
responseCode = getResponseCodeHTTP("http://localhost:8080/services");
} while (responseCode < 200 || responseCode >= 400);
System.out.println("Web services have loaded");
}
public int getResponseCodeHTTP(String urlToRead) throws IOException {
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
int result;
try {
conn.connect();
result = conn.getResponseCode();
} catch (ConnectException e){
return 500;
}
return result;
}

OK. I want to write test, which will start the webservices from jar file (loading process takes 1.5 min) and then execute test. To start web services I use Runtime.getRuntime().exec and to understand that them started I use HTTP response code. When the code [200-400) , it means the ws started OK.
I tried to debug code inside new Thread and added code with InputStreamReader and while cycle.
String line;
InputStream stdout = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));
while ((line = reader.readLine()) != null)
System.out.println("[Stdout] " + line);
And test successfully executed. The when I removed the while cycle with readline, the problem had repeated.
I have not understand yet why it worked.

Related

My app crashes when I try to send a request to the server

Well, it actually works pretty well on my android studio simulator but when I try to run it on my phone it just crashes.
I just want to send a number to the server and get a response with the data that I need to that number. so this is my code which do that:
thread = new Thread() {
#Override
public void run() {
//server stuff
try {
//Connecting
if(!userClass.equals("")) {
Log.i(debugString, "Attempting to connect to server");
socket = new Socket(hostname, portnumber);
Log.i(debugString, "Connection established!");
BufferedWriter bw = new BufferedWriter((new OutputStreamWriter(socket.getOutputStream())));
bw.write("" + userClass);
bw.newLine();
bw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
input = br.readLine();
}
} catch (IOException e) {
Log.e(debugString, e.getMessage());
} finally {
threadComplete = true;
}
}
};
thread.start();
while(!threadComplete)
continue;
then I just use this thread whenever I want to get the updated info for my request like that:
String getUserClass = userClass;
if(!getUserClass.equals(""))
{
threadComplete = false;
userClass = getUserClass;
thread.start();
while (!threadComplete)
continue;
changes.setText(input);
}
else Toast.makeText(this, "Error, choose your class", Toast.LENGTH_SHORT).show();
BTW, in the end of every thread (on the emulator because on my phone it crashes) I get a message:
Skipped 91 frames! The application may be doing too much work on its main thread.
and I have another problem, I also use IntentService to run my app service on the background, and obviously I don't want it to run constantly forever, so I made a loop which contains at the end of each loop a wait() command, but the problem is that when I set the time to wait for longer than 3000 milliseconds or so, the service crashes.
my code for the background service:
synchronized (this) {
int count = 0;
while (count<4) {
try {
wait(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (notifications && !userClass.equals("")) {
new Thread() {
#Override
public void run() {
//server stuff
try {
//Connecting
if (!userClass.equals("")) {
Log.i("debug", "Attempting to connect to server");
socket = new Socket(hostname, portnumber);
Log.i("debug", "Connection established!");
BufferedWriter bw = new BufferedWriter((new OutputStreamWriter(socket.getOutputStream())));
bw.write("" + userClass);
bw.newLine();
bw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
input = br.readLine();
}
} catch (IOException e) {
Log.e("debug", e.getMessage());
} finally {
complete = true;
}
}
}.start();
while (!complete)
continue;
Toast.makeText(this, "" + input, Toast.LENGTH_SHORT).show();
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.chanka)
.setContentTitle("ביטול שיעורים: ")
.setContentText(input);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
mNotificationId++;
Toast.makeText(this, "" + input, Toast.LENGTH_SHORT).show();
count++;
}
}
}
This following piece of code is the culprit -
while (!threadComplete)
continue;
You are kind of putting the main thread on a long loop. Android does not allow that. The general construct in these kind of use cases is this -
Step 1 - Show a progress dialog to the user indicating that you are
doing something important and user needs to wait till that is
complete. Show some meaningful text in the progress dialog which makes
sense to the user.
Step 2 - Start a async connection to the server. There are lot of
options in Android to do this. But for your purpose AsyncTask might
be useful. Connect to your server, fetch and parse data in the
doInBackground method of AsyncTask and once the task is complete,
let onPostExecute publish the same to the Main thread.
Step 3 - Once you get back the result from the Async task, you may
dismiss the progress dialog and continue with whatever you were doing.
Please note that the main thread should not be blocked at any time. This is the event handling thread of the app and handles all events (User initiated or system initiated). If the thread is blocked, you get the kind of error you are seeing now. Specifically in your case, Android system is not able to do some draw operations because of the while loop.
Create a new Asynctask and run the socket establisment codes inside it :)
socket = new Socket(hostname, portnumber);

Call SSIS Package from c# Console Application For Each Loop

I have a Console Application which is invoking SSIS Package.Below is the code which is working Fine.
public static void ExecuteSSIS_Staging()
{
DataAccessLayer objDAL = new DataAccessLayer();
LogManager_SSIS objlogM = new LogManager_SSIS();
String strDestinationFilePath = System.Configuration.ConfigurationManager.AppSettings.Get("FileDownloaded");
try
{
Package pkg;
Application app;
DTSExecResult pkgResults;
MyEventListener eventListener = new MyEventListener();
string staging_pkgLocation = System.Configuration.ConfigurationManager.AppSettings.Get("SSIS_Staging_Filepath").ToString();
app = new Application();
pkg = app.LoadPackage(staging_pkgLocation, eventListener);
pkgResults = pkg.Execute(null, null, eventListener, null, null);
if (pkgResults == Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success)
{
Console.WriteLine("Success");
}
else if (pkgResults == Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure)
{
string err = "";
foreach (Microsoft.SqlServer.Dts.Runtime.DtsError local_DtsError in pkg.Errors)
{
string error = local_DtsError.Description.ToString();
err = err + error;
}
throw new Exception("Error Occurred while executing the SSIS Staging package:" + err);
}
}
catch (Exception ex)
{
throw new Exception("SSIS Package Execution Failed:" + ex.Message.ToString());
}
}
Now I am in a position to Invoke this Package inside Foreach Loop.
static void Main(string[] args)
{
try
{
foreach (DateTime FileDate in SortedDates)
{
ExecuteSSIS_Staging(FileDate);
}
}
Catch(Exception ex)
{
}
}
I am getting Many Issues like
Could not load file or assembly 'Microsoft.SqlServer.ManagedDTS
and few other DLL reference error.
Can anyone suggest me, how can i invoke SSIS Package Inside Foreach loop. The main thing is, In my Local machine it is working obsolutely file. But When i deploy it in server, it is not.
The actuall issue is i have added
Microsoft.SQLServer.ManagedDTS.dll version 9.0
in one machine. When i tried to open it in other machine, some how DLL is refernced to
Microsoft.SQLServer.ManagedDTS.dll version 10.0 version.
I changed it again & executed. Now Working Fine.

Adding Try and Catch to existing program

Good Evening all,
In a little of a pickle with a huge brain fart and could use a little help with something. So i wrote this C# console app that uses Selenium to open a web page, logs in, does some stuff, then submit a form and logs off the site. Now I have this in a for loop to do it 100 times. Now very rarely it may hiccup and throws an exception cause page didn't load fast enough or something. I thought it may be good to use a try/catch but once as the catch catches the exception, but I want it to redo that loop number that it is on and continue on. So example, say if i am on iteration 66 of 100 and it throws an exception cause page didn't load fast enough or there was an error on the page for that link, i need it to catch it, log it, then restart at number 66 again. Below is some of my original code and another section of what i have gotten it to.
using System;
using System.Collections.Generic;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using System.Threading;
using System.IO;
namespace SeleniumTest
{
class Program
{
static void Main(string[] args)
{
for (Int64 i = 1; i < 100; i++)
{
DateTime time;
time = DateTime.Now;
StreamWriter tw = new StreamWriter(#"C:\folder\file.txt", true);
IWebDriver driver = new FirefoxDriver();
tw.WriteLine("Staring test," + time);
driver.Navigate().GoToUrl("http://site.com");
driver.FindElement(By.Name("username")).Clear();
driver.FindElement(By.Name("username")).SendKeys("username");
driver.FindElement(By.Name("password")).Clear();
driver.FindElement(By.Name("password")).SendKeys("password");
driver.FindElement(By.CssSelector("input.ui-standard-button")).Click();
driver.FindElement(By.LinkText("page")).Click();
driver.FindElement(By.LinkText("page")).Click();
Thread.Sleep(5000);
//Do awesome stuff
DateTime time1;
time1 = DateTime.Now;
driver.FindElement(By.CssSelector("div.Parameters")).Click();
driver.FindElement(By.Name("submit")).Click();
driver.FindElement(By.LinkText("Logoff")).Click();
driver.Quit();
tw.WriteLine("Stopping Test Successfully," + time1);
tw.Flush();
tw.Close();
Thread.Sleep(10000);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using System.Threading;
using System.IO;
namespace SeleniumTest
{
class Program
{
static void Main(string[] args)
{
try
{
for (Int64 i = 1; i < 100; i++)
{
DateTime time;
time = DateTime.Now;
StreamWriter tw = new StreamWriter(#"C:\folder\file.txt", true);
IWebDriver driver = new FirefoxDriver();
tw.WriteLine("Staring test," + time);
driver.Navigate().GoToUrl("http://site.com");
driver.FindElement(By.Name("username")).Clear();
driver.FindElement(By.Name("username")).SendKeys("username");
driver.FindElement(By.Name("password")).Clear();
driver.FindElement(By.Name("password")).SendKeys("password");
driver.FindElement(By.CssSelector("input.ui-standard-button")).Click();
driver.FindElement(By.LinkText("page")).Click();
driver.FindElement(By.LinkText("page")).Click();
Thread.Sleep(5000);
//Do awesome stuff
DateTime time1;
time1 = DateTime.Now;
driver.FindElement(By.CssSelector("div.Parameters")).Click();
driver.FindElement(By.Name("submit")).Click();
driver.FindElement(By.LinkText("Logoff")).Click();
driver.Quit();
tw.WriteLine("Stopping Test Successfully," + time1);
tw.Flush();
tw.Close();
Thread.Sleep(10000);
}
}
catch(Exception e)
{
StreamWriter tw = new StreamWriter(#"C:\folder\file.txt", true);
tw.WriteLine("Problem happened. Restarting test. Exception is :" + e);
//Line of code to restart test at number 66 which I don't know
}
}
}
}
Where //Line of code to restart test at number 66 which I don't know is where my knowledge ends and hopefully is where someone else is. Any guidance you can give would be great and appreciated.
Decrementing the counter when an exception is encountered should do it.
for (Int64 i = 1; i < 100; i++) {
try {
//main code here
} catch (Exception ex) {
//logging here
i--;
}
}
I would try to figure out why it's failing, but if that's not an option I would convert it to a while loop with a try catch
int i = 100;
while(i > 0)
{
try
{
//Do your logic here
i--
}
catch
{
//Log failure
}//Don't decrement in case of failure
}
for (Int64 i = 1; i < 100; ++i)
{
for (;;)
{
try
{
//code here
break;
}
catch (Exception exc)
{
//log error
}
}
}

Windows Phone C#, UnauthorizedAccessException when creating BitmapImage

I am trying to download image from Internet using async call like this:
private void DoGetAlbumart(object sender, DoWorkEventArgs e)
{
string req = (string)e.Argument;
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(ReadWebRequestCallback);
wc.OpenReadAsync(new Uri(req));
}
void ReadWebRequestCallback( object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null && !e.Cancelled)
{
try
{
BitmapImage image = new BitmapImage();
image.SetSource(e.Result);
SecondTile.Source = image;
}
catch (Exception ex)
{
}
}
else
{
}
}
It seems that when breakpoint hits at BitmapImage image = new BitmapImage(), I got the following exception:
ex = {System.UnauthorizedAccessException: Invalid cross-thread access.
at MS.Internal.XcpImports.CheckThread()
at System.Windows.DependencyObject..ctor(UInt32 nativeTypeIndex, IntPtr constructDO)
at System.Windows.Media.Imaging.BitmapImage..ctor()
What else can I try to get rid of this error?
Callback methods run in background threads, not the UI thread. Unfortunately, BitmapImages can only be instantiated in the UI thread. If you need to access the UI thread from a callback, try the following:
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
BitmapImage image = new BitmapImage();
image.SetSource(e.Result);
SecondTile.Source = image;
});

Calling Console Application (.exe) in Event Receiver and Getting Error

I am using SharePoint foundation. I have a console application that is used to run some OCR process. I am calling the exe of the console application from windows service and it is working fine. I am trying to call the same exe from an event receiver but unable to call the exe and getting some error. The Event receiver is working fine but unable to call exe. I have tried to call the other exes like notepad.exe but getting same error. The details are below:
Code:
public override void ItemAdded(SPItemEventProperties properties)
{
try
{
base.ItemAdded(properties);
Log("Event Occured.");
string OCRedText = string.Empty;
string Listname = properties.ListTitle;
string itemName = Convert.ToString(properties.ListItem["Name"]);
string itemTitle = Convert.ToString(properties.ListItem["Title"]);
callService(); // Here is the method to call Process
SPListItem item = properties.ListItem;
if (System.Threading.Monitor.TryEnter(myLock, TimeSpan.FromSeconds(100)))
{
if (Convert.ToString(item["OCRed"]) == "False")
{
item["OCRed"] = "True";
Thread.Sleep(10000);
item.SystemUpdate();
Log("Item Added and Updated.");
}
else
{
Log("Can not update the Item.");
}
}
Log("Event End."+"\r\n");
}
catch (Exception ex)
{
Log("Error in Item Added Event Receiver.");
Log(ex.ToString());
}
}
public void callService()
{
Log("Calling Service is not easy.");
try
{
ProcessStartInfo pinfoService = new ProcessStartInfo();
pinfoService.FileName = #"D:\Khan\khan.exe";
//pinfoService.FileName = #"C:\Windows\System32\notepad.exe";
pinfoService.UseShellExecute = false;
pinfoService.RedirectStandardError = true;
pinfoService.RedirectStandardInput = true;
pinfoService.RedirectStandardOutput = true;
pinfoService.CreateNoWindow = true;
pinfoService.WindowStyle = ProcessWindowStyle.Hidden;
Log("FileName: " + pinfoService.FileName);
Log("Arguments for callService : "+pinfoService.Arguments);
Process pService = new Process();
pService.StartInfo = pinfoService;
Log("Process Before Start.");
Thread.Sleep(5000);
pService.Start();
Thread.Sleep(2000);
Log("Process Before wait for exit.");
pService.WaitForExit();
Log("Process Completed.");
}
catch (Exception ex)
{
Log("Error in callService(). Please contact your Administrator.");
Log(ex.ToString());
}
}
and below is the error I am getting on pService.Start();
=========================================
Info : Process Before Start.
Info : Error in callService(). Please contact your Administrator.
Info : System.ComponentModel.Win32Exception: Not enough quota is available to process this command
at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
at OCRonUploadDoc.EventReceiver1.EventReceiver1.callService()
=========================================
I am unable to figure out the issue. Please help me...!!!
Thanks in Advance.
Khan Abubakar
I think that the asp.net account under which the application pool runs does not have permissions to start the exe file. You can check this out http://www.daniweb.com/web-development/aspnet/threads/386380/cannot-run-exe-files-in-asp.net-application
However if your system will be used by more users you can run into problems really quickly, because every change of a document will spawn a new process. The server will run out of ram and the farm will not be unavailable.

Resources