How to solve ConnectionNotFoundException in JavaME - netbeans

I'm trying to connect to the internet via my J2ME application on my Netbeans emulator with the following function which connects to a webpage and prints out its HTML using System.out.println().
function getHTML(String url)
{
HttpConnection httpConn = null;
InputStream is = null;
OutputStream os = null;
try
{
httpConn = (HttpConnection)Connector.open(url);
int respCode = httpConn.getResponseCode();
if (respCode == httpConn.HTTP_OK)
{
StringBuffer sb = new StringBuffer();
os = httpConn.openOutputStream();
is = httpConn.openDataInputStream();
int chr;
while ((chr = is.read()) != -1)
sb.append((char) chr);
System.out.println(sb.toString());
os.close();
is.close();
}
else
{
System.out.println("Error " + respCode);
}
httpConn.close();
}
catch(IOException ioex)
{
ioex.printStackTrace();
}
}
But I've been getting the following error;
javax.microedition.io.ConnectionNotFoundException: error 10051 in socket::open
at com.sun.midp.io.j2me.socket.Protocol.open0(), bci=0
at com.sun.midp.io.j2me.socket.Protocol.connect(), bci=209
at com.sun.midp.io.j2me.socket.Protocol.open(), bci=216
at com.sun.midp.io.j2me.socket.Protocol.openPrim(), bci=4
at com.sun.midp.io.j2me.http.Protocol.createConnection(), bci=41
at com.sun.midp.io.j2me.http.Protocol.connect(), bci=41
at com.sun.midp.io.j2me.http.Protocol.streamConnect(), bci=164
at com.sun.midp.io.j2me.http.Protocol.startRequest(), bci=7
at com.sun.midp.io.j2me.http.Protocol.sendRequest(), bci=33
at com.sun.midp.io.j2me.http.Protocol.sendRequest(), bci=3
at com.sun.midp.io.j2me.http.Protocol.getResponseCode(), bci=5
I know my code isn't the problem because this used to work on my old laptop, but it hasn't worked since I installed Netbeans on my new laptop. Is it because of my internet connection, or my firewall settings, or my settings in Netbeans, or did I just not install Netbeans properly?

If you want to send some data and receive means then try the coding
try
{
httpConn = (HttpConnection)Connector.open(url);
os = httpConn.openOutputStream();
//Writing data to os
os.write(b); //Here b is a byte array
os.flush();
int respCode = httpConn.getResponseCode();
if (respCode == httpConn.HTTP_OK)
{
StringBuffer sb = new StringBuffer();
is = httpConn.openDataInputStream();
int chr;
while ((chr = is.read()) != -1)
sb.append((char) chr);
System.out.println(sb.toString());
}
else
{
System.out.println("Error " + respCode);
}
}
catch(IOException ioex)
{
ioex.printStackTrace();
}
if(os!=null) os.close();
if(is!=null) is.close();
if(httpConn!=null) httpConn.close();
os=null;is=null;httpConn=null;
}

Related

Apache commons net FTP clients hangs unpredictably

We tried all the solutions provided in this post (FTP client hangs) but none of them is working. We are using version 3.6 of commons net. Sometimes it hangs while uploading a file, sometimes will checking existence of a directory. Max. file size is around 400 MB. But sometime it hangs even for a small file size < 1KB. Below is the fragment of code:
public boolean uploadData(String inputFilePath, String destinationFolderName) {
if (StringUtil.isNullOrBlank(inputFilePath) || StringUtil.isNullOrBlank(destinationFolderName)) {
LOGGER.error("Invalid parameters to uploadData. Aborting...");
return false;
}
boolean result = false;
FTPSClient ftpClient = getFTPSClient();
if (ftpClient == null) {
logFTPConnectionError();
return false;
}
try {
loginToFTPServer(ftpClient);
result = uploadFileToFTPServer(ftpClient, inputFilePath, destinationFolderName);
} catch (Exception e) {
logErrorUploadingFile(inputFilePath, e);
return false;
} finally {
try {
logoutFromFTPServer(ftpClient);
} catch (Exception e) {
logErrorUploadingFile(inputFilePath, e);
result = false;
}
}
return result;
}
private FTPSClient getFTPSClient() {
FTPSClient ftpClient = null;
try {
ftpClient = new FTPSClient();
LOGGER.debug("Connecting to FTP server...");
ftpClient.setConnectTimeout(connectTimeOut);
ftpClient.connect(server);
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
LOGGER.error("Could not connect to FTP server. Aborting.");
return null;
}
} catch (Exception e) {
LOGGER.error("Could not connect to FTP server.", e);
return null;
}
return ftpClient;
}
private void loginToFTPServer(FTPSClient ftpClient) throws Exception {
ftpClient.setDataTimeout(DATA_TIMEOUT);
ftpClient.login(ftpUserName, ftpPassword);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
LOGGER.debug("FTP Client Buffer Size Before:" + ftpClient.getBufferSize());
ftpClient.setBufferSize(BUFFER_SIZE);
LOGGER.debug("FTP Client Buffer Size After:" + ftpClient.getBufferSize());
ftpClient.execPBSZ(0);
ftpClient.execPROT("P");
ftpClient.setControlKeepAliveTimeout(300);
LOGGER.debug("Logged into FTP server.");
}
private void logoutFromFTPServer(FTPSClient ftpClient) throws Exception {
LOGGER.debug("Logging out from FTP server.");
ftpClient.logout();
ftpClient.disconnect();
LOGGER.debug("FTP server connection closed.");
}
private boolean uploadFileToFTPServer(FTPSClient ftpClient, String inputFilePath, String destinationFolderName) {
boolean result = false;
String remoteLocationFile;
File ftpFile = new File(inputFilePath);
try (InputStream inputStream = new FileInputStream(ftpFile)) {
String fileName = ftpFile.getName();
remoteLocationFile = (destinationFolderName == null || destinationFolderName.isEmpty())
? ftpFile.getName()
: destinationFolderName + File.separator + fileName;
LOGGER.info("Storing file " + ftpFile.getName() + " of size "
+ ftpFile.length() + " in folder " + remoteLocationFile);
result = ftpClient.storeFile(remoteLocationFile, inputStream);
if(result) {
LOGGER.info("Successfully stored file " + ftpFile.getName() + " in folder " + remoteLocationFile);
} else {
LOGGER.error("Unable to store file " + ftpFile.getName() + " in folder " + remoteLocationFile);
}
return result;
} catch (Exception e) {
logErrorUploadingFile(inputFilePath, e);
}
return result;
}
The application is hosted in apache tomcat 8. What could be other causes of this issue and how should we fix them? This is crucial functionality of our application and we may even consider to use alternate API if that is stable. Please suggest.
Adding ftpClient.setSoTimeout(20000); has fixed the issue.
Adding a enterLocalPassiveMode right before the retreiveFile should solve this issue.
You also need to add
ftpClient.setControlKeepAliveTimeout(300);
or Check this code which will resolve the hanging issue

“An error occured while executing doInBackground()”

i'm using the below code to get the file length and using which i display progress bar till i download the total file but i get an error from firebase crash report like below
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:304)
#Override
protected String doInBackground(String...Url) {
try {
URL url = new URL(Url[0]);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("HEAD");
connection.connect();
// Detect the file lenghth
fileLength = connection.getContentLength();
} else {
URLConnection connection = url.openConnection();
connection.connect();
// Detect the file lenghth
fileLength = connection.getContentLength();
}
/*
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("HEAD");
connection.connect();
int fileLength = connection.getContentLength();*/
// Locate storage location
// String filepath = Environment.getExternalStorageDirectory().getPath();
String filepath = getFilesDirectory(getApplicationContext()).getPath();
// File fo = getFilesDirectory(getApplicationContext());
// Download the file
InputStream input = new BufferedInputStream(url.openStream());
// Save the downloaded file
if (lang_slector == 0) {
// input stream to read file - with 8k buffer
File folder = new File(filepath, "/offlinedata/");
folder.mkdir();
File pdfFile = new File(folder, englishpdffilename);
try {
pdfFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
OutputStream output = new FileOutputStream(filepath + "/offlinedata/" +
pdffilename);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// Publish the progress
publishProgress((int)(total * 100 / fileLength));
output.write(data, 0, count);
}
// Close connection
output.flush();
output.close();
input.close();
} else if (lang_slector == 1) {
// input stream to read file - with 8k buffer
File folder = new File(filepath, "/offlinedata/");
folder.mkdir();
File pdfFile = new File(folder, englishpdffilename);
try {
pdfFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
OutputStream output = new FileOutputStream(filepath + "/offlinedata/" +
englishpdffilename);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// Publish the progress
publishProgress((int)(total * 100 / fileLength));
output.write(data, 0, count);
}
// Close connection
output.flush();
output.close();
input.close();
}
} catch (Exception e) {
// Error Log
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}

Using websockets through the simple websockets for webgl asset in unity3d, can connect but can't transmit messages

