org.apache.commons.net.ftp hangs timeout - upload

I am in trouble with org.apache.commons.net.ftp.
My client need to detect timeout when uploading (Timeout for downloads works like a charm)
if i unplugged the network cable or switch off the adsl, upload hangs and timeouts are not working. I have made several test but nothing works, it's going to make me crazy
this is my code :
public boolean uploadFile2(String localFile, String serverFile) {
try {
InputStream stO = new FileInputStream(localFile);
OutputStream stD = storeFileStream(serverFile);
setDataTimeout(dataTimeOut);
Util.copyStream(stO, stD, getBufferSize(), CopyStreamEvent.UNKNOWN_STREAM_SIZE, new CopyStreamAdapter() {
public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) {
System.out.println("On transfert " + "/" + totalBytesTransferred + "/" + bytesTransferred + "/" + streamSize);
}
});
completePendingCommand();
} catch (Exception e) {
}
return false;
}
public boolean connectAndLogin(String host, String userName, String password) throws IOException, UnknownHostException,
FTPConnectionClosedException {
boolean success = false;
setDefaultTimeout(this.defaultTimeOut);
setConnectTimeout(this.connectionTimeOut);
addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
setPassiveMode(true);
connect(host);
int reply = getReplyCode();
if (FTPReply.isPositiveCompletion(reply)) {
success = login(userName, password);
setKeepAlive(true);
setControlKeepAliveTimeout(keepAliveTimeout);
setControlKeepAliveReplyTimeout(keepAliveResponseTimeout);
setSoTimeout(soTimeOut);
setDataTimeout(dataTimeOut);
setFileTransferMode(FTP.BLOCK_TRANSFER_MODE);
setFileType(FTP.BINARY_FILE_TYPE);
}
if (!success) {
disconnect();
}
return success;
}
Any help would be appreciated, thanks
and this does not work either:
FileInputStream in = new FileInputStream(localFile);
boolean result = storeFile(serverFile, in);
in.close();
return result;

Related

Is it possible to switch wifi networks in Appium?

