Getting org.xmlpull.v1.XmlPullParserException for SOAP connection in BlackBerry - web-services

I am using ksoap2.jar in my application for webservice call.
While conneting, to the server it is giving the below error when i am testing using Wi-fi or simulator:
org.xmlpull.v1.XmlPullParserException: unexpected type (position:END_DOCUMENT null#1:0 in java.io.InputStreamReader#6111a1f1)
And when i am testing using SIM Card, it is throwing this error: java.io.InterruptedIOException: Local connection timed out after ~ 120000
I have written the below code for this webservice connection:
SoapObject rpc = new SoapObject(serviceNamespace, methodName);
rpc.addProperty("UserID", "1");
rpc.addProperty("UserName", "xyz");
rpc.addProperty("ContactNo", "9014567890");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = rpc;
envelope.dotNet = true;
envelope.encodingStyle = SoapSerializationEnvelope.ENC;
HttpTransport ht = new HttpTransport(serviceUrl + getConnectionString().trim());
ht.debug = true;
System.out.println("debug true ------- ");
ht.setXmlVersionTag(" version=\"1.0\" encoding=\"UTF-8\"?>");
SoapObject response = null;
try
{
ht.call(soapAction, envelope);
response = (SoapObject )envelope.getResponse();
String resultbody = response.getProperty("updateUserDetailResult").toString();
}
catch(org.xmlpull.v1.XmlPullParserException ex2){
resultLbl.setText(ex2.toString());
}
catch(Exception ex){
String bah = ex.toString();
resultLbl.setText(bah);
}
/**
* Looks through the phone's service book for a carrier provided BIBS network
*
* #return The uid used to connect to that network.
*/
private static String getCarrierBIBSUid()
{
net.rim.device.api.servicebook.ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++)
{
if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
if (records[currentRecord].getName().toLowerCase().indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
return null;
}
/**
* Getting the connection string based on the connection
* #return
*/
public static String getConnectionString()
{
String connectionString = null;
// Wifi is the preferred transmission method
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
connectionString = ";interface=wifi";
}
// Is the carrier network the only way to connect?
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT)
{
String carrierUid = getCarrierBIBSUid();
if (carrierUid == null)
{
// Has carrier coverage, but not BIBS. So use the carrier's TCP
// network
connectionString = ";deviceside=true";
}
else
{
// otherwise, use the Uid to construct a valid carrier BIBS
// request
connectionString = ";deviceside=false;connectionUID=" + carrierUid + ";ConnectionType=";
}
}
// Check for an MDS connection instead (BlackBerry Enterprise Server)
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS)
{
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid bugging the user
// unnecssarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE)
{
}
// In theory, all bases are covered so this shouldn't be reachable.
else
{
connectionString = ";deviceside=true";
}
return connectionString;
}
I am using the preverified ksoap jar file(ksoap2-j2me-core-prev-2.1.2.jar).
I am not getting exactly where it is going wrong. I have searched in the forum but did not get the proper solution.
Thanks.

Related

Switch WiFi mode from AP to STA

