Blackberry soap response - web-services

I am trying to consume .net webservices, and I can establish the connection. However this is the response I am getting:
[0.0] anyType{NewDataSet=anyType{Table=anyType{Card_ID_PK=2243; PAN=63369610009001016; Expiry_Date[0.0] =15/06/2015; Embossed_Name=IDL IG scheme;
I want them to split and display it as a table. I searched in google and I found some methods like split() but that can only delimit single character and also I need the way to remove the characters and use them as key value pair which is used for .
Here is my code for soap:
// TODO Auto-generated method stub
if (DeviceInfo.isSimulator()) {
URL = URL + ";deviceSide=true";
}
SoapObject rpc = new SoapObject(NAMESPACE, METHOD_NAME); //soap object to open the namespace and method name
rpc.addProperty("CH_ID","15");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = rpc;
System.out.println("envelope response"+envelope.bodyOut.toString());
envelope.dotNet = true;
envelope.encodingStyle = SoapSerializationEnvelope.XSD;
System.out.println("in soap");
envelope.setOutputSoapObject(rpc);
HttpTransport ht = new HttpTransport(URL);
ht.debug = true;
try {
System.out.println("int try");
ht.call(SOAP_ACTION, envelope);
System.out.println("int try");
SoapObject resultProperties = (SoapObject) envelope.getResponse();
System.out.println("IN TRY");
String res=resultProperties.getProperty(1).toString();
System.out.println("Response"+res);
String[] pattern={"{","}","anytype","Table",";"};
String replacement="";
String array=replaceall(res,pattern,replacement);
System.out.println(" array element:"+array[i]);
replace all method :
public String replaceall(String str, String[] pattern, String replacement)
{
if(str==null)
{
return "";
}
StringBuffer sb=new StringBuffer();
int index=-1;
String workingSource = str;
for(int i=0;i<pattern.length;i++)
{
while ((index = workingSource.indexOf(pattern[i])) != -1)
{
sb.append(workingSource.substring(0, index));
sb.append(replacement);
sb.append(workingSource.substring(index + pattern[i].length()));
workingSource = sb.toString();
sb.delete(0, sb.length());
}
}
return workingSource;
}
}

Related

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

MapReduce Hadoop - mapside joining the 2 data sets using customInputFormat

I am learning hadoop mapreduce framework ,i am trying to join 2 data sets have first record(Text) in the line as the Key , i tried to search in stackoverflow previous posts but nothing worked out.Here i am trying to customize the InputFormat and trying to join with the ID which is first record in the each line of data set.
My input file1:
cdd8dde3-0349-4f0d-b97a-7ae84b687f9c,Esther,Garner,4071 Haven Lane,Okemos,MI
81a43486-07e1-4b92-b92b-03d0caa87b5f,Timothy,Duncan,753 Stadium Drive,Taunton,MA
File2 :
cdd8dde3-0349-4f0d-b97a-7ae84b687f9c,517-706-9565,EstherJGarner#teleworm.us,Waskepter38,noL2ieghie,MasterCard,5305687295670850
81a43486-07e1-4b92-b92b-03d0caa87b5f,508-307-3433,TimothyDDuncan#einrot.com,Conerse,Gif4Edeiba,MasterCard,5265896533330445
**Driver class:**
conf.setInputFormat(CompositeInputFormat.class);
String strJoinStmt = CompositeInputFormat.compose("inner",
KeyValueLongInputFormat.class, dirEmployeesData, dirSalaryData);
conf.set("mapred.join.expr", strJoinStmt);
conf.setNumReduceTasks(0);
dirOutput.getFileSystem(conf).delete(dirOutput);
TextOutputFormat.setOutputPath(conf, dirOutput);
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(Text.class);
conf.setOutputFormat(TextOutputFormat.class);
**Custom RecordReader class:**
public class KeyValueLongLineRecordReader implements
RecordReader<Text, Text> {
private final LineRecordReader lineRecordReader;
private byte separator = (byte) ',';
private LongWritable dummyKey;
private Text innerValue;
public Class getKeyClass() {
return Text.class;
}
public Text createKey() {
return new Text("");
}
public Text createValue() {
return new Text();
}
public KeyValueLongLineRecordReader(Configuration job, FileSplit split)
throws IOException {
lineRecordReader = new LineRecordReader(job, split);
dummyKey = lineRecordReader.createKey();
innerValue = lineRecordReader.createValue();
String sepStr = job.get("key.value.separator.in.input.line", ",");
this.separator = (byte) sepStr.charAt(0);
}
public static int findSeparator(byte[] utf, int start, int length, byte sep) {
for (int i = start; i < (start + length); i++) {
if (utf[i] == sep) {
return i;
}
}
return -1;
}
/** Read key/value pair in a line. */
public synchronized boolean next(Text key, Text value)
throws IOException {
Text tKey = key;
Text tValue = value;
byte[] line = null;
int lineLen = -1;
if (!lineRecordReader.next(dummyKey, innerValue)) {
return false;
}
else
line = innerValue.getBytes();
lineLen = innerValue.getLength();
if (line == null)
return false;
int pos = findSeparator(line, 0, lineLen, this.separator);
if (pos == -1) {
tKey.set(new String(line, 0, lineLen));
tValue.set("");
} else {
int keyLen = pos;
byte[] keyBytes = new byte[keyLen];
System.arraycopy(line, 0, keyBytes, 0, keyLen);
int valLen = lineLen - keyLen - 1;
byte[] valBytes = new byte[valLen];
System.arraycopy(line, pos + 1, valBytes, 0, valLen);
tKey.set(new String(keyBytes));
tValue.set(valBytes);
}
return true;
}
}
**InputFormat class:**
public class KeyValueLongInputFormat extends
FileInputFormat<Text, Text> implements JobConfigurable {
private CompressionCodecFactory compressionCodecs = null;
#Override
public void configure(JobConf conf) {
compressionCodecs = new CompressionCodecFactory(conf);
}
protected boolean isSplitable(FileSystem fs, Path file) {
return compressionCodecs.getCodec(file) == null;
}
#Override
public RecordReader<Text, Text> getRecordReader(
InputSplit genericSplit, JobConf job, Reporter reporter)
throws IOException {
reporter.setStatus(genericSplit.toString());
return new KeyValueLongLineRecordReader(job, (FileSplit) genericSplit);
}
}
**Finally Mapper class:**
enter code here
public class MapperMapSideJoinLargeDatasets extends MapReduceBase implements
Mapper<Text, TupleWritable, Text, Text> {
Text txtKey = new Text("");
Text txtValue = new Text("");
#Override
public void map(Text key, TupleWritable value,
OutputCollector<Text, Text> output, Reporter reporter)
throws IOException {
if (value.toString().length() > 0) {
txtKey.set(key.toString());
String arrEmpAttributes[] = value.get(0).toString().split(",");
String arrDeptAttributes[] = value.get(1).toString().split(",");
txtValue.set(arrEmpAttributes[1].toString() + "\t"
+ arrEmpAttributes[2].toString() + "\t"
+ arrDeptAttributes[0].toString());
output.collect(txtKey, txtValue);
}
}
In the logs Map input records is 0.No output can be seen on hdfs .Someone please help me to understand this issue. Thanks
The problem lies in the Driver class where in InputFormat mentioned as KeyValueLongInputFormat.class in the strJoinStmt property which actually works for LongWritable key and Text value. Instead KeyValueTextInputFormat.class can be used when both the key and value are of Text type.As the input is comma separated file, also specify a custom delimiter as comma by setting a property in the job's configuration object as follows in the Driver class.conf.set("key.value.separator.in.input.line",",");
For Complete details please check the below example:
https://github.com/sudha-pn/CompositeInputFormat

Getting org.xmlpull.v1.XmlPullParserException for SOAP connection in BlackBerry

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.

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;
}
}
}
}