While executing my test suite I have to switch between different wifi networks available in Android Device.
In the middle of the execution I have to change my wifi connection from Wifi_Network_1 to Wifi_Network_2 provided ssid name and password of wifi network is known. How can it be done?
I am using:
Appium server -->1.8.1
java-client --> 6.1.0
selenium-java --> 3.13.0
Since NetworkConnectionSetting has been deprciated, I am not able to find alternate for it.
I can toggle wifi on/off using
driver.toggleWifi();
But it is not suitable for my case as i need to toggle between different wifi network available using SSID name and its password.
Thanks in advance.
Hi I'am using this method due Appium deprecated their switch for wifi, and I've created my own override via console via commands from adb. It is working for me so give it a try:
public synchronized boolean wifiSetup(String udid, boolean flg) {
synchronized (this) {
String flgEnabled = (flg) ? "enable" : "disable";
List<String> output = Console.runProcess(false, "adb -s " + udid + " shell am broadcast -a io.appium.settings.wifi --es setstatus " + flgEnabled);
for (String line : output) {
System.err.println(line);
if (line.equalsIgnoreCase("Broadcast completed: result=-1"))
return true;
}
return false;
}
}
usage to switch off:
wifiSetup("xxxUDIDfromAndroid", false);
usage to switch on:
wifiSetup("xxxUDIDfromAndroid", true);
And here is part for calling console:
public class Console {
private static final String[] WIN_RUNTIME = { "cmd.exe", "/C" };
private static final String[] OS_LINUX_RUNTIME = { "/bin/bash", "-l", "-c" };
private Console() {
}
private static <T> T[] concat(T[] first, T[] second) {
T[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
#SuppressWarnings({ "hiding"})
private static <String> String[] concatStr(String[] first, String[] second) {
String[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
public static List<String> runProcess(boolean isWin, String... command) {
String[] allCommand = null;
try {
if (isWin) {
allCommand = concat(WIN_RUNTIME, command);
} else {
allCommand = concat(OS_LINUX_RUNTIME, command);
}
ProcessBuilder pb = new ProcessBuilder(allCommand);
pb.redirectErrorStream(true);
Process p = pb.start();
p.waitFor();
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String _temp = null;
List<String> line = new ArrayList<String>();
while ((_temp = in.readLine()) != null) {
// system.out.println("temp line: " + _temp);
line.add(_temp);
}
// system.out.println("result after command: " + line);
return line;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Hope this helps,

Fetch parameters from redirected url in OAuth2 in java

I need to use OAuth 2.0 for accessing user's data.
I have used glassfish security oauth 2 library to implement OAuth 2 client.
I am not sure how can I get code and state values after user granted permission to access the data.
ClientIdentifier clientIdentifier = new ClientIdentifier(clientId, secret);
OAuth2CodeGrantFlow.Builder builder =
OAuth2ClientSupport.authorizationCodeGrantFlowBuilder(clientIdentifier,
HOST_NAME + "/authorize",
HOST_NAME + "/token");
OAuth2CodeGrantFlow flow = builder
.scope("activity")
.redirectUri("http://example.com/#/")
.build();
String authorizationUri = flow.start();
System.out.println(authorizationUri);
String redirectedUrl = getFinalRedirectedUrl(authorizationUri);
System.out.print("Enter the authorization code: ");
String code = "";
String state = "";
try {
code = IN.readLine();
state = IN.readLine();
} catch (final IOException ex) {
throw new RuntimeException(ex);
}
final TokenResult result = flow.finish(code, state);
System.out.println("Access Token: " + result.getAllProperties());
}
For Now, I am taking code and status manually from the redirected url. How Can I automate it.
I tried
public static String getFinalRedirectedUrl(String url) {
String finalRedirectedUrl = url;
try {
HttpURLConnection connection;
do {
connection = (HttpURLConnection) new URL(finalRedirectedUrl).openConnection();
connection.setInstanceFollowRedirects(false);
connection.setUseCaches(false);
connection.setRequestMethod("GET");
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode >= 300 && responseCode < 400) {
String redirectedUrl = connection.getHeaderField("Location");
if (null == redirectedUrl) {
break;
}
finalRedirectedUrl = redirectedUrl;
} else
break;
} while (connection.getResponseCode() != HttpURLConnection.HTTP_OK);
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(finalRedirectedUrl);
return finalRedirectedUrl;
}
but it returns the login page.

Display HTTP Request Information - BlackBerry

How can I get the all HTTP request headers, method, the suffix of the connection, and all parameters that I added to the request?
Try something like this (I ran this code on a background thread, which I why I use UiApplication.invokeLater() to display results):
try {
ConnectionFactory factory = new ConnectionFactory(); // for OS 5.0+
factory.setPreferredTransportTypes(new int[] {
TransportInfo.TRANSPORT_TCP_WIFI,
TransportInfo.TRANSPORT_TCP_CELLULAR
});
// For OS < 5.0
//HttpConnection conn = (HttpConnection) Connector.open("http://www.google.com;interface=wifi");
HttpConnection conn = (HttpConnection) factory.getConnection("http://www.google.com").getConnection();
conn.setRequestProperty("sessionId", "ABCDEF0123456789");
final StringBuffer results = new StringBuffer();
String key = "";
int index = 0;
// loop over all the header fields, and record their values
while (key != null) {
key = conn.getHeaderFieldKey(index);
if (key != null) {
String value = conn.getHeaderField(key);
results.append(key + " = " + value + "\n\n");
}
index++;
}
results.append("method = " + conn.getRequestMethod() + "\n\n");
// we (should) know which request properties we've set, so we ask
// for them by name here
String sessionId = conn.getRequestProperty("sessionId");
results.append("sessionId = " + sessionId + "\n\n");
String url = conn.getURL();
results.append("URL = " + url);
// show the result on screen (UI thread)
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
textField.setText(results.toString());
}
});
} catch (IOException e) {
e.printStackTrace();
}

What is correct way to implement the HTTPConnection in Blackberry

I tired to connect my app with the remote server and pass few credentials to it, but i am always getting a same response from the server. I tried changing all the parameter value and other request header values that i am passing, but still i can't reach the exact solution. I need to you, whether am i using the correct way to ping with the server and to pass the values.
Below is the code that i am using , Please let me know if i have gone wrong somewhere.
// HttpServiceConnection.java
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.HttpsConnection;
import net.rim.device.api.system.DeviceInfo;
import com.beacon.bb.app.util.WSMConfig;
/**
* #author N********
*
*/
public class HttpServiceCommunication {
public HttpServiceCommunication() {
System.out.println("Http Service Communication Called");
}
public String sendHttpPost(String uri, String email, String uid,
String pass) throws Exception { // Hashtable header
String response = null;
// create the connection...
System.out.println("Url    " + uri);
HttpConnection _connection = null;
String params = null;
if (DeviceInfo.isSimulator()) {
params = ";deviceside=false";
} else {
params = ";deviceside=true;interface=wifi";
}
String URL = uri + params;
System.out.println("Connecting to Http Connection ");
try {
_connection = (HttpConnection) Connector.open(URL);
} catch(Exception e){
e.printStackTrace();
}
if (_connection != null) {
_connection.setRequestMethod(HttpConnection.POST);
System.out.println("After Request Method ");
_connection.setRequestProperty("User-Agent",
"Profile/MIDP-2.0 Configuration/CLDC-1.1");
_connection.setRequestProperty("Content-Language", "en-US");
_connection.setRequestProperty("Content-type", "application/json");
// setting header if any
// if (header != null) {
// for (Enumeration en = header.keys(); en.hasMoreElements();) {
// String key = (String) en.nextElement();
// String value = (String) header.get(key);
// _connection.setRequestProperty(key, value);
_connection.setRequestProperty("email", email);
//_connection.setRequestProperty("method","login");
_connection.setRequestProperty("uid", uid);
_connection.setRequestProperty("password", pass);
//_connection.setRequestProperty("uid", uid);
// }
// }
System.out.println("Open Output Stream  ");
// System.out.println("Data is     "+data);
OutputStream _outputStream = _connection.openOutputStream();
//System.out.println("Writing data  ");
//_outputStream.write(data);
// _outputStream.flush(); // Optional, getResponseCode will flush
// Getting the response code will open the connection, send the
// request, and read the HTTP response headers.
// The headers are stored until requested.
try {
System.out.println("Response Code :" + _connection.getResponseCode());
int rc = _connection.getResponseCode();
System.out.println("Response Code :" + rc);
System.out.println("Response Code   :" + rc + " if HTTP OK    :"
+ (rc == HttpConnection.HTTP_OK));
if (rc == HttpConnection.HTTP_FORBIDDEN) {
System.out.println("FORBIDDEN");
response = WSMConfig.NOT_AUTH;
} else if (rc != HttpConnection.HTTP_OK) {
response = WSMConfig.NOT_OK;
} else if (rc == HttpConnection.HTTP_OK) {
InputStream _inputStream = _connection.openInputStream();
final int MAX_LENGTH = 128;
byte[] buf = new byte[MAX_LENGTH];
int total = 0;
while (total < MAX_LENGTH) {
int count = _inputStream.read(buf, total, MAX_LENGTH
- total);
if (count < 0) {
break;
}
total += count;
}
response = new String(buf, 0, total);
//ByteBuffer bb = new ByteBuffer(_inputStream);
//response = bb.getString();
System.out.println("Response from Server   :" + response);
// close everything out
{
if (_inputStream != null)
try {
_inputStream.close();
} catch (Exception e) {
}
if (_outputStream != null)
try {
_outputStream.close();
} catch (Exception e) {
}
if (_connection != null)
try {
_connection.close();
} catch (Exception e) {
}
}
}
else {
response = WSMConfig.SERVER_ERROR;
}
}catch(Exception e){
e.printStackTrace();
}
}
//System.out.println("Response :" + response);
return response;
}
}
I am getting a response like {"code":0,"err":"Missing 'method'."}
Any Help is Appreciable....
Thanks
Try this out when you're wanting to pass data to the server:
//encode your data to send
URLEncodedPostData encoder = new URLEncodedPostData(null, false);
encoder.encode("email", email);
encoder.encode("method", "login");
encoder.encode("uid", uid);
encoder.encode("password", pass);
//Now you open up an output stream to write to the connection
OutputStream os = _connection.openOutputStream();
os.write(encoder.getBytes();
os.flush();
And then continue with the rest of your logic

Retriving url from webservice and how to connect to that url

i am new to black berry.i am doing one task,i have one webservice to show some url.i need to retrive it and connect to that url.i tried with two threads one is to retrive url and other is to connect to url which is in webservice but it shows nullpointer exception.please help me.
Thank You.
since you have not posted any code, it's very difficult to diagnose the problem. But look at the following code which tries to open an absolute url. This can be helpful.
Use this method for both of your connection (Web Service and URL returned from Web Service). Be sure to call this method in a separate thread otherwise it will freeze the UI.
public static ResponseBean sendRequestAndReceiveResponse(
String method, String absoluteURL, String bodyData, boolean readResponseBody)
throws IOException
{
ResponseBean responseBean = new ResponseBean();
HttpConnection httpConnection = null;
try
{
String formattedURL = absoluteURL + "deviceside=true;interface=wifi"; // If you are using WiFi
//String formattedURL = absoluteURL + "deviceside=false"; // If you are using BES
//String formattedURL = absoluteURL + "deviceside=true"; // If you are using TCP
if(DeviceInfo.isSimulator()) // if simulator is running
formattedURL = absoluteURL;
httpConnection = (HttpConnection) Connector.open(formattedURL);
httpConnection.setRequestMethod(method);
if (bodyData != null && bodyData.length() > 0)
{
OutputStream os = httpConnection.openOutputStream();
os.write(bodyData.getBytes("UTF-8"));
}
int responseCode = httpConnection.getResponseCode();
responseBean.setResponseCode(responseCode);
if (readResponseBody)
{
responseBean.setBodyData(readBodyData(httpConnection));
}
}
catch (IOException ex)
{
System.out.println("!!!!!!!!!!!!!!! IOException in NetworkUtil::sendRequestAndReceiveResponse(): " + ex);
throw ex;
}
catch(Exception ex)
{
System.out.println("!!!!!!!!!!!!!!! Exception in NetworkUtil::sendRequestAndReceiveResponse(): " + ex);
throw new IOException(ex.toString());
}
finally
{
if (httpConnection != null)
httpConnection.close();
}
return responseBean;
}
public static StringBuffer readBodyData(HttpConnection httpConnection) throws UnsupportedEncodingException, IOException
{
if(httpConnection == null)
return null;
StringBuffer bodyData = new StringBuffer(256);
InputStream inputStream = httpConnection.openDataInputStream();
byte[] data = new byte[256];
int len = 0;
int size = 0;
while ( -1 != (len = inputStream.read(data)) )
{
bodyData.append(new String(data, 0, len,"UTF-8"));
size += len;
}
if (inputStream != null)
{
inputStream.close();
}
return bodyData;
}

Resources