I'm working on project with ESP32-S2-Saola-1M board in C/C++ via ESP-IDF framework. At the beginning I initialize a Wi-Fi in an AP mode and starts the HTTP WebServer to get WiFi data from user through browser. After the user saves his Wi-Fi data (SSID and Passwd) throught page, the
HTTP server should shut down and Wi-Fi switch from AP mode to STA mode - connect to user's Wi-Fi. I have problem with this part. I don't know how to solve this elegantly and in principle correctly. So can someone describe me any solutions or better ideas please?
I thought of using method with while cycle and POST handler. After the data comes from page via POST request, handler saves them and set some bool property (e.g. hasData in code below) to true and while cycle in method breaks/stops and other code in application can continue. Something like semaphore. Simply:
start Wi-Fi (AP mode)
start webserver
wait until user sends his Wi-Fi data
stop webserver
stop Wi-Fi AP mode -> switch to STA mode
next actions... (measure, send data out, deep sleep etc.)
Pseudo code:
bool hasData = false;
static esp_err_t postHandler(httpd_req_t *request)
{
.
. //saves data from POST request
.
hasData = true;
return ESP_OK;
}
void waitForUser(void)
{
while(hasData != true) {
//just wait
}
}
static const httpd_uri_t postData = {
.uri = "/connection",
.method = HTTP_POST,
.handler = postHandler,
.user_ctx = NULL
};
static httpd_handle_t start_webserver(void)
{
httpd_handle_t server = NULL;
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
if (httpd_start(&server, &config) == ESP_OK) {
httpd_register_uri_handler(server, &postData);
return server;
}
return NULL;
}
void stop_webserver(httpd_handle_t server)
{
if (server) {
httpd_stop(server);
}
}
void wifiAPInit(void)
{
.
. //Initialize wifi config for AP mode and start wifi
.
}
void app_main(void)
{
.
. //Initialize NVS and others...
.
httpd_handle_t server = NULL;
wifiAPinit();
server = start_webserver();
waitForUser();
stop_webserver(server);
.
. // start Wifi in STA mode and continue...
.
}
Is this principle correct?
Thanks for advice!
By far the easiest approach is to just reboot (esp_restart()) after saving new configuration.
Then select the right mode after reading the configuration on boot.
void app_main()
{
// init NVS
// load configuration from NVS
if (config.wifiSSID.empty()) {
startAPmode();
} else {
startSTAmode(config.wifiSSID, config.wifiPassword);
}
start_webserver();
// etc ...
}
You can use Both Sta and Ap at the same time
void connectSTA(char *ssid, char *pass)
{
wifi_config_t wifi_config;
memset(&wifi_config, 0, sizeof(wifi_config));
strcpy((char *)wifi_config.sta.ssid, said);
strcpy((char *)wifi_config.sta.password, pass);
esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config);
}
void connectAP()
{
wifi_config_t wifi_config =
{
.ap = {
.ssid = "my esp32",
.password = "P#ssword",
.max_connection = 4,
.authmode = WIFI_AUTH_WPA_WPA2_PSK}};
esp_wifi_set_config(ESP_IF_WIFI_AP, &wifi_config);
}
void wifiInit(void *params)
{
ESP_ERROR_CHECK(nvs_flash_init());
tcpip_adapter_init();
ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL));
nvs_handle_t nvs;
nvs_open("wifiCreds", NVS_READWRITE, &nvs);
size_t ssidLen, passLen;
char *ssid = NULL, *pass = NULL;
if (nvs_get_str(nvs, "ssid", NULL, &ssidLen) == ESP_OK)
{
if (ssidLen > 0)
{
ssid = malloc(ssidLen);
nvs_get_str(nvs, "ssid", ssid, &ssidLen);
}
}
if (nvs_get_str(nvs, "pass", NULL, &passLen) == ESP_OK)
{
if (passLen > 0)
{
pass = malloc(passLen);
nvs_get_str(nvs, "pass", pass, &passLen);
}
}
wifi_init_config_t wifi_init_config = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&wifi_init_config));
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_APSTA));
connectAP();
if (ssid != NULL && pass != NULL)
{
connectSTA(ssid, pass);
}
ESP_ERROR_CHECK(esp_wifi_start());
}

Trying to understand a parsing error when making an HTTP request with C++ on ESP32

