asmack-android-8-4.0.5.jar createOutgoingFileTransfer need fullJID I can't get it - smack

1.I had read https://www.igniterealtime.org/builds/smack/docs/latest/documentation/extensions /filetransfer.html
snippet code from this guide, it not need resource part
// Create the file transfer manager
FileTransferManager manager = new FileTransferManager(connection);
// Create the outgoing file transfer
OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer("romeo#montague.net");
// Send the file
transfer.sendFile(new File("shakespeare_complete_works.txt"), "You won't believe this!");
2.so I read spark source code org.jivesoftware.spark.PresenceManager find this method , so the documentation long time no to update;
/**
* Returns the fully qualified jid of a user.
*
* #param jid the users bare jid (ex. derek#jivesoftware.com)
* #return the fully qualified jid of a user (ex. derek#jivesoftware.com --> derek#jivesoftware.com/spark)
*/
public static String getFullyQualifiedJID(String jid) {
System.out.println("getFullyQualifiedJID : " + jid);
final Roster roster = SparkManager.getConnection().getRoster();
Presence presence = roster.getPresence(jid);
System.out.println("getFullyQualifiedJID : " + presence.getFrom());
return presence.getFrom();
}
I find this method not work for asmack , so google it found this
Smack's FileTransferManager.createOutgoingFileTransfer only accepts full JIDs. How can I determine the full JID of a user in Smack?
//snippet code from my project
Roster roster = connection.getRoster();
List presenceList = roster.getPresences(jid);
Log.d(TAG, "bareJid : " + jid);
for (Presence presence : presenceList) {
Log.d(TAG, "fullJID : " + presence.getFrom());
}
why the code can not get the fullJID.
the output:
12-23 06:55:35.840: D/MChat(1805): bareJid : test#tigereye-pc
12-23 06:55:35.840: D/MChat(1805): fullJID : test#tigereye-pc
4.the result is the same, so how can I get the fullJID
Thanks & Regards

You have to supply Full user id as : user#serveripaddress/Smack
For Example :
xyz#192.168.1.1/Smack

The need the full JID and the client resource.
You can do something like that:
String fullJID = xmppConnection.getRoster().getPresence(JID).getFrom();
My JID variable is the full JID without the resource.

Related

Import/Post CSV files into ServiceNow

We have a requirement for a CSV file to be pushed to the instance, imported and an incident created. I have created the import table and transformation map, and I've successfully tested them manually.
However, when I've attempted to use the instructions from ServiceNow documents site Post CSV files to Import Set nothing happens. The screen goes blank after I get prompted for login credentials.
When I check the system logs and import logs all I see is the error "java.lang.NullPointerException".
My url is basically the following one: https://.service-now.com/sys_import.do?sysparm_import_set_tablename=&sysparm_transform_after_load=true&uploadfile=
Is there something I'm missing?
I do the same thing but have it come in via an email to the my SN instance and process it using an inbound action.
var type = {};
type.schedule = 'u_imp_tmpl_u_term_phr_empl_mvs_ids'; //Display name for scheduled import -- eb9f2dae6f46a60051281ecbbb3ee4a5
type.table = 'u_imp_tmpl_u_term_phr_empl_mvs_ids'; //Import table name
gs.log('0. Process File Start');
if(type.schedule != '' && type.table != '') {
gs.log('1. Setting up data source');
current.name = type.schedule + ' ' + gs.nowDateTime(); //append date time to name of data source for audit
current.import_set_table_name = type.table;
current.import_set_table_label = "";
current.type= "File";
current.format = "CSV"; //"Excel CSV (tab)";
current.header_row = 1;
current.file_retrieval_method = "Attachment";
var myNewDataSource = current.insert();
gs.log('2. Data source inserted with sys_id - ' + myNewDataSource);
//point the scheduled import record to the new data source
var gr = new GlideRecord ('scheduled_import_set');
gr.addQuery('name', type.schedule);
gr.query();
if (gr.next()) {
gs.log('3. Found Scheduled Import definition');
gr.data_source = myNewDataSource;
gr.update();
gs.log('4. Scheduled Import definition updated to point to data source just added');
//Packages.com.snc.automation.TriggerSynchronizer.executeNow(gr);
//Execute a scheduled script job
SncTriggerSynchronizer.executeNow(gr);
} else {
// add error conditions to email somebody that this has occurred
gs.log('5. ERROR - Unable to locate scheduled import definition. Please contact your system administrator');
}
gs.log('6. Inbound email processing complete');
//gs.eventQueue("ep_server_processed",current);
event.state="stop_processing";
} else {
gs.log('7. Inbound email processing skipped');
}

Prevent users from registering with the same username in Backendless