Just having a problem on my mac trying to send strings over web sockets using this https://www.assetstore.unity3d.com/en/#!/content/38367
Lots of adapted code below from here mainly http://www.codepool.biz/how-to-implement-a-java-websocket-server-for-image-transmission-with-jetty.html and the web socket sharp echotest example.
I can connect but there is no sign of strings in my Jetty server console window (on a ws server running in java(eclipse)).
I’m basically just trying to send a “1” to my server over a websocket connection with the unity editor (5) at the moment, to prompt the server to start sending PNG files encoded as byte arrays, so I can put them back together in a C# script and apply them to a texture.
this is the script, I want to attach it to a game object like a plane or a cube and display the updating images sent over the web socket from my Jetty server, but at the moment I'm just stuck trying to send a message and see it pop up in my eclipse console window.
using UnityEngine;
using System.Collections;
using System;
public class socketTexture : MonoBehaviour {
// Use this for initialization
IEnumerator Start () {
WebSocket w = new WebSocket(new Uri("ws://192.168.0.149:8080/"));
yield return StartCoroutine(w.Connect());
Debug.Log ("Connected");
w.SendString("I'm client");
w.SendString("1");
while (true)
{
byte[] reply = w.Recv();
if (reply != null)
{
Debug.Log ("Received: "+reply);
var tex = new Texture2D(300, 300, TextureFormat.PVRTC_RGBA4, false);
// Load data into the texture and upload it to the GPU.
tex.LoadRawTextureData(reply);
tex.Apply();
// Assign texture to renderer's material.
GetComponent<Renderer>().material.mainTexture = tex;
}
if (w.Error != null)
{
Debug.LogError ("Error: "+w.Error);
break;
}
yield return 0;
}
w.Close();
}
}
...And the relevant code from the jetty server, but this works, I've tested it with some javascript and I can load the PNGs back into the browser window, so I'm definitely doing something wrong in Unity
#OnWebSocketMessage //part request from websocket client (remote browser)
public void onMessage( String message) {
System.out.println("message");
if (message.equals("1") || message.equals("2") || message.equals("3") || message.equals("4") ) {
System.out.println("Part " + message + " joined");
System.out.println( UIMain.usersPath + "/" + message + ".png" );
final String testVar = ( UIMain.usersPath + "/" + message + ".png" );
task = new FileWatcher( new File(testVar) ) {
protected void onChange( File file ) {
// here we code the action on a change
System.out.println( "File "+ file.getName() +" has changed!" );
try {
File f = new File(testVar);
BufferedImage bi = ImageIO.read(f);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(bi, "png", out);
ByteBuffer byteBuffer = ByteBuffer.wrap(out.toByteArray());
mSession.getRemote().sendBytes(byteBuffer);
out.close();
byteBuffer.clear();
}
catch (IOException e) {
e.printStackTrace();
}
}
};
Timer timer1 = new Timer(); {
timer1.schedule(task , new Date(), 40 );
}
}
else if (message.equals( "0")) {
zerocounter = zerocounter + 1;
if (zerocounter >= 2) {
task.cancel();
}
}
else if (message.equals( "Hi there, client here")) {
System.out.println( "Client says: " + message );
}
}
Any help would be really appreciated, been lurking on here for years, hopefully getting to the stage soon where I can help out others a bit too.
Benedict
Edit:
This is my console error message in Unity
FormatException: Invalid length. System.Convert.FromBase64String
(System.String s) (at
/Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System/Convert.cs:146)
EchoTest+c__Iterator0.MoveNext () (at
Assets/Example/EchoTest.cs:11)
I'm pretty sure the problem arises from websocket sharp for webgl. I need to send the message as a byte array.
OK So Joakim Erdfelt was right, the server was not configured to handle Byte[] messages. Here's what I added to fix it:
#OnWebSocketMessage
public void onMessage(byte[] buffer, int offset, int length) throws UnsupportedEncodingException {
System.out.println(buffer);
String sFclientOutStr = new String(buffer, "UTF-8");
sFclientOut = Integer.parseInt(sFclientOutStr);
System.out.println(sFclientOut);
if ((sFclientOut > 0) & (sFclientOut < 500)) {
System.out.println("Part " + sFclientOut + " joined");
System.out.println( UIMain.usersPath + "/" + sFclientOutStr + ".png" );
final String testVar = ( UIMain.usersPath + "/" + sFclientOutStr + ".png" );
task = new FileWatcher( new File(testVar) ) {
protected void onChange( File file ) {
// here we code the action on a change
System.out.println( "File "+ file.getName() +" has changed!" );
try {
File f = new File(testVar);
BufferedImage bi = ImageIO.read(f);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(bi, "png", out);
ByteBuffer byteBuffer = ByteBuffer.wrap(out.toByteArray());
mSession.getRemote().sendBytes(byteBuffer);
out.close();
byteBuffer.clear();
}
catch (IOException e) {
e.printStackTrace();
}
}
};
Timer timer1 = new Timer(); {
timer1.schedule(task , new Date(), 40 );
}
}
else if (sFclientOutStr.equals("0")) {
zerocounter = zerocounter + 1;
if (zerocounter >= 2) {
task.cancel();
}
}
else if (sFclientOutStr.equals( "I'm client")) {
System.out.println( "Client says: " + sFclientOutStr );
}
}
These links helped explain it for me http://www.programcreek.com/java-api-examples/index.php?api=org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage
http://www.eclipse.org/jetty/documentation/current/jetty-websocket-api-annotations.html

