Using Smack: login("foo", "bar") gives "Not connected to server" exception - xmpp

I´m so sorry about this noob question, in my application I use a button to send a friend request, the other person accept it and it works fine, my problem is, when I want to delete a contact I got FATAL EXCEPTION: main java.lang.IllegalStateException: Not connected to server.
The error is in this line
connection.login("113", "AA");
This is my code, I dont have any idea if this code works :(, can someone help me please?
ConnectionConfiguration connConfig = new ConnectionConfiguration(
"xxx.xxx.x.xx", 5222, "xxx.xxx.x.xx");
XMPPConnection connection = new XMPPConnection(connConfig);
SharedPreferences phoneNo3 = this.getSharedPreferences("phonef", MODE_PRIVATE);
String username = phoneNo3.getString("phonef", "");
SharedPreferences conts = this.getSharedPreferences("contrass", MODE_PRIVATE);
String passwords = conts.getString("contrass", "");
try {
connection.login("113", "AA");
RosterPacket packet = new RosterPacket();
packet.setType(IQ.Type.SET);
RosterPacket.Item item = new RosterPacket.Item("laboral#xxx.xxx.x.xx", null);
item.setItemType(RosterPacket.ItemType.remove);
packet.addRosterItem(item);
connection.sendPacket(packet);
} catch (XMPPException ex) {
Log.e("XMPPClient", "[SettingsDialog] Failed to log in as " + username);
connection.disconnect();
}

You need to call connect() before login(String, String).

Related

Power BI REST API ExportToFileInGroup Not Working

I am able to programmatically log in to the PowerBI Client, gather my Workspaces as well as get a specific Report from a specific Workspace. I need to programmatically render that report to a .pdf or .xlsx file. Allegedly this is possible with the ExportToFileInGroup/ExportToFileInGroupAsync methods. I even created a very simple report without any parameters. I can embed this using the sample app from here. So that at least tells me that I have what I need setup in the backend. But it fails when I try to run the ExportToFileInGroupAsync method (errors below code.)
My Code is:
var accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(new string[] {
PowerBiScopes.ReadReport,
PowerBiScopes.ReadDataset,
});
var userInfo = await graphServiceClient.Me.Request().GetAsync();
var userName = userInfo.Mail;
AuthDetails authDetails = new AuthDetails {
UserName = userName,
AccessToken = accessToken,
};
var credentials = new TokenCredentials($"{accessToken}", "Bearer");
PowerBIClient powerBIClient = new PowerBIClient(credentials);
var groups = await powerBIClient.Groups.GetGroupsAsync();
var theGroup = groups.Value
.Where(x => x.Name == "SWIFT Application Development")
.FirstOrDefault();
var groupReports = await powerBIClient.Reports.GetReportsAsync(theGroup.Id);
var theReport = groupReports.Value
.Where(x => x.Name == "No Param Test")
.FirstOrDefault();
var exportRequest = new ExportReportRequest {
Format = FileFormat.PDF,
};
string result = "";
try {
var response = await powerBIClient.Reports.ExportToFileInGroupAsync(theGroup.Id, theReport.Id, exportRequest);
result = response.ReportId.ToString();
} catch (Exception e) {
result = e.Message;
}
return result;
It gets to the line in the try block and then throws the following errors:
An error occurred while sending the request.
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host..
UPDATE
Relating to #AndreyNikolov question, here is our Embedded capacity:
After this was implemented, no change. Same exact error.
Turns out the issue was on our side, more specifically, security/firewall settings. Here is the exact quote from our networking guru.
"After some more investigation we determined that our firewall was causing this issue when it was terminating the SSL connection. We were able to add a bypass for the URL and it is now working as expected."

Notification message sent thru pinpoint does not reach the Mobile

Based on the link I tried tried working and here is the code I tried out
public static void SendNotification2(String appid, String pinpointEndpointId){
try {
GetEndpointRequest getEndpointRequest = new GetEndpointRequest()
.withApplicationId(appid)
.withEndpointId(pinpointEndpointId);
AmazonPinpoint pinpoint = AmazonPinpointClientBuilder.standard().withRegion(Regions.US_EAST_1).build();
GetEndpointResult endpointResult = pinpoint.getEndpoint(getEndpointRequest);
EndpointResponse endpointResponse = endpointResult.getEndpointResponse();
Map<String, String> data = new HashMap<String, String>();
data.put("message", "test");
DirectMessageConfiguration directMessageConfiguration =
new DirectMessageConfiguration().withGCMMessage(new GCMMessage().withData(data).withSilentPush(true));
AddressConfiguration addressConfiguration = new AddressConfiguration().withChannelType(ChannelType.GCM);
MessageRequest messageRequest = new MessageRequest().withMessageConfiguration(directMessageConfiguration)
.addAddressesEntry(endpointResponse.getAddress(), addressConfiguration);
SendMessagesRequest sendMessagesRequest = new SendMessagesRequest()
.withApplicationId(appid)
.withMessageRequest(messageRequest);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The code executes successfully without any error/exception but i do not see the notification.
However when i post the message from "Direct Messaging" section of pinpoint with the Endpoint Id I am able to see the notification in mobile.
Also using Amazon CLI the Notification message is delivered:
aws --region="us-east-1" pinpoint send-messages --application-id 1fd19ca6fa944a79bdd91beddb4b4f7e --message-request "{\"Context\":{},\"MessageConfiguration\":{\"DefaultMessage\":{\"Body\":\"Test from default message\",\"Substitutions\":{}},\"DefaultPushNotificationMessage\":{},\"APNSMessage\":{},\"GCMMessage\":{\"Data\":{\"message\":\"test\"},\"SilentPush\":true},\"BaiduMessage\":{},\"ADMMessage\":{},\"SMSMessage\":{}},\"Addresses\":{\"cltaa5owuOU:APA91bFOBUB5YRi_Ac6teNmuu19aoFDAByOeoVbqLmY1Yp6cZEp_aueunDU1ZPB6H50GKBfuxu300z-El_sEjxo72crYKnklI-wboxXDk180JICrif0c7R-fR4xFOm5WsQOGUJZPFLG6\":{\"ChannelType\":\"GCM\"}},\"Endpoints\":{}}
Any help will be appreciated.
Thanks

REST Application - I don't receive the error from server in case of insucess - the output displays only if the request is successfull

I have the next problem: I've made a simple application which retrieves information from a server (GET Method). The application works fine as long as the information is retrieved successfully.
In case of insuccess, I don't receive the error from the server (ex: 401 - Unauthorized, 403 - Forbidden - when the authentication token is incorrect for example).
How can I fix this so that my application will return the error from server ? I've done also a POST method and there it's working, I received all erorrs froem server in case of insuccess.
What i'm doing wrong with this code ? Why i don't receive an error in case of insuccess?
The only error I receive in output is 400 in all scenarios and this isn't enough.
For example, if the authorization token is incorrect, I should receive from server 401 - Unauthorized. I know this because i'm doing test with other REST application (like POSTMAN). Can it be fixed to show the errors related to that scenarios ?
void example2() {
// GET METHOD !
try {
String webPage = "https://www.clients.ro";
String name = "user";
String password = "pass";
String authString = name + ":" + password;
System.out.println("Decoded authorization token" + authString);
//byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
//String authStringEnc = new String(authEncBytes);
byte[] authEncBytes = authString.getBytes(StandardCharsets.UTF_8);
String authStringEnc = DatatypeConverter.printBase64Binary(authEncBytes);
System.out.println("Token encoded in Base64 " + authStringEnc);
URL url = new URL(webPage);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0) {
sb.append(charArray, 0, numCharsRead);
}
String result = sb.toString();
System.out.println(result);
System.out.println();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Spring RestTemplate Parse Custom Error Response

Given a REST service call
http://acme.com/app/widget/123
returns:
<widget>
<id>123</id>
<name>Foo</name>
<manufacturer>Acme</manufacturer>
</widget>
This client code works:
RestTemplate restTemplate = new RestTemplate();
XStreamMarshaller xStreamMarshaller = new XStreamMarshaller();
xStreamMarshaller.getXStream().processAnnotations(
new Class[] {
Widget.class,
ErrorMessage.class
});
HttpMessageConverter<?> marshallingConverter = new MarshallingHttpMessageConverter(
xStreamMarshaller, xStreamMarshaller);
List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
converters.add(marshallingConverter);
restTemplate.setMessageConverters(converters);
Widget w = restTemplate.getForObject(
"http://acme.com/app/widget/{id}", Widget.class, 123L);
However, calling http://acme.com/app/widget/456 returns:
<error>
<message>Widget 456 does not exist</message>
<timestamp>Wed, 12 Mar 2014 10:34:37 GMT</timestamp>
</error>
but this client code throws an Exception:
Widget w = restTemplate.getForObject(
"http://acme.com/app/widget/{id}", Widget.class, 456L);
org.springframework.web.client.HttpClientErrorException: 404 Not Found
I tried:
try {
Widget w = restTemplate.getForObject(
"http://acme.com/app/widget/{id}", Widget.class, 456L);
}
catch (HttpClientErrorException e) {
ErrorMessage errorMessage = restTemplate.getForObject(
"http://acme.com/app/widget/{id}", ErrorMessage.class, 456L);
// etc...
}
The second invocation just threw another HttpClientErrorException, plus it does not feel right calling the service twice.
Is there a way to call the service once and parse the response into a Widget on success and an ErrorMessage when not found?
Following from my comment, I checked the HttpClientErrorException JavaDoc and it does support both setting/getting the statusText as well as the responseBody. However they are optional and RestTemplate may not populate them - you'll need to try something like:
try {
Widget w = restTemplate.getForObject(
"http://acme.com/app/widget/{id}", Widget.class, 456L);
}
catch (HttpClientErrorException e) {
String responseBody = e.getResponseBodyAsString();
String statusText = e.getStatusText();
// log or process either of these...
// you'll probably have to unmarshall the XML manually (only 2 fields so easy)
}
If they are both empty/null then you may have to extend the RestTemplate class involved and populate those fields yourself and/or raise a Jira issue on the Spring site.
You can also create an object from Error response body if you like:
ObjectMapper om = new ObjectMapper();
String errorResponse = ex.getResponseBodyAsString();
MyClass obj = om.readValue(errorResponse, MyClass.class);
As you already catch the HttpClientErrorException object, it should allows you to easily extract useful information about the error and pass that to the caller.
For example:
try{
<call to rest endpoint using RestTemplate>
} catch(HttpClientErrorException e){
HttpStatus statusCode = e.getStatusCode();
String body = e.getResponseBodyAsString();
}
IMO if one needs to further de-serialize the error message body into some relevant object, that can be handled somewhere outside of the catch statement scope.
I too have found this a disturbing change in the Spring library. You used to be able to throw a ResponseStatusException and pass it the HttpStatus code and a custom message and then catch the HttpClientErrorException and simply print getMessage() to see the custom error. This no longer works. In order for me to print the custom error, I had to capture the ResponseBody as a String, getResponseBodyAsString on the HttpClientErrorException. Then I needed to parse this as a String doing some pretty hokey substring manipulation. Doing this strips out the information from the ResponseBody and gives the message sent by my server. The code to do this follows:
String message = hce.getResponseBodyAsString();
int start, end;
start = message.lastIndexOf(":", message.lastIndexOf(",")-1) + 2;
end = message.lastIndexOf(",") -1;
message = message.substring(start, end);
System.out.println(message);
When I test this using ARC or Postman, they can display the correct message after I add server.error.include-message=always to my application.properties file on the server. I am not sure what method they are using to extract the message but that would be nice to know.

SECURITY_ERR: DOM Exception 18: in iphone email composer

I have an ios App with email composer and database connectivity. After sending email and coming back to home page I am getting an Error message "security_err dom exception 18". I think the issue is with connecting the database after dismissing the email composer.
Here is my db connection code
var connection = null;
var name = "dbname";
var version = "1.0";
var display_name = "displaname";
var size = 200000;
try{
if(connection == null)
connection = window.openDatabase(name, version, display_name, size);
}
catch(e){
alert("SQL Error: "+e);
return;
}
Can anyone helpme out to resolve it?