I'm attempting to do an HTTPS PUT from C++ on an ESP-EYE. I started with the C esp_https_example code and had that working with the same PEM and URL. I started to transition to using this from C++ as part of a project that is primarily written in C++. My call looks like:
static const char *URL = "https://signal.unexpectedeof.casa/on-air";
void https_with_url(void)
{
esp_http_client_config_t* config = (esp_http_client_config_t*)calloc(sizeof(esp_http_client_config_t), 1);
config->url = URL;
config->cert_pem = unexpectedeof_casa_root_cert_pem_start;
config->event_handler = _http_event_handler;
esp_http_client_handle_t client = esp_http_client_init(config);
esp_http_client_set_method(client, HTTP_METHOD_PUT);
esp_err_t err = esp_http_client_perform(client);
if (err == ESP_OK) {
ESP_LOGI(TAG, "HTTPS Status = %d, content_length = %d",
esp_http_client_get_status_code(client),
esp_http_client_get_content_length(client));
} else {
ESP_LOGE(TAG, "Error perform http request %s", esp_err_to_name(err));
}
esp_http_client_close(client);
esp_http_client_cleanup(client);
}
I believe the URL I'm providing isn't being copied or initialized correctly resulting in a url parsing error. When the function https_with_url is called I get this error:
E (13593) esp-tls: couldn't get hostname for :signal.unexpectedeof.casa:
E (13593) esp-tls: Failed to open new connection
E (13603) TRANS_SSL: Failed to open a new connection
E (13603) HTTP_CLIENT: Connection failed, sock < 0
E (13613) HTTPS_HANDLING: Error perform http request ESP_ERR_HTTP_CONNECT
I (13623) HTTPS_HANDLING: HTTP_EVENT_DISCONNECTED
I (13623) HTTPS_HANDLING: HTTP_EVENT_DISCONNECTED
Since I'm using C++ but the parse happens in the esp-idf C code I thought maybe I'm not passing the data correctly, but haven't made much progress. Switching from an inline string for the URL to the character array shown didn't make a difference.
esp-idf version 4.1.
Ended up being that I didn't handle the wifi event properly before the request was sent.
static void wifi_event_handler(void* arg, esp_event_base_t event_base,
int32_t event_id, void* event_data)
{
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
esp_wifi_connect();
} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
if (s_retry_num < EXAMPLE_ESP_MAXIMUM_RETRY) {
esp_wifi_connect();
xEventGroupClearBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
s_retry_num++;
ESP_LOGI(LOGTAG, "retry to connect to the AP");
}
ESP_LOGI(LOGTAG,"connect to the AP fail");
} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
ESP_LOGI(LOGTAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
s_retry_num = 0;
xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
}
}
void wifi_init_sta(void)
{
s_wifi_event_group = xEventGroupCreate();
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
esp_netif_create_default_wifi_sta();
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL));
ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL));
wifi_config_t wifi_config = { };
strcpy((char*)wifi_config.sta.ssid, CONFIG_ESP_WIFI_SSID);
strcpy((char*)wifi_config.sta.password, CONFIG_ESP_WIFI_PASSWORD);
ESP_LOGI(LOGTAG, "Setting WiFi configuration SSID %s...", wifi_config.sta.ssid);
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) );
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config) );
ESP_ERROR_CHECK(esp_wifi_start() );
ESP_LOGI(LOGTAG, "wifi_init_sta finished.");
}
Examples of this are in the esp-idf github repo under examples/protocols/wifi.

Asmx Web Service Basic Authentication in Asp.net Core Web Application

I created a Asmx Web service and host it in IIS, in MVC, I could call it from below code:
BasicWebService.WebService1 client = new BasicWebService.WebService1();
client.Credentials = new System.Net.NetworkCredential("user", "pwd","domain");
string result = client.HelloWorld();
But, I failed to mark it work under Asp.net Core.
Here is the code what I have tried.
ServiceReference1.WebService1SoapClient client = new ServiceReference1.WebService1SoapClient(ServiceReference1.WebService1SoapClient.EndpointConfiguration.WebService1Soap);
client.ClientCredentials.UserName.UserName = "xx";
client.ClientCredentials.UserName.Password = "xx";
//string USER = "xx";
//string PASSWORD = "xx";
//string Domain = "xx";
//NetworkCredential netCredential = new NetworkCredential(USER, PASSWORD,Domain);
////client.Credentials = new System.Net.NetworkCredential("xx", "xx", "xx");
//client.ClientCredentials.Windows.ClientCredential = netCredential;// netCredential.GetCredential(new Uri("http://localhost/WCFBasicSecurity/WebService1.asmx"), "Basic");
ServiceReference1.HelloWorldResponse result =client.HelloWorldAsync().Result;
Got solution from GitHub, thanks for the suggestion from hongdai. Modify the generated reference.cs with below:
public WebService1SoapClient(EndpointConfiguration endpointConfiguration) :
base(WebService1SoapClient.GetBindingForEndpoint(endpointConfiguration), WebService1SoapClient.GetEndpointAddress(endpointConfiguration))
{
this.Endpoint.Name = endpointConfiguration.ToString();
this.ChannelFactory.Credentials.UserName.UserName = "xx\xx";
this.ChannelFactory.Credentials.UserName.Password = "xxxx";
ConfigureEndpoint(this.Endpoint, this.ClientCredentials);
}
private static System.ServiceModel.Channels.Binding GetBindingForEndpoint(EndpointConfiguration endpointConfiguration)
{
if ((endpointConfiguration == EndpointConfiguration.WebService1Soap))
{
//Transport Security
System.ServiceModel.BasicHttpBinding result = new System.ServiceModel.BasicHttpBinding(System.ServiceModel.BasicHttpSecurityMode.Transport);
result.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Basic;
result.MaxBufferSize = int.MaxValue;
result.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max;
result.MaxReceivedMessageSize = int.MaxValue;
result.AllowCookies = true;
return result;
}
if ((endpointConfiguration == EndpointConfiguration.WebService1Soap12))
{
System.ServiceModel.Channels.CustomBinding result = new System.ServiceModel.Channels.CustomBinding();
System.ServiceModel.Channels.TextMessageEncodingBindingElement textBindingElement = new System.ServiceModel.Channels.TextMessageEncodingBindingElement();
textBindingElement.MessageVersion = System.ServiceModel.Channels.MessageVersion.CreateVersion(System.ServiceModel.EnvelopeVersion.Soap12, System.ServiceModel.Channels.AddressingVersion.None);
result.Elements.Add(textBindingElement);
System.ServiceModel.Channels.HttpTransportBindingElement httpBindingElement = new System.ServiceModel.Channels.HttpTransportBindingElement();
httpBindingElement.AllowCookies = true;
httpBindingElement.MaxBufferSize = int.MaxValue;
httpBindingElement.MaxReceivedMessageSize = int.MaxValue;
result.Elements.Add(httpBindingElement);
return result;
}
throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration));
}
private static System.ServiceModel.EndpointAddress GetEndpointAddress(EndpointConfiguration endpointConfiguration)
{
if ((endpointConfiguration == EndpointConfiguration.WebService1Soap))
{
return new System.ServiceModel.EndpointAddress("https://localhost/WCFBasicSecurity/WebService1.asmx");
//return new System.ServiceModel.EndpointAddress("http://localhost/WCFBasicSecurity/WebService1.asmx");
}
if ((endpointConfiguration == EndpointConfiguration.WebService1Soap12))
{
return new System.ServiceModel.EndpointAddress("http://localhost/WCFBasicSecurity/WebService1.asmx");
}
throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration));
}
Reference:https://github.com/dotnet/wcf/issues/1812