Submitting a WebRequest from within a CLR Trigger

I just implemented a prototype solution for updating my caching server in real-time by assigning a CLR Trigger to a table so that whenever a certain column is updated the URL called from the trigger will update the caching server with the correct data.
It's working fine and the code is as follows:
[Microsoft.SqlServer.Server.SqlTrigger(Name = "AdStatusChanged", Target = "Ads", Event = "FOR UPDATE")]
public static void AdStatusChanged()
{
SqlTriggerContext triggContext = SqlContext.TriggerContext;
int adID = 0, adStatusID_Old = 0, adStatusID_New = 0;
if (triggContext.TriggerAction == TriggerAction.Update)
{
using (SqlConnection conn = new SqlConnection("context connection=true"))
{
conn.Open();
SqlCommand sqlComm = new SqlCommand();
SqlPipe sqlP = SqlContext.Pipe;
sqlComm.Connection = conn;
sqlComm.CommandText = "SELECT AdID, AdStatusID from INSERTED";
SqlDataReader reader = sqlComm.ExecuteReader();
if (reader.Read())
{
adID = reader.GetInt32(0);
adStatusID_New = reader.GetInt32(1);
}
reader.Close();
sqlComm.CommandText = "SELECT AdID, AdStatusID from DELETED WHERE AdID = " + adID;
reader = sqlComm.ExecuteReader();
if (reader.Read())
{
adID = reader.GetInt32(0);
adStatusID_Old = reader.GetInt32(1);
}
}
if (adID == 0 || adStatusID_New == adStatusID_Old)
{
// Check could be more thorough !
return;
}
WebResponse httpResponse = null;
try
{
string apiURL = string.Format("{0}/{1}", "http://localhost:14003/Home", "UpdateAdStatus?adID=" + adID + "&adStatusID=" + adStatusID_New);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(apiURL);
httpWebRequest.Method = "GET";
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
// check for successful response
}
catch (Exception ex)
{
Log("WebRequest from within SQL Server failed ! " + ex.Message);
}
finally
{
if (httpResponse != null)
{
httpResponse.Close();
}
}
}
}
I would like to have some expert/experienced views on the "CONS" of this approach regarding performance, deadlocks, sql crashing, or other areas that could be of potential concern.
Has anyone tried this (I'm sure many must have) and what was the result ? a successful implementation or did you revert to some other method or updating the cache real-time?

how can i connect my blackberry app to my website rest API?

I am trying to build my first app for blackberry mobile's but i am new # mobile development and i am cant find the correct way to connect my app with my webiste rest API can anyone guide me where to start from?
Thanx in advance :D
HttpConnection conn = null;
InputStream is = null;
ByteArrayOutputStream bos = null;
String response = null;
String connectionURL = null;
try {
connectionURL = "THIS CONTAIN YOUR API URL"
conn = (HttpConnection) Connector.open(connectionURL);
conn.setRequestProperty("Content-Type","application/json");
System.out.println("Response code : "+conn.getResponseCode());
if(conn.getResponseCode() == HttpConnection.HTTP_OK)
{
is = conn.openInputStream();
int ch=-1;
bos = new ByteArrayOutputStream();
while((ch = is.read())!=-1)
{
bos.write(ch);
}
response = new String(bos.toByteArray());
System.out.println("Response : "+response);
}
} catch (Exception e)
{
System.out.println("Exception .."+e);
}finally
{
if(conn != null)
conn.close();
if(is != null)
is.close();
if(bos != null)
bos.close();
}