I want to know how do i read and modify all the alarms ? I am currently facing problem to read the next set of alarms. The first set contains first 50.
DescribeAlarmsRequest describeAlarmsRequest = new DescribeAlarmsRequest();
DescribeAlarmsResult alarmsResult = cloudWatch.describeAlarms(describeAlarmsRequest);
System.out.println(alarmsResult.getMetricAlarms().size());
System.out.println(alarmsResult.getNextToken());
DescribeAlarmsRequest describeAlarmsRequest1 = new DescribeAlarmsRequest();
describeAlarmsRequest1.setNextToken(alarmsResult.getNextToken());
DescribeAlarmsResult alarmsResult1 = cloudWatch.describeAlarms(describeAlarmsRequest1);
System.out.println(alarmsResult1.getMetricAlarms().size());
I did it the following way and it worked.
public class Alarms {
private static AmazonCloudWatchClient cloudWatch;
private static AmazonSNSClient client;
private static ClientConfiguration clientConfiguration;
private static final String AWS_KEY = "";
private static final String AWS_SECRET_KEY = "";
static {
BasicAWSCredentials credentials = new BasicAWSCredentials(AWS_KEY,AWS_SECRET_KEY);
cloudWatch = new AmazonCloudWatchClient(credentials);
clientConfiguration = new ClientConfiguration();
clientConfiguration.setConnectionTimeout(10000);
clientConfiguration.setSocketTimeout(30000);
clientConfiguration.setMaxErrorRetry(5);
client = new AmazonSNSClient(credentials, clientConfiguration);
}
public static void main(String args[]) {
cloudWatch.setEndpoint("monitoring.us-east-1.amazonaws.com");
DescribeAlarmsRequest describeAlarmsRequest = new DescribeAlarmsRequest();
//describeAlarmsRequest.setStateValue(StateValue.OK);
DescribeAlarmsResult alarmsResult = cloudWatch.describeAlarms(describeAlarmsRequest);
List<MetricAlarm> metricAlarmList = new ArrayList<>();
metricAlarmList.addAll(alarmsResult.getMetricAlarms());
do {
describeAlarmsRequest.withNextToken(alarmsResult.getNextToken());
alarmsResult = cloudWatch.describeAlarms(describeAlarmsRequest);
metricAlarmList.addAll(alarmsResult.getMetricAlarms());
} while (alarmsResult.getNextToken() != null);
int i = metricAlarmList.size();
System.out.println("size " + i);
for(MetricAlarm alarm : metricAlarmList){
System.out.println(i--);
modifyalarm(alarm);
}
}
private static void modifyalarm(MetricAlarm alarm) {
Dimension instanceDimension = new Dimension();
instanceDimension.setName("InstanceId");
instanceDimension.setValue(alarm.getAlarmName());
PutMetricAlarmRequest request = new PutMetricAlarmRequest()
.withActionsEnabled(true).withAlarmName(alarm.getAlarmName())
.withComparisonOperator(ComparisonOperator.GreaterThanOrEqualToThreshold)
.withDimensions(Arrays.asList(instanceDimension))
.withAlarmActions(getTopicARN())
.withEvaluationPeriods(5)
.withPeriod(60)
.withThreshold(5.0D)
.withStatistic(Statistic.Average)
.withMetricName("StatusCheckFailed")
.withNamespace("AWS/EC2");
cloudWatch.putMetricAlarm(request);
}
private static String getTopicARN() {
ListTopicsResult listTopicsResult = client.listTopics();
String nextToken = listTopicsResult.getNextToken();
List<Topic> topics = listTopicsResult.getTopics();
String topicARN = "";
while (nextToken != null) {
listTopicsResult = client.listTopics(nextToken);
nextToken = listTopicsResult.getNextToken();
topics.addAll(listTopicsResult.getTopics());
}
for (Topic topic : topics) {
if (topic.getTopicArn().contains("status-alarms")) {
topicARN = topic.getTopicArn();
break;
}
}
return topicARN;
}
}
Related
The below code is used to get the id stored in a cookie for a guest shopping cart. This code works fine on localhost but is giving me an error on shared hosting where I deployed my website.
public static class Func
{
public static string SetCookie()
{
string key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string gid = Guid.NewGuid().ToString();
var cookieText = Encoding.UTF8.GetBytes(gid);
var encryptedValue = Convert.ToBase64String(MachineKey.Protect(cookieText, key));
HttpCookie myCookie = new HttpCookie("Ecomm", encryptedValue);
myCookie.Expires = DateTime.Now.AddDays(1);
HttpContext.Current.Response.Cookies.Add(myCookie);
return gid;
}
public static UserShopCart GetCookie()
{
var usc = new UserShopCart();
string key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
HttpCookie myCookie = HttpContext.Current.Request.Cookies["Ecomm"];
if (myCookie != null)
{
if (myCookie.Value != null)
{
var output = MachineKey.Unprotect(Convert.FromBase64String(myCookie.Value), key);
usc.id = Encoding.UTF8.GetString(output);
return usc;
}
else
{
usc.id = SetCookie();
return usc;
}
}
else
{
usc.id=SetCookie();
return usc;
}
}
}
public class UserShopCart {
public string id;
public string name;
}
Here is the snapshot of the error:
I have created a method to created JTable as per below:
public void refTable(String jobNo) {
Report rp = new Report();
final String noJob = jobNo;
Map<Integer, String> jMap = rp.getReportInfo(jobNo);
Map<Integer, String> sortedMap = new TreeMap<Integer, String>(jMap);
String[] row = new String[sortedMap.size()];
Integer[] no = new Integer[sortedMap.size()];
String[] stat = new String[sortedMap.size()];
Boolean[] dev = new Boolean[sortedMap.size()];
String[] remark = new String[sortedMap.size()];
Boolean[] rem = new Boolean[sortedMap.size()];
userRemark = new String[sortedMap.size()];
tabSize = sortedMap.size();
int i = 0;
for (Integer key : sortedMap.keySet()) {
no[i] = key;
String[] val = sortedMap.get(key).split("###");
if (val[0].trim().equals("DEV")) {
stat[i] = "FAIL";
} else {
stat[i] = val[0].trim();
}
row[i] = val[1].trim();
dev[i] = false;
remark[i] = "";
//remark[i] = false;
//if(userRemark1[i]!=null)
userRemark[i] = RemarkDropDownList.userOthersReamrk;
//else
//userRemark[i] ="";
rem[i] = false;
i++;
}
DefaultTableModel model = new DefaultTableModel();
model.fireTableDataChanged();
jTable1.setModel(model);
model.addColumn("No:", no);
model.addColumn("Status:", stat);
model.addColumn("Details:", row);
model.addColumn("Non-Deviation", dev);
model.addColumn("Remarks", remark);
model.addColumn("Remove", rem);
model.addColumn("UR", userRemark);
TableColumn col1 = jTable1.getColumnModel().getColumn(0);
col1.setPreferredWidth(30);
TableColumn col2 = jTable1.getColumnModel().getColumn(1);
col2.setPreferredWidth(30);
TableColumn col3 = jTable1.getColumnModel().getColumn(2);
TextRenderer renderer = new TextRenderer();
col3.setCellRenderer(renderer);
col3.setPreferredWidth(350);
CellRenderer cellRender = new CellRenderer();
TableColumn col4 = jTable1.getColumnModel().getColumn(3);
col4.setCellEditor(jTable1.getDefaultEditor(Boolean.class));
col4.setCellRenderer(cellRender);
col4.setPreferredWidth(50);
TableButton buttonEditor = new TableButton("Button");
buttonEditor.addTableButtonListener(new TableButtonListener() {
//#Override
public void tableButtonClicked(int row, int col) {
RemarkDropDownList rmk = new RemarkDropDownList(noJob, row);
rmk.setVisible(true);
//userRemark1[row] = RemarkDropDownList.userOthersReamrk;
//String test = RemarkDropDownList.userOthersReamrk;
}
});
TableColumn col5 = jTable1.getColumnModel().getColumn(4);
col5.setCellRenderer(buttonEditor);
col5.setCellEditor(buttonEditor);
TableColumn col6 = jTable1.getColumnModel().getColumn(5);
col6.setCellEditor(jTable1.getDefaultEditor(Boolean.class));
col6.setCellRenderer(jTable1.getDefaultRenderer(Boolean.class));
col6.setPreferredWidth(50);
jTable1.setShowGrid(true);
jTable1.setGridColor(Color.BLACK);
jTable1.setAutoCreateRowSorter(true);
}
In my JTable I've created a button in column 5 like this.
TableButton buttonEditor = new TableButton("Button");
buttonEditor.addTableButtonListener(new TableButtonListener() {
//#Override
public void tableButtonClicked(int row, int col) {
RemarkDropDownList rmk = new RemarkDropDownList(noJob, row);
rmk.setVisible(true);
//userRemark1[row] = RemarkDropDownList.userOthersReamrk;
//String test = RemarkDropDownList.userOthersReamrk;
}
});
TableColumn col5 = jTable1.getColumnModel().getColumn(4);
col5.setCellRenderer(buttonEditor);
col5.setCellEditor(buttonEditor);
The button basically create a new JFrame with combobox inside it like this.
public class RemarkDropDownList extends javax.swing.JFrame {
public static String userOthersReamrk = "test";
private String userSelectedItem = "File Issue";
String jobno;
int rowNo;
public RemarkDropDownList() {
initComponents();
this.lblOthers.setVisible(false);
this.txtOthers.setVisible(false);
}
public RemarkDropDownList(String jobNo, int row) {
initComponents();
this.lblOthers.setVisible(false);
this.txtOthers.setVisible(false);
this.jobno = jobNo;
this.rowNo = row;
}
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JComboBox cb = (JComboBox)evt.getSource();
userSelectedItem = (String)cb.getSelectedItem();
if(userSelectedItem.equalsIgnoreCase("others"))
{
this.lblOthers.setVisible(true);
this.txtOthers.setVisible(true);
}
else
{
this.lblOthers.setVisible(false);
this.txtOthers.setVisible(false);
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(userSelectedItem.equalsIgnoreCase("others"))
{
userOthersReamrk = txtOthers.getText().toString();
if(userOthersReamrk == null || userOthersReamrk.equalsIgnoreCase(""))
{
JOptionPane.showMessageDialog(null, "Please enter Remark");
}
}
else
{
userOthersReamrk = userSelectedItem;
//String [] remark = new String [1000];
///remark[rowNo] = userOthersReamrk;
ReportPanelMin rpm = new ReportPanelMin();
//rpm.userRemark1[rowNo] = remark[rowNo];
rpm.refTable(jobno);
this.setVisible(false);
}
}
}
Everything is working, but the last part. I've created a static global variable (userOthersReamrk) in RemarkDropDownList class (the new class) to hold user drop down selected value. I call the refTable function again to reload the table so i can assign the userOthersReamrk value to column no 7 like this userRemark = new String[sortedMap.size()];. When i debug, I can see the user selected value is assigned touserRemark array but its not population in the table. The column showing the default value test which i decalred in RemarkDropDownList. I know the code is so long, but i post everything to give better understanding on what im doing. What/where i need to make change so my user's selected value is shown in column 7 instead the default value.
Recently I've had my DB rights reduced so that I can't drop and recreate databases. This has led to me using the DontDropDbJustCreateTablesIfModelChanged Database initialisation from nuget.
However I'm now stuck as to how I should seed data as the Seed function is not in the initialisation so I can't override it. This is what I'd like to be able to do.
public class MyDBInitialiser : DontDropDbJustCreateTablesIfModelChanged<MyContext>
{
protected override void Seed(MyContext context)
{
base.Seed(context);
context.Item.Add(new Item() { ItemId = 1, Name = "Item 1"});
context.Item.Add(new Item() { ItemId = 2, Name = "Item 2"});
context.Item.Add(new Item() { ItemId = 3, Name = "Item 3"});
}
}
Is there another way of seeding data in this situation.
Simply,
public class DontDropDbJustCreateTablesIfModelChanged<T>
: IDatabaseInitializer<T> where T : DbContext
{
private EdmMetadata _edmMetaData;
public void InitializeDatabase(T context)
{
ObjectContext objectContext =
((IObjectContextAdapter)context).ObjectContext;
string modelHash = GetModelHash(objectContext);
if (CompatibleWithModel(modelHash, context, objectContext))
return;
DeleteExistingTables(objectContext);
CreateTables(objectContext);
SaveModelHashToDatabase(context, modelHash, objectContext);
Seed(context);
}
protected virtual void Seed(T context) { }
private void SaveModelHashToDatabase(T context, string modelHash,
ObjectContext objectContext)
{
if (_edmMetaData != null) objectContext.Detach(_edmMetaData);
_edmMetaData = new EdmMetadata();
context.Set<EdmMetadata>().Add(_edmMetaData);
_edmMetaData.ModelHash = modelHash;
context.SaveChanges();
}
private void CreateTables(ObjectContext objectContext)
{
string dataBaseCreateScript =
objectContext.CreateDatabaseScript();
objectContext.ExecuteStoreCommand(dataBaseCreateScript);
}
private void DeleteExistingTables(ObjectContext objectContext)
{
objectContext.ExecuteStoreCommand(Dropallconstraintsscript);
objectContext.ExecuteStoreCommand(Deletealltablesscript);
}
private string GetModelHash(ObjectContext context)
{
var csdlXmlString = GetCsdlXmlString(context).ToString();
return ComputeSha256Hash(csdlXmlString);
}
private bool CompatibleWithModel(string modelHash, DbContext context,
ObjectContext objectContext)
{
var isEdmMetaDataInStore =
objectContext.ExecuteStoreQuery<int>(LookupEdmMetaDataTable)
.FirstOrDefault();
if (isEdmMetaDataInStore == 1)
{
_edmMetaData = context.Set<EdmMetadata>().FirstOrDefault();
if (_edmMetaData != null)
{
return modelHash == _edmMetaData.ModelHash;
}
}
return false;
}
private string GetCsdlXmlString(ObjectContext context)
{
if (context != null)
{
var entityContainerList = context.MetadataWorkspace
.GetItems<EntityContainer>(DataSpace.SSpace);
if (entityContainerList != null)
{
var entityContainer = entityContainerList.FirstOrDefault();
var generator =
new EntityModelSchemaGenerator(entityContainer);
var stringBuilder = new StringBuilder();
var xmlWRiter = XmlWriter.Create(stringBuilder);
generator.GenerateMetadata();
generator.WriteModelSchema(xmlWRiter);
xmlWRiter.Flush();
return stringBuilder.ToString();
}
}
return string.Empty;
}
private static string ComputeSha256Hash(string input)
{
byte[] buffer = new SHA256Managed()
.ComputeHash(Encoding.ASCII.GetBytes(input));
var builder = new StringBuilder(buffer.Length * 2);
foreach (byte num in buffer)
{
builder.Append(num.ToString("X2",
CultureInfo.InvariantCulture));
}
return builder.ToString();
}
private const string Dropallconstraintsscript =
#"select
'ALTER TABLE ' + so.table_name + ' DROP CONSTRAINT '
+ so.constraint_name
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS so";
private const string Deletealltablesscript =
#"declare #cmd varchar(4000)
declare cmds cursor for
Select
'drop table [' + Table_Name + ']'
From
INFORMATION_SCHEMA.TABLES
open cmds
while 1=1
begin
fetch cmds into #cmd
if ##fetch_status != 0 break
print #cmd
exec(#cmd)
end
close cmds
deallocate cmds";
private const string LookupEdmMetaDataTable =
#"Select COUNT(*)
FROM INFORMATION_SCHEMA.TABLES T
Where T.TABLE_NAME = 'EdmMetaData'";
}
&
public class Population : DontDropDbJustCreateTablesIfModelChanged</* DbContext */>
{
protected override void Seed(Syndication Context)
{
/* Seeding :) */
}
}
&
Database.SetInitializer</* DbContext */>(new Population());
I my projects I split the db initialization from the db seeding. If you use inversion of control, you should be able to do something like this in your composition root (Application_Start if you are consuming the DbContext from a web app):
var seeder = ServiceLocatorPattern
.ServiceProviderLocator.Current.GetService<ISeedDb>();
if (seeder != null) seeder.Seed();
The interface:
public interface ISeedDb, IDisposable
{
void Seed();
}
A possible implementation:
public class MyDbSeeder : ISeedDb
{
private readonly MyContext _context;
public MyDbSeeder(MyContext context)
{
_context = context;
}
public void Seed()
{
_context.Item.Add(new Item { ItemId = 1, Name = "Item 1" });
// ... etc
}
public void Dispose()
{
_context.Dispose();
}
}
I have pasted a code snippet for HTTP Post where I am POSTING a multipart message to the server which needs Authentication. I am expecting a JSON response, but when I run this I always get the login page in HTML.
public final class MyScreen extends MainScreen {
private RichTextField _Output;
public MyScreen() {
// Set the displayed title of the screen
setTitle("MyTitle");
_Output = new RichTextField();
add(_Output);
addMenuItem(_GetDataAction);
}
protected MenuItem _GetDataAction = new MenuItem("GetData", 100000, 10) {
public void run() {
String URL = "<Sample URL Goes Here>";
ServiceRequestThread svc = new ServiceRequestThread(URL,
(MyScreen) UiApplication.getUiApplication()
.getActiveScreen());
svc.start();
}
};
public void updateDestination(final String text) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
_Output.setText(text);
}
});
}
}
class ServiceRequestThread extends Thread {
protected String _URL;
protected MyScreen _Dest = null;
protected URLEncodedPostData _PostData = null;
StringBuffer writer = new StringBuffer();
public void setPOSTData(URLEncodedPostData data) {
_PostData = data;
}
public ServiceRequestThread(String URL, MyScreen screen) {
super();
_Dest = screen;
_URL = URL;
}
public void run() {
try
{
String boundary = "SATBA";
String twoHyphens = "--";
String data1 = "{\"IMPORTING\":{ \"IN_COUNTRY_CODE\":\"US\"}}";
String CRLF = "\r\n";
byte[] encoded = Base64OutputStream.encode
("User:password".getBytes(), 0, "User:password".length(), false,false);
"Prepare the data for post"
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").append(
CRLF);
writer.append("Content-Type: text/json; charset=" + "UTF-8").append(CRLF);
writer.append("Content-Transfer-Encoding: 8bit").append(CRLF);
writer.append("Request-Id:Abcd123456" ).append(CRLF);
writer.append("Request-Type:rfc_json").append(CRLF);
writer.append("function:00163E0136C01EE0AE8B059433A71727")
.append(CRLF);
writer.append(CRLF);
writer.append(data1).append(CRLF);
writer.append("--" + boundary + "--").append(CRLF);
String string = new String(writer);
HttpConnection conn1 = (HttpConnection)Connector.open(_URL,Connector.READ_WRITE);
conn1.setRequestMethod(HttpConnection.POST);
conn1.setRequestProperty("Authorization", "Basic "+ new String(encoded));
conn1.setRequestProperty("Content-Type","multipart/mixed; boundary=" + boundary);
OutputStreamWriter osw = new OutputStreamWriter(conn1.openOutputStream(), "UTF-8");
osw.write(string);
osw.flush();
osw.close();
int responseCode = conn1.getResponseCode();
if (responseCode == HttpConnection.HTTP_OK) {
InputStream data = conn1.openInputStream();
StringBuffer raw = new StringBuffer();
byte[] buf = new byte[4096];
int nRead = data.read(buf);
while (nRead > 0) {
raw.append(new String(buf, 0, nRead));
nRead = data.read(buf);
}
_Dest.updateDestination(raw.toString());
} else {
_Dest.updateDestination("responseCode="
+ Integer.toString(responseCode));
}
}
catch( IOException e)
{
e.printStackTrace();
_Dest.updateDestination("Exception:"+e.toString());
}
}
}
Turns out the code was perfectly alright and the issue was on the rim.public property file where the application.handler.http.AuthenticationSupport was set to true and because of this it was not loggging in.
Now I set it to false and get the correct response.
I want to update my account's datas.How can I access and update it ?
I can create a new account using this code but also i want to update :
private static CrmService ConnectToCrm()
{
CrmService service = new CrmService();
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = "crm";
service.Url = "http://192.168.1.23:5555/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
return service;
}
protected void btnUpdateAccount_Click(object sender, EventArgs e)
{
try
{
CrmService MyService = ConnectToCrm();
DynamicEntity leadEntity = new DynamicEntity();
leadEntity.Name = EntityName.lead.ToString();
ArrayList arrProps = new ArrayList();
if (txtName.Text != string.Empty)
{
StringProperty firstname = new StringProperty();
firstname.Name = "firstname";
firstname.Value = txtName.Text;
arrProps.Add(firstname);
}
if (txtSurname.Text != string.Empty)
{
StringProperty lastname = new StringProperty();
lastname.Name = "lastname";
lastname.Value = txtSurname.Text;
arrProps.Add(lastname);
}
if (txtMail.Text != string.Empty)
{
StringProperty mail = new StringProperty();
mail.Name = "emailaddress1";
mail.Value = txtMail.Text;
arrProps.Add(mail);
}
if (txtState.Text != string.Empty)
{
StringProperty state = new StringProperty();
state.Name = "address1_stateorprovince";
state.Value = txtState.Text;
arrProps.Add(state);
}
leadEntity.Properties = (Property[])arrProps.ToArray(typeof(Property));
MyService.Create(leadEntity);
}
Updates work very similar to Creates. Just make sure that the DynamicEntity has the GUID and entity name of the record you want to update and replace
MyService.Create(leadEntity);
with
MyService.Update(LeadEntity);