Is there any way to delete the index of only one row in solr using solrj

I have made a java apllication which can index my last row (which is what I wabt)
But now I ask Is there any wa yo deete the index of this role! Can you give me directions how to do that or maybe simple code to change my code?
;
public class indexSolr {
private Connection conn = null;
private static HttpSolrServer server;
private Collection docs = new ArrayList();
private int _totalSql = 0;
private long _start = System.currentTimeMillis();
public static void main(String[] args) throws SolrServerException, IOException, SQLException
{ String url = "http://localhost:8983/solr/db";
indexSolr idxer = new indexSolr(url);
idxer.doSqlDocuments();
idxer.endIndexing();
}
private void doSqlDocuments() throws SQLException {
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/biz_cat",
"postgres", "pos");
java.sql.Statement st = null;
st = conn.createStatement();
ResultSet rs = st.executeQuery("select * from pl_biz order by id DESC LIMIT 1");
while (rs.next()) {
SolrInputDocument doc = new SolrInputDocument();
Integer id = rs.getInt("id");
String name = rs.getString("name");
String midname = rs.getString("midname");
String lastname = rs.getString("lastname");
String frlsname = rs.getString("frlsname");
String biz_subject = rs.getString("biz_subject");
String company_type = rs.getString("company_type");
String obshtina = rs.getString("obshtina");
String main_office_town = rs.getString("main_office_town");
String address = rs.getString("address");
String role = rs.getString("role");
String country = rs.getString("country");
String nace_code = rs.getString("nace_code");
String nace_text = rs.getString("nace_text");
String zip_code = rs.getString("zip_code");
String phone = rs.getString("phone");
String fax = rs.getString("fax");
String email = rs.getString("email");
String web = rs.getString("web");
String location = rs.getString("location");
String geohash = rs.getString("geohash");
Integer popularity = rs.getInt("popularity");
doc.addField("id", id);
doc.addField("name", name);
doc.addField("midname", midname);
doc.addField("lastname", lastname);
doc.addField("frlsname", frlsname);
doc.addField("biz_subject", biz_subject);
doc.addField("company_type", company_type);
doc.addField("obshtina", obshtina);
doc.addField("main_office_town", main_office_town);
doc.addField("address", address);
doc.addField("role", role);
doc.addField("country", country);
doc.addField("nace_code", nace_code);
doc.addField("nace_text", nace_text);
doc.addField("zip_code", zip_code);
doc.addField("phone", phone);
doc.addField("fax", fax);
doc.addField("email", email);
doc.addField("web", web);
doc.addField("location", location);
doc.addField("geohash", geohash);
doc.addField("popularity", popularity);
docs.add(doc);
++_totalSql;
if (docs.size() > 1) {
// Commit within 5 minutes.
UpdateResponse resp = server.add(docs);
System.out.println (resp);
if (resp.getStatus() != 0) {
log("Some horrible error has occurred, status is: " +
resp.getStatus());
}
docs.clear();
}
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally {
if (conn != null) {
conn.close();
}
}
}
private void endIndexing() throws IOException, SolrServerException {
if (docs.size() > 0) { // Are there any documents left over?
server.add(docs, 300000); // Commit within 5 minutes
}
try
{
server.commit();
}
catch (Exception ex)
{
ex.printStackTrace();
}
long endTime = System.currentTimeMillis();
log("Total Time Taken: " + (endTime - _start) +
" milliseconds to index " + _totalSql +
" SQL rows" );
}
private indexSolr(String url) throws IOException, SolrServerException {
// Create a multi-threaded communications channel to the Solr server.
try {
server = new HttpSolrServer(url);
server.setSoTimeout(1000); // socket read timeout
server.setConnectionTimeout(1000);
server.setMaxRetries(1);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
That's all you need to do to delete the index of a row with id for example 30682 from solr
SolrServer solrServer;
String url = "http://localhost:8983/solr/db";
solrServer = new HttpSolrServer(url);
solrServer.deleteByQuery("id:30682");
solrServer.commit();
System.out.println("index deleted");
I Hope it helps someone

List of windows users remotely

I would like to know how to retrieve the list of users that are logged onto a Remote machine. I can do it with qwinsta /server:xxxx, but would like to do it in C#.
check out wmi in .net under system.management.
something like:
ConnectionOptions conn = new ConnectionOptions();
conn.Authority = "ntdlmdomain:NAMEOFDOMAIN";
conn.Username = "";
conn.Password = "";
ManagementScope ms = new ManagementScope(#"\\remotecomputer\root\cimv2", conn);
ms.Connect();
ObjectQuery qry = new ObjectQuery("select * from Win32_ComputerSystem");
ManagementObjectSearcher search = new ManagementObjectSearcher(ms, qry);
ManagementObjectCollection return = search.Get();
foreach (ManagementObject rec in return)
{
Console.WriteLine("Logged in user: " + rec["UserName"].ToString());
}
You may not need the ConnectionOptions...
I ended up using the qwinsta /server:server1 command from C# -- it was much easier
thanks Ken
All this checks all 8 servers at the same time -- I put the result in sql server
but you can do what ever you want
query_citrix.bat script
cd C:.......\bin\citrix_boxes
qwinsta -server:servername or ip > servername.txt
string sAppCitrixPath = Application.StartupPath.ToString() + "\\citrix_boxes\\";
//Run Script for current citrix boxes
Process proc = new Process();
ProcessStartInfo si = new ProcessStartInfo();
si.FileName = sAppCitrixPath + "query_citrix.bat";
proc.StartInfo = si;
proc.Start();
proc.WaitForExit();
int exitCode = proc.ExitCode;
proc.Close();
if (exitCode == 0)
{
//Execute update who is on the Citrix_Boxes Currently
DirectoryInfo dic = new DirectoryInfo(sAppCitrixPath);
FileInfo[] fic = dic.GetFiles("*.txt");
for (int i = 0; i < fic.Length; i++)
{
ParseQWinStaServerFile(fic[i].FullName.ToString(), fic[i].Name.ToString().ToUpper().Replace(".TXT",""));
File.Delete(fic[i].FullName.ToString());
}
}
private void ParseQWinStaServerFile(string sLocation,string sServer)
{
using (StreamReader sr = File.OpenText(sLocation))
{
string sRecord = String.Empty;
char[] cSep = new char[] {' '};
bool bFirst = true;
while ((sRecord = sr.ReadLine()) != null)
{
if (bFirst == false)
{
string[] items = sRecord.Split(cSep, StringSplitOptions.RemoveEmptyEntries);
//Make sure all columns are present on the split for valid records
if (sRecord.Substring(19, 1) != " ") // check position of user id to see if it's their
{
//Send the user id and server name where you want to.
//here is your user
id = items[1].ToString().ToLower().Trim()
//here is your server
};
}
else
{
bFirst = false;
}
}
}
}