java.lang.securityException not allowed to open connection j2me - exception

In my j2me application, I receive above exception(java.lang.securityException not allowed to open connection). The flow of my function is like first I open socket for Receiving message in the constructor and then for sending SMS I open ports in the method body, on my phone MIDlet asks for permission to send SMS, if I press NO it shows security exception that SMS sending not denied, that's OK. But when being in the same MIDlet and performing this action second time it gives exception at the time of opening receiving port in the constructor as java.lang.securityException not allowed to open connection. At this time I yet not seen any permission asking for sending SMS for second time. My code for Constructor and SMS Sending is below:
//Constructor
public ServerContactRetriever(MainMidlet parent, Language lang) {
try {
this.language = lang;
this.parent = parent;
recvCon = (MessageConnection) Connector.open(RECV_URL); //open receiving port
recvCon.setMessageListener(this);
} catch (Exception ex) {
parent.dispErrorMessage(language.access_denied_disp);
parent.alertShow(language.access_denied_alert);
}
}
//METHOD
//Request restore contacts from server
private void sendRestoreRequest() {
try {
MessageConnection msgCon = (MessageConnection) Connector.open(SEND_URL);
TextMessage msg = (TextMessage) msgCon.newMessage(MessageConnection.TEXT_MESSAGE);
msg.setAddress(SEND_URL);
msg.setPayloadText("set payload here");
msgCon.send(msg);
msgCon.close();
} catch (Exception ex) {
try {
parent.alertShow(language.sms_error_alert);
parent.dispErrorMessage(language.sms_error_disp);
recvCon.close();
} catch (Exception ex1) {
}
}
}
I am using WTK with MIDP 2.0.
Checking over Nokia Devices.
First I wonder there could be issue of closing MessageConnection port, but I tried that too and it shows the same error. Whereas about SMS send and I select NO, it works fine if I just try to send SMS and select NO as many times as I want and it still stays on the midlet without any exception. Thanks

There is no issue with closing MessageConnection. In some of the s40 and Symbian phones(like X2-02), the permission will be asked only once for one entire session. If you choose 'Yes', it wont ask you again while connecting second time. It will directly connect. Similarly, if you select 'No', while connecting first time, no connections will be allowed(securityException will be thrown) on every attempt to connect.
On some Nokia phones, you might see this option,
Select the application->Options->Application Access->Communication->
1. Ask Every time
2. Ask first time
3. Always allowed
4. Not allowed.
You can select the one that is appropriate to you.
If you don't want your application to seek permissions at all, you need to have your app signed by Manufacturer.

Related

How to set up Tomcat for one Database Connection per Request

I have a Sparkjava app which I have deployed on a Tomcat server. It uses SQL2O to interface with the MySQL-database. After some time I start to have trouble connecting to the database. I've tried connecting directly from SQL2O, connecting through HikariCP and connecting through JNDI. They all work for about a day, before I start getting Communications link failure. This app gets hit a handful of times a day at best, so performance is a complete non issue. I want to configure the app to use one database connection per request. How do I go about that?
The app doesn't come online again afterwards until I redeploy it (overwrite ROOT.war again). Restarting tomcat or the entire server does nothing.
Currently every request creates a new Sql2o object and executes the query using withConnection. I'd be highly surprised if I was leaking any connections.
Here's some example code (simplified).
public class UserRepositry {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
protected Sql2o sql2o = new Sql2o("jdbc:mysql://mysql.server.name/dbname?serverTimezone=UTC", "username", "password");
public List<Users> getUsers() {
return sql2o.withConnection((c, o) -> {
return c.createQuery(
"SELECT\n" +
" id,\n" +
" name\n" +
"FROM users"
)
.executeAndFetch(User.class);
});
}
}
public class Main {
public static void main(String[] args) {
val gson = new Gson();
port(8080);
get("/users", (req, res) -> {
return new UserRepository().getUsers();
}, gson::toJson);
}
}
If you rely on Tomcat to provide the connection to you: It's coming from a pool. Just go with plain old JDBC and open that connection yourself (and make sure to close it as well) if you don't like that.
So much for the answer to your question, to the letter. Now for the spirit: There's nothing wrong with connections coming from a pool. In all cases, it's your responsibility to handle it properly: Get access to a connection and free it up (close) when you're done with it. It doesn't make a difference if the connection is coming from a pool or has been created manually.
As you say performance is not an issue: Note that the creation of a connection may take some time, so even if the computer is largely idle, creating a new connection per request may have a notable effect on the performance. Your server won't overheat, but it might add a second or two to the request turnaround time.
Check configurations for your pool - e.g. validationQuery (to detect communication failures) or limits for use per connection. And make sure that you don't run into those issues because of bugs in your code. You'll need to handle communication errors anyways. And, again, that handling doesn't differ whether you use pools or not.
Edit: And finally: Are you extra extra sure that there indeed is no communication link failure? Like: Database or router unplugged every night to connect the vacuum cleaner? (no pun intended), Firewall dropping/resetting connections etc?

Asynchronous download with HttpClient: The text associated with this error code could not be found

I intend to use the following code to download a file. It works when WIFI is available; but when there is no Wifi, I expect to catch the exception raised in the previousTask.get(). Unfortunately, catch in my code doesn't seem to catch the exception. The exception is HRESULT:0x80072F30 The text associated with this error code could not be found., by the way. Am I missing something like the exception is uncaughtable?
auto httpClient = ref new HttpClient();
auto get_operation = httpClient->GetAsync(ref new Uri(url), HttpCompletionOption::ResponseContentRead);
get_operation->Progress = progressHandler;
auto response = create_task(get_operation).then([](task<HttpResponseMessage^> previousTask)
{
try
{
return previousTask.get();
}
catch (Exception^ ex)
{
// Some how this does not catch
OutputDebugString(("Exception: " + ex->Message)->Data());
return (HttpResponseMessage^)nullptr;
}
}).get();
// At this point, I expect either a fully read response or response=nullptr
// Code to write to file is omitted
EDIT: ~~I tested the official Microsoft's HttpClient sample which apparently use similar code. Apparently, the same crash occurs in that app when there is no network connection. This sort of confirms that the defect is in the OS side and there's nothing one can do about it.~~
EDIT: It turns out that I thought the exception was not caught because Visual Studio pops up a dialog and I assume that means in reality the exception crashes the app i.e. when it is not launched via VS. I read the pop up message carefully and realize that VS prompts on every Exception thrown unless configured not to do so; pressing [Continue] button on the dialog goes to the catch clause. Launching app from Start menu poses no problem.
If this code is called from the UI thread then remove the get() call from the last line of this code. You can't do that in a UI thread.
Otherwise your code works fine for me with Airplane mode turned on; as expected I catch the exception in the handler. The exception has an HResult of 0x80072f30, which is documented on the MSDN page as ERROR_WINHTTP_NO_CM_CONNECTION

EWS API Streaming subscription stops working