I'm creating a Swift app using Backendless. The app automatically creates the user's username attribute, though this may be changed in the future. Either way, how can I get Backendless to prevent a user from registering if they have the same username as another?
I have added an event handler in Backendless (Business Logic section) to run before allowing a user to register:
/* global Backendless */
/**
* #param {Object} req The request object contains information about the request
* #param {Object} req.context The execution context contains an information about application, current user and event
* #param {Object} req.user
*/
Backendless.ServerCode.User.beforeRegister(function(req) {
//add your code here
}, true);
How can I set it up to check if a username value is the same as an existing one and, if so, throw an error?
Here is the query to know whether user exists or not
let query = BackendlessDataQuery()
let userEmail = "foo#foo.com"
query.whereClause = "email = '\(userEmail)'"
let users = backendless.data.of(BackendlessUser.ofClass()).find(query)
if( users.data.count > 0 )
{
// user exists
}
referenced from Here
You may set a UNIQUE constraint on the username column. This way you'll receive an error in your app, which you'll we able to handle as you wish.

Unable to send email via gmail api to multiple senders

We're using the new gmail api on iOS to send emails and everything works great for messages with single recipients. When we specify more than one in the "to" field, we get the following error:
Error Domain=com.google.GTLJSONRPCErrorDomain Code=400 "The operation couldn’t be completed. (Invalid to header)
I have verified the content we are sending is in fact a valid rfc822 message.
You should use a list in your to field.
E.g. :
[ "liz6beigle#hotmail.com",
"another.one#email.com" ]
Gmail has a limit of bounces and recipients you can send at the same time.
You cannot store multiple emails under a single string.
Placing a single email address on each line will give better readability and prevent parsing errors.
Here is a code sample in Java from google. I hope it will help others to understand :
/**
* Create a MimeMessage using the parameters provided.
*
* #param to Email address of the receiver.
* #param from Email address of the sender, the mailbox account.
* #param subject Subject of the email.
* #param bodyText Body text of the email.
* #return MimeMessage to be used to send email.
* #throws MessagingException
*/
public static MimeMessage createEmail(String to, String from, String subject,
String bodyText) throws MessagingException {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage email = new MimeMessage(session);
InternetAddress tAddress = new InternetAddress(to);
InternetAddress fAddress = new InternetAddress(from);
email.setFrom(new InternetAddress(from));
email.addRecipient(javax.mail.Message.RecipientType.TO,
new InternetAddress(to));
email.setSubject(subject);
email.setText(bodyText);
return email;
}
Gmail API : Sending Messages
Check the first code sample.
This was a regression but we finished deploying the fix on Monday, 2014-08-25.
I think you can do the following
get the 'To' fields as this
"test1#example.com, test2#example.com"
then split it with ','
String mail1 = "test1#example.com";
String mail2 = "test2#example.com";
then do this
email.addRecipient(javax.mail.Message.RecipientType.TO,
new InternetAddress(mail1));
email.addRecipient(javax.mail.Message.RecipientType.TO,
new InternetAddress(mail2));
I checked this
it worked
You can use comma separated emails and loop through those emails
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage email = new MimeMessage(session);
Multipart multiPart = new MimeMultipart("alternative");
email.setFrom(new InternetAddress(from));
String to = "xyz#gmail.com,sjaksks#gmail.cm,hysrtt#gmail.com";
String[] split = to.split(",");
for(int i=0;i<split.length;i++) {
email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(split[i]));
}
email.setSubject(subject);
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText(text, "utf-8");
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(html, "text/html; charset=utf-8");
multiPart.addBodyPart(textPart);
multiPart.addBodyPart(htmlPart);
email.setContent(multiPart);
return email;
I had an exchange with the gmail team and they did confirm that this is actually a bug with their api. Not sure when it will be fixed as they didn't provide any more details but it's on their radar.

Block IP address from Google adwords with their API

