C# Code
var querystringData = new Dictionary<string, string>();
querystringData.Add("UserName", LocalSettings.UserName);
querystringData.Add("LoginId", LocalSettings.LoginId);
hubConnection = new HubConnection("http://...", querystringData);
How do I pass the Dictionary as queryString in Android
Platform.loadPlatformComponent( new AndroidPlatformComponent() );
String host = "http://....;
String qs = "";
//Instead of String I want to pass List/Dictionary
HubConnection connection = new HubConnection(host, qs, true, new ConsoleLogger());
HubProxy hub = connection.createHubProxy("calculatorHub");
Referring http://whathecode.wordpress.com/2014/03/20/getting-started-with-the-java-signalr-sdk/ as the base
The C# client basically turns the dictionary you pass to "&{key}={value}" for each KeyValuePair. So you should be able to do the same on your side and pass to the HubConnection ctor as queryString.
Here my code, works perfect
String server = URL + "signalr";
String CONNECTION_QUERYSTRING ="Bearer=" + BaseActivity.getToken(activity).getAccess_token();
HubConnection connection = new HubConnection(server, CONNECTION_QUERYSTRING, false, new Logger() {
#Override
public void log(String message, LogLevel level) {
System.out.println(message);
}
});
Related
After getting the following code to work reliably for a month or so, it stopped working reliably a couple of days ago. About half the time it returns a properly translated string and the other half of the time it returns one of the following two messages:
java.io.FileNotFoundException:
https://api.cognitive.microsoft.com/sts/v1.0/issueToken
java.net.UnknownHostException: Unable to resolve host
"api.microsofttranslator.com": No address associated with hostname
The timing of this problem's beginning coincided with the expiration of my free azure cognitive services account however I migrated to a pay-as-you-go account yesterday and the problem continues.
Why is this happening?
static class translateMessageX extends AsyncTask<String, Void, String>
{
//input string array of 3 items
//[0]is the message to be translated
//[1]is the from language i.e. "english"
//[2]is the to language i.e. "spanish"
//[3]"echo" or "received"
String retString;
String inString = null;
String messageType = null;
String URLHolder = ""; //hold the URL here while we are translating the text
#Override
protected String doInBackground(String... params)
{
inString = params[0];
String from = params[1];
String to = params[2];
messageType = params[3];
int urlStart = inString.indexOf("http");
if (!(urlStart == -1))
{
URLHolder = inString.substring(urlStart);
inString = inString.substring(0, urlStart -1);
}
else
{
URLHolder = "";
}
Integer mesChars = params[0].length();
Integer tCharsLeft = GlobalStuff.getTranslationsFromSP();
if (tCharsLeft > 0)
{
if (tCharsLeft < mesChars) //we charge for both 'echo' and 'received' translations
{
GlobalStuff.updateTranslationInventory(tCharsLeft * -1);
}
else
{
GlobalStuff.updateTranslationInventory(mesChars * -1);
}
GlobalStuff.notifyListeners(this, "#uui", "notused", "notused" );
try
{
Language fromLang = GlobalStuff.getLang(from);
Language toLang = GlobalStuff.getLang(to);
//retString = Translate.execute(inString, fromLang, toLang);
//String debugstr = "look at retStr";
String authenticationUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
HttpsURLConnection authConn = (HttpsURLConnection) new URL(authenticationUrl).openConnection();
authConn.setRequestMethod("POST");
authConn.setDoOutput(true);
authConn.setRequestProperty("Ocp-Apim-Subscription-Key", GlobalStuff.translateKey);
IOUtils.write("", authConn.getOutputStream(), "UTF-8");
String token = IOUtils.toString(authConn.getInputStream(), "UTF-8");
System.out.println(token);
// Using the access token to build the appid for the request url
String appId = URLEncoder.encode("Bearer "+token, "UTF-8");
String text = URLEncoder.encode(inString, "UTF-8");
String translatorTextApiUrl = String.format("https://api.microsofttranslator.com/v2/http.svc/Translate?appid=%s&text=%s&from=%s&to=%s", appId, text, fromLang, toLang);
HttpsURLConnection translateConn = (HttpsURLConnection) new URL(translatorTextApiUrl).openConnection();
translateConn.setRequestMethod("GET");
translateConn.setRequestProperty("Accept", "application/xml");
retString = IOUtils.toString(translateConn.getInputStream(), "UTF-8");
String debug = "look at retString";
}
catch (Exception e)
{
retString = e.toString();
}
}
else
{
retString = "OUT OF TRANSLATION CREDITS - " + inString;
}
return retString;
}
#Override
protected void onPostExecute(String result)
{
//rest of logic should be here??
String debug = "look at result";
String answer = extractTranslation(result);
.. . . .
Host not found looks like a simple connectivity error. These hosts do exist.
You can void the call to the token service by passing the key in the call to api.microsofttranslator.com directly:
https://cognitive.uservoice.com/knowledgebase/articles/1815385-api-translator-text-speech-using-the-api-key
That fixes one of the host not found problems, but not the other.
I would recommend though to not embed the key in the client application. It is safer to call the translator service from your own proxy service, where the proxy is able to safely identify your client as your client.
I am trying to use the different SIP port other than 5060.
I change the port of following code, but only the source port is changed.
The destination port of SIP server is still 5060.
// Create SIP transport. Error handling sample is shown
TransportConfig sipTpConfig = new TransportConfig();
sipTpConfig.setPort(Long.parseLong(port, 10));
/* Create transports. */
try {
ep.transportCreate(pjsip_transport_type_e.PJSIP_TRANSPORT_UDP, sipTpConfig);
}catch(Exception e){
System.out.println(e);
}
Does anyone have the idea how to do?
Thanks in advance!
You have to modify the account configuration:
final String acc_id = String.format(Locale.ENGLISH, "sip:%s#%s", username, domain);
final String registrar = String.format(Locale.ENGLISH, "sip:%s", domain);
final String proxy = String.format(Locale.ENGLISH, "sip:%s:%d;transport=%s;port=%d", domainip, port, protocol, port);
accCfg.setIdUri(acc_id);
accCfg.getRegConfig().setRegistrarUri(registrar);
AuthCredInfoVector creds = accCfg.getSipConfig().getAuthCreds();
creds.clear();
if (username.length() != 0) {
creds.add(new AuthCredInfo("Digest", "*", username, 0, password));
}
StringVector proxies = accCfg.getSipConfig().getProxies();
proxies.clear();
if (proxy.length() != 0) {
proxies.add(proxy);
}
accCfg.getNatConfig().setIceEnabled(true); // Enable ICE
lastRegStatus = null;
account.modify(accCfg);
I need to send custom headers in my android app, I'm using the servicestack plugin for android studio http://docs.servicestack.net/java-add-servicestack-reference
In the net.servicestack.client.JsonServiceClient class exists the field
public static Connection Filter GlobalRequestFilter, Can I use it for send custom headers? thank you
Yes, you can set HTTP Headers on the AndroidServiceClient instance with:
AndroidServiceClient client = new AndroidServiceClient(baseUrl);
client.RequestFilter = new ConnectionFilter() {
#Override
public void exec(HttpURLConnection conn) {
conn.setRequestProperty("X-header", "value");
}
};
Java 8:
client.GlobalRequestFilter = conn -> conn.setRequestProperty("X-header", "value");
Or globally to all Service Client requests with:
AndroidServiceClient.GlobalRequestFilter = new ConnectionFilter() {
#Override
public void exec(HttpURLConnection conn) {
conn.setRequestProperty("X-header", "value");
}
};
Java 8:
AndroidServiceClient.GlobalRequestFilter = conn ->
conn.setRequestProperty("X-header", "value");
I am developing chat app using smack libary. I have issue in group chat. In my app i am creating group and in that members are auto joined.i want to notify all user when i send message in group even if they had not initiated chat.My code is as follow in that i have place listener in init method but unable to receive message.
//Initialize
public void init(String userId, String pwd, Context context) throws SmackException.NotConnectedException {
this.mUserName = userId;
this.mPassWord = pwd;
this.mContext = context;
sessionManager = new SessionManager(context);
if (userId.contains("#")) {
this.mUserName = userId.split("#")[0];
}
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(mUserName, mPassWord);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setServiceName(XMPPCredential.SERVICE);
configBuilder.setHost(XMPPCredential.HOST);
configBuilder.setPort(XMPPCredential.PORT);
configBuilder.setResource("");
// configBuilder.setDebuggerEnabled(true);
mConnection = new XMPPTCPConnection(configBuilder.build());
PingManager pingManager = PingManager.getInstanceFor(mConnection);
pingManager.setPingInterval(300); // 2.5 min
pingManager.registerPingFailedListener(this);
mChatmanager.getInstanceFor(mConnection).addChatListener(this);
multiUserChatManager = MultiUserChatManager.getInstanceFor(mConnection);
mConnection.addAsyncStanzaListener(this, null);
mConnection.addSyncStanzaListener(this,null);
ReconnectionManager.getInstanceFor(mConnection).enableAutomaticReconnection();
mConnection.addConnectionListener(this);
// Connect with XMPP server
connectConnection(context);
}
Each MultiUserChat needs to add a Listener like this:
MultiUserChat muc = MultiUserChatManager.getInstanceFor(mConnection).getMultiUserChat( mucJid );
muc.addMessageListener(new MessageListener()...);
This is signalR hub code.
How to implement signalR hub client method having more than 5 parameters at android client side
public void SendToSpecific(string sSenderSuid, string sSenderName, string sMessage, object objImage, string stoDelimited, string sGroupSuid, long nPriority)
{
string[] arrDelimited = MDLIB.Global.ASGetDelimUnjoinedStrings(stoDelimited);
foreach (string grpEntitysuid in arrDelimited)
{
foreach (string entry in _connections.GetConnections(grpEntitysuid))
{
Clients.Client(entry).broadcastMessage(sSenderSuid, sSenderName, sMessage, objImage, sGroupSuid, DateTime.UtcNow, nPriority, grpEntitysuid);
}
}
}
I found solution .Actually It was simple
Subscription subscriptionBroadcastMessage = mHubProxy.subscribe(client_broadcastMessage);
subscriptionBroadcastMessage.addReceivedHandler(new Action<JsonElement[]>() {
#Override
public void run(JsonElement[] jsonElements) throws Exception {
System.out.print(jsonElements.toString());
String sSenderSuid = jsonElements[0].getAsString();
String sSenderName = jsonElements[1].getAsString();
String sMessage = jsonElements[2].getAsString();
}
}
});