I was setting up a storm cluster to calculate real time trending and other statistics, however I have some problems introducing the "recovery" feature into this project, by allowing the offset that was last read by the kafka-spout (the source code for kafka-spout comes from https://github.com/apache/incubator-storm/tree/master/external/storm-kafka) to be remembered. I start my kafka-spout in this way:
BrokerHosts zkHost = new ZkHosts("localhost:2181");
SpoutConfig kafkaConfig = new SpoutConfig(zkHost, "test", "", "test");
kafkaConfig.forceFromStart = false;
KafkaSpout kafkaSpout = new KafkaSpout(kafkaConfig);
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("test" + "spout", kafkaSpout, ESConfig.spoutParallelism);
The default settings should be doing this, but I think it is not doing so in my case, every time I start my project, the PartitionManager tries to look for the file with the offsets, then nothing is found:
2014-06-25 11:57:08 INFO PartitionManager:73 - Read partition information from: /storm/partition_1 --> null
2014-06-25 11:57:08 INFO PartitionManager:86 - No partition information found, using configuration to determine offset
Then it starts reading from the latest possible offset. Which is okay if my project never fails, but not exactly what I wanted.
I also looked a bit more into the PartitionManager class which uses Zkstate class to write the offsets, from this code snippet:
PartitionManeger
public void commit() {
long lastCompletedOffset = lastCompletedOffset();
if (_committedTo != lastCompletedOffset) {
LOG.debug("Writing last completed offset (" + lastCompletedOffset + ") to ZK for " + _partition + " for topology: " + _topologyInstanceId);
Map<Object, Object> data = (Map<Object, Object>) ImmutableMap.builder()
.put("topology", ImmutableMap.of("id", _topologyInstanceId,
"name", _stormConf.get(Config.TOPOLOGY_NAME)))
.put("offset", lastCompletedOffset)
.put("partition", _partition.partition)
.put("broker", ImmutableMap.of("host", _partition.host.host,
"port", _partition.host.port))
.put("topic", _spoutConfig.topic).build();
_state.writeJSON(committedPath(), data);
_committedTo = lastCompletedOffset;
LOG.debug("Wrote last completed offset (" + lastCompletedOffset + ") to ZK for " + _partition + " for topology: " + _topologyInstanceId);
} else {
LOG.debug("No new offset for " + _partition + " for topology: " + _topologyInstanceId);
}
}
ZkState
public void writeBytes(String path, byte[] bytes) {
try {
if (_curator.checkExists().forPath(path) == null) {
_curator.create()
.creatingParentsIfNeeded()
.withMode(CreateMode.PERSISTENT)
.forPath(path, bytes);
} else {
_curator.setData().forPath(path, bytes);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
I could see that for the first message, the writeBytes method gets into the if block and tries to create a path, then for the second message it goes into the else block, which seems to be ok. But when I start the project again, the same message as mentioned above shows up. No partition information can be found.
I had the same problem. Turned out I was running in local mode which uses an in memory zookeeper and not the zookeeper that Kafka is using.
To make sure that KafkaSpout doesn't use Storm's ZooKeeper for the ZkState that stores the offset, you need to set the SpoutConfig.zkServers, SpoutConfig.zkPort, and SpoutConfig.zkRoot in addition to the ZkHosts. For example
import org.apache.zookeeper.client.ConnectStringParser;
import storm.kafka.SpoutConfig;
import storm.kafka.ZkHosts;
import storm.kafka.KeyValueSchemeAsMultiScheme;
...
final ConnectStringParser connectStringParser = new ConnectStringParser(zkConnectStr);
final List<InetSocketAddress> serverInetAddresses = connectStringParser.getServerAddresses();
final List<String> serverAddresses = new ArrayList<>(serverInetAddresses.size());
final Integer zkPort = serverInetAddresses.get(0).getPort();
for (InetSocketAddress serverInetAddress : serverInetAddresses) {
serverAddresses.add(serverInetAddress.getHostName());
}
final ZkHosts zkHosts = new ZkHosts(zkConnectStr);
zkHosts.brokerZkPath = kafkaZnode + zkHosts.brokerZkPath;
final SpoutConfig spoutConfig = new SpoutConfig(zkHosts, inputTopic, kafkaZnode, kafkaConsumerGroup);
spoutConfig.scheme = new KeyValueSchemeAsMultiScheme(inputKafkaKeyValueScheme);
spoutConfig.zkServers = serverAddresses;
spoutConfig.zkPort = zkPort;
spoutConfig.zkRoot = kafkaZnode;
I think you are hitting this bug:
https://community.hortonworks.com/questions/66524/closedchannelexception-kafka-spout-cannot-read-kaf.html
And the comment from the colleague above fixed my issue. I added some newer libraries to.
Related
Currently i am working on an app that uses sqlite. I have a scenario in which there are graphs according to days of week. User can check graphs of any day. There may be data available for that day or not.
Issue is for the first time every thing goes well. But then if user taps again on the day which actually have data available, app stop working, or i can say it stuck. it didn't crash or any exception.
private async void getGraphData(int p)
{
var checkCount = p;
Color currentAccentColorHex = (Color)Application.Current.Resources["PhoneAccentColor"];
BabySleepChart.Foreground = new SolidColorBrush(ConvertStringToColor(currentAccentColorHex.ToString()));
Conn = new SQLiteAsyncConnection(DB_NAME);
ObservableCollection<Graph> BabydailySleep = new ObservableCollection<Graph>();
var sundayData = await Conn.QueryAsync<BabySleep>("SELECT * FROM BabySleep WHERE today = ?", Convert.ToDateTime(DateTime.Now.AddDays(-p).Date.ToString("d")));
var count = sundayData.Any() ? sundayData.Count : 0;
if (count == 0)
{
MessageBox.Show("No date for " + DateTime.Now.AddDays(-p).ToString("dddddd"), "Data Not Found", MessageBoxButton.OK);
}
else
{
}
}
In else i display graphs. I am using amcharts. (The control doesn't go after the query for 2nd time.)
Please help . How can i solve this issue.
Regards.
I am trying to query free busy data from Google calendar. Simply I am providing start date/time and end date/time. All I want to know is if this time frame is available or not. When I run below query, I get "responseOBJ" response object which doesn't seem to include what I need. The response object only contains start and end time. It doesn't contain flag such as "IsBusy" "IsAvailable"
https://developers.google.com/google-apps/calendar/v3/reference/freebusy/query
#region Free_busy_request_NOT_WORKING
FreeBusyRequest requestobj = new FreeBusyRequest();
FreeBusyRequestItem c = new FreeBusyRequestItem();
c.Id = "calendarresource#domain.com";
requestobj.Items = new List<FreeBusyRequestItem>();
requestobj.Items.Add(c);
requestobj.TimeMin = DateTime.Now.AddDays(1);
requestobj.TimeMax = DateTime.Now.AddDays(2);
FreebusyResource.QueryRequest TestRequest = calendarService.Freebusy.Query(requestobj);
// var TestRequest = calendarService.Freebusy.
// FreeBusyResponse responseOBJ = TestRequest.Execute();
var responseOBJ = TestRequest.Execute();
#endregion
Calendar API will only ever provide ordered busy blocks in the response, never available blocks. Everything outside busy is available. Do you have at least one event on the calendar
with the given ID in the time window?
Also the account you are using needs to have at least free-busy access to the resource to be able to retrieve availability.
I know this question is old, however I think it would be beneficial to see an example. You will needed to actually grab the Busy information from your response. Below is a snippet from my own code (minus the call) with how to handle the response. You will need to utilized your c.Id as the key to search through the response:
FreebusyResource.QueryRequest testRequest = service.Freebusy.Query(busyRequest);
var responseObject = testRequest.Execute();
bool checkBusy;
bool containsKey;
if (responseObject.Calendars.ContainsKey("**INSERT YOUR KEY HERE**"))
{
containsKey = true;
if (containsKey)
{
//Had to deconstruct API response by WriteLine(). Busy returns a count of 1, while being free returns a count of 0.
//These are properties of a dictionary and a List of the responseObject (dictionary returned by API POST).
if (responseObject.Calendars["**YOUR KEY HERE**"].Busy.Count == 0)
{
checkBusy = false;
//WriteLine(checkBusy);
}
else
{
checkBusy = true;
//WriteLine(checkBusy);
}
if (checkBusy == true)
{
var busyStart = responseObject.Calendars["**YOUR KEY HERE**"].Busy[0].Start;
var busyEnd = responseObject.Calendars["**YOUR KEY HERE**].Busy[0].End;
//WriteLine(busyStart);
//WriteLine(busyEnd);
//Read();
string isBusyString = "Between " + busyStart + " and " + busyEnd + " your trainer is busy";
richTextBox1.Text = isBusyString;
}
else
{
string isFreeString = "Between " + startDate + " and " + endDate + " your trainer is free";
richTextBox1.Text += isFreeString;
}
}
else
{
richTextBox1.Clear();
MessageBox.Show("CalendarAPIv3 has failed, please contact support\nregarding missing <key>", "ERROR!");
}
}
My suggestion would be to break your responses down by writing them to the console. Then, you can "deconstruct" them. That is how I was able to figure out "where" to look within the response. As noted above, you will only receive the information for busyBlocks. I used the date and time that was selected by my client's search to show the "free" times.
EDIT:
You'll need to check if your key exists before attempting the TryGetValue or searching with a keyvaluepair.
Implemented the above logic to create a new commit (with no parents) that contains only my file. Commits are fast in the repository as compared to CommitCommand commit = git.commit();
But I am not able to get the Logs of a particular file , the number of times it has been updated/revised , and every time i go for Constants.HEAD , I am getting null.
Any help will be of great advantage.
Git git = jGitUtil.openRepo();
Repository repository = git.getRepository();
ObjectInserter repoInserter = repository.newObjectInserter();
ObjectId commitId = null;
try
{
byte[] fileBytes= FileUtils.readFileToByteArray(sourceFile);
// Add a blob to the repository
ObjectId blobId = repoInserter.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, fileBytes);
// Create a tree that contains the blob as file "hello.txt"
TreeFormatter treeFormatter = new TreeFormatter();
treeFormatter.append(actualFileName, FileMode.REGULAR_FILE, blobId);
ObjectId treeId = treeFormatter.insertTo(repoInserter);
System.out.println("File comment : " + relativePath + PortalConstants.FILESEPARATOR + actualFileName + PortalConstants.EP_DELIMETER + userComments);
// Create a commit that contains this tree
CommitBuilder commit = new CommitBuilder();
PersonIdent ident = new PersonIdent(user.getFirstName(), user.getUserId());
commit.setCommitter(ident);
commit.setAuthor(ident);
commit.setMessage(relativePath + PortalConstants.FILESEPARATOR + actualFileName + PortalConstants.EP_DELIMETER + userComments);
commit.setTreeId(treeId);
commitId = repoInserter.insert(commit);
System.out.println(" commitId : " + commitId.getName());
repoInserter.flush();
System.out.println("Flush Done");
}catch(IOException ioe){
log.logError(StackTraceUtil.getStackTrace(ioe));
System.out.println(StackTraceUtil.getStackTrace(ioe));
}
finally
{
repoInserter.release();
}
return commitId.getName();
}
I would probably use Add File and Commit File porcelain commands instead of trying to implement it myself. Then retrieving the log should be possible via something like this:
Iterable<RevCommit> logs = new Git(repository).log()
.all()
.call();
for(RevCommit rev : logs) {
System.out.println("Commit: " + rev + " " + rev.getName() + " " + rev.getId().getName());
}
Where you can retrieve the additional information based on the commit-id.
I have now also added this as new snippet Show Log
Note that if you are creating a commit with no parents, you are saying that there is no history. Therefore you won't be able to see any other changes from that history because it doesn't exist.
You probably should use a commit with the parent of the current position of the branch so that you'll be able to get more information.
I'm trying to implement this solution to "grey out" past events in Fullcalendar, but I'm not having any luck. I'm not too well versed in Javascript, though, so I assume I'm making some dumb mistakes.
I've been putting the suggested code into fullcalendar.js, inside the call for daySegHTML(segs) around line 4587.
I added the first two lines at the end of the function's initial var list (Why not, I figured)—so something like this:
...
var leftCol;
var rightCol;
var left;
var right;
var skinCss;
var hoy = new Date;// get today's date
hoy = parseInt((hoy.getTime()) / 1000); //get today date in unix
var html = '';
...
Then, just below, I added the other two lines inside the loop:
for (i=0; i<segCnt; i++) {
seg = segs[i];
event = seg.event;
classes = ['fc-event', 'fc-event-skin', 'fc-event-hori'];
if (isEventDraggable(event)) {
classes.push('fc-event-draggable');
}
unixevent = parseInt((event.end.getTime()) / 1000); //event date in Unix
if (unixevent < hoy) {classes.push('fc-past');} //add class if event is old
if (rtl) {
if (seg.isStart) {
classes.push('fc-corner-right');
}
...
Running this code results in a rendered calendar with no events displayed and an error message: Uncaught TypeError: Cannot call method 'getTime' of null
The "null" being referred to is, apparently, event.end.getTime(). But I'm not sure I understand what exactly is going wrong, or how things are being executed. As written, it seems like it should work. At this point in the code, from what I can tell, event.end contains a valid IETF timecode, but for some reason it's "not there" when I try to run it through getTime()?
This isn't a mission-critical tweak for me, but would still be nice—and I'd like to understand what's going on and what I'm doing wrong, as well! Any help greatly appreciated!
If you are using FullCalendar2 with Google Calendar, you will need to use the version of the code below. This uses Moment.js to do some conversions, but since FC2 requires it, you'll be using it already.
eventRender: function(event, element, view) {
var ntoday = new Date().getTime();
var eventEnd = moment( event.end ).valueOf();
var eventStart = moment( event.start ).valueOf();
if (!event.end){
if (eventStart < ntoday){
element.addClass("past-event");
element.children().addClass("past-event");
}
} else {
if (eventEnd < ntoday){
element.addClass("past-event");
element.children().addClass("past-event");
}
}
}
As per FullCalendar v1.6.4
Style past events in css:
.fc-past{background-color:red;}
Style future events in css:
.fc-future{background-color:red;}
There's no need to fiddle with fullcalendar.js. Just add a callback, like:
eventRender: function(calev, elt, view) {
if (calev.end.getTime() < sometime())
elt.addClass("greyclass");
},
you just have to define the correct CSS for .greyclass.
Every event has an ID associated with it. It is a good idea to maintain your own meta information on all events based on their ids. If you are getting the events popupated from a backend database, add a field to your table. What has worked best for me is to rely on callbacks only to get the event ids and then set/reset attributes fetched from my own data store. Just to give you some perspective, I am pasting below a section of my code snippet. The key is to target the EventDAO class for all your needs.
public class EventDAO
{
//change the connection string as per your database connection.
//private static string connectionString = "Data Source=ASHIT\\SQLEXPRESS;Initial Catalog=amit;Integrated Security=True";
//this method retrieves all events within range start-end
public static List<CalendarEvent> getEvents(DateTime start, DateTime end, long nParlorID)
{
List<CalendarEvent> events = new List<CalendarEvent>();
// your data access class instance
clsAppointments objAppts = new clsAppointments();
DataTable dt = objAppts.SelectAll( start, end);
for(int i=0; i<dt.Rows.Count; ++i)
{
CalendarEvent cevent = new CalendarEvent();
cevent.id = (int)Convert.ToInt64(dt.Rows[i]["ID"]);
.....
Int32 apptDuration = objAppts.GetDuration(); // minutes
string staffName = objAppts.GetStaffName();
string eventDesc = objAppts.GetServiceName();
cevent.title = eventDesc + ":" + staffName;
cevent.description = "Staff name: " + staffName + ", Description: " + eventDesc;
cevent.start = (DateTime)dt.Rows[i]["AppointmentDate"];
cevent.end = (DateTime) cevent.start.AddMinutes(apptDuration);
// set appropriate classNames based on whatever parameters you have.
if (cevent.start < DateTime.Now)
{
cevent.className = "pastEventsClass";
}
.....
events.Add(cevent);
}
}
}
The high level steps are as follows:
Add a property to your cevent class. Call it className or anything else you desire.
Fill it out in EventDAO class while getting all events. Use database or any other local store you maintain to get the meta information.
In your jsonresponse.ashx, retrieve the className and add it to the event returned.
Example snippet from jsonresponse.ashx:
return "{" +
"id: '" + cevent.id + "'," +
"title: '" + HttpContext.Current.Server.HtmlEncode(cevent.title) + "'," +
"start: " + ConvertToTimestamp(cevent.start).ToString() + "," +
"end: " + ConvertToTimestamp(cevent.end).ToString() + "," +
"allDay:" + allDay + "," +
"className: '" + cevent.className + "'," +
"description: '" +
HttpContext.Current.Server.HtmlEncode(cevent.description) + "'" + "},";
Adapted from #MaxD The below code is what i used for colouring past events grey.
JS for fullcalendar pulling in Json
events: '/json-feed.php',
eventRender: function(event,element,view) {
if (event.end < new Date().getTime())
element.addClass("past-event");
},
other options ....
'event.end' in my Json is a full date time '2017-10-10 10:00:00'
CSS
.past-event.fc-event, .past-event .fc-event-dot {
background: #a7a7a7;
border-color: #848484
}
eventDataTransform = (eventData) => {
let newDate = new Date();
if(new Date(newDate.setHours(0, 0, 0, 0)).getTime() > eventData.start.getTime()){
eventData.color = "grey";
}else{
eventData.color = "blue";
}
return eventData;
}
//color will change background color of event
//textColor to change the text color
Adapted from #Jeff original answer just simply check to see if an end date exists, if it does use it otherwise use the start date. There is an allDay key (true/false) but non allDay events can still be created without an end date so it will still throw an null error. Below code has worked for me.
eventRender: function(calev, elt, view) {
var ntoday = new Date().getTime();
if (!calev.end){
if (calev.start.getTime() < ntoday){
elt.addClass("past");
elt.children().addClass("past");
}
} else {
if (calev.end.getTime() < ntoday){
elt.addClass("past");
elt.children().addClass("past");
}
}
}
Ok, so here's what I've got now, that's working (kind of):
eventRender: function(calev, elt, view) {
var ntoday = new Date();
if (calev.start.getTime() < ntoday.getTime()){
elt.addClass("past");
elt.children().addClass("past");
}
}
In my stylesheet, I found I needed to restyle the outer and inner elements to change the color; thus the elt.children().addclass addition.
The only time check I could get to work, lacking an end time for all day events, was to look at the start time - but this is going to cause problems with multi-day events, obviously.
Is there another possible solution?
Note: This question can also be found on the WiX mailing list.
I need to be able to check for the existence of an IIS7 website based on the website's description. If the website does not exist I need to cancel the installation. If the website exists I want to continue the installation. I also need to be able to save the site id of the website so that I may use it during an uninstall.
For debugging purposes I have hard coded the website's description. I do not see any indication that a check for the website is being made within the MSI log file. This is the code I am using:
<iis:WebSite Id="IISWEBSITE" Description="Default Web Site" SiteId="*">
<iis:WebAddress Id="IisWebAddress" Port="1"/>
</iis:WebSite>
<Condition Message="Website [IISWEBSITE] not found.">
<![CDATA[IISWEBSITE]]>
</Condition>
Using ORCA I can see that IIsWebAddress and IIsWebSite tables are added to the MSI. The values are:
IIsWebsite
WEB: IISWEBSITE
Description: Default Web Site
KeyAddress: IisWebAddress
Id: -1
IIsWebAddress
Address: IisWebAddress
Web_: IISWEBSITE
Port: 1
Secure: 0
With the above code, the installation is halted with the error message "Website not found". It appears that IISWEBSITE is never getting set. Though, I know that "Default Web Site" exists. I know that I must be missing something, but what?
How can I perform a simple check for the existence of a website in IIS 7?
I too had same problem.
I wrote a custom action to check the version of IIS from registry.
On the basis of registry value create virtual directory
I wrote a custom action in Javascript to do this. If you are assuming IIS7, then you can use the appcmd.exe tool, and just invoke it from within Javascript to get the list of sites. In theory, it's pretty simple to do. But in practice, there's a bunch of hoops you need to jump through.
Here's what I came up with:
function RunAppCmd(command, deleteOutput) {
var shell = new ActiveXObject("WScript.Shell"),
fso = new ActiveXObject("Scripting.FileSystemObject"),
tmpdir = fso.GetSpecialFolder(SpecialFolders.TemporaryFolder),
tmpFileName = fso.BuildPath(tmpdir, fso.GetTempName()),
windir = fso.GetSpecialFolder(SpecialFolders.WindowsFolder),
appcmd = fso.BuildPath(windir,"system32\\inetsrv\\appcmd.exe") + " " + command,
rc;
deleteOutput = deleteOutput || false;
LogMessage("shell.Run("+appcmd+")");
// use cmd.exe to redirect the output
rc = shell.Run("%comspec% /c " + appcmd + "> " + tmpFileName, WindowStyle.Hidden, true);
LogMessage("shell.Run rc = " + rc);
if (deleteOutput) {
fso.DeleteFile(tmpFileName);
}
return {
rc : rc,
outputfile : (deleteOutput) ? null : tmpFileName
};
}
// GetWebSites_Appcmd()
//
// Gets website info using Appcmd.exe, only on IIS7+ .
//
// The return value is an array of JS objects, one per site.
//
function GetWebSites_Appcmd() {
var r, fso, textStream, sites, oneLine, record,
ParseOneLine = function(oneLine) {
// split the string: capture quoted strings, or a string surrounded
// by parens, or lastly, tokens separated by spaces,
var tokens = oneLine.match(/"[^"]+"|\(.+\)|[^ ]+/g),
// split the 3rd string: it is a set of properties separated by colons
props = tokens[2].slice(1,-1),
t2 = props.match(/\w+:.+?(?=,\w+:|$)/g),
bindingsString = t2[1],
ix1 = bindingsString.indexOf(':'),
t3 = bindingsString.substring(ix1+1).split(','),
L1 = t3.length,
bindings = {}, i, split, obj, p2;
for (i=0; i<L1; i++) {
split = t3[i].split('/');
obj = {};
if (split[0] == "net.tcp") {
p2 = split[1].split(':');
obj.port = p2[0];
}
else if (split[0] == "net.pipe") {
p2 = split[1].split(':');
obj.other = p2[0];
}
else if (split[0] == "http") {
p2 = split[1].split(':');
obj.ip = p2[0];
if (p2[1]) {
obj.port = p2[1];
}
obj.hostname = "";
}
else {
p2 = split[1].split(':');
obj.hostname = p2[0];
if (p2[1]) {
obj.port = p2[1];
}
}
bindings[split[0]] = obj;
}
// return the object describing the website
return {
id : t2[0].split(':')[1],
name : "W3SVC/" + t2[0].split(':')[1],
description : tokens[1].slice(1,-1),
bindings : bindings,
state : t2[2].split(':')[1] // started or not
};
};
LogMessage("GetWebSites_Appcmd() ENTER");
r = RunAppCmd("list sites");
if (r.rc !== 0) {
// 0x80004005 == E_FAIL
throw new Exception("ApplicationException", "exec appcmd.exe returned nonzero rc ("+r.rc+")", 0x80004005);
}
fso = new ActiveXObject("Scripting.FileSystemObject");
textStream = fso.OpenTextFile(r.outputfile, OpenMode.ForReading);
sites = [];
// Read from the file and parse the results.
while (!textStream.AtEndOfStream) {
oneLine = textStream.ReadLine();
record = ParseOneLine(oneLine);
LogMessage(" site: " + record.name);
sites.push(record);
}
textStream.Close();
fso.DeleteFile(r.outputfile);
LogMessage("GetWebSites_Appcmd() EXIT");
return sites;
}