Is it possible to search for an alarm or to check if alarm already exists in CloudWatch using Java api?
I am currently doing this way but it doesnt look promising to me.
long offsetInMilliseconds = 1000 * 60 * 60 * 24;
Dimension instanceDimension = new Dimension();
instanceDimension.setName("InstanceId");
instanceDimension.setValue("i-201cb891");
//Check is Alarms with name exist.
GetMetricStatisticsRequest getMetricStatisticsRequest = new GetMetricStatisticsRequest()
.withStartTime(new Date(new Date().getTime() - offsetInMilliseconds))
.withNamespace("AWS/EC2")
.withPeriod(60 * 60)
.withMetricName("StatusCheckFailed")
.withStatistics("Average")
.withDimensions(Arrays.asList(instanceDimension))
.withEndTime(new Date());
GetMetricStatisticsResult getMetricStatisticsResult = cloudWatch.getMetricStatistics(getMetricStatisticsRequest);
System.out.println("" + getMetricStatisticsResult.getDatapoints().size());
if(getMetricStatisticsResult.getDatapoints().size() == 0) {
PutMetricAlarmRequest request = new PutMetricAlarmRequest()
.withActionsEnabled(true).withAlarmName("i-201cb891")
.withComparisonOperator(ComparisonOperator.GreaterThanOrEqualToThreshold)
.withDimensions(Arrays.asList(instanceDimension))
// .withAlarmActions(getTopicARN())
.withEvaluationPeriods(1)
.withPeriod(60)
.withThreshold(60.0D)
.withStatistic(Statistic.Average)
.withMetricName("StatusCheckFailed")
.withNamespace("AWS/EC2");
cloudWatch.putMetricAlarm(request);
System.out.println("Alarm created for Instance with ID : " + "i-201cb891");
}else{
System.out.println("Alarm exists with name : " + "i-201cb891");
}
You can use AmazonCloudWatch interface to query for your alarms.
From AmazonCloudWatch API:
DescribeAlarmsResult describeAlarms(DescribeAlarmsRequest describeAlarmsRequest)
You can use this method to query for your alarms by name or by prefix, for instance.
The following code snippet shows how to use the API:
...
AmazonCloudWatch client = new AmazonCloudWatchClient(new ProfileCredentialsProvider());
DescribeAlarmsRequest request = new DescribeAlarmsRequest();
List<String> alarmNames = new ArrayList<String>();
alarmNames.add("alarmName1");
alarmNames.add("alarmName2");
request.setAlarmNames(alarmNames);
DescribeAlarmsResult result = client.describeAlarms(request);
List<MetricAlarm> alarms = result.getMetricAlarms();
for (MetricAlarm alarm : alarms) {
System.out.println(alarm.getAlarmName());
}
...
AWS SDK for Java API Reference - 1.10.43
Related
I am using smack on the client-side. I tried to search registered users on the client-side because before creating a new user I want to know that the id is registered on server or not if not then create the user either log in the user but ejabberd server crashed with the error. Here are the crash logs of ejabberd server.
Failed to process iq:
#iq{
id = <<"Hh6AJ-28">>,type = set,lang = <<"en">>,
from =
#jid{
user = <<"admin">>,server = <<"faiqkhan-virtualbox">>,
resource = <<"92526029764259513741138">>,luser = <<"admin">>,
lserver = <<"faiqkhan-virtualbox">>,
lresource = <<"92526029764259513741138">>},
to =
#jid{
user = <<>>,server = <<"vjud.faiqkhan-virtualbox">>,resource = <<>>,
luser = <<>>,lserver = <<"vjud.faiqkhan-virtualbox">>,lresource = <<>>},
sub_els =
[#xmlel{
name = <<"query">>,
attrs = [{<<"xmlns">>,<<"jabber:iq:search">>}],
children =
[#xmlel{
name = <<"x">>,
attrs = [{<<"xmlns">>,<<"jabber:x:data">>},{<<"type">>,<<"submit">>}],
children =
[#xmlel{
name = <<"field">>,
attrs = [{<<"var">>,<<"user">>},{<<"type">>,<<"text-single">>}],
children =
[#xmlel{
name = <<"value">>,attrs = [],
children = [{xmlcdata,<<"wasiq#faiqkhan-virtualbox">>}]}]}]}]}],
meta = #{ip => {0,0,0,0,0,65535,49320,11092}}}
exception error: {module_not_loaded,mod_vcard_mnesia,
<<"faiqkhan-virtualbox">>}
in function gen_mod:get_module_opts/2 (src/gen_mod.erl, line 338)
in call from gen_mod:get_module_opt/3 (src/gen_mod.erl, line 318)
in call from mod_vcard_mnesia:filter_fields/3 (src/mod_vcard_mnesia.erl, line 200)
in call from mod_vcard_mnesia:search/4 (src/mod_vcard_mnesia.erl, line 78)
in call from mod_vcard:search_result/4 (src/mod_vcard.erl, line 479)
in call from mod_vcard:process_search/1 (src/mod_vcard.erl, line 264)
in call from gen_iq_handler:process_iq/3 (src/gen_iq_handler.erl, line 131)
in call from gen_iq_handler:process_iq/4 (src/gen_iq_handler.erl, line 109)
I used the following code to get a registered user from the client-side:
InetAddress address = InetAddress.getByName(HOST);
DomainBareJid serviceName = JidCreate.domainBareFrom("faiqkhan-VirtualBox"); XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
builder.setPort(PORT);
builder.setSendPresence(true);
builder.setHostAddress(address);
builder.setServiceName(serviceName);
builder.setUsernameAndPassword("admin", "123456");
builder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
XMPPTCPConnection connection = new XMPPTCPConnection(builder.build());
try {
connection.connect();
connection.login("admin", "123456");
Logger.showError("21560-connection created to: " + connection.getHost());
Roster roster = Roster.getInstanceFor(connection);
Set<RosterEntry> entities = roster.getEntries();
UserSearchManager search = new UserSearchManager(connection);
DomainBareJid s = JidCreate.domainBareFrom("vjud.".concat("faiqkhan-VirtualBox"));
Form searchForm = search.getSearchForm(s);
Form answerForm = searchForm.createAnswerForm();
answerForm.setAnswer("user", "wasiq#faiqkhan-virtualbox");
ReportedData data = search.getSearchResults(answerForm, s);
if (data.getRows() != null) {
for (ReportedData.Row row : data.getRows()) {
for (CharSequence value : row.getValues("jid")) {
Log.i("Iteartor values......", " " + value);
}
}
}
} catch (SmackException | IOException | XMPPException | InterruptedException e) {
Logger.showError("21560-error on account creation: " + e.getMessage());
}
Server crashed on ReportedData data = search.getSearchResults(answerForm, s); line of code.
You found a bug in ejabberd:
It was already fixed in 2018 in
https://github.com/processone/ejabberd/commit/1be21126342d503205798605725ba5ceef9de42b
but the bug got reintroduced in 2019 in
https://github.com/processone/ejabberd/commit/a02cff0e780bb735531594c4ece81e8628f79782#diff-71f613241ed580c3e5dad2b4526503f2R12
and I've now applied a temporary fix in
https://github.com/processone/ejabberd/commit/92913389a51ddc564f11e0712b0d82fca8c9aecb
But even if that bug is fixed, the feature you want to use probably doesn't help: a user must set his vCard in order for his account to be provided in vJud search. In other words, vJUD searches in stored vCards, not in registered accounts. If I register an account but don't set a vCard, then vJUD will not find it.
before creating a new user I want to know that the id is registered on server or not
And why don't you simply attempt to register the account first?
On the other hand, if you would like to check in advance if an account is available for registration or not (like some web registration sites do, to allow the user modify the username until one is available), then I think XMPP doesn't provide that possibility for security reasons: it is not allowed to know if an account exists or not.
A solution for that would be to use the check_account ejabberd command
https://docs.ejabberd.im/developer/ejabberd-api/admin-api/#check-account
executing it with some frontend, like ejabberdctl, ReST or XMLRPC
https://docs.ejabberd.im/admin/guide/managing/#ejabberd-commands
$ ejabberdctl check_account user1 localhost
$ ejabberdctl check_account user6666 localhost
Error: false
~ 1
What is the correct way of getting PidLidEndRecurrenceDate values using Ews. below code does not give proper result. property details that i am looking is https://learn.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxprops/816378cf-07ef-4926-b7d2-53475792403d
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
service.Credentials = new WebCredentials("X#X.com", "XXX");
service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
ItemView view = new ItemView(10);
Guid MyPropertySetId = new Guid("{6ED8DA90-450B-101B-98DA-00AA003F1305}");
int intValue = Convert.ToInt32("0x0000000F", 16);
ExtendedPropertyDefinition extendedPropertyDefinition =
new ExtendedPropertyDefinition(MyPropertySetId, intValue, MapiPropertyType.Integer);
view.PropertySet =
new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, extendedPropertyDefinition);
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Calendar, view);
foreach (Item item in findResults.Items)
{
Console.WriteLine(item.Subject);
if (item.ExtendedProperties.Count > 0)
{
// Display the extended name and value of the extended property.
foreach (ExtendedProperty extendedProperty in item.ExtendedProperties)
{
Console.WriteLine(" Extended Property Name: " + extendedProperty.PropertyDefinition.Name);
Console.WriteLine(" Extended Property Value: " + extendedProperty.Value);
}
}
}
That property is set on the Meeting invite messages only not on the Master instance of the Calendar Appointments which is what you seem to be looking at. For the Master instances you should just be able to use the strongly typed property https://learn.microsoft.com/en-us/dotnet/api/microsoft.exchange.webservices.data.recurrence.enddate?redirectedfrom=MSDN&view=exchange-ews-api#Microsoft_Exchange_WebServices_Data_Recurrence_EndDate
It you wanted to view the property you have above search the SentItems Folder for invites with recurrences (with Enddates) and that's where you will see it. Or probably easier just look at the messages with a Mapi editor like OutlookSpy or MFCMAPI and you will see the properties available.
How can we generate a schema from the database in meteor app.
I want to generate multiple schemas from each database entry.
The DB used is Mongo DB.
This schema will be used later to generate a form.
I am using autoform to generate a form.
[1: http://autoform.meteor.com]
I've written a small script that you can run in mongo to reverse engineer an existing (flat) collection.
/*
** SimpleSchema definition generator
**
** This will reverse engineer a flat collection
** only at this point. If you improve this,
** please share: {"email-left": "timstew", "at":"#", "email-right": "gmail.com"}
**
*/
var schemaName = "publisherSchema"; // Name you want to give to your simple schema
var collectionName = "publishers"; // mongodb collection name (not including 'db.')
var sampleID = "54c00f0d2b21500370a2e4c4"; // _id of a good representative document
// OK, that's all the info we need - Let's get started!
var message = eval("db." + collectionName + ".findOne({_id:\"" + sampleID +"\"})");
var count = 0;
// Hack because I can't figure out how to find out how many fields are in
var numKeys = 0;
for(var key in message) {numKeys += 1}
var index = 0;
for (var key in message) {
if (index == 0) {
print(schemaName + " = new SimpleSchema({");
}
print("\t" + key + ": {");
print("\t\ttype: " + toProper(eval("typeof db." + collectionName + ".findOne({_id:\"" + sampleID + "\"})." + key)) + ",");
print("\t\tlabel: \"" + toProper(key) + "\"");
if (index == numKeys-1) {
print("\t\t}");
print("\t})");
} else {
print("\t\t},");
}
index += 1;
}
function toProper(str)
{
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
MongoDB is a document database, which doesn't require a schema. All you need to do is declare collections in Meteor
If you want to be strict about the document structure, check out https://github.com/aldeed/meteor-collection2 (meteor add aldeed:collection2)
I've recently explained Meteor collections and schemas here.
If you want to read the schema from a collection, you can simply access it via collectionName.simpleSchema(). For your purpose you can take this schema and convert it into your desired structure (or exclude certain configured fields).
I'm having problems to get my Windows Phone 8.1 live tile update by itself daily (around 7am)
My project has 2 parts :
a Web API project hosted on Azure that provides the tile template in XML (that part works fine)
a Windows Phone 8.1 project with a single MainPage.xaml where I build 2 square/wide tiles
When I pin my app to the start screen from the app list, my tile (whether I choose the square or wide format) flips back and forth between my 2 brands of the day just fine.
The next morning at 7:15 am, the tile won't update with the 2 new brands :(
I noticed that if I tap the tile to launch the app and come back to the start screen, the tile has updated.
It also works if I unpin and repin the tile but in both cases, that's "cheating" :-/
I call my Azure website like this to get the tile templates of both brands :
http://example.azurewebsites.net/api/tiles/0 (BRAND1)
http://example.azurewebsites.net/api/tiles/1 (BRAND2)
The XML tile template looks like this (example):
<tile>
<visual>
<binding template="TileWide310x150ImageAndText01">
<image id="1" src="http://www.example.com/sales/BRAND1/visualWide.png"/>
<text id="1">Brand 1</text>
</binding>
<binding template="TileSquare150x150PeekImageAndText04">
<image id="1" src="http://www.example.com/sales/BRAND1/visualSquare.png"/>
<text id="1">Brand 1</text>
</binding>
</visual>
</tile>
The WP8.1 page contains this :
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
TileUpdateManager.CreateTileUpdaterForApplication().EnableNotificationQueue(true);
PeriodicUpdateRecurrence recurrence = PeriodicUpdateRecurrence.Daily;
Task<string> responseBody;
for (int i = 0; i < 2; i++)
{
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("http://xxxxx.azurewebsites.net/api/tiles/" + i); //I hid the address here for discretion
HttpResponseMessage response = httpClient.GetAsync(httpClient.BaseAddress).Result;
string statusCode = response.StatusCode.ToString();
response.EnsureSuccessStatusCode();
responseBody = response.Content.ReadAsStringAsync();
}
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(responseBody.Result);
string srcWide, srcSquare, textWide, textSquare, templateWide, templateSquare;
XElement root = XElement.Parse(responseBody.Result);
IEnumerable<XElement> wideElement = root.Descendants("binding").Where(a => a.Attribute("template").Value.ToLower().Contains("wide"));
IEnumerable<XElement> squareElement = root.Descendants("binding").Where(a => a.Attribute("template").Value.ToLower().Contains("square"));
templateWide = wideElement.Attributes("template").SingleOrDefault().Value;
srcWide = wideElement.Descendants("image").Attributes("src").SingleOrDefault().Value;
textWide = wideElement.Descendants("text").SingleOrDefault().Value;
templateSquare = squareElement.Attributes("template").SingleOrDefault().Value;
srcSquare = wideElement.Descendants("image").Attributes("src").SingleOrDefault().Value;
textSquare = wideElement.Descendants("text").SingleOrDefault().Value;
XmlDocument wideTileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150ImageAndText01);
XmlNodeList wideTileTextAttributes = wideTileXml.GetElementsByTagName("text");
wideTileTextAttributes[0].InnerText = textWide;
XmlNodeList wideTileImageAttributes = wideTileXml.GetElementsByTagName("image");
((XmlElement)wideTileImageAttributes[0]).SetAttribute("src", srcWide);
((XmlElement)wideTileImageAttributes[0]).SetAttribute("alt", textWide);
XmlDocument squareTileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150PeekImageAndText01);
XmlNodeList squareTileTextAttributes = squareTileXml.GetElementsByTagName("text");
squareTileTextAttributes[0].AppendChild(squareTileXml.CreateTextNode(textSquare));
XmlNodeList squareTileImageAttributes = squareTileXml.GetElementsByTagName("image");
((XmlElement)squareTileImageAttributes[0]).SetAttribute("src", srcSquare);
((XmlElement)squareTileImageAttributes[0]).SetAttribute("alt", textSquare);
IXmlNode node = wideTileXml.ImportNode(squareTileXml.GetElementsByTagName("binding").Item(0), true);
wideTileXml.GetElementsByTagName("visual").Item(0).AppendChild(node);
TileNotification tileNotification = new TileNotification(wideTileXml);
tileNotification.ExpirationTime = DateTimeOffset.UtcNow.AddDays(1).AddHours(7).AddMinutes(0);
TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);
}
List<Uri> urisToPoll = new List<Uri>(5);
urisToPoll.Add(new Uri("http://example.azurewebsites.net/api/tiles/0")); //fake url
urisToPoll.Add(new Uri("http://example.azurewebsites.net/api/tiles/1")); //fake url
//I want the tile to update its content every day at 7:15am
//(the Azure website supposedly returns new brands of the day at 7am)
DateTime dtTomorrow7 = DateTime.SpecifyKind(DateTime.Today.AddDays(1).AddHours(7).AddMinutes(15), DateTimeKind.Local);
DateTimeOffset dtoTomorrow7 = dtTomorrow7;
TileUpdateManager.CreateTileUpdaterForApplication().StartPeriodicUpdateBatch(urisToPoll, dtoTomorrow7, recurrence);
}
I'm not sure I'm using the StartPeriodicUpdateBatch method correctly.
In debug mode,I can see the DateTimeOffset value is Day+1 7:15am +2:00 which looks correct but the tile does not update.
I live in France that is UTC+2
Thanks for your suggestions.
Your dtTomorrow7 is incorrect. It should just be 7:15 AM. Then it will first do an update at 7:15 AM and subsequent updates occurring at the periodic interval thereafter(you set it to daily).
Example of start time where the last TimeSpan is offset from UTC:
DateTime tomorrow = DateTime.Today.AddDays(1);
var startTime = new DateTimeOffset(tomorrow.Year, tomorrow.Month, tomorrow.Day, 7, 15, 0, TimeSpan.FromHours(2));
I have 20 fields on form, how to update fields modified by user during runtime and how to check which fields have changed so that i can only update those values in table using LINQ. I am working on windows application using C# and VS2010
Please refer the code (Currently i am passing all values, i knw this is not the correct way)
private void UpdateRecord(string groupBoxname)
{
using (SNTdbEntities1 context = new SNTdbEntities1())
{
{
Vendor_Account va = new Vendor_Account();
var Result = from grd in context.Vendor_Account
where grd.Bill_No == dd_billNo.Text
select grd;
if (Result.Count() > 0)
if ((dd_EditProjectName.Text!= "Select") && (dd_billNo.Text!="Select") && (dd_editVendorName.Text!="Select"))
{
foreach (var item in Result)
{
va.Account_ID = item.Account_ID;
}
va.Amount_After_Retention = Convert.ToDecimal(txt_AD_AfterRet.Text);
va.Balance = Convert.ToDecimal(txt_AD_Balance.Text);
va.Bill_Amount = Convert.ToDecimal(txt_AD_BillAmount.Text);
va.Bill_Date = Convert.ToDateTime(dt_AD_BillDate.Text);
va.Bill_No = dd_billNo.Text;
va.Comments = txt_AD_Comments.Text;
va.Paid_Till_Date = string.IsNullOrEmpty(txt_AD_Paid.Text)?0:Convert.ToDecimal(txt_AD_Paid.Text);
va.Project_Name = dd_EditProjectName.Text;
va.Retention_Perc = Convert.ToDecimal(txt_retPerc.Text);
va.Amount_After_Retention = Convert.ToDecimal(txt_AD_AfterRet.Text);
va.Vendor_Name = dd_editVendorName.Text;
va.Vendor_Code = txt_AD_Code.Text;
context.Vendor_Account.ApplyCurrentValues(va);
//context.Vendor_PersonalInfo.AddObject(vpi);
context.SaveChanges();
MessageBox.Show("Information Updated Sucessfully!");
lbl_Warning.Text = "";
entityDataSource1.Refresh();
}
else
{
MessageBox.Show("Vendor Name,Project Name and Bill No cannot be blank!!");
}
}
}
}
Entity framework will do that task.
Since you didn't provide any code, I cannot be precise about the answer but please check those links:
http://msdn.microsoft.com/en-us/library/aa697427(v=vs.80).aspx, section:Manipulating Data and Persisting Changes
http://www.codeproject.com/KB/database/sample_entity_framework.aspx
Note that the SaveChanges() function will update any modification done the records in EF.
Create some field dublicates, and compare value from the form element with the local dublicate, if it was changed than update it.