Does anyone know how to block certain IP addresses from our Google adwords account using the Google API?
In this article you can see how to do it manually, but I cannot find a way to do it programmatically.
I know it's late. But I needed it as well.
I found the IpBlock type on Google AdWords here.
Here is some sample code i found, and improved slightly
require_once this code, then make this call for each campaign u want to ban the IP for
YourNameSpace\BlockedIP::add($campaignId, $ip);
voila
<?php
/*
...
*/
namespace YourNameSpace;
use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\Common\OAuth2TokenBuilder;
use Google\AdsApi\AdWords\v201802\cm\CampaignCriterionService;
use Google\AdsApi\AdWords\v201802\cm\IpBlock;
use Google\AdsApi\AdWords\v201802\cm\NegativeCampaignCriterion;
use Google\AdsApi\AdWords\v201802\cm\CampaignCriterionOperation;
use Google\AdsApi\AdWords\v201802\cm\Operator;
class BlockedIP {
public static function runExample(AdWordsServices $adWordsServices,
AdWordsSession $session,
$campaignId,
$ip) {
$campaignCriterionService =
$adWordsServices->get($session, CampaignCriterionService::class);
$campaignCriteria = [];
// Add a negative campaign criterion.
$ipBlock = new IpBlock();
$ipBlock->setIpAddress($ip);
$negativeCriterion = new NegativeCampaignCriterion();
$negativeCriterion->setCampaignId($campaignId);
$negativeCriterion->setCriterion($ipBlock);
$operation = new CampaignCriterionOperation();
$operation->setOperator(Operator::ADD);
$operation->setOperand($negativeCriterion);
$operations[] = $operation;
$result = $campaignCriterionService->mutate($operations);
// Print out some information about added campaign criteria.
foreach ($result->getValue() as $campaignCriterion) {
printf(
"Campaign targeting criterion with ID %d and type '%s' was added.\n",
$campaignCriterion->getCriterion()->getId(),
$campaignCriterion->getCriterion()->getType());
}
}
public static function add($campaignId, $ip) {
// Generate a refreshable OAuth2 credential for authentication.
$oAuth2Credential = (new OAuth2TokenBuilder())
->fromFile()
->build();
// Construct an API session configured from a properties file and the OAuth2
// credentials above.
$session = (new AdWordsSessionBuilder())
->fromFile()
->withOAuth2Credential($oAuth2Credential)
->build();
self::runExample(new AdWordsServices(), $session, $campaignId, $ip);
}
}

google adwords api + getting all keywords

I'm using the google adwords api, I can retrieve all campaigns, group ads, ads,
but I have no idea on how to retrieve keywords related to an "group ads".
In the google adwords interface, when we select a group ads, we have two tabs, one for ads related to that group ads, and the second for keywords.
but programatily, right now I can only retrieve ads.
I'm using PHP, if some one knew how to do that in php or others programming languages or even a soap call.
To get the details of all the keywords of an adgroup you need the following to get the details of all the keywords.
require_once dirname(dirname(__FILE__)) . '/init.php';
// Enter parameters required by the code example.
$adGroupId = 'Enter your adgroup id';
/**
* Runs the example.
* #param AdWordsUser $user the user to run the example with
* #param string $adGroupId the id of the parent ad group
*/
function GetKeywordsExample(AdWordsUser $user, $adGroupId) {
// Get the service, which loads the required classes.
$adGroupCriterionService =
$user->GetService('AdGroupCriterionService', ADWORDS_VERSION);
// Create selector.
$selector = new Selector();
$selector->fields = array('KeywordText', 'KeywordMatchType', 'Id');
$selector->ordering[] = new OrderBy('KeywordText', 'ASCENDING');
// Create predicates.
$selector->predicates[] = new Predicate('AdGroupId', 'IN', array($adGroupId));
$selector->predicates[] =
new Predicate('CriteriaType', 'IN', array('KEYWORD'));
// Create paging controls.
$selector->paging = new Paging(0, AdWordsConstants::RECOMMENDED_PAGE_SIZE);
do {
// Make the get request.
$page = $adGroupCriterionService->get($selector);
// Display results.
if (isset($page->entries)) {
foreach ($page->entries as $adGroupCriterion) {
printf("Keyword with text '%s', match type '%s', and ID '%s' was "
. "found.\n", $adGroupCriterion->criterion->text,
$adGroupCriterion->criterion->matchType,
$adGroupCriterion->criterion->id);
}
} else {
print "No keywords were found.\n";
}
// Advance the paging index.
$selector->paging->startIndex += AdWordsConstants::RECOMMENDED_PAGE_SIZE;
} while ($page->totalNumEntries > $selector->paging->startIndex);
}
// Don't run the example if the file is being included.
if (__FILE__ != realpath($_SERVER['PHP_SELF'])) {
return;
}
try {
// Get AdWordsUser from credentials in "../auth.ini"
// relative to the AdWordsUser.php file's directory.
$user = new AdWordsUser();
// Log every SOAP XML request and response.
$user->LogAll();
// Run the example.
GetKeywordsExample($user, $adGroupId);
} catch (Exception $e) {
printf("An error has occurred: %s\n", $e->getMessage());
}
In the Adwords API Keywords are dubbed as AdGroup Criteria. You can add or retrieve the keywords for a certain AdGroup by using the AdGroupCriterionService.
If you're using the PHP client library of the Adwords API check out GetAllAdGroupCriteria.php in the example files. (don't forget to enter the AdGroupId you want to get the keywords for first)

Resources