Created an windows service which saves all received and sent emails to my local drive and my service successfully does that.I have also resubscribed my streaming subscription onDisconnect event and Onerror event also.But my service stops responding after some time and there is no exception catched even though i have handled everything properly.Saw other forum and found the same issue people facing but there is not proper solution.
static private void OnDisconnect(object sender, SubscriptionErrorEventArgs args)
{
try
{
// Cast the sender as a StreamingSubscriptionConnection object.
StreamingSubscriptionConnection connection = (StreamingSubscriptionConnection)sender;
if (!connection.IsOpen)
connection.Open();
}
static void OnError(object sender, SubscriptionErrorEventArgs args)
{
// Cast the sender as a StreamingSubscriptionConnection object.
StreamingSubscriptionConnection connection = (StreamingSubscriptionConnection)sender;
if (!connection.IsOpen)
connection.Open();
}
Is this something to do with the Microsoft bug or it requires any settings on Exchange server for changing the limits for EWS subscription.
Even i checked below something related to throttling limit but no success:
http://msdn.microsoft.com/en-us/library/exchange/hh881884(v=exchg.140).aspx
Thanks a million in advance.
We have exactly same issue. And we do re-create whole subscription in OnError event just in case. It is also interesting that multiple application instances running on separate boxes exhibit identical behavior: at some point they just stop receiving notifications. Restarting any and all of them doesn't help; they do successfully subscribe but still no notifications other than OnDisconnect. Restarting Exchange Server is what really helps, though for a while.
I can see that the problem here is that you are trying to open the connection in the OnError handler. The problem here is that when OnError happen, the connection normally loses all the subscriptions, so you might need to consider creating the subscriptions again before opening them.

Execute exe-file from html-page?

I want to launch a local exe-file (without saving it to another location first) upon clicking on a link on a local html file.
It either needs to work in IE, Firefox, Chrome or Opera, I don't care. It's just for a presentation tomorrow.
It's simply not possible. If it was, it would be considered a security flaw and fixed. On Firefox within hours, on IE within some months.
UPDATE: You could try registering your custom protocol: http://openwinforms.com/run_exe_from_javascript.html
But I believe the browser will still prompt you whether you want to run the app.
I want to share my experience.
The accepted response says that it is not possible but it is quite possible indirectly.
If you want to execute an exe on a pc, it means that you have acces on this pc and you can install your exe on that machine.
In my case, I had to take a 3D scan from a 3D scanner via a web application. It seemed impossible at the beginning.
After lots of research, I found that we can send socket messages via javascript.
It means that if we had an application which listens a specific port, it can communicate with a website.
Let's explain how I did this.
In my web application, I created a javascript method like this :
function openCapron3DScanner(foot) {
$("#div-wait").show();
//Creates a web socket pointed to local and the port 21000
var ws = new WebSocket("ws://127.0.0.1:21000");
ws.onopen = function () {
//Sends the socket message to the application which listens the port 21000
ws.send(foot + "-" + #ProjectHelper.CurrentProject.Proj_ID);
};
ws.onerror = function myfunction() {
$("#div-wait").hide();
alert("Erreur connection scanner.");
}
ws.onmessage = function (evt) {
//Receives the message and do something...
var received_msg = evt.data;
if (received_msg == "ErrorScan") {
alert("Erreur scan.");
}
else {
refreshCurrentProject();
}
};
ws.onclose = function () {
$("#div-wait").hide();
};
};
And I created a windows forms application who listens the localhost and port 21000.
This application is hidden, only shown in icon tray.
The only thing to do is to add the application on windows startup via code on the first load to assure that the next restart of windows it will be executed and listen the port.
private static WebSocketServer wsServer;
static WebSocketSession LastSession;
private void Form1_Load(object sender, EventArgs e)
{
wsServer = new WebSocketServer();
int port = 21000;
wsServer.Setup(port);
wsServer.NewMessageReceived += WsServer_NewMessageReceived;
wsServer.Start();
}
private static void WsServer_NewMessageReceived(WebSocketSession session, string value)
{
if (value.StartsWith("ScanComplete-"))
{
//If the scan is ok, uploads the result to the server via a webservice and updates the database.
UploadImage(value);
//Sends a confirmation answer to the web page to make it refresh itself and show the result.
if (LastMacSession != null)
LastMacSession.Send("ScanComplete");
}
else if (value == "ErrorScan")
{
//If the C++ application sends an error message
if (LastMacSession != null)
LastMacSession.Send("ErrorScan");
}
else//call the 3D Scanner from the web page
{
LastSession = session;//Keeps in memory the last session to be able to answer via a socket message
//Calls the C++ exe with parameters to save the scan in the related folder.
//In could be don in this same application if I had a solution to consume the scanner in C#.
var proc = System.Diagnostics.Process.Start(#"C:\Program Files\MyProjectFolder\MyScannerAppC++.exe", projectID + " " + param);
}
}
I hope it will help.
Use System.Diagnostics.Process.Start() method.
protected void LinkButton1_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("notepad.exe");
}
You'll have to use C#, but since that's on your post, it should work. You'll also need the full path, if the file is not in your environment path that's loaded in memory.
For a 'regular link' you'd still need to place this in an ASPX page.....
Click me
We're getting really fugly now though.
You can't run an exe file on a website. (First, if it's a Linux server, exe files won't run on it and second, if you're on a Windows server, your host would kill the program immediately. And probably terminate your account.)
That link (assuming it was Play Now!) will just allow your user to download the file. (C:\Program Files\World of Warcraft\ exists on your computer, but it doesn't exist on the web server.)
You could setup a custom protocol on your local OS, if it's Windows, in regedit.
Check out this and this.
Then you create a simple HTML page, and place a link, something like this :
Start!
Given that you registered your custom "presentation" protocol, and configured it correctly in the registry, the application should launch when you click that link.

error while stopping windows service programmatically

I have a windows service. In the OnStart method, I am performing some operation and if one of the operation fails, I want service to stop. In the Catch block I am writing below mentioned code:
var srvc = new System.ServiceProcess.ServiceController("Scv1", "localhost");
srvc.Stop();
srvc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped);
It does the job well but windows shows me a messagebox:
---------------------------
Services
---------------------------
The xxx service on Local Computer started and then stopped. Some services stop automatically if they are not in use by other services or programs.
---------------------------
OK
---------------------------
Am I doing something wrong here? How do I suppress the messagebox?
I created a basic test service in C#, installed it on Windows 7, and then tried to start it.
using System.ServiceProcess;
public class MyService : ServiceBase
{
static void Main()
{
System.ServiceProcess.ServiceBase.Run( new MyService() );
}
protected override void OnStart( string[] args )
{
bool failed = true;
// Do stuff...
// Oops, we failed! Time to stop!
if( failed ) {
base.Stop();
return;
}
base.OnStart( args );
}
}
When it fails, yes, I do see the message box that you describe. This message box is not part of your service -- the Services window is showing that. If you were to open an administrator command prompt and type the following:
net start Scv1
Then you would see a text-based error message instead of a message box.
In either case, you are running a program that asks the SCM to start your service. Your service failed to start. That failure is reported back to the program. The program has decided to display an error message to inform the user. That is beyond your control.
You can actually check the event handler. It will intimate you the mistake you have done in the configuration file. Some syntax error in the configuration file will be the reason for this kind of message box.