📄 httptransportagent.java
字号:
//# Log.debug("[HTTPTransportAgent] we have a working conifg!");
//# String options = BlackberryHelper.getOptions(i);
//# Log.debug("[sendMessage] Using BlackBerry Options: " + options);
//# url = requestURL + options;
//# } else if (BlackberryHelper.isOkToUseConfig(i)) {
//# String options = BlackberryHelper.getOptions(i);
//# Log.debug("[sendMessage] Using BlackBerry Options: " + options);
//# url = requestURL + options;
//# } else {
//# Log.debug("[HHTPTransportAgent] config " + i + " can not be used. should stop everything");
//# //i = NUM_RETRY-1;
//# throw new ConnectionDeniedException("config cannot be used!");
//# //TODO: stop stuff here
//# //break;
//# }
//#elif isBlackberry_plugin
//# if (BlackberryHelper.workingConfigHasBeenFound()) {
//# Log.debug("[HTTPTransportAgent] we have a working conifg!");
//# String options = BlackberryHelper.getOptions(i);
//# Log.debug("[sendMessage] Using BlackBerry Options: " + options);
//# url = requestURL + options;
//# } else if (BlackberryHelper.isOkToUseConfig(i)) {
//# String options = BlackberryHelper.getOptions(i);
//# Log.debug("[sendMessage] Using BlackBerry Options: " + options);
//# url = requestURL + options;
//# } else {
//# Log.debug("[HHTPTransportAgent] config " + i + " can not be used. should stop everything");
//# //i = NUM_RETRY-1;
//# throw new ConnectionDeniedException("config cannot be used!");
//# //TODO: stop stuff here
//# //break;
//# }
//#endif
Log.info("[sendMessage] url: [" + url + "]");
/*
* Emulating only cookie support
int jsIndex = url.indexOf("jsessionid");
if (jsIndex != -1) {
url = url.substring(0, jsIndex - 1);
}
*/
c = (HttpConnection) Connector.open(url, Connector.READ_WRITE, true);
//Request Configuration: Added ACCEPT ENCODING Parameter
setConfig(c, request.length);
}
private void writeRequest(byte[] request)
throws IllegalArgumentException, ConnectionNotFoundException,
SyncException {
for (int i=0; i<retryOnWrite; i++) {
try {
openConnection(request, i);
status = WRITE_REQUEST;
//Write the message to send into the stream
//forceBreakConnection();
os = c.openOutputStream();
//XXX if the mapping message is not sent due to network problem
//duplicated items arrive on the client
os.write(request);
Log.info("[sendMessage] message sent at attempt " + (i+1) + ", waiting for response.");
break;
} catch (IOException e) {
clear();
if (status == OPEN_CONNECTION) {
Log.error("[writeRequest.openConnection] Attempt n." + (i + 1) + " failed. Retrying...");
if (i == retryOnWrite - 1) {
//New Read Exception or New writeException
throw new SyncException(SyncException.CONN_NOT_FOUND, "Network problem: Cannot send the request to the server");
} else {
waitToConnect();
}
} else if (status == WRITE_REQUEST) {
Log.error("[writeRequest] Attempt n." + (i + 1) + " failed. Retrying...");
if (i == retryOnWrite - 1) {
//New Read Exception or New writeException
throw new WriteRequestException(SyncException.WRITE_SERVER_REQUEST_ERROR, "Network problem: Cannot send the request to the server");
} else {
waitToConnect();
}
}
}
}
}
private void waitToConnect() {
try {
long startTime = System.currentTimeMillis();
Log.info("Connection timer started");
Thread.sleep(CONNECTION_SLEEP_TIME);
long now = System.currentTimeMillis();
Log.info("Retrying after " + (now - startTime) + " msec");
} catch (InterruptedException ex) {
Log.error("Connection timer failed");
ex.printStackTrace();
}
}
private byte[] readResponse(byte[] data) throws SyncException {
status = READ_RESPONSE;
try {
is = c.openInputStream();
//Insert here the broken connection test code
Log.info("[sendMessage] message received");
logHeaders(c);
long len = c.getLength();
Log.info("HttpResponse length: " + len);
// Check http error
int httpCode = c.getResponseCode();
Log.info("[sendMessage] Http Code: " + httpCode);
if (httpCode != c.HTTP_OK) {
//throw new SyncException(SyncException.SERVER_ERROR,
Log.error("Http error: code=[" + httpCode + "] msg=[" + c.getResponseMessage() + "]");
String msg = " Http error: code=[" + httpCode + "] msg=[" + c.getResponseMessage() + "]";
throw new SyncException(SyncException.CONN_NOT_FOUND, msg);
} else {
responseDate = c.getHeaderField(PROP_DATE);
Log.info("[sendMessage] Date from server: " + responseDate);
contentType = c.getHeaderField(PROP_CONTENT_ENCODING);
Log.info("[sendMessage] Encoding Response Type from server: " + contentType);
uncompressedLength = c.getHeaderFieldInt(PROP_UNCOMPR_LENGHT, -1);
Log.info("[sendMessage] Uncompressed Content Lenght: " + uncompressedLength);
if ((len == -1) && (responseDate == null) && (contentType == null)) {
Log.error("Http error: httpCode=[" + httpCode + "] msg=[" + c.getResponseMessage() + "] len=[" + len + "] date=[" + responseDate + "] contentType=[" + contentType + "]");
Log.error("[sendMessage] Error in http response, not reading stream...");
} else {
data = StreamReaderFactory.getStreamReader(contentType).readStream(is, (int) len);
Log.debug("data.length: " + data.length);
if ((uncompressedLength != -1) && (data.length != uncompressedLength)) {
// try again but use uncompressed mode
//enableCompression = false;
//continue;
Log.error("[sendMessage] Error reading compressed response");
Log.error("[sendMessage] Trying with uncompressed.");
throw new CompressedSyncException("Error reading compressed response");
}
Log.info("[sendMessage] Stream correctly processed.");
//#ifdef isBlackberry
//# if (BlackberryHelper.getSavedConfigID()<0) {
//# BlackberryHelper.saveCurrentConfig();
//# }
//#elif isBlackberry_plugin
//# if (BlackberryHelper.getSavedConfigID()<0) {
//# BlackberryHelper.saveCurrentConfig();
//# }
//#endif
/*
if (UIController.WAP_SIMULATION) {
Log.debug("##### WAP SIMULATION with compression error#######");
UIController.WAP_SIMULATION = false;
throw new CompressedSyncException("Error reading compressed response");
}*/
status = RESPONSE_CORRECTLY_PROCESSED;
}
}
} catch (ConnectionDeniedException e) {
String msg = "[HttpTransportAgent] user denied connection" + e.toString();
Log.error(msg);
throw new SyncException(SyncException.CONNECTION_BLOCKED_BY_USER, msg);
} catch (IOException ioe) {
String msg = "HttpTransportAgent: error reading server response --> " + ioe.toString();
Log.error(msg);
//New Read Exception or New writeException
throw new ReadResponseException(SyncException.READ_SERVER_RESPONSE_ERROR, "Network problem: Cannot read the server response");
}
return data;
}
/**
* Simulate connections broken when the final message is sent in test mode
*/
/*private void breakConnection() throws IOException {
counter++;
Log.info("Counter=" + counter);
Log.info("Retries on read: " + retryOnWrite);
if (counter==4) {
counter=0;
Log.info("Brute Force Sync Death!! Counter=" + counter);
if (status==READ_RESPONSE) {
throw new IOException("Network Error: cannot read response!!");
} else {
throw new IOException("Network Error: cannot write request!!");
}
}
}*/
/**
* Simulate immediate connection broken
*/
/*private void forceBreakConnection() throws IOException {
throw new IOException("Brute Force Connection Death!!");
}*/
/**
* Add request properties for the configuration, profiles,
* and locale of this system.
* @param c current HttpConnection to receive user agent header
*/
private void setConfig(HttpConnection c, int length) throws IOException {
String ua = this.userAgent;
String locale = System.getProperty(PROP_MICROEDITION_LOCALE);
if (ua == null) {
// Build the default user agent
String conf = System.getProperty(PROP_MICROEDITION_CONFIGURATION);
String prof = System.getProperty(PROP_MICROEDITION_PROFILES);
ua = "Profile/" + prof + " Configuration/" + conf;
}
c.setRequestMethod(HttpConnection.POST);
c.setRequestProperty("Connection", "Close");
c.setRequestProperty(PROP_CONTENT_TYPE, "application/vnd.syncml+xml");
c.setRequestProperty(PROP_CONTENT_LENGTH, String.valueOf(length));
if (length == 0) {
Log.error("content length has been set to 0 !");
}
// workaround to avoid errors on server
// the client user agent must not be sent with User-Agent header
c.setRequestProperty(PROP_USER_AGENT, ua);
// we use Device-Agent for such an issue
c.setRequestProperty(PROP_DEVICE_AGENT, createDeviceAgent());
// If Set-Cookie header is set to empty value in http
// server response, in Nokia S60 3ed. FP1 devices the Application crashes
// It's due to a Symbian KVM bug.
// A specific workaround has been implemented: the client sends a specific header
// 'x-funambol-force-cookies' to force the server to set a 'Set-Cookie' header not empty.
if (forceCookies) {
c.setRequestProperty(PROP_FORCE_COOKIES, "true");
}
//Set Encoding and accepted properties: inflater or Gzip input Stream
if (enableCompression) {
c.setRequestProperty(PROP_ACCEPT_ENCODING, COMPRESSION_TYPE_GZIP);
Log.debug("Encoding Response Required from Client: " + COMPRESSION_TYPE_GZIP);
}
if (this.sizeThreshold != 0) {
c.setRequestProperty(PROP_SIZE_THRESHOLD,
String.valueOf(this.sizeThreshold));
}
if (locale != null) {
c.setRequestProperty(PROP_CONTENT_LANGUAGE, locale);
}
// FIX to support jsessionid in cookies
int jsIndex = requestURL.indexOf("jsessionid");
if (jsIndex != -1) {
String jsessionidString =
requestURL.substring(jsIndex, requestURL.length());
c.setRequestProperty("Cookie", jsessionidString.toUpperCase());
}
}
private void logHeaders(final HttpConnection c) throws IOException {
// debug section for reading http response headers
if (Log.getLogLevel() >= Log.INFO) {
StringBuffer sbh = new StringBuffer();
String tmp = "";
for (int h = 0; h < 12; h++) {
tmp = c.getHeaderFieldKey(h);
sbh.append("[").append(h).append("] - ").
append(tmp);
if ((tmp != null) && (!tmp.equals(""))) {
sbh.append(": ").append(c.getHeaderField(tmp)).append("\n");
} else {
sbh.append("\n");
}
}
Log.info("header: \n" + sbh.toString());
}
}
private String createDeviceAgent() {
StringBuffer sbAgent = new StringBuffer();
sbAgent.append(System.getProperty("microedition.platform"));
sbAgent.append(" ").append(System.getProperty("microedition.profiles"));
sbAgent.append(" ").append(System.getProperty(
"microedition.configuration"));
return sbAgent.toString();
}
private void clear() {
clearResponseStream();
clearRequestStream();
closeConnection();
}
private void clearRequestStream() {
if (os != null) {
try {
os.close();
os = null;
} catch (IOException ioe) {
ioe.printStackTrace();
Log.error("sendmessage: can't close output stream.");
}
}
}
private void clearResponseStream() {
if (is != null) {
try {
is.close();
is = null;
} catch (IOException ioe) {
ioe.printStackTrace();
Log.error("sendmessage: can't close input stream.");
}
}
}
private void closeConnection() {
if (c != null) {
try {
c.close();
c = null;
} catch (IOException ioe) {
ioe.printStackTrace();
Log.error("sendmessage: can't close connection.");
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -